1bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant/*
2bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * [The "BSD licence"]
3f5256e16dfc425c1d466f6308d4026d529ce9e0bHoward Hinnant * Copyright (c) 2005-2008 Terence Parr
4bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * All rights reserved.
5b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant *
6b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant * Conversion to C#:
7bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
8bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * All rights reserved.
9bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *
10bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * Redistribution and use in source and binary forms, with or without
11bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * modification, are permitted provided that the following conditions
12bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * are met:
13bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * 1. Redistributions of source code must retain the above copyright
14bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *    notice, this list of conditions and the following disclaimer.
15bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * 2. Redistributions in binary form must reproduce the above copyright
16bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *    notice, this list of conditions and the following disclaimer in the
17bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *    documentation and/or other materials provided with the distribution.
18bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * 3. The name of the author may not be used to endorse or promote products
19bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *    derived from this software without specific prior written permission.
20bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *
21bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28caee2b093fc892335f666f1a074e8d2de40df467Howard Hinnant * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant */
32bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
33bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantnamespace Antlr.Runtime.Tree
34bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant{
35bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    public delegate TResult Func<T, TResult>(T arg);
36bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    public delegate void Action();
37bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
38caee2b093fc892335f666f1a074e8d2de40df467Howard Hinnant    /**
39bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant     Cut-n-paste from material I'm not using in the book anymore (edit later
40bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant     to make sense):
41bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
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