diff options
| author | Krasimir Angelov <kr.angelov@gmail.com> | 2017-08-29 18:03:26 +0200 |
|---|---|---|
| committer | Krasimir Angelov <kr.angelov@gmail.com> | 2017-08-29 18:03:26 +0200 |
| commit | dc0b68cd4065db80f4facc31f9b9c7d24f0ea815 (patch) | |
| tree | 1ceb8fa69a25e167c8a1f5c5f2992a78a0e46e42 /doc | |
| parent | e9e5952eac2aa305d485b60642760aa12a0f729c (diff) | |
document the visitor pattern in Java
Diffstat (limited to 'doc')
| -rw-r--r-- | doc/runtime-api.html | 41 |
1 files changed, 40 insertions, 1 deletions
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 <tt>default</tt>. The following is an example: +call the method <tt>default</tt>. The following is an example: <pre class="python"> >>> class ExampleVisitor: def on_DetCN(self,quant,cn): @@ -587,6 +587,45 @@ correspondingly. In this example we just print a message and we call <tt>visit</tt> recursively to go deeper into the tree. </p> </span> +<span class="java"> +<p> +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 +<tt>f</tt> then you need a method called <tt>on_f</tt>. 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 <tt>defaultCase</tt>. The following is an example: +<pre class="java"> +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 +</pre> +Here we call the method <tt>visit</tt> from the tree e2 and we give +it, as parameter, an instance of a class with two methods <tt>on_DetCN</tt> +and <tt>on_AdjCN</tt> which are called when the top function of +the current tree is <tt>DetCN</tt> or <tt>AdjCN</tt> +correspondingly. In this example we just print a message and +we call <tt>visit</tt> recursively to go deeper into the tree. +</p> +</span> Constructing new trees is also easy. You can either use <tt>readExpr</tt> to read trees from strings, or you can |
