/** * @param context unused in this context but required for dispatching * @param indicator unused in this context but required for dispatching */ @SuppressWarnings("unchecked") protected Object _doEvaluate(XNumberLiteral literal, IEvaluationContext context, CancelIndicator indicator) { IResolvedTypes resolvedTypes = typeResolver.resolveTypes(literal); LightweightTypeReference expectedType = resolvedTypes.getExpectedType(literal); Class<? extends Number> type = numberLiterals.getJavaType(literal); if (expectedType != null && expectedType.isSubtypeOf(Number.class)) { try { Class<?> expectedClassType = getJavaType(expectedType.toJavaCompliantTypeReference().getType()); if (expectedClassType.isPrimitive()) { expectedClassType = ReflectionUtil.getObjectType(expectedClassType); } if (Number.class != expectedClassType && Number.class.isAssignableFrom(expectedClassType)) { type = (Class<? extends Number>) expectedClassType; } } catch (ClassNotFoundException e) { } } return numberLiterals.numberValue(literal, type); }
protected Object _doEvaluate(XListLiteral literal, IEvaluationContext context, CancelIndicator indicator) { IResolvedTypes resolveTypes = typeResolver.resolveTypes(literal); LightweightTypeReference type = resolveTypes.getActualType(literal); List<Object> list = newArrayList(); for(XExpression element: literal.getElements()) { if (indicator.isCanceled()) throw new InterpreterCanceledException(); list.add(internalEvaluate(element, context, indicator)); } if(type != null && type.isArray()) { try { LightweightTypeReference componentType = type.getComponentType(); return Conversions.unwrapArray(list, getJavaType(componentType.getType())); } catch (ClassNotFoundException e) { } } return Collections.unmodifiableList(list); }
protected Object _doEvaluate(XForLoopExpression forLoop, IEvaluationContext context, CancelIndicator indicator) { Object iterableOrIterator = internalEvaluate(forLoop.getForExpression(), context, indicator); if (iterableOrIterator == null) return throwNullPointerException(forLoop.getForExpression(), "iterable evaluated to 'null'"); Iterator<?> iter = null; if (iterableOrIterator instanceof Iterable<?>) { iter = ((Iterable<?>) iterableOrIterator).iterator(); } else if (iterableOrIterator.getClass().isArray()) { iter = ((Iterable<?>) Conversions.doWrapArray(iterableOrIterator)).iterator(); } else { return throwClassCastException(forLoop.getForExpression(), iterableOrIterator, java.lang.Iterable.class); } IEvaluationContext forkedContext = context.fork(); QualifiedName paramName = QualifiedName.create(forLoop.getDeclaredParam().getName()); forkedContext.newValue(paramName, null); while (iter.hasNext()) { Object next = iter.next(); forkedContext.assignValue(paramName, next); internalEvaluate(forLoop.getEachExpression(), forkedContext, indicator); } return null; }
protected Object _doEvaluate(XBasicForLoopExpression forLoop, IEvaluationContext context, CancelIndicator indicator) { IEvaluationContext forkedContext = context.fork(); for (XExpression initExpression : forLoop.getInitExpressions()) { internalEvaluate(initExpression, forkedContext, indicator); } XExpression expression = forLoop.getExpression(); Object condition = expression == null ? Boolean.TRUE : internalEvaluate(expression, forkedContext, indicator); while (Boolean.TRUE.equals(condition)) { internalEvaluate(forLoop.getEachExpression(), forkedContext, indicator); for (XExpression updateExpression : forLoop.getUpdateExpressions()) { internalEvaluate(updateExpression, forkedContext, indicator); } condition = expression == null ? Boolean.TRUE : internalEvaluate(expression, forkedContext, indicator); } return null; }
protected Object _doEvaluate(XConstructorCall constructorCall, IEvaluationContext context, CancelIndicator indicator) { JvmConstructor jvmConstructor = constructorCall.getConstructor(); List<Object> arguments = evaluateArgumentExpressions(jvmConstructor, constructorCall.getArguments(), context, indicator); Constructor<?> constructor = javaReflectAccess.getConstructor(jvmConstructor); try { if (constructor == null) throw new NoSuchMethodException("Could not find constructor " + jvmConstructor.getIdentifier()); constructor.setAccessible(true); Object result = constructor.newInstance(arguments.toArray(new Object[arguments.size()])); return result; } catch (InvocationTargetException targetException) { throw new EvaluationException(targetException.getTargetException()); } catch (Exception e) { throw new IllegalStateException("Could not invoke constructor: " + jvmConstructor.getIdentifier(), e); } }
protected Object _assignValueTo(JvmField jvmField, XAbstractFeatureCall assignment, Object value, IEvaluationContext context, CancelIndicator indicator) { Object receiver = getReceiver(assignment, context, indicator); Field field = javaReflectAccess.getField(jvmField); try { if (field == null) { throw new NoSuchFieldException("Could not find field " + jvmField.getIdentifier()); } if (!Modifier.isStatic(field.getModifiers()) && receiver == null) throw new EvaluationException(new NullPointerException("Cannot assign value to field: " + jvmField.getIdentifier() + " on null instance")); JvmTypeReference type = jvmField.getType(); Object coerced = coerceArgumentType(value, type); field.setAccessible(true); field.set(receiver, coerced); return value; } catch (Exception e) { throw new IllegalStateException("Could not access field: " + jvmField.getIdentifier() + " on instance: " + receiver, e); } }
public Object execute(IEvaluationContext evaluationContext) throws ScriptExecutionException { if(xExpression!=null) { try { IEvaluationResult result = interpreter.evaluate(xExpression, evaluationContext, CancelIndicator.NullImpl); if(result==null) { // this can only happen on an InterpreterCancelledException, i.e. NEVER ;-) return null; } if (result.getException() != null) { throw new ScriptExecutionException(result.getException().getMessage(), result.getException()); } return result.getResult(); } catch(Throwable e) { if(e instanceof ScriptExecutionException) { throw (ScriptExecutionException) e; } else { throw new ScriptExecutionException("An error occured during the script execution: " + e.getMessage(), e); } } } else { throw new ScriptExecutionException("Script does not contain any expression"); } }
protected Object internalEvaluate(XExpression expression, IEvaluationContext context, CancelIndicator indicator) throws EvaluationException { if (indicator.isCanceled()) throw new InterpreterCanceledException(); Object result = doEvaluate(expression, context, indicator); final LightweightTypeReference expectedType = typeResolver.resolveTypes(expression).getExpectedType(expression); if(expectedType != null) result = wrapOrUnwrapArray(result, expectedType); return result; }
/** * @param context unused in this context but required for dispatching * @param indicator unused in this context but required for dispatching */ protected Object _doEvaluate(XStringLiteral literal, IEvaluationContext context, CancelIndicator indicator) { LightweightTypeReference type = typeResolver.resolveTypes(literal).getActualType(literal); if (type != null && (type.isType(Character.TYPE) || type.isType(Character.class))) { return literal.getValue().charAt(0); } return literal.getValue(); }
/** * @param context unused in this context but required for dispatching * @param indicator unused in this context but required for dispatching */ protected Object _doEvaluate(XTypeLiteral literal, IEvaluationContext context, CancelIndicator indicator) { if (literal.getType() == null || literal.getType().eIsProxy()) { List<INode> nodesForFeature = NodeModelUtils.findNodesForFeature(literal, XbasePackage.Literals.XTYPE_LITERAL__TYPE); // TODO cleanup if (nodesForFeature.isEmpty()) throw new EvaluationException(new ClassNotFoundException()); throw new EvaluationException(new ClassNotFoundException(nodesForFeature.get(0).getText())); } JvmType type = literal.getType(); Object result = translateJvmTypeToResult(type, literal.getArrayDimensions().size()); return result; }
protected Object _doEvaluate(XClosure closure, IEvaluationContext context, CancelIndicator indicator) { Class<?> functionIntf = null; switch (closure.getFormalParameters().size()) { case 0: functionIntf = getClass(Functions.Function0.class); break; case 1: functionIntf = getClass(Functions.Function1.class); break; case 2: functionIntf = getClass(Functions.Function2.class); break; case 3: functionIntf = getClass(Functions.Function3.class); break; case 4: functionIntf = getClass(Functions.Function4.class); break; case 5: functionIntf = getClass(Functions.Function5.class); break; case 6: functionIntf = getClass(Functions.Function6.class); break; default: throw new IllegalStateException("Closures with more then 6 parameters are not supported."); } ClosureInvocationHandler invocationHandler = new ClosureInvocationHandler(closure, context, this, indicator); Object proxy = Proxy.newProxyInstance(classLoader, new Class<?>[] { functionIntf }, invocationHandler); return proxy; }
protected Object _doEvaluate(XBlockExpression literal, IEvaluationContext context, CancelIndicator indicator) { List<XExpression> expressions = literal.getExpressions(); Object result = null; IEvaluationContext forkedContext = context.fork(); for (int i = 0; i < expressions.size(); i++) { result = internalEvaluate(expressions.get(i), forkedContext, indicator); } return result; }
protected Object _doEvaluate(XIfExpression ifExpression, IEvaluationContext context, CancelIndicator indicator) { Object conditionResult = internalEvaluate(ifExpression.getIf(), context, indicator); if (Boolean.TRUE.equals(conditionResult)) { return internalEvaluate(ifExpression.getThen(), context, indicator); } else { if (ifExpression.getElse() == null) return getDefaultObjectValue(typeResolver.resolveTypes(ifExpression).getActualType(ifExpression)); return internalEvaluate(ifExpression.getElse(), context, indicator); } }
protected Object _doEvaluate(XThrowExpression throwExpression, IEvaluationContext context, CancelIndicator indicator) { Object thrown = internalEvaluate(throwExpression.getExpression(), context, indicator); if (thrown == null) { return throwNullPointerException(throwExpression, "throwable expression evaluated to 'null'"); } if (!(thrown instanceof Throwable)) { return throwClassCastException(throwExpression.getExpression(), thrown, Throwable.class); } throw new EvaluationException((Throwable) thrown); }
protected Object _doEvaluate(XWhileExpression whileLoop, IEvaluationContext context, CancelIndicator indicator) { Object condition = internalEvaluate(whileLoop.getPredicate(), context, indicator); while (Boolean.TRUE.equals(condition)) { internalEvaluate(whileLoop.getBody(), context, indicator); condition = internalEvaluate(whileLoop.getPredicate(), context, indicator); } return null; }
protected IEvaluationResult _doEvaluate(XDoWhileExpression doWhileLoop, IEvaluationContext context, CancelIndicator indicator) { Object condition = null; do { internalEvaluate(doWhileLoop.getBody(), context, indicator); condition = internalEvaluate(doWhileLoop.getPredicate(), context, indicator); } while (Boolean.TRUE.equals(condition)); return null; }
protected Object _doEvaluate(final XMemberFeatureCall featureCall, final IEvaluationContext context, final CancelIndicator indicator) { if (featureCall.isTypeLiteral()) { JvmType type = (JvmType) featureCall.getFeature(); Object result = translateJvmTypeToResult(type, 0); return result; } else { XExpression receiver = getActualReceiver(featureCall); //, featureCall.getFeature(), featureCall.getImplicitReceiver()); Object receiverObj = receiver==null?null:internalEvaluate(receiver, context, indicator); if (featureCall.isNullSafe() && receiverObj==null) { return getDefaultObjectValue(typeResolver.resolveTypes(featureCall).getActualType(featureCall)); } return invokeFeature(featureCall.getFeature(), featureCall, receiverObj, context, indicator); } }
protected Object _doEvaluate(XInstanceOfExpression instanceOf, IEvaluationContext context, CancelIndicator indicator) { Object instance = internalEvaluate(instanceOf.getExpression(), context, indicator); if (instance == null) return Boolean.FALSE; Class<?> expectedType = null; String className = instanceOf.getType().getType().getQualifiedName(); try { expectedType = classFinder.forName(className); } catch (ClassNotFoundException cnfe) { throw new EvaluationException(new NoClassDefFoundError(className)); } return expectedType.isInstance(instance); }
protected Object _doEvaluate(XVariableDeclaration variableDecl, IEvaluationContext context, CancelIndicator indicator) { Object initialValue = null; if (variableDecl.getRight()!=null) { initialValue = internalEvaluate(variableDecl.getRight(), context, indicator); } else { if (services.getPrimitives().isPrimitive(variableDecl.getType())) { Primitive primitiveKind = services.getPrimitives().primitiveKind((JvmPrimitiveType) variableDecl.getType().getType()); switch(primitiveKind) { case Boolean: initialValue = Boolean.FALSE; break; case Char: initialValue = Character.valueOf((char) 0); break; case Double: initialValue = Double.valueOf(0d); break; case Byte: initialValue = Byte.valueOf((byte) 0); break; case Float: initialValue = Float.valueOf(0f); break; case Int: initialValue = Integer.valueOf(0); break; case Long: initialValue = Long.valueOf(0L); break; case Short: initialValue = Short.valueOf((short) 0); break; case Void: throw new IllegalStateException("Void is not a valid variable type."); default: throw new IllegalStateException("Unknown primitive type " + primitiveKind); } } } context.newValue(QualifiedName.create(variableDecl.getName()), initialValue); return null; }
protected Object _doEvaluate(XFeatureCall featureCall, IEvaluationContext context, CancelIndicator indicator) { if (featureCall.isTypeLiteral()) { JvmType type = (JvmType) featureCall.getFeature(); Object result = translateJvmTypeToResult(type, 0); return result; } else { return _doEvaluate((XAbstractFeatureCall) featureCall, context, indicator); } }
protected Object evaluateGetAndAssign(XAbstractFeatureCall featureCall, IEvaluationContext context, CancelIndicator indicator) { XAbstractFeatureCall operand = (XAbstractFeatureCall) featureCall.getActualArguments().get(0); Object originalValue = internalEvaluate(operand, context, indicator); Object value = applyGetAndAssignOperator(originalValue, featureCall.getConcreteSyntaxFeatureName()); assignValueTo(operand.getFeature(), featureCall, value, context, indicator); return originalValue; }
protected Object invokeFeature(JvmIdentifiableElement feature, XAbstractFeatureCall featureCall, Object receiverObj, IEvaluationContext context, CancelIndicator indicator) { if (feature instanceof JvmField) { return _invokeFeature((JvmField)feature, featureCall, receiverObj, context, indicator); } else if (feature instanceof JvmOperation) { return _invokeFeature((JvmOperation)feature, featureCall, receiverObj, context, indicator); } else if (feature != null) { return _invokeFeature(feature, featureCall, receiverObj, context, indicator); } else { throw new NullPointerException("Feature was null"); } }
/** * @param featureCall unused in this context but required for dispatching * @param indicator unused in this context but required for dispatching */ protected Object _invokeFeature(JvmIdentifiableElement identifiable, XAbstractFeatureCall featureCall, Object receiver, IEvaluationContext context, CancelIndicator indicator) { if (receiver != null) throw new IllegalStateException("feature was simple feature call but got receiver instead of null. Receiver: " + receiver); String localVarName = featureNameProvider.getSimpleName(identifiable); Object value = context.getValue(QualifiedName.create(localVarName)); return value; }
protected Object _doEvaluate(XAssignment assignment, IEvaluationContext context, CancelIndicator indicator) { JvmIdentifiableElement feature = assignment.getFeature(); if (feature instanceof JvmOperation && ((JvmOperation) feature).isVarArgs()) { return _doEvaluate((XAbstractFeatureCall) assignment, context, indicator); } Object value = internalEvaluate(assignment.getValue(), context, indicator); Object assign = assignValueTo(feature, assignment, value, context, indicator); return assign; }
protected Object assignValueTo(JvmIdentifiableElement feature, XAbstractFeatureCall assignment, Object value, IEvaluationContext context, CancelIndicator indicator) { if (feature instanceof XVariableDeclaration) { return _assignValueTo((XVariableDeclaration) feature, assignment, value, context, indicator); } else if (feature instanceof JvmField) { return _assignValueTo((JvmField) feature, assignment, value, context, indicator); } else if (feature instanceof JvmOperation) { return _assignValueTo((JvmOperation) feature, assignment, value, context, indicator); } else { throw new IllegalArgumentException("Couldn't invoke 'assignValueTo' for feature "+feature+""); } }
/** * @param assignment unused in this context but required for dispatching * @param indicator unused in this context but required for dispatching */ protected Object _assignValueTo(XVariableDeclaration variable, XAbstractFeatureCall assignment, Object value, IEvaluationContext context, CancelIndicator indicator) { if (variable.getType() != null) { JvmTypeReference type = variable.getType(); Object coerced = coerceArgumentType(value, type); context.assignValue(QualifiedName.create(variable.getName()), coerced); } else { context.assignValue(QualifiedName.create(variable.getName()), value); } return value; }
@Override protected Object doInvoke(Method method, Object[] args) throws Throwable { IEvaluationContext forkedContext = context.fork(); if (args != null) { initializeClosureParameters(forkedContext, args); } IEvaluationResult result = interpreter.evaluate(closure.getExpression(), forkedContext, indicator); if (indicator.isCanceled()) throw new InterpreterCanceledException(); if (result.getException() != null) throw result.getException(); return result.getResult(); }
protected void initializeClosureParameters(IEvaluationContext context, Object[] args) { if (args.length != closure.getFormalParameters().size()) throw new IllegalStateException("Number of arguments did not match. Expected: " + closure.getFormalParameters().size() + " but was: " + args.length); int i = 0; for(JvmFormalParameter param: closure.getFormalParameters()) { context.newValue(QualifiedName.create(param.getName()), args[i]); i++; } }
protected Object _featureCallJvmIdentifyableElement(JvmIdentifiableElement identifiable, XFeatureCall featureCall, Object receiver, IEvaluationContext context, CancelIndicator indicator) { Object value = super._featureCallJvmIdentifyableElement(identifiable, featureCall, receiver, context, indicator); if(value==null && receiver==null) { for(Type type : stateAndCommandProvider.getAllTypes()) { if(type.toString().equals(featureCall.toString())) { return type; } } value = getItem(featureCall.toString()); } return value; }
protected Object internalFeatureCallDispatch(XAbstractFeatureCall featureCall, Object receiverObj, IEvaluationContext context, CancelIndicator indicator) { if(featureCall.getFeature().eIsProxy()) { throw new RuntimeException("The name '" + featureCall.toString() + "' cannot be resolved to an item or type."); } return featureCallDispatcher.invoke(featureCall.getFeature(), featureCall, receiverObj, context, indicator); }
/** * Retrieves the evaluation context (= set of variables) for a rule. The context is shared with all rules in the same model (= rule file). * * @param rule the rule to get the context for * @return the evaluation context */ public static synchronized IEvaluationContext getContext(Rule rule) { RuleModel ruleModel = (RuleModel) rule.eContainer(); // check if a context already exists on the resource for(Adapter adapter : ruleModel.eAdapters()) { if(adapter instanceof RuleContextAdapter) { return ((RuleContextAdapter) adapter).getContext(); } } // no evaluation context found, so create a new one IEvaluationContext evaluationContext = contextProvider.get(); for(XExpression expr : ruleModel.getVariables()) { if (expr instanceof XVariableDeclaration) { XVariableDeclaration var = (XVariableDeclaration) expr; try { Object initialValue = var.getRight()==null ? null : scriptEngine.newScriptFromXExpression(var.getRight()).execute(); evaluationContext.newValue(QualifiedName.create(var.getName()), initialValue); } catch (ScriptExecutionException e) { logger.warn("Variable '{}' on rule file '{}' cannot be initialized with value '{}': {}", new String[] { var.getName(), ruleModel.eResource().getURI().path(), var.getRight().toString(), e.getMessage() }); } } } ruleModel.eAdapters().add(new RuleContextAdapter(evaluationContext)); return evaluationContext; }
public Class<? extends IEvaluationContext> bindIEvaluationContext() { return DefaultEvaluationContext.class; }
public XbaseInterpreter(Provider<IEvaluationContext> contextProvider, JavaReflectAccess javaReflectAccess, ClassLoader loader) { this.contextProvider = contextProvider; this.javaReflectAccess = javaReflectAccess; setClassLoader(loader); }
protected IEvaluationContext createContext() { return contextProvider.get(); }
/** * don't call this directly. Always call evaluate() internalEvaluate() */ protected Object doEvaluate(XExpression expression, IEvaluationContext context, CancelIndicator indicator) { if (expression instanceof XAssignment) { return _doEvaluate((XAssignment)expression, context, indicator); } else if (expression instanceof XDoWhileExpression) { return _doEvaluate((XDoWhileExpression)expression, context, indicator); } else if (expression instanceof XMemberFeatureCall) { return _doEvaluate((XMemberFeatureCall)expression, context, indicator); } else if (expression instanceof XWhileExpression) { return _doEvaluate((XWhileExpression)expression, context, indicator); } else if (expression instanceof XFeatureCall) { return _doEvaluate((XFeatureCall)expression, context, indicator); } else if (expression instanceof XAbstractFeatureCall) { return _doEvaluate((XAbstractFeatureCall)expression, context, indicator); } else if (expression instanceof XBlockExpression) { return _doEvaluate((XBlockExpression)expression, context, indicator); } else if (expression instanceof XSynchronizedExpression) { return _doEvaluate((XSynchronizedExpression)expression, context, indicator); } else if (expression instanceof XBooleanLiteral) { return _doEvaluate((XBooleanLiteral)expression, context, indicator); } else if (expression instanceof XCastedExpression) { return _doEvaluate((XCastedExpression)expression, context, indicator); } else if (expression instanceof XClosure) { return _doEvaluate((XClosure)expression, context, indicator); } else if (expression instanceof XConstructorCall) { return _doEvaluate((XConstructorCall)expression, context, indicator); } else if (expression instanceof XForLoopExpression) { return _doEvaluate((XForLoopExpression)expression, context, indicator); } else if (expression instanceof XBasicForLoopExpression) { return _doEvaluate((XBasicForLoopExpression)expression, context, indicator); } else if (expression instanceof XIfExpression) { return _doEvaluate((XIfExpression)expression, context, indicator); } else if (expression instanceof XInstanceOfExpression) { return _doEvaluate((XInstanceOfExpression)expression, context, indicator); } else if (expression instanceof XNullLiteral) { return _doEvaluate((XNullLiteral)expression, context, indicator); } else if (expression instanceof XNumberLiteral) { return _doEvaluate((XNumberLiteral)expression, context, indicator); } else if (expression instanceof XReturnExpression) { return _doEvaluate((XReturnExpression)expression, context, indicator); } else if (expression instanceof XStringLiteral) { return _doEvaluate((XStringLiteral)expression, context, indicator); } else if (expression instanceof XSwitchExpression) { return _doEvaluate((XSwitchExpression)expression, context, indicator); } else if (expression instanceof XThrowExpression) { return _doEvaluate((XThrowExpression)expression, context, indicator); } else if (expression instanceof XTryCatchFinallyExpression) { return _doEvaluate((XTryCatchFinallyExpression)expression, context, indicator); } else if (expression instanceof XTypeLiteral) { return _doEvaluate((XTypeLiteral)expression, context, indicator); } else if (expression instanceof XVariableDeclaration) { return _doEvaluate((XVariableDeclaration)expression, context, indicator); } else if (expression instanceof XListLiteral) { return _doEvaluate((XListLiteral)expression, context, indicator); } else if (expression instanceof XSetLiteral) { return _doEvaluate((XSetLiteral)expression, context, indicator); } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(expression, context, indicator).toString()); } }
protected Object _doEvaluate(XReturnExpression returnExpr, IEvaluationContext context, CancelIndicator indicator) { Object returnValue = internalEvaluate(returnExpr.getExpression(), context, indicator); throw new ReturnValue(returnValue); }
protected Object _doEvaluate(XSynchronizedExpression expression, IEvaluationContext context, CancelIndicator indicator) { internalEvaluate(expression.getParam(), context, indicator); return internalEvaluate(expression.getExpression(), context, indicator); }
protected Object _invokeFeature(JvmOperation operation, XAbstractFeatureCall featureCall, Object receiver, IEvaluationContext context, CancelIndicator indicator) { List<XExpression> operationArguments = getActualArguments(featureCall); List<Object> argumentValues = evaluateArgumentExpressions(operation, operationArguments, context, indicator); return invokeOperation(operation, receiver, argumentValues, context, indicator); }
protected Object getReceiver(XAbstractFeatureCall assignment, IEvaluationContext context, CancelIndicator indicator) { XExpression receiver = getActualReceiver(assignment); Object result = receiver == null ? null : internalEvaluate(receiver, context, indicator); return result; }
public DefaultEvaluationContext(IEvaluationContext parent) { this.parent = parent; }