def test_items(grammar: Grammar, expected: tp.List[tp.Set[State]]): algo = Algo.fit(grammar) items = algo.items() assert len(items) == len(expected) for superstate in items: assert superstate in expected for superstate in expected: assert superstate in items
def main(): grammar = Grammar.from_input() algo = Algo.fit(grammar) while True: print("Enter the word, '$' to quit:") word = input() if word == '$': break print("YES" if algo.predict(word) else "NO")
def test_control_table(grammar: Grammar, expected_items: tp.List[tp.Set[State]], expected_table: tp.Tuple[tp.List[tp.Dict[str, Cell]], tp.List[tp.Dict[str, int]]]): algo = Algo.fit(grammar) items = algo.items() assert len(items) == len(expected_items) actual_to_expected = [-1 for i in range(len(items))] for index, superstate in enumerate(items): actual_to_expected[index] = expected_items.index(superstate) for superstate in expected_items: assert superstate in items expected_control_table, expected_goto = expected_table assert len(expected_control_table) == len(items) and len( algo.control_table) == len(items) for index, row in enumerate(algo.control_table): assert len(row) == len(algo.grammar.terminals) index_in_expected = actual_to_expected[index] assert len(expected_control_table[index_in_expected]) == len( algo.grammar.terminals) for symbol, cell in row.items(): assert cell.command == expected_control_table[index_in_expected][ symbol].command if cell.command == Cell.SHIFT: assert actual_to_expected[cell.how] == expected_control_table[ index_in_expected][symbol].how else: assert cell.how == expected_control_table[index_in_expected][ symbol].how assert len(expected_goto) == len(items) and len(algo.goto) == len(items) for index, row in enumerate(algo.goto): assert len(row) == len(algo.grammar.non_terminals) index_in_expected = actual_to_expected[index] assert len(expected_goto[index_in_expected]) == len( algo.grammar.non_terminals) for symbol, to in row.items(): if to == -1: assert expected_goto[index_in_expected][symbol] == -1 else: assert actual_to_expected[to] == expected_goto[ index_in_expected][symbol]
def test_lr(grammar: Grammar, tests: tp.List[tp.Tuple[str, bool]]): algo = Algo.fit(grammar) for word, expected in tests: assert algo.predict(word) == expected
def test_goto(grammar: Grammar, tests: tp.List[tp.Tuple[tp.Set[State], str, tp.Set[State]]]): algo = Algo.fit(grammar) for superstate, symbol, expected in tests: assert algo.goto_function(superstate, symbol) == expected
def test_closure(grammar: Grammar, tests: tp.List[tp.Tuple[tp.Set[State], tp.Set[State]]]): algo = Algo.fit(grammar) for set_of_states, expected in tests: assert algo.closure(set_of_states) == expected
def test_first(grammar: Grammar, tests: tp.List[tp.Tuple[str, tp.Set[str]]]): algo = Algo.fit(grammar) for word, expected in tests: assert algo.first(word) == expected