• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 [The "BSD license"]
3 Copyright (c) 2005-2009 Terence Parr
4 All rights reserved.
5
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9 1. Redistributions of source code must retain the above copyright
10     notice, this list of conditions and the following disclaimer.
11 2. Redistributions in binary form must reproduce the above copyright
12     notice, this list of conditions and the following disclaimer in the
13     documentation and/or other materials provided with the distribution.
14 3. The name of the author may not be used to endorse or promote products
15     derived from this software without specific prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/* Java Stuff
30package org.antlr.runtime.tree;
31
32import org.antlr.runtime.RecognizerSharedState;
33import org.antlr.runtime.RecognitionException;
34import org.antlr.runtime.TokenStream;
35*/
36
37/**
38 Cut-n-paste from material I'm not using in the book anymore (edit later
39 to make sense):
40
41 Now, how are we going to test these tree patterns against every
42subtree in our original tree?  In what order should we visit nodes?
43For this application, it turns out we need a simple ``apply once''
44rule application strategy and a ``down then up'' tree traversal
45strategy.  Let's look at rule application first.
46
47As we visit each node, we need to see if any of our patterns match. If
48a pattern matches, we execute the associated tree rewrite and move on
49to the next node. In other words, we only look for a single rule
50application opportunity (we'll see below that we sometimes need to
51repeatedly apply rules). The following method applies a rule in a @cl
52TreeParser (derived from a tree grammar) to a tree:
53
54here is where weReferenced code/walking/patterns/TreePatternMatcher.java
55
56It uses reflection to lookup the appropriate rule within the generated
57tree parser class (@cl Simplify in this case). Most of the time, the
58rule will not match the tree.  To avoid issuing syntax errors and
59attempting error recovery, it bumps up the backtracking level.  Upon
60failure, the invoked rule immediately returns. If you don't plan on
61using this technique in your own ANTLR-based application, don't sweat
62the details. This method boils down to ``call a rule to match a tree,
63executing any embedded actions and rewrite rules.''
64
65At this point, we know how to define tree grammar rules and how to
66apply them to a particular subtree. The final piece of the tree
67pattern matcher is the actual tree traversal. We have to get the
68correct node visitation order.  In particular, we need to perform the
69scalar-vector multiply transformation on the way down (preorder) and
70we need to reduce multiply-by-zero subtrees on the way up (postorder).
71
72To implement a top-down visitor, we do a depth first walk of the tree,
73executing an action in the preorder position. To get a bottom-up
74visitor, we execute an action in the postorder position.  ANTLR
75provides a standard @cl TreeVisitor class with a depth first search @v
76visit method. That method executes either a @m pre or @m post method
77or both. In our case, we need to call @m applyOnce in both. On the way
78down, we'll look for @r vmult patterns. On the way up,
79we'll look for @r mult0 patterns.
80 */
81
82/*  Java Stuff
83public class TreeFilter extends TreeParser {
84    public interface fptr {
85        public void rule() throws RecognitionException;
86    }
87
88    protected TokenStream originalTokenStream;
89    protected TreeAdaptor originalAdaptor;
90
91    public TreeFilter(TreeNodeStream input) {
92        this(input, new RecognizerSharedState());
93    }
94    public TreeFilter(TreeNodeStream input, RecognizerSharedState state) {
95        super(input, state);
96        originalAdaptor = input.getTreeAdaptor();
97        originalTokenStream = input.getTokenStream();
98    }
99
100    public void applyOnce(Object t, fptr whichRule) {
101        if ( t==null ) return;
102        try {
103            // share TreeParser object but not parsing-related state
104            state = new RecognizerSharedState();
105            input = new CommonTreeNodeStream(originalAdaptor, t);
106            ((CommonTreeNodeStream)input).setTokenStream(originalTokenStream);
107            setBacktrackingLevel(1);
108            whichRule.rule();
109            setBacktrackingLevel(0);
110        }
111        catch (RecognitionException e) { ; }
112    }
113
114    public void downup(Object t) {
115        TreeVisitor v = new TreeVisitor(new CommonTreeAdaptor());
116        TreeVisitorAction actions = new TreeVisitorAction() {
117            public Object pre(Object t)  { applyOnce(t, topdown_fptr); return t; }
118            public Object post(Object t) { applyOnce(t, bottomup_fptr); return t; }
119        };
120        v.visit(t, actions);
121    }
122
123    fptr topdown_fptr = new fptr() {
124        public void rule() throws RecognitionException {
125            topdown();
126        }
127    };
128
129    fptr bottomup_fptr = new fptr() {
130        public void rule() throws RecognitionException {
131            bottomup();
132        }
133    };
134
135    // methods the downup strategy uses to do the up and down rules.
136    // to override, just define tree grammar rule topdown and turn on
137    // filter=true.
138    public void topdown() throws RecognitionException {;}
139    public void bottomup() throws RecognitionException {;}
140}
141
142*/
143
144#import "CommonTreeNodeStream.h"
145#import "TreeFilter.h"
146
147@class TreeFilter;
148
149@implementation fptr
150
151+ (fptr *) newfptr:(TreeFilter *)aTreeFilter Rule:(SEL) aRule
152{
153    return [[fptr alloc] init];
154}
155
156- (fptr *) init:(TreeFilter *)aTreeFilter Rule:(SEL)aRule
157{
158    if ( (self = [super init]) != nil ) {
159        whichRule = aRule;
160        treeFilter = aTreeFilter;
161    }
162    return self;
163}
164
165- (void) rule
166{
167    if ( [treeFilter respondsToSelector:whichRule] ) {
168        [treeFilter performSelector:whichRule];
169    }
170    return;
171}
172
173@synthesize whichRule;
174@synthesize treeFilter;
175
176@end
177
178@implementation TreeFilter
179
180+ (TreeFilter *) newTreeFilter:(id<TreeNodeStream>)anInput
181{
182
183    return [[TreeFilter alloc] initWithStream:anInput State:[RecognizerSharedState newRecognizerSharedState]];
184}
185
186+ (TreeFilter *) newTreeFilter:(id<TreeNodeStream>)anInput State:(RecognizerSharedState *) aState
187{
188    return [[TreeFilter alloc] initWithStream:anInput State:aState];
189}
190
191- (id) initWithStream:(id<TreeNodeStream>)anInput State:(RecognizerSharedState *)aState
192{
193    if (( self = [super initWithStream:input State:aState]) != nil ) {
194        originalAdaptor = [anInput getTreeAdaptor];
195        originalTokenStream = [anInput getTokenStream];
196        topdown_fptr = nil;
197        bottomup_fptr = nil;
198    }
199    return self;
200}
201
202- (void) applyOnce:(id<BaseTree>)t rule:(fptr *)whichRule
203{
204        if ( t==nil ) return;
205        @try {
206            // share TreeParser object but not parsing-related state
207            state = [RecognizerSharedState newRecognizerSharedState];
208            input = [CommonTreeNodeStream newCommonTreeNodeStream:originalAdaptor Tree:(CommonTree *)t];
209            [(CommonTreeNodeStream *)input setTokenStream:originalTokenStream];
210            [self setBacktrackingLevel:1];
211            [whichRule rule];
212            [self setBacktrackingLevel:0];
213        }
214        @catch (RecognitionException *e) { ; }
215    }
216
217- (void) downup:(id<BaseTree>) t
218{
219    TreeVisitor *v = [TreeVisitor newTreeVisitor:[CommonTreeAdaptor newTreeAdaptor]];
220    TreeVisitorAction *actions = [TreeVisitorActionFiltered newTreeVisitorActionFiltered:self
221                                                                                   RuleD:topdown_fptr
222                                                                                   RuleU:bottomup_fptr];
223    [v visit:t Action:actions];
224}
225
226- (void) settopdown_fptr
227{
228    SEL aRule = @selector(topdown);
229    topdown_fptr =  [fptr newfptr:self Rule:aRule];
230}
231- (void) setbottomdown_fptr
232{
233    SEL aRule = @selector(bottomup);
234    bottomup_fptr =  [fptr newfptr:self Rule:aRule];
235}
236
237    // methods the downup strategy uses to do the up and down rules.
238    // to override, just define tree grammar rule topdown and turn on
239    // filter=true.
240- (void) topdown
241{
242    return;
243}
244
245- (void) bottomup
246{
247    return;
248}
249
250@synthesize originalTokenStream;
251@synthesize originalAdaptor;
252@synthesize topdown_fptr;
253@synthesize bottomup_fptr;
254
255@end
256
257// end TreeFilter.h
258
259