Java Code Examples for org.eclipse.xtext.xbase.XBlockExpression#getExpressions()

The following examples show how to use org.eclipse.xtext.xbase.XBlockExpression#getExpressions() . 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: SARLOperationHelper.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Test if the given expression has side effects.
 *
 * @param expression the expression.
 * @param context the list of context expressions.
 * @return {@code true} if the expression has side effects.
 */
protected Boolean _hasSideEffects(XBlockExpression expression, ISideEffectContext context) {
	final List<XExpression> exprs = expression.getExpressions();
	if (exprs != null && !exprs.isEmpty()) {
		context.open();
		try {
			for (final XExpression ex : exprs) {
				if (hasSideEffects(ex, context)) {
					return true;
				}
			}
		} finally {
			context.close();
		}
	}
	return false;
}
 
Example 2
Source File: TypeConvertingCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * On Java-level the any-type is represented as java.lang.Object as there is no subtype of everything (i.e. type for null).
 * So, when the values are used we need to manually cast them to whatever is expected.
 * 
 *  This method tells us whether such a cast is needed.
 */
private boolean isToBeCastedAnyType(LightweightTypeReference actualType, XExpression obj, ITreeAppendable appendable) {
	if (actualType instanceof AnyTypeReference) {
		if (getReferenceName(obj, appendable) != null)
			return true;
		else if (obj instanceof XBlockExpression) {
			XBlockExpression blockExpression = (XBlockExpression) obj;
			EList<XExpression> expressions = blockExpression.getExpressions();
			if (expressions.isEmpty())
				return false;
			if (expressions.size() > 1)
				return true;
			XExpression last = expressions.get(0);
			return isToBeCastedAnyType(actualType, last, appendable);
		}
	}
	return false;
}
 
Example 3
Source File: SARLEarlyExitValidator.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc}.
 *
 * <p>This function is overriden for:<ul>
 * <li>The XAbstractFeatureCall statements are not considered as potential early exit causes.
 *     in the super function. We need to mark the dead code for the XAbstractFeatureCall statements
 *     which refer to a function with the {@link EarlyExit} annotation.</li>
 * <li>Mark as dead the code after a "break" statement.</li>
 * </ul>
 */
@Override
@Check
public void checkDeadCode(XBlockExpression block) {
	final EList<XExpression> expressions = block.getExpressions();
	final int size = expressions.size();
	for (int i = 0; i < size - 1; ++i) {
		final XExpression expression = expressions.get(i);
		if (this.earlyExitComputer.isEarlyExit(expression)) {
			if (expression instanceof XAbstractFeatureCall) {
				if (this.earlyExitComputer.isEarlyExitAnnotatedElement(
						((XAbstractFeatureCall) expression).getFeature())) {
					markAsDeadCode(expressions.get(i + 1));
				}
			} else {
				// XAbstractFeatureCall does already a decent job for its argument lists
				// no additional error necessary
				markAsDeadCode(expressions.get(i + 1));
			}
			return;
		} else if (this.earlyExitComputer.isEarlyExitLoop(expression)) {
			markAsDeadCode(expressions.get(i + 1));
		}
	}
}
 
Example 4
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean bracesAreAddedByOuterStructure(XExpression expression) {
	EObject container = expression.eContainer();
	if (container instanceof XTryCatchFinallyExpression 
			|| container instanceof XIfExpression
			|| container instanceof XClosure
			|| container instanceof XSynchronizedExpression) {
		return true;
	}
	if (container instanceof XBlockExpression) {
		XBlockExpression blockExpression = (XBlockExpression) container;
		EList<XExpression> expressions = blockExpression.getExpressions();
		if (expressions.size() == 1 && expressions.get(0) == expression) {
			return bracesAreAddedByOuterStructure(blockExpression);
		}
	}
	if (!(container instanceof XExpression)) {
		return true;
	}
	return false;
}
 
Example 5
Source File: AbstractXbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void compileWithJvmConstructorCall(XBlockExpression obj, ITreeAppendable apendable) {
	EList<XExpression> expressions = obj.getExpressions();
	internalToJavaStatement(expressions.get(0), apendable.trace(obj, false), false);
	if (expressions.size() == 1) {
		return;
	}
	
	apendable.newLine().append("try {").increaseIndentation();
	
	ITreeAppendable b = apendable.trace(obj, false);
	for (int i = 1; i < expressions.size(); i++) {
		XExpression ex = expressions.get(i);
		internalToJavaStatement(ex, b, false);
	}
	
	generateCheckedExceptionHandling(apendable);
}
 
Example 6
Source File: AbstractXbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean hasJvmConstructorCall(XExpression obj) {
	if (!(obj instanceof XBlockExpression)) {
		return false;
	}
	XBlockExpression blockExpression = (XBlockExpression) obj;
	EList<XExpression> expressions = blockExpression.getExpressions();
	if (expressions.isEmpty()) {
		return false;
	}
	XExpression expr = expressions.get(0);
	if (!(expr instanceof XFeatureCall)) {
		return false;
	}
	XFeatureCall featureCall = (XFeatureCall) expr;
	return featureCall.getFeature() instanceof JvmConstructor;
}
 
Example 7
Source File: LinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testExtensionMethodCall_10() throws Exception {
	XtendClass clazz = clazz("" +
			"class C {" +
			"  def m() {\n" + 
			"    ''.m('', '', '')\n" +
			"    ''.m\n" +
			"    this.m('')\n" +
			"  }\n" +
			"  def void m(String s, String... s2) {" +
			"  }" +
			"}");
	XtendFunction func = (XtendFunction) clazz.getMembers().get(0);
	XBlockExpression block = (XBlockExpression) func.getExpression();
	for(XExpression element: block.getExpressions()) {
		XMemberFeatureCall call = (XMemberFeatureCall) element;
		assertFalse(call.getFeature().eIsProxy());
		assertEquals("C.m(java.lang.String,java.lang.String[])", call.getFeature().getIdentifier());
	}
}
 
Example 8
Source File: LinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testBug426788() throws Exception {
	XtendFile file = file("class Bug {\n" + 
			"  def <T extends Object> void m(T t) {}\n" + 
			"  def void m(CharSequence t) {}\n" + 
			"  def void n(Iterable<String> it) {\n" + 
			"    m(it.head)           \n" + 
			"    m(it.iterator.next)  \n" + 
			"    m(\"\")              \n" + 
			"  }\n" + 
			"}");
	XtendClass c = (XtendClass) file.getXtendTypes().get(0);
	XtendFunction n = (XtendFunction) c.getMembers().get(2);
	XBlockExpression body = (XBlockExpression) n.getExpression();
	for(XExpression featureCall: body.getExpressions()) {
		XFeatureCall casted = (XFeatureCall) featureCall;
		JvmIdentifiableElement method = casted.getFeature();
		assertEquals("Bug.m(java.lang.CharSequence)", method.getIdentifier());
	}
}
 
Example 9
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: PyExpressionGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Generate the given object.
 *
 * @param block the block expression.
 * @param it the target for the generated content.
 * @param context the context.
 * @return the last expression in the block or {@code null}.
 */
protected XExpression _generate(XBlockExpression block, IAppendable it, IExtraLanguageGeneratorContext context) {
	XExpression last = block;
	if (block.getExpressions().isEmpty()) {
		it.append("pass"); //$NON-NLS-1$
	} else {
		it.openScope();
		if (context.getExpectedExpressionType() == null) {
			boolean first = true;
			for (final XExpression expression : block.getExpressions()) {
				if (first) {
					first = false;
				} else {
					it.newLine();
				}
				last = generate(expression, it, context);
			}
		} else {
			final List<XExpression> exprs = block.getExpressions();
			if (!exprs.isEmpty()) {
				for (int i = 0; i < exprs.size() - 1; ++i) {
					if (i > 0) {
						it.newLine();
					}
					last = generate(exprs.get(i), it, context);
				}
				last = generate(exprs.get(exprs.size() - 1), context.getExpectedExpressionType(), it, context);
			}
		}
		it.closeScope();
	}
	return last;
}
 
Example 11
Source File: SARLEarlyExitValidator.java    From sarl with Apache License 2.0 5 votes vote down vote up
private boolean markAsDeadCode(XExpression expression) {
	if (expression instanceof XBlockExpression) {
		final XBlockExpression block = (XBlockExpression) expression;
		final EList<XExpression> expressions = block.getExpressions();
		if (!expressions.isEmpty()) {
			markAsDeadCode(expressions.get(0));
			return true;
		}
	}
	if (expression != null) {
		error(Messages.SARLEarlyExitValidator_0, expression, null, IssueCodes.UNREACHABLE_CODE); //$NON-NLS-1$
		return true;
	}
	return false;
}
 
Example 12
Source File: AssignmentLinkingTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected XAssignment getAssignment(XtendClass clazz, int assignmentInFunction) {
	XtendFunction function = (XtendFunction) clazz.getMembers().get(0);
	XBlockExpression body = (XBlockExpression) function.getExpression();
	List<XExpression> expressions = body.getExpressions();
	int idx = assignmentInFunction;
	if (idx == -1)
		idx = expressions.size() - 1;
	XAssignment result = (XAssignment) expressions.get(idx);
	return result;
}
 
Example 13
Source File: DefaultEarlyExitComputer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected Collection<IEarlyExitComputer.ExitPoint> _exitPoints(final XBlockExpression expression) {
  EList<XExpression> _expressions = expression.getExpressions();
  for (final XExpression child : _expressions) {
    {
      Collection<IEarlyExitComputer.ExitPoint> exitPoints = this.getExitPoints(child);
      boolean _isNotEmpty = this.isNotEmpty(exitPoints);
      if (_isNotEmpty) {
        return exitPoints;
      }
    }
  }
  return Collections.<IEarlyExitComputer.ExitPoint>emptyList();
}
 
Example 14
Source File: PureXbaseFormatter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void _format(final XBlockExpression xBlockExpression, @Extension final IFormattableDocument document) {
  final Consumer<ISemanticRegion> _function = (ISemanticRegion it) -> {
    final Procedure1<IHiddenRegionFormatter> _function_1 = (IHiddenRegionFormatter it_1) -> {
      it_1.newLine();
    };
    document.append(it, _function_1);
  };
  this.textRegionExtensions.regionFor(xBlockExpression).keywords(this._pureXbaseGrammarAccess.getSpecialBlockExpressionAccess().getSemicolonKeyword_1_1()).forEach(_function);
  EList<XExpression> _expressions = xBlockExpression.getExpressions();
  for (final XExpression xExpression : _expressions) {
    document.<XExpression>format(xExpression);
  }
}
 
Example 15
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void _toJavaStatement(XBlockExpression expr, ITreeAppendable b, boolean isReferenced) {
	b = b.trace(expr, false);
	if (expr.getExpressions().isEmpty())
		return;
	if (expr.getExpressions().size()==1) {
		internalToJavaStatement(expr.getExpressions().get(0), b, isReferenced);
		return;
	}
	if (isReferenced)
		declareSyntheticVariable(expr, b);
	boolean needsBraces = isReferenced || !bracesAreAddedByOuterStructure(expr);
	if (needsBraces) {
		b.newLine().append("{").increaseIndentation();
		b.openPseudoScope();
	}
	final EList<XExpression> expressions = expr.getExpressions();
	for (int i = 0; i < expressions.size(); i++) {
		XExpression ex = expressions.get(i);
		if (i < expressions.size() - 1) {
			internalToJavaStatement(ex, b, false);
		} else {
			internalToJavaStatement(ex, b, isReferenced);
			if (isReferenced) {
				b.newLine().append(getVarName(expr, b)).append(" = ");
				internalToConvertedExpression(ex, b, getLightweightType(expr));
				b.append(";");
			}
		}
	}
	if (needsBraces) {
		b.closeScope();
		b.decreaseIndentation().newLine().append("}");
	}
}
 
Example 16
Source File: EarlyExitValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkDeadCode(XBlockExpression block) {
	List<XExpression> expressions = block.getExpressions();
	for(int i = 0, size = expressions.size(); i < size - 1; i++) {
		XExpression expression = expressions.get(i);
		if (earlyExitComputer.isEarlyExit(expression)) {
			if (!(expression instanceof XAbstractFeatureCall)) {
				// XAbstractFeatureCall does already a decent job for its argument lists
				// no additional error necessary
				markAsDeadCode(expressions.get(i + 1));
			}
			return;
		}
	}
}
 
Example 17
Source File: ExtendedEarlyExitComputer.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Returns <code>true</code> for expressions that seem to be early exit expressions, e.g.
 * <pre>
 *   while(condition) {
 *     if (anotherCondition)
 *       return value
 *     changeResultOfFirstCondition
 *   }
 * </pre>
 */
public boolean isIntentionalEarlyExit(/* @Nullable */ XExpression expression) {
	if (expression == null) {
		return true;
	}
	if (expression instanceof XBlockExpression) {
		XBlockExpression block = (XBlockExpression) expression;
		List<XExpression> children = block.getExpressions();
		for(XExpression child: children) {
			if (isIntentionalEarlyExit(child)) {
				return true;
			}
		}
	} else if (expression instanceof XIfExpression) {
		return isIntentionalEarlyExit(((XIfExpression) expression).getThen()) 
				|| isIntentionalEarlyExit(((XIfExpression) expression).getElse());
	} else if (expression instanceof XSwitchExpression) {
		XSwitchExpression switchExpression = (XSwitchExpression) expression;
		for(XCasePart caseExpression: switchExpression.getCases()) {
			if (isIntentionalEarlyExit(caseExpression.getThen())) {
				return true;
			}
		}
		if (isIntentionalEarlyExit(switchExpression.getDefault())) {
			return true;
		}
	} else if (expression instanceof XTryCatchFinallyExpression) {
		XTryCatchFinallyExpression tryCatchFinally = (XTryCatchFinallyExpression) expression;
		if (isIntentionalEarlyExit(tryCatchFinally.getExpression())) {
			for(XCatchClause catchClause: tryCatchFinally.getCatchClauses()) {
				if (!isIntentionalEarlyExit(catchClause.getExpression()))
					return false;
			}
			return true;
		}
		return false;
	} else if (expression instanceof XAbstractWhileExpression) {
		return isIntentionalEarlyExit(((XAbstractWhileExpression) expression).getBody());
	} else if (expression instanceof XForLoopExpression) {
		return isIntentionalEarlyExit(((XForLoopExpression) expression).getEachExpression());
	} else if (expression instanceof XBasicForLoopExpression) {
		return isIntentionalEarlyExit(((XBasicForLoopExpression) expression).getEachExpression());
	} else if (expression instanceof XSynchronizedExpression) {
		return isIntentionalEarlyExit(((XSynchronizedExpression) expression).getExpression());
	}
	return expression instanceof XReturnExpression || expression instanceof XThrowExpression;
}
 
Example 18
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected boolean isValueExpectedRecursive(XExpression expr) {
	EStructuralFeature feature = expr.eContainingFeature();
	EObject container = expr.eContainer();
	
	// is part of block
	if (container instanceof XBlockExpression) {
		XBlockExpression blockExpression = (XBlockExpression) container;
		final List<XExpression> expressions = blockExpression.getExpressions();
		if (expressions.get(expressions.size()-1) != expr) {
			return false;
		}
	}
	// no expectation cases
	if (feature == XbasePackage.Literals.XTRY_CATCH_FINALLY_EXPRESSION__FINALLY_EXPRESSION
		|| feature == XbasePackage.Literals.XABSTRACT_WHILE_EXPRESSION__BODY
		|| feature == XbasePackage.Literals.XFOR_LOOP_EXPRESSION__EACH_EXPRESSION) {
		return false;
	}
	// is value expected
	if (container instanceof XAbstractFeatureCall 
		|| container instanceof XConstructorCall
		|| container instanceof XAssignment
		|| container instanceof XVariableDeclaration
		|| container instanceof XReturnExpression
		|| container instanceof XThrowExpression
		|| feature == XbasePackage.Literals.XFOR_LOOP_EXPRESSION__FOR_EXPRESSION
		|| feature == XbasePackage.Literals.XSWITCH_EXPRESSION__SWITCH
		|| feature == XbasePackage.Literals.XCASE_PART__CASE
		|| feature == XbasePackage.Literals.XIF_EXPRESSION__IF
		|| feature == XbasePackage.Literals.XABSTRACT_WHILE_EXPRESSION__PREDICATE
		|| feature == XbasePackage.Literals.XBASIC_FOR_LOOP_EXPRESSION__EXPRESSION
		|| feature == XbasePackage.Literals.XSYNCHRONIZED_EXPRESSION__PARAM) {
		return true;
	}
	if (isLocalClassSemantics(container) || logicalContainerProvider.getLogicalContainer(expr) != null) {
		LightweightTypeReference expectedReturnType = typeResolver.resolveTypes(expr).getExpectedReturnType(expr);
		return expectedReturnType == null || !expectedReturnType.isPrimitiveVoid();
	}
	if (container instanceof XCasePart || container instanceof XCatchClause) {
		container = container.eContainer();
	}
	if (container instanceof XExpression) {
		return isValueExpectedRecursive((XExpression) container);
	}
	return true;
}