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

The following examples show how to use org.eclipse.jdt.internal.compiler.lookup.Binding. 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: ASTNode.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static int checkInvocationArgument(BlockScope scope, Expression argument, TypeBinding parameterType, TypeBinding argumentType, TypeBinding originalParameterType) {
	argument.computeConversion(scope, parameterType, argumentType);

	if (argumentType != TypeBinding.NULL && parameterType.kind() == Binding.WILDCARD_TYPE) { // intersection types are tolerated
		WildcardBinding wildcard = (WildcardBinding) parameterType;
		if (wildcard.boundKind != Wildcard.SUPER) {
	    	return INVOCATION_ARGUMENT_WILDCARD;
		}
	}
	TypeBinding checkedParameterType = parameterType; // originalParameterType == null ? parameterType : originalParameterType;
	if (TypeBinding.notEquals(argumentType, checkedParameterType) && argumentType.needsUncheckedConversion(checkedParameterType)) {
		scope.problemReporter().unsafeTypeConversion(argument, argumentType, checkedParameterType);
		return INVOCATION_ARGUMENT_UNCHECKED;
	}
	return INVOCATION_ARGUMENT_OK;
}
 
Example #2
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 #3
Source File: TypesImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public TypeMirror erasure(TypeMirror t) {
	TypeMirrorImpl typeMirrorImpl = (TypeMirrorImpl) t;
	Binding binding = typeMirrorImpl._binding;
	if (binding instanceof ReferenceBinding) {
		return _env.getFactory().newTypeMirror(((ReferenceBinding) binding).erasure());
	}
	if (binding instanceof ArrayBinding) {
		TypeBinding typeBinding = (TypeBinding) binding;
		return _env.getFactory().newTypeMirror(
				this._env.getLookupEnvironment().createArrayType(
						typeBinding.leafComponentType().erasure(),
						typeBinding.dimensions()));
	}
	return t;
}
 
Example #4
Source File: TypesImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
 public List<? extends TypeMirror> directSupertypes(TypeMirror t) {
     switch(t.getKind()) {
         case PACKAGE :
         case EXECUTABLE :
             throw new IllegalArgumentException("Invalid type mirror for directSupertypes"); //$NON-NLS-1$
         default:
             break;
     }
     TypeMirrorImpl typeMirrorImpl = (TypeMirrorImpl) t;
     Binding binding = typeMirrorImpl._binding;
     if (binding instanceof ReferenceBinding) {
     	ReferenceBinding referenceBinding = (ReferenceBinding) binding;
     	ArrayList<TypeMirror> list = new ArrayList<TypeMirror>();
     	ReferenceBinding superclass = referenceBinding.superclass();
if (superclass != null) {
     		list.add(this._env.getFactory().newTypeMirror(superclass));
     	}
for (ReferenceBinding interfaceBinding : referenceBinding.superInterfaces()) {
     		list.add(this._env.getFactory().newTypeMirror(interfaceBinding));
}
return Collections.unmodifiableList(list);
     }
     return Collections.emptyList();
 }
 
Example #5
Source File: RecoveredTypeBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IPackageBinding getPackage() {
	if (this.binding != null) {
		switch (this.binding.kind()) {
			case Binding.BASE_TYPE :
			case Binding.ARRAY_TYPE :
			case Binding.TYPE_PARAMETER : // includes capture scenario
			case Binding.WILDCARD_TYPE :
			case Binding.INTERSECTION_TYPE:
				return null;
		}
		IPackageBinding packageBinding = this.resolver.getPackageBinding(this.binding.getPackage());
		if (packageBinding != null) return packageBinding;
	}
	if (this.innerTypeBinding != null && this.dimensions > 0) {
		return null;
	}
	CompilationUnitScope scope = this.resolver.scope();
	if (scope != null) {
		return this.resolver.getPackageBinding(scope.getCurrentPackage());
	}
	return null;
}
 
Example #6
Source File: RoundEnvImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * From the set of root elements and their enclosed elements, return the subset that are annotated
 * with {@code a}.  If {@code a} is annotated with the {@link java.lang.annotation.Inherited} 
 * annotation, include those elements that inherit the annotation from their superclasses.
 * Note that {@link java.lang.annotation.Inherited} only applies to classes (i.e. TypeElements).
 */
@Override
public Set<? extends Element> getElementsAnnotatedWith(TypeElement a)
{
	if (a.getKind() != ElementKind.ANNOTATION_TYPE) {
		throw new IllegalArgumentException("Argument must represent an annotation type"); //$NON-NLS-1$
	}
	Binding annoBinding = ((TypeElementImpl)a)._binding;
	if (0 != (annoBinding.getAnnotationTagBits() & TagBits.AnnotationInherited)) {
		Set<Element> annotatedElements = new HashSet<Element>(_annoToUnit.getValues(a));
		// For all other root elements that are TypeElements, and for their recursively enclosed
		// types, add each element if it has a superclass are annotated with 'a'
		ReferenceBinding annoTypeBinding = (ReferenceBinding) annoBinding;
		for (TypeElement element : ElementFilter.typesIn(getRootElements())) {
			ReferenceBinding typeBinding = (ReferenceBinding)((TypeElementImpl)element)._binding;
			addAnnotatedElements(annoTypeBinding, typeBinding, annotatedElements);
		}
		return Collections.unmodifiableSet(annotatedElements);
	}
	return Collections.unmodifiableSet(_annoToUnit.getValues(a));
}
 
Example #7
Source File: AnnotationDiscoveryVisitor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void resolveAnnotations(BlockScope scope, Annotation[] annotations, Binding currentBinding) {
	
	int length = annotations == null ? 0 : annotations.length;
	if (length == 0)
		return;
	
	boolean old = scope.insideTypeAnnotation;
	scope.insideTypeAnnotation = true;
	ASTNode.resolveAnnotations(scope, annotations, currentBinding);
	scope.insideTypeAnnotation = old;
	ElementImpl element = (ElementImpl) _factory.newElement(currentBinding);
	AnnotationBinding [] annotationBindings = element.getPackedAnnotationBindings(); // discovery is never in terms of repeating annotation.
	for (AnnotationBinding binding : annotationBindings) {
		if (binding != null) { // binding should be resolved, but in case it's not, ignore it: it could have been wrapped into a container.
			TypeElement anno = (TypeElement)_factory.newElement(binding.getAnnotationType());
			_annoToElement.put(anno, element);
		}
	}
}
 
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: SingleNameReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope, FlowInfo flowInfo) {
	//If inlinable field, forget the access emulation, the code gen will directly target it
	if (((this.bits & ASTNode.DepthMASK) == 0 && (this.bits & ASTNode.IsCapturedOuterLocal) == 0) || (this.constant != Constant.NotAConstant)) {
		return;
	}
	if ((this.bits & ASTNode.RestrictiveFlagMASK) == Binding.LOCAL) {
		LocalVariableBinding localVariableBinding = (LocalVariableBinding) this.binding;
		if (localVariableBinding != null) {
			if ((localVariableBinding.tagBits & TagBits.NotInitialized) != 0) {
				// local was tagged as uninitialized
				return;
			}
			switch(localVariableBinding.useFlag) {
				case LocalVariableBinding.FAKE_USED :
				case LocalVariableBinding.USED :
					currentScope.emulateOuterAccess(localVariableBinding);
			}
		}
	}
}
 
Example #10
Source File: QualifiedNameReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public Constant optimizedBooleanConstant() {
	switch (this.resolvedType.id) {
		case T_boolean :
		case T_JavaLangBoolean :
			if (this.constant != Constant.NotAConstant) return this.constant;
			switch (this.bits & ASTNode.RestrictiveFlagMASK) {
				case Binding.FIELD : // reading a field
					if (this.otherBindings == null)
						return ((FieldBinding)this.binding).constant();
					//$FALL-THROUGH$
				case Binding.LOCAL : // reading a local variable
					return this.otherBindings[this.otherBindings.length-1].constant();
		}
	}
	return Constant.NotAConstant;
}
 
Example #11
Source File: TypeReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public TypeBinding resolveTypeArgument(ClassScope classScope, ReferenceBinding genericType, int rank) {
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=294057, circularity is allowed when we are
	// resolving type arguments i.e interface A<T extends C> {}	interface B extends A<D> {}
	// interface D extends C {}	interface C extends B {}
	ReferenceBinding ref = classScope.referenceContext.binding;
	boolean pauseHierarchyCheck = false;
	try {
		if (ref.isHierarchyBeingConnected()) {
			ref.tagBits |= TagBits.PauseHierarchyCheck;
			pauseHierarchyCheck = true;
		}
	    return resolveType(classScope, Binding.DefaultLocationTypeArgument);
	} finally {
		if (pauseHierarchyCheck) {
			ref.tagBits &= ~TagBits.PauseHierarchyCheck;
		}
	}
}
 
Example #12
Source File: AssistSourceType.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public String getKey() {
	if (this.uniqueKey == null) {
		Binding binding = (Binding) this.bindingCache.get(this);
		if (binding != null) {
			this.isResolved = true;
			this.uniqueKey = new String(binding.computeUniqueKey());
		} else {
			this.isResolved = false;
			try {
				this.uniqueKey = getKey(this, false/*don't open*/);
			} catch (JavaModelException e) {
				// happen only if force open is true
				return null;
			}
		}
	}
	return this.uniqueKey;
}
 
Example #13
Source File: AssistSourceField.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public String getKey() {
	if (this.uniqueKey == null) {
		Binding binding = (Binding) this.bindingCache.get(this);
		if (binding != null) {
			this.isResolved = true;
			this.uniqueKey = new String(binding.computeUniqueKey());
		} else {
			this.isResolved = false;
			try {
				this.uniqueKey = getKey(this, false/*don't open*/);
			} catch (JavaModelException e) {
				// happen only if force open is true
				return null;
			}
		}
	}
	return this.uniqueKey;
}
 
Example #14
Source File: DefaultBindingResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
IBinding getBinding(org.eclipse.jdt.internal.compiler.lookup.Binding binding) {
	switch (binding.kind()) {
		case Binding.PACKAGE:
			return getPackageBinding((org.eclipse.jdt.internal.compiler.lookup.PackageBinding) binding);
		case Binding.TYPE:
		case Binding.BASE_TYPE:
		case Binding.GENERIC_TYPE:
		case Binding.PARAMETERIZED_TYPE:
		case Binding.RAW_TYPE:
			return getTypeBinding((org.eclipse.jdt.internal.compiler.lookup.TypeBinding) binding);
		case Binding.ARRAY_TYPE:
		case Binding.TYPE_PARAMETER:
			return new TypeBinding(this, (org.eclipse.jdt.internal.compiler.lookup.TypeBinding) binding);
		case Binding.METHOD:
			return getMethodBinding((org.eclipse.jdt.internal.compiler.lookup.MethodBinding) binding);
		case Binding.FIELD:
		case Binding.LOCAL:
			return getVariableBinding((org.eclipse.jdt.internal.compiler.lookup.VariableBinding) binding);
	}
	return null;
}
 
Example #15
Source File: BindingKeyResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void consumeWildCard(int kind) {
	switch (kind) {
		case Wildcard.EXTENDS:
		case Wildcard.SUPER:
			BindingKeyResolver boundResolver = (BindingKeyResolver) this.types.get(0);
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=157847, do not allow creation of
			// internally inconsistent wildcards of the form '? super <null>' or '? extends <null>'
			final Binding boundBinding = boundResolver.compilerBinding;
			if (boundBinding instanceof TypeBinding) {
				this.typeBinding = this.environment.createWildcard((ReferenceBinding) this.typeBinding, this.wildcardRank, (TypeBinding) boundBinding, null /*no extra bound*/, kind);
			} else {
				this.typeBinding = null;
			}
			break;
		case Wildcard.UNBOUND:
			this.typeBinding = this.environment.createWildcard((ReferenceBinding) this.typeBinding, this.wildcardRank, null/*no bound*/, null /*no extra bound*/, kind);
			break;
	}
}
 
Example #16
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 #17
Source File: OrLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public SearchMatch newDeclarationMatch(ASTNode reference, IJavaElement element, Binding elementBinding, int accuracy, int length, MatchLocator locator) {
	PatternLocator closestPattern = null;
	int level = IMPOSSIBLE_MATCH;
	for (int i = 0, pl = this.patternLocators.length; i < pl; i++) {
		PatternLocator patternLocator = this.patternLocators[i];
		int newLevel = patternLocator.referenceType() == 0 ? IMPOSSIBLE_MATCH : patternLocator.resolveLevel(reference);
		if (newLevel > level) {
			closestPattern = patternLocator;
			if (newLevel == ACCURATE_MATCH) break;
			level = newLevel;
		}
	}
	if (closestPattern != null) {
	    return closestPattern.newDeclarationMatch(reference, element, elementBinding, accuracy, length, locator);
	}
	// super implementation...
    return locator.newDeclarationMatch(element, elementBinding, accuracy, reference.sourceStart, length);
}
 
Example #18
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void reportBinding(Object key, FileASTRequestor astRequestor, CompilationUnitDeclaration unit) {
	BindingKeyResolver keyResolver = (BindingKeyResolver) key;
	Binding compilerBinding = keyResolver.getCompilerBinding();
	if (compilerBinding != null) {
		DefaultBindingResolver resolver = new DefaultBindingResolver(unit.scope, null, this.bindingTables, false, this.fromJavaProject);
		AnnotationBinding annotationBinding = keyResolver.getAnnotationBinding();
		IBinding binding;
		if (annotationBinding != null) {
			binding = resolver.getAnnotationInstance(annotationBinding);
		} else {
			binding = resolver.getBinding(compilerBinding);
		}
		if (binding != null)
			astRequestor.acceptBinding(keyResolver.getKey(), binding);
	}
}
 
Example #19
Source File: SingleNameReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) {
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=185682
	switch (this.bits & ASTNode.RestrictiveFlagMASK) {
		case Binding.LOCAL:
			LocalVariableBinding localBinding = (LocalVariableBinding) this.binding;
			// check if compound assignment is the only usage of this local
			Reference.reportOnlyUselesslyReadLocal(currentScope, localBinding, valueRequired);
			break;
		case Binding.FIELD:
			// check if compound assignment is the only usage of a private field
			reportOnlyUselesslyReadPrivateField(currentScope, (FieldBinding)this.binding, valueRequired);
	}
	this.generateCompoundAssignment(
		currentScope,
		codeStream,
		this.syntheticAccessors == null ? null : this.syntheticAccessors[SingleNameReference.WRITE],
		expression,
		operator,
		assignmentImplicitConversion,
		valueRequired);
}
 
Example #20
Source File: FakedTrackingVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void cleanUpAfterAssignment(BlockScope currentScope, int lhsBits, Expression expression) {
	// remove all remaining track vars with no original binding

	// unwrap uninteresting nodes:
	while (true) {
		if (expression instanceof Assignment)
			expression = ((Assignment)expression).expression;
		else if (expression instanceof CastExpression)
			expression = ((CastExpression) expression).expression;
		else
			break;
	}
	if (expression instanceof AllocationExpression) {
		FakedTrackingVariable tracker = ((AllocationExpression) expression).closeTracker;
		if (tracker != null && tracker.originalBinding == null) {
			currentScope.removeTrackingVar(tracker);
			((AllocationExpression) expression).closeTracker = null;
		}
	} else {
		// assignment passing a local into a field?
		LocalVariableBinding local = expression.localVariableBinding();
		if (local != null && local.closeTracker != null && ((lhsBits & Binding.FIELD) != 0))
			currentScope.removeTrackingVar(local.closeTracker); // TODO: may want to use local.closeTracker.markPassedToOutside(..,true)
	}
}
 
Example #21
Source File: BindingKeyResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void consumeAnnotation() {
	int size = this.types.size();
	if (size == 0) return;
	Binding annotationType = ((BindingKeyResolver) this.types.get(size-1)).compilerBinding;
	AnnotationBinding[] annotationBindings;
	if (this.compilerBinding == null && this.typeBinding instanceof ReferenceBinding) {
		annotationBindings = ((ReferenceBinding) this.typeBinding).getAnnotations();
	} else if (this.compilerBinding instanceof MethodBinding) {
		annotationBindings = ((MethodBinding) this.compilerBinding).getAnnotations();
	} else if (this.compilerBinding instanceof VariableBinding) {
		annotationBindings = ((VariableBinding) this.compilerBinding).getAnnotations();
	} else {
		return;
	}
	for (int i = 0, length = annotationBindings.length; i < length; i++) {
		AnnotationBinding binding = annotationBindings[i];
		if (binding.getAnnotationType() == annotationType) {
			this.annotationBinding = binding;
			break;
		}
	}
}
 
Example #22
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean kosherDescriptor(Scope currentScope, MethodBinding sam, boolean shouldChatter) {
	if (sam.typeVariables != Binding.NO_TYPE_VARIABLES) {
		if (shouldChatter)
			currentScope.problemReporter().lambdaExpressionCannotImplementGenericMethod(this, sam);
		return false;
	}
	return super.kosherDescriptor(currentScope, sam, shouldChatter);
}
 
Example #23
Source File: JavadocQualifiedTypeReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TypeBinding internalResolveType(Scope scope, boolean checkBounds) {
	// handle the error here
	this.constant = Constant.NotAConstant;
	if (this.resolvedType != null) // is a shared type reference which was already resolved
		return this.resolvedType.isValidBinding() ? this.resolvedType : this.resolvedType.closestMatch(); // already reported error

	TypeBinding type = this.resolvedType = getTypeBinding(scope);
	// End resolution when getTypeBinding(scope) returns null. This may happen in
	// certain circumstances, typically when an illegal access is done on a type
	// variable (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=204749)
	if (type == null) return null;
	if (!type.isValidBinding()) {
		Binding binding = scope.getTypeOrPackage(this.tokens);
		if (binding instanceof PackageBinding) {
			this.packageBinding = (PackageBinding) binding;
			// Valid package references are allowed in Javadoc (https://bugs.eclipse.org/bugs/show_bug.cgi?id=281609)
		} else {
			reportInvalidType(scope);
		}
		return null;
	}
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=209936
	// raw convert all enclosing types when dealing with Javadoc references
	if (type.isGenericType() || type.isParameterizedType()) {
		this.resolvedType = scope.environment().convertToRawType(type, true /*force the conversion of enclosing types*/);
	}
	return this.resolvedType;
}
 
Example #24
Source File: PatchVal.java    From EasyMPermission with MIT License 5 votes vote down vote up
private static TypeBinding getForEachComponentType(Expression collection, BlockScope scope) {
	if (collection != null) {
		TypeBinding resolved = collection.resolvedType;
		if (resolved == null) resolved = collection.resolveType(scope);
		if (resolved == null) return null;
		if (resolved.isArrayType()) {
			resolved = ((ArrayBinding) resolved).elementsType();
			return resolved;
		} else if (resolved instanceof ReferenceBinding) {
			ReferenceBinding iterableType = ((ReferenceBinding)resolved).findSuperTypeOriginatingFrom(TypeIds.T_JavaLangIterable, false);
			
			TypeBinding[] arguments = null;
			if (iterableType != null) switch (iterableType.kind()) {
				case Binding.GENERIC_TYPE : // for (T t : Iterable<T>) - in case used inside Iterable itself
					arguments = iterableType.typeVariables();
					break;
				case Binding.PARAMETERIZED_TYPE : // for(E e : Iterable<E>)
					arguments = ((ParameterizedTypeBinding)iterableType).arguments;
					break;
				case Binding.RAW_TYPE : // for(Object e : Iterable)
					return null;
			}
			
			if (arguments != null && arguments.length == 1) {
				return arguments[0];
			}
		}
	}
	
	return null;
}
 
Example #25
Source File: TypeBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public int getRank() {
	switch (this.binding.kind()) {
		case Binding.WILDCARD_TYPE :
		case Binding.INTERSECTION_TYPE :
			WildcardBinding wildcardBinding = (WildcardBinding) this.binding;
			return wildcardBinding.rank;
		default:
			return -1;
	}
}
 
Example #26
Source File: Factory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a new element that knows what kind it is even if the binding is unresolved.
 */
public Element newElement(Binding binding, ElementKind kindHint) {
	if (binding == null)
		return null;
	switch (binding.kind()) {
	case Binding.FIELD:
	case Binding.LOCAL:
	case Binding.VARIABLE:
		return new VariableElementImpl(_env, (VariableBinding) binding);
	case Binding.TYPE:
	case Binding.GENERIC_TYPE:
		ReferenceBinding referenceBinding = (ReferenceBinding)binding;
		if ((referenceBinding.tagBits & TagBits.HasMissingType) != 0) {
			return new ErrorTypeElement(this._env, referenceBinding);
		}
		if (CharOperation.equals(referenceBinding.sourceName, TypeConstants.PACKAGE_INFO_NAME)) {
			return new PackageElementImpl(_env, referenceBinding.fPackage);
		}
		return new TypeElementImpl(_env, referenceBinding, kindHint);
	case Binding.METHOD:
		return new ExecutableElementImpl(_env, (MethodBinding)binding);
	case Binding.RAW_TYPE:
	case Binding.PARAMETERIZED_TYPE:
		return new TypeElementImpl(_env, ((ParameterizedTypeBinding)binding).genericType(), kindHint);
	case Binding.PACKAGE:
		return new PackageElementImpl(_env, (PackageBinding)binding);
	case Binding.TYPE_PARAMETER:
		return new TypeParameterElementImpl(_env, (TypeVariableBinding)binding);
		// TODO: fill in the rest of these
	case Binding.IMPORT:
	case Binding.ARRAY_TYPE:
	case Binding.BASE_TYPE:
	case Binding.WILDCARD_TYPE:
	case Binding.INTERSECTION_TYPE:
		throw new UnsupportedOperationException("NYI: binding type " + binding.kind()); //$NON-NLS-1$
	}
	return null;
}
 
Example #27
Source File: DefaultBindingResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
synchronized IPackageBinding resolvePackage(PackageDeclaration pkg) {
	if (this.scope == null) return null;
	try {
		org.eclipse.jdt.internal.compiler.ast.ASTNode node = (org.eclipse.jdt.internal.compiler.ast.ASTNode) this.newAstToOldAst.get(pkg);
		if (node instanceof ImportReference) {
			ImportReference importReference = (ImportReference) node;
			Binding binding = this.scope.getOnlyPackage(CharOperation.subarray(importReference.tokens, 0, importReference.tokens.length));
			if ((binding != null) && (binding.isValidBinding())) {
				if (binding instanceof ReferenceBinding) {
					// this only happens if a type name has the same name as its package
					ReferenceBinding referenceBinding = (ReferenceBinding) binding;
					binding = referenceBinding.fPackage;
				}
				if (binding instanceof org.eclipse.jdt.internal.compiler.lookup.PackageBinding) {
					IPackageBinding packageBinding = getPackageBinding((org.eclipse.jdt.internal.compiler.lookup.PackageBinding) binding);
					if (packageBinding == null) {
						return null;
					}
					this.bindingsToAstNodes.put(packageBinding, pkg);
					String key = packageBinding.getKey();
					if (key != null) {
						this.bindingTables.bindingKeysToBindings.put(key, packageBinding);
					}
					return packageBinding;
				}
			}
		}
	} catch (AbortCompilation e) {
		// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53357
		// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=63550
		// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=64299
	}
	return null;
}
 
Example #28
Source File: BindingKeyResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Binding getCompilerBinding() {
	try {
		parse();
		return this.compilerBinding;
	} catch (RuntimeException e) {
		Util.log(e, "Could not create binding from binding key: " + getKey()); //$NON-NLS-1$
		return null;
	}
}
 
Example #29
Source File: Extractor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unused")
static boolean hasSourceRetention(@NonNull Annotation[] annotations) {
    for (Annotation annotation : annotations) {
        String typeName = Extractor.getFqn(annotation);
        if ("java.lang.annotation.Retention".equals(typeName)) {
            MemberValuePair[] pairs = annotation.memberValuePairs();
            if (pairs == null || pairs.length != 1) {
                warning("Expected exactly one parameter passed to @Retention");
                return false;
            }
            MemberValuePair pair = pairs[0];
            Expression value = pair.value;
            if (value instanceof NameReference) {
                NameReference reference = (NameReference) value;
                Binding binding = reference.binding;
                if (binding != null) {
                    if (binding instanceof FieldBinding) {
                        FieldBinding fb = (FieldBinding) binding;
                        if ("SOURCE".equals(new String(fb.name)) &&
                                "java.lang.annotation.RetentionPolicy".equals(
                                        new String(fb.declaringClass.readableName()))) {
                            return true;
                        }
                    }
                }
            }
        }
    }

    return false;
}
 
Example #30
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);
	}
}