Java Code Examples for org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference#isType()
The following examples show how to use
org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference#isType() .
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: XbaseValidator.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
@Check public void checkOperandTypesForTripleEquals(XBinaryOperation binaryOperation) { if(isTripleEqualsOperation(binaryOperation)){ LightweightTypeReference left = getActualType(binaryOperation.getLeftOperand()); LightweightTypeReference right = getActualType(binaryOperation.getRightOperand()); if(left.isArray() != right.isArray()) { if (left.isArray()) { if (right.isAny() || right.isType(Object.class) || right.isType(Serializable.class) || right.isType(Cloneable.class)) { return; } } else { if (left.isAny() || left.isType(Object.class) || left.isType(Serializable.class) || left.isType(Cloneable.class)) { return; } } error("Incompatible operand types " + left.getHumanReadableName() + " and " + right.getHumanReadableName(), null, INVALID_OPERAND_TYPES); } } }
Example 2
Source File: XtendReentrantTypeResolver.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
private EObject getNearestClosureOrTypeDeclaration(EObject object, IResolvedTypes resolvedTypes) { EObject candidate = object; while(candidate != null) { if (candidate instanceof XClosure) { return candidate; } if (candidate instanceof XConstructorCall) { // skip anonymous class constructors themselves if (candidate.eContainingFeature() == XtendPackage.Literals.ANONYMOUS_CLASS__CONSTRUCTOR_CALL) { candidate = candidate.eContainer(); } } else if (candidate instanceof XtendTypeDeclaration) { return candidate; } if (candidate instanceof RichString) { LightweightTypeReference type = resolvedTypes.getActualType((RichString)candidate); if (type != null && type.isType(StringConcatenationClient.class)) { return candidate; } } candidate = candidate.eContainer(); } return null; }
Example 3
Source File: XbaseCompiler.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
protected void _toJavaExpression(XSetLiteral literal, ITreeAppendable b) { LightweightTypeReference literalType = batchTypeResolver.resolveTypes(literal).getActualType(literal); if (literalType == null) { b.append("error - couldn't compute type for literal : "+literal); return; } if (literalType.isType(Map.class)) { LightweightTypeReference keyType = literalType.getTypeArguments().get(0); LightweightTypeReference valueType = literalType.getTypeArguments().get(1); b.append(Collections.class) .append(".<").append(keyType).append(", ").append(valueType) .append(">unmodifiableMap("); b.append(CollectionLiterals.class).append(".<").append(keyType).append(", ").append(valueType).append(">newHashMap("); Iterator<XExpression> elements = literal.getElements().iterator(); while(elements.hasNext()) { XExpression element = elements.next(); internalToJavaExpression(element, b); if (elements.hasNext()) { b.append(", "); } } b.append("))"); } else { appendImmutableCollectionExpression(literal, b, "unmodifiableSet", CollectionLiterals.class, "newHashSet"); } }
Example 4
Source File: SARLReentrantTypeResolver.java From sarl with Apache License 2.0 | 6 votes |
@SuppressWarnings("all") private EObject getNearestClosureOrTypeDeclaration(EObject object, IResolvedTypes resolvedTypes) { // Overriding for proper lambda expression. EObject candidate = object; while(candidate != null) { if (candidate instanceof XClosure) { return candidate; } if (candidate instanceof XConstructorCall) { // skip anonymous class constructors themselves if (candidate.eContainingFeature() == XtendPackage.Literals.ANONYMOUS_CLASS__CONSTRUCTOR_CALL) { candidate = candidate.eContainer(); } } else if (candidate instanceof XtendTypeDeclaration) { return candidate; } if (candidate instanceof RichString) { LightweightTypeReference type = resolvedTypes.getActualType((RichString)candidate); if (type != null && type.isType(StringConcatenationClient.class)) { return candidate; } } candidate = candidate.eContainer(); } return null; }
Example 5
Source File: AbstractPendingLinkingCandidate.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
/** * Returns false if the argument expression is a lambda and the expected type * of the argument is not a function type or {@link Object}. * Returns true in all other cases. * * This serves as a shortcut to rule out decision path's where a method is overloaded * and one of the overloads accepts a function type but the other doesn't. In those cases * it is not necessary to compute the type of the lamdba expression twice. * * An example for this pattern is {@link IterableExtensions#filter(Iterable, Class)} vs * {@link IterableExtensions#filter(Iterable, org.eclipse.xtext.xbase.lib.Functions.Function1)}. */ protected boolean isPossibleFunctionType(int idx) { if (idx < arguments.getArgumentCount()) { XExpression argument = arguments.getArgument(idx); if (argument instanceof XClosure) { XClosure closure = (XClosure) argument; LightweightTypeReference declaredType = arguments.getDeclaredTypeForLambda(idx); if (declaredType != null && !declaredType.isType(Object.class)) { CommonTypeComputationServices services = getState().getReferenceOwner().getServices(); JvmOperation operation = services.getFunctionTypes().findImplementingOperation(declaredType); if (operation == null) { return false; } if (closure.isExplicitSyntax() && closure.getDeclaredFormalParameters().size() != operation.getParameters().size()) { return false; } } } } return true; }
Example 6
Source File: AbstractPendingLinkingCandidate.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
/** * 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 7
Source File: RawTypeConformanceComputer.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
protected int doIsConformant(LightweightTypeReference left, UnboundTypeReference right, int flags) { if (left.getType() == right.getType() || left.isType(Object.class)) { return flags | SUCCESS; } if ((flags & ALLOW_UNBOXING) == 0 && left.isPrimitive()) { return flags; } boolean doesNotHaveSignificantHints = false; if (((flags & RAW_TYPE) == 0) && (right.canResolveTo(left) || (flags & AS_TYPE_ARGUMENT) != 0 && (doesNotHaveSignificantHints = !right.hasSignificantHints()))) { if ((flags & UNBOUND_COMPUTATION_ADDS_HINTS) != 0 && doesNotHaveSignificantHints) { right.acceptHint(left, BoundTypeArgumentSource.INFERRED_LATER, left, VarianceInfo.INVARIANT, VarianceInfo.INVARIANT); } return flags | SUCCESS; } right.tryResolve(false); LightweightTypeReference resolvedTo = right.getResolvedTo(); if (resolvedTo != null) { return doIsConformant(left, resolvedTo, flags); } return flags; }
Example 8
Source File: SynonymTypesProvider.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
public void collectSynonymTypes(/* @Nullable */ LightweightTypeReference type, /* @NonNull */ Acceptor acceptor) { if (type == null || type.isPrimitiveVoid() || type.isType(Void.class)) { return; } if (type.isWrapper()) { if (!acceptor.accept(type.getPrimitiveIfWrapperType(), ConformanceFlags.CHECKED_SUCCESS | ConformanceFlags.UNBOXING)) { return; } // a primitive type is never an array or list collectCustomSynonymTypes(type, acceptor); return; } else if (type.isPrimitive()) { if (!acceptor.accept(type.getWrapperTypeIfPrimitive(), ConformanceFlags.CHECKED_SUCCESS | ConformanceFlags.BOXING)) { return; } // a primitive type is never an array or list collectCustomSynonymTypes(type, acceptor); return; } if (addArrayAndListSynonyms(type, acceptor)) { collectCustomSynonymTypes(type, acceptor); } }
Example 9
Source File: CollectionLiteralsTypeComputer.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
/** * 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 10
Source File: AbstractLinkingCandidate.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
protected void initializeConstraintMapping(JvmTypeParameter typeParameter, UnboundTypeParameterPreservingSubstitutor substitutor, UnboundTypeReference typeReference) { if (!typeReference.internalIsResolved()) { List<JvmTypeConstraint> constraints = typeParameter.getConstraints(); for(JvmTypeConstraint constraint: constraints) { JvmTypeReference constraintReference = constraint.getTypeReference(); if (constraintReference != null) { LightweightTypeReference substitute = substitutor.substitute(constraintReference); if (!substitute.isType(Object.class) && !substitute.isPrimitiveVoid()) { typeReference.acceptHint(substitute, BoundTypeArgumentSource.CONSTRAINT, constraint, VarianceInfo.OUT, VarianceInfo.OUT); } } } } }
Example 11
Source File: AbstractTypeExpectation.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
@Override public boolean isVoidTypeAllowed() { LightweightTypeReference expectedType = getExpectedType(); if (expectedType != null && expectedType.isType(Void.TYPE)) { return true; } return false; }
Example 12
Source File: XbaseTypeComputer.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
protected boolean hasThrowableExpectation(ITypeComputationState state) { List<? extends ITypeExpectation> expectations = state.getExpectations(); for (ITypeExpectation typeExpectation : expectations) { LightweightTypeReference expected = typeExpectation.getExpectedType(); if (expected != null && expected.isType(Throwable.class)) return true; } return false; }
Example 13
Source File: XbaseInterpreter.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
/** * @param context unused in this context but required for dispatching * @param indicator unused in this context but required for dispatching */ protected Object _doEvaluate(XStringLiteral literal, IEvaluationContext context, CancelIndicator indicator) { LightweightTypeReference type = typeResolver.resolveTypes(literal).getActualType(literal); if (type != null && (type.isType(Character.TYPE) || type.isType(Character.class))) { return literal.getValue().charAt(0); } return literal.getValue(); }
Example 14
Source File: XbaseValidator.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
@Check public void checkInstanceOf(XInstanceOfExpression instanceOfExpression) { LightweightTypeReference leftType = getActualType(instanceOfExpression.getExpression()); final LightweightTypeReference rightType = toLightweightTypeReference(instanceOfExpression.getType(), true); if (leftType == null || rightType == null || rightType.getType() == null || rightType.getType().eIsProxy()) { return; } if (containsTypeArgs(rightType)) { error("Cannot perform instanceof check against parameterized type " + getNameOfTypes(rightType), null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, INVALID_INSTANCEOF); return; } if (leftType.isAny() || leftType.isUnknown()) { return; // null / unknown is ok } if (rightType.isPrimitive()) { error("Cannot perform instanceof check against primitive type " + this.getNameOfTypes(rightType), null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, INVALID_INSTANCEOF); return; } if (leftType.isPrimitive() || rightType.isArray() && !(leftType.isArray() || leftType.isType(Object.class) || leftType.isType(Cloneable.class) || leftType.isType(Serializable.class)) || isFinal(rightType) && !memberOfTypeHierarchy(rightType, leftType) || isFinal(leftType) && !memberOfTypeHierarchy(leftType, rightType)) { error("Incompatible conditional operand types " + this.getNameOfTypes(leftType)+" and "+this.getNameOfTypes(rightType), null, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, INVALID_INSTANCEOF); return; } if (!isIgnored(OBSOLETE_INSTANCEOF) && rightType.isAssignableFrom(leftType, new TypeConformanceComputationArgument(false, false, true, true, false, false))) { // check that we do not have a type parameter usage on the rhs of the instanceof if (rightType.getConstraintSubstitute() == rightType) { addIssueToState(OBSOLETE_INSTANCEOF, "The expression of type " + getNameOfTypes(leftType) + " is already of type " + canonicalName(rightType), null); } } }
Example 15
Source File: FeatureScopeSessionWithContext.java From xtext-extras with Eclipse Public License 2.0 | 4 votes |
@Override public boolean isVisible(JvmMember member, /* @Nullable */ LightweightTypeReference receiverType, /* @Nullable */ JvmIdentifiableElement receiverFeature) { boolean result = isVisible(member); if (result && JvmVisibility.PROTECTED == member.getVisibility()) { if (receiverFeature != null) { // We bypass this check for qualified.this and qualified.super in the scope provider // they are considered to be always visible /* * class A { * class B { * { * A.super.toString * } * } * } */ if (isThisSuperOrTypeLiteral(receiverFeature)) { if (receiverType == null || !receiverType.isType(Class.class)) { return true; } } } JvmType contextType = visibilityHelper.getRawContextType(); if (contextType instanceof JvmDeclaredType) { String packageName = visibilityHelper.getPackageName(); JvmDeclaredType declaringType = member.getDeclaringType(); String memberPackageName = declaringType.getPackageName(); if (Strings.equal(packageName, memberPackageName)) { return true; } } if (receiverType != null) { if (receiverType.isSubtypeOf(contextType)) { return true; } EObject container = contextType.eContainer(); while (container instanceof JvmType) { if (receiverType.isSubtypeOf((JvmType)container)) { return true; } container = container.eContainer(); } } return false; } return result; }
Example 16
Source File: SarlCompiler.java From sarl with Apache License 2.0 | 4 votes |
private void convertNullSafeWrapperToPrimitive( LightweightTypeReference wrapper, LightweightTypeReference primitive, XExpression context, ITreeAppendable appendable, Later expression) { // BEGIN Specific final String defaultValue = primitive.isType(boolean.class) ? "false" : "0"; //$NON-NLS-1$ //$NON-NLS-2$ // END Specific final XExpression normalized = normalizeBlockExpression(context); if (normalized instanceof XAbstractFeatureCall && !(context.eContainer() instanceof XAbstractFeatureCall)) { // Avoid javac bug // https://bugs.eclipse.org/bugs/show_bug.cgi?id=410797 // TODO make that dependent on the compiler version (javac 1.7 fixed that bug) final XAbstractFeatureCall featureCall = (XAbstractFeatureCall) normalized; if (featureCall.isStatic()) { final JvmIdentifiableElement feature = featureCall.getFeature(); if (feature instanceof JvmOperation) { if (!((JvmOperation) feature).getTypeParameters().isEmpty()) { // BEGIN Specific appendable.append("(("); //$NON-NLS-1$ expression.exec(appendable); appendable.append(") == null ? "); //$NON-NLS-1$ appendable.append(defaultValue); appendable.append(" : "); //$NON-NLS-1$ // END Specific appendable.append("("); //$NON-NLS-1$ appendable.append(primitive); appendable.append(") "); //$NON-NLS-1$ expression.exec(appendable); // BEGIN Specific appendable.append(") "); //$NON-NLS-1$ // END Specific return; } } } } // BEGIN Specific appendable.append("(("); //$NON-NLS-1$ expression.exec(appendable); appendable.append(") == null ? "); //$NON-NLS-1$ appendable.append(defaultValue); appendable.append(" : "); //$NON-NLS-1$ // END Specific final boolean mustInsertTypeCast; try { mustInsertTypeCast = (Boolean) this.reflect.invoke(this, "mustInsertTypeCast", context, wrapper); //$NON-NLS-1$ } catch (Exception exception) { throw new Error(exception); } if (mustInsertTypeCast) { appendable.append("("); //$NON-NLS-1$ appendable.append(wrapper); appendable.append(") "); //$NON-NLS-1$ } // BEGIN Specific appendable.append("("); //$NON-NLS-1$ expression.exec(appendable); appendable.append(")"); //$NON-NLS-1$ // END Specific appendable.append("."); //$NON-NLS-1$ appendable.append(primitive); appendable.append("Value())"); //$NON-NLS-1$ }
Example 17
Source File: CollectionLiteralsTypeComputer.java From xtext-extras with Eclipse Public License 2.0 | 4 votes |
protected boolean isMapLiteral(LightweightTypeReference expectation, LightweightTypeReference elementType) { if (isIterableExpectation(expectation)) { return false; } return elementType.isType(Pair.class) && elementType.getTypeArguments().size() == 2; }
Example 18
Source File: XbaseCompiler.java From xtext-extras with Eclipse Public License 2.0 | 4 votes |
protected ITreeAppendable appendOpenIfStatement(XCasePart casePart, ITreeAppendable b, String matchedVariable, String variableName, XSwitchExpressionCompilationState state) { ITreeAppendable caseAppendable = b.trace(casePart, true); if (state.caseNeedsIfNotMatchedCheck()) { caseAppendable.newLine().append("if (!").append(matchedVariable).append(") {"); caseAppendable.increaseIndentation(); } JvmTypeReference typeGuard = casePart.getTypeGuard(); if (typeGuard != null) { ITreeAppendable typeGuardAppendable = caseAppendable.trace(typeGuard, true); typeGuardAppendable.newLine().append("if ("); if (typeGuard instanceof JvmSynonymTypeReference) { Iterator<JvmTypeReference> iter = ((JvmSynonymTypeReference) typeGuard).getReferences().iterator(); while(iter.hasNext()) { typeGuardAppendable.append(variableName); typeGuardAppendable.append(" instanceof "); typeGuardAppendable.trace(typeGuard).append(iter.next().getType()); if (iter.hasNext()) { typeGuardAppendable.append(" || "); } } } else { typeGuardAppendable.append(variableName); typeGuardAppendable.append(" instanceof "); typeGuardAppendable.trace(typeGuard).append(typeGuard.getType()); } typeGuardAppendable.append(") {"); typeGuardAppendable.increaseIndentation(); typeGuardAppendable.openPseudoScope(); } if (casePart.getCase() != null) { ITreeAppendable conditionAppendable = caseAppendable.trace(casePart.getCase(), true); internalToJavaStatement(casePart.getCase(), conditionAppendable, true); conditionAppendable.newLine().append("if ("); LightweightTypeReference convertedType = getLightweightType(casePart.getCase()); if (convertedType.isType(Boolean.TYPE) || convertedType.isType(Boolean.class)) { internalToJavaExpression(casePart.getCase(), conditionAppendable); } else { JvmType objectsType = findKnownType(Objects.class, casePart); if (objectsType != null) { conditionAppendable.append(objectsType); conditionAppendable.append(".equal(").append(variableName).append(", "); internalToJavaExpression(casePart.getCase(), conditionAppendable); conditionAppendable.append(")"); } else { // use ObjectExtensions rather than a == b || a != null && a.equals(b) since // that won't work with primitive types and other incompatible conditional operands conditionAppendable.append(ObjectExtensions.class); conditionAppendable.append(".operator_equals(").append(variableName).append(", "); internalToJavaExpression(casePart.getCase(), conditionAppendable); conditionAppendable.append(")"); } } conditionAppendable.append(")"); caseAppendable.append(" {"); caseAppendable.increaseIndentation(); } // set matched to true return caseAppendable.newLine().append(matchedVariable).append("=true;"); }
Example 19
Source File: XbaseInterpreter.java From xtext-extras with Eclipse Public License 2.0 | 4 votes |
protected LightweightTypeReference resolveType(XExpression element, Class<?> clazz) { LightweightTypeReference elementType = typeResolver.resolveTypes(element).getActualType(element); return elementType != null && elementType.isType(clazz) ? elementType : null; }
Example 20
Source File: SARLValidator.java From sarl with Apache License 2.0 | 4 votes |
/** Check the implemented type. * * @param element the child type. * @param feature the syntactic feature related to the supertypes. * @param implementedTypes the current super types. * @param expectedType the expected root type. * @param mandatoryNumberOfTypes the minimal number of implemented types. * @param onlySubTypes if <code>true</code> only the subtype of the <code>expectedType</code> are valid; * <code>false</code> if the <code>expectedType</code> is allowed. * @return the count of supertypes. */ protected boolean checkImplementedTypes( XtendTypeDeclaration element, EReference feature, List<? extends JvmTypeReference> implementedTypes, Class<?> expectedType, int mandatoryNumberOfTypes, boolean onlySubTypes) { boolean success = true; int nb = 0; int index = 0; for (final JvmTypeReference superType : implementedTypes) { final LightweightTypeReference ref = toLightweightTypeReference(superType); if (ref != null && (!ref.isInterfaceType() || !ref.isSubtypeOf(expectedType) || (onlySubTypes && ref.isType(expectedType)))) { final String msg; if (onlySubTypes) { msg = Messages.SARLValidator_72; } else { msg = Messages.SARLValidator_73; } error(MessageFormat.format( msg, superType.getQualifiedName(), expectedType.getName(), element.getName()), element, feature, index, INVALID_IMPLEMENTED_TYPE, superType.getSimpleName()); success = false; } else { ++nb; } ++index; } if (nb < mandatoryNumberOfTypes) { error(MessageFormat.format( Messages.SARLValidator_74, expectedType.getName(), element.getName()), element, feature, ValidationMessageAcceptor.INSIGNIFICANT_INDEX, MISSING_TYPE); success = false; } return success; }