-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathJavaMethod.java
More file actions
362 lines (309 loc) · 11.8 KB
/
JavaMethod.java
File metadata and controls
362 lines (309 loc) · 11.8 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
357
358
359
360
361
362
/*******************************************************************************
* Copyright (c) 2009-2013 CWI
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI
* * Tijs van der Storm - Tijs.van.der.Storm@cwi.nl
* * Emilie Balland - (CWI)
* * Paul Klint - Paul.Klint@cwi.nl - CWI
* * Mark Hills - Mark.Hills@cwi.nl (CWI)
* * Arnold Lankamp - Arnold.Lankamp@cwi.nl
* * Anya Helene Bagge - anya@ii.uib.no (UiB)
*******************************************************************************/
package org.rascalmpl.interpreter.result;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.rascalmpl.ast.Expression;
import org.rascalmpl.ast.FunctionDeclaration;
import org.rascalmpl.ast.Tag;
import org.rascalmpl.exceptions.ImplementationError;
import org.rascalmpl.exceptions.RuntimeExceptionFactory;
import org.rascalmpl.exceptions.StackTrace;
import org.rascalmpl.exceptions.Throw;
import org.rascalmpl.interpreter.IEvaluator;
import org.rascalmpl.interpreter.control_exceptions.MatchFailed;
import org.rascalmpl.interpreter.env.Environment;
import org.rascalmpl.interpreter.staticErrors.StaticError;
import org.rascalmpl.interpreter.staticErrors.UnexpectedType;
import org.rascalmpl.interpreter.utils.JavaBridge;
import org.rascalmpl.interpreter.utils.Names;
import org.rascalmpl.uri.URIUtil;
import io.usethesource.vallang.ISourceLocation;
import io.usethesource.vallang.IValue;
import io.usethesource.vallang.exceptions.FactTypeUseException;
import io.usethesource.vallang.type.Type;
public class JavaMethod extends NamedFunction {
private final Object instance;
private final Method method;
private final boolean hasReflectiveAccess;
private final JavaBridge javaBridge;
private final Type formals;
public JavaMethod(IEvaluator<Result<IValue>> eval, FunctionDeclaration func, boolean varargs, Environment env, JavaBridge javaBridge){
this(eval,
func.getSignature().typeOf(env, eval, false),
func.getSignature().typeOf(env, eval, false).instantiate(env.getDynamicTypeBindings()),
func,
hasTestMod(func.getSignature()),
isDefault(func),
varargs,
env,
javaBridge
);
}
@Override
public Type getFormals() {
return this.formals;
}
/*
* This one is to be called by cloneInto only, to avoid
* looking into the environment again for obtaining the type.
* (cloneInto is called when a moduleEnv is extended, so it
* might not be finished yet, and hence not have all the
* require types.
*/
private JavaMethod(IEvaluator<Result<IValue>> eval, Type staticType, Type dynamicType, FunctionDeclaration func, boolean varargs, boolean isTest, boolean isDefault, Environment env, JavaBridge javaBridge){
super(func, eval, staticType, dynamicType, getFormals(func), Names.name(func.getSignature().getName()), isDefault, isTest, varargs, env);
this.javaBridge = javaBridge;
this.hasReflectiveAccess = hasReflectiveAccess(func);
this.instance = javaBridge.getJavaClassInstance(func, eval.getMonitor(), env.getStore(), eval.getOutPrinter(), eval.getErrorPrinter(), eval.getInput(), eval);
this.method = javaBridge.lookupJavaMethod(eval, func, env, hasReflectiveAccess);
this.formals = calculateFormals(func, staticType);
}
private static Type calculateFormals(FunctionDeclaration func, Type ft) {
List<Expression> formals = func.getSignature().getParameters().getFormals().getFormals();
int arity = formals.size();
Type[] types = new Type[arity];
String[] labels = new String[arity];
for (int i = 0; i < arity; i++) {
types[i] = ft.getFieldType(i);
assert formals.get(i).isTypedVariable(); // Java methods only have normal parameters as in `int i, int j`
labels[i] = Names.name(formals.get(i).getName());
}
return TF.tupleType(types, labels);
}
@Override
public JavaMethod cloneInto(Environment env) {
return new JavaMethod(getEval(), getFunctionType(), getType(), (FunctionDeclaration)getAst(), isDefault, isTest, hasVarArgs, env, javaBridge);
}
@Override
public boolean isStatic() {
return true;
}
private boolean hasReflectiveAccess(FunctionDeclaration func) {
for (Tag tag : func.getTags().getTags()) {
if (Names.name(tag.getName()).equals("reflect")) {
return true;
}
}
return false;
}
@Override
public Result<IValue> call(Type[] actualStaticTypes, IValue[] actuals, Map<String, IValue> keyArgValues) {
Result<IValue> resultValue = getMemoizedResult(actuals, keyArgValues);
if (resultValue != null) {
return resultValue;
}
if (hasVarArgs) {
actuals = computeVarArgsActuals(actuals, formals);
actualStaticTypes = computeVarArgsStaticTypes(actualStaticTypes);
}
if (actualStaticTypes.length != formals.getArity()) {
throw new MatchFailed();
}
// check parameters are a subtype
for (int i = 0; i < actualStaticTypes.length; i++) {
if (!actualStaticTypes[i].isSubtypeOf(formals.getFieldType(i))
&& !actuals[i].getType().isSubtypeOf(formals.getFieldType(i))) {
throw new MatchFailed();
}
}
Object[] oActuals = addKeywordActuals(actuals, formals, keyArgValues);
if (hasReflectiveAccess) {
oActuals = addCtxActual(oActuals);
}
if (eval.getCallTracing()) {
printStartTrace(actuals);
}
Environment old = ctx.getCurrentEnvt();
try {
ctx.pushEnv(getName());
Environment env = ctx.getCurrentEnvt();
Map<Type, Type> renamings = Collections.emptyMap();
if (formals.isOpen() || anyOpen(actualStaticTypes)) {
renamings = fastBindTypeParameters(actualStaticTypes, actuals, env);
}
IValue result = invoke(oActuals);
Type resultType = getReturnType().instantiate(env.getStaticTypeBindings());
resultType = unrenameType(renamings, resultType);
resultValue = ResultFactory.makeResult(resultType, result, eval);
resultValue = storeMemoizedResult(actuals, keyArgValues, resultValue);
printEndTrace(resultValue.value);
if (!getReturnType().isBottom() && getReturnType().instantiate(env.getStaticTypeBindings()).isBottom()) {
// type parameterized functions are not allowed to return void,
// so if they do not throw an exception, we now do so automatically
throw new MatchFailed();
}
return resultValue;
}
catch (Throwable e) {
printExcept(e);
throw e;
}
finally {
if (eval.getCallTracing()) {
eval.decCallNesting();
}
ctx.unwind(old);
}
}
private Map<Type, Type> fastBindTypeParameters(Type[] actualStaticTypes, IValue[] actuals, Environment env) {
try {
Map<Type, Type> renamings;
if (anyOpen(actualStaticTypes)) {
// we have to make the environment hygenic now, because the caller scope
// may have the same type variable names as the current scope
renamings = new HashMap<>();
actualStaticTypes = fastRenameType(actualStaticTypes, renamings, env.getCreatorLocation());
}
else {
renamings = Collections.emptyMap();
}
try {
boolean matched = true;
Map<Type, Type> staticBindings = new HashMap<>();
// we have to go reverse since we infer from right to left
for (int i = actuals.length -1; i >= 0; i--) {
matched &= formals.getFieldType(i).match(actualStaticTypes[i], staticBindings);
}
if (matched) {
env.storeStaticTypeBindings(staticBindings);
}
} catch (FactTypeUseException e) {
// this can happen if static types collide
}
return renamings;
}
catch (FactTypeUseException e) {
throw new UnexpectedType(formals, TF.tupleType(actualStaticTypes), ast);
}
}
private Type[] fastRenameType(Type[] actualStaticTypes, Map<Type, Type> renamings, ISourceLocation uniquePrefix) {
var result = new Type[actualStaticTypes.length];
for (int i = 0; i < result.length; i++) {
result[i] = renameType(actualStaticTypes[i], renamings, uniquePrefix);
}
return result;
}
private boolean anyOpen(Type[] types) {
for (var t: types) {
if (t.isOpen()) {
return true;
}
}
return false;
}
private Type[] computeVarArgsStaticTypes(Type[] actualStaticTypes) {
int arity = formals.getArity();
if (arity == 0) {
return actualStaticTypes;
}
if (arity == actualStaticTypes.length) {
var lastType = actualStaticTypes[arity - 1];
if (lastType.isList() && lastType.isSubtypeOf(formals.getFieldType(arity - 1))) {
// already a list
return actualStaticTypes;
}
}
var result = Arrays.copyOf(actualStaticTypes, arity);
Type lub = TF.voidType();
for (int i = arity - 1; i < actualStaticTypes.length; i++) {
lub = lub.lub(actualStaticTypes[i]);
}
result[arity - 1] = TF.listType(lub);
return result;
}
private Object[] addCtxActual(Object[] oActuals) {
Object[] newActuals = new Object[oActuals.length + 1];
System.arraycopy(oActuals, 0, newActuals, 0, oActuals.length);
newActuals[oActuals.length] = ctx;
return newActuals;
}
protected Object[] addKeywordActuals(Object[] oldActuals, Type formals, Map<String, IValue> keyArgValues) {
if (!getFunctionType().hasKeywordParameters()) {
return oldActuals;
}
Environment env = new Environment(declarationEnvironment, URIUtil.rootLocation("initializer"), "keyword parameter initializer");
Environment old = ctx.getCurrentEnvt();
try {
// we set up an environment to hold the positional parameter values
ctx.setCurrentEnvt(env);
for (int i = 0; i < formals.getArity(); i++) {
String fieldName = formals.getFieldName(i);
Type fieldType = formals.getFieldType(i);
env.declareVariable(fieldType, fieldName);
env.storeLocalVariable(fieldName, ResultFactory.makeResult(fieldType, (IValue) oldActuals[i], ctx));
}
// then we initialize the keyword parameters in this environment
Type kwType = getFunctionType().getKeywordParameterTypes();
int amountOfKWArguments = kwType.getArity();
Object[] newActuals = new Object[oldActuals.length + amountOfKWArguments];
System.arraycopy(oldActuals, 0, newActuals, 0, oldActuals.length);
bindKeywordArgs(keyArgValues);
// then we add the resulting values in order to the actual parameter array for the Java method
for (int i = 0; i < amountOfKWArguments; i++) {
newActuals[oldActuals.length + i] = env.getFrameVariable(kwType.getFieldName(i)).getValue();
}
return newActuals;
}
finally {
ctx.setCurrentEnvt(old);
}
}
public IValue invoke(Object[] oActuals) {
try {
return (IValue) method.invoke(instance, oActuals);
}
catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
if (targetException instanceof Throw) {
Throw th = (Throw) targetException;
StackTrace trace = new StackTrace();
trace.addAll(th.getTrace());
ISourceLocation loc = th.getLocation();
if (loc == null || loc.getScheme().equals("TODO")) {
loc = getAst().getLocation();
}
trace.add(loc, null);
th.setLocation(loc);
trace.addAll(eval.getStackTrace());
th.setTrace(trace.freeze());
throw th;
}
else if (targetException instanceof StaticError) {
throw (StaticError) targetException;
}
else if (targetException instanceof ImplementationError) {
throw (ImplementationError) targetException;
}
if (ctx.getConfiguration().printErrors()) {
targetException.printStackTrace();
}
throw RuntimeExceptionFactory.javaException(e.getTargetException(), getAst(), eval.getStackTrace());
}
catch (Throwable e) {
if(ctx.getConfiguration().printErrors()){
e.printStackTrace();
}
throw RuntimeExceptionFactory.javaException(e, getAst(), eval.getStackTrace());
}
}
}