def test_parser_brackets() -> None: brackets = ContextFreeGrammar(terminals={'(', ')'}, non_terminals={'A'}, start='A', rules={'A': ['(A)', '', 'AA']}) parser = Parser(brackets) assert parser.is_in_language('') assert parser.is_in_language('()') assert parser.is_in_language("()()(())") assert not parser.is_in_language("())((())")
def test_parser_polynoms() -> None: polynoms = ContextFreeGrammar(terminals={'x', '^', 'n', '+'}, non_terminals={'m', 'p'}, start='p', rules={ 'p': ['m', 'p+m'], 'm': ['x', 'x^n'] }) parser = Parser(polynoms) assert parser.is_in_language("x^n+x+x^n") assert not parser.is_in_language("x^x^n+x+x^n")
def test_parser_arithmetic() -> None: arithm = ContextFreeGrammar(terminals={'(', ')', '+', '*', '1', '2'}, non_terminals={'t', 's', 'c'}, start='s', rules={ 'c': ['1', '2'], 't': ['c', 't*c', '(s)'], 's': ['t', 's+t'] }) parser = Parser(arithm) assert parser.is_in_language("1*2+2") assert parser.is_in_language("(1*2+2*1)") assert not parser.is_in_language("1+(2*1*)")
from grammar import ContextFreeGrammar from parser import Lr0Parser grammar = ContextFreeGrammar("input.json", "example") parser = Lr0Parser(grammar) def display_cannonical_states(): print("\nBelow is the cannonical collection: ") state_index = 0 cannonical_collection = parser.get_canonical_collection() for state in cannonical_collection: print('s' + str(state_index) + ' = ' + str([x[0] + '->' + str(''.join(x[1])) for x in state])) state_index += 1 def parsing_an_input_sequence(sequence): print("\nParsing the input sequence: " + str(sequence)) out = parser.parse(sequence) res = "" for i in out: aux = "" for c in grammar.production_rules[int(i)][1]: aux += c if res == "": res += grammar.production_rules[int(i)][0] + '->' + aux else: res += ', ' + grammar.production_rules[int(i)][0] + '->' + aux print("\nHow we got there: ") for production in res.split(", "): print(production)