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

The following examples show how to use org.eclipse.jdt.internal.compiler.lookup.TypeConstants. 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: PatchVal.java    From EasyMPermission with MIT License 6 votes vote down vote up
public static boolean handleValForForEach(ForeachStatement forEach, BlockScope scope) {
	if (forEach.elementVariable == null) return false;
	
	if (!isVal(forEach.elementVariable.type, scope)) return false;
	
	TypeBinding component = getForEachComponentType(forEach.collection, scope);
	if (component == null) return false;
	TypeReference replacement = makeType(component, forEach.elementVariable.type, false);
	
	forEach.elementVariable.modifiers |= ClassFileConstants.AccFinal;
	forEach.elementVariable.annotations = addValAnnotation(forEach.elementVariable.annotations, forEach.elementVariable.type, scope);
	forEach.elementVariable.type = replacement != null ? replacement :
			new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(forEach.elementVariable.type, 3));
	
	return false;
}
 
Example #2
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 #3
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 6 votes vote down vote up
public IfStatement generateCompareFloatOrDouble(Expression thisRef, Expression otherRef, char[] floatOrDouble, ASTNode source) {
	int pS = source.sourceStart, pE = source.sourceEnd;
	/* if (Float.compare(fieldName, other.fieldName) != 0) return false */
	MessageSend floatCompare = new MessageSend();
	floatCompare.sourceStart = pS; floatCompare.sourceEnd = pE;
	setGeneratedBy(floatCompare, source);
	floatCompare.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.LANG, floatOrDouble);
	floatCompare.selector = "compare".toCharArray();
	floatCompare.arguments = new Expression[] {thisRef, otherRef};
	IntLiteral int0 = makeIntLiteral("0".toCharArray(), source);
	EqualExpression ifFloatCompareIsNot0 = new EqualExpression(floatCompare, int0, OperatorIds.NOT_EQUAL);
	ifFloatCompareIsNot0.sourceStart = pS; ifFloatCompareIsNot0.sourceEnd = pE;
	setGeneratedBy(ifFloatCompareIsNot0, source);
	FalseLiteral falseLiteral = new FalseLiteral(pS, pE);
	setGeneratedBy(falseLiteral, source);
	ReturnStatement returnFalse = new ReturnStatement(falseLiteral, pS, pE);
	setGeneratedBy(returnFalse, source);
	IfStatement ifStatement = new IfStatement(ifFloatCompareIsNot0, returnFalse, pS, pE);
	setGeneratedBy(ifStatement, source);
	return ifStatement;
}
 
Example #4
Source File: ClassFileInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void generateStandardAnnotationsInfos(JavaElement javaElement, char[] parameterName, long tagBits, HashMap newElements) {
	if ((tagBits & TagBits.AllStandardAnnotationsMask) == 0)
		return;
	if ((tagBits & TagBits.AnnotationTargetMASK) != 0) {
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_ANNOTATION_TARGET, getTargetElementTypes(tagBits), newElements);
	}
	if ((tagBits & TagBits.AnnotationRetentionMASK) != 0) {
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_ANNOTATION_RETENTION, getRetentionPolicy(tagBits), newElements);
	}
	if ((tagBits & TagBits.AnnotationDeprecated) != 0) {
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_DEPRECATED, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
	}
	if ((tagBits & TagBits.AnnotationDocumented) != 0) {
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_ANNOTATION_DOCUMENTED, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
	}
	if ((tagBits & TagBits.AnnotationInherited) != 0) {
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_ANNOTATION_INHERITED, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
	}
	if ((tagBits & TagBits.AnnotationPolymorphicSignature) != 0) {
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_INVOKE_METHODHANDLE_$_POLYMORPHICSIGNATURE, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
	}
	if ((tagBits & TagBits.AnnotationSafeVarargs) != 0) {
		generateStandardAnnotation(javaElement, TypeConstants.JAVA_LANG_SAFEVARARGS, Annotation.NO_MEMBER_VALUE_PAIRS, newElements);
	}
	// note that JAVA_LANG_SUPPRESSWARNINGS and JAVA_LANG_OVERRIDE cannot appear in binaries
}
 
Example #5
Source File: EclipseSingularsRecipes.java    From EasyMPermission with MIT License 6 votes vote down vote up
protected TypeReference cloneParamType(int index, List<TypeReference> typeArgs, EclipseNode builderType) {
	if (typeArgs != null && typeArgs.size() > index) {
		TypeReference originalType = typeArgs.get(index);
		if (originalType instanceof Wildcard) {
			Wildcard wOriginalType = (Wildcard) originalType;
			if (wOriginalType.kind == Wildcard.EXTENDS) {
				try {
					return copyType(wOriginalType.bound);
				} catch (Exception e) {
					// fallthrough
				}
			}
		} else {
			return copyType(originalType);
		}
	}
	
	return new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, NULL_POSS);
}
 
Example #6
Source File: FakedTrackingVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public FakedTrackingVariable(LocalVariableBinding original, ASTNode location, FlowInfo flowInfo, FlowContext flowContext, int nullStatus) {
	super(original.name, location.sourceStart, location.sourceEnd);
	this.type = new SingleTypeReference(
			TypeConstants.OBJECT,
			((long)this.sourceStart <<32)+this.sourceEnd);
	this.methodScope = original.declaringScope.methodScope();
	this.originalBinding = original;
	// inside a finally block?
	while (flowContext != null) {
		if (flowContext instanceof FinallyFlowContext) {
			// yes -> connect to the corresponding try block:
			this.tryContext = ((FinallyFlowContext) flowContext).tryContext;
			break;
		}
		flowContext = flowContext.parent;
	}
	resolve(original.declaringScope);
	if (nullStatus != 0)
		flowInfo.markNullStatus(this.binding, nullStatus); // mark that this flow has seen the resource
}
 
Example #7
Source File: SourceIndexerRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void enterEnum(TypeInfo typeInfo) {
	// eliminate possible qualifications, given they need to be fully resolved again
	if (typeInfo.superinterfaces != null){
		for (int i = 0, length = typeInfo.superinterfaces.length; i < length; i++){
			typeInfo.superinterfaces[i] = getSimpleName(typeInfo.superinterfaces[i]);
		}
	}
	char[][] typeNames;
	if (this.methodDepth > 0) {
		typeNames = ONE_ZERO_CHAR;
	} else {
		typeNames = enclosingTypeNames();
	}
	char[] superclass = typeInfo.superclass == null ? CharOperation.concatWith(TypeConstants.JAVA_LANG_ENUM, '.'): typeInfo.superclass;
	this.indexer.addEnumDeclaration(typeInfo.modifiers, this.packageName, typeInfo.name, typeNames, superclass, typeInfo.superinterfaces, typeInfo.secondary);
	addDefaultConstructorIfNecessary(typeInfo);
	pushTypeName(typeInfo.name);
}
 
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: ExecutableElementImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ElementKind getKind() {
	MethodBinding binding = (MethodBinding)_binding;
	if (binding.isConstructor()) {
		return ElementKind.CONSTRUCTOR;
	}
	else if (CharOperation.equals(binding.selector, TypeConstants.CLINIT)) {
		return ElementKind.STATIC_INIT;
	}
	else if (CharOperation.equals(binding.selector, TypeConstants.INIT)) {
		return ElementKind.INSTANCE_INIT;
	}
	else {
		return ElementKind.METHOD;
	}
}
 
Example #10
Source File: ClassFileInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IMemberValuePair[] getRetentionPolicy(long tagBits) {
	if ((tagBits & TagBits.AnnotationRetentionMASK) == 0)
		return Annotation.NO_MEMBER_VALUE_PAIRS;
	String retention = null;
	if ((tagBits & TagBits.AnnotationRuntimeRetention) == TagBits.AnnotationRuntimeRetention) {
		// TagBits.AnnotationRuntimeRetention combines both TagBits.AnnotationClassRetention & TagBits.AnnotationSourceRetention
		retention = new String(CharOperation.concatWith(TypeConstants.JAVA_LANG_ANNOTATION_RETENTIONPOLICY, '.')) + '.' + new String(TypeConstants.UPPER_RUNTIME);
	} else if ((tagBits & TagBits.AnnotationSourceRetention) != 0) {
		retention = new String(CharOperation.concatWith(TypeConstants.JAVA_LANG_ANNOTATION_RETENTIONPOLICY, '.')) + '.' + new String(TypeConstants.UPPER_SOURCE);
	} else {
		retention = new String(CharOperation.concatWith(TypeConstants.JAVA_LANG_ANNOTATION_RETENTIONPOLICY, '.')) + '.' + new String(TypeConstants.UPPER_CLASS);
	}
	final String value = retention;
	return 
		new IMemberValuePair[] {
			new IMemberValuePair() {
				public int getValueKind() {
					return IMemberValuePair.K_QUALIFIED_NAME;
				}
				public Object getValue() {
					return value;
				}
				public String getMemberName() {
					return new String(TypeConstants.VALUE);
				}
			}
		};
}
 
Example #11
Source File: CompilationResult.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Same as getProblems() but don't answer problems that actually concern the enclosing package.
 */
public CategorizedProblem[] getCUProblems() {
	// Re-adjust the size of the problems if necessary and filter package problems
	if (this.problems != null) {
		CategorizedProblem[] filteredProblems = new CategorizedProblem[this.problemCount];
		int keep = 0;
		for (int i=0; i< this.problemCount; i++) {
			CategorizedProblem problem = this.problems[i];
			if (problem.getID() != IProblem.MissingNonNullByDefaultAnnotationOnPackage) {
				filteredProblems[keep++] = problem;
			} else if (this.compilationUnit != null) {
				if (CharOperation.equals(this.compilationUnit.getMainTypeName(), TypeConstants.PACKAGE_INFO_NAME)) {
					filteredProblems[keep++] = problem;
				}
			}
		}
		if (keep < this.problemCount) {
			System.arraycopy(filteredProblems, 0, filteredProblems = new CategorizedProblem[keep], 0, keep);
			this.problemCount = keep;
		}
		this.problems = filteredProblems;
		if (this.maxProblemPerUnit > 0 && this.problemCount > this.maxProblemPerUnit){
			quickPrioritize(this.problems, 0, this.problemCount - 1);
			this.problemCount = this.maxProblemPerUnit;
			System.arraycopy(this.problems, 0, (this.problems = new CategorizedProblem[this.problemCount]), 0, this.problemCount);
		}

		// Stable sort problems per source positions.
		Arrays.sort(this.problems, 0, this.problems.length, CompilationResult.PROBLEM_COMPARATOR);
		//quickSort(problems, 0, problems.length-1);
	}
	return this.problems;
}
 
Example #12
Source File: IncrementalImageBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void addDependentsOf(IPath path, boolean isStructuralChange, StringSet qualifiedNames, StringSet simpleNames, StringSet rootNames) {
	path = path.setDevice(null);
	if (isStructuralChange) {
		String last = path.lastSegment();
		if (last.length() == TypeConstants.PACKAGE_INFO_NAME.length)
			if (CharOperation.equals(last.toCharArray(), TypeConstants.PACKAGE_INFO_NAME)) {
				path = path.removeLastSegments(1); // the package-info file has changed so blame the package itself
				/* https://bugs.eclipse.org/bugs/show_bug.cgi?id=323785, in the case of default package,
				   there is no need to blame the package itself as there can be no annotations or documentation
				   comment tags in the package-info file that can influence the rest of the package. Just bail out
				   so we don't touch null objects below.
				 */
				if (path.isEmpty())
					return;
			}
	}

	if (isStructuralChange && !this.hasStructuralChanges) {
		this.newState.tagAsStructurallyChanged();
		this.hasStructuralChanges = true;
	}
	// the qualifiedStrings are of the form 'p1/p2' & the simpleStrings are just 'X'
	rootNames.add(path.segment(0));
	String packageName = path.removeLastSegments(1).toString();
	boolean wasNew = qualifiedNames.add(packageName);
	String typeName = path.lastSegment();
	int memberIndex = typeName.indexOf('$');
	if (memberIndex > 0)
		typeName = typeName.substring(0, memberIndex);
	wasNew = simpleNames.add(typeName) | wasNew;
	if (wasNew && JavaBuilder.DEBUG)
		System.out.println("  will look for dependents of " //$NON-NLS-1$
			+ typeName + " in " + packageName); //$NON-NLS-1$
}
 
Example #13
Source File: IncrementalImageBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void updateProblemsFor(SourceFile sourceFile, CompilationResult result) throws CoreException {
	if (CharOperation.equals(sourceFile.getMainTypeName(), TypeConstants.PACKAGE_INFO_NAME)) {
		IResource pkgResource = sourceFile.resource.getParent();
		pkgResource.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_ZERO);
	}
	IMarker[] markers = JavaBuilder.getProblemsFor(sourceFile.resource);
	CategorizedProblem[] problems = result.getProblems();
	if (problems == null && markers.length == 0) return;

	this.notifier.updateProblemCounts(markers, problems);
	JavaBuilder.removeProblemsFor(sourceFile.resource);
	storeProblemsFor(sourceFile, problems);
}
 
Example #14
Source File: BinaryMember.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected IAnnotation[] getStandardAnnotations(long tagBits) {
	if ((tagBits & TagBits.AllStandardAnnotationsMask) == 0)
		return Annotation.NO_ANNOTATIONS;
	ArrayList annotations = new ArrayList();

	if ((tagBits & TagBits.AnnotationTargetMASK) != 0) {
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_ANNOTATION_TARGET));
	}
	if ((tagBits & TagBits.AnnotationRetentionMASK) != 0) {
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_ANNOTATION_RETENTION));
	}
	if ((tagBits & TagBits.AnnotationDeprecated) != 0) {
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_DEPRECATED));
	}
	if ((tagBits & TagBits.AnnotationDocumented) != 0) {
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_ANNOTATION_DOCUMENTED));
	}
	if ((tagBits & TagBits.AnnotationInherited) != 0) {
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_ANNOTATION_INHERITED));
	}
	if ((tagBits & TagBits.AnnotationPolymorphicSignature) != 0) {
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_INVOKE_METHODHANDLE_$_POLYMORPHICSIGNATURE));
	}
	if ((tagBits & TagBits.AnnotationSafeVarargs) != 0) {
		annotations.add(getAnnotation(TypeConstants.JAVA_LANG_SAFEVARARGS));
	}
	// note that JAVA_LANG_SUPPRESSWARNINGS and JAVA_LANG_OVERRIDE cannot appear in binaries
	return (IAnnotation[]) annotations.toArray(new IAnnotation[annotations.size()]);
}
 
Example #15
Source File: SourceElementNotifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean hasDeprecatedAnnotation(Annotation[] annotations) {
	if (annotations != null) {
		for (int i = 0, length = annotations.length; i < length; i++) {
			Annotation annotation = annotations[i];
			if (CharOperation.equals(annotation.type.getLastToken(), TypeConstants.JAVA_LANG_DEPRECATED[2])) {
				return true;
			}
		}
	}
	return false;
}
 
Example #16
Source File: CodeSnippetScope.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public MethodBinding getConstructor(ReferenceBinding receiverType, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
	MethodBinding methodBinding = receiverType.getExactConstructor(argumentTypes);
	if (methodBinding != null) {
		if (canBeSeenByForCodeSnippet(methodBinding, receiverType, invocationSite, this)) {
			return methodBinding;
		}
	}
	MethodBinding[] methods = receiverType.getMethods(TypeConstants.INIT);
	if (methods == Binding.NO_METHODS) {
		return new ProblemMethodBinding(TypeConstants.INIT, argumentTypes, ProblemReasons.NotFound);
	}
	MethodBinding[] compatible = new MethodBinding[methods.length];
	int compatibleIndex = 0;
	for (int i = 0, length = methods.length; i < length; i++) {
	    MethodBinding compatibleMethod = computeCompatibleMethod(methods[i], argumentTypes, invocationSite, Scope.APPLICABILITY);
		if (compatibleMethod != null)
			compatible[compatibleIndex++] = compatibleMethod;
	}
	if (compatibleIndex == 0)
		return new ProblemMethodBinding(TypeConstants.INIT, argumentTypes, ProblemReasons.NotFound); // need a more descriptive error... cannot convert from X to Y

	MethodBinding[] visible = new MethodBinding[compatibleIndex];
	int visibleIndex = 0;
	for (int i = 0; i < compatibleIndex; i++) {
		MethodBinding method = compatible[i];
		if (canBeSeenByForCodeSnippet(method, receiverType, invocationSite, this)) {
			visible[visibleIndex++] = method;
		}
	}
	if (visibleIndex == 1) {
		// 1.8: Give inference a chance to perform outstanding tasks (18.5.2):
		return inferInvocationType(invocationSite, visible[0], argumentTypes);
	}
	if (visibleIndex == 0) {
		return new ProblemMethodBinding(compatible[0], TypeConstants.INIT, compatible[0].parameters, ProblemReasons.NotVisible);
	}
	return mostSpecificClassMethodBinding(visible, visibleIndex, invocationSite);
}
 
Example #17
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ReferenceBinding getTypeBinding() {

	if (this.classType != null || this.resolvedType == null)
		return null;
	
	class LambdaTypeBinding extends ReferenceBinding {
		public MethodBinding[] methods() {
			return new MethodBinding [] { getMethodBinding() };
		}
		public char[] sourceName() {
			return TypeConstants.LAMBDA_TYPE;
		}
		public ReferenceBinding superclass() {
			return LambdaExpression.this.scope.getJavaLangObject();
		}
		public ReferenceBinding[] superInterfaces() {
			return new ReferenceBinding[] { (ReferenceBinding) LambdaExpression.this.resolvedType };
		}
		@Override
		public char[] computeUniqueKey() {
			return LambdaExpression.this.descriptor.declaringClass.computeUniqueKey();
		}
		public String toString() {
			StringBuffer output = new StringBuffer("()->{} implements "); //$NON-NLS-1$
			output.append(LambdaExpression.this.descriptor.declaringClass.sourceName());
			output.append('.');
			output.append(LambdaExpression.this.descriptor.toString());
			return output.toString();
		}
	}
	return this.classType = new LambdaTypeBinding();
}
 
Example #18
Source File: CompilationUnitDeclaration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void createPackageInfoType() {
	TypeDeclaration declaration = new TypeDeclaration(this.compilationResult);
	declaration.name = TypeConstants.PACKAGE_INFO_NAME;
	declaration.modifiers = ClassFileConstants.AccDefault | ClassFileConstants.AccInterface;
	declaration.javadoc = this.javadoc;
	this.types[0] = declaration; // Assumes the first slot is meant for this type
}
 
Example #19
Source File: FakedTrackingVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private FakedTrackingVariable(BlockScope scope, ASTNode location, FlowInfo flowInfo, int nullStatus) {
	super(UNASSIGNED_CLOSEABLE_NAME, location.sourceStart, location.sourceEnd);
	this.type = new SingleTypeReference(
			TypeConstants.OBJECT,
			((long)this.sourceStart <<32)+this.sourceEnd);
	this.methodScope = scope.methodScope();
	this.originalBinding = null;
	resolve(scope);
	if (nullStatus != 0)
		flowInfo.markNullStatus(this.binding, nullStatus); // mark that this flow has seen the resource
}
 
Example #20
Source File: FakedTrackingVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isBlacklistedMethod(Expression expression) {
	if (expression instanceof MessageSend) {
		MethodBinding method = ((MessageSend) expression).binding;
		if (method != null && method.isValidBinding())
			// for all methods in java.nio.file.Files that return a resource (Stream) it really needs closing
			return CharOperation.equals(method.declaringClass.compoundName, TypeConstants.JAVA_NIO_FILE_FILES);
	}
	return false;
}
 
Example #21
Source File: EclipseHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static Annotation[] addSuppressWarningsAll(EclipseNode node, ASTNode source, Annotation[] originalAnnotationArray) {
	Annotation[] anns = addAnnotation(source, originalAnnotationArray, TypeConstants.JAVA_LANG_SUPPRESSWARNINGS, new StringLiteral(ALL, 0, 0, 0));
	
	if (Boolean.TRUE.equals(node.getAst().readConfiguration(ConfigurationKeys.ADD_FINDBUGS_SUPPRESSWARNINGS_ANNOTATIONS))) {
		MemberValuePair mvp = new MemberValuePair(JUSTIFICATION, 0, 0, new StringLiteral(GENERATED_CODE, 0, 0, 0));
		anns = addAnnotation(source, anns, EDU_UMD_CS_FINDBUGS_ANNOTATIONS_SUPPRESSFBWARNINGS, mvp);
	}
	
	return anns;
}
 
Example #22
Source File: BinaryIndexer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addBinaryRetentionAnnotation(long bits) {
	char[][] compoundName = TypeConstants.JAVA_LANG_ANNOTATION_RETENTIONPOLICY;
	addTypeReference(compoundName[compoundName.length-1]);
	if ((bits & TagBits.AnnotationRuntimeRetention) == TagBits.AnnotationRuntimeRetention) {
		addFieldReference(TypeConstants.UPPER_RUNTIME);
	} else if ((bits & TagBits.AnnotationClassRetention) != 0) {
		addFieldReference(TypeConstants.UPPER_CLASS);
	} else if ((bits & TagBits.AnnotationSourceRetention) != 0) {
		addFieldReference(TypeConstants.UPPER_SOURCE);
	}
}
 
Example #23
Source File: AbstractIndexer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void addAnnotationTypeDeclaration(int modifiers, char[] packageName, char[] name, char[][] enclosingTypeNames, boolean secondary) {
	addTypeDeclaration(modifiers, packageName, name, enclosingTypeNames, secondary);

	addIndexEntry(
		SUPER_REF,
		SuperTypeReferencePattern.createIndexKey(
			modifiers, packageName, name, enclosingTypeNames, null, ANNOTATION_TYPE_SUFFIX, CharOperation.concatWith(TypeConstants.JAVA_LANG_ANNOTATION_ANNOTATION, '.'), ANNOTATION_TYPE_SUFFIX));
}
 
Example #24
Source File: PackageElementImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected AnnotationBinding[] getAnnotationBindings()
{
	PackageBinding packageBinding = (PackageBinding) this._binding;
	char[][] compoundName = CharOperation.arrayConcat(packageBinding.compoundName, TypeConstants.PACKAGE_INFO_NAME);
	ReferenceBinding type = this._env.getLookupEnvironment().getType(compoundName);
	AnnotationBinding[] annotations = null;
	if (type != null && type.isValidBinding()) {
		annotations = type.getAnnotations();
	}
	return annotations;
}
 
Example #25
Source File: HandleSynchronized.java    From EasyMPermission with MIT License 5 votes vote down vote up
public char[] createLockField(AnnotationValues<Synchronized> annotation, EclipseNode annotationNode, boolean isStatic, boolean reportErrors) {
	char[] lockName = annotation.getInstance().value().toCharArray();
	Annotation source = (Annotation) annotationNode.get();
	boolean autoMake = false;
	if (lockName.length == 0) {
		autoMake = true;
		lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME;
	}
	
	if (fieldExists(new String(lockName), annotationNode) == MemberExistsResult.NOT_EXISTS) {
		if (!autoMake) {
			if (reportErrors) annotationNode.addError(String.format("The field %s does not exist.", new String(lockName)));
			return null;
		}
		FieldDeclaration fieldDecl = new FieldDeclaration(lockName, 0, -1);
		setGeneratedBy(fieldDecl, source);
		fieldDecl.declarationSourceEnd = -1;
		
		fieldDecl.modifiers = (isStatic ? Modifier.STATIC : 0) | Modifier.FINAL | Modifier.PRIVATE;
		
		//We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable!
		ArrayAllocationExpression arrayAlloc = new ArrayAllocationExpression();
		setGeneratedBy(arrayAlloc, source);
		arrayAlloc.dimensions = new Expression[] { makeIntLiteral("0".toCharArray(), source) };
		arrayAlloc.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { 0, 0, 0 });
		setGeneratedBy(arrayAlloc.type, source);
		fieldDecl.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, new long[] { 0, 0, 0 });
		setGeneratedBy(fieldDecl.type, source);
		fieldDecl.initialization = arrayAlloc;
		// TODO temporary workaround for issue 217. http://code.google.com/p/projectlombok/issues/detail?id=217
		// injectFieldSuppressWarnings(annotationNode.up().up(), fieldDecl);
		injectField(annotationNode.up().up(), fieldDecl);
	}
	
	return lockName;
}
 
Example #26
Source File: EclipseGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generatePluralMethod(TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) {
	boolean mapMode = isMap();
	
	MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
	md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	md.modifiers = ClassFileConstants.AccPublic;
	
	List<Statement> statements = new ArrayList<Statement>();
	statements.add(createConstructBuilderVarIfNeeded(data, builderType));
	
	FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L);
	thisDotField.receiver = new ThisReference(0, 0);
	MessageSend thisDotFieldDotAddAll = new MessageSend();
	thisDotFieldDotAddAll.arguments = new Expression[] {new SingleNameReference(data.getPluralName(), 0L)};
	thisDotFieldDotAddAll.receiver = thisDotField;
	thisDotFieldDotAddAll.selector = (mapMode ? "putAll" : "addAll").toCharArray();
	statements.add(thisDotFieldDotAddAll);
	if (returnStatement != null) statements.add(returnStatement);
	
	md.statements = statements.toArray(new Statement[statements.size()]);
	
	TypeReference paramType;
	if (mapMode) {
		paramType = new QualifiedTypeReference(JAVA_UTIL_MAP, NULL_POSS);
		paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs());
	} else {
		paramType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_ITERABLE, NULL_POSS);
		paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs());
	}
	Argument param = new Argument(data.getPluralName(), 0, paramType, 0);
	md.arguments = new Argument[] {param};
	md.returnType = returnType;
	md.selector = fluent ? data.getPluralName() : HandlerUtil.buildAccessorName(mapMode ? "putAll" : "addAll", new String(data.getPluralName())).toCharArray();
	
	data.setGeneratedByRecursive(md);
	injectMethod(builderType, md);
}
 
Example #27
Source File: EclipseJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generatePluralMethod(TypeReference returnType, Statement returnStatement, SingularData data, EclipseNode builderType, boolean fluent) {
	MethodDeclaration md = new MethodDeclaration(((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
	md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
	md.modifiers = ClassFileConstants.AccPublic;
	
	List<Statement> statements = new ArrayList<Statement>();
	statements.add(createConstructBuilderVarIfNeeded(data, builderType, false));
	
	FieldReference thisDotField = new FieldReference(data.getPluralName(), 0L);
	thisDotField.receiver = new ThisReference(0, 0);
	MessageSend thisDotFieldDotAddAll = new MessageSend();
	thisDotFieldDotAddAll.arguments = new Expression[] {new SingleNameReference(data.getPluralName(), 0L)};
	thisDotFieldDotAddAll.receiver = thisDotField;
	thisDotFieldDotAddAll.selector = "addAll".toCharArray();
	statements.add(thisDotFieldDotAddAll);
	if (returnStatement != null) statements.add(returnStatement);
	
	md.statements = statements.toArray(new Statement[statements.size()]);
	
	TypeReference paramType = new QualifiedTypeReference(TypeConstants.JAVA_UTIL_COLLECTION, NULL_POSS);
	paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs());
	Argument param = new Argument(data.getPluralName(), 0, paramType, 0);
	md.arguments = new Argument[] {param};
	md.returnType = returnType;
	md.selector = fluent ? data.getPluralName() : HandlerUtil.buildAccessorName("addAll", new String(data.getPluralName())).toCharArray();
	
	data.setGeneratedByRecursive(md);
	injectMethod(builderType, md);
}
 
Example #28
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 #29
Source File: PackageBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public IAnnotationBinding[] getAnnotations() {
	try {
		INameEnvironment nameEnvironment = this.binding.environment.nameEnvironment;
		if (!(nameEnvironment instanceof SearchableEnvironment))
			return AnnotationBinding.NoAnnotations;
		NameLookup nameLookup = ((SearchableEnvironment) nameEnvironment).nameLookup;
		if (nameLookup == null)
			return AnnotationBinding.NoAnnotations;
		final String pkgName = getName();
		IPackageFragment[] pkgs = nameLookup.findPackageFragments(pkgName, false/*exact match*/);
		if (pkgs == null)
			return AnnotationBinding.NoAnnotations;

		for (int i = 0, len = pkgs.length; i < len; i++) {
			int fragType = pkgs[i].getKind();
			switch(fragType) {
				case IPackageFragmentRoot.K_SOURCE:
					String unitName = "package-info.java"; //$NON-NLS-1$
					ICompilationUnit unit = pkgs[i].getCompilationUnit(unitName);
					if (unit != null && unit.exists()) {
						ASTParser p = ASTParser.newParser(AST.JLS3_INTERNAL);
						p.setSource(unit);
						p.setResolveBindings(true);
						p.setUnitName(unitName);
						p.setFocalPosition(0);
						p.setKind(ASTParser.K_COMPILATION_UNIT);
						CompilationUnit domUnit = (CompilationUnit) p.createAST(null);
						PackageDeclaration pkgDecl = domUnit.getPackage();
						if (pkgDecl != null) {
							List annos = pkgDecl.annotations();
							if (annos == null || annos.isEmpty())
								return AnnotationBinding.NoAnnotations;
							IAnnotationBinding[] result = new IAnnotationBinding[annos.size()];
							int index=0;
	 						for (Iterator it = annos.iterator(); it.hasNext(); index++) {
								result[index] = ((Annotation) it.next()).resolveAnnotationBinding();
								// not resolving bindings
								if (result[index] == null)
									return AnnotationBinding.NoAnnotations;
							}
							return result;
						}
					}
					break;
				case IPackageFragmentRoot.K_BINARY:
					NameEnvironmentAnswer answer =
						nameEnvironment.findType(TypeConstants.PACKAGE_INFO_NAME, this.binding.compoundName);
					if (answer != null && answer.isBinaryType()) {
						IBinaryType type = answer.getBinaryType();
						char[][][] missingTypeNames = type.getMissingTypeNames();
						IBinaryAnnotation[] binaryAnnotations = type.getAnnotations();
						org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding[] binaryInstances =
							BinaryTypeBinding.createAnnotations(binaryAnnotations, this.binding.environment, missingTypeNames);
						org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding[] allInstances =
							org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding.addStandardAnnotations(binaryInstances, type.getTagBits(), this.binding.environment);
						int total = allInstances.length;
						IAnnotationBinding[] domInstances = new AnnotationBinding[total];
						for (int a = 0; a < total; a++) {
							final IAnnotationBinding annotationInstance = this.resolver.getAnnotationInstance(allInstances[a]);
							if (annotationInstance == null) {// not resolving binding
								return AnnotationBinding.NoAnnotations;
							}
							domInstances[a] = annotationInstance;
						}
						return domInstances;
					}
			}
		}
	} catch(JavaModelException e) {
		return AnnotationBinding.NoAnnotations;
	}
	return AnnotationBinding.NoAnnotations;
}
 
Example #30
Source File: MessageSend.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private int detectAssertionUtility(int argumentIdx) {
	TypeBinding[] parameters = this.binding.original().parameters;
	if (argumentIdx < parameters.length) {
		TypeBinding parameterType = parameters[argumentIdx];
		if (this.actualReceiverType != null && parameterType != null) {
			switch (this.actualReceiverType.id) {
				case TypeIds.T_OrgEclipseCoreRuntimeAssert:
					if (parameterType.id == TypeIds.T_boolean)
						return TRUE_ASSERTION;
					if (parameterType.id == TypeIds.T_JavaLangObject && CharOperation.equals(TypeConstants.IS_NOTNULL, this.selector))
						return NONNULL_ASSERTION;
					break;
				case TypeIds.T_JunitFrameworkAssert:
				case TypeIds.T_OrgJunitAssert:
					if (parameterType.id == TypeIds.T_boolean) {
						if (CharOperation.equals(TypeConstants.ASSERT_TRUE, this.selector))
							return TRUE_ASSERTION;
						if (CharOperation.equals(TypeConstants.ASSERT_FALSE, this.selector))
							return FALSE_ASSERTION;
					} else if (parameterType.id == TypeIds.T_JavaLangObject) {
						if (CharOperation.equals(TypeConstants.ASSERT_NOTNULL, this.selector))
							return NONNULL_ASSERTION;
						if (CharOperation.equals(TypeConstants.ASSERT_NULL, this.selector))
							return NULL_ASSERTION;
					}
					break;
				case TypeIds.T_OrgApacheCommonsLangValidate:
					if (parameterType.id == TypeIds.T_boolean) {
						if (CharOperation.equals(TypeConstants.IS_TRUE, this.selector))
							return TRUE_ASSERTION;
					} else if (parameterType.id == TypeIds.T_JavaLangObject) {
						if (CharOperation.equals(TypeConstants.NOT_NULL, this.selector))
							return NONNULL_ASSERTION;
					}
					break;
				case TypeIds.T_OrgApacheCommonsLang3Validate:
					if (parameterType.id == TypeIds.T_boolean) {
						if (CharOperation.equals(TypeConstants.IS_TRUE, this.selector))
							return TRUE_ASSERTION;
					} else if (parameterType.isTypeVariable()) {
						if (CharOperation.equals(TypeConstants.NOT_NULL, this.selector))
							return NONNULL_ASSERTION;
					}
					break;
				case TypeIds.T_ComGoogleCommonBasePreconditions:
					if (parameterType.id == TypeIds.T_boolean) {
						if (CharOperation.equals(TypeConstants.CHECK_ARGUMENT, this.selector)
							|| CharOperation.equals(TypeConstants.CHECK_STATE, this.selector))
							return TRUE_ASSERTION;
					} else if (parameterType.isTypeVariable()) {
						if (CharOperation.equals(TypeConstants.CHECK_NOT_NULL, this.selector))
							return NONNULL_ASSERTION;
					}
					break;					
				case TypeIds.T_JavaUtilObjects:
					if (parameterType.isTypeVariable()) {
						if (CharOperation.equals(TypeConstants.REQUIRE_NON_NULL, this.selector))
							return NONNULL_ASSERTION;
					}
					break;					
			}
		}
	}
	return 0;
}