Debian Codegraph @

src/main/java/com/google/escapevelocity/Macro.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 com.google.common.collect.ImmutableSet;
21 import java.lang.reflect.Method;
22 import java.util.LinkedHashMap;
23 import java.util.List;
24 import java.util.Map;
25
26 /**
27 * A macro definition. Macros appear in templates using the syntax {@code #macro (m $x $y) ... #end}
28 * and each one produces an instance of this class. Evaluating a macro involves setting the
29 * parameters (here {$x $y)} and evaluating the macro body. Macro arguments are call-by-name, which
30 * means that we need to set each parameter variable to the node in the parse tree that corresponds
31 * to it, and arrange for that node to be evaluated when the variable is actually referenced.
32 *
33 * @author [email protected] (Éamonn McManus)
34 */
35 class Macro {
36 private final int definitionLineNumber;
37 private final String name;
38 private final ImmutableList<String> parameterNames;
39 private final Node body;
40
41 Macro(int definitionLineNumber, String name, List<String> parameterNames, Node body) {
42 this.definitionLineNumber = definitionLineNumber;
43 this.name = name;
44 this.parameterNames = ImmutableList.copyOf(parameterNames);
45 this.body = body;
46 }
47
48 String name() {
49 return name;
50 }
51
52 int parameterCount() {
53 return parameterNames.size();
54 }
55
56 Object evaluate(EvaluationContext context, List<Node> thunks) {
57 try {
58 Verify.verify(thunks.size() == parameterNames.size(), "Argument mistmatch for %s", name);
59 Map<String, Node> parameterThunks = new LinkedHashMap<>();
60 for (int i = 0; i < parameterNames.size(); i++) {
61 parameterThunks.put(parameterNames.get(i), thunks.get(i));
62 }
63 EvaluationContext newContext = new MacroEvaluationContext(parameterThunks, context);
64 return body.evaluate(newContext);
65 } catch (EvaluationException e) {
66 EvaluationException newException = new EvaluationException(
67 "In macro #" + name + " defined on line " + definitionLineNumber + ": " + e.getMessage());
68 newException.setStackTrace(e.getStackTrace());
69 throw e;
70 }
71 }
72
73 /**
74 * The context for evaluation within macros. This wraps an existing {@code EvaluationContext}
75 * but intercepts reads of the macro's parameters so that they result in a call-by-name evaluation
76 * of whatever was passed as the parameter. For example, if you write...
77 * <pre>{@code
78 * #macro (mymacro $x)
79 * $x $x
80 * #end
81 * #mymacro($foo.bar(23))
82 * }</pre>
83 * ...then the {@code #mymacro} call will result in {@code $foo.bar(23)} being evaluated twice,
84 * once for each time {@code $x} appears. The way this works is that {@code $x} is a <i>thunk</i>.
85 * Historically a thunk is a piece of code to evaluate an expression in the context where it
86 * occurs, for call-by-name procedures as in Algol 60. Here, it is not exactly a piece of code,
87 * but it has the same responsibility.
88 */
89 static class MacroEvaluationContext implements EvaluationContext {
90 private final Map<String, Node> parameterThunks;
91 private final EvaluationContext originalEvaluationContext;
92
93 MacroEvaluationContext(
94 Map<String, Node> parameterThunks, EvaluationContext originalEvaluationContext) {
95 this.parameterThunks = parameterThunks;
96 this.originalEvaluationContext = originalEvaluationContext;
97 }
98
99 @Override
100 public Object getVar(String var) {
101 Node thunk = parameterThunks.get(var);
102 if (thunk == null) {
103 return originalEvaluationContext.getVar(var);
104 } else {
105 // Evaluate the thunk in the context where it appeared, not in this context. Otherwise
106 // if you pass $x to a parameter called $x you would get an infinite recursion. Likewise
107 // if you had #macro(mymacro $x $y) and a call #mymacro($y 23), you would expect that $x
108 // would expand to whatever $y meant at the call site, rather than to the value of the $y
109 // parameter.
110 return thunk.evaluate(originalEvaluationContext);
111 }
112 }
113
114 @Override
115 public boolean varIsDefined(String var) {
116 return parameterThunks.containsKey(var) || originalEvaluationContext.varIsDefined(var);
117 }
118
119 @Override
120 public Runnable setVar(final String var, Object value) {
121 // Copy the behaviour that #set will shadow a macro parameter, even though the Velocity peeps
122 // seem to agree that that is not good.
123 final Node thunk = parameterThunks.get(var);
124 if (thunk == null) {
125 return originalEvaluationContext.setVar(var, value);
126 } else {
127 parameterThunks.remove(var);
128 final Runnable originalUndo = originalEvaluationContext.setVar(var, value);
129 return () -> {
130 originalUndo.run();
131 parameterThunks.put(var, thunk);
132 };
133 }
134 }
135
136 @Override
137 public ImmutableSet<Method> publicMethodsWithName(Class<?> startClass, String name) {
138 return originalEvaluationContext.publicMethodsWithName(startClass, name);
139 }
140 }
141 }