-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathProcedure.java
More file actions
356 lines (332 loc) · 13.6 KB
/
Procedure.java
File metadata and controls
356 lines (332 loc) · 13.6 KB
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
package com.laytonsmith.core;
import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.PureUtilities.SmartComment;
import com.laytonsmith.core.constructs.Auto;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CClassType;
import com.laytonsmith.core.constructs.CFunction;
import com.laytonsmith.core.constructs.CNull;
import com.laytonsmith.core.constructs.CVoid;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.IVariable;
import com.laytonsmith.core.constructs.InstanceofUtil;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.CRE.AbstractCREException;
import com.laytonsmith.core.exceptions.CRE.CRECastException;
import com.laytonsmith.core.exceptions.CRE.CREFormatException;
import com.laytonsmith.core.exceptions.CRE.CREStackOverflowError;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.exceptions.FunctionReturnException;
import com.laytonsmith.core.exceptions.LoopManipulationException;
import com.laytonsmith.core.exceptions.StackTraceManager;
import com.laytonsmith.core.functions.ControlFlow;
import com.laytonsmith.core.functions.Function;
import com.laytonsmith.core.functions.FunctionBase;
import com.laytonsmith.core.functions.FunctionList;
import com.laytonsmith.core.functions.StringHandling;
import com.laytonsmith.core.natives.interfaces.Mixed;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* A procedure is a user defined function, essentially. Unlike a closure, however, it does not clone a reference to the
* environment when it is defined. It takes on the environment characteristics of the executing environment, not the
* defining environment.
*/
public class Procedure implements Cloneable {
private final String name;
private Map<String, IVariable> varList;
private final Map<String, Mixed> originals = new HashMap<>();
private final List<IVariable> varIndex = new ArrayList<>();
private ParseTree tree;
private CClassType returnType;
private boolean possiblyConstant = false;
private SmartComment procComment;
private static final Pattern PROCEDURE_NAME_REGEX = Pattern.compile("^_[\\p{L}0-9]+[\\p{L}_0-9]*");
/**
* The line the procedure is defined at (for stacktraces)
*/
private final Target definedAt;
public Procedure(String name, CClassType returnType, List<IVariable> varList, SmartComment procComment,
ParseTree tree, Target t) {
this.name = name;
this.definedAt = t;
this.varList = new HashMap<>();
this.procComment = procComment;
for(int i = 0; i < varList.size(); i++) {
IVariable var = varList.get(i);
if(var.getDefinedType().isVariadicType() && i != varList.size() - 1) {
throw new CREFormatException("Varargs can only be added to the last argument.", t);
}
try {
this.varList.put(var.getVariableName(), var.clone());
} catch (CloneNotSupportedException e) {
this.varList.put(var.getVariableName(), var);
}
this.varIndex.add(var);
if(var.getDefinedType().isVariadicType() && var.ival() != CNull.UNDEFINED) {
throw new CREFormatException("Varargs may not have default values", t);
}
this.originals.put(var.getVariableName(), var.ival());
}
this.tree = tree;
if(!PROCEDURE_NAME_REGEX.matcher(name).matches()) {
throw new CREFormatException("Procedure names must start with an underscore, and may only contain letters, underscores, and digits. (Found " + this.name + ")", t);
}
//Let's look through the tree now, and see if this is possibly constant or not.
//If it is, it may or may not help us during compilation, but if it's not,
//we can be sure that we cannot inline this in any way.
this.possiblyConstant = checkPossiblyConstant(tree);
this.returnType = returnType;
}
private boolean checkPossiblyConstant(ParseTree tree) {
//TODO: This whole thing is a mess. Instead of doing it this way,
//individual procs need to be inlined as deemed appropriate.
if(true) {
return false;
}
if(!Construct.IsDynamicHelper(tree.getData())) {
//If it isn't dynamic, it certainly could be constant
return true;
} else if(tree.getData() instanceof IVariable) {
//Variables will return true for isDynamic, but they are technically constant, because
//they are being declared in this scope, or passed in. An import() would break this
//contract, but import() itself is dynamic, so this is not an issue.
return true;
} else if(tree.getData() instanceof CFunction) {
//If the function itself is not optimizable, we needn't recurse.
try {
FunctionBase fb = FunctionList.getFunction((CFunction) tree.getData(), null);
if(fb instanceof Function) {
Function f = (Function) fb;
if(f instanceof ControlFlow._return) {
//This is a special exception. Return itself is not optimizable,
//but if the contents are optimizable, it is still considered constant.
if(!tree.hasChildren()) {
return true;
} else {
return checkPossiblyConstant(tree.getChildAt(0));
}
}
//If it's optimizable, it's possible. If it's restricted, it doesn't matter, because
//we can't optimize it out anyways, because we need to do the permission check
Set<Optimizable.OptimizationOption> o = EnumSet.noneOf(Optimizable.OptimizationOption.class);
if(f instanceof Optimizable) {
o = ((Optimizable) f).optimizationOptions();
}
if(!((o != null && (o.contains(Optimizable.OptimizationOption.OPTIMIZE_DYNAMIC)
|| o.contains(Optimizable.OptimizationOption.OPTIMIZE_CONSTANT))) && !f.isRestricted())) {
return false; //Nope. Doesn't matter if the children are or not
}
} else {
return false;
}
} catch (ConfigCompileException e) {
//It's a proc. We will treat this just like any other function call,
}
//Ok, well, we have to check the children first.
for(ParseTree child : tree.getChildren()) {
if(!checkPossiblyConstant(child)) {
return false; //Nope, since our child can't be constant, neither can we
}
}
//They all check out, so, yep, we could possibly be constant
return true;
} else {
//Uh. Ok, well, nope.
return false;
}
}
public boolean isPossiblyConstant() {
return this.possiblyConstant;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name + "(" + StringUtils.Join(varList.keySet(), ", ") + ")";
}
public SmartComment getSmartComment() {
return procComment;
}
/**
* Convenience wrapper around executing a procedure if the parameters are in tree mode still.
*
* @param args
* @param env
* @param t
* @return
*/
public Mixed cexecute(List<ParseTree> args, Environment env, Target t) {
List<Mixed> list = new ArrayList<>();
for(ParseTree arg : args) {
list.add(env.getEnv(GlobalEnv.class).GetScript().seval(arg, env));
}
return execute(list, env, t);
}
/**
* Executes this procedure, with the arguments that were passed in
*
* @param args The arguments passed to the procedure call.
* @param oldEnv The environment to be cloned.
* @param t
* @return
*/
public Mixed execute(List<Mixed> args, Environment oldEnv, Target t) {
boolean prev = oldEnv.getEnv(GlobalEnv.class).getCloneVars();
oldEnv.getEnv(GlobalEnv.class).setCloneVars(false);
Environment env;
try {
env = oldEnv.clone();
env.getEnv(GlobalEnv.class).setCloneVars(true);
} catch (CloneNotSupportedException ex) {
throw new RuntimeException(ex);
}
oldEnv.getEnv(GlobalEnv.class).setCloneVars(prev);
Script fakeScript = Script.GenerateScript(tree, env.getEnv(GlobalEnv.class).GetLabel(), null);
// Create container for the @arguments variable.
CArray arguments = new CArray(Target.UNKNOWN, this.varIndex.size());
// Handle passed procedure arguments.
int varInd;
CArray vararg = null;
for(varInd = 0; varInd < args.size(); varInd++) {
Mixed c = args.get(varInd);
arguments.push(c, t);
if(this.varIndex.size() > varInd
|| (!this.varIndex.isEmpty()
&& this.varIndex.get(this.varIndex.size() - 1).getDefinedType().isVariadicType())) {
IVariable var;
if(varInd < this.varIndex.size() - 1
|| !this.varIndex.get(this.varIndex.size() - 1).getDefinedType().isVariadicType()) {
var = this.varIndex.get(varInd);
} else {
var = this.varIndex.get(this.varIndex.size() - 1);
if(vararg == null) {
// TODO: Once generics are added, add the type
vararg = new CArray(t);
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE,
var.getVariableName(), vararg, c.getTarget()));
}
}
// Type check "void" value.
if(c instanceof CVoid
&& !(var.getDefinedType().equals(Auto.TYPE) || var.getDefinedType().equals(CVoid.TYPE))) {
throw new CRECastException("Procedure \"" + name + "\" expects a value of type "
+ var.getDefinedType().val() + " in argument " + (varInd + 1) + ", but"
+ " a void value was found instead.", c.getTarget());
}
// Type check vararg parameter.
if(var.getDefinedType().isVariadicType()) {
if(InstanceofUtil.isInstanceof(c.typeof(), var.getDefinedType().getVarargsBaseType(), env)) {
vararg.push(c, t);
continue;
} else {
throw new CRECastException("Procedure \"" + name + "\" expects a value of type "
+ var.getDefinedType().val() + " in argument " + (varInd + 1) + ", but"
+ " a value of type " + c.typeof() + " was found instead.", c.getTarget());
}
}
// Type check non-vararg parameter.
if(InstanceofUtil.isInstanceof(c.typeof(), var.getDefinedType(), env)) {
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(var.getDefinedType(),
var.getVariableName(), c, c.getTarget()));
continue;
} else {
throw new CRECastException("Procedure \"" + name + "\" expects a value of type "
+ var.getDefinedType().val() + " in argument " + (varInd + 1) + ", but"
+ " a value of type " + c.typeof() + " was found instead.", c.getTarget());
}
}
}
// Assign default values to remaining proc arguments.
while(varInd < this.varIndex.size()) {
String varName = this.varIndex.get(varInd++).getVariableName();
Mixed defVal = this.originals.get(varName);
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(Auto.TYPE, varName, defVal, defVal.getTarget()));
arguments.push(defVal, t);
}
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, t));
StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("proc " + name, getTarget()));
try {
if(tree.getData() instanceof CFunction
&& tree.getData().val().equals(StringHandling.sconcat.NAME)) {
//If the inner tree is just an sconcat, we can optimize by
//simply running the arguments to the sconcat. We're not going
//to use the results, after all, and this is a common occurrence,
//because the compiler will often put it there automatically.
//We *could* optimize this by removing it from the compiled code,
//and we still should do that, but this check is quick enough,
//and so can remain even once we do add the optimization to the
//compiler proper.
for(ParseTree child : tree.getChildren()) {
fakeScript.eval(child, env);
}
} else {
fakeScript.eval(tree, env);
}
} catch (FunctionReturnException e) {
// Normal exit
Mixed ret = e.getReturn();
if(returnType.equals(Auto.TYPE)) {
return ret;
}
if(returnType.equals(CVoid.TYPE) != ret.equals(CVoid.VOID)
|| !ret.equals(CNull.NULL) && !ret.equals(CVoid.VOID)
&& !InstanceofUtil.isInstanceof(ret.typeof(), returnType, env)) {
throw new CRECastException("Expected procedure \"" + name + "\" to return a value of type "
+ returnType.val() + " but a value of type " + ret.typeof() + " was returned instead",
ret.getTarget());
}
return ret;
} catch (LoopManipulationException ex) {
// These cannot bubble up past procedure calls. This will eventually be
// a compile error.
throw ConfigRuntimeException.CreateUncatchableException("Loop manipulation operations (e.g. break() or continue()) cannot"
+ " bubble up past procedures.", t);
} catch (ConfigRuntimeException e) {
if(e instanceof AbstractCREException) {
((AbstractCREException) e).freezeStackTraceElements(stManager);
}
throw e;
} catch (StackOverflowError e) {
throw new CREStackOverflowError(null, t, e);
} finally {
stManager.popStackTraceElement();
}
// Normal exit, but no return.
// If we got here, then there was no return value. This is fine, but only for returnType void or auto.
// TODO: Once strong typing is implemented at a compiler level, this should be removed to increase runtime
// performance.
if(!(returnType.equals(Auto.TYPE) || returnType.equals(CVoid.TYPE))) {
throw new CRECastException("Expecting procedure \"" + name + "\" to return a value of type " + returnType.val() + ","
+ " but no value was returned.", tree.getTarget());
}
return CVoid.VOID;
}
public Target getTarget() {
return definedAt;
}
@Override
public Procedure clone() throws CloneNotSupportedException {
Procedure clone = (Procedure) super.clone();
if(this.varList != null) {
clone.varList = new HashMap<>(this.varList);
}
if(this.tree != null) {
clone.tree = this.tree.clone();
}
return clone;
}
public void definitelyNotConstant() {
possiblyConstant = false;
}
}