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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#getDimensions() . 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: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static int getDimensions(VariableDeclaration declaration) {
	int dim= declaration.getExtraDimensions();
	if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) {
		LambdaExpression lambda= (LambdaExpression) declaration.getParent();
		IMethodBinding methodBinding= lambda.resolveMethodBinding();
		if (methodBinding != null) {
			ITypeBinding[] parameterTypes= methodBinding.getParameterTypes();
			int index= lambda.parameters().indexOf(declaration);
			ITypeBinding typeBinding= parameterTypes[index];
			return typeBinding.getDimensions();
		}
	} else {
		Type type= getType(declaration);
		if (type instanceof ArrayType) {
			dim+= ((ArrayType) type).getDimensions();
		}
	}
	return dim;
}
 
Example 2
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 3
Source File: AbstractPairedInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Comparing type bindings from different ASTs appears to work correctly
 * unless the bindings involve arrays of primitives or type parameters. In the
 * case of arrays case,
 * {@link TypeRules#canAssign(ITypeBinding, ITypeBinding)} assumes that the
 * bindings are from the same AST and so it uses an identity comparison
 * instead of equality.
 * 
 * In the case of type parameters, two List<T>'s where T extend Serializable
 * are not considered equal or assignment compatible. In this case, we simply
 * erase to the entire type and simply check raw types.
 * 
 * TODO: Maybe create a BindingUtilities class for this?
 */
protected static boolean canAssign(ITypeBinding lhs, ITypeBinding rhs) {
  if (containsTypeVariableReferences(lhs)
      || containsTypeVariableReferences(rhs)) {
    // One of the type bindings referenced a type parameter, so just compare
    // the erasures of each type
    lhs = lhs.getErasure();
    rhs = rhs.getErasure();
  }

  if (lhs.isArray() && rhs.isArray()) {
    if (lhs.getDimensions() == rhs.getDimensions()) {

      while (lhs.isArray()) {
        lhs = lhs.getComponentType();
      }

      while (rhs.isArray()) {
        rhs = rhs.getComponentType();
      }

      if (lhs.isPrimitive() && rhs.isPrimitive()) {
        return lhs.getKey().equals(rhs.getKey());
      }
    }
  }

  return TypeRules.canAssign(lhs, rhs);
}
 
Example 4
Source File: ArrayType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void initialize(ITypeBinding binding, TType elementType) {
	Assert.isTrue(binding.isArray());
	super.initialize(binding);
	fElementType= elementType;
	fDimensions= binding.getDimensions();
	if (fElementType.isStandardType() || fElementType.isGenericType() || fElementType.isPrimitiveType()) {
		fErasure= this;
	} else {
		fErasure= getEnvironment().create(binding.getErasure());
	}
}
 
Example 5
Source File: TypeEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ArrayType createArrayType(ITypeBinding binding) {
	int index= binding.getDimensions() - 1;
	TType elementType= create(binding.getElementType());
	Map<TType, ArrayType> arrayTypes= getArrayTypesMap(index);
	ArrayType result= arrayTypes.get(elementType);
	if (result != null)
		return result;
	result= new ArrayType(this);
	arrayTypes.put(elementType, result);
	result.initialize(binding, elementType);
	return result;
}
 
Example 6
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 7
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 8
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SingleVariableDeclaration createParameterDeclaration(String parameterName, VariableDeclarationFragment fragement, Expression arrayAccess, ForStatement statement, ImportRewrite importRewrite, ASTRewrite rewrite, TextEditGroup group, LinkedProposalPositionGroup pg, boolean makeFinal) {
	CompilationUnit compilationUnit= (CompilationUnit)arrayAccess.getRoot();
	AST ast= compilationUnit.getAST();

	SingleVariableDeclaration result= ast.newSingleVariableDeclaration();

	SimpleName name= ast.newSimpleName(parameterName);
	pg.addPosition(rewrite.track(name), true);
	result.setName(name);

	ITypeBinding arrayTypeBinding= arrayAccess.resolveTypeBinding();
	Type type= importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit);
	if (arrayTypeBinding.getDimensions() != 1) {
		type= ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1);
	}
	result.setType(type);

	if (fragement != null) {
		VariableDeclarationStatement declaration= (VariableDeclarationStatement)fragement.getParent();
		ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group);
	}
	if (makeFinal && (fragement == null || ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragement)) == null)) {
		ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group);
	}

	return result;
}
 
Example 9
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 10
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);
	}
}