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

The following examples show how to use org.eclipse.xtext.xbase.typesystem.references.LightweightTypeReference#getType() . 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: 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 2
Source File: CreateMemberQuickfixes.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void newMethodQuickfixes(LightweightTypeReference containerType, String name, /* @Nullable */ LightweightTypeReference returnType,
	List<LightweightTypeReference> argumentTypes, XAbstractFeatureCall call, JvmDeclaredType callersType,
	final Issue issue, final IssueResolutionAcceptor issueResolutionAcceptor) {
	boolean isLocal = callersType == containerType.getType();
	boolean isStatic = isStaticAccess(call);
	boolean isAbstract = true;
	if(containerType.getType() instanceof JvmGenericType) {
		isAbstract = !((JvmGenericType) containerType.getType()).isInstantiateable();
	} else if(containerType.getType() instanceof JvmDeclaredType) {
		isAbstract = ((JvmDeclaredType) containerType.getType()).isAbstract();
	}
	if(containerType.getType() instanceof JvmDeclaredType) {
		JvmDeclaredType declaredType = (JvmDeclaredType) containerType.getType();
		newMethodQuickfix(declaredType, name, returnType, argumentTypes, isStatic, isAbstract, false, isLocal, call, issue, issueResolutionAcceptor);
	}
	if(!isLocal && !isStatic) {
		List<LightweightTypeReference> extensionMethodParameterTypes = newArrayList(argumentTypes);
		extensionMethodParameterTypes.add(0, containerType);
		newMethodQuickfix(callersType, name, returnType, extensionMethodParameterTypes, false, isAbstract, true, true, call, issue, issueResolutionAcceptor);
	}
}
 
Example 3
Source File: InheritanceHelper.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies if the type candidate is a subtype of the given super type.
 *
 * @param candidate the type to test.
 * @param jvmSuperType the expected JVM super-type.
 * @param sarlSuperType the expected SARL super-type.
 * @return <code>true</code> if the candidate is a sub-type of the super-type.
 */
public boolean isSubTypeOf(LightweightTypeReference candidate, Class<?> jvmSuperType,
		Class<? extends XtendTypeDeclaration> sarlSuperType) {
	if (candidate.isSubtypeOf(jvmSuperType)) {
		return true;
	}
	if (sarlSuperType != null) {
		final JvmType type = candidate.getType();
		if (type instanceof JvmGenericType) {
			final JvmGenericType genType = (JvmGenericType) type;
			if (genType.getSuperTypes().isEmpty()) {
				for (final EObject sarlObject : this.sarlAssociations.getSourceElements(type)) {
					if (sarlSuperType.isInstance(sarlObject)) {
						return true;
					}
				}
			}
		}
	}
	return false;
}
 
Example 4
Source File: UnboundTypeParameterPreservingSubstitutor.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
/* @Nullable */
protected LightweightTypeReference getBoundTypeArgument(ParameterizedTypeReference reference, JvmTypeParameter type, Set<JvmTypeParameter> visiting) {
	LightweightMergedBoundTypeArgument boundTypeArgument = getTypeParameterMapping().get(type);
	if (boundTypeArgument != null) {
		LightweightTypeReference boundReference = boundTypeArgument.getTypeReference();
		if (boundReference != null && reference != boundReference) {
			if (boundReference instanceof UnboundTypeReference)
				return boundReference.copyInto(getOwner());
			JvmType boundType = boundReference.getType();
			if (boundType != type) {
				if (visiting.add(type)) {
					try {
						LightweightTypeReference result = boundReference.accept(this, visiting);
						return result;
					} finally {
						visiting.remove(type);
					}
				} else {
					return reference;
				}
			} 
		}
	}
	return null;
}
 
Example 5
Source File: RawTypeConformanceComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected int doIsConformantOuter(LightweightTypeReference left, LightweightTypeReference right, int nestedResult, int flags) {
	if ((nestedResult & SUCCESS) != 0) {
		JvmType leftType = left.getType();
		EObject leftDeclarator = leftType.eContainer();
		if (leftDeclarator instanceof JvmDeclaredType) {
			JvmDeclaredType castedLeftDeclarator = (JvmDeclaredType) leftDeclarator;
			LightweightTypeReference leftOuter = left.getOuter().getSuperType(castedLeftDeclarator);
			if (leftOuter != null) {
				LightweightTypeReference rightOuter = right.getOuter().getSuperType(castedLeftDeclarator);
				if (rightOuter != null) {
					int outerResult = doIsConformant(leftOuter, rightOuter, flags);
					if ((outerResult & SUCCESS) == 0) {
						return outerResult;
					}
				}
			}
		}
	}
	return nestedResult;
}
 
Example 6
Source File: RawTypeConformanceComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
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 7
Source File: TypeConformanceComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean accept(LightweightTypeReference superType, int distance) {
	if (superType == null)
		throw new IllegalStateException("superType may not be null");
	JvmType type = superType.getType();
	if (type != null) {
		rawTypeToReference.put(type, superType);
		if (distances.contains(type)) {
			int currentCount = distances.count(type);
			if (currentCount < distance + 1) {
				distances.setCount(type, distance + 1);
			}
		} else {
			distances.add(type, distance + 1);
		}
	}
	return true;
}
 
Example 8
Source File: ClosureWithExpectationHelper.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected ITypeComputationState getClosureBodyTypeComputationState(ITypeAssigner typeAssigner) {
	ITypeComputationState result = assignParameters(typeAssigner);
	LightweightTypeReference expectedType = getExpectation().getExpectedType();
	if (expectedType == null) {
		throw new IllegalStateException();
	}
	JvmType knownType = expectedType.getType();
	if (knownType != null && knownType instanceof JvmGenericType) {
		result.assignType(IFeatureNames.SELF, knownType, expectedType);
	}
	List<JvmTypeReference> exceptions = operation.getExceptions();
	if (exceptions.isEmpty()) {
		result.withinScope(getClosure());
		return result;
	}
	List<LightweightTypeReference> expectedExceptions = Lists.newArrayListWithCapacity(exceptions.size());
	for (JvmTypeReference exception : exceptions) {
		expectedExceptions.add(typeAssigner.toLightweightTypeReference(exception));
	}
	result.withinScope(getClosure());
	return result.withExpectedExceptions(expectedExceptions);
}
 
Example 9
Source File: XbaseCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean canCompileToJavaLambda(XClosure closure, LightweightTypeReference typeRef, JvmOperation operation) {
	if (!typeRef.isInterfaceType())
		return false;
	
	if (!operation.getTypeParameters().isEmpty())
		return false;
	
	TreeIterator<EObject> iterator = closure.eAllContents();
	JvmType jvmType = typeRef.getType();
	while (iterator.hasNext()) {
		EObject obj = iterator.next();
		if (obj instanceof XClosure) {
			iterator.prune();
		} else if (obj instanceof XFeatureCall && isReferenceToSelf((XFeatureCall) obj, jvmType)) {
			return false;
		}
	}
	return true;
}
 
Example 10
Source File: ClosureTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * This method is only public for testing purpose.
 * 
 * @noreference This method is not intended to be referenced by clients.
 */
public void selectStrategy() {
	LightweightTypeReference expectedType = expectation.getExpectedType();
	if (expectedType == null) {
		strategy = getClosureWithoutExpectationHelper();
	} else {
		JvmOperation operation = functionTypes.findImplementingOperation(expectedType);
		JvmType type = expectedType.getType();
		int closureParameterSize;
		if (closure.isExplicitSyntax()) {
			closureParameterSize = closure.getDeclaredFormalParameters().size();
		} else if (operation != null) {
			closureParameterSize = operation.getParameters().size();
		} else {
			closureParameterSize = 1;
		}
		if (operation == null || operation.getParameters().size() != closureParameterSize || type == null) {
			strategy = getClosureWithoutExpectationHelper();
		} else {
			strategy = createClosureWithExpectationHelper(operation);
		}
	}
	
}
 
Example 11
Source File: TypeConvertingCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected void doConversion(final LightweightTypeReference left, final LightweightTypeReference right,
		final ITreeAppendable appendable, XExpression context, final Later expression) {
	if(left.isPrimitive() && !right.isPrimitive()) {
		if (right.isAny()) {
			convertWrapperToPrimitive(left, left, context, appendable, expression);
		} else {
			convertWrapperToPrimitive(right, right.getPrimitiveIfWrapperType(), context, appendable, expression);
		}
	} else if (right.isPrimitive() && !left.isPrimitive()) {
		convertPrimitiveToWrapper(right, right.getWrapperTypeIfPrimitive(), appendable, expression);
	} else if (right.isMultiType()) {
		convertMultiType(left, (CompoundTypeReference) right, context, appendable, expression);
	} else if (right.isArray() && !left.isArray() && left.isSubtypeOf(Iterable.class)) {
		convertArrayToList(left, appendable, context, expression);
	} else if (isJavaConformant(left, right)) {
		if (mustInsertTypeCast(context, left)) {
			doCastConversion(left, appendable, expression);
		} else {
			expression.exec(appendable);
		}
	} else if (left.isArray() && !right.isArray() && right.isSubtypeOf(Iterable.class)) {
		convertListToArray(left, appendable, expression);
	} else if ((isFunction(left) && isFunction(right) || isProcedure(left) && isProcedure(right)) && left.getType() == right.getType()) {
		doCastConversion(left, appendable, expression);
	} else if (isFunction(right) || (isFunction(left) && findImplementingOperation(right) != null)) {
		convertFunctionType(left, right, appendable, expression);
	} else if (isProcedure(right) || (isProcedure(left) && findImplementingOperation(right) != null)) {
		convertFunctionType(left, right, appendable, expression);
	} else if (mustInsertTypeCast(context, left)) {
		doCastConversion(left, appendable, expression);
	} else {
		expression.exec(appendable);
	}
}
 
Example 12
Source File: CollectionLiteralsTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * A function type reference may be known to have the type argument {@link Number} but still use a more
 * specific return type {@link Integer}. Normalization converts such a reference to the return type {@link Number}.
 */
protected LightweightTypeReference normalizeFunctionTypeReference(LightweightTypeReference type) {
	if (type.getKind() == LightweightTypeReference.KIND_FUNCTION_TYPE_REFERENCE) {
		ParameterizedTypeReference parameterized = new ParameterizedTypeReference(type.getOwner(), type.getType());
		for(LightweightTypeReference argument: type.getTypeArguments()) {
			parameterized.addTypeArgument(argument);
		}
		type = parameterized.tryConvertToFunctionTypeReference(false);
	}
	return type;
}
 
Example 13
Source File: AbstractResolvedFeature.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isRawTypeInheritance() {
	List<LightweightTypeReference> superTypes = getContextType().getAllSuperTypes();
	JvmDeclaredType declaringType = getDeclaration().getDeclaringType();
	for(LightweightTypeReference superType: superTypes) {
		if (superType.getType() == declaringType && superType.isRawType()) {
			return true;
		}
	}
	return false;
}
 
Example 14
Source File: SARLOutlineTreeProvider.java    From sarl with Apache License 2.0 5 votes vote down vote up
private void createInheritedConstructors(EStructuralFeatureNode elementNode, XtendClass modelElement) {
	final JvmTypeReference extend = modelElement.getExtends();
	if (extend != null) {
		final LightweightTypeReference reference = Utils.toLightweightTypeReference(extend, this.services);
		if (reference != null) {
			final JvmType type = reference.getType();
			if (type instanceof JvmDeclaredType) {
				for (final JvmConstructor constructor : ((JvmDeclaredType) type).getDeclaredConstructors()) {
					createNode(elementNode, constructor);
				}
			}
		}
	}
}
 
Example 15
Source File: OverrideHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected JvmOperation findOverriddenOperation(JvmOperation operation, LightweightTypeReference declaringType,
		TypeParameterSubstitutor<?> substitutor, ITypeReferenceOwner owner, IVisibilityHelper visibilityHelper) {
	int parameterSize = operation.getParameters().size();
	List<LightweightTypeReference> superTypes = declaringType.getSuperTypes();
	for(LightweightTypeReference superType: superTypes) {
		if (superType.getType() instanceof JvmDeclaredType) {
			JvmDeclaredType declaredSuperType = (JvmDeclaredType) superType.getType();
			if (declaredSuperType != null) {
				Iterable<JvmFeature> equallyNamedFeatures = declaredSuperType.findAllFeaturesByName(operation.getSimpleName());
				for(JvmFeature feature: equallyNamedFeatures) {
					if (feature instanceof JvmOperation) {
						JvmOperation candidate = (JvmOperation) feature;
						if (parameterSize == candidate.getParameters().size()) {
							if (visibilityHelper.isVisible(feature)) {
								boolean matchesSignature = true;
								for(int i = 0; i < parameterSize && matchesSignature; i++) {
									JvmFormalParameter parameter = operation.getParameters().get(i);
									JvmFormalParameter candidateParameter = candidate.getParameters().get(i);
									matchesSignature = isMatchesSignature(parameter, candidateParameter, substitutor, owner);
								}
								if (matchesSignature) {
									return candidate;
								}
							}
						}
					}
				}
			}
		}
	}
	return null;
}
 
Example 16
Source File: TypeConvertingCompiler.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private boolean identifierStartWith(LightweightTypeReference typeReference, String prefix) {
	JvmType type = typeReference.getType();
	if (type == null)
		return false;
	String identifier = type.getIdentifier();
	if (identifier != null)
		return identifier.startsWith(prefix);
	return false;
}
 
Example 17
Source File: TypeParameterSubstitutor.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected LightweightTypeReference getBoundTypeArgument(ParameterizedTypeReference reference, JvmTypeParameter type,
		Visiting visiting) {
	LightweightMergedBoundTypeArgument boundTypeArgument = typeParameterMapping.get(type);
	if (boundTypeArgument != null) {
		LightweightTypeReference boundReference = boundTypeArgument.getTypeReference();
		if (boundReference != null && reference != boundReference && boundReference.getType() != type) {
			return boundReference.accept(this, visiting);
		}
	}
	return null;
}
 
Example 18
Source File: AbstractXtendOutlineTreeBuilder.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
protected void buildInheritedMembers(final JvmDeclaredType inferredType, final IXtendOutlineContext context) {
  ResourceSet _resourceSet = inferredType.eResource().getResourceSet();
  final StandardTypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, _resourceSet);
  final LightweightTypeReference typeReference = owner.toLightweightTypeReference(inferredType);
  final List<LightweightTypeReference> superTypes = typeReference.getAllSuperTypes();
  IXtendOutlineContext superTypeContext = context;
  for (final LightweightTypeReference superTypeRef : superTypes) {
    {
      superTypeContext = superTypeContext.increaseInheritanceDepth();
      final ResolvedFeatures resolvedFeatures = new ResolvedFeatures(superTypeRef);
      List<IResolvedField> _declaredFields = resolvedFeatures.getDeclaredFields();
      for (final IResolvedField jvmField : _declaredFields) {
        boolean _skipFeature = this.skipFeature(jvmField.getDeclaration());
        boolean _not = (!_skipFeature);
        if (_not) {
          this.xtendOutlineNodeBuilder.buildResolvedFeatureNode(inferredType, jvmField, superTypeContext);
        }
      }
      List<IResolvedConstructor> _declaredConstructors = resolvedFeatures.getDeclaredConstructors();
      for (final IResolvedConstructor constructor : _declaredConstructors) {
        boolean _skipFeature_1 = this.skipFeature(constructor.getDeclaration());
        boolean _not_1 = (!_skipFeature_1);
        if (_not_1) {
          this.xtendOutlineNodeBuilder.buildResolvedFeatureNode(inferredType, constructor, superTypeContext);
        }
      }
      List<IResolvedOperation> _declaredOperations = resolvedFeatures.getDeclaredOperations();
      for (final IResolvedOperation operation : _declaredOperations) {
        if (((!this.skipFeature(operation.getDeclaration())) && (!superTypeContext.isProcessed(operation.getDeclaration())))) {
          this.xtendOutlineNodeBuilder.buildResolvedFeatureNode(inferredType, operation, superTypeContext);
        }
      }
      final JvmType declaredType = superTypeRef.getType();
      if ((declaredType instanceof JvmDeclaredType)) {
        final IXtendOutlineContext nestedTypeContext = superTypeContext.hideInherited();
        final Consumer<JvmDeclaredType> _function = (JvmDeclaredType it) -> {
          this.buildJvmType(it, nestedTypeContext);
        };
        Iterables.<JvmDeclaredType>filter(((JvmDeclaredType)declaredType).getMembers(), JvmDeclaredType.class).forEach(_function);
      }
    }
  }
}
 
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: Utils.java    From sarl with Apache License 2.0 2 votes vote down vote up
/** Replies if the given type is an interface.
 *
 * @param type - the type to test.
 * @return {@code true} if the given type is an interface.
 */
public static boolean isInterface(LightweightTypeReference type) {
	return type.getType() instanceof JvmGenericType
			&& ((JvmGenericType) type.getType()).isInterface();
}