diff --git a/TP03/tree/Makefile b/TP03/tree/Makefile new file mode 100644 index 0000000..a4f1d15 --- /dev/null +++ b/TP03/tree/Makefile @@ -0,0 +1,24 @@ +PACKAGE = Tree +MAINFILE = tree + +ifndef ANTLR4 +abort: + $(error variable ANTLR4 is not set) +endif + +all: $(PACKAGE).g4 + $(ANTLR4) $^ -Dlanguage=Python3 -visitor + +run: $(MAINFILE).py + python3 $^ + +ex: $(MAINFILE).py + python3 $^ < true_example + python3 $^ < false_example + +test: all + python3 ./test_arith_visitor.py + +clean: + find . \( -iname "~" -or -iname "*.cache*" -or -iname "*.diff" -or -iname "log.txt" -or -iname "*.pyc" -or -iname "*.tokens" -or -iname "*.interp" \) -exec rm -rf '{}' \; + rm -rf $(PACKAGE)*.py diff --git a/TP03/tree/MyTreeVisitor.py b/TP03/tree/MyTreeVisitor.py new file mode 100644 index 0000000..2e379a0 --- /dev/null +++ b/TP03/tree/MyTreeVisitor.py @@ -0,0 +1,19 @@ +from TreeParser import TreeParser +from TreeVisitor import TreeVisitor + +class MyTreeVisitor(TreeVisitor): + def visitTop(self, ctx:TreeParser.TopContext): + return self.visit(ctx.int_tree()) + + def visitLeaf(self, ctx:TreeParser.LeafContext): + return True + + def visitNode(self, ctx:TreeParser.NodeContext): + return ( + len(ctx.int_tree()) == 2 + and all([self.visit(it) for it in ctx.int_tree()]) + ) + + +del TreeVisitor +del TreeParser diff --git a/TP03/tree/false_example b/TP03/tree/false_example new file mode 100644 index 0000000..7d5ad3f --- /dev/null +++ b/TP03/tree/false_example @@ -0,0 +1 @@ +(42 12 1515 17) diff --git a/TP03/tree/tree.py b/TP03/tree/tree.py new file mode 100644 index 0000000..f76fce5 --- /dev/null +++ b/TP03/tree/tree.py @@ -0,0 +1,26 @@ +from TreeLexer import TreeLexer +from TreeParser import TreeParser +# from TreeVisitor import TreeVisitor +from MyTreeVisitor import MyTreeVisitor + +from antlr4 import InputStream, CommonTokenStream +import sys + +# example of use of visitors to parse arithmetic expressions. +# stops when the first SyntaxError is launched. + + +def main(): + lexer = TreeLexer(InputStream(sys.stdin.read())) + stream = CommonTokenStream(lexer) + parser = TreeParser(stream) + tree = parser.int_tree_top() + visitor = MyTreeVisitor() + is_binary_tree: bool = visitor.visit(tree) + print("Is it a binary tree ? " + str(is_binary_tree)) + + +if __name__ == '__main__': + main() + + diff --git a/TP03/tree/true_example b/TP03/tree/true_example new file mode 100644 index 0000000..a5d8857 --- /dev/null +++ b/TP03/tree/true_example @@ -0,0 +1 @@ +(12 (13 (14 15 15) 16) (17 18 (19 20 1)))