1/*
2 * [The "BSD licence"]
3 * Copyright (c) 2005-2008 Terence Parr
4 * All rights reserved.
5 *
6 * Conversion to C#:
7 * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. The name of the author may not be used to endorse or promote products
19 *    derived from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33namespace Antlr.Runtime.Tree
34{
35    public delegate TResult Func<T, TResult>(T arg);
36    public delegate void Action();
37
38    /**
39     Cut-n-paste from material I'm not using in the book anymore (edit later
40     to make sense):
41
42     Now, how are we going to test these tree patterns against every
43    subtree in our original tree?  In what order should we visit nodes?
44    For this application, it turns out we need a simple ``apply once''
45    rule application strategy and a ``down then up'' tree traversal
46    strategy.  Let's look at rule application first.
47
48    As we visit each node, we need to see if any of our patterns match. If
49    a pattern matches, we execute the associated tree rewrite and move on
50    to the next node. In other words, we only look for a single rule
51    application opportunity (we'll see below that we sometimes need to
52    repeatedly apply rules). The following method applies a rule in a @cl
53    TreeParser (derived from a tree grammar) to a tree:
54
55    here is where weReferenced code/walking/patterns/TreePatternMatcher.java
56
57    It uses reflection to lookup the appropriate rule within the generated
58    tree parser class (@cl Simplify in this case). Most of the time, the
59    rule will not match the tree.  To avoid issuing syntax errors and
60    attempting error recovery, it bumps up the backtracking level.  Upon
61    failure, the invoked rule immediately returns. If you don't plan on
62    using this technique in your own ANTLR-based application, don't sweat
63    the details. This method boils down to ``call a rule to match a tree,
64    executing any embedded actions and rewrite rules.''
65
66    At this point, we know how to define tree grammar rules and how to
67    apply them to a particular subtree. The final piece of the tree
68    pattern matcher is the actual tree traversal. We have to get the
69    correct node visitation order.  In particular, we need to perform the
70    scalar-vector multiply transformation on the way down (preorder) and
71    we need to reduce multiply-by-zero subtrees on the way up (postorder).
72
73    To implement a top-down visitor, we do a depth first walk of the tree,
74    executing an action in the preorder position. To get a bottom-up
75    visitor, we execute an action in the postorder position.  ANTLR
76    provides a standard @cl TreeVisitor class with a depth first search @v
77    visit method. That method executes either a @m pre or @m post method
78    or both. In our case, we need to call @m applyOnce in both. On the way
79    down, we'll look for @r vmult patterns. On the way up,
80    we'll look for @r mult0 patterns.
81     */
82    public class TreeFilter : TreeParser
83    {
84        protected ITokenStream originalTokenStream;
85        protected ITreeAdaptor originalAdaptor;
86
87        public TreeFilter( ITreeNodeStream input )
88            : this( input, new RecognizerSharedState() )
89        {
90        }
91        public TreeFilter( ITreeNodeStream input, RecognizerSharedState state )
92            : base( input, state )
93        {
94            originalAdaptor = input.TreeAdaptor;
95            originalTokenStream = input.TokenStream;
96        }
97
98        public virtual void ApplyOnce( object t, Action whichRule )
99        {
100            if ( t == null )
101                return;
102
103            try
104            {
105                // share TreeParser object but not parsing-related state
106                state = new RecognizerSharedState();
107                input = new CommonTreeNodeStream( originalAdaptor, t );
108                ( (CommonTreeNodeStream)input ).TokenStream = originalTokenStream;
109                BacktrackingLevel = 1;
110                whichRule();
111                BacktrackingLevel = 0;
112            }
113            catch ( RecognitionException )
114            {
115            }
116        }
117
118        public virtual void Downup( object t )
119        {
120            TreeVisitor v = new TreeVisitor( new CommonTreeAdaptor() );
121            Func<object, object> pre = delegate(object o)
122            {
123                ApplyOnce( o, Topdown );
124                return o;
125            };
126            Func<object, object> post = delegate(object o)
127            {
128                ApplyOnce( o, Bottomup );
129                return o;
130            };
131            v.Visit( t, pre, post );
132        }
133
134        // methods the downup strategy uses to do the up and down rules.
135        // to override, just define tree grammar rule topdown and turn on
136        // filter=true.
137        protected virtual void Topdown()
138        {
139        }
140        protected virtual void Bottomup()
141        {
142        }
143    }
144}
145