Question: I am writing a parser in python that will parse the given grammar into an Abstract Syntax Tree. I already have a scanner built using
I am writing a parser in python that will parse the given grammar into an Abstract Syntax Tree. I already have a scanner built using regular expressions. I'm having a lot of trouble actually starting the parser portion. My main issue is how do I tap into my token list after the file has been read, additionally I'm not really sure how to code the grammar so that it will be output in AST. Can anyone help get me started and on the right track? Thanks(Python code and Grammar below).
import re import sys f = open("scannertestdata.txt","r") string = f.read() #string = sys.stdin.read() use later when submitting scanner=re.Scanner([ (r"(var|fun|if|else|return|read|write|not|or|and)", lambda scanner,token:("KEYWORD: ", token)), (r"\d+\.\d*",lambda scanner,token:("REAL",token)), (r"\d+",lambda scanner,token:("INTEGER", token)), (r"[a-zA-Z0-9]+",lambda scanner,token:("IDENTIFIER", token)), (r"(\(|\)|{|}|,|\+|\-|\*|/|%|:=|!=|=|)",lambda scanner,token:("PUNCTUATION", token)), (r"(#t|#f)+",lambda scanner,token:("BOOLEAN", token)), (r"\s+",None),# Skips white space (r'.', lambda scanner,token:None)#Skips invalid token ]) results, remainder=scanner.scan(string) print(results[0] )
program id bool literal int literal real literal constant cmds
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
