org.eclipse.xtext.xbase.XSwitchExpression Java Examples

The following examples show how to use org.eclipse.xtext.xbase.XSwitchExpression. 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: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected String declareLocalVariable(XSwitchExpression expr, ITreeAppendable b) {
	// declare local var for the switch expression
	String variableName = getSwitchLocalVariableName(expr, b); 
	if (variableName != null) {
		return variableName;
	}
	String name = createSwitchLocalVariableName(expr);
	JvmTypeReference variableType = getSwitchLocalVariableType(expr);
	b.newLine().append("final ");
	serialize(variableType, expr, b);
	b.append(" ");
	variableName = declareAndAppendSwitchSyntheticLocalVariable(expr, name, b);
	b.append(" = ");
	internalToJavaExpression(expr.getSwitch(), b);
	b.append(";");
	return variableName;
}
 
Example #2
Source File: XSwitchExpressions.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public boolean isJavaCaseExpression(XSwitchExpression it, XCasePart casePart) {
	if (casePart.getTypeGuard() != null) {
		return false;
	}
	XExpression caseExpression = casePart.getCase();
	if (caseExpression == null) {
		return false;
	}
	IResolvedTypes resolvedTypes = batchTypeResolver.resolveTypes(it);
	LightweightTypeReference caseType = resolvedTypes.getActualType(caseExpression);
	if (caseType == null) {
		return false;
	}
	LightweightTypeReference switchType = getSwitchVariableType(it);
	if (!switchType.isAssignableFrom(caseType)) {
		return false;
	}
	return true;
}
 
Example #3
Source File: XSwitchExpressions.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Determine whether the given switch expression is valid for Java version 7
 * or higher.
 */
public boolean isJava7SwitchExpression(XSwitchExpression it) {
	LightweightTypeReference switchType = getSwitchVariableType(it);
	if (switchType == null) {
		return false;
	}
	if (switchType.isSubtypeOf(Integer.TYPE)) {
		return true;
	}
	if (switchType.isSubtypeOf(Enum.class)) {
		return true;
	}
	if (switchType.isSubtypeOf(String.class)) {
		return true;
	}
	return false;
}
 
Example #4
Source File: SerializerScopeProvider.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public IScope createFeatureCallSerializationScope(EObject context) {
	if (!(context instanceof XAbstractFeatureCall)) {
		return IScope.NULLSCOPE;
	}
	XAbstractFeatureCall call = (XAbstractFeatureCall) context;
	JvmIdentifiableElement feature = call.getFeature();
	// this and super - logical container aware FeatureScopes
	if (feature instanceof JvmType) {
		return getTypeScope(call, (JvmType) feature);
	}
	if (feature instanceof JvmConstructor) {
		return getThisOrSuperScope(call, (JvmConstructor) feature);
	}
	if (feature instanceof JvmExecutable) {
		return getExecutableScope(call, feature);
	}
	if (feature instanceof JvmFormalParameter || feature instanceof JvmField || feature instanceof XVariableDeclaration || feature instanceof XSwitchExpression) {
		return new SingletonScope(EObjectDescription.create(feature.getSimpleName(), feature), IScope.NULLSCOPE);
	}
	return IScope.NULLSCOPE;
}
 
Example #5
Source File: XSwitchExpressions.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public XExpression getThen(XCasePart casePart, XSwitchExpression switchExpression) {
	XExpression then = casePart.getThen();
	if (then != null) {
		return then;
	}
	int casePartIndex = switchExpression.getCases().indexOf(casePart);
	if (casePartIndex == -1) {
		return null;
	}
	int count = switchExpression.getCases().size();
	if (casePartIndex == count - 1) {
		return switchExpression.getDefault();
	}
	if (casePartIndex + 1 < count) {
		return getThen(switchExpression.getCases().get(casePartIndex + 1), switchExpression);
	}
	return null;
}
 
Example #6
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected ILocationData getLocationOfDefault(XSwitchExpression expression) {
	final ICompositeNode startNode = NodeModelUtils.getNode(expression);
	if (startNode != null) {
		List<INode> resultNodes = Lists.newArrayList();
		boolean defaultSeen = false;
		for (INode child : startNode.getChildren()) {
			if (defaultSeen) {
				resultNodes.add(child);
				if (GrammarUtil.containingAssignment(child.getGrammarElement()) != null) {
					break;
				}
			} else if (child.getGrammarElement() instanceof Keyword && "default".equals(child.getText())) {
				defaultSeen = true;
				resultNodes.add(child);
			}
		}
		return toLocationData(resultNodes);
	}
	return null;
}
 
Example #7
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected String getSwitchLocalVariableName(XSwitchExpression expr, ITreeAppendable b) {
	JvmFormalParameter declaredParam = expr.getDeclaredParam();
	if (declaredParam != null) {
		if (b.hasName(declaredParam)) {
			return b.getName(declaredParam);
		}
		return null;
	}
	XExpression switchExpression = expr.getSwitch();
	if (b.hasName(switchExpression)) {
		return b.getName(switchExpression);
	} 
	if (switchExpression instanceof XFeatureCall) {
		XFeatureCall featureCall = (XFeatureCall) switchExpression;
		JvmIdentifiableElement feature = featureCall.getFeature();
		if (b.hasName(feature)) {
			return b.getName(feature);
		}
	}
	return null;
}
 
Example #8
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkTypeGuardsOrderWithGenerics(XSwitchExpression expression) {
	if (isIgnored(IssueCodes.UNREACHABLE_CASE)) {
		return;
	}
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(getServices(), expression);
	List<LightweightTypeReference> previousTypeReferences = new ArrayList<LightweightTypeReference>();
	for (XCasePart casePart : expression.getCases()) {
		JvmTypeReference typeGuard = casePart.getTypeGuard();
		if (typeGuard == null) {
			continue;
		}
		LightweightTypeReference typeReference = owner.toLightweightTypeReference(typeGuard);
		LightweightTypeReference actualType = typeReference.getRawTypeReference();
		if (actualType == null || typeReference == actualType) {
			continue;
		}
		if (isHandled(actualType, previousTypeReferences)) {
			addIssue("Unreachable code: The case can never match. It is already handled by a previous condition (with the same type erasure).", typeGuard, IssueCodes.UNREACHABLE_CASE);
			continue;
		}
		if (casePart.getCase() == null) {
			previousTypeReferences.add(actualType);
		}
	}
}
 
Example #9
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Check
public void checkTypeGuardsOrder(XSwitchExpression expression) {
	if (isIgnored(IssueCodes.UNREACHABLE_CASE)) {
		return;
	}
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(getServices(), expression);
	List<LightweightTypeReference> previousTypeReferences = new ArrayList<LightweightTypeReference>();
	for (XCasePart casePart : expression.getCases()) {
		JvmTypeReference typeGuard = casePart.getTypeGuard();
		if (typeGuard == null) {
			continue;
		}
		LightweightTypeReference actualType = owner.toLightweightTypeReference(typeGuard);
		if (actualType == null) {
			continue;
		}
		if (isHandled(actualType, previousTypeReferences)) {
			addIssue("Unreachable code: The case can never match. It is already handled by a previous condition.", typeGuard, IssueCodes.UNREACHABLE_CASE);
			continue;
		}
		if (casePart.getCase() == null) {
			previousTypeReferences.add(actualType);
		}
	}
}
 
Example #10
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Determine whether the given switch expression should be compiled to a Java switch for Java version 7 or higher.
 */
protected boolean isCompiledToJava7Switch(XSwitchExpression expr) {
	// NOTE: This method could be merged with #isCompiledToJavaSwitch(XSwitchExpression)
	if (!switchExpressions.isJava7SwitchExpression(expr)) {
		return false;
	}
	for (XCasePart casePart : expr.getCases()) {
		if (!switchExpressions.isJavaCaseExpression(expr, casePart)) {
			return false;
		}
		if (!switchExpressions.isConstant(casePart)) {
			return false;
		}
	}
	return true;
}
 
Example #11
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean allCasesAreExitedEarly(XSwitchExpression expr) {
	for(XCasePart casePart: expr.getCases()) {
		if(casePart.getThen() != null && !isEarlyExit(casePart.getThen())) {
			return false;
		}
	}
	return true;
}
 
Example #12
Source File: AbstractXbaseLinkingTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSwitchExpression_02() throws Exception {
	XSwitchExpression switchExpr = (XSwitchExpression) expression(
			"switch x : new Object() { " +
			"    case true : true "+
			"    default : x" +
			"}");
	assertEquals(switchExpr.getDeclaredParam(), ((XFeatureCall)switchExpr.getDefault()).getFeature());
}
 
Example #13
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
/* @Nullable */
protected String getReferenceName(XExpression expr, ITreeAppendable b) {
	if (expr instanceof XSwitchExpression) {
		Object key = getSwitchExpressionKey((XSwitchExpression) expr);
		if (b.hasName(key))
			return b.getName(key);
	}
	return super.getReferenceName(expr, b);
}
 
Example #14
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void _toJavaExpression(XSwitchExpression expr, ITreeAppendable b) {
	final String referenceName = getReferenceName(expr, b);
	if (referenceName != null)
		b.trace(expr, false).append(referenceName);
	else
		throw new IllegalStateException("Switch expression wasn't translated to Java statements before.");
}
 
Example #15
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Determine whether the given switch expression should be compiled to a Java switch for Java version 6 or lower. 
 */
protected boolean isCompiledToJavaSwitch(XSwitchExpression expr) {
	if (!switchExpressions.isJavaSwitchExpression(expr)) {
		return false;
	}
	for (XCasePart casePart : expr.getCases()) {
		if (!switchExpressions.isJavaCaseExpression(expr, casePart)) {
			return false;
		}
		if (!switchExpressions.isConstant(casePart)) {
			return false;
		}
	}
	return true;
}
 
Example #16
Source File: AbstractXbaseLinkingTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSwitchExpression_03() throws Exception {
	XSwitchExpression switchExpr = (XSwitchExpression) expression(
			"switch x : 'foo' as CharSequence {" +
			"  Comparable : x.toString()" +
			"}");
	XMemberFeatureCall then = (XMemberFeatureCall) switchExpr.getCases().get(0).getThen();
	assertEquals("java.lang.CharSequence.toString()", then.getFeature().getIdentifier());
}
 
Example #17
Source File: XbaseQuickfixProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Fix(IssueCodes.REDUNDANT_CASE)
public void fixRedundantCase(final Issue issue, IssueResolutionAcceptor acceptor) {
	acceptor.accept(issue, "Remove redundant case.", "Remove redundant case.", null, new ReplaceModification(issue,
			""));
	acceptor.accept(issue, "Assign empty expression.", "Assign empty expression.", null,
			new ISemanticModification() {

				@Override
				public void apply(EObject element, IModificationContext context) throws Exception {
					XSwitchExpression switchExpression = EcoreUtil2.getContainerOfType(element,
							XSwitchExpression.class);
					if (switchExpression == null) {
						return;
					}
					XCasePart casePart = IterableExtensions.last(switchExpression.getCases());
					if (casePart == null || !(casePart.isFallThrough() && casePart.getThen() == null)) {
						return;
					}
					List<INode> nodes = NodeModelUtils.findNodesForFeature(casePart,
							XbasePackage.Literals.XCASE_PART__FALL_THROUGH);
					if (nodes.isEmpty()) {
						return;
					}
					INode firstNode = IterableExtensions.head(nodes);
					INode lastNode = IterableExtensions.last(nodes);
					int offset = firstNode.getOffset();
					int length = lastNode.getEndOffset() - offset;
					ReplacingAppendable appendable = appendableFactory.create(context.getXtextDocument(),
							(XtextResource) element.eResource(), offset, length);
					appendable.append(": {");
					appendable.increaseIndentation().newLine();
					appendable.decreaseIndentation().newLine().append("}");
					appendable.commitChanges();
				}

			});
}
 
Example #18
Source File: XSwitchExpressions.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Determine whether the given switch expression is valid for Java version 6
 * or lower.
 */
public boolean isJavaSwitchExpression(XSwitchExpression it) {
	LightweightTypeReference switchType = getSwitchVariableType(it);
	if (switchType == null) {
		return false;
	}
	if (switchType.isSubtypeOf(Integer.TYPE)) {
		return true;
	}
	if (switchType.isSubtypeOf(Enum.class)) {
		return true;
	}
	return false;
}
 
Example #19
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected String createSwitchLocalVariableName(XSwitchExpression expr) {
	String name = getSwitchLocalVariableSimpleName(expr);
	if (name != null) { 
		return makeJavaIdentifier(name);
	}
	// define synthetic name
	return "_switchValue";
}
 
Example #20
Source File: XbaseImplicitReturnFinder.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void _findImplicitReturns(final XSwitchExpression expression, final ImplicitReturnFinder.Acceptor acceptor) {
  final Consumer<XCasePart> _function = (XCasePart it) -> {
    this.findImplicitReturns(it.getThen(), acceptor);
  };
  expression.getCases().forEach(_function);
  this.findImplicitReturns(expression.getDefault(), acceptor);
}
 
Example #21
Source File: AbstractXbaseLinkingTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSwitchExpression_01() throws Exception {
	XSwitchExpression switchExpr = (XSwitchExpression) expression(
			"switch x : new Object() { " +
			"   case x : x" +
	"}");
	final XCasePart xCasePart = switchExpr.getCases().get(0);
	assertEquals(switchExpr.getDeclaredParam(), ((XFeatureCall) xCasePart.getThen()).getFeature());
	assertEquals(switchExpr.getDeclaredParam(), ((XFeatureCall) xCasePart.getCase()).getFeature());
}
 
Example #22
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 #23
Source File: XbaseTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testTypeGuardedCase_1() throws Exception {
	XSwitchExpression expression = (XSwitchExpression) expression("switch s: '' as CharSequence { Cloneable: s String: s }", true);
	assertEquals("java.lang.CharSequence", toString(getType(expression.getSwitch())));
	assertEquals("java.lang.CharSequence & java.lang.Cloneable", toString(getType(expression.getCases().get(0).getThen())));
	assertEquals("java.lang.String", toString(getType(expression.getCases().get(1).getThen())));
	assertEquals("java.lang.CharSequence", toString(getType(expression)));
}
 
Example #24
Source File: XbaseTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testTypeGuardedCase_0() throws Exception {
		XSwitchExpression expression = (XSwitchExpression) expression("switch  s: new Object() { String: s StringBuffer: s}", true);
//		assertEquals("java.lang.Object", toString(typeProvider.getType(expression.getSwitch())));
//		assertEquals("java.lang.String", toString(typeProvider.getType(expression.getCases().get(0).getThen())));
//		assertEquals("java.lang.StringBuffer", toString(typeProvider.getType(expression.getCases().get(1).getThen())));
		if (isJava11OrLater()) {
			assertEquals("java.io.Serializable & java.lang.Comparable<? extends java.lang.Object> & java.lang.CharSequence", toString(getType(expression)));
		} else{
			assertEquals("java.io.Serializable & java.lang.CharSequence", toString(getType(expression)));
		}
	}
 
Example #25
Source File: XbaseExpectedTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSwitchExpression_1() throws Exception {
	XSwitchExpression exp = (XSwitchExpression) expressionWithExpectedType(
			"switch true {" +
			"  java.lang.Boolean case null : null" +
			"  default : null" +
			"}", "String");
	for (XCasePart cp : exp.getCases()) {
		assertExpected(null, cp.getCase());
		assertExpected("java.lang.String", cp.getThen());
	}
	assertExpected("java.lang.String", exp.getDefault());
}
 
Example #26
Source File: XbaseExpectedTypeProviderTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSwitchExpression_0() throws Exception {
	XSwitchExpression exp = (XSwitchExpression) expressionWithExpectedType(
			"switch null {" +
			"  java.lang.Boolean case null : null" +
			"  default : null" +
			"}", "String");
	assertExpected(null,exp.getSwitch());
	for (XCasePart cp : exp.getCases()) {
		assertExpected(null, cp.getCase());
		assertExpected("java.lang.String", cp.getThen());
	}
	assertExpected("java.lang.String", exp.getDefault());
}
 
Example #27
Source File: XbaseShufflingInjectorProvider.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected List<XCasePart> getCases(XSwitchExpression switchExpression) {
	List<XCasePart> result = super.getCases(switchExpression);
	for(XCasePart casePart: result) {
		if (casePart.getThen() == null) {
			return result;
		}
	}
	return Lists.reverse(result);
}
 
Example #28
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSwitch_0() throws Exception {
	XSwitchExpression se = (XSwitchExpression) expression("switch true { case 1==0 : '1' }");
	assertNull(se.getDefault());
	assertEquals(1, se.getCases().size());
	assertNotNull(se.getSwitch());
	XCasePart casePart = se.getCases().get(0);
	assertTrue(casePart.getCase() instanceof XBinaryOperation);
	assertTrue(casePart.getThen() instanceof XStringLiteral);
}
 
Example #29
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test public void testSwitch_1() throws Exception {
	XSwitchExpression se = (XSwitchExpression) expression("switch number{case 1:'1' case 2:'2' default:'3'}");
	assertTrue(se.getDefault() instanceof XStringLiteral);
	assertEquals(2, se.getCases().size());
	assertTrue(se.getSwitch() instanceof XFeatureCall);

	XCasePart case1 = se.getCases().get(0);
	assertEquals("1", ((XNumberLiteral) case1.getCase()).getValue());
	assertTrue(case1.getThen() instanceof XStringLiteral);

	XCasePart case2 = se.getCases().get(1);
	assertEquals("2", ((XNumberLiteral) case2.getCase()).getValue());
	assertTrue(case2.getThen() instanceof XStringLiteral);
}
 
Example #30
Source File: XbaseParserTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void doTestSwitch_2(XSwitchExpression se) {
	assertEquals(2,se.getCases().size());
	assertNull(se.getDefault());
	XCasePart c1 = se.getCases().get(0);
	assertEquals("java.lang.String",c1.getTypeGuard().getIdentifier());
	assertFeatureCall("length",c1.getCase());
	assertFeatureCall("foo",((XMemberFeatureCall)c1.getCase()).getMemberCallTarget());
	assertFeatureCall("bar",c1.getThen());
	
	XCasePart c2 = se.getCases().get(1);
	assertEquals("java.lang.String",c2.getTypeGuard().getIdentifier());
	assertNull(c2.getCase());
	assertFeatureCall("baz",((XBlockExpression)c2.getThen()).getExpressions().get(0));
}