Answered step by step
Verified Expert Solution
Question
1 Approved Answer
import syssys.path.insert(0, ../..)tokens = ('VAR',)literals = ['=', '+', '-', '*', '/']def t_VAR(t): r'VAR ' return tt_ignore = tdef t_newline(t): r'+' t.lexer.lineno += t.value.count()def t_error(t):
import syssys.path.insert(0, "../..")tokens = ('VAR',)literals = ['=', '+', '-', '*', '/']def t_VAR(t): r'VAR ' return tt_ignore = " t"def t_newline(t): r'+' t.lexer.lineno += t.value.count("")def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1)# Build the lexerimport ply.lex as lexlexer = lex.lex()# dictionary of namesnames = {}def p_expression_stmt(p): '''stmt : VAR'''def p_error(p): if p: print("Syntax error at '%s'" % p.value) else: print("Syntax error at EOF")import ply.yacc as yaccparser = yacc.yacc()while True: try: s = input("Enter a line of code: ") except EOFError: break if not s: continue yacc.parse(s)
Building a Parser Next you'll add on to your working scanner generator code to generate a full lexical and syntactic analyzer. You can run the sample scanner/parser generator using parser_example.py Here is an example of both a valid and invalid syntactical statement: Generating LALR tables Enter a line of code: VAR Enter a line of code: var Illegal character 'v' Illegal character 'a' Illegal character 'r' Syntax error at EOF Enter a line of code: You'll see in the code that 'stmt' is the entry point into the syntax analyzer and maps to a VAR token (which was defined in the scanner you built above). The parser that is generated checks that the input matches a VAR token and throws a syntax error if it does not. Your job in this portion of the assignment is to combine your scanner generator code with the additional methods needed to enforce the grammar specified above (assign, declare, binop, etc.). For reference, my solution contains 5 methods to implement the grammar. Please note that the sample parser code is just an example to show you how the YACC portion of PLY works and VAR may not (probably should not) be a part of 'stmt' for your final solution.
Step by Step Solution
★★★★★
3.40 Rating (163 Votes )
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started