org.eclipse.xtext.xbase.typesystem.references.ITypeReferenceOwner Java Examples

The following examples show how to use org.eclipse.xtext.xbase.typesystem.references.ITypeReferenceOwner. 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 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 #2
Source File: ResolvedOperationInHierarchy.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected TypeParameterSubstitutor<?> getSubstitutor() {
	if (isRawTypeInheritance()) {
		return new RawTypeSubstitutor(getContextType().getOwner());
	}
	TypeParameterSubstitutor<?> result = super.getSubstitutor();
	List<JvmTypeParameter> typeParameters = getTypeParameters();
	if (!typeParameters.isEmpty()) {
		List<JvmTypeParameter> resolvedTypeParameters = getResolvedTypeParameters();
		int max = Math.min(typeParameters.size(), resolvedTypeParameters.size());
		ITypeReferenceOwner owner = getContextType().getOwner();
		Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> additionalMapping = Maps.newHashMapWithExpectedSize(max);
		for(int i = 0; i < max; i++) {
			LightweightTypeReference localReference = owner.newParameterizedTypeReference(resolvedTypeParameters.get(i));
			additionalMapping.put(typeParameters.get(i), new LightweightMergedBoundTypeArgument(localReference, VarianceInfo.INVARIANT));
		}
		result.enhanceMapping(additionalMapping);
	}
	return result;
}
 
Example #3
Source File: ReplacingAppendableTest.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected XtextDocument insertListField(final String model, final String fieldName)
		throws Exception {
	final int cursorPosition = model.indexOf('|');
	String actualModel = model.replace("|", " ");
	final XtendFile file = testHelper.xtendFile("Foo", actualModel);
	final XtextDocument document = documentProvider.get();
	document.set(actualModel);
	XtextResource xtextResource = (XtextResource) file.eResource();
	document.setInput(xtextResource);
	final EObject context = eObjectAtOffsetHelper.resolveElementAt(xtextResource, cursorPosition);
	document.modify(new IUnitOfWork.Void<XtextResource>() {
		@Override
		public void process(XtextResource state) throws Exception {
			ReplacingAppendable a = appendableFactory.create(document, state, cursorPosition, 1);
			ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, context);
			LightweightTypeReference typeRef = owner.toLightweightTypeReference(services.getTypeReferences().getTypeForName(List.class, context, typesFactory.createJvmWildcardTypeReference()));
			a.append(typeRef);
			a.append(" ").append(fieldName);
			a.commitChanges();
		}
	});
	return document;
}
 
Example #4
Source File: XbaseTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected void _computeTypes(XTypeLiteral object, ITypeComputationState state) {
	JvmType type = object.getType();
	if (type == null) {
		return;
	}
	checkTypeParameterNotAllowedAsLiteral(object, type, state);
	ITypeReferenceOwner owner = state.getReferenceOwner();
	LightweightTypeReference clazz = owner.newParameterizedTypeReference(type);
	for (int i = 0; i < object.getArrayDimensions().size(); i++) {
		clazz = owner.newArrayTypeReference(clazz);
	}
	if (object.getArrayDimensions().isEmpty()) {
		if (clazz.isPrimitiveVoid()) {
			clazz = state.getReferenceOwner().newReferenceTo(Void.class);
		} else {
			clazz = clazz.getWrapperTypeIfPrimitive();
		}
	}
	LightweightTypeReference result = owner.newReferenceTo(Class.class);
	if (result instanceof ParameterizedTypeReference) {
		ParameterizedTypeReference parameterizedTypeReference = (ParameterizedTypeReference) result;
		parameterizedTypeReference.addTypeArgument(clazz);
	}
	state.acceptActualType(result);
}
 
Example #5
Source File: DispatchHelper.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Computes all the dispatch methods that are declared in the given type or altered
 * by additional cases in this type. The associated operations are sorted by according their parameter types
 * from left to right where the most special types occur before more common types. Ambiguous
 * ordering is resolved alphabetically.
 * 
    * An exemplary order would look like this
 * <pre>
 *   method(String)
 *   method(Serializable)
 *   method(CharSequence)
 *   method(Object)
 * </pre>
 * 
 * @return a mapping from {@link DispatchSignature signature} to sorted operations.
 */
public ListMultimap<DispatchSignature, JvmOperation> getDeclaredOrEnhancedDispatchMethods(JvmDeclaredType type) {
	ListMultimap<DispatchSignature, JvmOperation> result = Multimaps2.newLinkedHashListMultimap(2,4);
	Iterable<JvmOperation> operations = type.getDeclaredOperations();
	ITypeReferenceOwner owner = new StandardTypeReferenceOwner(services, type);
	ContextualVisibilityHelper contextualVisibilityHelper = new ContextualVisibilityHelper(visibilityHelper, owner.newParameterizedTypeReference(type));
	for(JvmOperation operation: operations) {
		if (isDispatchFunction(operation)) {
			DispatchSignature signature = new DispatchSignature(operation.getSimpleName().substring(1), operation.getParameters().size());
			if (!result.containsKey(signature)) {
				List<JvmOperation> allOperations = getAllDispatchMethods(signature, type,
						contextualVisibilityHelper);
				result.putAll(signature, allOperations);
			}
		}
	}
	return result;
}
 
Example #6
Source File: StaticFeatureOnTypeLiteralScope.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected List<IEObjectDescription> getAllLocalElements() {
	List<IEObjectDescription> result = super.getAllLocalElements();
	if (getSession().isInstanceContext() && !isExplicitStaticFeatureCall()) {
		ITypeReferenceOwner owner = getReceiverType().getOwner();
		QualifiedThisOrSuperDescription thisDescription = new QualifiedThisOrSuperDescription(THIS,
				owner.newParameterizedTypeReference(getTypeLiteral()), getBucket().getId(), true, getReceiver());
		addToList(thisDescription, result);
		JvmType receiverRawType = getTypeLiteral();
		if (receiverRawType instanceof JvmDeclaredType) {
			JvmType referencedType = receiverRawType;
			// If the receiver type is an interface, 'super' always refers to that interface
			if (!(receiverRawType instanceof JvmGenericType && ((JvmGenericType) receiverRawType).isInterface())) {
				JvmTypeReference superType = ((JvmDeclaredType) receiverRawType).getExtendedClass();
				if (superType != null) {
					referencedType = superType.getType();
				}
			}
			QualifiedThisOrSuperDescription superDescription = new QualifiedThisOrSuperDescription(SUPER,
					owner.newParameterizedTypeReference(referencedType), getBucket().getId(), true, getReceiver());
			addToList(superDescription, result);
		}
	}
	return result;
}
 
Example #7
Source File: TypeConformanceComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected LightweightTypeReference doGetTypeParametersForSuperType(
		final Multimap<JvmType, LightweightTypeReference> all, JvmArrayType rawType, ITypeReferenceOwner owner,
		List<LightweightTypeReference> types) {
	JvmComponentType componentType = rawType.getComponentType();
	Multimap<JvmType, LightweightTypeReference> copiedMultimap = LinkedHashMultimap.create(all);
	Collection<LightweightTypeReference> originalReferences = all.get(rawType);
	List<LightweightTypeReference> componentReferences = Lists.newArrayListWithCapacity(originalReferences.size());
	for(LightweightTypeReference originalReference: originalReferences) {
		addComponentType(originalReference, componentReferences);
	}
	copiedMultimap.replaceValues(componentType, componentReferences);
	List<LightweightTypeReference> componentRequests = Lists.newArrayListWithCapacity(types.size());
	for(LightweightTypeReference type: types) {
		addComponentType(type, componentRequests);
	}
	LightweightTypeReference componentTypeReference = getTypeParametersForSuperType(
			copiedMultimap, 
			componentType,
			owner,
			componentRequests);
	if (componentTypeReference != null) {
		return owner.newArrayTypeReference(componentTypeReference);
	}
	return null;
}
 
Example #8
Source File: TypeConformanceComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
protected LightweightTypeReference doGetTypeParametersForSuperType(
		final Multimap<JvmType, LightweightTypeReference> all, JvmGenericType rawType, ITypeReferenceOwner owner,
		List<LightweightTypeReference> types) {
	// if we do not declare any parameters it is safe to return the first candidate
	if (!hasTypeParameters(rawType)) {
		return getFirstForRawType(all, rawType); 
	}
	ParameterizedTypeReference result = owner.newParameterizedTypeReference(rawType);
	pushRequestedTypes(types);
	if (!enhanceSuperType(Lists.newArrayList(all.get(rawType)), result)) {
		return null;
	}
	FunctionTypeReference resultAsFunctionType = result.getAsFunctionTypeReference();
	if (resultAsFunctionType != null)
		return resultAsFunctionType;
	return result;
}
 
Example #9
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 #10
Source File: CollectionLiteralsTypeComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a map type reference that comes as close as possible / necessary to its expected type.
 */
protected LightweightTypeReference createMapTypeReference(JvmGenericType mapType, LightweightTypeReference pairType, LightweightTypeReference expectation, ITypeReferenceOwner owner) {
	List<LightweightTypeReference> leftAndRight = pairType.getTypeArguments();
	
	LightweightTypeReference left = leftAndRight.get(0).getInvariantBoundSubstitute();
	LightweightTypeReference right = leftAndRight.get(1).getInvariantBoundSubstitute();
	
	LightweightTypeReference mapExpectation = getMapExpectation(expectation);
	if (mapExpectation != null) {
		List<LightweightTypeReference> typeArguments = expectation.getTypeArguments();
		left = doNormalizeElementType(left, typeArguments.get(0));
		right = doNormalizeElementType(right, typeArguments.get(1));
	}
	ParameterizedTypeReference result = owner.newParameterizedTypeReference(mapType);
	result.addTypeArgument(left.copyInto(owner));
	result.addTypeArgument(right.copyInto(owner));
	if (mapExpectation != null && !expectation.isAssignableFrom(result)) {
		// expectation does not match the computed type, but looks good according to the element types:
		// use expected type
		if (matchesExpectation(left, mapExpectation.getTypeArguments().get(0)) && matchesExpectation(right, mapExpectation.getTypeArguments().get(1))) {
			return expectation;
		}
	}
	return result;
}
 
Example #11
Source File: TypeConvertingCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
private void convertMultiType(LightweightTypeReference expectation, CompoundTypeReference multiType, XExpression context,
		ITreeAppendable b, Later expression) {
	LightweightTypeReference castTo = null;
	List<LightweightTypeReference> components = multiType.getMultiTypeComponents();
	ITypeReferenceOwner owner = multiType.getOwner();
	LightweightTypeReference commonType = owner.getServices().getTypeConformanceComputer().getCommonSuperType(components, owner);
	if (!isJavaConformant(expectation, commonType)) {
		for(LightweightTypeReference candidate: multiType.getMultiTypeComponents()) {
			if (isJavaConformant(expectation, candidate)) {
				castTo = candidate;
				break;
			}
		}
	}
	if (castTo != null && mustInsertTypeCast(context, castTo)) {
		b.append("((");
		b.append(castTo);
		b.append(")");
		expression.exec(b);
		b.append(")");
	} else {
		expression.exec(b);
	}
}
 
Example #12
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 #13
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 #14
Source File: ExpressionScope.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public ExpressionScope(FeatureScopes featureScopes, EObject context, Anchor anchor, ITypeReferenceOwner owner) {
	this.owner = owner;
	this.data = Lists.newArrayListWithExpectedSize(2);
	this.featureScopes = featureScopes;
	this.context = context;
	this.anchor = anchor;
}
 
Example #15
Source File: WrapperTypeLookup.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
private static LightweightTypeReference findTopLevelType(LightweightTypeReference context, String typeName) {
	ITypeReferenceOwner owner = context.getOwner();
	ResourceSet resourceSet = owner.getContextResourceSet();
	Resource typeResource = resourceSet.getResource(URIHelperConstants.OBJECTS_URI.appendSegment(typeName), true);
	EList<EObject> contents = typeResource.getContents();
	if (contents.isEmpty()) {
		return null;
	}
	JvmType type = (JvmType) contents.get(0);
	if (type == null)
		return null;
	return owner.newParameterizedTypeReference(type);
}
 
Example #16
Source File: ResolvedFeature.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected LightweightTypeReference getDeclaredType(JvmIdentifiableElement feature) {
	if (feature instanceof JvmConstructor) {
		return getState().getReferenceOwner().newReferenceTo(Void.TYPE);
	}
	/*
	 * The actual result type is Class<? extends |X|> where |X| is the erasure of 
	 * the static type of the expression on which getClass is called. For example, 
	 * no cast is required in this code fragment:
	 *   Number n = 0;
	 *   Class<? extends Number> c = n.getClass();
	 */
	if (feature instanceof JvmOperation && feature.getSimpleName().equals("getClass")) {
		JvmOperation getClassOperation = (JvmOperation) feature;
		if (getClassOperation.getParameters().isEmpty() && "java.lang.Object".equals(getClassOperation.getDeclaringType().getIdentifier())) {
			LightweightTypeReference receiverType = getReceiverType();
			if (receiverType == null) {
				throw new IllegalStateException("Cannot determine type of receiver "+ getReceiver());
			}
			List<JvmType> rawTypes = receiverType.getRawTypes();
			if (rawTypes.isEmpty()) {
				return super.getDeclaredType(feature);
			}
			ITypeReferenceOwner owner = receiverType.getOwner();
			ParameterizedTypeReference result = owner.newParameterizedTypeReference(((JvmOperation) feature).getReturnType().getType());
			WildcardTypeReference wildcard = owner.newWildcardTypeReference();
			wildcard.addUpperBound(owner.toPlainTypeReference(rawTypes.get(0)));
			result.addTypeArgument(wildcard);
			return result;
		}
	}
	return super.getDeclaredType(feature);
}
 
Example #17
Source File: MockTypeParameterSubstitutor.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public LightweightTypeReference doVisitParameterizedTypeReference(final ParameterizedTypeReference reference, final Set<JvmTypeParameter> visiting) {
  final JvmType type = reference.getType();
  if ((type instanceof JvmTypeParameter)) {
    boolean _add = visiting.add(((JvmTypeParameter)type));
    boolean _not = (!_add);
    if (_not) {
      return null;
    }
    try {
      final LightweightMergedBoundTypeArgument mappedReference = this.getTypeParameterMapping().get(type);
      if ((mappedReference != null)) {
        return mappedReference.getTypeReference().<Set<JvmTypeParameter>, LightweightTypeReference>accept(this, visiting);
      } else {
        ITypeReferenceOwner _owner = this.getOwner();
        Object _object = new Object();
        final SimpleUnboundTypeReference result = new SimpleUnboundTypeReference(_owner, ((JvmTypeParameter)type), _object);
        Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> _typeParameterMapping = this.getTypeParameterMapping();
        LightweightMergedBoundTypeArgument _lightweightMergedBoundTypeArgument = new LightweightMergedBoundTypeArgument(result, VarianceInfo.INVARIANT);
        _typeParameterMapping.put(((JvmTypeParameter)type), _lightweightMergedBoundTypeArgument);
        return result;
      }
    } finally {
      visiting.remove(type);
    }
  }
  return super.doVisitParameterizedTypeReference(reference, visiting);
}
 
Example #18
Source File: OverrideHelper.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected boolean isMatchesSignature(JvmFormalParameter parameter, JvmFormalParameter candidateParameter, TypeParameterSubstitutor<?> substitutor, ITypeReferenceOwner owner) {
	JvmTypeReference parameterType = parameter.getParameterType();
	if (parameterType == null || parameterType.getType() == null) {
		return false;
	} 
	String identifier = parameterType.getIdentifier();
	LightweightTypeReference candidateParameterType = substitutor.substitute(owner.toLightweightTypeReference(candidateParameter.getParameterType()));
	return identifier.equals(candidateParameterType.getJavaIdentifier());
}
 
Example #19
Source File: TypeInsteadOfConstructorLinkingCandidate.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void applyType() {
	JvmType type = (JvmType) getFeature();
	if (type == null || type.eIsProxy()) {
		throw new IllegalStateException();
	}
	ITypeReferenceOwner referenceOwner = getResolvedTypes().getReferenceOwner();
	ParameterizedTypeReference result = referenceOwner.newParameterizedTypeReference(type);
	for(LightweightTypeReference typeArgument: getTypeArguments()) {
		result.addTypeArgument(typeArgument);
	}
	getState().acceptActualType(result);
}
 
Example #20
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 #21
Source File: ActualTypeArgumentMergeTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public Map<JvmTypeParameter, List<LightweightBoundTypeArgument>> mappedBy(final String typeParameters, final String... alternatingTypeReferences) {
  try {
    StringConcatenation _builder = new StringConcatenation();
    _builder.append("def ");
    {
      boolean _isNullOrEmpty = StringExtensions.isNullOrEmpty(typeParameters);
      boolean _not = (!_isNullOrEmpty);
      if (_not) {
        _builder.append("<");
        _builder.append(typeParameters);
        _builder.append(">");
      }
    }
    _builder.append(" void method(");
    final Function1<String, CharSequence> _function = (String it) -> {
      return it;
    };
    String _join = IterableExtensions.<String>join(((Iterable<String>)Conversions.doWrapArray(alternatingTypeReferences)), null, " p, ", " p", _function);
    _builder.append(_join);
    _builder.append(") {}");
    final String signature = _builder.toString();
    final XtendFunction function = this.function(signature.toString());
    final JvmOperation operation = this._iXtendJvmAssociations.getDirectlyInferredOperation(function);
    EList<JvmTypeParameter> _typeParameters = operation.getTypeParameters();
    ITypeReferenceOwner _owner = this.getOwner();
    final ActualTypeArgumentCollector collector = new ActualTypeArgumentCollector(_typeParameters, BoundTypeArgumentSource.INFERRED, _owner);
    int _size = ((List<String>)Conversions.doWrapArray(alternatingTypeReferences)).size();
    int _minus = (_size - 1);
    IntegerRange _withStep = new IntegerRange(0, _minus).withStep(2);
    for (final Integer i : _withStep) {
      collector.populateTypeParameterMapping(this.toLightweightTypeReference(operation.getParameters().get((i).intValue()).getParameterType()), this.toLightweightTypeReference(operation.getParameters().get(((i).intValue() + 1)).getParameterType()));
    }
    return collector.getTypeParameterMapping();
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #22
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 #23
Source File: CommonSuperTypeTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCommonSuperType_23() {
  try {
    this.function("def void m() {}");
    ITypeReferenceOwner _owner = this.getOwner();
    AnyTypeReference _anyTypeReference = new AnyTypeReference(_owner);
    ITypeReferenceOwner _owner_1 = this.getOwner();
    AnyTypeReference _anyTypeReference_1 = new AnyTypeReference(_owner_1);
    final List<LightweightTypeReference> types = CollectionLiterals.<LightweightTypeReference>newImmutableList(_anyTypeReference, _anyTypeReference_1);
    final LightweightTypeReference superType = this.getServices().getTypeConformanceComputer().getCommonSuperType(types, this.getOwner());
    Assert.assertEquals("null", superType.getSimpleName());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #24
Source File: LogicalContainerAwareReentrantTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
protected IFeatureScopeSession addThisAndSuper(
		IFeatureScopeSession session,
		ITypeReferenceOwner owner,
		JvmDeclaredType thisType,
		/* @Nullable */ JvmTypeReference superType,
		boolean addNestedTypes) {
	IFeatureScopeSession childSession = session;
	if (thisType.eContainer() != null) {
		if (thisType.isStatic()) {
			childSession = childSession.dropLocalElements();
		} else {
			childSession = childSession.captureLocalElements();
		}
	}
	if (superType != null && superType.getType() != null) {
		ImmutableMap.Builder<QualifiedName, JvmIdentifiableElement> builder = ImmutableMap.builder();
		builder.put(IFeatureNames.THIS, thisType);
		builder.put(IFeatureNames.SUPER, superType.getType());
		childSession = childSession.addLocalElements(builder.build(), owner);
	} else {
		childSession = childSession.addLocalElement(IFeatureNames.THIS, thisType, owner);
	}
	childSession = addThisTypeToStaticScope(childSession, thisType);
	if (addNestedTypes)
		childSession = childSession.addNestedTypesToScope(thisType);
	return childSession;
}
 
Example #25
Source File: TypeArgumentFromComputedTypeCollector.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public static void resolveAgainstActualType(final LightweightTypeReference declaredType, LightweightTypeReference actualType,
		Collection<JvmTypeParameter> typeParameters, Map<JvmTypeParameter, LightweightMergedBoundTypeArgument> typeParameterMapping,
		BoundTypeArgumentSource source,
		ITypeReferenceOwner owner) {
	if (declaredType.isRawType() || actualType.isRawType())
		return;
	TypeArgumentFromComputedTypeCollector implementation = new TypeArgumentFromComputedTypeCollector(typeParameters, source, owner);
	implementation.populateTypeParameterMapping(declaredType, actualType);
	Map<JvmTypeParameter, List<LightweightBoundTypeArgument>> parameterMapping = implementation.rawGetTypeParameterMapping();
	for(Map.Entry<JvmTypeParameter, List<LightweightBoundTypeArgument>> entry: parameterMapping.entrySet()) {
		LightweightMergedBoundTypeArgument boundTypeArgument = typeParameterMapping.get(entry.getKey());
		if (boundTypeArgument != null ) {
			List<LightweightBoundTypeArgument> computedBoundTypeArguments = entry.getValue();
			for(LightweightBoundTypeArgument computedBoundTypeArgument: computedBoundTypeArguments) { 
				if (computedBoundTypeArgument.getSource() == BoundTypeArgumentSource.RESOLVED) {
					VarianceInfo varianceInfo = computedBoundTypeArgument.getDeclaredVariance().mergeDeclaredWithActual(computedBoundTypeArgument.getActualVariance());
					typeParameterMapping.put(entry.getKey(), new LightweightMergedBoundTypeArgument(computedBoundTypeArgument.getTypeReference(), varianceInfo));
				} else if (boundTypeArgument.getTypeReference() instanceof UnboundTypeReference) {
					UnboundTypeReference typeReference = (UnboundTypeReference) boundTypeArgument.getTypeReference();
					if (!typeReference.internalIsResolved()) {
						if (!(computedBoundTypeArgument.getTypeReference() instanceof UnboundTypeReference) || 
								((UnboundTypeReference) computedBoundTypeArgument.getTypeReference()).getHandle() != typeReference.getHandle())
							typeReference.acceptHint(computedBoundTypeArgument);
					}
				}
			}
		}
	}
}
 
Example #26
Source File: SARLHoverSignatureProvider.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the type name for the given type.
 *
 * @param type the type.
 * @return the string representation of the given type.
 */
protected String getTypeName(JvmType type) {
	if (type != null) {
		if (type instanceof JvmDeclaredType) {
			final ITypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, type);
			return owner.toLightweightTypeReference(type).getHumanReadableName();
		}
		return type.getSimpleName();
	}
	return Messages.SARLHoverSignatureProvider_1;
}
 
Example #27
Source File: ActualTypeArgumentCollectorTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public Map<JvmTypeParameter, List<LightweightBoundTypeArgument>> mappedBy(final String typeParameters, final String... alternatingTypeReferences) {
  final JvmOperation operation = this.operation(typeParameters, alternatingTypeReferences);
  EList<JvmTypeParameter> _typeParameters = operation.getTypeParameters();
  ITypeReferenceOwner _owner = this.getOwner();
  final ActualTypeArgumentCollector collector = new ActualTypeArgumentCollector(_typeParameters, BoundTypeArgumentSource.INFERRED, _owner);
  int _size = ((List<String>)Conversions.doWrapArray(alternatingTypeReferences)).size();
  int _minus = (_size - 1);
  IntegerRange _withStep = new IntegerRange(0, _minus).withStep(2);
  for (final Integer i : _withStep) {
    collector.populateTypeParameterMapping(this.toLightweightTypeReference(operation.getParameters().get((i).intValue()).getParameterType()), this.toLightweightTypeReference(operation.getParameters().get(((i).intValue() + 1)).getParameterType()));
  }
  return collector.getTypeParameterMapping();
}
 
Example #28
Source File: AbstractTestingTypeReferenceOwner.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Pure
protected ITypeReferenceOwner getOwner() {
  return this.owner;
}
 
Example #29
Source File: TypeExpectation.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public TypeExpectation copyInto(ITypeReferenceOwner referenceOwner) {
	if (reference == null || reference.isOwnedBy(referenceOwner))
		return this;
	return new TypeExpectation(reference.copyInto(referenceOwner), getState(), isReturnType());
}
 
Example #30
Source File: RootNoExpectation.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public RootNoExpectation copyInto(ITypeReferenceOwner referenceOwner) {
	return this;
}