Question: =================================================== x = 2; while x : print x end; if (x + 1) : print x else print (x-9) end =================================================== Here is the
=================================================== x = 2; while x : print x end; if (x + 1) : print x else print (x-9) end =================================================== Here is the execution of this program: python run.py Type program; OK to do it on multiple lines; terminate with ! as the first symbol on a line by itself: x = 2; while x : print x end; if (x + 1) : print x else print (x-9) end ! scanned program: ['x', '=', '2', ';', 'while', 'x', ':', 'print', 'x', 'end', ';', 'if', '(', 'x', '+', '1', ')', ':', 'print', 'x', 'else', 'print', '(', 'x', '-', '9', ')', 'end'] parsed program: [[['=', 'x', '2'], ['while', 'x', [['print', 'x']]], ['if', ['+', 'x', '1'], [['print', 'x']], [['print', ['-', 'x', '9']]]]]] press Enter key to finish The program is parsed into its tree. Here the grammar of the language we implement: =================================================== PROGRAM ::= COMMANDLIST COMMANDLIST ::= COMMAND | COMMAND ; COMMANDLIST COMMAND ::= VAR = EXPRESSSION | print EXPRESSION | while EXPRESSION : COMMANDLIST end | if EXPRESSION : COMMANDLIST else COMMANDLIST end EXPRESSION ::= NUMERAL | VAR | ( EXPRESSION OPERATOR EXPRESSION ) OPERATOR is + or - NUMERAL is a sequence of digits from the set, {0,1,2,...,9} VAR is a string of lower-case letters, not a keyword =================================================== A scanner essentially same as the one in Lecture Note 1 to build parse trees for this grammar has been provided, you job is to modify the parser so that it will parse if-else as well with grammar defined above. Abstract syntax tree (operator tree) format The parser will construct the list-represented tree for a program. The syntax of trees is this: =================================================== PTREE ::= [ CLIST ] CLIST ::= [ CTREE+ ] where CTREE+ means one or more CTREEs CTREE ::= ["=", VAR, ETREE] | ["print", ETREE] | ["while", ETREE, CLIST] | ["if", ETREE, CLIST, CLIST] ETREE ::= NUMERAL | VAR | [OP, ETREE, ETREE] where OP is either "+" or "-" =================================================== Notice how the trees match the grammar constructions. Since the trees are nested lists, it is easy to disassemble them and compute on their parts. Submission and grading Make a new folder, named YourFirstNameYourLastName_lab2, and place in it your final version of parse.py and also tests.txt (provide the test case that you tried.). Zip the folder into the .zip file, YourFirstNameYourLastName_ps1.zip, and submit the .zip file to Canvas. (If you do not use the naming convention, YourFirstNameYourLastName_lab2.zip, your work will not be graded.)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
