From ce0eba2c673848f1920b4a085ca264eb255681b4 Mon Sep 17 00:00:00 2001 From: Jean Privat Date: Sat, 21 Feb 2015 09:56:54 +0700 Subject: [PATCH] parser: add `ASTDump` and `ANode::dump_tree` Signed-off-by: Jean Privat --- src/parser/parser_nodes.nit | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/parser/parser_nodes.nit b/src/parser/parser_nodes.nit index 289ad53..1c0eb21 100644 --- a/src/parser/parser_nodes.nit +++ b/src/parser/parser_nodes.nit @@ -17,6 +17,7 @@ module parser_nodes import location +import ordered_tree # Root of the AST class-hierarchy abstract class ANode @@ -33,6 +34,15 @@ abstract class ANode sys.stderr.write "{hot_location} {self.class_name}: {message}\n{hot_location.colored_line("0;32")}\n" end + # Write the subtree on stdout. + # See `ASTDump` + fun dump_tree + do + var d = new ASTDump + d.enter_visit(self) + d.write_to(sys.stdout) + end + # Parent of the node in the AST var parent: nullable ANode = null @@ -158,6 +168,33 @@ private class CollectAnnotationsByNameVisitor end end +# A helper class to handle (print) Nit AST as an OrderedTree +class ASTDump + super Visitor + super OrderedTree[ANode] + + # Reference to the last parent in the Ordered Tree + # Is used to handle the initial node parent and workaround possible inconsistent `ANode::parent` + private var last_parent: nullable ANode = null + + redef fun visit(n) + do + var p = last_parent + add(p, n) + last_parent = n + n.visit_all(self) + last_parent = p + end + + redef fun display(n) + do + if n isa Token then + return "{n.class_name} \"{n.text.escape_to_c}\" @{n.location}" + else + return "{n.class_name} @{n.location}" + end + end +end # A sequence of nodes # It is a specific class (instead of using a Array) to track the parent/child relation when nodes are added or removed -- 1.7.9.5