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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#isArray() . 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: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Is the specified name a field access?
 *
 * @param name
 *            the name to check
 * @return <code>true</code> if this name is a field access,
 *         <code>false</code> otherwise
 */
protected static boolean isFieldAccess(final SimpleName name) {
	Assert.isNotNull(name);
	final IBinding binding= name.resolveBinding();
	if (!(binding instanceof IVariableBinding))
		return false;
	final IVariableBinding variable= (IVariableBinding) binding;
	if (!variable.isField())
		return false;
	if ("length".equals(name.getIdentifier())) { //$NON-NLS-1$
		final ASTNode parent= name.getParent();
		if (parent instanceof QualifiedName) {
			final QualifiedName qualified= (QualifiedName) parent;
			final ITypeBinding type= qualified.getQualifier().resolveTypeBinding();
			if (type != null && type.isArray())
				return false;
		}
	}
	return !Modifier.isStatic(variable.getModifiers());
}
 
Example 2
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 3
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 4
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 5
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 6
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void copyArguments(MethodDeclaration intermediary, CompilationUnitRewrite rew) throws JavaModelException {
	String[] names= fTargetMethod.getParameterNames();
	ITypeBinding[] types= fTargetMethodBinding.getParameterTypes();
	for (int i= 0; i < names.length; i++) {
		ITypeBinding typeBinding= types[i];
		SingleVariableDeclaration newElement= rew.getAST().newSingleVariableDeclaration();
		newElement.setName(rew.getAST().newSimpleName(names[i]));

		if (i == (names.length - 1) && fTargetMethodBinding.isVarargs()) {
			newElement.setVarargs(true);
			if (typeBinding.isArray())
				typeBinding= typeBinding.getComponentType();
		}

		newElement.setType(rew.getImportRewrite().addImport(typeBinding, rew.getAST()));
		intermediary.parameters().add(newElement);
	}
}
 
Example 7
Source File: TypeURIHelper.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected void createResourceURI(ITypeBinding typeBinding, StringBuilder uriBuilder) {
	if (typeBinding.isPrimitive()) {
		createResourceURIForPrimitive(uriBuilder);
		return;
	}
	if (typeBinding.isClass() || typeBinding.isInterface() || typeBinding.isAnnotation() || typeBinding.isEnum()) {
		createResourceURIForClass(typeBinding, uriBuilder);
		return;
	}
	if (typeBinding.isArray()) {
		createResourceURIForArray(typeBinding, uriBuilder);
		return;
	}
	if (typeBinding.isTypeVariable()) {
		createResourceURIForTypeVariable(typeBinding, uriBuilder);
		return;
	}
	throw new IllegalStateException("Unexpected type: " + typeBinding);
}
 
Example 8
Source File: MissingAnnotationAttributesProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression newDefaultExpression(AST ast, ITypeBinding type, ImportRewriteContext context) {
	if (type.isPrimitive()) {
		String name= type.getName();
		if ("boolean".equals(name)) { //$NON-NLS-1$
			return ast.newBooleanLiteral(false);
		} else {
			return ast.newNumberLiteral("0"); //$NON-NLS-1$
		}
	}
	if (type == ast.resolveWellKnownType("java.lang.String")) { //$NON-NLS-1$
		return ast.newStringLiteral();
	}
	if (type.isArray()) {
		ArrayInitializer initializer= ast.newArrayInitializer();
		initializer.expressions().add(newDefaultExpression(ast, type.getElementType(), context));
		return initializer;
	}
	if (type.isAnnotation()) {
		MarkerAnnotation annotation= ast.newMarkerAnnotation();
		annotation.setTypeName(ast.newName(getImportRewrite().addImport(type, context)));
		return annotation;
	}
	return ast.newNullLiteral();
}
 
Example 9
Source File: EnhancedForLoop.java    From JDeodorant with MIT License 6 votes vote down vote up
private static AbstractControlVariable generateConditionControlVariable(Expression dataStructure)
{
	// initialize startValue
	VariableValue startValue = new VariableValue(0);
	// initialize endValue
	VariableValue endValue = null;
	ITypeBinding dataStructureBinding = dataStructure.resolveTypeBinding();
	// if the dataStructure is an array or a mehtodInvocation returning and array (both covered by the first expression) OR
	// the data structure is a collection or the data structure is a methodInvocation returning a collection (both covered by the second expression)
	// These are the only cases supported by the JAVA enhanced for loop
	if (dataStructureBinding.isArray() || AbstractLoopUtilities.isCollection(dataStructureBinding))
	{
		endValue = new VariableValue(VariableValue.ValueType.DATA_STRUCTURE_SIZE);
	}
	// initialize variableUpdaters
	List<VariableUpdater> variableUpdaters = new ArrayList<VariableUpdater>();
	variableUpdaters.add(new VariableUpdater(1));
	if (endValue == null)
	{
		return null;
	}
	return new AbstractControlVariable(startValue, endValue, variableUpdaters, dataStructure);
}
 
Example 10
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
protected JvmAnnotationValue createAnnotationValue(ITypeBinding annotationType, /* @Nullable */ Object value, IMethodBinding methodBinding) {
	ITypeBinding originalTypeBinding = methodBinding.getReturnType();
	ITypeBinding typeBinding = originalTypeBinding;
	if (originalTypeBinding.isArray()) {
		typeBinding = typeBinding.getComponentType();
	}
	if (typeBinding.isParameterizedType())
		typeBinding = typeBinding.getErasure();
	JvmAnnotationValue annotationValue = createAnnotationValue(typeBinding, value);
	annotationValue.setOperation(createMethodProxy(annotationType, methodBinding));
	return annotationValue;
}
 
Example 11
Source File: AbstractToStringGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Iterates over selected members to determine whether helper methods will be needed.
 */
protected void checkNeedForHelperMethods() {
	if ((!fContext.isLimitItems() && !fContext.isCustomArray()) || (fContext.isLimitItems() && fContext.getLimitItemsValue() == 0))
		return;

	boolean isNonPrimitive= false;
	for (int i= 0; i < fContext.getSelectedMembers().length; i++) {
		ITypeBinding memberType= getMemberType(fContext.getSelectedMembers()[i]);
		boolean[] implementsInterfaces= implementsInterfaces(memberType.getErasure(), new String[] { "java.util.Collection", "java.util.List", "java.util.Map" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		boolean isCollection= implementsInterfaces[0];
		boolean isList= implementsInterfaces[1];
		boolean isMap= implementsInterfaces[2];

		if (fContext.isLimitItems() && (isCollection || isMap) && !isList) {
			needCollectionToStringMethod= true;
		}
		if (fContext.isCustomArray() && memberType.isArray()) {
			ITypeBinding componentType= memberType.getComponentType();
			if (componentType.isPrimitive() && (!fContext.is50orHigher() || (!fContext.is60orHigher() && fContext.isLimitItems()))) {
				if (!typesThatNeedArrayToStringMethod.contains(componentType))
					typesThatNeedArrayToStringMethod.add(componentType);
			} else if (!componentType.isPrimitive())
				isNonPrimitive= true;
		}
	}
	if (!typesThatNeedArrayToStringMethod.isEmpty() && isNonPrimitive)
		typesThatNeedArrayToStringMethod.add(fAst.resolveWellKnownType("java.lang.Object")); //$NON-NLS-1$
}
 
Example 12
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding[] getRelaxingTypes(AST ast, ITypeBinding type) {
	ArrayList<ITypeBinding> res= new ArrayList<ITypeBinding>();
	res.add(type);
	if (type.isArray()) {
		res.add(ast.resolveWellKnownType("java.lang.Object")); //$NON-NLS-1$
		// The following two types are not available in some j2me implementations, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=288060 :
		ITypeBinding serializable= ast.resolveWellKnownType("java.io.Serializable"); //$NON-NLS-1$
		if (serializable != null)
			res.add(serializable);
		ITypeBinding cloneable= ast.resolveWellKnownType("java.lang.Cloneable"); //$NON-NLS-1$
		if (cloneable != null)
			res.add(cloneable);
	} else if (type.isPrimitive()) {
		Code code= PrimitiveType.toCode(type.getName());
		boolean found= false;
		for (int i= 0; i < CODE_ORDER.length; i++) {
			if (found) {
				String typeName= CODE_ORDER[i].toString();
				res.add(ast.resolveWellKnownType(typeName));
			}
			if (code == CODE_ORDER[i]) {
				found= true;
			}
		}
	} else {
		collectRelaxingTypes(res, type);
	}
	return res.toArray(new ITypeBinding[res.size()]);
}
 
Example 13
Source File: TypeURIHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.4
 */
public StringBuilder getQualifiedName(ITypeBinding binding, StringBuilder stringBuilder) {
	if (binding.isParameterizedType()) {
		getQualifiedName(binding.getErasure(), stringBuilder);
	}
	else if (binding.isArray()) {
		getQualifiedName(binding.getComponentType(), stringBuilder).append("[]");
	}
	else if (binding.isTopLevel() || binding.isTypeVariable() || binding.isPrimitive()) {
		stringBuilder.append(binding.getQualifiedName());
	} else {
		getQualifiedName(binding.getDeclaringClass(), stringBuilder).append('$').append(binding.getName());
	}
	return stringBuilder;
}
 
Example 14
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 15
Source File: JdtUtils.java    From j2cl with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a type descriptor for the given type binding, taking into account nullability.
 *
 * @param typeBinding the type binding, used to create the type descriptor.
 * @param elementAnnotations the annotations on the element
 */
private static TypeDescriptor createTypeDescriptorWithNullability(
    ITypeBinding typeBinding, IAnnotationBinding[] elementAnnotations) {
  if (typeBinding == null) {
    return null;
  }

  if (typeBinding.isPrimitive()) {
    return PrimitiveTypes.get(typeBinding.getName());
  }

  if (isIntersectionType(typeBinding)) {
    return createIntersectionType(typeBinding);
  }

  if (typeBinding.isNullType()) {
    return TypeDescriptors.get().javaLangObject;
  }

  if (typeBinding.isTypeVariable() || typeBinding.isCapture() || typeBinding.isWildcardType()) {
    return createTypeVariable(typeBinding);
  }

  boolean isNullable = isNullable(typeBinding, elementAnnotations);
  if (typeBinding.isArray()) {
    TypeDescriptor componentTypeDescriptor = createTypeDescriptor(typeBinding.getComponentType());
    return ArrayTypeDescriptor.newBuilder()
        .setComponentTypeDescriptor(componentTypeDescriptor)
        .setNullable(isNullable)
        .build();
  }

  return withNullability(createDeclaredType(typeBinding), isNullable);
}
 
Example 16
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 17
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 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: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Checks whether the passed type binding is a runtime exception.
 *
 * @param thrownException the type binding
 *
 * @return <code>true</code> if the passed type binding is a runtime exception;
 * 	otherwise <code>false</code> is returned
 */
public static boolean isRuntimeException(ITypeBinding thrownException) {
	if (thrownException == null || thrownException.isPrimitive() || thrownException.isArray())
		return false;
	return findTypeInHierarchy(thrownException, "java.lang.RuntimeException") != null; //$NON-NLS-1$
}