From dc0b68cd4065db80f4facc31f9b9c7d24f0ea815 Mon Sep 17 00:00:00 2001 From: Krasimir Angelov Date: Tue, 29 Aug 2017 18:03:26 +0200 Subject: [PATCH] document the visitor pattern in Java --- doc/runtime-api.html | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/doc/runtime-api.html b/doc/runtime-api.html index bdff41a06..d8759e01b 100644 --- a/doc/runtime-api.html +++ b/doc/runtime-api.html @@ -561,7 +561,7 @@ in the abstract syntax of the grammar. If the functions is called will be called each time when the corresponding function is encountered, and its arguments will be the arguments from the original tree. If there is no matching method name then the runtime will -to call the method default. The following is an example: +call the method default. The following is an example:
 >>> class ExampleVisitor:
 		def on_DetCN(self,quant,cn):
@@ -587,6 +587,45 @@ correspondingly. In this example we just print a message and
 we call visit recursively to go deeper into the tree.
 

+ +

+For more complex analyses you can use the visitor pattern. +In object oriented languages this is just a clumpsy way to do +what is called pattern matching in most functional languages. +You need to define a class which has one method for each function +in the abstract syntax of the grammar. If the functions is called +f then you need a method called on_f. The method +will be called each time when the corresponding function is encountered, +and its arguments will be the arguments from the original tree. +If there is no matching method name then the runtime will +call the method defaultCase. The following is an example: +

+e2.visit(new Object() {
+            public void on_DetCN(Expr quant, Expr cn) {
+                System.out.println("found DetCN");
+                cn.visit(this);
+            }
+
+            public void on_AdjCN(Expr adj, Expr cn) {
+                System.out.println("found AdjCN");
+                cn.visit(this);
+            }
+
+            public void defaultCase(Expr e) {
+                System.out.println("found "+e);
+            }
+        });
+Found DetCN
+Found AdjCN
+
+Here we call the method visit from the tree e2 and we give +it, as parameter, an instance of a class with two methods on_DetCN +and on_AdjCN which are called when the top function of +the current tree is DetCN or AdjCN +correspondingly. In this example we just print a message and +we call visit recursively to go deeper into the tree. +

+
Constructing new trees is also easy. You can either use readExpr to read trees from strings, or you can