org.eclipse.jdt.internal.compiler.lookup.MethodBinding Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.lookup.MethodBinding. 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: SingleNameReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void manageSyntheticAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo, boolean isReadAccess) {
	if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0)	return;

	//If inlinable field, forget the access emulation, the code gen will directly target it
	if (this.constant != Constant.NotAConstant)
		return;

	if ((this.bits & Binding.FIELD) != 0) {
		FieldBinding fieldBinding = (FieldBinding) this.binding;
		FieldBinding codegenField = fieldBinding.original();
		if (((this.bits & ASTNode.DepthMASK) != 0)
			&& (codegenField.isPrivate() // private access
				|| (codegenField.isProtected() // implicit protected access
						&& codegenField.declaringClass.getPackage() != currentScope.enclosingSourceType().getPackage()))) {
			if (this.syntheticAccessors == null)
				this.syntheticAccessors = new MethodBinding[2];
			this.syntheticAccessors[isReadAccess ? SingleNameReference.READ : SingleNameReference.WRITE] =
			    ((SourceTypeBinding)currentScope.enclosingSourceType().
					enclosingTypeAt((this.bits & ASTNode.DepthMASK) >> ASTNode.DepthSHIFT)).addSyntheticMethod(codegenField, isReadAccess, false /*not super access*/);
			currentScope.problemReporter().needToEmulateFieldAccess(codegenField, this, isReadAccess);
			return;
		}
	}
}
 
Example #2
Source File: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean isCompatibleWith(TypeBinding left, Scope scope) {
	if (this.binding != null && this.binding.isValidBinding() // binding indicates if full resolution has already happened
			&& this.resolvedType != null && this.resolvedType.isValidBinding()) {
		return this.resolvedType.isCompatibleWith(left, scope);
	}
	// 15.28.2
	left = left.uncapture(this.enclosingScope);
	final MethodBinding sam = left.getSingleAbstractMethod(this.enclosingScope, true);
	if (sam == null || !sam.isValidBinding())
		return false;
	boolean isCompatible;
	setExpectedType(left);
	IErrorHandlingPolicy oldPolicy = this.enclosingScope.problemReporter().switchErrorHandlingPolicy(silentErrorHandlingPolicy);
	try {
		this.binding = null;
		this.trialResolution = true;
		resolveType(this.enclosingScope);
	} finally {
		this.enclosingScope.problemReporter().switchErrorHandlingPolicy(oldPolicy);
		isCompatible = this.binding != null && this.binding.isValidBinding();
		this.binding = null;
		setExpectedType(null);
		this.trialResolution = false;
	}
	return isCompatible;
}
 
Example #3
Source File: Extractor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
private static String getParameterList(@NonNull MethodBinding binding, boolean isVarargs) {
    // Create compact type signature (no spaces around commas or generics arguments)
    StringBuilder sb = new StringBuilder();
    TypeBinding[] typeParameters = binding.parameters;
    if (typeParameters != null) {
        for (int i = 0, n = typeParameters.length; i < n; i++) {
            TypeBinding parameter = typeParameters[i];
            if (i > 0) {
                sb.append(',');
            }
            String str = fixParameterString(new String(parameter.readableName()));
            if (isVarargs && i == n - 1 && str.endsWith("[]")) {
                str = str.substring(0, str.length() - 2) + "...";
            }
            sb.append(str);
        }
    }
    return sb.toString();
}
 
Example #4
Source File: Extractor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) {
    Annotation[] annotations = constructorDeclaration.annotations;
    if (hasRelevantAnnotations(annotations)) {
        MethodBinding constructorBinding = constructorDeclaration.binding;
        if (constructorBinding == null) {
            return false;
        }

        String fqn = getFqn(scope);
        ClassKind kind = ClassKind.forType(scope.referenceContext);
        Item item = MethodItem.create(fqn, kind, constructorDeclaration, constructorBinding);
        if (item != null) {
            addItem(fqn, item);
            addAnnotations(annotations, item);
        }
    }

    Argument[] arguments = constructorDeclaration.arguments;
    if (arguments != null) {
        for (Argument argument : arguments) {
            argument.traverse(this, constructorDeclaration.scope);
        }
    }
    return false;
}
 
Example #5
Source File: EcjParser.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/** Computes the super method, if any, given a method binding */
private static MethodBinding findSuperMethodBinding(@NonNull MethodBinding binding) {
    try {
        ReferenceBinding superclass = binding.declaringClass.superclass();
        while (superclass != null) {
            MethodBinding[] methods = superclass.getMethods(binding.selector,
                    binding.parameters.length);
            for (MethodBinding method : methods) {
                if (method.areParameterErasuresEqual(binding)) {
                    return method;
                }
            }

            superclass = superclass.superclass();
        }
    } catch (Exception ignore) {
        // Work around ECJ bugs; see https://code.google.com/p/android/issues/detail?id=172268
    }

    return null;
}
 
Example #6
Source File: FunctionalExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public TypeBinding resolveType(BlockScope blockScope) {
	this.constant = Constant.NotAConstant;
	this.enclosingScope = blockScope;
	MethodBinding sam = this.expectedType == null ? null : this.expectedType.getSingleAbstractMethod(blockScope, argumentsTypeElided());
	if (sam == null) {
		blockScope.problemReporter().targetTypeIsNotAFunctionalInterface(this);
		return null;
	}
	if (!sam.isValidBinding()) {
		return reportSamProblem(blockScope, sam);
	}
	
	this.descriptor = sam;
	if (kosherDescriptor(blockScope, sam, true)) {
		return this.resolvedType = this.expectedType;		
	}
	
	return this.resolvedType = null;
}
 
Example #7
Source File: EcjParser.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
@NonNull
public Iterable<ResolvedMethod> getConstructors() {
    if (mBinding instanceof ReferenceBinding) {
        ReferenceBinding cls = (ReferenceBinding) mBinding;
        MethodBinding[] methods = cls.getMethods(TypeConstants.INIT);
        if (methods != null) {
            int count = methods.length;
            List<ResolvedMethod> result = Lists.newArrayListWithExpectedSize(count);
            for (MethodBinding method : methods) {
                if (method.isConstructor()) {
                    result.add(new EcjResolvedMethod(method));
                }
            }
            return result;
        }
    }

    return Collections.emptyList();
}
 
Example #8
Source File: CodeSnippetScope.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public MethodBinding findMethodForArray(ArrayBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
	ReferenceBinding object = getJavaLangObject();
	MethodBinding methodBinding = object.getExactMethod(selector, argumentTypes, null);
	if (methodBinding != null) {
		// handle the method clone() specially... cannot be protected or throw exceptions
		if (argumentTypes == Binding.NO_PARAMETERS && CharOperation.equals(selector, TypeConstants.CLONE))
			return new MethodBinding((methodBinding.modifiers & ~ClassFileConstants.AccProtected) | ClassFileConstants.AccPublic, TypeConstants.CLONE, methodBinding.returnType, argumentTypes, null, object);
		if (canBeSeenByForCodeSnippet(methodBinding, receiverType, invocationSite, this))
			return methodBinding;
	}

	// answers closest approximation, may not check argumentTypes or visibility
	methodBinding = findMethod(object, selector, argumentTypes, invocationSite, false);
	if (methodBinding == null)
		return new ProblemMethodBinding(selector, argumentTypes, ProblemReasons.NotFound);
	if (methodBinding.isValidBinding()) {
	    MethodBinding compatibleMethod = computeCompatibleMethod(methodBinding, argumentTypes, invocationSite, Scope.FULL_INFERENCE);
	    if (compatibleMethod == null)
			return new ProblemMethodBinding(methodBinding, selector, argumentTypes, ProblemReasons.NotFound);
	    methodBinding = compatibleMethod;
		if (!canBeSeenByForCodeSnippet(methodBinding, receiverType, invocationSite, this))
			return new ProblemMethodBinding(methodBinding, selector, methodBinding.parameters, ProblemReasons.NotVisible);
	}
	return methodBinding;
}
 
Example #9
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(Argument argument, BlockScope scope) {
	Annotation[] annotations = argument.annotations;
	ReferenceContext referenceContext = scope.referenceContext();
	if (referenceContext instanceof AbstractMethodDeclaration) {
		MethodBinding binding = ((AbstractMethodDeclaration) referenceContext).binding;
		if (binding != null) {
			TypeDeclaration typeDeclaration = scope.referenceType();
			typeDeclaration.binding.resolveTypesFor(binding);
			if (argument.binding != null) {
				argument.binding = new AptSourceLocalVariableBinding(argument.binding, binding);
			}
		}
		if (annotations != null) {
			this.resolveAnnotations(
					scope,
					annotations,
					argument.binding);
		}
	}
	return false;
}
 
Example #10
Source File: PatchDelegate.java    From EasyMPermission with MIT License 6 votes vote down vote up
private static void failIfContainsAnnotation(TypeBinding parent, Binding[] bindings) throws DelegateRecursion {
	if (bindings == null) return;
	
	for (Binding b : bindings) {
		AnnotationBinding[] anns = null;
		if (b instanceof MethodBinding) anns = ((MethodBinding) b).getAnnotations();
		if (b instanceof FieldBinding) anns = ((FieldBinding) b).getAnnotations();
		// anns = b.getAnnotations() would make a heck of a lot more sense, but that is a late addition to ecj, so would cause NoSuchMethodErrors! Don't use that!
		if (anns == null) continue;
		for (AnnotationBinding ann : anns) {
			char[][] name = null;
			try {
				name = ann.getAnnotationType().compoundName;
			} catch (Exception ignore) {}
			
			if (name == null || name.length < 2 || name.length > 3) continue;
			if (!Arrays.equals(STRING_LOMBOK, name[0])) continue;
			if (!Arrays.equals(STRING_DELEGATE, name[name.length - 1])) continue;
			if (name.length == 3 && !Arrays.equals(STRING_EXPERIMENTAL, name[1])) continue;
			
			throw new DelegateRecursion(parent.readableName(), b.readableName());
		}
	}
}
 
Example #11
Source File: PatchExtensionMethodCompletionProposal.java    From EasyMPermission with MIT License 6 votes vote down vote up
public static IJavaCompletionProposal[] getJavaCompletionProposals(IJavaCompletionProposal[] javaCompletionProposals,
		CompletionProposalCollector completionProposalCollector) {
	
	List<IJavaCompletionProposal> proposals = new ArrayList<IJavaCompletionProposal>(Arrays.asList(javaCompletionProposals));
	if (canExtendCodeAssist(proposals)) {
		IJavaCompletionProposal firstProposal = proposals.get(0);
		int replacementOffset = getReplacementOffset(firstProposal);
		for (Extension extension : getExtensionMethods(completionProposalCollector)) {
			for (MethodBinding method : extension.extensionMethods) {
				ExtensionMethodCompletionProposal newProposal = new ExtensionMethodCompletionProposal(replacementOffset);
				copyNameLookupAndCompletionEngine(completionProposalCollector, firstProposal, newProposal);
				ASTNode node = getAssistNode(completionProposalCollector);
				newProposal.setMethodBinding(method, node);
				createAndAddJavaCompletionProposal(completionProposalCollector, newProposal, proposals);
			}
		}
	}
	return proposals.toArray(new IJavaCompletionProposal[proposals.size()]);
}
 
Example #12
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean isPertinentToApplicability(TypeBinding targetType, MethodBinding method) {
	if (targetType == null) // assumed to signal another primary error
		return true;
	
	if (argumentsTypeElided())
		return false;
	
	if (!super.isPertinentToApplicability(targetType, method))
		return false;
	
	if (this.body instanceof Expression) {
		if (!((Expression) this.body).isPertinentToApplicability(targetType, method))
			return false;
	} else {
		Expression [] returnExpressions = this.resultExpressions;
		for (int i = 0, length = returnExpressions.length; i < length; i++) {
			if (!returnExpressions[i].isPertinentToApplicability(targetType, method))
				return false;
		}
	}
	
	return true;
}
 
Example #13
Source File: PatchExtensionMethod.java    From EasyMPermission with MIT License 6 votes vote down vote up
private static List<MethodBinding> getApplicableExtensionMethodsDefinedInProvider(EclipseNode typeNode, ReferenceBinding extensionMethodProviderBinding,
		TypeBinding receiverType) {
	
	List<MethodBinding> extensionMethods = new ArrayList<MethodBinding>();
	CompilationUnitScope cuScope = ((CompilationUnitDeclaration) typeNode.top().get()).scope;
	for (MethodBinding method : extensionMethodProviderBinding.methods()) {
		if (!method.isStatic()) continue;
		if (!method.isPublic()) continue;
		if (method.parameters == null || method.parameters.length == 0) continue;
		TypeBinding firstArgType = method.parameters[0];
		if (receiverType.isProvablyDistinct(firstArgType) && !receiverType.isCompatibleWith(firstArgType.erasure())) continue;
		TypeBinding[] argumentTypes = Arrays.copyOfRange(method.parameters, 1, method.parameters.length);
		if ((receiverType instanceof ReferenceBinding) && ((ReferenceBinding) receiverType).getExactMethod(method.selector, argumentTypes, cuScope) != null) continue;
		extensionMethods.add(method);
	}
	return extensionMethods;
}
 
Example #14
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public TypeBinding[] getMarkerInterfaces() {
	if (this.expectedType instanceof IntersectionCastTypeBinding) {
		Set markerBindings = new LinkedHashSet();
		TypeBinding[] intersectionTypes = ((IntersectionCastTypeBinding)this.expectedType).intersectingTypes;
		for (int i = 0,max = intersectionTypes.length; i < max; i++) {
			TypeBinding typeBinding = intersectionTypes[i];
			MethodBinding methodBinding = typeBinding.getSingleAbstractMethod(this.scope, true);
			// Why doesn't getSingleAbstractMethod do as the javadoc says, and return null
			// when it is not a SAM type
			if (!(methodBinding instanceof ProblemMethodBinding && ((ProblemMethodBinding)methodBinding).problemId()==ProblemReasons.NoSuchSingleAbstractMethod)) {
				continue;
			}
			if (typeBinding.id == TypeIds.T_JavaIoSerializable) {
				// Serializable is captured as a bitflag
				continue;
			}
			markerBindings.add(typeBinding);
		}
		if (markerBindings.size() > 0) {
			return (TypeBinding[])markerBindings.toArray(new TypeBinding[markerBindings.size()]);
		}
	}
	return null;
}
 
Example #15
Source File: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
MethodBinding internalResolveTentatively(TypeBinding targetType, Scope scope) {
	// FIXME: could enclosingScope still be null here??
	IErrorHandlingPolicy oldPolicy = this.enclosingScope.problemReporter().switchErrorHandlingPolicy(silentErrorHandlingPolicy);
	ExpressionContext previousContext = this.expressionContext;
	MethodBinding previousBinding = this.binding;
	MethodBinding previousDescriptor = this.descriptor;
	TypeBinding previousResolvedType = this.resolvedType;
	try {
		setExpressionContext(INVOCATION_CONTEXT);
		setExpectedType(targetType);
		this.binding = null;
		this.trialResolution = true;
		resolveType(this.enclosingScope);
		return this.binding;
	} finally {
		this.enclosingScope.problemReporter().switchErrorHandlingPolicy(oldPolicy);
		// remove *any relevant* traces of this 'inofficial' resolving:
		this.binding = previousBinding;
		this.descriptor = previousDescriptor;
		this.resolvedType = previousResolvedType;
		setExpressionContext(previousContext);
		this.expectedType = null; // don't call setExpectedType(null), would NPE
		this.trialResolution = false;
	}
}
 
Example #16
Source File: SelectionRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This method returns an IMethod element from the given method and declaring type bindings. However,
 * unlike {@link Util#findMethod(IType, char[], String[], boolean)} , this does not require an IType to get 
 * the IMethod element.
 * @param method the given method binding
 * @param signatures the type signatures of the method arguments
 * @param declaringClass the binding of the method's declaring class
 * @return an IMethod corresponding to the method binding given, or null if none is found.
 */
public IJavaElement findMethodFromBinding(MethodBinding method, String[] signatures, ReferenceBinding declaringClass) {
	IType foundType = this.resolveType(declaringClass.qualifiedPackageName(), declaringClass.qualifiedSourceName(), NameLookup.ACCEPT_CLASSES & NameLookup.ACCEPT_INTERFACES);
	if (foundType != null) {
		if (foundType instanceof BinaryType) {
			try {
				return Util.findMethod(foundType, method.selector, signatures, method.isConstructor());
			} catch (JavaModelException e) {
				return null;
			}
		} else {
			return foundType.getMethod(new String(method.selector), signatures);
		}
	}
	return null;
}
 
Example #17
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public MethodBinding getMethodBinding() {
	if (this.actualMethodBinding == null) {
		if (this.binding != null) {
			this.actualMethodBinding = new MethodBinding(this.binding.modifiers, this.binding.selector, this.binding.returnType, 
					this.binding instanceof SyntheticMethodBinding ? this.descriptor.parameters : this.binding.parameters,  // retain any faults in parameter list.
							this.binding.thrownExceptions, this.binding.declaringClass);
			this.actualMethodBinding.tagBits = this.binding.tagBits;
		} else {
			this.actualMethodBinding = new ProblemMethodBinding(CharOperation.NO_CHAR, null, ProblemReasons.NoSuchSingleAbstractMethod);
		}
	}
	return this.actualMethodBinding;
}
 
Example #18
Source File: ThrownExceptionFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void endVisitMethodInvocation(MethodBinding methodBinding) {
	ReferenceBinding[] thrownExceptionBindings = methodBinding.thrownExceptions;
	int length = thrownExceptionBindings == null ? 0 : thrownExceptionBindings.length;
	for (int i = 0; i < length; i++) {
		acceptException(thrownExceptionBindings[i]);
	}
}
 
Example #19
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(TypeParameter typeParameter, BlockScope scope) {
	Annotation[] annotations = typeParameter.annotations;
	if (annotations != null) {
		TypeVariableBinding binding = typeParameter.binding;
		if (binding == null) {
			return false;
		}
		// when we get here, it is guaranteed that class type parameters are connected, but method type parameters may not be.			
		MethodBinding methodBinding = (MethodBinding) binding.declaringElement;
		((SourceTypeBinding) methodBinding.declaringClass).resolveTypesFor(methodBinding);
		this.resolveAnnotations(scope, annotations, binding);
	}
	return false;
}
 
Example #20
Source File: Extractor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private static String getReturnType(MethodBinding binding) {
    if (binding.returnType != null) {
        return new String(binding.returnType.readableName());
    } else if (binding.declaringClass != null) {
        assert binding.isConstructor();
        return new String(binding.declaringClass.readableName());
    }

    return null;
}
 
Example #21
Source File: Expression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void getAllInheritedMethods0(ReferenceBinding binding, ArrayList<MethodBinding> collector) {
	if (!binding.isInterface()) return;
	MethodBinding[] methodBindings = binding.methods();
	for (int i = 0, max = methodBindings.length; i < max; i++) {
		collector.add(methodBindings[i]);
	}
	ReferenceBinding[] superInterfaces = binding.superInterfaces();
	for (int i = 0, max = superInterfaces.length; i < max; i++) {
		getAllInheritedMethods0(superInterfaces[i], collector);
	}
}
 
Example #22
Source File: ExecutableElementImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String getFileName() {
	ReferenceBinding dc = ((MethodBinding)_binding).declaringClass;
	char[] name = dc.getFileName();
	if (name == null)
		return null;
	return new String(name);
}
 
Example #23
Source File: InnerInferenceHelper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public TypeBinding[] getArgumentTypesForCandidate(MethodBinding candidate, TypeBinding[] plainArgTypes) {
	TypeBinding[] argTypes = this.argTypesPerCandidate.get(candidate);
	if (argTypes == null)
		return plainArgTypes;
	// fill in any blanks now:
	for (int i = 0; i < argTypes.length; i++) {
		if (argTypes[i] == null)
			argTypes[i] = plainArgTypes[i];
	}
	return argTypes;
}
 
Example #24
Source File: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean sIsMoreSpecific(TypeBinding s, TypeBinding t, Scope scope) {
	
	if (super.sIsMoreSpecific(s, t, scope))
		return true;
	
	if (this.exactMethodBinding == null || t.findSuperTypeOriginatingFrom(s) != null)
		return false;
	
	s = s.capture(this.enclosingScope, this.sourceEnd);
	MethodBinding sSam = s.getSingleAbstractMethod(this.enclosingScope, true);
	if (sSam == null || !sSam.isValidBinding())
		return false;
	TypeBinding r1 = sSam.returnType;
	
	MethodBinding tSam = t.getSingleAbstractMethod(this.enclosingScope, true);
	if (tSam == null || !tSam.isValidBinding())
		return false;
	TypeBinding r2 = tSam.returnType;
	
	if (r2.id == TypeIds.T_void)
		return true;
	
	if (r1.id == TypeIds.T_void)
		return false;
	
	// r1 <: r2
	if (r1.isCompatibleWith(r2, scope))
		return true;
	
	return r1.isBaseType() != r2.isBaseType() && r1.isBaseType() == this.exactMethodBinding.returnType.isBaseType();
}
 
Example #25
Source File: OrLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void matchLevelAndReportImportRef(ImportReference importRef, Binding binding, MatchLocator locator) throws CoreException {

	// for static import, binding can be a field binding or a member type binding
	// verify that in this case binding is static and use declaring class for fields
	Binding refBinding = binding;
	if (importRef.isStatic()) {
		if (binding instanceof FieldBinding) {
			FieldBinding fieldBinding = (FieldBinding) binding;
			if (!fieldBinding.isStatic()) return;
			refBinding = fieldBinding.declaringClass;
		} else if (binding instanceof MethodBinding) {
			MethodBinding methodBinding = (MethodBinding) binding;
			if (!methodBinding.isStatic()) return;
			refBinding = methodBinding.declaringClass;
		} else if (binding instanceof MemberTypeBinding) {
			MemberTypeBinding memberBinding = (MemberTypeBinding) binding;
			if (!memberBinding.isStatic()) return;
		}
	}

	// Look for closest pattern
	PatternLocator closestPattern = null;
	int level = IMPOSSIBLE_MATCH;
	for (int i = 0, length = this.patternLocators.length; i < length; i++) {
		PatternLocator patternLocator = this.patternLocators[i];
		int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(refBinding);
		if (newLevel > level) {
			closestPattern = patternLocator;
			if (newLevel == ACCURATE_MATCH) break;
			level = newLevel;
		}
	}
	if (closestPattern != null) {
		closestPattern.matchLevelAndReportImportRef(importRef, binding, locator);
	}
}
 
Example #26
Source File: Sorting.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static MethodBinding[] concreteFirst(MethodBinding[] methods, int length) {
	if (length == 0 || (length > 0 && !methods[0].isAbstract()))
		return methods;
	MethodBinding[] copy = new MethodBinding[length];
	int idx = 0;
	for (int i=0; i<length; i++)
		if (!methods[i].isAbstract())
			copy[idx++] = methods[i];
	for (int i=0; i<length; i++)
		if (methods[i].isAbstract())
			copy[idx++] = methods[i];
	return copy;
}
 
Example #27
Source File: CodeSnippetScope.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public MethodBinding findExactMethod(ReferenceBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
	MethodBinding exactMethod = receiverType.getExactMethod(selector, argumentTypes, null);
	if (exactMethod != null){
		if (receiverType.isInterface() || canBeSeenByForCodeSnippet(exactMethod, receiverType, invocationSite, this))
			return exactMethod;
	}
	return null;
}
 
Example #28
Source File: ElementsImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public PackageElement getPackageOf(Element type) {
	switch(type.getKind()) {
		case ANNOTATION_TYPE :
		case CLASS :
		case ENUM :
		case INTERFACE :
			TypeElementImpl typeElementImpl = (TypeElementImpl) type;
			ReferenceBinding referenceBinding = (ReferenceBinding)typeElementImpl._binding;
			return (PackageElement) _env.getFactory().newElement(referenceBinding.fPackage);
		case PACKAGE :
			return (PackageElement) type;
		case CONSTRUCTOR :
		case METHOD :
			ExecutableElementImpl executableElementImpl = (ExecutableElementImpl) type;
			MethodBinding methodBinding = (MethodBinding) executableElementImpl._binding;
			return (PackageElement) _env.getFactory().newElement(methodBinding.declaringClass.fPackage);
		case ENUM_CONSTANT :
		case FIELD :
			VariableElementImpl variableElementImpl = (VariableElementImpl) type;
			FieldBinding fieldBinding = (FieldBinding) variableElementImpl._binding;
			return (PackageElement) _env.getFactory().newElement(fieldBinding.declaringClass.fPackage);
		case PARAMETER :
			variableElementImpl = (VariableElementImpl) type;
			LocalVariableBinding localVariableBinding = (LocalVariableBinding) variableElementImpl._binding;
			return (PackageElement) _env.getFactory().newElement(localVariableBinding.declaringScope.classScope().referenceContext.binding.fPackage);
		case EXCEPTION_PARAMETER :
		case INSTANCE_INIT :
		case OTHER :
		case STATIC_INIT :
		case TYPE_PARAMETER :
		case LOCAL_VARIABLE :
			return null;
	}
	// unreachable
	return null;
}
 
Example #29
Source File: ElementsImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Compute a list of all the visible entities in this type.  Specifically:
 * <ul>
 * <li>All nested types declared in this type, including interfaces and enums</li>
 * <li>All protected or public nested types declared in this type's superclasses
 * and superinterfaces, that are not hidden by a name collision</li>
 * <li>All methods declared in this type, including constructors but not
 * including static or instance initializers, and including abstract
 * methods and unimplemented methods declared in interfaces</li>
 * <li>All protected or public methods declared in this type's superclasses,
 * that are not overridden by another method, but not including constructors
 * or initializers. Includes abstract methods and methods declared in
 * superinterfaces but not implemented</li>
 * <li>All fields declared in this type, including constants</li>
 * <li>All non-private fields declared in this type's superclasses and
 * superinterfaces, that are not hidden by a name collision.</li>
 * </ul>
 */
@Override
public List<? extends Element> getAllMembers(TypeElement type) {
	if (null == type || !(type instanceof TypeElementImpl)) {
		return Collections.emptyList();
	}
	ReferenceBinding binding = (ReferenceBinding)((TypeElementImpl)type)._binding;
	// Map of element simple name to binding
	Map<String, ReferenceBinding> types = new HashMap<String, ReferenceBinding>();
	// Javac implementation does not take field name collisions into account
	List<FieldBinding> fields = new ArrayList<FieldBinding>();
	// For methods, need to compare parameters, not just names
	Map<String, Set<MethodBinding>> methods = new HashMap<String, Set<MethodBinding>>();
	Set<ReferenceBinding> superinterfaces = new LinkedHashSet<ReferenceBinding>();
	boolean ignoreVisibility = true;
	while (null != binding) {
		addMembers(binding, ignoreVisibility, types, fields, methods);
		Set<ReferenceBinding> newfound = new LinkedHashSet<ReferenceBinding>();
		collectSuperInterfaces(binding, superinterfaces, newfound);
		for (ReferenceBinding superinterface : newfound) {
			addMembers(superinterface, false, types, fields, methods);
		}
		superinterfaces.addAll(newfound);
		binding = binding.superclass();
		ignoreVisibility = false;
	}
	List<Element> allMembers = new ArrayList<Element>();
	for (ReferenceBinding nestedType : types.values()) {
		allMembers.add(_env.getFactory().newElement(nestedType));
	}
	for (FieldBinding field : fields) {
		allMembers.add(_env.getFactory().newElement(field));
	}
	for (Set<MethodBinding> sameNamedMethods : methods.values()) {
		for (MethodBinding method : sameNamedMethods) {
			allMembers.add(_env.getFactory().newElement(method));
		}
	}
	return allMembers;
}
 
Example #30
Source File: CastExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Cast expressions will considered as useful if removing them all would actually bind to a different method
 * (no fine grain analysis on per casted argument basis, simply separate widening cast from narrowing ones)
 */
public static void checkNeedForArgumentCasts(BlockScope scope, Expression receiver, TypeBinding receiverType, MethodBinding binding, Expression[] arguments, TypeBinding[] argumentTypes, final InvocationSite invocationSite) {
	if (scope.compilerOptions().getSeverity(CompilerOptions.UnnecessaryTypeCheck) == ProblemSeverities.Ignore) return;

	int length = argumentTypes.length;

	// iterate over arguments, and retrieve original argument types (before cast)
	TypeBinding[] rawArgumentTypes = argumentTypes;
	for (int i = 0; i < length; i++) {
		Expression argument = arguments[i];
		if (argument instanceof CastExpression) {
			// narrowing conversion on base type may change value, thus necessary
			if ((argument.bits & ASTNode.UnnecessaryCast) == 0 && argument.resolvedType.isBaseType()) {
				continue;
			}
			TypeBinding castedExpressionType = ((CastExpression)argument).expression.resolvedType;
			if (castedExpressionType == null) return; // cannot do better
			// obvious identity cast
			if (TypeBinding.equalsEquals(castedExpressionType, argumentTypes[i])) {
				scope.problemReporter().unnecessaryCast((CastExpression)argument);
			} else if (castedExpressionType == TypeBinding.NULL){
				continue; // tolerate null argument cast
			} else if ((argument.implicitConversion & TypeIds.BOXING) != 0) {
				continue; // boxing has a side effect: (int) char   is not boxed as simple char
			} else {
				if (rawArgumentTypes == argumentTypes) {
					System.arraycopy(rawArgumentTypes, 0, rawArgumentTypes = new TypeBinding[length], 0, length);
				}
				// retain original argument type
				rawArgumentTypes[i] = castedExpressionType;
			}
		}
	}
	// perform alternate lookup with original types
	if (rawArgumentTypes != argumentTypes) {
		checkAlternateBinding(scope, receiver, receiverType, binding, arguments, argumentTypes, rawArgumentTypes, invocationSite);
	}
}