Java Code Examples for org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference#isAssignableFrom()

The following examples show how to use org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference#isAssignableFrom() . 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: OverrideTester.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void addExceptionDetails(AbstractResolvedOperation overriding, AbstractResolvedOperation overridden,
		EnumSet<OverrideCheckDetails> result) {
	List<LightweightTypeReference> exceptions = overriding.getResolvedExceptions();
	if (exceptions.isEmpty()) {
		return;
	}
	List<LightweightTypeReference> inheritedExceptions = overridden.getResolvedExceptions();
	for(LightweightTypeReference exception: exceptions) {
		if (!exception.isSubtypeOf(RuntimeException.class) && !exception.isSubtypeOf(Error.class)) {
			boolean isDeclared = false;
			for(LightweightTypeReference inheritedException: inheritedExceptions) {
				if (inheritedException.isAssignableFrom(exception)) {
					isDeclared = true;
					break;
				}
			}
			if (!isDeclared) {
				result.add(OverrideCheckDetails.EXCEPTION_MISMATCH);
				return;
			}
		}
	}
}
 
Example 2
Source File: CollectionLiteralsTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a collection type reference that comes as close as possible / necessary to its expected type.
 */
protected LightweightTypeReference createCollectionTypeReference(JvmGenericType collectionType, LightweightTypeReference elementType, LightweightTypeReference expectedType, ITypeReferenceOwner owner) {
	ParameterizedTypeReference result = new ParameterizedTypeReference(owner, collectionType);
	result.addTypeArgument(elementType);
	if (isIterableExpectation(expectedType) && !expectedType.isAssignableFrom(result)) {
		// avoid to assign a set literal to a list and viceversa:
		// at least the raw types must be assignable
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=498779
		if (expectedType.getRawTypeReference().isAssignableFrom(result.getRawTypeReference())) {
			LightweightTypeReference expectedElementType = getElementOrComponentType(expectedType, owner);
			if (matchesExpectation(elementType, expectedElementType)) {
				return expectedType;
			}
		}
	}
	return result;
}
 
Example 3
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 4
Source File: FeatureLinkHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public LightweightTypeReference getExpectedReceiverType(JvmIdentifiableElement linkedFeature, LightweightTypeReference receiverType) {
	if (receiverType.isMultiType() && linkedFeature instanceof JvmMember) {
		LightweightTypeReference declaratorReference = receiverType.getOwner().newParameterizedTypeReference(((JvmMember) linkedFeature).getDeclaringType());
		if (!declaratorReference.isAssignableFrom(receiverType.toJavaType())) {
			for(LightweightTypeReference multiTypeComponent: receiverType.getMultiTypeComponents()) {
				if (declaratorReference.isAssignableFrom(multiTypeComponent)) {
					return multiTypeComponent;
				}
			}
		} else {
			return declaratorReference;
		}
	} else if (receiverType.isSynonym() && linkedFeature instanceof JvmMember) {
		List<LightweightTypeReference> components = receiverType.getMultiTypeComponents();
		return components.get(components.size() - 1);
	}
	return receiverType;
}
 
Example 5
Source File: CollectionLiteralsTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Same as {@link LightweightTypeReference#isSubtypeOf(Class)} but does not accept synonym types as subtypes.
 */
protected boolean isSubtypeButNotSynonym(LightweightTypeReference expectation, Class<?> clazz) {
	if (expectation.isType(clazz)) {
		return true;
	}
	ITypeReferenceOwner owner = expectation.getOwner();
	JvmType declaredType = owner.getServices().getTypeReferences().findDeclaredType(clazz, owner.getContextResourceSet());
	if (declaredType == null) {
		return false;
	}
	LightweightTypeReference superType = owner.newParameterizedTypeReference(declaredType);
	// don't allow synonyms, e.g. Iterable is not considered to be a supertype of Functions.Function0
	boolean result = superType.isAssignableFrom(expectation.getRawTypeReference(), 
			new TypeConformanceComputationArgument(false, false, true, true, false, false));
	return result;
}
 
Example 6
Source File: CastOperatorLinkingCandidate.java    From sarl with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("checkstyle:magicnumber")
private static int computeCompliance(LightweightTypeReference target, LightweightTypeReference current) {
	if (isSame(target, current)) {
		return 0;
	}
	final LightweightTypeReference target2 = target.getWrapperTypeIfPrimitive();
	if (target2.isSubtypeOf(Number.class)) {
		final LightweightTypeReference current2 = current.getWrapperTypeIfPrimitive();
		if (current2.isSubtypeOf(Number.class)) {
			return 1 + Math.max(getNumberPrecision(target) - getNumberPrecision(current), 0);
		}
		if (target.isAssignableFrom(current)) {
			return 8;
		}
		return 9;
	}
	if (target.isAssignableFrom(current)) {
		return 1;
	}
	return 2;
}
 
Example 7
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 8
Source File: TypeConvertingCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
private boolean mustInsertTypeCast(XExpression expression, LightweightTypeReference actualType) {
	IResolvedTypes resolvedTypes = getResolvedTypes(expression);
	if (mustCheckForMandatoryTypeCast(resolvedTypes, expression)) {
		if (expression instanceof XAbstractFeatureCall) {
			LightweightTypeReference featureType = resolvedTypes.getActualType(((XAbstractFeatureCall) expression).getFeature());
			if (featureType != null && !featureType.isMultiType() && actualType.isAssignableFrom(featureType)) {
				return false;
			}
			if (featureType != null && featureType.isMultiType()) {
				JvmTypeReference compliantTypeReference = featureType.toJavaCompliantTypeReference();
				if (actualType.isAssignableFrom(featureType.getOwner().toLightweightTypeReference(compliantTypeReference))) {
					return false;
				}
			}
		}
		if (expression.eContainer() instanceof XCastedExpression) {
			XCastedExpression castedExpression = (XCastedExpression) expression.eContainer();
			LightweightTypeReference castedExpressionType = getResolvedTypes(castedExpression).getActualType(castedExpression);
			if (castedExpressionType != null) {
				return actualType.getType() != castedExpressionType.getType();	
			}
		}
		return true;
	}
	return false;
}
 
Example 9
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 10
Source File: ObjectAndPrimitiveBasedCastOperationCandidateSelector.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Validate the parameters of the operation.
 *
 * @param operation the operation from which the parameters are extracted.
 * @return {@code true} if the return type is valid; otherwise {@code false}.
 */
protected boolean isValidParameters(JvmOperation operation) {
	final List<JvmFormalParameter> parameters = operation.getParameters();
	if (parameters.size() == 0) {
		final JvmType originType = operation.getDeclaringType();
		return this.expressionType.isSubtypeOf(originType);
	} else if (parameters.size() == 1) {
		final JvmTypeReference parameterType = parameters.get(0).getParameterType();
		final LightweightTypeReference paramType = this.state.getReferenceOwner().toLightweightTypeReference(parameterType);
		if (parameterType != null) {
			return paramType.isAssignableFrom(this.expressionType);
		}
	}
	return false;
}
 
Example 11
Source File: DeferredTypeParameterHintCollector.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected LightweightTypeReference getStricterConstraint(final UnboundTypeReference typeParameter, LightweightTypeReference hint) {
	final JvmTypeParameter parameter = typeParameter.getTypeParameter();
	List<JvmTypeConstraint> constraints = parameter.getConstraints();
	for(JvmTypeConstraint constraint: constraints) {
		JvmTypeReference constraintReference = constraint.getTypeReference();
		if (constraintReference != null) {
			final boolean[] recursive = new boolean[] { false };
			LightweightTypeReferenceFactory factory = new LightweightTypeReferenceFactory(hint.getOwner()) {
				@Override
				public LightweightTypeReference doVisitParameterizedTypeReference(JvmParameterizedTypeReference reference) {
					JvmType type = reference.getType();
					if (type == parameter) {// recursively bound
						recursive[0] = true;
					}
					return super.doVisitParameterizedTypeReference(reference);
				}
			};
			LightweightTypeReference lightweightReference = factory.toLightweightReference(constraintReference);
			if (!recursive[0]) {
				if (hint.isAssignableFrom(lightweightReference)) {
					hint = lightweightReference;	
				} else if (hint.isResolved() && !lightweightReference.getRawTypeReference().isAssignableFrom(hint, TypeConformanceComputationArgument.RAW)) {
					return null;
				}
			}
		}
	}
	return hint;
}
 
Example 12
Source File: ExtensionScopeHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Check the type of the first parameter against the argument type rather
 * than the {@link #rawArgumentType}. Should not be used during linking
 * since we need proper error messages there for type mismatches.
 */
protected boolean isMatchingFirstParameterDeepCheck(JvmOperation feature) {
	if (isMatchingFirstParameter(feature)) {
		if (isResolvedReceiverType()) {
			LightweightTypeReference parameterType = argumentType.getOwner().toLightweightTypeReference(feature.getParameters().get(0).getParameterType());
			if (isResolvedOrKnownTypeParam(parameterType) && !parameterType.isAssignableFrom(argumentType)) {
				return false;
			}
		}
		return true;
	}
	return false;
}
 
Example 13
Source File: SARLValidator.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Report the warnings associated to the casted expressions.
 *
 * @param concreteSyntax the type specified into the casted expression.
 * @param toType the type specified into the casted expression.
 * @param fromType the type of the source expression.
 */
protected void reportCastWarnings(JvmTypeReference concreteSyntax, LightweightTypeReference toType, LightweightTypeReference fromType) {
	if (!isIgnored(OBSOLETE_CAST) && toType.isAssignableFrom(fromType)) {
		addIssue(MessageFormat.format(Messages.SARLValidator_96, fromType.getHumanReadableName(),
				toType.getHumanReadableName()), concreteSyntax, OBSOLETE_CAST);
	}
}
 
Example 14
Source File: ConstructorLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected LightweightTypeReference deferredBindTypeArgument(ITypeExpectation expectation, LightweightTypeReference type) {
	LightweightTypeReference result = super.deferredBindTypeArgument(expectation, type);
	LightweightTypeReference expectedType = expectation.getExpectedType();
	if (expectedType != null && getConstructorCall().getTypeArguments().isEmpty() && !result.isRawType() && !getDeclaredTypeParameters().isEmpty()) {
		if (!expectedType.isAssignableFrom(result, TypeConformanceComputationArgument.DEFAULT)) {
			LightweightTypeReference rawFeatureType = result.getRawTypeReference();
			if (expectedType.isAssignableFrom(rawFeatureType)) {
				result = rawFeatureType;
				getTypeParameterMapping().clear();
			}
		}
	}
	return result;
}
 
Example 15
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 16
Source File: ExpressionScope.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Filters the extensions by their most specific first parameter.
 */
protected List<IIdentifiableElementDescription> getFilteredExtensionDescriptions(Map<String, List<IIdentifiableElementDescription>> extensionSignatures) {
	List<IIdentifiableElementDescription> result = Lists.newArrayList();
	for(List<IIdentifiableElementDescription> list: extensionSignatures.values()) {
		int size = list.size();
		for(int i = 0; i < size; i++) {
			IIdentifiableElementDescription candidate = list.get(i);
			if (candidate != null) {
				LightweightTypeReference firstParameterType = getFirstParameterType(candidate);
				if (firstParameterType != null) {
					if (i + 1 < list.size()) {
						for(int j = i + 1; j < list.size() && firstParameterType != null; j++) {
							IIdentifiableElementDescription next = list.get(j);
							if (next != null) {
								if (next.isStatic() != candidate.isStatic()) {
									if (next.isStatic()) {
										list.set(j, null);
									} else {
										list.set(j, null);
										candidate = next;
										firstParameterType = getFirstParameterType(next);
									}
								} else {
									LightweightTypeReference otherFirstParameterType = getFirstParameterType(next);
									if (otherFirstParameterType != null) {
										if (otherFirstParameterType.isAssignableFrom(firstParameterType)) {
											list.set(j, null);
										} else if (firstParameterType.isAssignableFrom(otherFirstParameterType)) {
											list.set(j, null);
											candidate = next;
											firstParameterType = otherFirstParameterType;
										}
									}
								}
							}
						}
					}
				}
				result.add(candidate);
			}
		}
	}
	return result;
}
 
Example 17
Source File: AbstractAssignabilityTest.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
public boolean doIsAssignable(final LightweightTypeReference lhs, final LightweightTypeReference rhs) {
  return lhs.isAssignableFrom(rhs);
}
 
Example 18
Source File: SARLValidator.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Check the type of the behavior unit's guard.
 *
 * @param behaviorUnit the behavior unit.
 */
@Check(CheckType.FAST)
public void checkBehaviorUnitGuardType(SarlBehaviorUnit behaviorUnit) {
	final XExpression guard = behaviorUnit.getGuard();
	if (guard != null) {
		if (this.operationHelper.hasSideEffects(null, guard)) {
			error(Messages.SARLValidator_53,
					guard,
					null,
					ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
					INVALID_INNER_EXPRESSION);
			return;
		}
		if (guard instanceof XBooleanLiteral) {
			final XBooleanLiteral booleanLiteral = (XBooleanLiteral) guard;
			if (booleanLiteral.isIsTrue()) {
				if (!isIgnored(DISCOURAGED_BOOLEAN_EXPRESSION)) {
					addIssue(Messages.SARLValidator_54,
							booleanLiteral,
							null,
							ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
							DISCOURAGED_BOOLEAN_EXPRESSION);
				}
			} else if (!isIgnored(UNREACHABLE_BEHAVIOR_UNIT)) {
				addIssue(Messages.SARLValidator_55,
						behaviorUnit,
						null,
						ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
						UNREACHABLE_BEHAVIOR_UNIT,
						behaviorUnit.getName().getSimpleName());
			}
			return;
		}

		final LightweightTypeReference fromType = getActualType(guard);
		if (!fromType.isAssignableFrom(Boolean.TYPE)) {
			error(MessageFormat.format(
					Messages.SARLValidator_38,
					getNameOfTypes(fromType), boolean.class.getName()),
					guard,
					null,
					ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
					INCOMPATIBLE_TYPES);
		}
	}
}
 
Example 19
Source File: XbaseValidator.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
protected void checkCast(JvmTypeReference concreteSyntax, LightweightTypeReference toType, LightweightTypeReference fromType) {
		if (toType == null || fromType == null)
			return;
		if (fromType.getType() instanceof JvmDeclaredType || fromType.isPrimitive()) {
			// if one of the types is an interface and the other is a non final class (or interface) there always can be a subtype
			if ((!isInterface(fromType) || isFinal(toType)) && (!isInterface(toType) || isFinal(fromType))) { 
				if (!toType.isAssignableFrom(fromType)) {
					if (   isFinal(fromType) || isFinal(toType)
						|| isClass(fromType) && isClass(toType)) {
						if (!fromType.isAssignableFrom(toType)) { // no upcast
							error("Cannot cast from " + getNameOfTypes(fromType) + " to "
									+ canonicalName(toType), concreteSyntax, null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
									INVALID_CAST);
						}
					}
				}
			}
		} else if (fromType.isPrimitiveVoid()) {
			error("Cannot cast from void to "
					+ canonicalName(toType), concreteSyntax, null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
					INVALID_CAST);
		}
		if(toType.isPrimitive() && !(fromType.isPrimitive() || fromType.isWrapper())) {
				error("Cannot cast from " + getNameOfTypes(fromType) + " to "
						+ canonicalName(toType), concreteSyntax, null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX,
						INVALID_CAST);
		}
		/*
		 * TODO: JDT reports no unnecessary cast of List<?> but for List<String> ... why is there an exception?
		 * 
		 * 
		 */
//			List<? extends String> list = Collections.emptyList();
//			if (((List<? extends String>)list).isEmpty()) {}
//			List<String> list = Collections.emptyList();
//			if (((List<String>)list).isEmpty()) {}
//			List list = Collections.emptyList();
//			if (((List)list).isEmpty()) {}
		if (toType.getIdentifier().equals(fromType.getIdentifier())) {
			addIssue("Unnecessary cast from " + fromType.getHumanReadableName() + " to " + toType.getHumanReadableName(), concreteSyntax, IssueCodes.OBSOLETE_CAST);
		}
	}
 
Example 20
Source File: CollectionLiteralsTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Implements fall-back strategy. If the expected type of a collection literal does not match the actual type, but the expected element
 * types would match the actual element type, the collection literal will be successfully typed according to the expectation.
 */
protected boolean matchesExpectation(LightweightTypeReference elementType, LightweightTypeReference expectation) {
	return expectation != null && expectation.isResolved() && !expectation.isWildcard() && expectation.isAssignableFrom(elementType);
}