Java Code Examples for org.eclipse.jdt.core.IType#getTypeParameters()

The following examples show how to use org.eclipse.jdt.core.IType#getTypeParameters() . 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: TypeProposalUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
static int mapTypeParameterIndex(IType[] path, int pathIndex, int paramIndex) throws JavaModelException, ArrayIndexOutOfBoundsException {
	if (pathIndex == 0) {
		// break condition: we've reached the top of the hierarchy
		return paramIndex;
	}

	IType subType= path[pathIndex];
	IType superType= path[pathIndex - 1];

	String superSignature= findMatchingSuperTypeSignature(subType, superType);
	ITypeParameter param= subType.getTypeParameters()[paramIndex];
	int index= findMatchingTypeArgumentIndex(superSignature, param.getElementName());
	if (index == -1) {
		// not mapped through
		return -1;
	}

	return mapTypeParameterIndex(path, pathIndex - 1, index);
}
 
Example 2
Source File: TypeVariableUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns a type variable mapping from a subclass to a superclass.
 *
 * @param subtype
 *        the type representing the subclass
 * @param supertype
 *        the type representing the superclass
 * @return a type variable mapping. The mapping entries consist of simple type variable names.
 * @throws JavaModelException
 *         if the signature of one of the types involved could not be retrieved
 */
public static TypeVariableMaplet[] subTypeToSuperType(final IType subtype, final IType supertype) throws JavaModelException {
	Assert.isNotNull(subtype);
	Assert.isNotNull(supertype);

	final TypeVariableMaplet[] mapping= subTypeToInheritedType(subtype);
	if (mapping.length > 0) {
		final ITypeParameter[] range= supertype.getTypeParameters();
		if (range.length > 0) {
			final String signature= subtype.getSuperclassTypeSignature();
			if (signature != null) {
				final String[] domain= getVariableSignatures(signature);
				if (domain.length > 0)
					return composeMappings(mapping, signaturesToParameters(domain, range));
			}
		}
	}
	return mapping;
}
 
Example 3
Source File: TypeVariableUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns a type variable mapping from a superclass to a subclass.
 *
 * @param supertype
 *        the type representing the superclass
 * @param subtype
 *        the type representing the subclass
 * @return a type variable mapping. The mapping entries consist of simple type variable names.
 * @throws JavaModelException
 *         if the signature of one of the types involved could not be retrieved
 */
public static TypeVariableMaplet[] superTypeToInheritedType(final IType supertype, final IType subtype) throws JavaModelException {
	Assert.isNotNull(subtype);
	Assert.isNotNull(supertype);

	final ITypeParameter[] domain= supertype.getTypeParameters();
	if (domain.length > 0) {
		final String signature= subtype.getSuperclassTypeSignature();
		if (signature != null) {
			final String[] range= getVariableSignatures(signature);
			if (range.length > 0)
				return parametersToSignatures(domain, range, true);
		}
	}
	return new TypeVariableMaplet[0];
}
 
Example 4
Source File: MethodProposalInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The type and method signatures received in
 * <code>CompletionProposals</code> of type <code>METHOD_REF</code>
 * contain concrete type bounds. When comparing parameters of the signature
 * with an <code>IMethod</code>, we have to make sure that we match the
 * case where the formal method declaration uses a type variable which in
 * the signature is already substituted with a concrete type (bound).
 * <p>
 * This method creates a map from type variable names to type signatures
 * based on the position they appear in the type declaration. The type
 * signatures are filtered through
 * {@link SignatureUtil#getLowerBound(char[])}.
 * </p>
 *
 * @param type the type to get the variables from
 * @return a map from type variables to concrete type signatures
 * @throws JavaModelException if accessing the java model fails
 */
private Map<String, char[]> computeTypeVariables(IType type) throws JavaModelException {
	Map<String, char[]> map= new HashMap<String, char[]>();
	char[] declarationSignature= fProposal.getDeclarationSignature();
	if (declarationSignature == null) // array methods don't contain a declaration signature
		return map;
	char[][] concreteParameters= Signature.getTypeArguments(declarationSignature);

	ITypeParameter[] typeParameters= type.getTypeParameters();
	for (int i= 0; i < typeParameters.length; i++) {
		String variable= typeParameters[i].getElementName();
		if (concreteParameters.length > i)
			// use lower bound since method equality is only parameter based
			map.put(variable, SignatureUtil.getLowerBound(concreteParameters[i]));
		else
			// fProposal.getDeclarationSignature() is a raw type - use Object
			map.put(variable, "Ljava.lang.Object;".toCharArray()); //$NON-NLS-1$
	}

	return map;
}
 
Example 5
Source File: SuperInterfaceSelectionDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static String getNameWithTypeParameters(IType type) {
	String superName= type.getFullyQualifiedName('.');
	if (!JavaModelUtil.is50OrHigher(type.getJavaProject())) {
		return superName;
	}
	try {
		ITypeParameter[] typeParameters= type.getTypeParameters();
		if (typeParameters.length > 0) {
			StringBuffer buf= new StringBuffer(superName);
			buf.append('<');
			for (int k= 0; k < typeParameters.length; k++) {
				if (k != 0) {
					buf.append(',').append(' ');
				}
				buf.append(typeParameters[k].getElementName());
			}
			buf.append('>');
			return buf.toString();
		}
	} catch (JavaModelException e) {
		// ignore
	}
	return superName;

}
 
Example 6
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new type signature of a subtype.
 *
 * @param subRewrite
 *            the compilation unit rewrite of a subtype
 * @param declaration
 *            the type declaration of a subtype
 * @param extractedType
 *            the extracted super type
 * @param extractedBinding
 *            the binding of the extracted super type
 * @param monitor
 *            the progress monitor to use
 * @throws JavaModelException
 *             if the type parameters cannot be retrieved
 */
protected final void createTypeSignature(final CompilationUnitRewrite subRewrite, final AbstractTypeDeclaration declaration, final IType extractedType, final ITypeBinding extractedBinding, final IProgressMonitor monitor) throws JavaModelException {
	Assert.isNotNull(subRewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(extractedType);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 10);
		final AST ast= subRewrite.getAST();
		Type type= null;
		if (extractedBinding != null) {
			type= subRewrite.getImportRewrite().addImport(extractedBinding, ast);
		} else {
			subRewrite.getImportRewrite().addImport(extractedType.getFullyQualifiedName('.'));
			type= ast.newSimpleType(ast.newSimpleName(extractedType.getElementName()));
		}
		subRewrite.getImportRemover().registerAddedImport(extractedType.getFullyQualifiedName('.'));
		if (type != null) {
			final ITypeParameter[] parameters= extractedType.getTypeParameters();
			if (parameters.length > 0) {
				final ParameterizedType parameterized= ast.newParameterizedType(type);
				for (int index= 0; index < parameters.length; index++)
					parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getElementName())));
				type= parameterized;
			}
		}
		final ASTRewrite rewriter= subRewrite.getASTRewrite();
		if (type != null && declaration instanceof TypeDeclaration) {
			final TypeDeclaration extended= (TypeDeclaration) declaration;
			final Type superClass= extended.getSuperclassType();
			if (superClass != null) {
				rewriter.replace(superClass, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
				subRewrite.getImportRemover().registerRemovedNode(superClass);
			} else
				rewriter.set(extended, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
		}
	} finally {
		monitor.done();
	}
}
 
Example 7
Source File: TypeVariableUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a type variable mapping from a subclass to a superclass.
 *
 * @param type
 *        the type representing the subclass class
 * @return a type variable mapping. The mapping entries consist of simple type variable names.
 * @throws JavaModelException
 *         if the signature of one of the types involved could not be retrieved
 */
public static TypeVariableMaplet[] subTypeToInheritedType(final IType type) throws JavaModelException {
	Assert.isNotNull(type);

	final ITypeParameter[] domain= type.getTypeParameters();
	if (domain.length > 0) {
		final String signature= type.getSuperclassTypeSignature();
		if (signature != null) {
			final String[] range= getVariableSignatures(signature);
			if (range.length > 0)
				return parametersToSignatures(domain, range, false);
		}
	}
	return new TypeVariableMaplet[0];
}
 
Example 8
Source File: LazyGenericTypeProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean hasParameters() {
	try {
		IType type= (IType) getJavaElement();
		if (type == null)
			return false;

		return type.getTypeParameters().length > 0;
	} catch (JavaModelException e) {
		return false;
	}
}
 
Example 9
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 10
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 11
Source File: LazyGenericTypeProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * For the type parameter at <code>paramIndex</code> in the type at <code>path[pathIndex]</code>
 * , this method computes the corresponding type parameter index in the type at
 * <code>path[0]</code>. If the type parameter does not map to a type parameter of the super
 * type, <code>-1</code> is returned.
 * 
 * @param path the type inheritance path, a non-empty array of consecutive sub types
 * @param pathIndex an index into <code>path</code> specifying the type to start with
 * @param paramIndex the index of the type parameter to map - <code>path[pathIndex]</code> must
 *            have a type parameter at that index, lest an
 *            <code>ArrayIndexOutOfBoundsException</code> is thrown
 * @return the index of the type parameter in <code>path[0]</code> corresponding to the type
 *         parameter at <code>paramIndex</code> in <code>path[pathIndex]</code>, or -1 if there
 *         is no corresponding type parameter
 * @throws JavaModelException if this element does not exist or if an exception occurs while
 *             accessing its corresponding resource
 * @throws ArrayIndexOutOfBoundsException if <code>path[pathIndex]</code> has &lt;=
 *             <code>paramIndex</code> parameters
 */
private int mapTypeParameterIndex(IType[] path, int pathIndex, int paramIndex) throws JavaModelException, ArrayIndexOutOfBoundsException {
	if (pathIndex == 0)
		// break condition: we've reached the top of the hierarchy
		return paramIndex;

	IType subType= path[pathIndex];
	IType superType= path[pathIndex - 1];

	String superSignature= findMatchingSuperTypeSignature(subType, superType);
	ITypeParameter param= subType.getTypeParameters()[paramIndex];
	int index= findMatchingTypeArgumentIndex(superSignature, param.getElementName());
	if (index == -1) {
		// not mapped through
		return -1;
	}

	return mapTypeParameterIndex(path, pathIndex - 1, index);
}