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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#isAnonymous() . 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, 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 2
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void handleMethod(SimpleName node, IMethodBinding binding) {
	ITypeBinding declaringClass= binding.getDeclaringClass();
	if (Modifier.isStatic(binding.getModifiers())) {
		if (fFindUnqualifiedStaticMethodAccesses) {
			//Do not qualify static fields if defined inside an anonymous class
			if (declaringClass.isAnonymous())
				return;

			fResult.add(new AddStaticQualifierOperation(declaringClass, node));
		}
	} else {
		if (fFindUnqualifiedMethodAccesses) {
			String qualifier= getThisExpressionQualifier(declaringClass, fImportRewrite, node);
			if (qualifier == null)
				return;

			if (qualifier.length() == 0)
				qualifier= null;

			fResult.add(new AddThisQualifierOperation(qualifier, node));
		}
	}
}
 
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: ReferenceResolvingVisitor.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
private String getQualifiedName(ITypeBinding typeBinding)
{
    if (typeBinding == null)
        return null;

    String qualifiedName = typeBinding.getQualifiedName();

    if (StringUtils.isEmpty(qualifiedName))
    {
        if (typeBinding.isAnonymous())
        {
            if (typeBinding.getSuperclass() != null)
                qualifiedName = getQualifiedName(typeBinding.getSuperclass());
            else if (typeBinding instanceof AnonymousClassDeclaration)
            {
                qualifiedName = ((AnonymousClassDeclaration) typeBinding).toString();
            }
        }
        else if (StringUtils.isEmpty(qualifiedName) && typeBinding.isNested())
            qualifiedName = typeBinding.getName();
    }

    return qualifiedName;
}
 
Example 5
Source File: JdtUtils.java    From j2cl with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the binary name for a type binding.
 *
 * <p>NOTE: This accounts for the cases that JDT does not assign binary names, which are those of
 * unreachable local or anonymous classes.
 */
private static String getBinaryNameFromTypeBinding(ITypeBinding typeBinding) {
  String binaryName = typeBinding.getBinaryName();
  if (binaryName == null && (typeBinding.isLocal() || typeBinding.isAnonymous())) {
    // Local and anonymous classes in unreachable code have null binary name.

    // The code here is a HACK that relies on the way that JDT synthesizes keys. Keys for
    // unreachable classes have the closest enclosing reachable class key as a prefix (minus the
    // ending semicolon)
    ITypeBinding closestReachableExclosingClass = typeBinding.getDeclaringClass();
    while (closestReachableExclosingClass.getBinaryName() == null) {
      closestReachableExclosingClass = closestReachableExclosingClass.getDeclaringClass();
    }
    String parentKey = closestReachableExclosingClass.getKey();
    String key = typeBinding.getKey();
    return getBinaryNameFromTypeBinding(typeBinding.getDeclaringClass())
        + "$$Unreachable"
        // remove the parent prefix and the ending semicolon
        + key.substring(parentKey.length() - 1, key.length() - 1);
  }
  return binaryName;
}
 
Example 6
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {
	IBinding binding= getBinding(token);
	if (binding != null) {
		if (binding.isDeprecated())
			return true;
		if (binding instanceof IMethodBinding) {
			IMethodBinding methodBinding= (IMethodBinding) binding;
			if (methodBinding.isConstructor() && methodBinding.getJavaElement() == null) {
				ITypeBinding declaringClass= methodBinding.getDeclaringClass();
				if (declaringClass.isAnonymous()) {
					ITypeBinding[] interfaces= declaringClass.getInterfaces();
					if (interfaces.length > 0)
						return interfaces[0].isDeprecated();
					else
						return declaringClass.getSuperclass().isDeprecated();
				}
				return declaringClass.isDeprecated();
			}
		}
	}
	return false;
}
 
Example 7
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static IBinding resolveBinding(ASTNode node) {
	if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName) node;
		// workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not method)
		ASTNode normalized= ASTNodes.getNormalizedNode(simpleName);
		if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
			ClassInstanceCreation cic= (ClassInstanceCreation) normalized.getParent();
			IMethodBinding constructorBinding= cic.resolveConstructorBinding();
			if (constructorBinding == null)
				return null;
			ITypeBinding declaringClass= constructorBinding.getDeclaringClass();
			if (!declaringClass.isAnonymous())
				return constructorBinding;
			ITypeBinding superTypeDeclaration= declaringClass.getSuperclass().getTypeDeclaration();
			return resolveSuperclassConstructor(superTypeDeclaration, constructorBinding);
		}
		return simpleName.resolveBinding();
		
	} else if (node instanceof SuperConstructorInvocation) {
		return ((SuperConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof ConstructorInvocation) {
		return ((ConstructorInvocation) node).resolveConstructorBinding();
	} else {
		return null;
	}
}
 
Example 8
Source File: JdtUtils.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private static Kind getKindFromTypeBinding(ITypeBinding typeBinding) {
  if (typeBinding.isEnum() && !typeBinding.isAnonymous()) {
    // Do not consider the anonymous classes that constitute enum values as Enums, only the
    // enum "class" itself is considered Kind.ENUM.
    return Kind.ENUM;
  } else if (typeBinding.isClass() || (typeBinding.isEnum() && typeBinding.isAnonymous())) {
    return Kind.CLASS;
  } else if (typeBinding.isInterface()) {
    return Kind.INTERFACE;
  }
  throw new InternalCompilerError("Type binding %s not handled", typeBinding);
}
 
Example 9
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IBinding resolveBinding(ASTNode node) {
	if (node instanceof SimpleName) {
		SimpleName simpleName = (SimpleName) node;
		// workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not method)
		ASTNode normalized = ASTNodes.getNormalizedNode(simpleName);
		if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
			ClassInstanceCreation cic = (ClassInstanceCreation) normalized.getParent();
			IMethodBinding constructorBinding = cic.resolveConstructorBinding();
			if (constructorBinding == null) {
				return null;
			}
			ITypeBinding declaringClass = constructorBinding.getDeclaringClass();
			if (!declaringClass.isAnonymous()) {
				return constructorBinding;
			}
			ITypeBinding superTypeDeclaration = declaringClass.getSuperclass().getTypeDeclaration();
			return resolveSuperclassConstructor(superTypeDeclaration, constructorBinding);
		}
		return simpleName.resolveBinding();

	} else if (node instanceof SuperConstructorInvocation) {
		return ((SuperConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof ConstructorInvocation) {
		return ((ConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof LambdaExpression) {
		return ((LambdaExpression) node).resolveMethodBinding();
	} else {
		return null;
	}
}
 
Example 10
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void addNewFieldForType(ICompilationUnit targetCU, ITypeBinding binding,
		ITypeBinding senderDeclBinding, SimpleName simpleName, boolean isWriteAccess, boolean mustBeConst,
		Collection<ChangeCorrectionProposal> proposals) {
	String name= simpleName.getIdentifier();
	String nameLabel= BasicElementLabels.getJavaElementName(name);
	String label;
	if (senderDeclBinding.isEnum() && !isWriteAccess) {
		label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createenum_description,
				new Object[] { nameLabel, org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) });
		proposals.add(new NewVariableCorrectionProposal(label, targetCU, NewVariableCorrectionProposal.ENUM_CONST,
				simpleName, senderDeclBinding, 10));
	} else {
		if (!mustBeConst) {
			if (binding == null) {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_description, nameLabel);
			} else {
				label = Messages.format(
						CorrectionMessages.UnresolvedElementsSubProcessor_createfield_other_description,
						new Object[] { nameLabel, org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) });
			}
			int fieldRelevance= StubUtility.hasFieldName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_FIELD_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_FIELD;
			proposals.add(new NewVariableCorrectionProposal(label, targetCU, NewVariableCorrectionProposal.FIELD,
					simpleName, senderDeclBinding, fieldRelevance));
		}

		if (!isWriteAccess && !senderDeclBinding.isAnonymous()) {
			if (binding == null) {
				label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_description, nameLabel);
			} else {
				label = Messages.format(
						CorrectionMessages.UnresolvedElementsSubProcessor_createconst_other_description,
						new Object[] { nameLabel, org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) });
			}
			int constRelevance= StubUtility.hasConstantName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_CONSTANT_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_CONSTANT;
			proposals.add(new NewVariableCorrectionProposal(label, targetCU,
					NewVariableCorrectionProposal.CONST_FIELD, simpleName, senderDeclBinding, constRelevance));
		}
	}
}
 
Example 11
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection<ICommandAccess> proposals) throws JavaModelException {
	// new variables
	ICompilationUnit targetCU;
	ITypeBinding senderDeclBinding;
	if (binding != null) {
		senderDeclBinding= binding.getTypeDeclaration();
		targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
	} else { // binding is null for accesses without qualifier
		senderDeclBinding= declaringTypeBinding;
		targetCU= cu;
	}

	if (!senderDeclBinding.isFromSource() || targetCU == null) {
		return;
	}

	boolean mustBeConst= ASTResolving.isInsideModifiers(simpleName);

	addNewFieldForType(targetCU, binding, senderDeclBinding, simpleName, isWriteAccess, mustBeConst, proposals);

	if (binding == null && senderDeclBinding.isNested()) {
		ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
		if (anonymDecl != null) {
			ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
			if (!bind.isAnonymous()) {
				addNewFieldForType(targetCU, bind, bind, simpleName, isWriteAccess, mustBeConst, proposals);
			}
		}
	}
}
 
Example 12
Source File: TType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Initialized the type from the given binding
 *
 * @param binding the binding to initialize from
 */
protected void initialize(ITypeBinding binding) {
	fBindingKey= binding.getKey();
	Assert.isNotNull(fBindingKey);
	fModifiers= binding.getModifiers();
	if (binding.isClass()) {
		fFlags= F_IS_CLASS;
	// the annotation test has to be done before test for interface
	// since annotations are interfaces as well.
	} else if (binding.isAnnotation()) {
		fFlags= F_IS_ANNOTATION | F_IS_INTERFACE;
	} else if (binding.isInterface()) {
		fFlags= F_IS_INTERFACE;
	} else if (binding.isEnum()) {
		fFlags= F_IS_ENUM;
	}

	if (binding.isTopLevel()) {
		fFlags|= F_IS_TOP_LEVEL;
	} else if (binding.isNested()) {
		fFlags|= F_IS_NESTED;
		if (binding.isMember()) {
			fFlags|= F_IS_MEMBER;
		} else if (binding.isLocal()) {
			fFlags|= F_IS_LOCAL;
		} else if (binding.isAnonymous()) {
			fFlags|= F_IS_ANONYMOUS;
		}
	}
}
 
Example 13
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static String getThisExpressionQualifier(ITypeBinding declaringClass, ImportRewrite imports, SimpleName name) {
	ITypeBinding parentType= Bindings.getBindingOfParentType(name);
	ITypeBinding currType= parentType;
	while (currType != null && !Bindings.isSuperType(declaringClass, currType)) {
		currType= currType.getDeclaringClass();
	}
	if (currType == null) {
		declaringClass= declaringClass.getTypeDeclaration();
		currType= parentType;
		while (currType != null && !Bindings.isSuperType(declaringClass, currType)) {
			currType= currType.getDeclaringClass();
		}
	}
	if (currType != parentType) {
		if (currType == null)
			return null;

		if (currType.isAnonymous())
			//If we access a field of a super class of an anonymous class
			//then we can only qualify with 'this' but not with outer.this
			//see bug 115277
			return null;

		return imports.addImport(currType);
	} else {
		return ""; //$NON-NLS-1$
	}
}
 
Example 14
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Collects all elements available in a type: its hierarchy and its outer scopes.
 * @param binding The type binding
 * @param flags Flags defining the elements to report
 * @param requestor the requestor to which all results are reported
 * @return return <code>true</code> if the requestor has reported the binding as found and no further results are required
 */
private boolean addTypeDeclarations(ITypeBinding binding, int flags, IBindingRequestor requestor) {
	if (hasFlag(TYPES, flags) && !binding.isAnonymous()) {
		if (requestor.acceptBinding(binding))
			return true;

		ITypeBinding[] typeParameters= binding.getTypeParameters();
		for (int i= 0; i < typeParameters.length; i++) {
			if (requestor.acceptBinding(typeParameters[i]))
				return true;
		}
	}

	addInherited(binding, flags, requestor); // add inherited

	if (binding.isLocal()) {
		addOuterDeclarationsForLocalType(binding, flags, requestor);
	} else {
		ITypeBinding declaringClass= binding.getDeclaringClass();
		if (declaringClass != null) {
			if (addTypeDeclarations(declaringClass, flags, requestor)) // Recursively add inherited
				return true;
		} else if (hasFlag(TYPES, flags)) {
			if (fRoot.findDeclaringNode(binding) != null) {
				List<AbstractTypeDeclaration> types= fRoot.types();
				for (int i= 0; i < types.size(); i++) {
					if (requestor.acceptBinding(types.get(i).resolveBinding()))
						return true;
				}
			}
		}
	}
	return false;
}
 
Example 15
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.4
 */
protected JvmDeclaredType createType(ITypeBinding typeBinding, String handleIdentifier, List<String> path, StringBuilder fqn) {
	if (typeBinding.isAnonymous() || typeBinding.isSynthetic())
		throw new IllegalStateException("Cannot create type for anonymous or synthetic classes");

	// Creates the right type of instance based on the type of binding.
	//
	JvmGenericType jvmGenericType;
	JvmDeclaredType result;
	if (typeBinding.isAnnotation()) {
		jvmGenericType = null;
		result = TypesFactory.eINSTANCE.createJvmAnnotationType();
	} else if (typeBinding.isEnum()) {
		jvmGenericType = null;
		result = TypesFactory.eINSTANCE.createJvmEnumerationType();
	} else {
		result = jvmGenericType = TypesFactory.eINSTANCE.createJvmGenericType();
		jvmGenericType.setInterface(typeBinding.isInterface());
	}

	// Populate the information computed from the modifiers.
	//
	int modifiers = typeBinding.getModifiers();
	setTypeModifiers(result, modifiers);
	result.setDeprecated(typeBinding.isDeprecated());
	setVisibility(result, modifiers);

	// Determine the simple name and compose the fully qualified name and path, remembering the fqn length and path size so we can reset them.
	//
	String simpleName = typeBinding.getName();
	fqn.append(simpleName);
	int length = fqn.length();
	int size = path.size();
	path.add(simpleName);

	String qualifiedName = fqn.toString();
	result.internalSetIdentifier(qualifiedName);
	result.setSimpleName(simpleName);

	// Traverse the nested types using '$' as the qualified name separator.
	//
	fqn.append('$');
	createNestedTypes(typeBinding, result, handleIdentifier, path, fqn);

	// Traverse the methods using '.'as the qualifed name separator.
	//
	fqn.setLength(length);
	fqn.append('.');
	createMethods(typeBinding, handleIdentifier, path, fqn, result);
	
	createFields(typeBinding, fqn, result);

	// Set the super types.
	//
	setSuperTypes(typeBinding, qualifiedName, result);

	// If this is for a generic type, populate the type parameters.
	//
	if (jvmGenericType != null) {
		ITypeBinding[] typeParameterBindings = typeBinding.getTypeParameters();
		if (typeParameterBindings.length > 0) {
			InternalEList<JvmTypeParameter> typeParameters = (InternalEList<JvmTypeParameter>)jvmGenericType.getTypeParameters();
			for (ITypeBinding variable : typeParameterBindings) {
				typeParameters.addUnique(createTypeParameter(variable, result));
			}
		}
	}

	// Populate the annotation values.
	//
	createAnnotationValues(typeBinding, result);

	// Restore the path.
	//
	path.remove(size);

	return result;
}
 
Example 16
Source File: RefactorProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean getConvertVarTypeToResolvedTypeProposal(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> proposals) {
	CompilationUnit astRoot = context.getASTRoot();
	IJavaElement root = astRoot.getJavaElement();
	if (root == null) {
		return false;
	}
	IJavaProject javaProject = root.getJavaProject();
	if (javaProject == null) {
		return false;
	}
	if (!JavaModelUtil.is10OrHigher(javaProject)) {
		return false;
	}

	if (!(node instanceof SimpleName)) {
		return false;
	}
	SimpleName name = (SimpleName) node;
	IBinding binding = name.resolveBinding();
	if (!(binding instanceof IVariableBinding)) {
		return false;
	}
	IVariableBinding varBinding = (IVariableBinding) binding;
	if (varBinding.isField() || varBinding.isParameter()) {
		return false;
	}

	ASTNode varDeclaration = astRoot.findDeclaringNode(varBinding);
	if (varDeclaration == null) {
		return false;
	}

	ITypeBinding typeBinding = varBinding.getType();
	if (typeBinding == null || typeBinding.isAnonymous() || typeBinding.isIntersectionType() || typeBinding.isWildcardType()) {
		return false;
	}

	Type type = null;
	if (varDeclaration instanceof SingleVariableDeclaration) {
		type = ((SingleVariableDeclaration) varDeclaration).getType();
	} else if (varDeclaration instanceof VariableDeclarationFragment) {
		ASTNode parent = varDeclaration.getParent();
		if (parent instanceof VariableDeclarationStatement) {
			type = ((VariableDeclarationStatement) parent).getType();
		} else if (parent instanceof VariableDeclarationExpression) {
			type = ((VariableDeclarationExpression) parent).getType();
		}
	}
	if (type == null || !type.isVar()) {
		return false;
	}

	TypeChangeCorrectionProposal proposal = new TypeChangeCorrectionProposal(context.getCompilationUnit(), varBinding, astRoot, typeBinding, false, IProposalRelevance.CHANGE_VARIABLE);
	proposal.setKind(CodeActionKind.Refactor);
	proposals.add(proposal);
	return true;
}
 
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: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender,
		List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig = org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getMethodSignature(methodName, parameterTypes, false);
				boolean is18OrHigher= JavaModelUtil.is18OrHigher(targetCU.getJavaProject());

				boolean isSenderBindingInterface= senderDeclBinding.isInterface();
				if (nodeParentType == senderDeclBinding) {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
				} else {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
				}
				if (is18OrHigher || !isSenderBindingInterface
						|| (nodeParentType != senderDeclBinding && (!(sender instanceof SimpleName) || !((SimpleName) sender).getIdentifier().equals(senderDeclBinding.getName())))) {
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments,
							senderDeclBinding, IProposalRelevance.CREATE_METHOD));
				}

				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						isSenderBindingInterface= senderDeclBinding.isInterface();
						if (!senderDeclBinding.isAnonymous()) {
							if (is18OrHigher || !isSenderBindingInterface) {
								String[] args = new String[] { sig,
										org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) };
								label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
								proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode,
										arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD));
							}
						}
					}
				}
			}
		}
	}
}
 
Example 19
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender, List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName, Collection<ICommandAccess> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			Image image;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig= ASTResolving.getMethodSignature(methodName, parameterTypes, false);

				if (ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
					if (nodeParentType == senderDeclBinding) {
						label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
						image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
					} else {
						label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
						image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
					}
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD, image));
				}
				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						if (!senderDeclBinding.isAnonymous() && ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
							String[] args= new String[] { sig, ASTResolving.getTypeSignature(senderDeclBinding) };
							label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
							image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
							proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD, image));
						}
					}
				}
			}
		}
	}
}
 
Example 20
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);
	}
}