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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#isParameterizedType() . 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: JavaTypeHierarchyExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void getTypeBindingParents(ITypeBinding binding) {
	if (binding.isParameterizedType()) {
		binding = binding.getErasure();
	}
	final String bindingName = binding.isRecovered() ? binding
			.getName() : binding.getQualifiedName();
	final ITypeBinding superclassBinding = binding.getSuperclass();
	if (superclassBinding != null) {
		addTypes(
				superclassBinding.isRecovered() ? superclassBinding.getName()
						: superclassBinding.getQualifiedName(),
				bindingName);
		getTypeBindingParents(superclassBinding);
	}

	for (ITypeBinding iface : binding.getInterfaces()) {
		if (iface.isParameterizedType()) {
			iface = iface.getErasure();
		}
		addTypes(
				iface.isRecovered() ? iface.getName()
						: iface.getQualifiedName(), bindingName);
		getTypeBindingParents(iface);
	}
}
 
Example 2
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 3
Source File: ConvertIterableLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String[] getVariableNameProposals() {

		String[] variableNames= getUsedVariableNames();
		String[] elementSuggestions= StubUtility.getLocalNameSuggestions(getJavaProject(), FOR_LOOP_ELEMENT_IDENTIFIER, 0, variableNames);

		final ITypeBinding binding= fIteratorVariable.getType();
		if (binding != null && binding.isParameterizedType()) {
			String type= binding.getTypeArguments()[0].getName();
			String[] typeSuggestions= StubUtility.getLocalNameSuggestions(getJavaProject(), type, 0, variableNames);

			String[] result= new String[elementSuggestions.length + typeSuggestions.length];
			System.arraycopy(typeSuggestions, 0, result, 0, typeSuggestions.length);
			System.arraycopy(elementSuggestions, 0, result, typeSuggestions.length, elementSuggestions.length);
			return result;
		} else {
			return elementSuggestions;
		}
	}
 
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: JavaTypeHierarchyExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void getTypeBindingParents(ITypeBinding binding) {
	if (binding.isParameterizedType()) {
		binding = binding.getErasure();
	}
	final String bindingName = binding.isRecovered() ? binding
			.getName() : binding.getQualifiedName();
	final ITypeBinding superclassBinding = binding.getSuperclass();
	if (superclassBinding != null) {
		addTypes(
				superclassBinding.isRecovered() ? superclassBinding.getName()
						: superclassBinding.getQualifiedName(),
				bindingName);
		getTypeBindingParents(superclassBinding);
	}

	for (ITypeBinding iface : binding.getInterfaces()) {
		if (iface.isParameterizedType()) {
			iface = iface.getErasure();
		}
		addTypes(
				iface.isRecovered() ? iface.getName()
						: iface.getQualifiedName(), bindingName);
		getTypeBindingParents(iface);
	}
}
 
Example 6
Source File: TypeChangeCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void sortTypes(ITypeBinding[] typeProposals) {
	ITypeBinding oldType;
	if (fBinding instanceof IMethodBinding) {
		oldType= ((IMethodBinding) fBinding).getReturnType();
	} else {
		oldType= ((IVariableBinding) fBinding).getType();
	}
	if (! oldType.isParameterizedType()) {
		return;
	}

	final ITypeBinding oldTypeDeclaration= oldType.getTypeDeclaration();
	Arrays.sort(typeProposals, new Comparator<ITypeBinding>() {
		@Override
		public int compare(ITypeBinding o1, ITypeBinding o2) {
			return rank(o2) - rank(o1);
		}

		private int rank(ITypeBinding type) {
			if (type.getTypeDeclaration().equals(oldTypeDeclaration)) {
				return 1;
			}
			return 0;
		}
	});
}
 
Example 7
Source File: JavaTypeHierarchyExtractor.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
private void getTypeBindingParents(ITypeBinding binding) {
	if (binding.isParameterizedType()) {
		binding = binding.getErasure();
	}
	final String bindingName = binding.isRecovered() ? binding
			.getName() : binding.getQualifiedName();
	final ITypeBinding superclassBinding = binding.getSuperclass();
	if (superclassBinding != null) {
		addTypes(
				superclassBinding.isRecovered() ? superclassBinding.getName()
						: superclassBinding.getQualifiedName(),
				bindingName);
		getTypeBindingParents(superclassBinding);
	}

	for (ITypeBinding iface : binding.getInterfaces()) {
		if (iface.isParameterizedType()) {
			iface = iface.getErasure();
		}
		addTypes(
				iface.isRecovered() ? iface.getName()
						: iface.getQualifiedName(), bindingName);
		getTypeBindingParents(iface);
	}
}
 
Example 8
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 9
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 10
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 5 votes vote down vote up
public Type ensureTypeFromTypeBinding(ITypeBinding binding) {
	String qualifiedName = binding.getQualifiedName();
	if (types.has(qualifiedName))
		return types.named(qualifiedName);
	Type type = createTypeFromTypeBinding(binding);
	type.setName(binding.getName());
	types.add(qualifiedName, type);
	type.setIsStub(true);
	extractBasicModifiersFromBinding(binding.getModifiers(), type);
	type.setContainer(ensureContainerEntityForTypeBinding(binding));
	if (binding.getSuperclass() != null)
		createInheritanceFromSubtypeToSuperTypeBinding(type, binding.getSuperclass());
	for (ITypeBinding interfaceBinding : binding.getInterfaces()) {
		createInheritanceFromSubtypeToSuperTypeBinding(type, interfaceBinding);
	}
	if (binding.isParameterizedType()) {
		/*
		 * This if duplicates the condition from the create method because we want to
		 * break possible infinite loops induced by the below ensure calls. This is
		 * achieved by having this condition after the addition of the type in the types
		 * map.
		 */
		ParameterizedType parameterizedType = ((ParameterizedType) type);
		if (ensureTypeFromTypeBinding(binding.getErasure()) instanceof ParameterizableClass)
			parameterizedType.setParameterizableClass(
					(ParameterizableClass) ensureTypeFromTypeBinding(binding.getErasure()));
		List<Type> arguments = Stream.of(binding.getTypeArguments()).map(arg -> ensureTypeFromTypeBinding(arg))
				.collect(Collectors.toList());
		parameterizedType.setArguments(arguments);
	}
	if (binding.isGenericType()) {
		ParameterizableClass parameterizableClass = (ParameterizableClass) type;
		Stream.of(binding.getTypeParameters())
				.forEach(p -> createParameterType(p.getName().toString(), parameterizableClass));
	}
	return type;
}
 
Example 11
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ITypeBinding handleBug84585(ITypeBinding typeBinding) {
	if (typeBinding == null)
		return null;
	else if (typeBinding.isGenericType() && ! typeBinding.isRawType() && ! typeBinding.isParameterizedType())
		return null; //see bug 84585
	else
		return typeBinding;
}
 
Example 12
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 13
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static boolean containsTypeVariables(ITypeBinding type) {
	if (type.isTypeVariable())
		return true;
	if (type.isArray())
		return containsTypeVariables(type.getElementType());
	if (type.isCapture())
		return containsTypeVariables(type.getWildcard());
	if (type.isParameterizedType())
		return containsTypeVariables(type.getTypeArguments());
	if (type.isWildcardType() && type.getBound() != null)
		return containsTypeVariables(type.getBound());
	return false;
}
 
Example 14
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean subclassTypeMismatch(ITypeBinding nodeTypeBinding, ITypeBinding otherTypeBinding) {
	if(nodeTypeBinding.isParameterizedType() && otherTypeBinding.isParameterizedType()) {
		ITypeBinding declarationTypeBinding1 = nodeTypeBinding.getTypeDeclaration();
		ITypeBinding declarationTypeBinding2 = otherTypeBinding.getTypeDeclaration();
		return !declarationTypeBinding1.isEqualTo(declarationTypeBinding2) || !typeBindingMatch(nodeTypeBinding, otherTypeBinding);
	}
	return !nodeTypeBinding.isEqualTo(otherTypeBinding) || !nodeTypeBinding.getQualifiedName().equals(otherTypeBinding.getQualifiedName());
}
 
Example 15
Source File: TypeURIHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public String getQualifiedName(ITypeBinding binding) {
	if (binding.isParameterizedType()) {
		return getQualifiedName(binding.getErasure());
	}
	if (binding.isArray()) {
		return getQualifiedName(binding.getComponentType(), new StringBuilder()).append("[]").toString();
	}
	if (binding.isTopLevel() || binding.isTypeVariable() || binding.isPrimitive())
		return binding.getQualifiedName();
	return getQualifiedName(binding.getDeclaringClass(), new StringBuilder()).append('$').append(binding.getName()).toString();
}
 
Example 16
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isSubTypeOf(ITypeBinding type1, ITypeBinding type2){

		// to ensure that, e.g., Comparable<String> is considered a subtype of raw Comparable
		if (type1.isParameterizedType() && type1.getTypeDeclaration().isEqualTo(type2.getTypeDeclaration())){
			return true;
		}
		Set<ITypeBinding> superTypes= getAllSuperTypes(type1);
		return contains(superTypes, type2);
	}
 
Example 17
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String[] getVariableNameSuggestions(int variableKind, IJavaProject project, ITypeBinding expectedType, Expression assignedExpression, Collection<String> excluded) {
	LinkedHashSet<String> res= new LinkedHashSet<String>(); // avoid duplicates but keep order

	if (assignedExpression != null) {
		String nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind);
		if (nameFromExpression != null) {
			add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
		}

		String nameFromParent= getBaseNameFromLocationInParent(assignedExpression);
		if (nameFromParent != null) {
			add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
		}
	}
	if (expectedType != null) {
		expectedType= Bindings.normalizeTypeBinding(expectedType);
		if (expectedType != null) {
			int dim= 0;
			if (expectedType.isArray()) {
				dim= expectedType.getDimensions();
				expectedType= expectedType.getElementType();
			}
			if (expectedType.isParameterizedType()) {
				expectedType= expectedType.getTypeDeclaration();
			}
			String typeName= expectedType.getName();
			if (typeName.length() > 0) {
				add(getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, false), res);
			}
		}
	}
	if (res.isEmpty()) {
		return getDefaultVariableNameSuggestions(variableKind, excluded);
	}
	return res.toArray(new String[res.size()]);
}
 
Example 18
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance,
		Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	SimilarElement[] elements = SimilarElementsRequestor.findSimilarElement(cu, node, kind);

	// try to resolve type in context -> highest severity
	String resolvedTypeName= null;
	ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
	if (binding != null) {
		ITypeBinding simpleBinding= binding;
		if (simpleBinding.isArray()) {
			simpleBinding= simpleBinding.getElementType();
		}
		simpleBinding= simpleBinding.getTypeDeclaration();

		if (!simpleBinding.isRecovered()) {
			resolvedTypeName= simpleBinding.getQualifiedName();
			CUCorrectionProposal proposal= createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2, elements.length);
			proposals.add(proposal);
			if (proposal instanceof AddImportCorrectionProposal) {
				proposal.setRelevance(relevance + elements.length + 2);
			}

			if (binding.isParameterizedType()
					&& (node.getParent() instanceof SimpleType || node.getParent() instanceof NameQualifiedType)
					&& !(node.getParent().getParent() instanceof Type)) {
				proposals.add(createTypeRefChangeFullProposal(cu, binding, node, relevance + 5));
			}
		}
	} else {
		ASTNode normalizedNode= ASTNodes.getNormalizedNode(node);
		if (!(normalizedNode.getParent() instanceof Type) && node.getParent() != normalizedNode) {
			ITypeBinding normBinding= ASTResolving.guessBindingForTypeReference(normalizedNode);
			if (normBinding != null && !normBinding.isRecovered()) {
				proposals.add(createTypeRefChangeFullProposal(cu, normBinding, normalizedNode, relevance + 5));
			}
		}
	}

	// add all similar elements
	for (int i= 0; i < elements.length; i++) {
		SimilarElement elem= elements[i];
		if ((elem.getKind() & TypeKinds.ALL_TYPES) != 0) {
			String fullName= elem.getName();
			if (!fullName.equals(resolvedTypeName)) {
				proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance, elements.length));
			}
		}
	}
}
 
Example 19
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;
}
 
Example 20
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the type to which an inlined variable initializer should be cast, or
 * <code>null</code> if no cast is necessary.
 * 
 * @param initializer the initializer expression of the variable to inline
 * @param reference the reference to the variable (which is to be inlined)
 * @return a type binding to which the initializer should be cast, or <code>null</code> iff no cast is necessary
 * @since 3.6
 */
public static ITypeBinding getExplicitCast(Expression initializer, Expression reference) {
	ITypeBinding initializerType= initializer.resolveTypeBinding();
	ITypeBinding referenceType= reference.resolveTypeBinding();
	if (initializerType == null || referenceType == null)
		return null;
	
	if (initializerType.isPrimitive() && referenceType.isPrimitive() && ! referenceType.isEqualTo(initializerType)) {
		return referenceType;
		
	} else if (initializerType.isPrimitive() && ! referenceType.isPrimitive()) { // initializer is autoboxed
		ITypeBinding unboxedReferenceType= Bindings.getUnboxedTypeBinding(referenceType, reference.getAST());
		if (!unboxedReferenceType.isEqualTo(initializerType))
			return unboxedReferenceType;
		else if (needsExplicitBoxing(reference))
			return referenceType;
		
	} else if (! initializerType.isPrimitive() && referenceType.isPrimitive()) { // initializer is autounboxed
		ITypeBinding unboxedInitializerType= Bindings.getUnboxedTypeBinding(initializerType, reference.getAST());
		if (!unboxedInitializerType.isEqualTo(referenceType))
			return referenceType;
		
	} else if (initializerType.isRawType() && referenceType.isParameterizedType()) {
		return referenceType; // don't lose the unchecked conversion

	} else if (initializer instanceof LambdaExpression || initializer instanceof MethodReference) {
		if (isTargetAmbiguous(reference, isExplicitlyTypedLambda(initializer))) {
			return referenceType;
		} else {
			ITypeBinding targetType= getTargetType(reference);
			if (targetType == null || targetType != referenceType) {
				return referenceType;
			}
		}

	} else if (! TypeRules.canAssign(initializerType, referenceType)) {
		if (!Bindings.containsTypeVariables(referenceType))
			return referenceType;
	}
	
	return null;
}