import sys from Lexer import * next_token = None l = None # expr # Parses strings in the language generated by the rules: # -> + # -> - # -> def expr(): global next_token global l print("Enter ") term() while next_token.get_token().value == TokenTypes.ADD.value or \ next_token.get_token().value == TokenTypes.SUB.value: next_token = l.lex() term() print("Exit ") # term # Parses strings in the language generated by the rules: # -> * # -> / # -> def term(): global next_token global l print("Enter ") factor() while next_token.get_token().value == TokenTypes.MUL.value or \ next_token.get_token().value == TokenTypes.DIV.value: next_token = l.lex() factor() print("Exit ") # factor # Parses strings in the language generated by the rules: # -> id # -> int_constant # -> ( ) def factor(): global next_token global l print("Enter ") if next_token.get_token().value == TokenTypes.ID.value or \ next_token.get_token().value == TokenTypes.INT.value: next_token = l.lex() else: # if the RHS is ( ), pass over (, call expr, check for ) if next_token.get_token().value == TokenTypes.LPAREN.value: next_token = l.lex() expr() if next_token.get_token().value == TokenTypes.RPAREN.value: next_token = l.lex() else: error("Expecting RPAREN") sys.exit(-1) else: error("Expecting LPAREN") sys.exit(-1) print("Exit ") def error(s): print("SYNTAX ERROR: "+s) def main(): global next_token global l l = Lexer(sys.argv[1]) next_token = l.lex() expr() if next_token.get_token().value == TokenTypes.EOF.value: print("PARSE SUCCEEDED") else: print("PARSE FAILED") main()