/
CClosure.java
252 lines (233 loc) · 8.63 KB
/
CClosure.java
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
package com.laytonsmith.core.constructs;
import com.laytonsmith.PureUtilities.Version;
import com.laytonsmith.annotations.typeof;
import com.laytonsmith.core.CHLog;
import com.laytonsmith.core.MSVersion;
import com.laytonsmith.core.MethodScriptCompiler;
import com.laytonsmith.core.ParseTree;
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.CancelCommandException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.exceptions.FunctionReturnException;
import com.laytonsmith.core.exceptions.LoopManipulationException;
import com.laytonsmith.core.exceptions.ProgramFlowManipulationException;
import com.laytonsmith.core.exceptions.StackTraceManager;
import com.laytonsmith.core.natives.interfaces.Mixed;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A closure is just an anonymous procedure.
*
*
*/
@typeof("ms.lang.closure")
public class CClosure extends Construct {
public static final long serialVersionUID = 1L;
protected ParseTree node;
protected final Environment env;
protected final String[] names;
protected final Mixed[] defaults;
protected final CClassType[] types;
protected final CClassType returnType;
@SuppressWarnings("FieldNameHidesFieldInSuperclass")
public static final CClassType TYPE = CClassType.get("ms.lang.closure");
public CClosure(ParseTree node, Environment env, CClassType returnType, String[] names, Mixed[] defaults, CClassType[] types, Target t) {
super(node != null ? node.toString() : "", ConstructType.CLOSURE, t);
this.node = node;
this.env = env;
this.names = names;
this.defaults = defaults;
this.types = types;
this.returnType = returnType;
for(String pName : names) {
if(pName.equals("@arguments")) {
CHLog.GetLogger().w(CHLog.Tags.COMPILER, "This closure overrides the builtin @arguments parameter", t);
break;
}
}
}
@Override
public String val() {
StringBuilder b = new StringBuilder();
condense(getNode(), b);
return b.toString();
}
private void condense(ParseTree node, StringBuilder b) {
if(node == null) {
return;
}
if(node.getData() instanceof CFunction) {
b.append(((CFunction) node.getData()).val()).append("(");
for(int i = 0; i < node.numberOfChildren(); i++) {
condense(node.getChildAt(i), b);
if(i != node.numberOfChildren() - 1 && !((CFunction) node.getData()).val().equals("__autoconcat__")) {
b.append(",");
}
}
b.append(")");
} else if(node.getData() instanceof CString) {
CString data = (CString) node.getData();
// Convert: \ -> \\ and ' -> \'
b.append("'").append(data.val().replace("\\", "\\\\").replaceAll("\t", "\\\\t").replaceAll("\n", "\\\\n").replace("'", "\\'")).append("'");
} else if(node.getData() instanceof IVariable) {
b.append(((IVariable) node.getData()).getVariableName());
} else {
b.append(node.getData().val());
}
}
public ParseTree getNode() {
return node;
}
@Override
public CClosure clone() throws CloneNotSupportedException {
CClosure clone = (CClosure) super.clone();
if(this.node != null) {
clone.node = this.node.clone();
}
return clone;
}
/**
* If meta code needs to affect this closure's environment, it can access it with this function. Note that changing
* this will only affect future runs of the closure, it will not affect the currently running closure, (if any) due
* to the environment being cloned right before running.
*
* @return
*/
public synchronized Environment getEnv() {
return env;
}
/**
* Executes the closure, giving it the supplied arguments. {@code values} may be null, which means that no arguments
* are being sent.
*
* LoopManipulationExceptions will never bubble up past this point, because they are never allowed, so they are
* handled automatically, but other ProgramFlowManipulationExceptions will, . ConfigRuntimeExceptions will also
* bubble up past this, since an execution mechanism may need to do custom handling.
*
* A typical execution will include the following code:
* <pre>
* try {
* closure.execute();
* } catch (ConfigRuntimeException e){
* ConfigRuntimeException.HandleUncaughtException(e);
* } catch (ProgramFlowManipulationException e){
* // Ignored
* }
* </pre>
*
* @param values The values to be passed to the closure
* @throws ConfigRuntimeException If any call inside the closure causes a CRE
* @throws ProgramFlowManipulationException If any ProgramFlowManipulationException is thrown (other than a
* LoopManipulationException) within the closure
* @throws FunctionReturnException If the closure has a return() call in it.
*/
public void execute(Mixed... values) throws ConfigRuntimeException, ProgramFlowManipulationException, FunctionReturnException, CancelCommandException {
if(node == null) {
return;
}
StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("<<closure>>", getTarget()));
try {
Environment environment;
synchronized(this) {
environment = env.clone();
}
if(values != null) {
for(int i = 0; i < names.length; i++) {
String name = names[i];
Mixed value;
try {
value = values[i];
} catch (Exception e) {
value = defaults[i].clone();
}
environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(types[i], name, value, getTarget()));
}
}
boolean hasArgumentsParam = false;
for(String pName : this.names) {
if(pName.equals("@arguments")) {
hasArgumentsParam = true;
break;
}
}
if(!hasArgumentsParam) {
CArray arguments = new CArray(node.getData().getTarget());
if(values != null) {
for(Mixed value : values) {
arguments.push(value, node.getData().getTarget());
}
}
environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, node.getData().getTarget()));
}
ParseTree newNode = new ParseTree(new CFunction("g", getTarget()), node.getFileOptions());
List<ParseTree> children = new ArrayList<ParseTree>();
children.add(node);
newNode.setChildren(children);
try {
MethodScriptCompiler.execute(newNode, environment, null, environment.getEnv(GlobalEnv.class).GetScript());
} catch (LoopManipulationException e) {
//This shouldn't ever happen.
LoopManipulationException lme = ((LoopManipulationException) e);
Target t = lme.getTarget();
ConfigRuntimeException.HandleUncaughtException(ConfigRuntimeException.CreateUncatchableException("A " + lme.getName() + "() bubbled up to the top of"
+ " a closure, which is unexpected behavior.", t), environment);
} catch (FunctionReturnException ex) {
// Check the return type of the closure to see if it matches the defined type
// Normal execution.
Mixed ret = ex.getReturn();
if(!InstanceofUtil.isInstanceof(ret, returnType)) {
throw new CRECastException("Expected closure to return a value of type " + returnType.val()
+ " but a value of type " + ret.typeof() + " was returned instead", ret.getTarget());
}
// Now rethrow it
throw ex;
} catch (CancelCommandException e) {
// die()
} catch (ConfigRuntimeException ex) {
if(ex instanceof AbstractCREException) {
((AbstractCREException) ex).freezeStackTraceElements(stManager);
}
throw ex;
} catch (Throwable t) {
// Not sure. Pop and re-throw.
throw t;
} finally {
stManager.popStackTraceElement();
}
// If we got here, then there was no return type. This is fine, but only for returnType void or auto.
if(!(returnType.equals(Auto.TYPE) || returnType.equals(CVoid.TYPE))) {
throw new CRECastException("Expecting closure to return a value of type " + returnType.val() + ","
+ " but no value was returned.", node.getTarget());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CClosure.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public boolean isDynamic() {
return false;
}
@Override
public String docs() {
return "A closure is a data type that contains executable code. This is similar to a procedure, but the value is first class,"
+ " and can be stored in variables, and executed.";
}
@Override
public Version since() {
return MSVersion.V3_3_1;
}
@Override
public CClassType[] getSuperclasses() {
return new CClassType[]{Mixed.TYPE};
}
@Override
public CClassType[] getInterfaces() {
return CClassType.EMPTY_CLASS_ARRAY;
}
}