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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#isFromSource() . 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
public static ICompilationUnit findCompilationUnit(ITypeBinding typeBinding, IJavaProject project) throws JavaModelException {
    if (!typeBinding.isFromSource()) {
        return null;
    }
    while (typeBinding != null && !typeBinding.isTopLevel()) {
        typeBinding= typeBinding.getDeclaringClass();
    }
    if (typeBinding != null) {
        IPackageBinding pack= typeBinding.getPackage();
        String packageName= pack.isUnnamed() ? "" : pack.getName(); //$NON-NLS-1$
        IType type= project.findType(packageName, typeBinding.getName());
        if (type != null) {
            return type.getCompilationUnit();
        }
    }
    return null;
}
 
Example 2
Source File: Resolver.java    From DesigniteJava with Apache License 2.0 6 votes vote down vote up
private void inferPrimitiveType(SM_Project parentProject, TypeInfo typeInfo, ITypeBinding iType) {
	if (iType != null && iType.isFromSource() && iType.getModifiers() != 0 && !iType.isWildcardType()) {
		SM_Type inferredType = findType(iType.getName(), iType.getPackage().getName(), parentProject);
		if (inferredType != null) {
			typeInfo.setTypeObj(inferredType);
			typeInfo.setPrimitiveType(false);
		} else {
			typeInfo.setObjPrimitiveType(iType.getName());
			typeInfo.setPrimitiveType(true);
		}
	} else {
		if (iType == null)
			typeInfo.setObjPrimitiveType("wildcard");
		else
			typeInfo.setObjPrimitiveType(iType.getName());
		typeInfo.setPrimitiveType(true);
	}
}
 
Example 3
Source File: Resolver.java    From DesigniteJava with Apache License 2.0 6 votes vote down vote up
private void addNonPrimitiveParameters(SM_Project parentProject, TypeInfo typeInfo, ITypeBinding iType) {
	if (iType.isFromSource() && iType.getModifiers() != 0) {
		SM_Type inferredBasicType = findType(iType.getName(), iType.getPackage().getName(), parentProject);
		addParameterIfNotAlreadyExists(typeInfo, inferredBasicType);
	}
	for (ITypeBinding typeParameter : iType.getTypeArguments()) {
		if (typeParameter.isParameterizedType()) {
			addNonPrimitiveParameters(parentProject, typeInfo, typeParameter);
		} else {
			if (typeParameter.isFromSource() && typeParameter.getModifiers() != 0) {
				SM_Type inferredType = findType(typeParameter.getName(), typeParameter.getPackage().getName(),
						parentProject);
				if (inferredType != null) {
					addParameterIfNotAlreadyExists(typeInfo, inferredType);
				}
			}
		}
	}
}
 
Example 4
Source File: NLSHintHelper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static IStorage getResourceBundle(IJavaProject javaProject, AccessorClassReference accessorClassReference) throws JavaModelException {
	String resourceBundle= accessorClassReference.getResourceBundleName();
	if (resourceBundle == null)
		return null;

	String resourceName= Signature.getSimpleName(resourceBundle) + NLSRefactoring.PROPERTY_FILE_EXT;
	String packName= Signature.getQualifier(resourceBundle);
	ITypeBinding accessorClass= accessorClassReference.getBinding();

	if (accessorClass.isFromSource())
		return getResourceBundle(javaProject, packName, resourceName);
	else if (accessorClass.getJavaElement() != null)
		return getResourceBundle((IPackageFragmentRoot)accessorClass.getJavaElement().getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT), packName, resourceName);

	return null;
}
 
Example 5
Source File: NullAnnotationsRewriteOperations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static CompilationUnit findCUForMethod(CompilationUnit compilationUnit, ICompilationUnit cu, IMethodBinding methodBinding) {
	ASTNode methodDecl= compilationUnit.findDeclaringNode(methodBinding.getMethodDeclaration());
	if (methodDecl == null) {
		// is methodDecl defined in another CU?
		ITypeBinding declaringTypeDecl= methodBinding.getDeclaringClass().getTypeDeclaration();
		if (declaringTypeDecl.isFromSource()) {
			ICompilationUnit targetCU= null;
			try {
				targetCU= ASTResolving.findCompilationUnitForBinding(cu, compilationUnit, declaringTypeDecl);
			} catch (JavaModelException e) { /* can't do better */
			}
			if (targetCU != null) {
				return ASTResolving.createQuickFixAST(targetCU, null);
			}
		}
		return null;
	}
	return compilationUnit;
}
 
Example 6
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ICompilationUnit findCompilationUnitForBinding(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding) throws JavaModelException {
	if (binding == null || !binding.isFromSource() || binding.isTypeVariable() || binding.isWildcardType()) {
		return null;
	}
	ASTNode node= astRoot.findDeclaringNode(binding.getTypeDeclaration());
	if (node == null) {
		ICompilationUnit targetCU= Bindings.findCompilationUnit(binding, cu.getJavaProject());
		if (targetCU != null) {
			return targetCU;
		}
		return null;
	} else if (node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration) {
		return cu;
	}
	return null;
}
 
Example 7
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding,
		ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess,
		Collection<ChangeCorrectionProposal> 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 8
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes the target categories for the method to move.
 *
 * @param declaration
 *            the method declaration
 * @return the possible targets as variable bindings of read-only fields and
 *         parameters
 */
protected IVariableBinding[] computeTargetCategories(final MethodDeclaration declaration) {
	Assert.isNotNull(declaration);
	if (fPossibleTargets.length == 0 || fCandidateTargets.length == 0) {
		final List<IVariableBinding> possibleTargets= new ArrayList<IVariableBinding>(16);
		final List<IVariableBinding> candidateTargets= new ArrayList<IVariableBinding>(16);
		final IMethodBinding method= declaration.resolveBinding();
		if (method != null) {
			final ITypeBinding declaring= method.getDeclaringClass();
			IVariableBinding[] bindings= getArgumentBindings(declaration);
			ITypeBinding binding= null;
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || binding.isEnum() || is18OrHigherInterface(binding)) && binding.isFromSource()) {
					possibleTargets.add(bindings[index]);
					candidateTargets.add(bindings[index]);
				}
			}
			final ReadyOnlyFieldFinder visitor= new ReadyOnlyFieldFinder(declaring);
			declaration.accept(visitor);
			bindings= visitor.getReadOnlyFields();
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || is18OrHigherInterface(binding)) && binding.isFromSource())
					possibleTargets.add(bindings[index]);
			}
			bindings= visitor.getDeclaredFields();
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || is18OrHigherInterface(binding)) && binding.isFromSource())
					candidateTargets.add(bindings[index]);
			}
		}
		fPossibleTargets= new IVariableBinding[possibleTargets.size()];
		possibleTargets.toArray(fPossibleTargets);
		fCandidateTargets= new IVariableBinding[candidateTargets.size()];
		candidateTargets.toArray(fCandidateTargets);
	}
	return fPossibleTargets;
}
 
Example 9
Source File: VarargsWarningsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addAddSafeVarargsToDeclarationProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	if (!JavaModelUtil.is17OrHigher(context.getCompilationUnit().getJavaProject()))
		return;

	ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot());
	IMethodBinding methodBinding;
	if (coveringNode instanceof MethodInvocation) {
		methodBinding= ((MethodInvocation) coveringNode).resolveMethodBinding();
	} else if (coveringNode instanceof ClassInstanceCreation) {
		methodBinding= ((ClassInstanceCreation) coveringNode).resolveConstructorBinding();
	} else {
		return;
	}
	if (methodBinding == null)
		return;
	
	String label= Messages.format(CorrectionMessages.VarargsWarningsSubProcessor_add_safevarargs_to_method_label, methodBinding.getName());

	ITypeBinding declaringType= methodBinding.getDeclaringClass();
	CompilationUnit astRoot= (CompilationUnit) coveringNode.getRoot();
	if (declaringType != null && declaringType.isFromSource()) {
		try {
			ICompilationUnit targetCu= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), astRoot, declaringType);
			if (targetCu != null) {
				AddSafeVarargsProposal proposal= new AddSafeVarargsProposal(label, targetCu, null, methodBinding.getMethodDeclaration(), IProposalRelevance.ADD_SAFEVARARGS);
				proposals.add(proposal);
			}
		} catch (JavaModelException e) {
			return;
		}
	}
}
 
Example 10
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 11
Source File: JdtUtils.java    From j2cl with Apache License 2.0 4 votes vote down vote up
public static TypeDeclaration createDeclarationForType(final ITypeBinding typeBinding) {
  if (typeBinding == null) {
    return null;
  }

  checkArgument(typeBinding.getTypeDeclaration() == typeBinding);
  checkArgument(!typeBinding.isArray());
  checkArgument(!typeBinding.isParameterizedType());
  checkArgument(!typeBinding.isTypeVariable());
  checkArgument(!typeBinding.isWildcardType());
  checkArgument(!typeBinding.isCapture());

  PackageInfoCache packageInfoCache = PackageInfoCache.get();

  ITypeBinding topLevelTypeBinding = toTopLevelTypeBinding(typeBinding);
  if (topLevelTypeBinding.isFromSource()) {
    // Let the PackageInfoCache know that this class is Source, otherwise it would have to rummage
    // around in the class path to figure it out and it might even come up with the wrong answer
    // for example if this class has also been globbed into some other library that is a
    // dependency of this one.
    PackageInfoCache.get().markAsSource(getBinaryNameFromTypeBinding(topLevelTypeBinding));
  }

  // Compute these first since they're reused in other calculations.
  String packageName =
      typeBinding.getPackage() == null ? null : typeBinding.getPackage().getName();
  boolean isAbstract = isAbstract(typeBinding);
  boolean isFinal = isFinal(typeBinding);

  Supplier<ImmutableMap<String, MethodDescriptor>> declaredMethods =
      () -> {
        ImmutableMap.Builder<String, MethodDescriptor> mapBuilder = ImmutableMap.builder();
        for (IMethodBinding methodBinding : typeBinding.getDeclaredMethods()) {
          MethodDescriptor methodDescriptor = createMethodDescriptor(methodBinding);
          mapBuilder.put(
              // TODO(b/33595109): Using the method declaration signature here is kind of iffy;
              // but needs to be done because parameterized types might make multiple
              // superinterface methods collide which are represented by JDT as different method
              // bindings but with the same signature, e.g.
              //   interface I<U, V extends Serializable> {
              //     void foo(U u);
              //     void foo(V v);
              //   }
              // When considering the type I<A,A>, there are two different method bindings
              // that describe the single method 'void foo(A a)' each with the respective
              // method declaration.
              methodDescriptor.getDeclarationDescriptor().getMethodSignature(), methodDescriptor);
        }
        return mapBuilder.build();
      };

  Supplier<ImmutableList<FieldDescriptor>> declaredFields =
      () ->
          Arrays.stream(typeBinding.getDeclaredFields())
              .map(JdtUtils::createFieldDescriptor)
              .collect(toImmutableList());

  JsEnumInfo jsEnumInfo = JsInteropUtils.getJsEnumInfo(typeBinding);

  return TypeDeclaration.newBuilder()
      .setClassComponents(getClassComponents(typeBinding))
      .setEnclosingTypeDeclaration(createDeclarationForType(typeBinding.getDeclaringClass()))
      .setInterfaceTypeDescriptorsFactory(
          () -> createTypeDescriptors(typeBinding.getInterfaces(), DeclaredTypeDescriptor.class))
      .setUnparameterizedTypeDescriptorFactory(() -> createDeclaredTypeDescriptor(typeBinding))
      .setHasAbstractModifier(isAbstract)
      .setKind(getKindFromTypeBinding(typeBinding))
      .setCapturingEnclosingInstance(capturesEnclosingInstance(typeBinding))
      .setFinal(isFinal)
      .setFunctionalInterface(typeBinding.getFunctionalInterfaceMethod() != null)
      .setJsFunctionInterface(JsInteropUtils.isJsFunction(typeBinding))
      .setAnnotatedWithFunctionalInterface(isAnnotatedWithFunctionalInterface(typeBinding))
      .setAnnotatedWithAutoValue(isAnnotatedWithAutoValue(typeBinding))
      .setJsType(JsInteropUtils.isJsType(typeBinding))
      .setJsEnumInfo(jsEnumInfo)
      .setNative(JsInteropUtils.isJsNativeType(typeBinding))
      .setAnonymous(typeBinding.isAnonymous())
      .setLocal(isLocal(typeBinding))
      .setSimpleJsName(getJsName(typeBinding))
      .setCustomizedJsNamespace(getJsNamespace(typeBinding, packageInfoCache))
      .setPackageName(packageName)
      .setSuperTypeDescriptorFactory(getSuperTypeFactory(jsEnumInfo != null, typeBinding))
      .setTypeParameterDescriptors(
          getTypeArgumentTypeDescriptors(typeBinding, TypeVariable.class))
      .setVisibility(getVisibility(typeBinding))
      .setDeclaredMethodDescriptorsFactory(declaredMethods)
      .setDeclaredFieldDescriptorsFactory(declaredFields)
      .setUnusableByJsSuppressed(JsInteropAnnotationUtils.isUnusableByJsSuppressed(typeBinding))
      .setDeprecated(isDeprecated(typeBinding))
      .build();
}
 
Example 12
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.4
 */
protected void enhanceExecutable(StringBuilder fqn, String handleIdentifier, String[] path, JvmExecutable result, IMethodBinding method) {
	String name = method.getName();
	fqn.append(name);
	fqn.append('(');
	ITypeBinding[] parameterTypes = method.getParameterTypes();
	for (int i = 0; i < parameterTypes.length; i++) {
		if (i != 0)
			fqn.append(',');
		fqn.append(getQualifiedName(parameterTypes[i]));
	}
	fqn.append(')');
	result.internalSetIdentifier(fqn.toString());
	result.setSimpleName(name);
	setVisibility(result, method.getModifiers());
	result.setDeprecated(method.isDeprecated());
	if (parameterTypes.length > 0) {
		result.setVarArgs(method.isVarargs());
		String[] parameterNames = null;

		// If the method is derived from source, we can efficiently determine the parameter names now.
		//
		ITypeBinding declaringClass = method.getDeclaringClass();
		if (declaringClass.isFromSource()) {
			parameterNames = getParameterNamesFromSource(fqn, method);
		} else {
			// Use the key to determine the signature for the method.
			//
			SegmentSequence signaturex = getSignatureAsSegmentSequence(method);
			ParameterNameInitializer initializer = jdtCompliance.createParameterNameInitializer(method, workingCopyOwner, result, handleIdentifier, path, name, signaturex);
			((JvmExecutableImplCustom)result).setParameterNameInitializer(initializer);
		}

		setParameterNamesAndAnnotations(method, parameterTypes, parameterNames, result);
	}

	ITypeBinding[] exceptionTypes = method.getExceptionTypes();
	if (exceptionTypes.length > 0) {
		InternalEList<JvmTypeReference> exceptions = (InternalEList<JvmTypeReference>)result.getExceptions();
		for (ITypeBinding exceptionType : exceptionTypes) {
			exceptions.addUnique(createTypeReference(exceptionType));
		}
	}
}
 
Example 13
Source File: TypeMismatchSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	MethodDeclaration decl= ASTResolving.findParentMethodDeclaration(selectedNode);
	if (decl == null) {
		return;
	}
	IMethodBinding methodDeclBinding= decl.resolveBinding();
	if (methodDeclBinding == null) {
		return;
	}

	ITypeBinding returnType= methodDeclBinding.getReturnType();
	IMethodBinding overridden= Bindings.findOverriddenMethod(methodDeclBinding, false);
	if (overridden == null || overridden.getReturnType() == returnType) {
		return;
	}


	ICompilationUnit cu= context.getCompilationUnit();
	IMethodBinding methodDecl= methodDeclBinding.getMethodDeclaration();
	ITypeBinding overriddenReturnType= overridden.getReturnType();
	if (! JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaProject())) {
		overriddenReturnType= overriddenReturnType.getErasure();
	}
	proposals.add(new TypeChangeCorrectionProposal(cu, methodDecl, astRoot, overriddenReturnType, false, IProposalRelevance.CHANGE_RETURN_TYPE));

	ICompilationUnit targetCu= cu;

	IMethodBinding overriddenDecl= overridden.getMethodDeclaration();
	ITypeBinding overridenDeclType= overriddenDecl.getDeclaringClass();

	if (overridenDeclType.isFromSource()) {
		targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, overridenDeclType);
		if (targetCu != null && ASTResolving.isUseableTypeInContext(returnType, overriddenDecl, false)) {
			TypeChangeCorrectionProposal proposal= new TypeChangeCorrectionProposal(targetCu, overriddenDecl, astRoot, returnType, false, IProposalRelevance.CHANGE_RETURN_TYPE_OF_OVERRIDDEN);
			if (overridenDeclType.isInterface()) {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofimplemented_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			} else {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofoverridden_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			}
			proposals.add(proposal);
		}
	}
}
 
Example 14
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 15
Source File: TypeMismatchSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	MethodDeclaration decl= ASTResolving.findParentMethodDeclaration(selectedNode);
	if (decl == null) {
		return;
	}
	IMethodBinding methodDeclBinding= decl.resolveBinding();
	if (methodDeclBinding == null) {
		return;
	}

	ITypeBinding returnType= methodDeclBinding.getReturnType();
	IMethodBinding overridden= Bindings.findOverriddenMethod(methodDeclBinding, false);
	if (overridden == null || overridden.getReturnType() == returnType) {
		return;
	}


	ICompilationUnit cu= context.getCompilationUnit();
	IMethodBinding methodDecl= methodDeclBinding.getMethodDeclaration();
	ITypeBinding overriddenReturnType= overridden.getReturnType();
	if (! JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaProject())) {
		overriddenReturnType= overriddenReturnType.getErasure();
	}
	proposals.add(new TypeChangeCorrectionProposal(cu, methodDecl, astRoot, overriddenReturnType, false, IProposalRelevance.CHANGE_RETURN_TYPE));

	ICompilationUnit targetCu= cu;

	IMethodBinding overriddenDecl= overridden.getMethodDeclaration();
	ITypeBinding overridenDeclType= overriddenDecl.getDeclaringClass();

	if (overridenDeclType.isFromSource()) {
		targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, overridenDeclType);
		if (targetCu != null && ASTResolving.isUseableTypeInContext(returnType, overriddenDecl, false)) {
			TypeChangeCorrectionProposal proposal= new TypeChangeCorrectionProposal(targetCu, overriddenDecl, astRoot, returnType, false, IProposalRelevance.CHANGE_RETURN_TYPE_OF_OVERRIDDEN);
			if (overridenDeclType.isInterface()) {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofimplemented_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			} else {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofoverridden_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			}
			proposals.add(proposal);
		}
	}
}
 
Example 16
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));
						}
					}
				}
			}
		}
	}
}