org.eclipse.xtext.xbase.XIfExpression Java Examples

The following examples show how to use org.eclipse.xtext.xbase.XIfExpression. 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(XIfExpression expression, ISideEffectContext context) {
	if (hasSideEffects(expression.getIf(), context)) {
		return true;
	}
	final Map<String, List<XExpression>> buffer1 = context.createVariableAssignmentBufferForBranch();
	if (hasSideEffects(expression.getThen(), context.branch(buffer1))) {
		return true;
	}
	final Map<String, List<XExpression>> buffer2 = context.createVariableAssignmentBufferForBranch();
	if (hasSideEffects(expression.getElse(), context.branch(buffer2))) {
		return true;
	}
	context.mergeBranchVariableAssignments(Arrays.asList(buffer1, buffer2));
	return false;
}
 
Example #2
Source File: XtendSyntacticSequencer.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Syntax: '('*
 */
@Override
protected void emit_XParenthesizedExpression_LeftParenthesisKeyword_0_a(EObject semanticObject,
		ISynNavigable transition, List<INode> nodes) {

	Keyword kw = grammarAccess.getXParenthesizedExpressionAccess().getLeftParenthesisKeyword_0();

	if (nodes == null) {
		if (semanticObject instanceof XIfExpression || semanticObject instanceof XTryCatchFinallyExpression) {
			EObject cnt = semanticObject.eContainer();
			if (cnt instanceof XExpression && !(cnt instanceof XBlockExpression)
					&& !(cnt instanceof XForLoopExpression))
				acceptUnassignedKeyword(kw, kw.getValue(), null);
		}
		if (semanticObject instanceof XConstructorCall) {
			XConstructorCall call = (XConstructorCall) semanticObject;
			if (!call.isExplicitConstructorCall() && call.getArguments().isEmpty()) {
				acceptUnassignedKeyword(kw, kw.getValue(), null);
			}
		}
	}
	acceptNodes(transition, nodes);
}
 
Example #3
Source File: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void _computeTypes(XIfExpression object, ITypeComputationState state) {
	ITypeComputationState conditionExpectation = state.withExpectation(getRawTypeForName(Boolean.TYPE, state));
	XExpression condition = object.getIf();
	conditionExpectation.computeTypes(condition);
	
	// TODO then expression may influence the expected type of else and vice versa
	XExpression thenExpression = getThen(object);
	ITypeComputationState thenState = reassignCheckedType(condition, thenExpression, state);
	ITypeComputationResult thenResult = thenState.computeTypes(thenExpression);
	XExpression elseExpression = getElse(object);
	if (elseExpression != null) {
		state.computeTypes(elseExpression);
	} else {
		BranchExpressionProcessor processor = new BranchExpressionProcessor(state, object) {
			@Override
			protected String getMessage() {
				return "Missing else branch for conditional expression with primitive type";
			}
		};
		processor.process(thenResult);
		processor.commit();
	}
}
 
Example #4
Source File: XbaseSyntacticSequencer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Syntax: '('*
 */
@Override
protected void emit_XParenthesizedExpression_LeftParenthesisKeyword_0_a(EObject semanticObject,
		ISynNavigable transition, List<INode> nodes) {

	Keyword kw = grammarAccess.getXParenthesizedExpressionAccess().getLeftParenthesisKeyword_0();

	if (nodes == null) {
		if (semanticObject instanceof XIfExpression || semanticObject instanceof XTryCatchFinallyExpression) {
			EObject cnt = semanticObject.eContainer();
			if (cnt instanceof XExpression && !(cnt instanceof XBlockExpression)
					&& !(cnt instanceof XForLoopExpression))
				acceptUnassignedKeyword(kw, kw.getValue(), null);
		}
		if (semanticObject instanceof XConstructorCall) {
			XConstructorCall call = (XConstructorCall) semanticObject;
			if (!call.isExplicitConstructorCall() && call.getArguments().isEmpty()) {
				acceptUnassignedKeyword(kw, kw.getValue(), null);
			}
		}
	}
	acceptNodes(transition, nodes);
}
 
Example #5
Source File: SerializerTest.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testSerialize_02() throws Exception {
	Resource resource = newResource("'foo' as String");
	XCastedExpression casted = (XCastedExpression) resource.getContents().get(0);
	
	XbaseFactory factory = XbaseFactory.eINSTANCE;
	XIfExpression ifExpression = factory.createXIfExpression();
	ifExpression.setIf(factory.createXBooleanLiteral());
	XStringLiteral stringLiteral = factory.createXStringLiteral();
	stringLiteral.setValue("value");
	ifExpression.setThen(stringLiteral);
	XInstanceOfExpression instanceOfExpression = factory.createXInstanceOfExpression();
	instanceOfExpression.setExpression(ifExpression);
	instanceOfExpression.setType(EcoreUtil.copy(casted.getType()));
	resource.getContents().clear();
	resource.getContents().add(instanceOfExpression);
	ISerializer serializer = get(ISerializer.class);
	String string = serializer.serialize(instanceOfExpression);
	// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=464846
	assertEquals("( if(false) \"value\" ) instanceof String", string);
	
	XInstanceOfExpression parsedExpression = parseHelper.parse(string);
	assertTrue(EcoreUtil.equals(instanceOfExpression, parsedExpression));
}
 
Example #6
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected int[] getOffsetAndLength(XIfExpression ifExpression, ICompositeNode node) {
	int offset = node.getOffset();
	int length = node.getLength();
	if (ifExpression.getElse() != null) {
		ICompositeNode elseNode = NodeModelUtils.findActualNodeFor(ifExpression.getElse());
		if (elseNode != null) {
			length = elseNode.getOffset() - offset;
		}
	} else {
		XIfExpression parentIfExpression = EcoreUtil2.getContainerOfType(ifExpression.eContainer(),
				XIfExpression.class);
		if (parentIfExpression != null && parentIfExpression.getElse() == ifExpression) {
			ICompositeNode thenNode = NodeModelUtils.findActualNodeFor(parentIfExpression.getThen());
			if (thenNode != null) {
				int endOffset = thenNode.getEndOffset();
				length = length + (offset - endOffset);
				offset = endOffset;
			}
		}
	}
	return new int[] { offset, length };
}
 
Example #7
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 #8
Source File: PyExpressionGenerator.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Generate the given object.
 *
 * @param ifStatement the if-then-else statement.
 * @param it the target for the generated content.
 * @param context the context.
 * @return the statement.
 */
protected XExpression _generate(XIfExpression ifStatement, IAppendable it, IExtraLanguageGeneratorContext context) {
	it.append("if "); //$NON-NLS-1$
	generate(ifStatement.getIf(), it, context);
	it.append(":"); //$NON-NLS-1$
	it.increaseIndentation().newLine();
	if (ifStatement.getThen() != null) {
		generate(ifStatement.getThen(), context.getExpectedExpressionType(), it, context);
	} else if (context.getExpectedExpressionType() == null) {
		it.append("pass"); //$NON-NLS-1$
	} else {
		it.append("return ").append(toDefaultValue(context.getExpectedExpressionType().toJavaCompliantTypeReference())); //$NON-NLS-1$
	}
	it.decreaseIndentation();
	if (ifStatement.getElse() != null) {
		it.newLine().append("else:"); //$NON-NLS-1$
		it.increaseIndentation().newLine();
		generate(ifStatement.getElse(), context.getExpectedExpressionType(), it, context);
		it.decreaseIndentation();
	} else if (context.getExpectedExpressionType() != null) {
		it.newLine().append("else:"); //$NON-NLS-1$
		it.increaseIndentation().newLine();
		it.append("return ").append(toDefaultValue(context.getExpectedExpressionType().toJavaCompliantTypeReference())); //$NON-NLS-1$
		it.decreaseIndentation();
	}
	return ifStatement;
}
 
Example #9
Source File: ExpressionScopeTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testReassignedType_03() throws Exception {
	XIfExpression ifExpr = (XIfExpression) IterableExtensions
			.last(((XBlockExpression) expression("{ var it = new Object() if (it instanceof String) { it = new Object() } }", false))
					.getExpressions());
	XBlockExpression block = (XBlockExpression) ifExpr.getThen();
	XExpression assignment = Iterables.getFirst(block.getExpressions(), null);
	IExpressionScope expressionScope = batchTypeResolver.resolveTypes(assignment).getExpressionScope(assignment,
			IExpressionScope.Anchor.AFTER);
	containsNot(expressionScope, "charAt");
	contains(expressionScope, "it");
	containsNot(expressionScope, "operator_lessThan");
}
 
Example #10
Source File: ExpressionScopeTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testReassignedType_02() throws Exception {
	XIfExpression ifExpr = (XIfExpression) IterableExtensions
			.last(((XBlockExpression) expression("{ var it = new Object() if (it instanceof String) { it = new Object() } }", false))
					.getExpressions());
	XBlockExpression block = (XBlockExpression) ifExpr.getThen();
	IExpressionScope expressionScope = batchTypeResolver.resolveTypes(block).getExpressionScope(block, IExpressionScope.Anchor.BEFORE);
	contains(expressionScope, "charAt");
	contains(expressionScope, "it");
	contains(expressionScope, "operator_lessThan");
}
 
Example #11
Source File: ExpressionScopeTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testReassignedType_01() throws Exception {
	XIfExpression ifExpr = (XIfExpression) IterableExtensions
			.last(((XBlockExpression) expression("{ var it = new Object() if (it instanceof String) {} }", false)).getExpressions());
	XBlockExpression block = (XBlockExpression) ifExpr.getThen();
	IExpressionScope expressionScope = batchTypeResolver.resolveTypes(block).getExpressionScope(block, IExpressionScope.Anchor.BEFORE);
	contains(expressionScope, "charAt");
	contains(expressionScope, "it");
	contains(expressionScope, "operator_lessThan");
}
 
Example #12
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testIf_3() throws Exception {
	XIfExpression ie = (XIfExpression) expression("if (foo) bar else if (baz) if (apa) bpa else cpa");
	XIfExpression nestedIf = (XIfExpression) ie.getElse();
	XIfExpression secondNested = (XIfExpression) nestedIf.getThen();
	XFeatureCall cpa = (XFeatureCall) secondNested.getElse();
	assertEquals("cpa",cpa.getConcreteSyntaxFeatureName());
}
 
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 XExpression expression) {
  if (expression instanceof XDoWhileExpression) {
    return _exitPoints((XDoWhileExpression)expression);
  } else if (expression instanceof XWhileExpression) {
    return _exitPoints((XWhileExpression)expression);
  } else if (expression instanceof XAbstractFeatureCall) {
    return _exitPoints((XAbstractFeatureCall)expression);
  } else if (expression instanceof XBasicForLoopExpression) {
    return _exitPoints((XBasicForLoopExpression)expression);
  } else if (expression instanceof XBlockExpression) {
    return _exitPoints((XBlockExpression)expression);
  } else if (expression instanceof XConstructorCall) {
    return _exitPoints((XConstructorCall)expression);
  } else if (expression instanceof XForLoopExpression) {
    return _exitPoints((XForLoopExpression)expression);
  } else if (expression instanceof XIfExpression) {
    return _exitPoints((XIfExpression)expression);
  } else if (expression instanceof XReturnExpression) {
    return _exitPoints((XReturnExpression)expression);
  } else if (expression instanceof XSwitchExpression) {
    return _exitPoints((XSwitchExpression)expression);
  } else if (expression instanceof XSynchronizedExpression) {
    return _exitPoints((XSynchronizedExpression)expression);
  } else if (expression instanceof XThrowExpression) {
    return _exitPoints((XThrowExpression)expression);
  } else if (expression instanceof XTryCatchFinallyExpression) {
    return _exitPoints((XTryCatchFinallyExpression)expression);
  } else if (expression instanceof XVariableDeclaration) {
    return _exitPoints((XVariableDeclaration)expression);
  } else if (expression != null) {
    return _exitPoints(expression);
  } else {
    throw new IllegalArgumentException("Unhandled parameter types: " +
      Arrays.<Object>asList(expression).toString());
  }
}
 
Example #14
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 XIfExpression expression) {
  Collection<IEarlyExitComputer.ExitPoint> ifExitPoints = this.getExitPoints(expression.getIf());
  boolean _isNotEmpty = this.isNotEmpty(ifExitPoints);
  if (_isNotEmpty) {
    return ifExitPoints;
  }
  Collection<IEarlyExitComputer.ExitPoint> thenExitPoints = this.getExitPoints(expression.getThen());
  Collection<IEarlyExitComputer.ExitPoint> elseExitPoints = this.getExitPoints(expression.getElse());
  if ((this.isNotEmpty(thenExitPoints) && this.isNotEmpty(elseExitPoints))) {
    Collection<IEarlyExitComputer.ExitPoint> result = Lists.<IEarlyExitComputer.ExitPoint>newArrayList(thenExitPoints);
    result.addAll(elseExitPoints);
    return result;
  }
  return Collections.<IEarlyExitComputer.ExitPoint>emptyList();
}
 
Example #15
Source File: XbaseExpectedTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testIfExpression() throws Exception {
	XIfExpression target = (XIfExpression) expressionWithExpectedType("if (null) null else null", "String");

	assertExpected("boolean", target.getIf()); // if (null) is invalid thus we expect the primitive boolean
	assertExpected("java.lang.String", target.getThen());
	assertExpected("java.lang.String", target.getElse());
}
 
Example #16
Source File: XbaseInterpreter.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
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);
	}
}
 
Example #17
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void _toJavaStatement(XIfExpression expr, ITreeAppendable b, boolean isReferenced) {
	if (isReferenced)
		declareSyntheticVariable(expr, b);
	internalToJavaStatement(expr.getIf(), b, true);
	b.newLine().append("if (");
	internalToJavaExpression(expr.getIf(), b);
	b.append(") {").increaseIndentation();
	final boolean canBeReferenced = isReferenced && !isPrimitiveVoid(expr.getThen());
	internalToJavaStatement(expr.getThen(), b, canBeReferenced);
	if (canBeReferenced) {
		b.newLine();
		b.append(getVarName(expr, b));
		b.append(" = ");
		internalToConvertedExpression(expr.getThen(), b, getLightweightType(expr));
		b.append(";");
	}
	b.decreaseIndentation().newLine().append("}");
	if (expr.getElse() != null) {
		b.append(" else {").increaseIndentation();
		final boolean canElseBeReferenced = isReferenced && !isPrimitiveVoid(expr.getElse());
		internalToJavaStatement(expr.getElse(), b, canElseBeReferenced);
		if (canElseBeReferenced) {
			b.newLine();
			b.append(getVarName(expr, b));
			b.append(" = ");
			internalToConvertedExpression(expr.getElse(), b, getLightweightType(expr));
			b.append(";");
		}
		b.decreaseIndentation().newLine().append("}");
	}
}
 
Example #18
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void internalToConvertedExpression(XExpression obj, ITreeAppendable appendable) {
	if (obj instanceof XBlockExpression) {
		_toJavaExpression((XBlockExpression) obj, appendable);
	} else if (obj instanceof XCastedExpression) {
		_toJavaExpression((XCastedExpression) obj, appendable);
	} else if (obj instanceof XClosure) {
		_toJavaExpression((XClosure) obj, appendable);
	} else if (obj instanceof XAnnotation) {
		_toJavaExpression((XAnnotation) obj, appendable);
	} else if (obj instanceof XConstructorCall) {
		_toJavaExpression((XConstructorCall) obj, appendable);
	} else if (obj instanceof XIfExpression) {
		_toJavaExpression((XIfExpression) obj, appendable);
	} else if (obj instanceof XInstanceOfExpression) {
		_toJavaExpression((XInstanceOfExpression) obj, appendable);
	} else if (obj instanceof XSwitchExpression) {
		_toJavaExpression((XSwitchExpression) obj, appendable);
	} else if (obj instanceof XTryCatchFinallyExpression) {
		_toJavaExpression((XTryCatchFinallyExpression) obj, appendable);
	} else if (obj instanceof XListLiteral) {
		_toJavaExpression((XListLiteral) obj, appendable);
	} else if (obj instanceof XSetLiteral) {
		_toJavaExpression((XSetLiteral) obj, appendable);
	} else if (obj instanceof XSynchronizedExpression) {
		_toJavaExpression((XSynchronizedExpression) obj, appendable);
	} else if (obj instanceof XReturnExpression) {
		_toJavaExpression((XReturnExpression) obj, appendable);
	} else if (obj instanceof XThrowExpression) {
		_toJavaExpression((XThrowExpression) obj, appendable);
	} else {
		super.internalToConvertedExpression(obj, appendable);
	}
}
 
Example #19
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkTernaryExpressionUsed(XIfExpression exp) {
	if (exp.isConditionalExpression()) {
		//Check if this expression is nested in another already marked ternary expression
		EObject container = exp.eContainer();
		if (container instanceof XIfExpression && ((XIfExpression) container).isConditionalExpression()) {
			return;
		}
		//Raise issue
		addIssue("The ternary operator is not allowed. Use a normal if-expression.", exp, TERNARY_EXPRESSION_NOT_ALLOWED);
	}
}
 
Example #20
Source File: EarlyExitValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Check
public void checkDeadCode(XIfExpression condition) {
	if (!earlyExitComputer.isEarlyExit(condition.getIf())) {
		validateCondition(condition.getIf(), false);
	} else {
		if (!markAsDeadCode(condition.getThen())) {
			markAsDeadCode(condition.getElse());
		}
	}
}
 
Example #21
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private List<XExpression> collectIfParts(XIfExpression expression, List<XExpression> result) {
	result.add(expression.getIf());
	if (expression.getElse() instanceof XIfExpression) {
		collectIfParts((XIfExpression) expression.getElse(), result);
	}
	return result;
}
 
Example #22
Source File: XtendHoverSignatureProviderTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testAutcastExpressions() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package testPackage");
    _builder.newLine();
    _builder.append("class Foo {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def foo() {");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("val CharSequence c = \"\"");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("if (c instanceof String) {");
    _builder.newLine();
    _builder.append("\t\t\t");
    _builder.append("c.substring(1, 1)");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("switch(c){");
    _builder.newLine();
    _builder.append("\t\t\t");
    _builder.append("String : c.length");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtendFile xtendFile = this.parseHelper.parse(_builder, this.getResourceSet());
    XtendTypeDeclaration _head = IterableExtensions.<XtendTypeDeclaration>head(xtendFile.getXtendTypes());
    XtendMember _head_1 = IterableExtensions.<XtendMember>head(((XtendClass) _head).getMembers());
    final XtendFunction func = ((XtendFunction) _head_1);
    XExpression _expression = func.getExpression();
    final XBlockExpression block = ((XBlockExpression) _expression);
    final XExpression dec = IterableExtensions.<XExpression>head(block.getExpressions());
    Assert.assertEquals("CharSequence c", this.signatureProvider.getSignature(dec));
    XExpression _get = block.getExpressions().get(1);
    final XIfExpression ifexpr = ((XIfExpression) _get);
    final XExpression then = ifexpr.getThen();
    XExpression _head_2 = IterableExtensions.<XExpression>head(((XBlockExpression) then).getExpressions());
    final XExpression target = ((XMemberFeatureCall) _head_2).getMemberCallTarget();
    Assert.assertEquals("String c", this.signatureProvider.getSignature(target));
    XExpression _get_1 = block.getExpressions().get(2);
    final XSwitchExpression switchExpr = ((XSwitchExpression) _get_1);
    XExpression _then = IterableExtensions.<XCasePart>head(switchExpr.getCases()).getThen();
    final XExpression expr = ((XMemberFeatureCall) _then).getMemberCallTarget();
    Assert.assertEquals("String c", this.signatureProvider.getSignature(expr));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #23
Source File: XtendHoverSignatureProviderTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testAutcastExpressions_2() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package testPackage");
    _builder.newLine();
    _builder.append("class Foo {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("CharSequence c = \"\"");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def foo() {");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("if (c instanceof String) {");
    _builder.newLine();
    _builder.append("\t\t\t");
    _builder.append("c.substring(1, 1)");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("switch(c){");
    _builder.newLine();
    _builder.append("\t\t\t");
    _builder.append("String : c.length");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtendFile xtendFile = this.parseHelper.parse(_builder, this.getResourceSet());
    XtendTypeDeclaration _head = IterableExtensions.<XtendTypeDeclaration>head(xtendFile.getXtendTypes());
    Assert.assertEquals("CharSequence c", this.signatureProvider.getSignature(IterableExtensions.<XtendMember>head(((XtendClass) _head).getMembers())));
    XtendTypeDeclaration _head_1 = IterableExtensions.<XtendTypeDeclaration>head(xtendFile.getXtendTypes());
    XtendMember _get = ((XtendClass) _head_1).getMembers().get(1);
    final XtendFunction func = ((XtendFunction) _get);
    XExpression _expression = func.getExpression();
    final XBlockExpression block = ((XBlockExpression) _expression);
    XExpression _head_2 = IterableExtensions.<XExpression>head(block.getExpressions());
    final XIfExpression ifexpr = ((XIfExpression) _head_2);
    final XExpression then = ifexpr.getThen();
    XExpression _head_3 = IterableExtensions.<XExpression>head(((XBlockExpression) then).getExpressions());
    final XExpression target = ((XMemberFeatureCall) _head_3).getMemberCallTarget();
    Assert.assertEquals("String Foo.c", this.signatureProvider.getSignature(target));
    XExpression _get_1 = block.getExpressions().get(1);
    final XSwitchExpression switchExpr = ((XSwitchExpression) _get_1);
    XExpression _then = IterableExtensions.<XCasePart>head(switchExpr.getCases()).getThen();
    final XExpression expr = ((XMemberFeatureCall) _then).getMemberCallTarget();
    Assert.assertEquals("String Foo.c", this.signatureProvider.getSignature(expr));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #24
Source File: XtendHoverSignatureProviderTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testAutcastExpressions_3() {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("package testPackage");
    _builder.newLine();
    _builder.append("class Foo {");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("def foo(CharSequence c) {");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("if (c instanceof String) {");
    _builder.newLine();
    _builder.append("\t\t\t");
    _builder.append("c.substring(1, 1)");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("switch(c){");
    _builder.newLine();
    _builder.append("\t\t\t");
    _builder.append("String : c.length");
    _builder.newLine();
    _builder.append("\t\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("\t");
    _builder.append("}");
    _builder.newLine();
    _builder.append("}");
    _builder.newLine();
    final XtendFile xtendFile = this.parseHelper.parse(_builder, this.getResourceSet());
    XtendTypeDeclaration _head = IterableExtensions.<XtendTypeDeclaration>head(xtendFile.getXtendTypes());
    XtendMember _head_1 = IterableExtensions.<XtendMember>head(((XtendClass) _head).getMembers());
    final XtendFunction func = ((XtendFunction) _head_1);
    Assert.assertEquals("CharSequence c - foo(CharSequence)", this.signatureProvider.getSignature(IterableExtensions.<XtendParameter>head(func.getParameters())));
    XExpression _expression = func.getExpression();
    final XBlockExpression block = ((XBlockExpression) _expression);
    XExpression _head_2 = IterableExtensions.<XExpression>head(block.getExpressions());
    final XIfExpression ifexpr = ((XIfExpression) _head_2);
    final XExpression then = ifexpr.getThen();
    XExpression _head_3 = IterableExtensions.<XExpression>head(((XBlockExpression) then).getExpressions());
    final XExpression target = ((XMemberFeatureCall) _head_3).getMemberCallTarget();
    Assert.assertEquals("String c", this.signatureProvider.getSignature(target));
    XExpression _get = block.getExpressions().get(1);
    final XSwitchExpression switchExpr = ((XSwitchExpression) _get);
    XExpression _then = IterableExtensions.<XCasePart>head(switchExpr.getCases()).getThen();
    final XExpression expr = ((XMemberFeatureCall) _then).getMemberCallTarget();
    Assert.assertEquals("String c", this.signatureProvider.getSignature(expr));
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #25
Source File: StaticExtensionMethodImporter.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Returns true if the expression should be wrapped in ( )
 * in order to accept a static extension call.
 */
private boolean shouldWrap(final XExpression expression) {
  boolean _switchResult = false;
  boolean _matched = false;
  if (expression instanceof XMemberFeatureCall) {
    _matched=true;
  }
  if (!_matched) {
    if (expression instanceof XFeatureCall) {
      _matched=true;
    }
  }
  if (_matched) {
    _switchResult = false;
  }
  if (!_matched) {
    if (expression instanceof XAbstractFeatureCall) {
      _matched=true;
    }
    if (!_matched) {
      if (expression instanceof XSwitchExpression) {
        _matched=true;
      }
    }
    if (!_matched) {
      if (expression instanceof XTryCatchFinallyExpression) {
        _matched=true;
      }
    }
    if (!_matched) {
      if (expression instanceof XSynchronizedExpression) {
        _matched=true;
      }
    }
    if (!_matched) {
      if (expression instanceof XIfExpression) {
        _matched=true;
      }
    }
    if (_matched) {
      _switchResult = true;
    }
  }
  if (!_matched) {
    _switchResult = false;
  }
  return _switchResult;
}
 
Example #26
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testIfWithAdd() throws Exception {
	XBinaryOperation bo = (XBinaryOperation) expression("1 + if (foo) bar + 2");
	assertTrue(bo.getExplicitArguments().get(1) instanceof XIfExpression);
}
 
Example #27
Source File: ErrorTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testErrorModel_076() throws Exception {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("class C {");
  _builder.newLine();
  _builder.append("\t");
  _builder.append("def String m(boolean b) {");
  _builder.newLine();
  _builder.append("\t\t");
  _builder.append("switch \'a\' {");
  _builder.newLine();
  _builder.append("\t\t\t");
  _builder.append("case \'b\': \'a\'");
  _builder.newLine();
  _builder.append("\t\t\t");
  _builder.append("case \'c\': {");
  _builder.newLine();
  _builder.append("\t\t\t\t");
  _builder.append("if ");
  _builder.newLine();
  _builder.append("\t\t\t\t\t");
  _builder.append("return \'b\'");
  _builder.newLine();
  _builder.append("\t\t\t\t");
  _builder.append("else");
  _builder.newLine();
  _builder.append("\t\t\t\t\t");
  _builder.append("return \'c\'");
  _builder.newLine();
  _builder.append("\t\t\t");
  _builder.append("}");
  _builder.newLine();
  _builder.append("\t\t");
  _builder.append("}");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("}");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  final XtendFile file = this.processWithoutException(_builder);
  final IResolvedTypes resolvedTypes = this.typeResolver.resolveTypes(file);
  final XIfExpression ifExpression = IteratorExtensions.<XIfExpression>head(Iterators.<XIfExpression>filter(file.eAllContents(), XIfExpression.class));
  Assert.assertNull(ifExpression.getThen());
  Assert.assertNull(ifExpression.getElse());
  Assert.assertNotNull(resolvedTypes.getActualType(ifExpression));
}
 
Example #28
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testIfWithClosure() throws Exception {
	XIfExpression ie = (XIfExpression) expression("if (foo) [| if (bar) zonk else bar]");
	assertNull(ie.getElse());
}
 
Example #29
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testIf_2() throws Exception {
	XIfExpression ie = (XIfExpression) expression("if (foo) bar else if (baz) apa else bpa");
	XIfExpression nestedIf = (XIfExpression) ie.getElse();
	XFeatureCall bpa = (XFeatureCall) nestedIf.getElse();
	assertEquals("bpa",bpa.getConcreteSyntaxFeatureName());
}
 
Example #30
Source File: XtendImplicitReturnFinder.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
public void findImplicitReturns(final XExpression expression, final ImplicitReturnFinder.Acceptor acceptor) {
  if (expression instanceof AnonymousClass) {
    _findImplicitReturns((AnonymousClass)expression, acceptor);
    return;
  } else if (expression instanceof RichString) {
    _findImplicitReturns((RichString)expression, acceptor);
    return;
  } else if (expression instanceof XAbstractFeatureCall) {
    _findImplicitReturns((XAbstractFeatureCall)expression, acceptor);
    return;
  } else if (expression instanceof XBlockExpression) {
    _findImplicitReturns((XBlockExpression)expression, acceptor);
    return;
  } else if (expression instanceof XBooleanLiteral) {
    _findImplicitReturns((XBooleanLiteral)expression, acceptor);
    return;
  } else if (expression instanceof XCastedExpression) {
    _findImplicitReturns((XCastedExpression)expression, acceptor);
    return;
  } else if (expression instanceof XClosure) {
    _findImplicitReturns((XClosure)expression, acceptor);
    return;
  } else if (expression instanceof XCollectionLiteral) {
    _findImplicitReturns((XCollectionLiteral)expression, acceptor);
    return;
  } else if (expression instanceof XConstructorCall) {
    _findImplicitReturns((XConstructorCall)expression, acceptor);
    return;
  } else if (expression instanceof XIfExpression) {
    _findImplicitReturns((XIfExpression)expression, acceptor);
    return;
  } else if (expression instanceof XInstanceOfExpression) {
    _findImplicitReturns((XInstanceOfExpression)expression, acceptor);
    return;
  } else if (expression instanceof XNullLiteral) {
    _findImplicitReturns((XNullLiteral)expression, acceptor);
    return;
  } else if (expression instanceof XNumberLiteral) {
    _findImplicitReturns((XNumberLiteral)expression, acceptor);
    return;
  } else if (expression instanceof XStringLiteral) {
    _findImplicitReturns((XStringLiteral)expression, acceptor);
    return;
  } else if (expression instanceof XSwitchExpression) {
    _findImplicitReturns((XSwitchExpression)expression, acceptor);
    return;
  } else if (expression instanceof XSynchronizedExpression) {
    _findImplicitReturns((XSynchronizedExpression)expression, acceptor);
    return;
  } else if (expression instanceof XTryCatchFinallyExpression) {
    _findImplicitReturns((XTryCatchFinallyExpression)expression, acceptor);
    return;
  } else if (expression instanceof XTypeLiteral) {
    _findImplicitReturns((XTypeLiteral)expression, acceptor);
    return;
  } else if (expression != null) {
    _findImplicitReturns(expression, acceptor);
    return;
  } else if (expression == null) {
    _findImplicitReturns((Void)null, acceptor);
    return;
  } else {
    throw new IllegalArgumentException("Unhandled parameter types: " +
      Arrays.<Object>asList(expression, acceptor).toString());
  }
}