File: ExpressionParseTree.java

package info (click to toggle)
tomcat10 10.1.52-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 47,900 kB
  • sloc: java: 375,756; xml: 59,410; jsp: 4,741; sh: 1,381; perl: 324; makefile: 25; ansic: 14
file content (473 lines) | stat: -rw-r--r-- 14,439 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.catalina.ssi;


import java.text.ParseException;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;

/**
 * Represents a parsed expression.
 */
public class ExpressionParseTree {
    private static final StringManager sm = StringManager.getManager(ExpressionParseTree.class);
    /**
     * Contains the current set of completed nodes. This is a workspace for the parser. Needs to be LinkedList since it
     * can contain {@code null}s.
     */
    private final LinkedList<Node> nodeStack = new LinkedList<>();
    /**
     * Contains operator nodes that don't yet have values. This is a workspace for the parser. Needs to be LinkedList
     * since it can contain {@code null}s.
     */
    private final LinkedList<OppNode> oppStack = new LinkedList<>();
    /**
     * The root node after the expression has been parsed.
     */
    private Node root;
    /**
     * The SSIMediator to use when evaluating the expressions.
     */
    private final SSIMediator ssiMediator;


    /**
     * Creates a new parse tree for the specified expression.
     *
     * @param expr        The expression string
     * @param ssiMediator Used to evaluate the expressions
     *
     * @throws ParseException a parsing error occurred
     */
    public ExpressionParseTree(String expr, SSIMediator ssiMediator) throws ParseException {
        this.ssiMediator = ssiMediator;
        parseExpression(expr);
    }


    /**
     * Evaluates the tree and returns true or false. The specified SSIMediator is used to resolve variable references.
     *
     * @return the evaluation result
     *
     * @throws SSIStopProcessingException If an error occurs evaluating the tree
     */
    public boolean evaluateTree() throws SSIStopProcessingException {
        try {
            return root.evaluate();
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            throw new SSIStopProcessingException(t);
        }
    }


    /**
     * Pushes a new operator onto the opp stack, resolving existing opps as needed.
     *
     * @param node The operator node
     */
    private void pushOpp(OppNode node) {
        // If node is null then it's just a group marker
        if (node == null) {
            oppStack.addFirst(null);
            return;
        }
        while (true) {
            if (oppStack.isEmpty()) {
                break;
            }
            OppNode top = oppStack.getFirst();
            // If the top is a spacer then don't pop
            // anything
            if (top == null) {
                break;
            }
            // If the top node has a lower precedence then
            // let it stay
            if (top.getPrecedence() < node.getPrecedence()) {
                break;
            }
            // Remove the top node
            oppStack.removeFirst();
            // Let it fill its branches
            top.popValues(nodeStack);
            // Stick it on the resolved node stack
            nodeStack.addFirst(top);
        }
        // Add the new node to the opp stack
        oppStack.addFirst(node);
    }


    /**
     * Resolves all pending opp nodes on the stack until the next group marker is reached.
     */
    private void resolveGroup() {
        OppNode top;
        while ((top = oppStack.removeFirst()) != null) {
            // Let it fill its branches
            top.popValues(nodeStack);
            // Stick it on the resolved node stack
            nodeStack.addFirst(top);
        }
    }


    /**
     * Parses the specified expression into a tree of parse nodes.
     *
     * @param expr The expression to parse
     *
     * @throws ParseException a parsing error occurred
     */
    private void parseExpression(String expr) throws ParseException {
        StringNode currStringNode = null;
        // We cheat a little and start an artificial
        // group right away. It makes finishing easier.
        pushOpp(null);
        ExpressionTokenizer et = new ExpressionTokenizer(expr);
        while (et.hasMoreTokens()) {
            int token = et.nextToken();
            if (token != ExpressionTokenizer.TOKEN_STRING) {
                currStringNode = null;
            }
            switch (token) {
                case ExpressionTokenizer.TOKEN_STRING:
                    if (currStringNode == null) {
                        currStringNode = new StringNode(et.getTokenValue());
                        nodeStack.addFirst(currStringNode);
                    } else {
                        // Add to the existing
                        currStringNode.value.append(' ');
                        currStringNode.value.append(et.getTokenValue());
                    }
                    break;
                case ExpressionTokenizer.TOKEN_AND:
                    pushOpp(new AndNode());
                    break;
                case ExpressionTokenizer.TOKEN_OR:
                    pushOpp(new OrNode());
                    break;
                case ExpressionTokenizer.TOKEN_NOT:
                    pushOpp(new NotNode());
                    break;
                case ExpressionTokenizer.TOKEN_EQ:
                    pushOpp(new EqualNode());
                    break;
                case ExpressionTokenizer.TOKEN_NOT_EQ:
                    pushOpp(new NotNode());
                    // Sneak the regular node in. They will NOT
                    // be resolved when the next opp comes along.
                    oppStack.addFirst(new EqualNode());
                    break;
                case ExpressionTokenizer.TOKEN_RBRACE:
                    // Closeout the current group
                    resolveGroup();
                    break;
                case ExpressionTokenizer.TOKEN_LBRACE:
                    // Push a group marker
                    pushOpp(null);
                    break;
                case ExpressionTokenizer.TOKEN_GE:
                    pushOpp(new NotNode());
                    // Similar strategy to NOT_EQ above, except this
                    // is NOT less than
                    oppStack.addFirst(new LessThanNode());
                    break;
                case ExpressionTokenizer.TOKEN_LE:
                    pushOpp(new NotNode());
                    // Similar strategy to NOT_EQ above, except this
                    // is NOT greater than
                    oppStack.addFirst(new GreaterThanNode());
                    break;
                case ExpressionTokenizer.TOKEN_GT:
                    pushOpp(new GreaterThanNode());
                    break;
                case ExpressionTokenizer.TOKEN_LT:
                    pushOpp(new LessThanNode());
                    break;
                case ExpressionTokenizer.TOKEN_END:
                    break;
            }
        }
        // Finish off the rest of the opps
        resolveGroup();
        if (nodeStack.isEmpty()) {
            throw new ParseException(sm.getString("expressionParseTree.noNodes"), et.getIndex());
        }
        if (nodeStack.size() > 1) {
            throw new ParseException(sm.getString("expressionParseTree.extraNodes"), et.getIndex());
        }
        if (!oppStack.isEmpty()) {
            throw new ParseException(sm.getString("expressionParseTree.unusedOpCodes"), et.getIndex());
        }
        root = nodeStack.getFirst();
    }

    /**
     * A node in the expression parse tree.
     */
    private abstract static class Node {
        /**
         * @return {@code true} if the node evaluates to true.
         */
        public abstract boolean evaluate();
    }

    /**
     * A node the represents a String value
     */
    private class StringNode extends Node {
        StringBuilder value;
        String resolved = null;


        StringNode(String value) {
            this.value = new StringBuilder(value);
        }


        /**
         * Resolves any variable references and returns the value string.
         *
         * @return the value string
         */
        public String getValue() {
            if (resolved == null) {
                resolved = ssiMediator.substituteVariables(value.toString());
            }
            return resolved;
        }


        /**
         * Returns true if the string is not empty.
         */
        @Override
        public boolean evaluate() {
            return !(getValue().isEmpty());
        }


        @Override
        public String toString() {
            return value.toString();
        }
    }

    private static final int PRECEDENCE_NOT = 5;
    private static final int PRECEDENCE_COMPARE = 4;
    private static final int PRECEDENCE_LOGICAL = 1;

    /**
     * A node implementation that represents an operation.
     */
    private abstract static class OppNode extends Node {
        /**
         * The left branch.
         */
        Node left;
        /**
         * The right branch.
         */
        Node right;


        /**
         * @return a precedence level suitable for comparison to other OppNode preference levels.
         */
        public abstract int getPrecedence();


        /**
         * Lets the node pop its own branch nodes off the front of the specified list. The default pulls two.
         *
         * @param values The list from which to pop the values
         */
        public void popValues(List<Node> values) {
            right = values.remove(0);
            left = values.remove(0);
        }
    }

    private static final class NotNode extends OppNode {
        @Override
        public boolean evaluate() {
            return !left.evaluate();
        }


        @Override
        public int getPrecedence() {
            return PRECEDENCE_NOT;
        }


        /**
         * Overridden to pop only one value.
         */
        @Override
        public void popValues(List<Node> values) {
            left = values.remove(0);
        }


        @Override
        public String toString() {
            return left + " NOT";
        }
    }

    private static final class AndNode extends OppNode {
        @Override
        public boolean evaluate() {
            if (!left.evaluate()) {
                return false;
            }
            return right.evaluate();
        }


        @Override
        public int getPrecedence() {
            return PRECEDENCE_LOGICAL;
        }


        @Override
        public String toString() {
            return left + " " + right + " AND";
        }
    }

    private static final class OrNode extends OppNode {
        @Override
        public boolean evaluate() {
            if (left.evaluate()) {
                return true;
            }
            return right.evaluate();
        }


        @Override
        public int getPrecedence() {
            return PRECEDENCE_LOGICAL;
        }


        @Override
        public String toString() {
            return left + " " + right + " OR";
        }
    }

    private abstract class CompareNode extends OppNode {
        protected int compareBranches() {
            String val1 = ((StringNode) left).getValue();
            String val2 = ((StringNode) right).getValue();

            int val2Len = val2.length();
            if (val2Len > 1 && val2.charAt(0) == '/' && val2.charAt(val2Len - 1) == '/') {
                // Treat as a regular expression
                String expr = val2.substring(1, val2Len - 1);
                ssiMediator.clearMatchGroups();
                try {
                    Pattern pattern = Pattern.compile(expr);
                    // Regular expressions will only ever be used with EqualNode
                    // so return zero for equal and non-zero for not equal
                    Matcher matcher = pattern.matcher(val1);
                    if (matcher.find()) {
                        ssiMediator.populateMatchGroups(matcher);
                        return 0;
                    } else {
                        return -1;
                    }
                } catch (PatternSyntaxException pse) {
                    ssiMediator.log(sm.getString("expressionParseTree.invalidExpression", expr), pse);
                    return 0;
                }
            }
            return val1.compareTo(val2);
        }
    }

    private final class EqualNode extends CompareNode {
        @Override
        public boolean evaluate() {
            return (compareBranches() == 0);
        }


        @Override
        public int getPrecedence() {
            return PRECEDENCE_COMPARE;
        }


        @Override
        public String toString() {
            return left + " " + right + " EQ";
        }
    }

    private final class GreaterThanNode extends CompareNode {
        @Override
        public boolean evaluate() {
            return (compareBranches() > 0);
        }


        @Override
        public int getPrecedence() {
            return PRECEDENCE_COMPARE;
        }


        @Override
        public String toString() {
            return left + " " + right + " GT";
        }
    }

    private final class LessThanNode extends CompareNode {
        @Override
        public boolean evaluate() {
            return (compareBranches() < 0);
        }


        @Override
        public int getPrecedence() {
            return PRECEDENCE_COMPARE;
        }


        @Override
        public String toString() {
            return left + " " + right + " LT";
        }
    }
}