Debian Codegraph @

src/main/java/com/google/escapevelocity/DirectiveNode.java

raw
1 /*
2 * Copyright (C) 2018 Google, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package com.google.escapevelocity;
17
18 import com.google.common.base.Verify;
19 import com.google.common.collect.ImmutableList;
20 import java.util.Arrays;
21 import java.util.Iterator;
22 import java.util.Map;
23
24 /**
25 * A node in the parse tree that is a directive such as {@code #set ($x = $y)}
26 * or {@code #if ($x) y #end}.
27 *
28 * @author [email protected] (Éamonn McManus)
29 */
30 abstract class DirectiveNode extends Node {
31 DirectiveNode(String resourceName, int lineNumber) {
32 super(resourceName, lineNumber);
33 }
34
35 /**
36 * A node in the parse tree representing a {@code #set} construct. Evaluating
37 * {@code #set ($x = 23)} will set {@code $x} to the value 23. It does not in itself produce
38 * any text in the output.
39 *
40 * <p>Velocity supports setting values within arrays or collections, with for example
41 * {@code $set ($x[$i] = $y)}. That is not currently supported here.
42 */
43 static class SetNode extends DirectiveNode {
44 private final String var;
45 private final Node expression;
46
47 SetNode(String var, Node expression) {
48 super(expression.resourceName, expression.lineNumber);
49 this.var = var;
50 this.expression = expression;
51 }
52
53 @Override
54 Object evaluate(EvaluationContext context) {
55 context.setVar(var, expression.evaluate(context));
56 return "";
57 }
58 }
59
60 /**
61 * A node in the parse tree representing an {@code #if} construct. All instances of this class
62 * have a <i>true</i> subtree and a <i>false</i> subtree. For a plain {@code #if (cond) body
63 * #end}, the false subtree will be empty. For {@code #if (cond1) body1 #elseif (cond2) body2
64 * #else body3 #end}, the false subtree will contain a nested {@code IfNode}, as if {@code #else
65 * #if} had been used instead of {@code #elseif}.
66 */
67 static class IfNode extends DirectiveNode {
68 private final ExpressionNode condition;
69 private final Node truePart;
70 private final Node falsePart;
71
72 IfNode(
73 String resourceName,
74 int lineNumber,
75 ExpressionNode condition,
76 Node trueNode,
77 Node falseNode) {
78 super(resourceName, lineNumber);
79 this.condition = condition;
80 this.truePart = trueNode;
81 this.falsePart = falseNode;
82 }
83
84 @Override Object evaluate(EvaluationContext context) {
85 Node branch = condition.isDefinedAndTrue(context) ? truePart : falsePart;
86 return branch.evaluate(context);
87 }
88 }
89
90 /**
91 * A node in the parse tree representing a {@code #foreach} construct. While evaluating
92 * {@code #foreach ($x in $things)}, {$code $x} will be set to each element of {@code $things} in
93 * turn. Once the loop completes, {@code $x} will go back to whatever value it had before, which
94 * might be undefined. During loop execution, the variable {@code $foreach} is also defined.
95 * Velocity defines a number of properties in this variable, but here we only support
96 * {@code $foreach.hasNext}.
97 */
98 static class ForEachNode extends DirectiveNode {
99 private final String var;
100 private final ExpressionNode collection;
101 private final Node body;
102
103 ForEachNode(String resourceName, int lineNumber, String var, ExpressionNode in, Node body) {
104 super(resourceName, lineNumber);
105 this.var = var;
106 this.collection = in;
107 this.body = body;
108 }
109
110 @Override
111 Object evaluate(EvaluationContext context) {
112 Object collectionValue = collection.evaluate(context);
113 Iterable<?> iterable;
114 if (collectionValue instanceof Iterable<?>) {
115 iterable = (Iterable<?>) collectionValue;
116 } else if (collectionValue instanceof Object[]) {
117 iterable = Arrays.asList((Object[]) collectionValue);
118 } else if (collectionValue instanceof Map<?, ?>) {
119 iterable = ((Map<?, ?>) collectionValue).values();
120 } else {
121 throw evaluationException("Not iterable: " + collectionValue);
122 }
123 Runnable undo = context.setVar(var, null);
124 StringBuilder sb = new StringBuilder();
125 CountingIterator it = new CountingIterator(iterable.iterator());
126 Runnable undoForEach = context.setVar("foreach", new ForEachVar(it));
127 while (it.hasNext()) {
128 context.setVar(var, it.next());
129 sb.append(body.evaluate(context));
130 }
131 undoForEach.run();
132 undo.run();
133 return sb.toString();
134 }
135
136 private static class CountingIterator implements Iterator<Object> {
137 private final Iterator<?> iterator;
138 private int index = -1;
139
140 CountingIterator(Iterator<?> iterator) {
141 this.iterator = iterator;
142 }
143
144 @Override
145 public boolean hasNext() {
146 return iterator.hasNext();
147 }
148
149 @Override
150 public Object next() {
151 Object next = iterator.next();
152 index++;
153 return next;
154 }
155
156 int index() {
157 return index;
158 }
159 }
160
161 /**
162 * This class is the type of the variable {@code $foreach} that is defined within
163 * {@code #foreach} loops. Its {@link #getHasNext()} method means that we can write
164 * {@code #if ($foreach.hasNext)} and likewise for {@link #getIndex()}.
165 */
166 private static class ForEachVar {
167 private final CountingIterator iterator;
168
169 ForEachVar(CountingIterator iterator) {
170 this.iterator = iterator;
171 }
172
173 public boolean getHasNext() {
174 return iterator.hasNext();
175 }
176
177 public int getIndex() {
178 return iterator.index();
179 }
180 }
181 }
182
183 /**
184 * A node in the parse tree representing a macro call. If the template contains a definition like
185 * {@code #macro (mymacro $x $y) ... #end}, then a call of that macro looks like
186 * {@code #mymacro (xvalue yvalue)}. The call is represented by an instance of this class. The
187 * definition itself does not appear in the parse tree.
188 *
189 * <p>Evaluating a macro involves temporarily setting the parameter variables ({@code $x $y} in
190 * the example) to thunks representing the argument expressions, evaluating the macro body, and
191 * restoring any previous values that the parameter variables had.
192 */
193 static class MacroCallNode extends DirectiveNode {
194 private final String name;
195 private final ImmutableList<Node> thunks;
196 private Macro macro;
197
198 MacroCallNode(
199 String resourceName,
200 int lineNumber,
201 String name,
202 ImmutableList<Node> argumentNodes) {
203 super(resourceName, lineNumber);
204 this.name = name;
205 this.thunks = argumentNodes;
206 }
207
208 String name() {
209 return name;
210 }
211
212 int argumentCount() {
213 return thunks.size();
214 }
215
216 void setMacro(Macro macro) {
217 this.macro = macro;
218 }
219
220 @Override
221 Object evaluate(EvaluationContext context) {
222 Verify.verifyNotNull(macro, "Macro #%s should have been linked", name);
223 return macro.evaluate(context, thunks);
224 }
225 }
226 }