1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.jexl2.parser;
18
19 import org.apache.commons.jexl2.DebugInfo;
20 import org.apache.commons.jexl2.JexlInfo;
21
22 /**
23 * Base class for parser nodes - holds an 'image' of the token for later use.
24 *
25 * @since 2.0
26 */
27 public abstract class JexlNode extends SimpleNode implements JexlInfo {
28 /** A marker interface for literals.
29 * @param <T> the literal type
30 */
31 public interface Literal<T> {
32 T getLiteral();
33 }
34 /** token value. */
35 public String image;
36
37 public JexlNode(int id) {
38 super(id);
39 }
40
41 public JexlNode(Parser p, int id) {
42 super(p, id);
43 }
44
45 /** {@inheritDoc} */
46 public DebugInfo debugInfo() {
47 JexlNode node = this;
48 while (node != null) {
49 if (node.value instanceof DebugInfo) {
50 return (DebugInfo) node.value;
51 }
52 node = node.jjtGetParent();
53 }
54 return null;
55 }
56
57 /** {@inheritDoc} */
58 public String debugString() {
59 DebugInfo info = debugInfo();
60 return info != null ? info.debugString() : "";
61 }
62
63 /**
64 * Whether this node is a constant node
65 * Its value can not change after the first evaluation and can be cached indefinitely.
66 * @return true if constant, false otherwise
67 */
68 public final boolean isConstant() {
69 return isConstant(this instanceof JexlNode.Literal<?>);
70 }
71
72 protected boolean isConstant(boolean literal) {
73 if (literal) {
74 if (children != null) {
75 for (JexlNode child : children) {
76 if (child instanceof ASTReference) {
77 boolean is = child.isConstant(true);
78 if (!is) {
79 return false;
80 }
81 } else if (child instanceof ASTMapEntry) {
82 boolean is = child.isConstant(true);
83 if (!is) {
84 return false;
85 }
86 } else if (!child.isConstant()) {
87 return false;
88 }
89 }
90 }
91 return true;
92 }
93 return false;
94 }
95 }