Java Code Examples for org.eclipse.xtext.xbase.interpreter.IEvaluationContext#newValue()

The following examples show how to use org.eclipse.xtext.xbase.interpreter.IEvaluationContext#newValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 3
Source File: ClosureInvocationHandler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
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++;
	}
}
 
Example 4
Source File: RuleContextHelper.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Retrieves the evaluation context (= set of variables) for a ruleModel. The context is shared with all rules in
 * the
 * same model (= rule file).
 *
 * @param ruleModel the ruleModel to get the context for
 * @return the evaluation context
 */
public static synchronized IEvaluationContext getContext(RuleModel ruleModel) {
    Logger logger = LoggerFactory.getLogger(RuleContextHelper.class);
    Injector injector = RulesStandaloneSetup.getInjector();

    // check if a context already exists on the resource
    for (Adapter adapter : ruleModel.eAdapters()) {
        if (adapter instanceof RuleContextAdapter) {
            return ((RuleContextAdapter) adapter).getContext();
        }
    }
    Provider<@NonNull IEvaluationContext> contextProvider = injector.getProvider(IEvaluationContext.class);
    // no evaluation context found, so create a new one
    ScriptEngine scriptEngine = injector.getInstance(ScriptEngine.class);
    IEvaluationContext evaluationContext = contextProvider.get();
    for (VariableDeclaration var : ruleModel.getVariables()) {
        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 '{}': {}", var.getName(),
                    ruleModel.eResource().getURI().path(), var.getRight(), e.getMessage());
        }
    }
    ruleModel.eAdapters().add(new RuleContextAdapter(evaluationContext));
    return evaluationContext;
}
 
Example 5
Source File: RuleContextHelper.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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, Injector injector) {
    Logger logger = LoggerFactory.getLogger(RuleContextHelper.class);
    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();
        }
    }
    Provider<IEvaluationContext> contextProvider = injector.getProvider(IEvaluationContext.class);
    // no evaluation context found, so create a new one
    ScriptEngine scriptEngine = injector.getInstance(ScriptEngine.class);
    if (scriptEngine != null) {
        IEvaluationContext evaluationContext = contextProvider.get();
        for (VariableDeclaration var : ruleModel.getVariables()) {
            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 Object[] { var.getName(), ruleModel.eResource().getURI().path(),
                                var.getRight().toString(), e.getMessage() });
            }
        }
        ruleModel.eAdapters().add(new RuleContextAdapter(evaluationContext));
        return evaluationContext;
    } else {
        logger.debug("Rule variables of rule {} cannot be evaluated as no scriptengine is available!",
                ruleModel.eResource().getURI().path());
        return contextProvider.get();
    }
}
 
Example 6
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected Object _doEvaluate(XTryCatchFinallyExpression tryCatchFinally, 
		IEvaluationContext context,
		CancelIndicator indicator) {
	Object result = null;
	ReturnValue returnValue = null;
	Map<String, Boolean> resIsInit = new HashMap<String, Boolean>();
	List<XVariableDeclaration> resources = tryCatchFinally.getResources();
	List<EvaluationException> caughtExceptions = newArrayList();
	// Resources
	try {
		for (XVariableDeclaration res : resources) {
			resIsInit.put(res.getName(), false);
			result = internalEvaluate(res, context, indicator);
			// Remember for automatic close which resources are initialized
			resIsInit.put(res.getName(), true);
		}
		// Expression Body
		result = internalEvaluate(tryCatchFinally.getExpression(), context, indicator);

	} catch (ReturnValue value) {
		// Keep thrown return value in mind until resources are closed
		returnValue = value;
	} catch (EvaluationException evaluationException) {
		Throwable cause = evaluationException.getCause();
		boolean caught = false;
		// Catch Clauses
		for (XCatchClause catchClause : tryCatchFinally.getCatchClauses()) {
			JvmFormalParameter exception = catchClause.getDeclaredParam();
			JvmTypeReference catchParameterType = exception.getParameterType();
			if (!isInstanceoOf(cause, catchParameterType)) {
				continue;
			}
			IEvaluationContext forked = context.fork();
			forked.newValue(QualifiedName.create(exception.getName()), cause);
			result = internalEvaluate(catchClause.getExpression(), forked, indicator);
			caught = true;
			break;
		}
		// Save uncaught exception
		if(!caught) caughtExceptions.add(evaluationException);
	}

	// finally expressions ...
	// ... given
	if (tryCatchFinally.getFinallyExpression() != null) {
		try {
			internalEvaluate(tryCatchFinally.getFinallyExpression(), context, indicator);
		} catch (EvaluationException e) {
			throw new EvaluationException(new FinallyDidNotCompleteException(e));
		}
	}
	// ... prompted by try with resources (automatic close)
	if (!resources.isEmpty()) {
		for (int i = resources.size() - 1; i >= 0; i--) {
			XVariableDeclaration resource = resources.get(i);
			// Only close resources that are instantiated (= avoid
			// NullPointerException)
			if (resIsInit.get(resource.getName())) {
				// Find close method for resource
				JvmOperation close = findCloseMethod(resource);
				// Invoke close on resource
				if (close != null) {
					// Invoking the close method might throw
					// a EvaluationException. Hence, we collect those thrown
					// EvaluationExceptions and propagate them later on.
					try {
						invokeOperation(close,
								context.getValue(QualifiedName.create(resource.getSimpleName())),
								Collections.emptyList());
					} catch (EvaluationException t) {
						caughtExceptions.add(t);
					}
				}
			}
		}
	}
	
	// Throw caught exceptions if there are any
	if (!caughtExceptions.isEmpty()) throw caughtExceptions.get(0);
				
	// throw return value from expression block after resources are closed
	if (returnValue != null)
		throw returnValue;

	return result;
}