def test_given_tree_then_correct_prune(self) -> None: from cmaj.testing.ast import tree, token node = tree(('X', [('X', [token('Y', 0), ('X', [token('Y', 1), token('Y', 2)])]), ('Y', [('X', [token('X', 3)])])])) result = prune(node, 'Y') expected = tree(('X', [])) self.assertEqual(expected, result)
def compile_grammar(grammar_node: Node) -> Grammar: from cmaj.ast.simplify import squash, prune, skip grammar_node = squash(grammar_node, 'GRAMMAR', 'OPTION', 'SEQUENCE') grammar_node = prune(grammar_node, 'comment', '=', '|', 'eol') grammar_node = skip(grammar_node, 'LINE', 'ANCHOR') rules: List[Rule] = [] for definition_node in grammar_node.children: identifier, option = definition_node.children rules += compile_rules(identifier.token.value, option) return Grammar(*rules)
def test_given_root_with_leaf_to_prune_then_root_becomes_leaf(self) -> None: from cmaj.testing.ast import tree, token node = tree(('X', [token('X', 0)])) result = prune(node, 'X') expected = tree(('X', [])) self.assertEqual(expected, result)
def test_when_all_children_are_pruned_then_prune_empty_nodes(self) -> None: from cmaj.testing.ast import tree, token node = tree(('X', [token('Y', 0), ('Y', [token('X', 1), token('X', 2)])])) result = prune(node, 'X') expected = tree(('X', [token('Y', 0)])) self.assertEqual(expected, result)
def test_given_root_is_leaf_then_no_prune(self) -> None: from cmaj.testing.ast import tree tree_def = ('node', []) result = prune(tree(tree_def), 'node') self.assertEqual(tree(tree_def), result)