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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#isPrimitive() . 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
/**
 * Finds the method specified by <code>methodName<code> and </code>parameters</code> in
 * the given <code>type</code>. Returns <code>null</code> if no such method exits.
 * @param type The type to search the method in
 * @param methodName The name of the method to find
 * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only
 *  the name is matched and parameters are ignored.
 * @return the method binding representing the method
 */
public static IMethodBinding findMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) {
	if (type.isPrimitive())
		return null;
	IMethodBinding[] methods= type.getDeclaredMethods();
	for (int i= 0; i < methods.length; i++) {
		if (parameters == null) {
			if (methodName.equals(methods[i].getName()))
				return methods[i];
		} else {
			if (isEqualMethod(methods[i], methodName, parameters))
				return methods[i];
		}
	}
	return null;
}
 
Example 3
Source File: RefactoringUtility.java    From JDeodorant with MIT License 6 votes vote down vote up
public static Type generateWrapperTypeForPrimitiveTypeBinding(ITypeBinding typeBinding, AST ast) {
	Type type = null;
	if(typeBinding.isPrimitive()) {
		String primitiveType = typeBinding.getName();
		if(primitiveType.equals("int"))
			type = ast.newSimpleType(ast.newSimpleName("Integer"));
		else if(primitiveType.equals("double"))
			type = ast.newSimpleType(ast.newSimpleName("Double"));
		else if(primitiveType.equals("byte"))
			type = ast.newSimpleType(ast.newSimpleName("Byte"));
		else if(primitiveType.equals("short"))
			type = ast.newSimpleType(ast.newSimpleName("Short"));
		else if(primitiveType.equals("char"))
			type = ast.newSimpleType(ast.newSimpleName("Character"));
		else if(primitiveType.equals("long"))
			type = ast.newSimpleType(ast.newSimpleName("Long"));
		else if(primitiveType.equals("float"))
			type = ast.newSimpleType(ast.newSimpleName("Float"));
		else if(primitiveType.equals("boolean"))
			type = ast.newSimpleType(ast.newSimpleName("Boolean"));
	}
	return type;
}
 
Example 4
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Normalizes the binding so that it can be used as a type inside a declaration (e.g. variable
 * declaration, method return type, parameter type, ...).
 * For null bindings, java.lang.Object is returned.
 * For void bindings, <code>null</code> is returned.
 * 
 * @param binding binding to normalize
 * @param ast current AST
 * @return the normalized type to be used in declarations, or <code>null</code>
 */
public static ITypeBinding normalizeForDeclarationUse(ITypeBinding binding, AST ast) {
	if (binding.isNullType())
		return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
	if (binding.isPrimitive())
		return binding;
	binding= normalizeTypeBinding(binding);
	if (binding == null || !binding.isWildcardType())
		return binding;
	ITypeBinding bound= binding.getBound();
	if (bound == null || !binding.isUpperbound()) {
		ITypeBinding[] typeBounds= binding.getTypeBounds();
		if (typeBounds.length > 0) {
			return typeBounds[0];
		} else {
			return binding.getErasure();
		}
	} else {
		return bound;
	}
}
 
Example 5
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 6
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected JvmType createProxy(ITypeBinding typeBinding) {
	JvmType proxy = typeProxies.get(typeBinding);
	if (proxy == null) {
		if (typeBinding.isPrimitive()) {
			proxy = PRIMITIVE_PROXIES[typeBinding.getKey().charAt(0) - 'B'];
		} else {
			URI uri = uriHelper.getFullURI(typeBinding);
			proxy = COMMON_PROXIES.get(uri.fragment());
			if (proxy == null) {
				proxy = TypesFactory.eINSTANCE.createJvmVoid();
				((InternalEObject)proxy).eSetProxyURI(uri);
			}
		}
		typeProxies.put(typeBinding, proxy);
	}
	return proxy;
}
 
Example 7
Source File: Util.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a GWT RPC async callback parameter declaration based on the sync
 * method return type.
 *
 * @param ast {@link AST} associated with the destination compilation unit
 * @param syncReturnType the sync method return type
 * @param callbackParameterName name of the callback parameter
 * @param imports {@link ImportsRewrite} for the destination compilation unit
 * @return callback paramter declaration
 */
@SuppressWarnings("unchecked")
public static SingleVariableDeclaration createAsyncCallbackParameter(AST ast,
    Type syncReturnType, String callbackParameterName, ImportRewrite imports) {
  ITypeBinding syncReturnTypeBinding = syncReturnType.resolveBinding();

  SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();

  String gwtCallbackTypeSig = Signature.createTypeSignature(
      RemoteServiceUtilities.ASYNCCALLBACK_QUALIFIED_NAME, true);
  Type gwtCallbackType = imports.addImportFromSignature(gwtCallbackTypeSig,
      ast);

  if (syncReturnTypeBinding.isPrimitive()) {
    String wrapperName = JavaASTUtils.getWrapperTypeName(syncReturnTypeBinding.getName());
    String wrapperTypeSig = Signature.createTypeSignature(wrapperName, true);
    syncReturnType = imports.addImportFromSignature(wrapperTypeSig, ast);
  } else {
    syncReturnType = JavaASTUtils.normalizeTypeAndAddImport(ast,
        syncReturnType, imports);
  }

  ParameterizedType type = ast.newParameterizedType(gwtCallbackType);
  List<Type> typeArgs = type.typeArguments();
  typeArgs.add(syncReturnType);

  parameter.setType(type);
  parameter.setName(ast.newSimpleName(callbackParameterName));

  return parameter;
}
 
Example 8
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if the given type is a super type of a candidate.
 * <code>true</code> is returned if the two type bindings are identical (TODO)
 * @param possibleSuperType the type to inspect
 * @param type the type whose super types are looked at
 * @param considerTypeArguments if <code>true</code>, consider type arguments of <code>type</code>
 * @return <code>true</code> iff <code>possibleSuperType</code> is
 * 		a super type of <code>type</code> or is equal to it
 */
public static boolean isSuperType(ITypeBinding possibleSuperType, ITypeBinding type, boolean considerTypeArguments) {
	if (type.isArray() || type.isPrimitive()) {
		return false;
	}
	if (! considerTypeArguments) {
		type= type.getTypeDeclaration();
	}
	if (Bindings.equals(type, possibleSuperType)) {
		return true;
	}
	ITypeBinding superClass= type.getSuperclass();
	if (superClass != null) {
		if (isSuperType(possibleSuperType, superClass, considerTypeArguments)) {
			return true;
		}
	}

	if (possibleSuperType.isInterface()) {
		ITypeBinding[] superInterfaces= type.getInterfaces();
		for (int i= 0; i < superInterfaces.length; i++) {
			if (isSuperType(possibleSuperType, superInterfaces[i], considerTypeArguments)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 9
Source File: SrcTreeGenerator.java    From sahagin-java with Apache License 2.0 5 votes vote down vote up
private List<String> getArgClassQualifiedNames(IMethodBinding method) {
    ITypeBinding[] paramTypes;
    if (method.isParameterizedMethod()) {
        // Use generic type to get argument class types
        // instead of the actual type resolved by JDT.
        IMethodBinding originalMethod = method.getMethodDeclaration();
        paramTypes = originalMethod.getParameterTypes();
    } else {
        paramTypes = method.getParameterTypes();
    }

    List<String> result = new ArrayList<>(paramTypes.length);
    for (ITypeBinding param : paramTypes) {
        // AdditionalTestDoc's argClassQualifiedNames are defined by type erasure.
        // TODO is this generic handling logic always work well??
        ITypeBinding erasure = param.getErasure();
        if (erasure.isPrimitive() || erasure.isArray()) {
            // "int", "boolean", etc
            result.add(erasure.getQualifiedName());
        } else {
            // getBinaryName and getQualifiedName are not the same.
            // For example, getBinaryName returns parent$child for inner class,
            // but getQualifiedName returns parent.child
            result.add(erasure.getBinaryName());
        }
    }
    return result;
}
 
Example 10
Source File: InferTypeArgumentsTCModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TType getBoxedType(ITypeBinding typeBinding, Expression expression) {
	if (typeBinding == null)
		return null;

	if (! typeBinding.isPrimitive())
		return createTType(typeBinding);

	if (expression == null || ! expression.resolveBoxing())
		return null;

	ITypeBinding boxed= Bindings.getBoxedTypeBinding(typeBinding, expression.getAST());
	return createTType(boxed);
}
 
Example 11
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 12
Source File: RemoteServiceProblemFactory.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
static String toAsyncMethodSignature(IMethodBinding syncMethod) {
  StringBuilder sb = new StringBuilder();
  sb.append(syncMethod.getName());
  sb.append("(");
  ITypeBinding[] parameterTypes = syncMethod.getParameterTypes();
  for (int i = 0; i < parameterTypes.length; ++i) {
    if (i != 0) {
      sb.append(", ");
    }

    sb.append(parameterTypes[i].getName());
  }

  if (parameterTypes.length > 0) {
    sb.append(", ");
  }

  sb.append("AsyncCallback<");
  ITypeBinding returnType = syncMethod.getReturnType();
  if (returnType.isPrimitive()) {
    sb.append(Signature.getSimpleName(JavaASTUtils.getWrapperTypeName(returnType.getName())));
  } else {
    sb.append(returnType.getName());
  }
  sb.append(">");
  sb.append(")");

  return sb.toString();
}
 
Example 13
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 14
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 5 votes vote down vote up
private AnnotationTypeAttribute ensureAnnotationTypeAttributeFromBinding(IMethodBinding binding) {
	ITypeBinding parentTypeBinding = binding.getDeclaringClass();
	if (parentTypeBinding == null) {
		return null;
	}
	AnnotationType annotationType = (AnnotationType) ensureTypeFromTypeBinding(parentTypeBinding);
	AnnotationTypeAttribute attribute = ensureAnnotationTypeAttribute(annotationType, binding.getName());
	ITypeBinding returnType = binding.getReturnType();
	if ((returnType != null) && !(returnType.isPrimitive() && returnType.getName().equals("void"))) {
		// we do not want to set void as a return type
		attribute.setDeclaredType(ensureTypeFromTypeBinding(returnType));
	}
	return attribute;
}
 
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: 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 17
Source File: StructCache.java    From junion with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Entry get(ITypeBinding ib) {
	if(ib == null) {
		CompilerError.exec(CompilerError.UNCATEGORIZED, "Null binding ");
		return null;
	}
	if(ib.isPrimitive()) return null;		
	return get(ib.getBinaryName(), ib);
}
 
Example 18
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 19
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 20
Source File: SuperTypeConstraintsModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Is the type represented by the specified binding a constrained type?
 *
 * @param binding the binding to check, or <code>null</code>
 * @return <code>true</code> if it is constrained, <code>false</code> otherwise
 */
public static boolean isConstrainedType(final ITypeBinding binding) {
	return binding != null && !binding.isSynthetic() && !binding.isPrimitive();
}