From 83d04f26f902520b3385394a238367b52bbe5fe6 Mon Sep 17 00:00:00 2001 From: "Esteban Prince, Liam (UG - Computer Science)" <le00210@surrey.ac.uk> Date: Fri, 21 Feb 2020 21:28:45 +0000 Subject: [PATCH] Upload New File --- parser.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 parser.py diff --git a/parser.py b/parser.py new file mode 100644 index 0000000..70235f4 --- /dev/null +++ b/parser.py @@ -0,0 +1,48 @@ +from graphviz import Digraph +# Parser: parses the stream of tokens generated by the lexer and creates an abstract syntax tree + +# Each token will become a node in the graph +# Nodes are represented with the Node type, each instance of which contains a "children" array which holds more Nodes +class Node: + def __init__(self, name): + self.name = name + self.children = [] + + def add(self, node): + self.children.append(node) + +# Ingredient ::= +def ingredient(): + node = Node('ingredient') + +# Amount ::= Digit+ ("-" | "/" | "to")? Digit* +def amount(): + node = Node('digit') + if nextToken().type == 'digit': + return node + +# Digit ::= ("0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")+ +def digit(): + node = Node('digit') + +def unit(): + node = Node('unit') + +def example(): + text = "10 to 20 minutes" + dot = Digraph(comment='Abstract Syntax Tree') + dot.node('a', 'amount') + dot.node('d', 'digit') + dot.edge('a', 'd') + dot.node('t', '10') + dot.edge('d', 't') + dot.node('to') + dot.node('digit') + dot.node('unit') + dot.render('ast.gv', view=True) + +def draw(): + dot = Digraph(comment='Abstract Syntax Tree') + dot.render('ast.gv', view=True) + +example() -- GitLab