Java Code Examples for org.eclipse.jdt.core.dom.ITypeBinding#getTypeArguments()

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#getTypeArguments() . 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: Resolver.java    From DesigniteJava with Apache License 2.0 6 votes vote down vote up
private void addNonPrimitiveParameters(SM_Project parentProject, TypeInfo typeInfo, ITypeBinding iType) {
	if (iType.isFromSource() && iType.getModifiers() != 0) {
		SM_Type inferredBasicType = findType(iType.getName(), iType.getPackage().getName(), parentProject);
		addParameterIfNotAlreadyExists(typeInfo, inferredBasicType);
	}
	for (ITypeBinding typeParameter : iType.getTypeArguments()) {
		if (typeParameter.isParameterizedType()) {
			addNonPrimitiveParameters(parentProject, typeInfo, typeParameter);
		} else {
			if (typeParameter.isFromSource() && typeParameter.getModifiers() != 0) {
				SM_Type inferredType = findType(typeParameter.getName(), typeParameter.getPackage().getName(),
						parentProject);
				if (inferredType != null) {
					addParameterIfNotAlreadyExists(typeInfo, inferredType);
				}
			}
		}
	}
}
 
Example 2
Source File: Invocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ITypeBinding[] getInferredTypeArguments(Expression invocation) {
	IMethodBinding methodBinding;
	switch (invocation.getNodeType()) {
		case ASTNode.METHOD_INVOCATION:
			methodBinding= ((MethodInvocation) invocation).resolveMethodBinding();
			return methodBinding == null ? null : methodBinding.getTypeArguments();
		case ASTNode.SUPER_METHOD_INVOCATION:
			methodBinding= ((SuperMethodInvocation) invocation).resolveMethodBinding();
			return methodBinding == null ? null : methodBinding.getTypeArguments();
		case ASTNode.CLASS_INSTANCE_CREATION:
			Type type= ((ClassInstanceCreation) invocation).getType();
			ITypeBinding typeBinding= type.resolveBinding();
			return typeBinding == null ? null : typeBinding.getTypeArguments();
			
		default:
			throw new IllegalArgumentException(invocation.toString());
	}
}
 
Example 3
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the appropriate ParameterizedType node. Recursion is needed to
 * handle the nested case (e.g., Vector<Vector<String>>).
 * @param ast
 * @param typeBinding
 * @return the created type
 */
private Type createParameterizedType(AST ast, ITypeBinding typeBinding){
	if (typeBinding.isParameterizedType() && !typeBinding.isRawType()){
		Type baseType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName()));
		ParameterizedType newType= ast.newParameterizedType(baseType);
		for (int i=0; i < typeBinding.getTypeArguments().length; i++){
			ITypeBinding typeArg= typeBinding.getTypeArguments()[i];
			Type argType= createParameterizedType(ast, typeArg); // recursive call
			newType.typeArguments().add(argType);
		}
		return newType;
	} else {
		if (!typeBinding.isTypeVariable()){
			return ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName()));
		} else {
			return ast.newSimpleType(ast.newSimpleName(typeBinding.getName()));
		}
	}
}
 
Example 4
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void collectTypeVariables(ITypeBinding typeBinding, Set<ITypeBinding> typeVariablesCollector) {
	if (typeBinding.isTypeVariable()) {
		typeVariablesCollector.add(typeBinding);
		ITypeBinding[] typeBounds= typeBinding.getTypeBounds();
		for (int i= 0; i < typeBounds.length; i++)
			collectTypeVariables(typeBounds[i], typeVariablesCollector);

	} else if (typeBinding.isArray()) {
		collectTypeVariables(typeBinding.getElementType(), typeVariablesCollector);

	} else if (typeBinding.isParameterizedType()) {
		ITypeBinding[] typeArguments= typeBinding.getTypeArguments();
		for (int i= 0; i < typeArguments.length; i++)
			collectTypeVariables(typeArguments[i], typeVariablesCollector);

	} else if (typeBinding.isWildcardType()) {
		ITypeBinding bound= typeBinding.getBound();
		if (bound != null) {
			collectTypeVariables(bound, typeVariablesCollector);
		}
	}
}
 
Example 5
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus checkTempTypeForLocalTypeUsage() throws JavaModelException {
	Expression expression = getSelectedExpression().getAssociatedExpression();
	Type resultingType = null;
	ITypeBinding typeBinding = expression.resolveTypeBinding();
	AST ast = fCURewrite.getAST();

	if (expression instanceof ClassInstanceCreation && (typeBinding == null || typeBinding.getTypeArguments().length == 0)) {
		resultingType = ((ClassInstanceCreation) expression).getType();
	} else if (expression instanceof CastExpression) {
		resultingType = ((CastExpression) expression).getType();
	} else {
		if (typeBinding == null) {
			typeBinding = ASTResolving.guessBindingForReference(expression);
		}
		if (typeBinding != null) {
			typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
			ImportRewrite importRewrite = fCURewrite.getImportRewrite();
			ImportRewriteContext context = new ContextSensitiveImportRewriteContext(expression, importRewrite);
			resultingType = importRewrite.addImport(typeBinding, ast, context, TypeLocation.LOCAL_VARIABLE);
		} else {
			resultingType = ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
		}
	}

	IMethodBinding declaringMethodBinding = getMethodDeclaration().resolveBinding();
	ITypeBinding[] methodTypeParameters = declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
	LocalTypeAndVariableUsageAnalyzer analyzer = new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
	resultingType.accept(analyzer);
	boolean usesLocalTypes = !analyzer.getUsageOfEnclosingNodes().isEmpty();
	if (usesLocalTypes) {
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractFieldRefactoring_uses_type_declared_locally);
	}
	return null;
}
 
Example 6
Source File: AbstractPairedInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if the given type binding references a type
 * variable, at any depth.
 */
protected static boolean containsTypeVariableReferences(
    ITypeBinding typeBinding) {
  if (typeBinding.isTypeVariable()) {
    return true;
  }

  if (typeBinding.isArray()) {
    return containsTypeVariableReferences(typeBinding.getComponentType());
  }

  if (typeBinding.isParameterizedType()) {
    ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
    for (int i = 0; i < typeArguments.length; ++i) {
      if (containsTypeVariableReferences(typeArguments[i])) {
        return true;
      }
    }
  }

  if (typeBinding.isWildcardType()) {
    ITypeBinding bound = typeBinding.getBound();
    if (bound != null) {
      return containsTypeVariableReferences(bound);
    }
  }

  return false;
}
 
Example 7
Source File: AsynchronousInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Validate that the AsyncCallback's parameterization and the sync method's
 * return type are assignment compatible.
 */
@SuppressWarnings("unchecked")
private List<CategorizedProblem> doValidateReturnTypes(
    MethodDeclaration node, SingleVariableDeclaration lastParameter,
    ITypeBinding[] parameterTypes, IMethodBinding dependentMethod) {
  ITypeBinding asyncCallbackParam = parameterTypes[parameterTypes.length - 1];
  if (asyncCallbackParam.isParameterizedType()) {
    ITypeBinding[] typeArguments = asyncCallbackParam.getTypeArguments();
    ITypeBinding syncReturnTypeBinding = dependentMethod.getReturnType();

    ITypeBinding typeBinding = syncReturnTypeBinding;
    if (syncReturnTypeBinding.isPrimitive()) {
      String qualifiedWrapperTypeName = JavaASTUtils.getWrapperTypeName(syncReturnTypeBinding.getQualifiedName());
      typeBinding = node.getAST().resolveWellKnownType(
          qualifiedWrapperTypeName);
    }

    boolean compatible = false;
    if (typeBinding != null) {
      compatible = canAssign(typeArguments[0], typeBinding);
    }

    if (!compatible) {
      ParameterizedType parameterizedType = (ParameterizedType) lastParameter.getType();
      List<Type> types = parameterizedType.typeArguments();
      CategorizedProblem problem = RemoteServiceProblemFactory.newAsyncCallbackTypeArgumentMismatchOnAsync(
          types.get(0), typeArguments[0], syncReturnTypeBinding);
      if (problem != null) {
        return Collections.singletonList(problem);
      }
    }
  }

  return Collections.emptyList();
}
 
Example 8
Source File: NewAsyncRemoteServiceInterfaceCreationWizardPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
static void expandTypeBinding(ITypeBinding typeBinding, StringBuilder sb,
    ImportManagerAdapter importsManager) {

  if (typeBinding.isParameterizedType()) {
    expandTypeBinding(typeBinding.getErasure(), sb, importsManager);

    sb.append("<");
    ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
    for (int i = 0; i < typeArguments.length; ++i) {
      if (i != 0) {
        sb.append(", ");
      }
      expandTypeBinding(typeArguments[i], sb, importsManager);
    }

    sb.append(">");
  } else if (typeBinding.isWildcardType()) {
    ITypeBinding bound = typeBinding.getBound();
    if (bound == null) {
      sb.append("?");
    } else {
      if (typeBinding.isUpperbound()) {
        sb.append("? extends ");
      } else {
        sb.append("? super ");
      }
      expandTypeBinding(bound, sb, importsManager);
    }
  } else if (typeBinding.isTypeVariable()) {
    sb.append(typeBinding.getName());
  } else if (typeBinding.isArray()) {
    expandTypeBinding(typeBinding.getComponentType(), sb, importsManager);
    sb.append("[]");
  } else if (typeBinding.isPrimitive()) {
    sb.append(typeBinding.getName());
  } else {
    sb.append(importsManager.addImport(typeBinding));
  }
}
 
Example 9
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the necessary changes to remove method type parameters if they
 * match with enclosing type parameters.
 *
 * @param rewrite
 *            the ast rewrite to use
 * @param declaration
 *            the method declaration to remove type parameters
 * @param status
 *            the refactoring status
 */
protected void createMethodTypeParameters(final ASTRewrite rewrite, final MethodDeclaration declaration, final RefactoringStatus status) {
	ITypeBinding binding= fTarget.getType();
	if (binding != null && binding.isParameterizedType()) {
		final IMethodBinding method= declaration.resolveBinding();
		if (method != null) {
			final ITypeBinding[] parameters= method.getTypeParameters();
			if (parameters.length > 0) {
				final ListRewrite rewriter= rewrite.getListRewrite(declaration, MethodDeclaration.TYPE_PARAMETERS_PROPERTY);
				boolean foundStatic= false;
				while (binding != null && !foundStatic) {
					if (Flags.isStatic(binding.getModifiers()))
						foundStatic= true;
					final ITypeBinding[] bindings= binding.getTypeArguments();
					for (int index= 0; index < bindings.length; index++) {
						for (int offset= 0; offset < parameters.length; offset++) {
							if (parameters[offset].getName().equals(bindings[index].getName())) {
								rewriter.remove((ASTNode) rewriter.getOriginalList().get(offset), null);
								status.addWarning(Messages.format(RefactoringCoreMessages.MoveInstanceMethodProcessor_present_type_parameter_warning, new Object[] { BasicElementLabels.getJavaElementName(parameters[offset].getName()), BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED) }), JavaStatusContext.create(fMethod));
							}
						}
					}
					binding= binding.getDeclaringClass();
				}
			}
		}
	}
}
 
Example 10
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns a type reference for the given type binding. If the binding is null, an {@link JvmUnknownTypeReference unknown}
 * type reference is returned.
 */
// @NonNull 
protected JvmTypeReference createTypeReference(/* @Nullable */ ITypeBinding typeBinding) {
	if (typeBinding == null) {
		return TypesFactory.eINSTANCE.createJvmUnknownTypeReference();
	}
	if (typeBinding.isArray()) {
		ITypeBinding componentType = typeBinding.getComponentType();
		JvmTypeReference componentTypeReference = createTypeReference(componentType);
		JvmGenericArrayTypeReference typeReference = TypesFactory.eINSTANCE.createJvmGenericArrayTypeReference();
		typeReference.setComponentType(componentTypeReference);
		return typeReference;
	}
	ITypeBinding outer = null;
	if (typeBinding.isMember() && !Modifier.isStatic(typeBinding.getModifiers())) {
		outer = typeBinding.getDeclaringClass();
	}
	JvmParameterizedTypeReference result;
	if (outer != null) {
		JvmParameterizedTypeReference outerReference = (JvmParameterizedTypeReference) createTypeReference(outer);
		result = TypesFactory.eINSTANCE.createJvmInnerTypeReference();
		((JvmInnerTypeReference) result).setOuter(outerReference);
	} else {
		result = TypesFactory.eINSTANCE.createJvmParameterizedTypeReference();
	}
	ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
	if (typeArguments.length != 0) {
		ITypeBinding erasure = typeBinding.getErasure();
		result.setType(createProxy(erasure));
		InternalEList<JvmTypeReference> arguments = (InternalEList<JvmTypeReference>)result.getArguments();
		for (int i = 0; i < typeArguments.length; i++) {
			JvmTypeReference argument = createTypeArgument(typeArguments[i]);
			arguments.addUnique(argument);
		}
	} else {
		result.setType(createProxy(typeBinding));
	}
	return result;
}
 
Example 11
Source File: JavaMethodParameterCodeMining.java    From jdt-codemining with Eclipse Public License 1.0 5 votes vote down vote up
private String getParameterLabel(IMethod method, ITypeBinding calledTypeBinding) throws JavaModelException {
	ParameterMiningLabelBuilder label = new ParameterMiningLabelBuilder();
	if (showType) {
		String paramType = "";
		if (calledTypeBinding.isParameterizedType()) {
			// ex : List<String>
			ITypeBinding typeArgument = calledTypeBinding.getTypeArguments()[parameterIndex];
			paramType = typeArgument.getName();
		} else {
			paramType = method.getParameterTypes()[parameterIndex];
			paramType = Signature.getSimpleName(Signature.toString(Signature.getTypeErasure(paramType)));
			// replace [] with ... when varArgs
			if (parameterIndex == method.getParameterTypes().length - 1 && Flags.isVarargs(method.getFlags())) {
				paramType = paramType.substring(0, paramType.length() - 2) + "...";
			}
		}
		label.addParameterInfo(paramType);
	}
	if (showName) {
		String paramName = method.getParameterNames()[parameterIndex];
		if (!isArgNumber(paramName, method)) {
			label.addParameterInfo(paramName);
		}
	}
	return label.toString();

}
 
Example 12
Source File: ParameterizedType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void initialize(ITypeBinding binding, IType javaElementType) {
	Assert.isTrue(binding.isParameterizedType());
	super.initialize(binding, javaElementType);
	TypeEnvironment environment= getEnvironment();
	fTypeDeclaration= (GenericType)environment.create(binding.getTypeDeclaration());
	ITypeBinding[] typeArguments= binding.getTypeArguments();
	fTypeArguments= new TType[typeArguments.length];
	for (int i= 0; i < typeArguments.length; i++) {
		fTypeArguments[i]= environment.create(typeArguments[i]);
	}
}
 
Example 13
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static Type newCreationType(AST ast, ITypeBinding typeBinding, ImportRewrite importRewrite, ImportRewriteContext importContext) {
	if (typeBinding.isParameterizedType()) {
		Type baseType= newCreationType(ast, typeBinding.getTypeDeclaration(), importRewrite, importContext);
		ParameterizedType parameterizedType= ast.newParameterizedType(baseType);
		for (ITypeBinding typeArgument : typeBinding.getTypeArguments()) {
			parameterizedType.typeArguments().add(newCreationType(ast, typeArgument, importRewrite, importContext));
		}
		return parameterizedType;
		
	} else if (typeBinding.isParameterizedType()) {
		Type elementType= newCreationType(ast, typeBinding.getElementType(), importRewrite, importContext);
		ArrayType arrayType= ast.newArrayType(elementType, 0);
		while (typeBinding.isArray()) {
			Dimension dimension= ast.newDimension();
			IAnnotationBinding[] typeAnnotations= typeBinding.getTypeAnnotations();
			for (IAnnotationBinding typeAnnotation : typeAnnotations) {
				dimension.annotations().add(importRewrite.addAnnotation(typeAnnotation, ast, importContext));
			}
			arrayType.dimensions().add(dimension);
			typeBinding= typeBinding.getComponentType();
		}
		return arrayType;
			
	} else if (typeBinding.isWildcardType()) {
		ITypeBinding bound= typeBinding.getBound();
		typeBinding= (bound != null) ? bound : typeBinding.getErasure();
		return newCreationType(ast, typeBinding, importRewrite, importContext);
		
	} else {
		return importRewrite.addImport(typeBinding, ast, importContext);
	}
}
 
Example 14
Source File: ConvertIterableLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the type of elements returned by the iterator.
 *
 * @param iterator
 *            the iterator type binding, or <code>null</code>
 * @return the element type
 */
private ITypeBinding getElementType(final ITypeBinding iterator) {
	if (iterator != null) {
		final ITypeBinding[] bindings= iterator.getTypeArguments();
		if (bindings.length > 0) {
			ITypeBinding arg= bindings[0];
			if (arg.isWildcardType()) {
				arg= ASTResolving.normalizeWildcardType(arg, true, getRoot().getAST());
			}
			return arg;
		}
	}
	return getRoot().getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
 
Example 15
Source File: ExtractToNullCheckedLocalProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/** 
 * Create a fresh type reference
 * @param typeBinding the type we want to refer to
 * @param ast AST for creating new nodes
 * @param imports use this for optimal type names
 * @return a fully features non-null type reference (can be parameterized and/or array).
 */
public static Type newType(ITypeBinding typeBinding, AST ast, ImportRewrite imports) {
	// unwrap array type:
	int dimensions= typeBinding.getDimensions();
	if (dimensions > 0)
		typeBinding= typeBinding.getElementType();
	
	// unwrap parameterized type:
	ITypeBinding[] typeArguments= typeBinding.getTypeArguments();
	typeBinding= typeBinding.getErasure();	

	// create leaf type:
	Type elementType = (typeBinding.isPrimitive())
				? ast.newPrimitiveType(PrimitiveType.toCode(typeBinding.getName()))
				: ast.newSimpleType(ast.newName(imports.addImport(typeBinding)));

	// re-wrap as parameterized type:
	if (typeArguments.length > 0) {
		ParameterizedType parameterizedType= ast.newParameterizedType(elementType);
		for (ITypeBinding typeArgument : typeArguments)
			parameterizedType.typeArguments().add(newType(typeArgument, ast, imports));
		elementType = parameterizedType;
	}
	
	// re-wrap as array type:
	if (dimensions > 0)
		return ast.newArrayType(elementType, dimensions);
	else
		return elementType;
}
 
Example 16
Source File: RefactoringUtility.java    From JDeodorant with MIT License 5 votes vote down vote up
private static ParameterizedType createQualifiedParameterizedType(AST ast, ITypeBinding typeBinding, ASTRewrite rewriter) {
	ITypeBinding erasure = typeBinding.getErasure();
	ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
	ParameterizedType parameterizedType = ast.newParameterizedType(generateQualifiedTypeFromTypeBinding(erasure, ast, rewriter));
	ListRewrite typeArgumentsRewrite = rewriter.getListRewrite(parameterizedType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
	for(ITypeBinding typeArgument : typeArguments) {
		typeArgumentsRewrite.insertLast(generateQualifiedTypeFromTypeBinding(typeArgument, ast, rewriter), null);
	}
	return parameterizedType;
}
 
Example 17
Source File: RefactoringUtility.java    From JDeodorant with MIT License 5 votes vote down vote up
private static ParameterizedType createParameterizedType(AST ast, ITypeBinding typeBinding, ASTRewrite rewriter) {
	ITypeBinding erasure = typeBinding.getErasure();
	ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
	ParameterizedType parameterizedType = ast.newParameterizedType(generateTypeFromTypeBinding(erasure, ast, rewriter));
	ListRewrite typeArgumentsRewrite = rewriter.getListRewrite(parameterizedType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
	for(ITypeBinding typeArgument : typeArguments) {
		typeArgumentsRewrite.insertLast(generateTypeFromTypeBinding(typeArgument, ast, rewriter), null);
	}
	return parameterizedType;
}
 
Example 18
Source File: CompletionProposalReplacementProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private String[] computeTypeArgumentProposals(CompletionProposal proposal) {
	try {
		IType type = (IType) resolveJavaElement(
				compilationUnit.getJavaProject(), proposal);
		if (type == null) {
			return new String[0];
		}

		ITypeParameter[] parameters = type.getTypeParameters();
		if (parameters.length == 0) {
			return new String[0];
		}

		String[] arguments = new String[parameters.length];

		ITypeBinding expectedTypeBinding = getExpectedTypeForGenericParameters();
		if (expectedTypeBinding != null && expectedTypeBinding.isParameterizedType()) {
			// in this case, the type arguments we propose need to be compatible
			// with the corresponding type parameters to declared type

			IType expectedType= (IType) expectedTypeBinding.getJavaElement();

			IType[] path= TypeProposalUtils.computeInheritancePath(type, expectedType);
			if (path == null) {
				// proposed type does not inherit from expected type
				// the user might be looking for an inner type of proposed type
				// to instantiate -> do not add any type arguments
				return new String[0];
			}

			int[] indices= new int[parameters.length];
			for (int paramIdx= 0; paramIdx < parameters.length; paramIdx++) {
				indices[paramIdx]= TypeProposalUtils.mapTypeParameterIndex(path, path.length - 1, paramIdx);
			}

			// for type arguments that are mapped through to the expected type's
			// parameters, take the arguments of the expected type
			ITypeBinding[] typeArguments= expectedTypeBinding.getTypeArguments();
			for (int paramIdx= 0; paramIdx < parameters.length; paramIdx++) {
				if (indices[paramIdx] != -1) {
					// type argument is mapped through
					ITypeBinding binding= typeArguments[indices[paramIdx]];
					arguments[paramIdx]= computeTypeProposal(binding, parameters[paramIdx]);
				}
			}
		}

		// for type arguments that are not mapped through to the expected type,
		// take the lower bound of the type parameter
		for (int i = 0; i < arguments.length; i++) {
			if (arguments[i] == null) {
				arguments[i] = computeTypeProposal(parameters[i]);
			}
		}
		return arguments;
	} catch (JavaModelException e) {
		return new String[0];
	}
}
 
Example 19
Source File: LazyGenericTypeProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Computes the type argument proposals for this type proposals. If there is
 * an expected type binding that is a super type of the proposed type, the
 * wildcard type arguments of the proposed type that can be mapped through
 * to type the arguments of the expected type binding are bound accordingly.
 * <p>
 * For type arguments that cannot be mapped to arguments in the expected
 * type, or if there is no expected type, the upper bound of the type
 * argument is proposed.
 * </p>
 * <p>
 * The argument proposals have their <code>isAmbiguos</code> flag set to
 * <code>false</code> if the argument can be mapped to a non-wildcard type
 * argument in the expected type, otherwise the proposal is ambiguous.
 * </p>
 *
 * @return the type argument proposals for the proposed type
 * @throws JavaModelException if accessing the java model fails
 */
private TypeArgumentProposal[] computeTypeArgumentProposals() throws JavaModelException {
	if (fTypeArgumentProposals == null) {

		IType type= (IType) getJavaElement();
		if (type == null)
			return new TypeArgumentProposal[0];

		ITypeParameter[] parameters= type.getTypeParameters();
		if (parameters.length == 0)
			return new TypeArgumentProposal[0];

		TypeArgumentProposal[] arguments= new TypeArgumentProposal[parameters.length];

		ITypeBinding expectedTypeBinding= getExpectedType();
		if (expectedTypeBinding != null && expectedTypeBinding.isParameterizedType()) {
			// in this case, the type arguments we propose need to be compatible
			// with the corresponding type parameters to declared type

			IType expectedType= (IType) expectedTypeBinding.getJavaElement();

			IType[] path= computeInheritancePath(type, expectedType);
			if (path == null)
				// proposed type does not inherit from expected type
				// the user might be looking for an inner type of proposed type
				// to instantiate -> do not add any type arguments
				return new TypeArgumentProposal[0];

			int[] indices= new int[parameters.length];
			for (int paramIdx= 0; paramIdx < parameters.length; paramIdx++) {
				indices[paramIdx]= mapTypeParameterIndex(path, path.length - 1, paramIdx);
			}

			// for type arguments that are mapped through to the expected type's
			// parameters, take the arguments of the expected type
			ITypeBinding[] typeArguments= expectedTypeBinding.getTypeArguments();
			for (int paramIdx= 0; paramIdx < parameters.length; paramIdx++) {
				if (indices[paramIdx] != -1) {
					// type argument is mapped through
					ITypeBinding binding= typeArguments[indices[paramIdx]];
					arguments[paramIdx]= computeTypeProposal(binding, parameters[paramIdx]);
				}
			}
		}

		// for type arguments that are not mapped through to the expected type,
		// take the lower bound of the type parameter
		for (int i= 0; i < arguments.length; i++) {
			if (arguments[i] == null) {
				arguments[i]= computeTypeProposal(parameters[i]);
			}
		}
		fTypeArgumentProposals= arguments;
	}
	return fTypeArgumentProposals;
}
 
Example 20
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static boolean isUseableTypeInContext(ITypeBinding type, IBinding context, boolean noWildcards) {
	if (type.isArray()) {
		type= type.getElementType();
	}
	if (type.isAnonymous()) {
		return false;
	}
	if (type.isRawType() || type.isPrimitive()) {
		return true;
	}
	if (type.isTypeVariable()) {
		return isVariableDefinedInContext(context, type);
	}
	if (type.isGenericType()) {
		ITypeBinding[] typeParameters= type.getTypeParameters();
		for (int i= 0; i < typeParameters.length; i++) {
			if (!isUseableTypeInContext(typeParameters[i], context, noWildcards)) {
				return false;
			}
		}
		return true;
	}
	if (type.isParameterizedType()) {
		ITypeBinding[] typeArguments= type.getTypeArguments();
		for (int i= 0; i < typeArguments.length; i++) {
			if (!isUseableTypeInContext(typeArguments[i], context, noWildcards)) {
				return false;
			}
		}
		return true;
	}
	if (type.isCapture()) {
		type= type.getWildcard();
	}

	if (type.isWildcardType()) {
		if (noWildcards) {
			return false;
		}
		if (type.getBound() != null) {
			return isUseableTypeInContext(type.getBound(), context, noWildcards);
		}
	}
	return true;
}