org.eclipse.jdt.internal.compiler.impl.CompilerOptions Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.impl.CompilerOptions. 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: InMemoryJavaCompiler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * sets the compliance level (see @link(org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants))
 */
private void setComplianceLevel(final long jdkVersion) {
  try {
    this.compilerOptions.complianceLevel = jdkVersion;
    try {
      CompilerOptions.class.getField("originalComplianceLevel").setLong(this.compilerOptions, jdkVersion);
    } catch (final Throwable _t) {
      if (_t instanceof NoSuchFieldException) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #2
Source File: InMemoryJavaCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * sets the source level (see @link(org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants))
 */
private void setSourceLevel(final long jdkVersion) {
  try {
    this.compilerOptions.sourceLevel = jdkVersion;
    try {
      CompilerOptions.class.getField("originalSourceLevel").setLong(this.compilerOptions, jdkVersion);
    } catch (final Throwable _t) {
      if (_t instanceof NoSuchFieldException) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #3
Source File: InMemoryJavaCompiler.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * sets the compliance level (see @link(org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants))
 */
private void setComplianceLevel(final long jdkVersion) {
  try {
    this.compilerOptions.complianceLevel = jdkVersion;
    try {
      CompilerOptions.class.getField("originalComplianceLevel").setLong(this.compilerOptions, jdkVersion);
    } catch (final Throwable _t) {
      if (_t instanceof NoSuchFieldException) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #4
Source File: ArrayInitializer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {

		if (this.expressions != null) {
			CompilerOptions compilerOptions = currentScope.compilerOptions();
			boolean analyseResources = compilerOptions.analyseResourceLeaks;
			boolean evalNullTypeAnnotations = compilerOptions.sourceLevel >= ClassFileConstants.JDK1_8 
												&& compilerOptions.isAnnotationBasedNullAnalysisEnabled;
			for (int i = 0, max = this.expressions.length; i < max; i++) {
				flowInfo = this.expressions[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits();

				if (analyseResources && FakedTrackingVariable.isAnyCloseable(this.expressions[i].resolvedType)) {
					flowInfo = FakedTrackingVariable.markPassedToOutside(currentScope, this.expressions[i], flowInfo, flowContext, false);
				}
				if (evalNullTypeAnnotations) {
					checkAgainstNullTypeAnnotation(currentScope, this.binding.elementsType(), this.expressions[i], flowContext, flowInfo);
				}
			}
		}
		return flowInfo;
	}
 
Example #5
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean filterEnum(SearchMatch match) {
	
	// filter org.apache.commons.lang.enum package for projects above 1.5 
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=317264	
	IJavaElement element = (IJavaElement)match.getElement();
	PackageFragment pkg = (PackageFragment)element.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
	if (pkg != null) {
		// enum was found in org.apache.commons.lang.enum at index 5
		if (pkg.names.length == 5 && pkg.names[4].equals("enum")) {  //$NON-NLS-1$
			if (this.options == null) {
				IJavaProject proj = (IJavaProject)pkg.getAncestor(IJavaElement.JAVA_PROJECT);
				String complianceStr = proj.getOption(CompilerOptions.OPTION_Source, true);
				if (CompilerOptions.versionToJdkLevel(complianceStr) >= ClassFileConstants.JDK1_5)
					return true;
			} else if (this.options.sourceLevel >= ClassFileConstants.JDK1_5) {
				return true;
			}
		}
	}
	return false;
}
 
Example #6
Source File: LookupEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public LookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions globalOptions, ProblemReporter problemReporter, INameEnvironment nameEnvironment) {
	this.typeRequestor = typeRequestor;
	this.globalOptions = globalOptions;
	this.problemReporter = problemReporter;
	this.defaultPackage = new PackageBinding(this); // assume the default package always exists
	this.defaultImports = null;
	this.nameEnvironment = nameEnvironment;
	this.knownPackages = new HashtableOfPackage();
	this.uniqueParameterizedGenericMethodBindings = new SimpleLookupTable(3);
	this.uniquePolymorphicMethodBindings = new SimpleLookupTable(3);
	this.missingTypes = null;
	this.accessRestrictions = new HashMap(3);
	this.classFilePool = ClassFilePool.newInstance();
	this.typesBeingConnected = new HashSet();
	this.typeSystem = this.globalOptions.sourceLevel >= ClassFileConstants.JDK1_8 && this.globalOptions.storeAnnotations ? new AnnotatableTypeSystem(this) : new TypeSystem(this);
}
 
Example #7
Source File: MethodBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Compute the tagbits for standard annotations. For source types, these could require
 * lazily resolving corresponding annotation nodes, in case of forward references.
 * @see org.eclipse.jdt.internal.compiler.lookup.Binding#getAnnotationTagBits()
 */
public long getAnnotationTagBits() {
	MethodBinding originalMethod = original();
	if ((originalMethod.tagBits & TagBits.AnnotationResolved) == 0 && originalMethod.declaringClass instanceof SourceTypeBinding) {
		ClassScope scope = ((SourceTypeBinding) originalMethod.declaringClass).scope;
		if (scope != null) {
			TypeDeclaration typeDecl = scope.referenceContext;
			AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(originalMethod);
			if (methodDecl != null)
				ASTNode.resolveAnnotations(methodDecl.scope, methodDecl.annotations, originalMethod);
			CompilerOptions options = scope.compilerOptions();
			if (options.isAnnotationBasedNullAnalysisEnabled) {
				boolean isJdk18 = options.sourceLevel >= ClassFileConstants.JDK1_8;
				long nullDefaultBits = isJdk18 ? this.defaultNullness
						: this.tagBits & (TagBits.AnnotationNonNullByDefault|TagBits.AnnotationNullUnspecifiedByDefault);
				if (nullDefaultBits != 0 && this.declaringClass instanceof SourceTypeBinding) {
					SourceTypeBinding declaringSourceType = (SourceTypeBinding) this.declaringClass;
					if (declaringSourceType.checkRedundantNullnessDefaultOne(methodDecl, methodDecl.annotations, nullDefaultBits, isJdk18)) {
						declaringSourceType.checkRedundantNullnessDefaultRecurse(methodDecl, methodDecl.annotations, nullDefaultBits, isJdk18);
					}
				}
			}
		}
	}
	return originalMethod.tagBits;
}
 
Example #8
Source File: CastExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Only complain for identity cast, since other type of casts may be useful: e.g.  ~((~(long) 0) << 32)  is different from: ~((~0) << 32)
 */
public static void checkNeedForArgumentCast(BlockScope scope, int operator, int operatorSignature, Expression expression, int expressionTypeId) {
	if (scope.compilerOptions().getSeverity(CompilerOptions.UnnecessaryTypeCheck) == ProblemSeverities.Ignore) return;

	// check need for left operand cast
	if ((expression.bits & ASTNode.UnnecessaryCast) == 0 && expression.resolvedType.isBaseType()) {
		// narrowing conversion on base type may change value, thus necessary
		return;
	} else {
		TypeBinding alternateLeftType = ((CastExpression)expression).expression.resolvedType;
		if (alternateLeftType == null) return; // cannot do better
		if (alternateLeftType.id == expressionTypeId) { // obvious identity cast
			scope.problemReporter().unnecessaryCast((CastExpression)expression);
			return;
		}
	}
}
 
Example #9
Source File: InMemoryJavaCompiler.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * sets the source level (see @link(org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants))
 */
private void setSourceLevel(final long jdkVersion) {
  try {
    this.compilerOptions.sourceLevel = jdkVersion;
    try {
      CompilerOptions.class.getField("originalSourceLevel").setLong(this.compilerOptions, jdkVersion);
    } catch (final Throwable _t) {
      if (_t instanceof NoSuchFieldException) {
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #10
Source File: AppCompiler.java    From actframework with Apache License 2.0 6 votes vote down vote up
private void configureCompilerOptions() {
    Map<String, String> map = new HashMap<>();
    opt(map, OPTION_ReportMissingSerialVersion, IGNORE);
    opt(map, OPTION_LineNumberAttribute, GENERATE);
    opt(map, OPTION_SourceFileAttribute, GENERATE);
    opt(map, OPTION_LocalVariableAttribute, GENERATE);
    opt(map, OPTION_PreserveUnusedLocal, PRESERVE);
    opt(map, OPTION_ReportDeprecation, IGNORE);
    opt(map, OPTION_ReportUnusedImport, IGNORE);
    opt(map, OPTION_Encoding, "UTF-8");
    opt(map, OPTION_Process_Annotations, ENABLED);
    opt(map, OPTION_Source, conf.sourceVersion());
    opt(map, OPTION_TargetPlatform, conf.targetVersion());
    opt(map, OPTION_Compliance, conf.sourceVersion());
    opt(map, OPTION_MethodParametersAttribute, GENERATE);
    compilerOptions = new CompilerOptions(map);
}
 
Example #11
Source File: SourceTypeBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void createArgumentBindings(MethodBinding method, CompilerOptions compilerOptions) {
	
	if (!isPrototype()) throw new IllegalStateException();
	if (compilerOptions.isAnnotationBasedNullAnalysisEnabled)
		getNullDefault(); // ensure initialized
	AbstractMethodDeclaration methodDecl = method.sourceMethod();
	if (methodDecl != null) {
		// while creating argument bindings we also collect explicit null annotations:
		if (method.parameters != Binding.NO_PARAMETERS)
			methodDecl.createArgumentBindings();
		// add implicit annotations (inherited(?) & default):
		if (compilerOptions.isAnnotationBasedNullAnalysisEnabled) {
			new ImplicitNullAnnotationVerifier(this.scope.environment()).checkImplicitNullAnnotations(method, methodDecl, true, this.scope);
		}
	}
}
 
Example #12
Source File: CastExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Complain if assigned expression is cast, but not actually used as such, e.g. Object o = (List) object;
 */
public static void checkNeedForAssignedCast(BlockScope scope, TypeBinding expectedType, CastExpression rhs) {
	CompilerOptions compilerOptions = scope.compilerOptions();
	if (compilerOptions.getSeverity(CompilerOptions.UnnecessaryTypeCheck) == ProblemSeverities.Ignore) return;

	TypeBinding castedExpressionType = rhs.expression.resolvedType;
	//	int i = (byte) n; // cast still had side effect
	// double d = (float) n; // cast to float is unnecessary
	if (castedExpressionType == null || rhs.resolvedType.isBaseType()) return;
	//if (castedExpressionType.id == T_null) return; // tolerate null expression cast
	if (castedExpressionType.isCompatibleWith(expectedType, scope)) {
		if (compilerOptions.isAnnotationBasedNullAnalysisEnabled && compilerOptions.sourceLevel >= ClassFileConstants.JDK1_8) {
			// are null annotations compatible, too?
			if (NullAnnotationMatching.analyse(expectedType, castedExpressionType, -1).isAnyMismatch())
				return; // already reported unchecked cast (nullness), say no more.
		}
		scope.problemReporter().unnecessaryCast(rhs);
	}
}
 
Example #13
Source File: CastExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Casting an enclosing instance will considered as useful if removing it would actually bind to a different type
 */
public static void checkNeedForEnclosingInstanceCast(BlockScope scope, Expression enclosingInstance, TypeBinding enclosingInstanceType, TypeBinding memberType) {
	if (scope.compilerOptions().getSeverity(CompilerOptions.UnnecessaryTypeCheck) == ProblemSeverities.Ignore) return;

	TypeBinding castedExpressionType = ((CastExpression)enclosingInstance).expression.resolvedType;
	if (castedExpressionType == null) return; // cannot do better
	// obvious identity cast
	if (TypeBinding.equalsEquals(castedExpressionType, enclosingInstanceType)) {
		scope.problemReporter().unnecessaryCast((CastExpression)enclosingInstance);
	} else if (castedExpressionType == TypeBinding.NULL){
		return; // tolerate null enclosing instance cast
	} else {
		TypeBinding alternateEnclosingInstanceType = castedExpressionType;
		if (castedExpressionType.isBaseType() || castedExpressionType.isArrayType()) return; // error case
		if (TypeBinding.equalsEquals(memberType, scope.getMemberType(memberType.sourceName(), (ReferenceBinding) alternateEnclosingInstanceType))) {
			scope.problemReporter().unnecessaryCast((CastExpression)enclosingInstance);
		}
	}
}
 
Example #14
Source File: RunTestsViaEcj.java    From EasyMPermission with MIT License 6 votes vote down vote up
protected CompilerOptions ecjCompilerOptions() {
	CompilerOptions options = new CompilerOptions();
	options.complianceLevel = Eclipse.getLatestEcjCompilerVersionConstant();
	options.sourceLevel = Eclipse.getLatestEcjCompilerVersionConstant();
	options.targetJDK = Eclipse.getLatestEcjCompilerVersionConstant();
	options.docCommentSupport = false;
	options.parseLiteralExpressionsAsConstants = true;
	options.inlineJsrBytecode = true;
	options.reportUnusedDeclaredThrownExceptionExemptExceptionAndThrowable = false;
	options.reportUnusedDeclaredThrownExceptionIncludeDocCommentReference = false;
	options.reportUnusedDeclaredThrownExceptionWhenOverriding = false;
	options.reportUnusedParameterIncludeDocCommentReference = false;
	options.reportUnusedParameterWhenImplementingAbstract = false;
	options.reportUnusedParameterWhenOverridingConcrete = false;
	options.reportDeadCodeInTrivialIfStatement = false;
	options.generateClassFiles = false;
	Map<String, String> warnings = new HashMap<String, String>();
	warnings.put(CompilerOptions.OPTION_ReportUnusedLocal, "ignore");
	warnings.put(CompilerOptions.OPTION_ReportUnusedLabel, "ignore");
	warnings.put(CompilerOptions.OPTION_ReportUnusedImport, "ignore");
	warnings.put(CompilerOptions.OPTION_ReportUnusedPrivateMember, "ignore");
	warnings.put(CompilerOptions.OPTION_Source, "1." + Eclipse.getEcjCompilerVersion());
	options.set(warnings);
	return options;
}
 
Example #15
Source File: Main.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void disableAll(int severity) {
	String checkedValue = null;
	switch(severity) {
		case ProblemSeverities.Error :
			checkedValue = CompilerOptions.ERROR;
			break;
		case ProblemSeverities.Warning :
			checkedValue = CompilerOptions.WARNING;
			break;
	}
	Object[] entries = this.options.entrySet().toArray();
	for (int i = 0, max = entries.length; i < max; i++) {
		Map.Entry entry = (Map.Entry) entries[i];
		if (!(entry.getKey() instanceof String))
			continue;
		if (!(entry.getValue() instanceof String))
			continue;
		if (((String) entry.getValue()).equals(checkedValue)) {
			this.options.put(entry.getKey(), CompilerOptions.IGNORE);
		}
	}
}
 
Example #16
Source File: CodeSnippetEvaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private CodeSnippetToCuMapper getMapper() {
	if (this.mapper == null) {
		char[] varClassName = null;
		VariablesInfo installedVars = this.context.installedVars;
		if (installedVars != null) {
			char[] superPackageName = installedVars.packageName;
			if (superPackageName != null && superPackageName.length != 0) {
				varClassName = CharOperation.concat(superPackageName, installedVars.className, '.');
			} else {
				varClassName = installedVars.className;
			}

		}
		this.mapper = new CodeSnippetToCuMapper(
			this.codeSnippet,
			this.context.packageName,
			this.context.imports,
			getClassName(),
			varClassName,
			this.context.localVariableNames,
			this.context.localVariableTypeNames,
			this.context.localVariableModifiers,
			this.context.declaringTypeName,
			this.context.lineSeparator,
			CompilerOptions.versionToJdkLevel(this.options.get(JavaCore.COMPILER_COMPLIANCE))
		);

	}
	return this.mapper;
}
 
Example #17
Source File: ReferenceBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void appendNullAnnotation(StringBuffer nameBuffer, CompilerOptions options) {
	if (options.isAnnotationBasedNullAnalysisEnabled) {
		// restore applied null annotation from tagBits:
	    if ((this.tagBits & TagBits.AnnotationNonNull) != 0) {
	    	char[][] nonNullAnnotationName = options.nonNullAnnotationName;
			nameBuffer.append('@').append(nonNullAnnotationName[nonNullAnnotationName.length-1]).append(' ');
	    }
	    if ((this.tagBits & TagBits.AnnotationNullable) != 0) {
	    	char[][] nullableAnnotationName = options.nullableAnnotationName;
			nameBuffer.append('@').append(nullableAnnotationName[nullableAnnotationName.length-1]).append(' ');
	    }
	}
}
 
Example #18
Source File: CompilationUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
private static CompilerOptions getDefaultCompilerOptions() {
    CompilerOptions options = new CompilerOptions();
    options.docCommentSupport = true;
    options.complianceLevel = ClassFileConstants.JDK1_7;
    options.sourceLevel = ClassFileConstants.JDK1_7;
    options.targetJDK = ClassFileConstants.JDK1_7;
    return options;
}
 
Example #19
Source File: InternalNamingConventions.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Scanner getNameScanner(CompilerOptions compilerOptions) {
	return
		new Scanner(
			false /*comment*/,
			false /*whitespace*/,
			false /*nls*/,
			compilerOptions.sourceLevel /*sourceLevel*/,
			null /*taskTags*/,
			null/*taskPriorities*/,
			true/*taskCaseSensitive*/);
}
 
Example #20
Source File: CompilationUnitProblemFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static CompilerOptions getCompilerOptions(Map settings, boolean creatingAST, boolean statementsRecovery) {
	CompilerOptions compilerOptions = new CompilerOptions(settings);
	compilerOptions.performMethodsFullRecovery = statementsRecovery;
	compilerOptions.performStatementsRecovery = statementsRecovery;
	compilerOptions.parseLiteralExpressionsAsConstants = !creatingAST; /*parse literal expressions as constants only if not creating a DOM AST*/
	if (creatingAST)
		compilerOptions.storeAnnotations = true; /* store annotations in the bindings if creating a DOM AST */
	return compilerOptions;
}
 
Example #21
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ASTNode[] parseClassBodyDeclarations(
		char[] source,
		int offset,
		int length,
		Map settings,
		boolean recordParsingInformation,
		boolean enabledStatementRecovery) {
	if (source == null) {
		throw new IllegalArgumentException();
	}
	CompilerOptions compilerOptions = new CompilerOptions(settings);
	compilerOptions.ignoreMethodBodies = this.ignoreMethodBodies;
	final ProblemReporter problemReporter = new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				compilerOptions,
				new DefaultProblemFactory(Locale.getDefault()));

	CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);
	parser.setMethodsFullRecovery(false);
	parser.setStatementsRecovery(enabledStatementRecovery);

	ICompilationUnit sourceUnit =
		new CompilationUnit(
			source,
			"", //$NON-NLS-1$
			compilerOptions.defaultEncoding);

	CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
	final CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length);
	ASTNode[] result = parser.parseClassBodyDeclarations(source, offset, length, compilationUnitDeclaration);

	if (recordParsingInformation) {
		this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments);
	}
	return result;
}
 
Example #22
Source File: SortElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Method processElement.
 * @param unit
 * @param source
 */
private String processElement(ICompilationUnit unit, char[] source) {
	Document document = new Document(new String(source));
	CompilerOptions options = new CompilerOptions(unit.getJavaProject().getOptions(true));
	ASTParser parser = ASTParser.newParser(this.apiLevel);
	parser.setCompilerOptions(options.getMap());
	parser.setSource(source);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setResolveBindings(false);
	org.eclipse.jdt.core.dom.CompilationUnit ast = (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(null);

	ASTRewrite rewriter= sortCompilationUnit(ast, null);
	if (rewriter == null)
		return document.get();

	TextEdit edits = rewriter.rewriteAST(document, unit.getJavaProject().getOptions(true));

	RangeMarker[] markers = null;
	if (this.positions != null) {
		markers = new RangeMarker[this.positions.length];
		for (int i = 0, max = this.positions.length; i < max; i++) {
			markers[i]= new RangeMarker(this.positions[i], 0);
			insert(edits, markers[i]);
		}
	}
	try {
		edits.apply(document, TextEdit.UPDATE_REGIONS);
		if (this.positions != null) {
			for (int i= 0, max = markers.length; i < max; i++) {
				this.positions[i]= markers[i].getOffset();
			}
		}
	} catch (BadLocationException e) {
		// ignore
	}
	return document.get();
}
 
Example #23
Source File: QualifiedAllocationExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public TypeBinding resolveType(BlockScope scope) {
	// added for code assist...cannot occur with 'normal' code
	if (this.anonymousType == null && this.enclosingInstance == null) {
		return super.resolveType(scope);
	}
	TypeBinding result=resolveTypeForQualifiedAllocationExpression(scope);
	if(result != null && this.binding != null) {
		final CompilerOptions compilerOptions = scope.compilerOptions();
		if (compilerOptions.isAnnotationBasedNullAnalysisEnabled && (this.binding.tagBits & TagBits.IsNullnessKnown) == 0) {
			new ImplicitNullAnnotationVerifier(scope.environment(), compilerOptions.inheritNullAnnotations)
					.checkImplicitNullAnnotations(this.binding, null/*srcMethod*/, false, scope);
		}
	}
	return result;
}
 
Example #24
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static CompilerOptions getCompilerOptions(Map options, boolean statementsRecovery) {
	CompilerOptions compilerOptions = new CompilerOptions(options);
	compilerOptions.performMethodsFullRecovery = statementsRecovery;
	compilerOptions.performStatementsRecovery = statementsRecovery;
	compilerOptions.parseLiteralExpressionsAsConstants = false;
	compilerOptions.storeAnnotations = true /*store annotations in the bindings*/;
	compilerOptions.ignoreSourceFolderWarningOption = true;
	return compilerOptions;
}
 
Example #25
Source File: CompilationUnitProblemFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add additional source types
 */
public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {
	// ensure to jump back to toplevel type for first one (could be a member)
	while (sourceTypes[0].getEnclosingType() != null) {
		sourceTypes[0] = sourceTypes[0].getEnclosingType();
	}

	CompilationResult result =
		new CompilationResult(sourceTypes[0].getFileName(), 1, 1, this.options.maxProblemsPerUnit);
	
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=305259, build the compilation unit in its own sand box.
	final long savedComplianceLevel = this.options.complianceLevel;
	final long savedSourceLevel = this.options.sourceLevel;
	
	try {
		IJavaProject project = ((SourceTypeElementInfo) sourceTypes[0]).getHandle().getJavaProject();
		this.options.complianceLevel = CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
		this.options.sourceLevel = CompilerOptions.versionToJdkLevel(project.getOption(JavaCore.COMPILER_SOURCE, true));

		// need to hold onto this
		CompilationUnitDeclaration unit =
			SourceTypeConverter.buildCompilationUnit(
					sourceTypes,//sourceTypes[0] is always toplevel here
					SourceTypeConverter.FIELD_AND_METHOD // need field and methods
					| SourceTypeConverter.MEMBER_TYPE // need member types
					| SourceTypeConverter.FIELD_INITIALIZATION, // need field initialization
					this.lookupEnvironment.problemReporter,
					result);

		if (unit != null) {
			this.lookupEnvironment.buildTypeBindings(unit, accessRestriction);
			this.lookupEnvironment.completeTypeBindings(unit);
		}
	} finally {
		this.options.complianceLevel = savedComplianceLevel;
		this.options.sourceLevel = savedSourceLevel;
	}
}
 
Example #26
Source File: TypeReference.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/** Check all typeArguments against null constraints on their corresponding type variables. */
protected void checkNullConstraints(Scope scope, TypeReference[] typeArguments) {
	CompilerOptions compilerOptions = scope.compilerOptions();
	if (compilerOptions.isAnnotationBasedNullAnalysisEnabled
			&& compilerOptions.sourceLevel >= ClassFileConstants.JDK1_8
			&& typeArguments != null)
	{
		TypeVariableBinding[] typeVariables = this.resolvedType.original().typeVariables();
		for (int i = 0; i < typeArguments.length; i++) {
			TypeReference arg = typeArguments[i];
			if (arg.resolvedType != null && arg.resolvedType.hasNullTypeAnnotations())
				arg.checkNullConstraints(scope, typeVariables, i);
		}
	}
}
 
Example #27
Source File: SourceIndexer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void resolveDocument() {
	try {
		IPath path = new Path(this.document.getPath());
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0));
		JavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
		JavaProject javaProject = (JavaProject) model.getJavaProject(project);

		this.options = new CompilerOptions(javaProject.getOptions(true));
		ProblemReporter problemReporter =
				new ProblemReporter(
						DefaultErrorHandlingPolicies.proceedWithAllProblems(),
						this.options,
						new DefaultProblemFactory());

		// Re-parse using normal parser, IndexingParser swallows several nodes, see comment above class.
		this.basicParser = new Parser(problemReporter, false);
		this.basicParser.reportOnlyOneSyntaxError = true;
		this.basicParser.scanner.taskTags = null;
		this.cud = this.basicParser.parse(this.compilationUnit, new CompilationResult(this.compilationUnit, 0, 0, this.options.maxProblemsPerUnit));

		// Use a non model name environment to avoid locks, monitors and such.
		INameEnvironment nameEnvironment = new JavaSearchNameEnvironment(javaProject, JavaModelManager.getJavaModelManager().getWorkingCopies(DefaultWorkingCopyOwner.PRIMARY, true/*add primary WCs*/));
		this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, nameEnvironment);
		reduceParseTree(this.cud);
		this.lookupEnvironment.buildTypeBindings(this.cud, null);
		this.lookupEnvironment.completeTypeBindings();
		this.cud.scope.faultInTypes();
		this.cud.resolve();
	} catch (Exception e) {
		if (JobManager.VERBOSE) {
			e.printStackTrace();
		}
	}
}
 
Example #28
Source File: TypeVariableBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public char[] nullAnnotatedReadableName(CompilerOptions options, boolean shortNames) {
    StringBuffer nameBuffer = new StringBuffer(10);
	appendNullAnnotation(nameBuffer, options);
	nameBuffer.append(this.sourceName());
	if (!this.inRecursiveFunction) {
		this.inRecursiveFunction = true;
		try {
			if (this.superclass != null && TypeBinding.equalsEquals(this.firstBound, this.superclass)) {
				nameBuffer.append(" extends ").append(this.superclass.nullAnnotatedReadableName(options, shortNames)); //$NON-NLS-1$
			}
			if (this.superInterfaces != null && this.superInterfaces != Binding.NO_SUPERINTERFACES) {
				if (TypeBinding.notEquals(this.firstBound, this.superclass)) {
					nameBuffer.append(" extends "); //$NON-NLS-1$
				}
				for (int i = 0, length = this.superInterfaces.length; i < length; i++) {
					if (i > 0 || TypeBinding.equalsEquals(this.firstBound, this.superclass)) {
						nameBuffer.append(" & "); //$NON-NLS-1$
					}
					nameBuffer.append(this.superInterfaces[i].nullAnnotatedReadableName(options, shortNames));
				}
			}
		} finally {
			this.inRecursiveFunction = false;
		}
	}
	int nameLength = nameBuffer.length();
	char[] readableName = new char[nameLength];
	nameBuffer.getChars(0, nameLength, readableName, 0);
    return readableName;
}
 
Example #29
Source File: CompletionOnReferenceExpressionName.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public TypeBinding resolveType(BlockScope scope) {
	
	final CompilerOptions compilerOptions = scope.compilerOptions();
	TypeBinding lhsType;
	boolean typeArgumentsHaveErrors;

	this.constant = Constant.NotAConstant;
	lhsType = this.lhs.resolveType(scope);
	if (this.typeArguments != null) {
		int length = this.typeArguments.length;
		typeArgumentsHaveErrors = compilerOptions.sourceLevel < ClassFileConstants.JDK1_5;
		this.resolvedTypeArguments = new TypeBinding[length];
		for (int i = 0; i < length; i++) {
			TypeReference typeReference = this.typeArguments[i];
			if ((this.resolvedTypeArguments[i] = typeReference.resolveType(scope, true /* check bounds*/)) == null) {
				typeArgumentsHaveErrors = true;
			}
			if (typeArgumentsHaveErrors && typeReference instanceof Wildcard) { // resolveType on wildcard always return null above, resolveTypeArgument is the real workhorse.
				scope.problemReporter().illegalUsageOfWildcard(typeReference);
			}
		}
		if (typeArgumentsHaveErrors || lhsType == null)
			throw new CompletionNodeFound();
	}
   	
	if (lhsType != null && lhsType.isValidBinding())
		throw new CompletionNodeFound(this, lhsType, scope);
	throw new CompletionNodeFound();
}
 
Example #30
Source File: Eclipse.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static int getEcjCompilerVersion() {
	if (ecjCompilerVersionCached >= 0) return ecjCompilerVersionCached;
	
	for (Field f : CompilerOptions.class.getDeclaredFields()) {
		try {
			if (f.getName().startsWith("VERSION_1_")) {
				ecjCompilerVersionCached = Math.max(ecjCompilerVersionCached, Integer.parseInt(f.getName().substring("VERSION_1_".length())));
			}
		} catch (Exception ignore) {}
	}
	
	if (ecjCompilerVersionCached < 5) ecjCompilerVersionCached = 5;
	if (!ecjSupportsJava7Features()) ecjCompilerVersionCached = Math.min(6, ecjCompilerVersionCached);
	return ecjCompilerVersionCached;
}