org.eclipse.xtext.xbase.XCatchClause Java Examples

The following examples show how to use org.eclipse.xtext.xbase.XCatchClause. 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: XTryCatchFinallyExpressionImpl.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
	switch (featureID)
	{
		case XbasePackage.XTRY_CATCH_FINALLY_EXPRESSION__EXPRESSION:
			setExpression((XExpression)newValue);
			return;
		case XbasePackage.XTRY_CATCH_FINALLY_EXPRESSION__FINALLY_EXPRESSION:
			setFinallyExpression((XExpression)newValue);
			return;
		case XbasePackage.XTRY_CATCH_FINALLY_EXPRESSION__CATCH_CLAUSES:
			getCatchClauses().clear();
			getCatchClauses().addAll((Collection<? extends XCatchClause>)newValue);
			return;
		case XbasePackage.XTRY_CATCH_FINALLY_EXPRESSION__RESOURCES:
			getResources().clear();
			getResources().addAll((Collection<? extends XVariableDeclaration>)newValue);
			return;
	}
	super.eSet(featureID, newValue);
}
 
Example #2
Source File: PyExpressionGenerator.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Generate the given object.
 *
 * @param tryStatement the try-catch-finally statement.
 * @param it the target for the generated content.
 * @param context the context.
 * @return the statement.
 */
protected XExpression _generate(XTryCatchFinallyExpression tryStatement, IAppendable it, IExtraLanguageGeneratorContext context) {
	it.append("try:"); //$NON-NLS-1$
	it.increaseIndentation().newLine();
	generate(tryStatement.getExpression(), context.getExpectedExpressionType(), it, context);
	it.decreaseIndentation().newLine();
	for (final XCatchClause clause : tryStatement.getCatchClauses()) {
		it.append("except "); //$NON-NLS-1$
		it.append(clause.getDeclaredParam().getParameterType().getType());
		it.append(", "); //$NON-NLS-1$
		it.append(it.declareUniqueNameVariable(clause.getDeclaredParam(), clause.getDeclaredParam().getSimpleName()));
		it.append(":"); //$NON-NLS-1$
		it.increaseIndentation().newLine();
		generate(clause.getExpression(), context.getExpectedExpressionType(), it, context);
		it.decreaseIndentation().newLine();
	}
	if (tryStatement.getFinallyExpression() != null) {
		it.append("finally:"); //$NON-NLS-1$
		it.increaseIndentation().newLine();
		generate(tryStatement.getFinallyExpression(), it, context);
		it.decreaseIndentation();
	}
	return tryStatement;
}
 
Example #3
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(XTryCatchFinallyExpression expression, ISideEffectContext context) {
	final List<Map<String, List<XExpression>>> buffers = new ArrayList<>();
	Map<String, List<XExpression>> buffer = context.createVariableAssignmentBufferForBranch();
	if (hasSideEffects(expression.getExpression(), context.branch(buffer))) {
		return true;
	}
	buffers.add(buffer);
	for (final XCatchClause clause : expression.getCatchClauses()) {
		context.open();
		try {
			buffer = context.createVariableAssignmentBufferForBranch();
			if (hasSideEffects(clause.getExpression(), context.branch(buffer))) {
				return true;
			}
			buffers.add(buffer);
		} finally {
			context.close();
		}
	}
	context.mergeBranchVariableAssignments(buffers);
	if (hasSideEffects(expression.getFinallyExpression(), context)) {
		return true;
	}
	return false;
}
 
Example #4
Source File: DefaultEarlyExitComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected Collection<IEarlyExitComputer.ExitPoint> _exitPoints(final XTryCatchFinallyExpression expression) {
  Collection<IEarlyExitComputer.ExitPoint> tryExitPoints = this.getExitPoints(expression.getExpression());
  boolean _isNotEmpty = this.isNotEmpty(tryExitPoints);
  if (_isNotEmpty) {
    Collection<IEarlyExitComputer.ExitPoint> result = Lists.<IEarlyExitComputer.ExitPoint>newArrayList(tryExitPoints);
    EList<XCatchClause> _catchClauses = expression.getCatchClauses();
    for (final XCatchClause catchClause : _catchClauses) {
      {
        Collection<IEarlyExitComputer.ExitPoint> catchExitPoints = this.getExitPoints(catchClause.getExpression());
        boolean _isNotEmpty_1 = this.isNotEmpty(catchExitPoints);
        if (_isNotEmpty_1) {
          result.addAll(catchExitPoints);
        } else {
          return this.getExitPoints(expression.getFinallyExpression());
        }
      }
    }
    return result;
  }
  return this.getExitPoints(expression.getFinallyExpression());
}
 
Example #5
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkCatchClausesOrder(XTryCatchFinallyExpression expression) {
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(getServices(), expression);
	List<LightweightTypeReference> previousTypeReferences = new ArrayList<LightweightTypeReference>();
	for (XCatchClause catchClause : expression.getCatchClauses()) {
		LightweightTypeReference actualTypeReference = owner.toLightweightTypeReference(catchClause.getDeclaredParam().getParameterType());
		if (actualTypeReference == null) {
			continue;
		}
		if (isHandled(actualTypeReference, previousTypeReferences)) {
			error("Unreachable code: The catch block can never match. It is already handled by a previous condition.", catchClause.getDeclaredParam().getParameterType(), null, IssueCodes.UNREACHABLE_CATCH_BLOCK);
			continue;
		}
		previousTypeReferences.add(actualTypeReference);
	}
}
 
Example #6
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkTypes(XCatchClause catchClause) {
	LightweightTypeReference parameterType = getActualType(catchClause, catchClause.getDeclaredParam());
	if (parameterType != null && !parameterType.isSubtypeOf(Throwable.class)) {
		error("No exception of type " + parameterType.getHumanReadableName()
				+ " can be thrown; an exception type must be a subclass of Throwable",
				catchClause.getDeclaredParam(), TypesPackage.Literals.JVM_FORMAL_PARAMETER__PARAMETER_TYPE,
				ValidationMessageAcceptor.INSIGNIFICANT_INDEX, INCOMPATIBLE_TYPES);
	}
}
 
Example #7
Source File: ParserTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMultiCatch_02() throws Exception {
	XtendClass clazz = clazz("class Foo { def void m() { try {} catch(extension NullPointerException | IllegalArgumentException | IllegalStateException e) {} } }");
	assertEquals(1, clazz.getMembers().size());
	XtendFunction m = (XtendFunction) clazz.getMembers().get(0);
	XBlockExpression body = (XBlockExpression) m.getExpression();
	assertEquals(1, body.getExpressions().size());
	XTryCatchFinallyExpression tryCatch = (XTryCatchFinallyExpression) body.getExpressions().get(0);
	XCatchClause singleCatchClause = tryCatch.getCatchClauses().get(0);
	XtendFormalParameter parameter = (XtendFormalParameter) singleCatchClause.getDeclaredParam();
	assertTrue(parameter.isExtension());
	JvmSynonymTypeReference parameterType = (JvmSynonymTypeReference) parameter.getParameterType();
	assertEquals(3, parameterType.getReferences().size());
}
 
Example #8
Source File: ParserTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMultiCatch_01() throws Exception {
	XtendClass clazz = clazz("class Foo { def void m() { try {} catch(NullPointerException | IllegalArgumentException e) {} } }");
	assertEquals(1, clazz.getMembers().size());
	XtendFunction m = (XtendFunction) clazz.getMembers().get(0);
	XBlockExpression body = (XBlockExpression) m.getExpression();
	assertEquals(1, body.getExpressions().size());
	XTryCatchFinallyExpression tryCatch = (XTryCatchFinallyExpression) body.getExpressions().get(0);
	XCatchClause singleCatchClause = tryCatch.getCatchClauses().get(0);
	XtendFormalParameter parameter = (XtendFormalParameter) singleCatchClause.getDeclaredParam();
	assertFalse(parameter.isExtension());
	JvmSynonymTypeReference parameterType = (JvmSynonymTypeReference) parameter.getParameterType();
	assertEquals(2, parameterType.getReferences().size());
}
 
Example #9
Source File: ParserTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testExtensionOnCatchClause_01() throws Exception {
	XtendClass clazz = clazz("class Foo { def void m() { try {} catch(extension NullPointerException e) {} } }");
	assertEquals(1, clazz.getMembers().size());
	XtendFunction m = (XtendFunction) clazz.getMembers().get(0);
	XBlockExpression body = (XBlockExpression) m.getExpression();
	assertEquals(1, body.getExpressions().size());
	XTryCatchFinallyExpression tryCatch = (XTryCatchFinallyExpression) body.getExpressions().get(0);
	XCatchClause singleCatchClause = tryCatch.getCatchClauses().get(0);
	XtendFormalParameter parameter = (XtendFormalParameter) singleCatchClause.getDeclaredParam();
	assertTrue(parameter.isExtension());
}
 
Example #10
Source File: XTryCatchFinallyExpressionImpl.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public EList<XCatchClause> getCatchClauses()
{
	if (catchClauses == null)
	{
		catchClauses = new EObjectContainmentEList<XCatchClause>(XCatchClause.class, this, XbasePackage.XTRY_CATCH_FINALLY_EXPRESSION__CATCH_CLAUSES);
	}
	return catchClauses;
}
 
Example #11
Source File: AbstractXbaseSemanticSequencer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Contexts:
 *     XCatchClause returns XCatchClause
 *
 * Constraint:
 *     (declaredParam=FullJvmFormalParameter expression=XExpression)
 */
protected void sequence_XCatchClause(ISerializationContext context, XCatchClause semanticObject) {
	if (errorAcceptor != null) {
		if (transientValues.isValueTransient(semanticObject, XbasePackage.Literals.XCATCH_CLAUSE__DECLARED_PARAM) == ValueTransient.YES)
			errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, XbasePackage.Literals.XCATCH_CLAUSE__DECLARED_PARAM));
		if (transientValues.isValueTransient(semanticObject, XbasePackage.Literals.XCATCH_CLAUSE__EXPRESSION) == ValueTransient.YES)
			errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, XbasePackage.Literals.XCATCH_CLAUSE__EXPRESSION));
	}
	SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
	feeder.accept(grammarAccess.getXCatchClauseAccess().getDeclaredParamFullJvmFormalParameterParserRuleCall_2_0(), semanticObject.getDeclaredParam());
	feeder.accept(grammarAccess.getXCatchClauseAccess().getExpressionXExpressionParserRuleCall_4_0(), semanticObject.getExpression());
	feeder.finish();
}
 
Example #12
Source File: XbaseImplicitReturnFinder.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void _findImplicitReturns(final XTryCatchFinallyExpression expression, final ImplicitReturnFinder.Acceptor acceptor) {
  this.findImplicitReturns(expression.getExpression(), acceptor);
  final Consumer<XCatchClause> _function = (XCatchClause it) -> {
    this.findImplicitReturns(it.getExpression(), acceptor);
  };
  expression.getCatchClauses().forEach(_function);
}
 
Example #13
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void doTestTryCatchExpression(XTryCatchFinallyExpression tryEx) {
	assertFeatureCall("foo", ((XThrowExpression)tryEx.getExpression()).getExpression());
	assertFeatureCall("baz", tryEx.getFinallyExpression());
	
	assertEquals(1,tryEx.getCatchClauses().size());
	XCatchClause clause = tryEx.getCatchClauses().get(0);
	assertFeatureCall("bar", clause.getExpression());
	assertEquals("java.lang.Exception", clause.getDeclaredParam().getParameterType().getIdentifier());
	assertEquals("e", clause.getDeclaredParam().getName());
}
 
Example #14
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void doTestTryCatchExpression_2(XTryCatchFinallyExpression tryEx) {
	assertFeatureCall("foo", tryEx.getExpression());
	assertNull(tryEx.getFinallyExpression());
	
	assertEquals(1,tryEx.getCatchClauses().size());
	XCatchClause clause = tryEx.getCatchClauses().get(0);
	assertFeatureCall("bar", clause.getExpression());
	assertEquals("java.lang.Exception", clause.getDeclaredParam().getParameterType().getIdentifier());
	assertEquals("e", clause.getDeclaredParam().getName());
}
 
Example #15
Source File: XbaseExpectedTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testTryCatchExpression() throws Exception {
	XTryCatchFinallyExpression exp = (XTryCatchFinallyExpression)  
			expressionWithExpectedType("try null catch (java.lang.Throwable t) null finally null", "String");

	assertExpected("java.lang.String", exp.getExpression());
	for (XCatchClause cc : exp.getCatchClauses()) {
		assertExpected("java.lang.String", cc.getExpression());
	}
	assertExpected(null, exp.getFinallyExpression());
}
 
Example #16
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;
}
 
Example #17
Source File: AbstractXbaseSemanticSequencer.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Deprecated
protected void sequence_XCatchClause(EObject context, XCatchClause semanticObject) {
	sequence_XCatchClause(createContext(context, semanticObject), semanticObject);
}
 
Example #18
Source File: XtendCompiler.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected void appendCatchClauseParameter(XCatchClause catchClause, JvmTypeReference parameterType,
		String parameterName, ITreeAppendable appendable) {
	appendExtensionAnnotation(catchClause.getDeclaredParam(), catchClause, appendable, false);
	super.appendCatchClauseParameter(catchClause, parameterType, parameterName, appendable);
}
 
Example #19
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Check
public void checkValidExtension(XtendFormalParameter parameter) {
	// catch clauses validate their types against java.lang.Throwable
	if (parameter.isExtension() && !(parameter.eContainer() instanceof XCatchClause))
		checkValidExtensionType(parameter, parameter, TypesPackage.Literals.JVM_FORMAL_PARAMETER__PARAMETER_TYPE);
}
 
Example #20
Source File: AbstractXbaseLinkingTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testTryCatch_0() throws Exception {
	XTryCatchFinallyExpression exp = (XTryCatchFinallyExpression) expression("try 'foo' catch (Exception e) e",true);
	XCatchClause xCatchClause = exp.getCatchClauses().get(0);
	assertSame(xCatchClause.getDeclaredParam(), ((XFeatureCall)xCatchClause.getExpression()).getFeature());
}
 
Example #21
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;
}
 
Example #22
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected void appendCatchClauseParameter(XCatchClause catchClause, JvmTypeReference parameterType, final String parameterName, ITreeAppendable appendable) {
	appendable.append("final ");
	serialize(parameterType, catchClause, appendable);
	appendable.append(" ");
	appendable.trace(catchClause.getDeclaredParam(), TypesPackage.Literals.JVM_FORMAL_PARAMETER__NAME, 0).append(parameterName);
}
 
Example #23
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected void appendCatchClause(XCatchClause catchClause, boolean parentIsReferenced, String parentVariable,
		ITreeAppendable appendable) {
	JvmTypeReference type = catchClause.getDeclaredParam().getParameterType();
	final String declaredParamName = makeJavaIdentifier(catchClause.getDeclaredParam().getName());
	final String name = appendable.declareVariable(catchClause.getDeclaredParam(), declaredParamName);
	appendable.append("if (");
	JvmTypeReference typeToUse = type;
	if (type instanceof JvmSynonymTypeReference) {
		List<JvmTypeReference> references = ((JvmSynonymTypeReference) type).getReferences();
		Iterator<JvmTypeReference> iter = references.iterator();
		while(iter.hasNext()) {
			appendable.append(parentVariable).append(" instanceof ");
			serialize(iter.next(), catchClause, appendable);
			if (iter.hasNext()) {
				appendable.append(" || ");
			}
		}
		typeToUse = resolveSynonymType((JvmSynonymTypeReference) type, catchClause);
	} else {
		appendable.append(parentVariable).append(" instanceof ");
		serialize(type, catchClause, appendable);			
	}
	appendable.append(") ").append("{");
	appendable.increaseIndentation();
	ITreeAppendable withDebugging = appendable.trace(catchClause, true);
	if (!XbaseUsageCrossReferencer.find(catchClause.getDeclaredParam(), catchClause.getExpression()).isEmpty()) {
		ITreeAppendable parameterAppendable = withDebugging.trace(catchClause.getDeclaredParam());
		appendCatchClauseParameter(catchClause, typeToUse, name, parameterAppendable.newLine());
		withDebugging.append(" = (");
		serialize(typeToUse, catchClause, withDebugging);
		withDebugging.append(")").append(parentVariable).append(";");
	}
	final boolean canBeReferenced = parentIsReferenced && ! isPrimitiveVoid(catchClause.getExpression());
	internalToJavaStatement(catchClause.getExpression(), withDebugging, canBeReferenced);
	if (canBeReferenced) {
		appendable.newLine().append(getVarName(catchClause.eContainer(), appendable)).append(" = ");
		internalToConvertedExpression(catchClause.getExpression(), appendable, getLightweightType((XExpression) catchClause.eContainer()));
		appendable.append(";");
	}
	closeBlock(appendable);
}
 
Example #24
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected void appendCatchAndFinally(XTryCatchFinallyExpression expr, ITreeAppendable b, boolean isReferenced) {
	final EList<XCatchClause> catchClauses = expr.getCatchClauses();
	final XExpression finallyExp = expr.getFinallyExpression();
	boolean isTryWithResources = !expr.getResources().isEmpty();
	// If Java 7 or better: use Java's try-with-resources
	boolean nativeTryWithResources = isAtLeast(b, JAVA7);
	final String throwablesStore = b.getName(Tuples.pair(expr, "_caughtThrowables"));

	// Catch
	if (!catchClauses.isEmpty()) {
		String variable = b.declareSyntheticVariable(Tuples.pair(expr, "_caughtThrowable"), "_t");
		b.append(" catch (final Throwable ").append(variable).append(") ");
		b.append("{").increaseIndentation().newLine();
		Iterator<XCatchClause> iterator = catchClauses.iterator();
		while (iterator.hasNext()) {
			XCatchClause catchClause = iterator.next();
			ITreeAppendable catchClauseAppendable = b.trace(catchClause);
			appendCatchClause(catchClause, isReferenced, variable, catchClauseAppendable);
			if (iterator.hasNext()) {
				b.append(" else ");
			}
		}
		b.append(" else {");
		b.increaseIndentation().newLine();
		if (isTryWithResources && !nativeTryWithResources) {
			b.append(throwablesStore + ".add(" + variable + ");").newLine();
		}
		appendSneakyThrow(expr, b, variable);
		closeBlock(b);
		closeBlock(b);
	}

	// Finally
	if (finallyExp != null || (!nativeTryWithResources && isTryWithResources)) {
		b.append(" finally {").increaseIndentation();
		if (finallyExp != null)
			internalToJavaStatement(finallyExp, b, false);
		if (!nativeTryWithResources && isTryWithResources)
			appendFinallyWithResources(expr, b);
		b.decreaseIndentation().newLine().append("}");
	}
}
 
Example #25
Source File: ExtendedEarlyExitComputer.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
public boolean isDefiniteEarlyExit(XExpression expression) {
	// TODO further improvements
	if (expression instanceof XIfExpression) {
		XIfExpression ifExpression = (XIfExpression) expression;
		return isDefiniteEarlyExit(ifExpression.getThen()) && isDefiniteEarlyExit(ifExpression.getElse());
	} else if (expression instanceof XSwitchExpression) {
		XSwitchExpression switchExpression = (XSwitchExpression) expression;
		if (isDefiniteEarlyExit(switchExpression.getDefault())) {
			for(XCasePart caseExpression: switchExpression.getCases()) {
				if (!isDefiniteEarlyExit(caseExpression.getThen())) {
					return false;
				}
			}
			return true;
		}
		return false;
	} else if (expression instanceof XTryCatchFinallyExpression) {
		XTryCatchFinallyExpression tryExpression = (XTryCatchFinallyExpression) expression;
		if (isDefiniteEarlyExit(tryExpression.getFinallyExpression())) {
			return true;
		}
		if (isDefiniteEarlyExit(tryExpression.getExpression())) {
			for(XCatchClause catchClause: tryExpression.getCatchClauses()) {
				if (!isDefiniteEarlyExit(catchClause.getExpression())) {
					return false;
				}
			}
			return true;
		}
		return false;
	} else if (expression instanceof XBlockExpression) {
		List<XExpression> expressions = ((XBlockExpression) expression).getExpressions();
		for(int i = expressions.size() - 1; i >= 0; i--) {
			if (isDefiniteEarlyExit(expressions.get(i))) {
				return true;
			}
		}
	} else if (expression instanceof XSynchronizedExpression) {
		return isDefiniteEarlyExit(((XSynchronizedExpression) expression).getExpression());
	}
	return expression instanceof XReturnExpression || expression instanceof XThrowExpression;
}
 
Example #26
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 #27
Source File: ThrownExceptionSwitch.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Boolean caseXTryCatchFinallyExpression(XTryCatchFinallyExpression object) {
	List<XVariableDeclaration> resources = object.getResources();
	List<XCatchClause> clauses = object.getCatchClauses();

	if (clauses.isEmpty()) {
		// collect exceptions thrown by automatic close method
		// of given resources
		processExceptionsFromAutoclosable(resources, delegate);
		// let procedure traverse child elements, to check if they throw
		// exceptions
		return Boolean.TRUE;
	}

	// traverse child elements explicitly, to filter for caught exceptions
	final List<LightweightTypeReference> caughtExceptions = Lists.newArrayList();
	boolean wasThrowable = false;
	for (XCatchClause clause : clauses) {
		JvmTypeReference caught = clause.getDeclaredParam().getParameterType();
		if (caught != null) {
			LightweightTypeReference caughtException = delegate.toLightweightReference(caught)
					.getRawTypeReference();
			if (caughtException.isType(Throwable.class)) {
				wasThrowable = true;
			}
			if (caughtException.isSynonym()) {
				caughtExceptions.addAll(caughtException.getMultiTypeComponents());
			} else {
				caughtExceptions.add(caughtException);
			}
		}
		delegate.collectThrownExceptions(clause.getExpression());
	}
	delegate.collectThrownExceptions(object.getFinallyExpression());
	if (wasThrowable) {
		// Stop child traversing of procedure
		return Boolean.FALSE;
	}

	// Filter caught exceptions from all thrown excpetions
	// (thrown by resource constructor/automatic close, try expressions)
	IThrownExceptionDelegate filteredDelegate = delegate.catchExceptions(caughtExceptions);
	processExceptionsFromAutoclosable(resources, filteredDelegate);
	filteredDelegate.collectThrownExceptions(object.getExpression());
	// Stop child traversing of procedure
	return Boolean.FALSE;
}
 
Example #28
Source File: ThrownExceptionSwitch.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Boolean caseXCatchClause(XCatchClause object) {
	return Boolean.TRUE;
}