diff --git a/table_generator.py b/table_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..4cd8122782cd7a74ce8a56f7438bc63a733918d0 --- /dev/null +++ b/table_generator.py @@ -0,0 +1,73 @@ + +class TreeNode: + def __init__(self, language_element, subnodes): + self.language_element = language_element + self.subnodes = subnodes + + def __str__(self): + return str(self.language_element) + " " + str(self.subnodes) + + +def walk_the_tree(tree, level = 1): + if tree == None: + return + + print(" " * (level -1) + "|---" + str(tree.language_element) + " with " + str(len(tree.subnodes)) + " subnodes") + for subnode in tree.subnodes: + walk_the_tree(subnode, level + 1) + + + +CFG = collections.namedtuple("CFG", "nonterminals terminals rules start") +# We define a context-free grammar as: +# 1. A list of nonterminal symbols +# 2. A list of terminal symbols +# 3. A list of production rules +# 4. A start symbol. + +# Each symbol is defined by a positive integer. + + +# For the ETF expression grammar: + +# Terminal symbols are: +# INTEGER, ADDOP, MULTOP, OPENPAREN, CLOSEPAREN + +# Nonterminal symbols are: +# EXPRESSION, TERM, FACTOR + +# The start symbol is EXPRESSION + +# The rules are: + +# EXPRESSION -> EXPRESSION ADDOP TERM +# EXPRESSION -> TERM +# TERM -> TERM MULTOP FACTOR +# TERM -> FACTOR +# FACTOR -> OPENPAREN EXPRESSION CLOSEPAREN +# FACTOR -> INTEGER + +#symbols = Enum("Symbols", "EXPRESSION TERM FACTOR INTEGER ADDOP MULTOP OPENPAREN CLOSEPAREN") + +nonterminals = Enum("Nonterminals", "EXPRESSION TERM FACTOR") + +terminals = Enum("Terminals", "INTEGER ADDOP MULTOP OPENPAREN CLOSEPAREN") + +list_of_nonterminals = [e for e in nonterminals] +list_of_terminals = [e for e in terminals] + +start = nonterminals.EXPRESSION + +# The rules are a list of tuples, each of which represents a rule, as follows: + +# (Nonterminal symbol, [ordered list of symbols (terminal or nonterminal) that are reduced to aforementioned nonterminal]) + +rules = [ + (nonterminals.EXPRESSION, [nonterminals.EXPRESSION, terminals.ADDOP, nonterminals.TERM ]), + (nonterminals.EXPRESSION, [nonterminals.TERM ]), + (nonterminals.TERM, [nonterminals.TERM, terminals.MULTOP, nonterminals.FACTOR ]), + (nonterminals.TERM, [nonterminals.FACTOR ]), + (nonterminals.FACTOR, [terminals.OPENPAREN, nonterminals.EXPRESSION, terminals.CLOSEPAREN]), + (nonterminals.FACTOR, [terminals.INTEGER ]) + ] +