Java Code Examples for org.eclipse.xtext.xbase.typesystem.references.ITypeReferenceOwner#toLightweightTypeReference()

The following examples show how to use org.eclipse.xtext.xbase.typesystem.references.ITypeReferenceOwner#toLightweightTypeReference() . 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: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the unresolved string representation of the given type parameter. The simple names of
 * the type bounds are used. The string representation includes the bounds, except for
 * the upper bound {@link Object}. 
 */
protected String getTypeParameterAsString(JvmTypeParameter typeParameter) {
	StringBuilder b = new StringBuilder();
	b.append(typeParameter.getName());
	ITypeReferenceOwner referenceOwner = getState().getReferenceOwner();
	if(!typeParameter.getConstraints().isEmpty()) {
		boolean firstUpperBound = true;
		for(int j=0; j<typeParameter.getConstraints().size(); ++j) {
			JvmTypeConstraint constraint = typeParameter.getConstraints().get(j);
			LightweightTypeReference typeRef = referenceOwner.toLightweightTypeReference(constraint.getTypeReference());
			if(constraint instanceof JvmUpperBound) {
				if(typeRef.isType(Object.class))
					continue;
				if (firstUpperBound) {
					b.append(" extends ");
					firstUpperBound = false;
				} else {
					b.append(" & ");
				}
			} else 
				b.append(" super ");
			b.append(typeRef.getHumanReadableName());
		}
	}
	return b.toString();
}
 
Example 2
Source File: XtendValidator.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private void checkExceptions(EObject context, List<JvmTypeReference> exceptions, EReference reference) {
	Set<String> declaredExceptionNames = Sets.newHashSet();
	JvmTypeReference throwableType = getServices().getTypeReferences().getTypeForName(Throwable.class, context);
	if (throwableType == null) {
		return;
	}
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(getServices(), context);
	LightweightTypeReference throwableReference = owner.toLightweightTypeReference(throwableType);
	for(int i = 0; i < exceptions.size(); i++) {
		JvmTypeReference exception = exceptions.get(i);
		// throwables may not carry generics thus the raw comparison is sufficient
		if (exception.getType() != null && !exception.getType().eIsProxy()) {
			if(!throwableReference.isAssignableFrom(exception.getType()))
				error("No exception of type " + exception.getSimpleName() + " can be thrown; an exception type must be a subclass of Throwable",
						reference, i, EXCEPTION_NOT_THROWABLE);
			if(!declaredExceptionNames.add(exception.getQualifiedName()))
				error("Exception " + exception.getSimpleName() + " is declared twice", reference, i, EXCEPTION_DECLARED_TWICE);
		}
	}
}
 
Example 3
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 4
Source File: DispatchMethodCompileStrategy.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void generateActualDispatchCall(JvmOperation dispatchOperation, JvmOperation actualOperationToCall,
		ITreeAppendable a, ITypeReferenceOwner owner) {
	a.append(actualOperationToCall.getSimpleName()).append("(");
	Iterator<JvmFormalParameter> iter1 = dispatchOperation.getParameters().iterator();
	for (Iterator<JvmFormalParameter> iter2 = actualOperationToCall.getParameters().iterator(); iter2.hasNext();) {
		JvmFormalParameter p1 = iter1.next();
		JvmFormalParameter p2 = iter2.next();
		LightweightTypeReference type1 = owner.toLightweightTypeReference(p1.getParameterType());
		LightweightTypeReference type2 = owner.toLightweightTypeReference(p2.getParameterType());
		if (!type2.isAssignableFrom(type1, new TypeConformanceComputationArgument(true, false, true, true, false, false))) {
			a.append("(").append(type2.getWrapperTypeIfPrimitive()).append(")");
		}
		if (typeReferences.is(p2.getParameterType(), Void.class)) {
			a.append("null");
		} else {
			a.append(getVarName(p1, a));
		}
		if (iter2.hasNext()) {
			a.append(", ");
		}
	}
	a.append(")");
}
 
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 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 7
Source File: AbstractTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected LightweightTypeReference getTypeForName(Class<?> clazz, ITypeComputationState state) {
	JvmType type = findDeclaredType(clazz, state);
	ITypeReferenceOwner owner = state.getReferenceOwner();
	if (type == null) {
		return owner.newUnknownTypeReference(clazz.getName());
	}
	return owner.toLightweightTypeReference(type);
}
 
Example 8
Source File: AbstractTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @see #findDeclaredType(String, ITypeReferenceOwner)
 * @since 2.14
 */
protected LightweightTypeReference getTypeForName(String clazzName, ITypeComputationState state) {
	JvmType type = findDeclaredType(clazzName, state);
	ITypeReferenceOwner owner = state.getReferenceOwner();
	if (type == null) {
		return owner.newUnknownTypeReference(clazzName);
	}
	return owner.toLightweightTypeReference(type);
}
 
Example 9
Source File: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected LightweightTypeReference normalizedMultiType(ITypeReferenceOwner referenceOwner, JvmTypeReference ref) {
	LightweightTypeReference result = referenceOwner.toLightweightTypeReference(ref);
	if (result.isSynonym()) {
		List<LightweightTypeReference> components = result.getMultiTypeComponents();
		result = referenceOwner.getServices().getTypeConformanceComputer().getCommonSuperType(components, referenceOwner);
	}
	return result;
}
 
Example 10
Source File: LogicalContainerAwareReentrantTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void prepareMembers(ResolvedTypes resolvedTypes, IFeatureScopeSession featureScopeSession, JvmDeclaredType type, Map<JvmIdentifiableElement, ResolvedTypes> resolvedTypesByType) {
	IFeatureScopeSession childSession = addExtensionsToMemberSession(resolvedTypes, featureScopeSession, type);
	
	StackedResolvedTypes childResolvedTypes = declareTypeParameters(resolvedTypes, type, resolvedTypesByType);
	
	JvmTypeReference superType = getExtendedClass(type);
	ITypeReferenceOwner referenceOwner = childResolvedTypes.getReferenceOwner();
	if (superType != null) {
		LightweightTypeReference lightweightSuperType = referenceOwner.toLightweightTypeReference(superType);
		childResolvedTypes.reassignTypeWithoutMerge(superType.getType(), lightweightSuperType);
		/* 
		 * We use reassignType to make sure that the following works:
		 *
		 * StringList extends AbstractList<String> {
		 *   NestedIntList extends AbstractList<Integer> {
		 *   }
		 *   SubType extends StringList {}
		 * }
		 */
	}
	LightweightTypeReference lightweightThisType = referenceOwner.toLightweightTypeReference(type);
	childResolvedTypes.reassignTypeWithoutMerge(type, lightweightThisType);
	
	List<JvmMember> members = type.getMembers();
	int size = members.size();
	for(int i = 0; i < size; i++) {
		doPrepare(childResolvedTypes, childSession, members.get(i), resolvedTypesByType);
	}
}
 
Example 11
Source File: AbstractLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected List<LightweightTypeReference> getSyntacticTypeArguments() {
	List<LightweightTypeReference> result = Lists.newArrayList();
	List<JvmTypeReference> typeArguments = getPlainSyntacticTypeArguments();
	ITypeReferenceOwner referenceOwner = getState().getReferenceOwner();
	for(int i = 0, size = typeArguments.size(); i < size; i++) {
		LightweightTypeReference typeArgument = referenceOwner.toLightweightTypeReference(typeArguments.get(i));
		result.add(typeArgument);
	}
	return result;
}
 
Example 12
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private CandidateCompareResult compareDeclaredParameterTypes(AbstractPendingLinkingCandidate<?> right) {
	if(getFeature() instanceof JvmExecutable && right.getFeature() instanceof JvmExecutable) {
		List<JvmFormalParameter> parameters = ((JvmExecutable) getFeature()).getParameters();
		List<JvmFormalParameter> rightParameters = ((JvmExecutable) right.getFeature()).getParameters();
		if (parameters.size() == rightParameters.size()) {
			int result = 0;
			ITypeReferenceOwner leftReferenceOwner = getState().getReferenceOwner();
			ITypeReferenceOwner rightReferenceOwner = right.getState().getReferenceOwner();
			TypeParameterByConstraintSubstitutor substitutor = new TypeParameterByConstraintSubstitutor(getDeclaratorParameterMapping(), leftReferenceOwner);
			TypeParameterByConstraintSubstitutor rightSubstitutor = new TypeParameterByConstraintSubstitutor(right.getDeclaratorParameterMapping(), right.getState().getReferenceOwner());
			for(int i = 0; i < parameters.size(); i++) {
				LightweightTypeReference parameterType = leftReferenceOwner.toLightweightTypeReference(parameters.get(i).getParameterType());
				LightweightTypeReference rightParameterType = rightReferenceOwner.toLightweightTypeReference(rightParameters.get(i).getParameterType());
				if (!parameterType.isResolved() || !rightParameterType.isResolved()) {
					result += compareDeclaredTypes(
							substitutor.substitute(parameterType),
							rightSubstitutor.substitute(rightParameterType),
							false,
							false);
				}
			}
			if (result == 0) {
				return CandidateCompareResult.AMBIGUOUS;
			} else if (result < 0) {
				return CandidateCompareResult.THIS;
			} else {
				return getExpectedTypeCompareResultOther(right);
			}
		}
	}
	return CandidateCompareResult.AMBIGUOUS;
}
 
Example 13
Source File: AbstractResolvedFeature.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected LightweightTypeReference getResolvedReference(/* @Nullable */ JvmTypeReference unresolved) {
	ITypeReferenceOwner owner = getContextType().getOwner();
	if (unresolved == null) {
		return owner.newReferenceToObject();
	}
	LightweightTypeReference unresolvedLightweight = owner.toLightweightTypeReference(unresolved);
	if (unresolvedLightweight.isPrimitive() || unresolvedLightweight.isPrimitiveVoid())
		return unresolvedLightweight;
	TypeParameterSubstitutor<?> substitutor = getSubstitutor();
	LightweightTypeReference result = substitutor.substitute(unresolvedLightweight);
	return result;
}
 
Example 14
Source File: OverrideHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public JvmOperation findOverriddenOperation(JvmOperation operation) {
	if (operation.getVisibility() == JvmVisibility.PRIVATE) {
		return null;
	}
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, operation.eResource().getResourceSet());
	LightweightTypeReference declaringType = owner.toLightweightTypeReference(operation.getDeclaringType());
	TypeParameterSubstitutor<?> substitutor = createSubstitutor(owner, declaringType);
	return findOverriddenOperation(operation, declaringType, substitutor, owner, new ContextualVisibilityHelper(visibilityHelper, declaringType));
}
 
Example 15
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Check
public void checkInstanceOfOrder(XIfExpression expression) {
	if (isIgnored(IssueCodes.UNREACHABLE_IF_BLOCK)) {
		return;
	}
	if (expression.eContainer() instanceof XIfExpression) {
		XIfExpression container = (XIfExpression) expression.eContainer();
		if (container.getElse() == expression) {
			return;
		}
	}
	List<XExpression> ifParts = collectIfParts(expression, new ArrayList<XExpression>());
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(getServices(), expression);
	Multimap<JvmIdentifiableElement, LightweightTypeReference> previousTypeReferences = HashMultimap.create();
	for (XExpression ifPart : ifParts) {
		if (!(ifPart instanceof XInstanceOfExpression)) {
			continue;
		}
		XInstanceOfExpression instanceOfExpression = (XInstanceOfExpression) ifPart;
		if (!(instanceOfExpression.getExpression() instanceof XAbstractFeatureCall)) {
			continue;
		}
		XAbstractFeatureCall featureCall = (XAbstractFeatureCall) instanceOfExpression.getExpression();
		JvmIdentifiableElement feature = featureCall.getFeature();
		if (!(feature instanceof XVariableDeclaration)
				&& !(feature instanceof JvmField)
				&& !(feature instanceof JvmFormalParameter)) {
			continue;
		}
		JvmTypeReference type = instanceOfExpression.getType();
		LightweightTypeReference actualType = owner.toLightweightTypeReference(type);
		if (actualType == null) {
			continue;
		}
		if (isHandled(actualType, previousTypeReferences.get(feature))) {
			addIssue("Unreachable code: The if condition can never match. It is already handled by a previous condition.", type, IssueCodes.UNREACHABLE_IF_BLOCK);
			continue;
		}
		previousTypeReferences.put(feature, actualType);
	}
}
 
Example 16
Source File: AbstractPendingLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected boolean validateUnhandledExceptions(JvmExecutable executable, IAcceptor<? super AbstractDiagnostic> result) {
	TypeParameterSubstitutor<?> substitutor = createArgumentTypeSubstitutor();
	List<LightweightTypeReference> unhandledExceptions = null;
	List<LightweightTypeReference> expectedExceptions = getState().getExpectedExceptions();
	ITypeReferenceOwner referenceOwner = getState().getReferenceOwner();
	outer: for(JvmTypeReference typeReference: executable.getExceptions()) {
		LightweightTypeReference exception = referenceOwner.toLightweightTypeReference(typeReference);
		LightweightTypeReference resolvedException = substitutor.substitute(exception);
		if (resolvedException.isSubtypeOf(Throwable.class) && !resolvedException.isSubtypeOf(RuntimeException.class) && !resolvedException.isSubtypeOf(Error.class)) {
			for (LightweightTypeReference expectedException : expectedExceptions) {
				if (expectedException.isAssignableFrom(resolvedException)) {
					continue outer;
				}
			}
			if (unhandledExceptions == null) {
				unhandledExceptions = Lists.newArrayList(resolvedException);
			} else {
				unhandledExceptions.add(resolvedException);
			}
		}
	}
	if (unhandledExceptions != null) {
		String message = null;
		int count = unhandledExceptions.size();
		if (count > 1) {
			message = String.format("Unhandled exception types %s and %s", 
					IterableExtensions.join(unhandledExceptions.subList(0, count - 1), ", "),
					unhandledExceptions.get(count - 1));
		} else {
			message = String.format("Unhandled exception type %s", unhandledExceptions.get(0).getHumanReadableName());
		}
		String[] data = new String[unhandledExceptions.size() + 1];
		for(int i = 0; i < data.length - 1; i++) {
			LightweightTypeReference unhandled = unhandledExceptions.get(i);
			data[i] = EcoreUtil.getURI(unhandled.getType()).toString();
		}
		data[data.length - 1] = EcoreUtil.getURI(getExpression()).toString();
		AbstractDiagnostic diagnostic = new EObjectDiagnosticImpl(
				getUnhandledExceptionSeverity(executable), 
				IssueCodes.UNHANDLED_EXCEPTION,
				message, 
				getExpression(),
				getDefaultValidationFeature(), 
				-1, 
				data);
		result.accept(diagnostic);
		return false;
	}
	return true;
}
 
Example 17
Source File: OverrideHelper.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Returns the resolved features targeting a specific Java version in order to support new language features.
 */
public ResolvedFeatures getResolvedFeatures(JvmDeclaredType type, JavaVersion targetVersion) {
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, type.eResource().getResourceSet());
	LightweightTypeReference contextType = owner.toLightweightTypeReference(type);
	return getResolvedFeatures(contextType, targetVersion);
}
 
Example 18
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected LightweightTypeReference getClosureOperationParameterType(LightweightTypeReference closureType, JvmOperation operation, int i) {
	ITypeReferenceOwner owner = newTypeReferenceOwner(operation);
	Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> mapping = new DeclaratorTypeArgumentCollector().getTypeParameterMapping(closureType);
	LightweightTypeReference parameterType = owner.toLightweightTypeReference(operation.getParameters().get(i).getParameterType());
	return new StandardTypeParameterSubstitutor(mapping, owner).substitute(parameterType);
}
 
Example 19
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected LightweightTypeReference getClosureOperationReturnType(LightweightTypeReference closureType, JvmOperation operation) {
	ITypeReferenceOwner owner = newTypeReferenceOwner(operation);
	Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> mapping = new DeclaratorTypeArgumentCollector().getTypeParameterMapping(closureType);
	LightweightTypeReference parameterType = owner.toLightweightTypeReference(operation.getReturnType());
	return new StandardTypeParameterSubstitutor(mapping, owner).substitute(parameterType);
}
 
Example 20
Source File: OverrideHelper.java    From xtext-extras with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Returns the resolved features that are defined in the given <code>type</code> and its supertypes.
 * Considers private methods of super types, too.
 * @param type the type. Has to be contained in a resource.
 * @return the resolved features. 
 */
public ResolvedFeatures getResolvedFeatures(JvmDeclaredType type) {
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, type.eResource().getResourceSet());
	LightweightTypeReference contextType = owner.toLightweightTypeReference(type);
	return getResolvedFeatures(contextType);
}