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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#getElementType() . 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: Binding2JavaModel.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
private static void createName(ITypeBinding type, boolean includePackage, StringBuffer buffer) {
    ITypeBinding baseType= type;
    if (type.isArray()) {
        baseType= type.getElementType();
    }
    if (!baseType.isPrimitive() && !baseType.isNullType()) {
        ITypeBinding declaringType= baseType.getDeclaringClass();
        if (declaringType != null) {
            createName(declaringType, includePackage, buffer);
            buffer.append('.');
        } else if (includePackage && !baseType.getPackage().isUnnamed()) {
            buffer.append(baseType.getPackage().getName());
            buffer.append('.');
        }
    }
    if (!baseType.isAnonymous()) {
        buffer.append(type.getName());
    } else {
        buffer.append("$local$"); //$NON-NLS-1$
    }
}
 
Example 2
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void createName(ITypeBinding type, boolean includePackage, List<String> list) {
	ITypeBinding baseType= type;
	if (type.isArray()) {
		baseType= type.getElementType();
	}
	if (!baseType.isPrimitive() && !baseType.isNullType()) {
		ITypeBinding declaringType= baseType.getDeclaringClass();
		if (declaringType != null) {
			createName(declaringType, includePackage, list);
		} else if (includePackage && !baseType.getPackage().isUnnamed()) {
			String[] components= baseType.getPackage().getNameComponents();
			for (int i= 0; i < components.length; i++) {
				list.add(components[i]);
			}
		}
	}
	if (!baseType.isAnonymous()) {
		list.add(type.getName());
	} else {
		list.add("$local$"); //$NON-NLS-1$
	}
}
 
Example 3
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final void endVisit(final ConditionalExpression node) {
	ConstraintVariable2 thenVariable= null;
	ConstraintVariable2 elseVariable= null;
	final Expression thenExpression= node.getThenExpression();
	if (thenExpression != null)
		thenVariable= (ConstraintVariable2) thenExpression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
	final Expression elseExpression= node.getElseExpression();
	if (elseExpression != null)
		elseVariable= (ConstraintVariable2) elseExpression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
	ITypeBinding binding= node.resolveTypeBinding();
	if (binding != null) {
		if (binding.isArray())
			binding= binding.getElementType();
		final ConstraintVariable2 ancestor= fModel.createIndependentTypeVariable(binding);
		if (ancestor != null) {
			node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
			if (thenVariable != null)
				fModel.createSubtypeConstraint(thenVariable, ancestor);
			if (elseVariable != null)
				fModel.createSubtypeConstraint(elseVariable, ancestor);
			if (thenVariable != null && elseVariable != null)
				fModel.createConditionalTypeConstraint(ancestor, thenVariable, elseVariable);
		}
	}
}
 
Example 4
Source File: BindingLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ImageDescriptor getBaseImageDescriptor(IBinding binding, int flags) {
	if (binding instanceof ITypeBinding) {
		ITypeBinding typeBinding= (ITypeBinding) binding;
		if (typeBinding.isArray()) {
			typeBinding= typeBinding.getElementType();
		}
		if (typeBinding.isCapture()) {
			typeBinding.getWildcard();
		}
		return getTypeImageDescriptor(typeBinding.getDeclaringClass() != null, typeBinding, flags);
	} else if (binding instanceof IMethodBinding) {
		ITypeBinding type= ((IMethodBinding) binding).getDeclaringClass();
		int modifiers= binding.getModifiers();
		if (type.isEnum() && (!Modifier.isPublic(modifiers) && !Modifier.isProtected(modifiers) && !Modifier.isPrivate(modifiers)) && ((IMethodBinding) binding).isConstructor())
			return JavaPluginImages.DESC_MISC_PRIVATE;
		return getMethodImageDescriptor(binding.getModifiers());
	} else if (binding instanceof IVariableBinding)
		return getFieldImageDescriptor((IVariableBinding) binding);
	return JavaPluginImages.DESC_OBJS_UNKNOWN;
}
 
Example 5
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new method parameter variable.
 *
 * @param method the method binding
 * @param index the index of the parameter
 * @return the created method parameter variable, or <code>null</code>
 */
public final ConstraintVariable2 createMethodParameterVariable(final IMethodBinding method, final int index) {
	final ITypeBinding[] parameters= method.getParameterTypes();
	if (parameters.length < 1)
		return null;
	ITypeBinding binding= parameters[Math.min(index, parameters.length - 1)];
	if (binding.isArray())
		binding= binding.getElementType();
	if (isConstrainedType(binding)) {
		ConstraintVariable2 variable= null;
		final TType type= createTType(binding);
		if (method.getDeclaringClass().isFromSource())
			variable= new ParameterTypeVariable2(type, index, method.getMethodDeclaration());
		else
			variable= new ImmutableTypeVariable2(type);
		return fConstraintVariables.addExisting(variable);
	}
	return null;
}
 
Example 6
Source File: GenerateHashCodeEqualsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
RefactoringStatus checkMember(Object memberBinding) {
	RefactoringStatus status= new RefactoringStatus();
	IVariableBinding variableBinding= (IVariableBinding)memberBinding;
	ITypeBinding fieldsType= variableBinding.getType();
	if (fieldsType.isArray())
		fieldsType= fieldsType.getElementType();
	if (!fieldsType.isPrimitive() && !fieldsType.isEnum() && !alreadyCheckedMemberTypes.contains(fieldsType) && !fieldsType.equals(fTypeBinding)) {
		status.merge(checkHashCodeEqualsExists(fieldsType, false));
		alreadyCheckedMemberTypes.add(fieldsType);
	}
	if (Modifier.isTransient(variableBinding.getModifiers()))
		status.addWarning(Messages.format(ActionMessages.GenerateHashCodeEqualsAction_transient_field_included_error, BasicElementLabels.getJavaElementName(variableBinding.getName())),
				createRefactoringStatusContext(variableBinding.getJavaElement()));
	return status;
}
 
Example 7
Source File: Binding2JavaModel.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
private static void createName(ITypeBinding type, boolean includePackage, List<String> list) {
    ITypeBinding baseType= type;
    if (type.isArray()) {
        baseType= type.getElementType();
    }
    if (!baseType.isPrimitive() && !baseType.isNullType()) {
        ITypeBinding declaringType= baseType.getDeclaringClass();
        if (declaringType != null) {
            createName(declaringType, includePackage, list);
        } else if (includePackage && !baseType.getPackage().isUnnamed()) {
            String[] components= baseType.getPackage().getNameComponents();
            for (int i= 0; i < components.length; i++) {
                list.add(components[i]);
            }
        }
    }
    if (!baseType.isAnonymous()) {
        list.add(type.getName());
    } else {
        list.add("$local$"); //$NON-NLS-1$
    }       
}
 
Example 8
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a cast variable.
 *
 * @param expression the cast expression
 * @param variable the associated constraint variable
 * @return the created cast variable, or <code>null</code>
 */
public final ConstraintVariable2 createCastVariable(final CastExpression expression, final ConstraintVariable2 variable) {
	ITypeBinding binding= expression.resolveTypeBinding();
	if (binding.isArray())
		binding= binding.getElementType();
	if (isConstrainedType(binding)) {
		final CastVariable2 result= new CastVariable2(createTType(binding), new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(expression), expression), variable);
		fCastVariables.add(result);
		return result;
	}
	return null;
}
 
Example 9
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates an immutable type variable.
 *
 * @param type the type binding
 * @return the created plain type variable, or <code>null</code>
 */
public final ConstraintVariable2 createImmutableTypeVariable(ITypeBinding type) {
	if (type.isArray())
		type= type.getElementType();
	if (isConstrainedType(type))
		return fConstraintVariables.addExisting(new ImmutableTypeVariable2(createTType(type)));
	return null;
}
 
Example 10
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a type variable.
 *
 * @param type the type binding
 * @param range the compilation unit range
 * @return the created type variable, or <code>null</code>
 */
public final ConstraintVariable2 createTypeVariable(ITypeBinding type, final CompilationUnitRange range) {
	if (type.isArray())
		type= type.getElementType();
	if (isConstrainedType(type))
		return fConstraintVariables.addExisting(new TypeVariable2(createTType(type), range));
	return null;
}
 
Example 11
Source File: Binding2JavaModel.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
private static boolean sameParameter(ITypeBinding type, String candidate, IType scope) throws JavaModelException {
    if (type.getDimensions() != Signature.getArrayCount(candidate))
        return false;
        
    // Normalizes types
    if (type.isArray())
        type= type.getElementType();
    candidate= Signature.getElementType(candidate);
    
    if (isPrimitiveType(candidate) || type.isPrimitive()) {
        return type.getName().equals(Signature.toString(candidate));
    } else {
        if (isResolvedType(candidate)) {
            return Signature.toString(candidate).equals(getFullyQualifiedName(type));
        } else {
            String[][] qualifiedCandidates= scope.resolveType(Signature.toString(candidate));
            if (qualifiedCandidates == null || qualifiedCandidates.length == 0)
                return false;
            String packageName= type.getPackage().isUnnamed() ? "" : type.getPackage().getName(); //$NON-NLS-1$
            String typeName= getTypeQualifiedName(type);
            for (int i= 0; i < qualifiedCandidates.length; i++) {
                String[] qualifiedCandidate= qualifiedCandidates[i];
                if (qualifiedCandidate[0].equals(packageName) &&
                        qualifiedCandidate[1].equals(typeName)) {
                    return true;
                        }
            }
        }
    }
    return false;
}
 
Example 12
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean sameParameter(ITypeBinding type, String candidate, IType scope) throws JavaModelException {
	if (type.getDimensions() != Signature.getArrayCount(candidate))
		return false;

	// Normalizes types
	if (type.isArray())
		type= type.getElementType();
	candidate= Signature.getElementType(candidate);

	if ((Signature.getTypeSignatureKind(candidate) == Signature.BASE_TYPE_SIGNATURE) != type.isPrimitive()) {
		return false;
	}

	if (type.isPrimitive() || type.isTypeVariable()) {
		return type.getName().equals(Signature.toString(candidate));
	} else {
		// normalize (quick hack until binding.getJavaElement works)
		candidate= Signature.getTypeErasure(candidate);
		type= type.getErasure();

		if (candidate.charAt(Signature.getArrayCount(candidate)) == Signature.C_RESOLVED) {
			return Signature.toString(candidate).equals(Bindings.getFullyQualifiedName(type));
		} else {
			String[][] qualifiedCandidates= scope.resolveType(Signature.toString(candidate));
			if (qualifiedCandidates == null || qualifiedCandidates.length == 0)
				return false;
			String packageName= type.getPackage().isUnnamed() ? "" : type.getPackage().getName(); //$NON-NLS-1$
			String typeName= getTypeQualifiedName(type);
			for (int i= 0; i < qualifiedCandidates.length; i++) {
				String[] qualifiedCandidate= qualifiedCandidates[i];
				if (	qualifiedCandidate[0].equals(packageName) &&
						qualifiedCandidate[1].equals(typeName))
					return true;
			}
		}
	}
	return false;
}
 
Example 13
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ITypeBinding getTargetTypeForArrayInitializer(ArrayInitializer arrayInitializer) {
	ASTNode initializerParent= arrayInitializer.getParent();
	while (initializerParent instanceof ArrayInitializer) {
		initializerParent= initializerParent.getParent();
	}
	if (initializerParent instanceof ArrayCreation) {
		return ((ArrayCreation) initializerParent).getType().getElementType().resolveBinding();
	} else if (initializerParent instanceof VariableDeclaration) {
		ITypeBinding typeBinding= ((VariableDeclaration) initializerParent).getName().resolveTypeBinding();
		if (typeBinding != null) {
			return typeBinding.getElementType();
		}
	}
	return null;
}
 
Example 14
Source File: OrganizeImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tries to find the given type name and add it to the import structure.
 * @param ref the name node
 */
public void add(SimpleName ref) {
	String typeName= ref.getIdentifier();

	if (fImportsAdded.contains(typeName)) {
		return;
	}

	IBinding binding= ref.resolveBinding();
	if (binding != null) {
		if (binding.getKind() != IBinding.TYPE) {
			return;
		}
		ITypeBinding typeBinding= (ITypeBinding) binding;
		if (typeBinding.isArray()) {
			typeBinding= typeBinding.getElementType();
		}
		typeBinding= typeBinding.getTypeDeclaration();
		if (!typeBinding.isRecovered()) {
			if (needsImport(typeBinding, ref)) {
				fImpStructure.addImport(typeBinding);
				fImportsAdded.add(typeName);
			}
			return;
		}
	} else {
		if (fDoIgnoreLowerCaseNames && typeName.length() > 0) {
			char ch= typeName.charAt(0);
			if (Strings.isLowerCase(ch) && Character.isLetter(ch)) {
				return;
			}
		}
	}
	fImportsAdded.add(typeName);
	fUnresolvedTypes.put(typeName, new UnresolvedTypeData(ref));
}
 
Example 15
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 16
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 17
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 18
Source File: TypeRules.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Tests if a two types are cast compatible
 * @param castType The binding of the type to cast to
 * @param bindingToCast The binding ef the expression to cast.
 * @return boolean Returns true if (castType) bindingToCast is a valid cast expression (can be unnecessary, but not invalid).
 */
public static boolean canCast(ITypeBinding castType, ITypeBinding bindingToCast) {
	//see bug 80715

	String voidName= PrimitiveType.VOID.toString();

	if (castType.isAnonymous() || castType.isNullType() || voidName.equals(castType.getName())) {
		throw new IllegalArgumentException();
	}

	if (castType == bindingToCast) {
		return true;
	}

	if (voidName.equals(bindingToCast.getName())) {
		return false;
	}

	if (bindingToCast.isArray()) {
		if (!castType.isArray()) {
			return isArrayCompatible(castType); // can not cast an arraytype to a non array type (except to Object, Serializable...)
		}

		int toCastDim= bindingToCast.getDimensions();
		int castTypeDim= castType.getDimensions();
		if (toCastDim == castTypeDim) {
			bindingToCast= bindingToCast.getElementType();
			castType= castType.getElementType();
			if (castType.isPrimitive() && castType != bindingToCast) {
				return false; // can't assign arrays of different primitive types to each other
			}
			// fall through
		} else if (toCastDim < castTypeDim) {
			return isArrayCompatible(bindingToCast.getElementType());
		} else {
			return isArrayCompatible(castType.getElementType());
		}
	}
	if (castType.isPrimitive()) {
		if (!bindingToCast.isPrimitive()) {
			return false;
		}
		String boolName= PrimitiveType.BOOLEAN.toString();
		return (!boolName.equals(castType.getName()) && !boolName.equals(bindingToCast.getName()));
	} else {
		if (bindingToCast.isPrimitive()) {
			return false;
		}
		if (castType.isArray()) {
			return isArrayCompatible(bindingToCast);
		}
		if (castType.isInterface()) {
			if ((bindingToCast.getModifiers() & Modifier.FINAL) != 0) {
				return Bindings.isSuperType(castType, bindingToCast);
			} else {
				return true;
			}
		}
		if (bindingToCast.isInterface()) {
			if ((castType.getModifiers() & Modifier.FINAL) != 0) {
				return Bindings.isSuperType(bindingToCast, castType);
			} else {
				return true;
			}
		}
		if (isJavaLangObject(castType)) {
			return true;
		}

		return Bindings.isSuperType(bindingToCast, castType) || Bindings.isSuperType(castType, bindingToCast);
	}
}
 
Example 19
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a declaring type variable.
 * <p>
 * A declaring type variable stands for a type where something has been declared.
 * </p>
 *
 * @param type the type binding
 * @return the created declaring type variable
 */
public final ConstraintVariable2 createDeclaringTypeVariable(ITypeBinding type) {
	if (type.isArray())
		type= type.getElementType();
	type= type.getTypeDeclaration();
	return fConstraintVariables.addExisting(new ImmutableTypeVariable2(createTType(type)));
}
 
Example 20
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates an independent type variable.
 * <p>
 * An independant type variable stands for an arbitrary type.
 * </p>
 *
 * @param type the type binding
 * @return the created independant type variable, or <code>null</code>
 */
public final ConstraintVariable2 createIndependentTypeVariable(ITypeBinding type) {
	if (type.isArray())
		type= type.getElementType();
	if (isConstrainedType(type))
		return fConstraintVariables.addExisting(new IndependentTypeVariable2(createTType(type)));
	return null;
}