org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy. 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: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean isCompatibleWith(TypeBinding left, Scope scope) {
	if (this.binding != null && this.binding.isValidBinding() // binding indicates if full resolution has already happened
			&& this.resolvedType != null && this.resolvedType.isValidBinding()) {
		return this.resolvedType.isCompatibleWith(left, scope);
	}
	// 15.28.2
	left = left.uncapture(this.enclosingScope);
	final MethodBinding sam = left.getSingleAbstractMethod(this.enclosingScope, true);
	if (sam == null || !sam.isValidBinding())
		return false;
	boolean isCompatible;
	setExpectedType(left);
	IErrorHandlingPolicy oldPolicy = this.enclosingScope.problemReporter().switchErrorHandlingPolicy(silentErrorHandlingPolicy);
	try {
		this.binding = null;
		this.trialResolution = true;
		resolveType(this.enclosingScope);
	} finally {
		this.enclosingScope.problemReporter().switchErrorHandlingPolicy(oldPolicy);
		isCompatible = this.binding != null && this.binding.isValidBinding();
		this.binding = null;
		setExpectedType(null);
		this.trialResolution = false;
	}
	return isCompatible;
}
 
Example #2
Source File: RunTestsViaEcj.java    From EasyMPermission with MIT License 6 votes vote down vote up
protected IErrorHandlingPolicy ecjErrorHandlingPolicy() {
	return new IErrorHandlingPolicy() {
		public boolean stopOnFirstError() {
			return true;
		}
		
		public boolean proceedOnErrors() {
			return false;
		}
		
		@SuppressWarnings("all") // Added to the interface in later ecj version.
		public boolean ignoreAllErrors() {
			return false;
		}
	};
}
 
Example #3
Source File: EclipseCompilerImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IErrorHandlingPolicy getHandlingPolicy() {
	// passes the initial set of files to the batch oracle (to avoid finding more than once the same units when case insensitive match)
	return new IErrorHandlingPolicy() {
		@Override
		public boolean proceedOnErrors() {
			return false; // stop if there are some errors
		}
		@Override
		public boolean stopOnFirstError() {
			return false;
		}
		@Override
		public boolean ignoreAllErrors() {
			return false;
		}
	};
}
 
Example #4
Source File: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
MethodBinding internalResolveTentatively(TypeBinding targetType, Scope scope) {
	// FIXME: could enclosingScope still be null here??
	IErrorHandlingPolicy oldPolicy = this.enclosingScope.problemReporter().switchErrorHandlingPolicy(silentErrorHandlingPolicy);
	ExpressionContext previousContext = this.expressionContext;
	MethodBinding previousBinding = this.binding;
	MethodBinding previousDescriptor = this.descriptor;
	TypeBinding previousResolvedType = this.resolvedType;
	try {
		setExpressionContext(INVOCATION_CONTEXT);
		setExpectedType(targetType);
		this.binding = null;
		this.trialResolution = true;
		resolveType(this.enclosingScope);
		return this.binding;
	} finally {
		this.enclosingScope.problemReporter().switchErrorHandlingPolicy(oldPolicy);
		// remove *any relevant* traces of this 'inofficial' resolving:
		this.binding = previousBinding;
		this.descriptor = previousDescriptor;
		this.resolvedType = previousResolvedType;
		setExpressionContext(previousContext);
		this.expectedType = null; // don't call setExpectedType(null), would NPE
		this.trialResolution = false;
	}
}
 
Example #5
Source File: CodeSnippetCompiler.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new code snippet compiler initialized with a code snippet parser.
 */
public CodeSnippetCompiler(
   		INameEnvironment environment,
   		IErrorHandlingPolicy policy,
   		CompilerOptions compilerOptions,
   		ICompilerRequestor requestor,
   		IProblemFactory problemFactory,
   		EvaluationContext evaluationContext,
   		int codeSnippetStart,
   		int codeSnippetEnd) {
	super(environment, policy, compilerOptions, requestor, problemFactory);
	this.codeSnippetStart = codeSnippetStart;
	this.codeSnippetEnd = codeSnippetEnd;
	this.evaluationContext = evaluationContext;
	this.parser =
		new CodeSnippetParser(
			this.problemReporter,
			evaluationContext,
			this.options.parseLiteralExpressionsAsConstants,
			codeSnippetStart,
			codeSnippetEnd);
	this.parseThreshold = 1;
	// fully parse only the code snippet compilation unit
}
 
Example #6
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static IErrorHandlingPolicy getHandlingPolicy() {

		// passes the initial set of files to the batch oracle (to avoid finding more than once the same units when case insensitive match)
		return new IErrorHandlingPolicy() {
			public boolean stopOnFirstError() {
				return false;
			}
			public boolean proceedOnErrors() {
				return false; // stop if there are some errors
			}
			public boolean ignoreAllErrors() {
				return false;
			}
		};
	}
 
Example #7
Source File: FilerImplTest.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testBinaryOriginatingElements() throws Exception {
  // the point of this test is to assert Filer#createSourceFile does not puke when originatingElements are not sources

  // originating source elements are used to cleanup generated outputs when corresponding sources change
  // originating binary elements are not currently fully supported and are not tracked during incremental build

  Classpath namingEnvironment = createClasspath();
  IErrorHandlingPolicy errorHandlingPolicy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
  IProblemFactory problemFactory = ProblemFactory.getProblemFactory(Locale.getDefault());
  CompilerOptions compilerOptions = new CompilerOptions();
  ICompilerRequestor requestor = null;
  Compiler compiler = new Compiler(namingEnvironment, errorHandlingPolicy, compilerOptions, requestor, problemFactory);

  EclipseFileManager fileManager = new EclipseFileManager(null, Charsets.UTF_8);
  File outputDir = temp.newFolder();
  fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(outputDir));

  CompilerBuildContext context = null;
  Map<String, String> processorOptions = null;
  CompilerJdt incrementalCompiler = null;
  ProcessingEnvImpl env = new ProcessingEnvImpl(context, fileManager, processorOptions, compiler, incrementalCompiler);

  TypeElement typeElement = env.getElementUtils().getTypeElement("java.lang.Object");

  FilerImpl filer = new FilerImpl(null /* context */, fileManager, null /* compiler */, null /* env */);
  filer.createSourceFile("test.Source", typeElement);
}
 
Example #8
Source File: Main.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IErrorHandlingPolicy getHandlingPolicy() {

	// passes the initial set of files to the batch oracle (to avoid finding more than once the same units when case insensitive match)
	return new IErrorHandlingPolicy() {
		public boolean proceedOnErrors() {
			return Main.this.proceedOnError; // stop if there are some errors
		}
		public boolean stopOnFirstError() {
			return false;
		}
		public boolean ignoreAllErrors() {
			return false;
		}
	};
}
 
Example #9
Source File: HierarchyResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public HierarchyResolver(INameEnvironment nameEnvironment, Map settings, HierarchyBuilder builder, IProblemFactory problemFactory) {
	// create a problem handler with the 'exit after all problems' handling policy
	this.options = new CompilerOptions(settings);
	IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
	ProblemReporter problemReporter = new ProblemReporter(policy, this.options, problemFactory);

	LookupEnvironment environment = new LookupEnvironment(this, this.options, problemReporter, nameEnvironment);
	environment.mayTolerateMissingType = true;
	setEnvironment(environment, builder);
}
 
Example #10
Source File: JRJdtCompiler.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected String compileUnits(final JRCompilationUnit[] units, String classpath, File tempDirFile)
{
	final INameEnvironment env = getNameEnvironment(units);

	final IErrorHandlingPolicy policy = 
		DefaultErrorHandlingPolicies.proceedWithAllProblems();

	final CompilerOptions options = new CompilerOptions(getJdtSettings());

	final IProblemFactory problemFactory = 
		new DefaultProblemFactory(Locale.getDefault());

	final CompilerRequestor requestor = getCompilerRequestor(units);

	final Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);

	do
	{
		CompilationUnit[] compilationUnits = requestor.processCompilationUnits();

		compiler.compile(compilationUnits);
	}
	while (requestor.hasMissingMethods());
	
	requestor.processProblems();

	return requestor.getFormattedProblems();
}
 
Example #11
Source File: EcjParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public NonGeneratingCompiler(INameEnvironment environment, IErrorHandlingPolicy policy,
        CompilerOptions options, ICompilerRequestor requestor,
        IProblemFactory problemFactory,
        Map<ICompilationUnit, CompilationUnitDeclaration> units) {
    super(environment, policy, options, requestor, problemFactory, null, null);
    mUnits = units;
}
 
Example #12
Source File: EcjParser.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/** Parse the given source units and class path and store it into the given output map */
public static INameEnvironment parse(
        CompilerOptions options,
        @NonNull List<ICompilationUnit> sourceUnits,
        @NonNull List<String> classPath,
        @NonNull Map<ICompilationUnit, CompilationUnitDeclaration> outputMap,
        @Nullable LintClient client) {
    INameEnvironment environment = new FileSystem(
            classPath.toArray(new String[classPath.size()]), new String[0],
            options.defaultEncoding);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    ICompilerRequestor requestor = new ICompilerRequestor() {
        @Override
        public void acceptResult(CompilationResult result) {
            // Not used; we need the corresponding CompilationUnitDeclaration for the source
            // units (the AST parsed from source) which we don't get access to here, so we
            // instead subclass AST to get our hands on them.
        }
    };

    NonGeneratingCompiler compiler = new NonGeneratingCompiler(environment, policy, options,
            requestor, problemFactory, outputMap);
    try {
        compiler.compile(sourceUnits.toArray(new ICompilationUnit[sourceUnits.size()]));
    } catch (OutOfMemoryError e) {
        environment.cleanup();

        // Since we're running out of memory, if it's all still held we could potentially
        // fail attempting to log the failure. Actively get rid of the large ECJ data
        // structure references first so minimize the chance of that
        //noinspection UnusedAssignment
        compiler = null;
        //noinspection UnusedAssignment
        environment = null;
        //noinspection UnusedAssignment
        requestor = null;
        //noinspection UnusedAssignment
        problemFactory = null;
        //noinspection UnusedAssignment
        policy = null;

        String msg = "Ran out of memory analyzing .java sources with ECJ: Some lint checks "
                + "may not be accurate (missing type information from the compiler)";
        if (client != null) {
            // Don't log exception too; this isn't a compiler error per se where we
            // need to pin point the exact unlucky code that asked for memory when it
            // had already run out
            client.log(null, msg);
        } else {
            System.out.println(msg);
        }
    } catch (Throwable t) {
        if (client != null) {
            CompilationUnitDeclaration currentUnit = compiler.getCurrentUnit();
            if (currentUnit == null || currentUnit.getFileName() == null) {
                client.log(t, "ECJ compiler crashed");
            } else {
                client.log(t, "ECJ compiler crashed processing %1$s",
                        new String(currentUnit.getFileName()));
            }
        } else {
            t.printStackTrace();
        }

        environment.cleanup();
        environment = null;
    }

    return environment;
}
 
Example #13
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Get a resolved copy of this lambda for use by type inference, as to avoid spilling any premature
 * type results into the original lambda.
 * 
 * @param targetType the target functional type against which inference is attempted, must be a non-null valid functional type 
 * @return a resolved copy of 'this' or null if significant errors where encountered
 */
public LambdaExpression getResolvedCopyForInferenceTargeting(TypeBinding targetType) {
	// note: this is essentially a simplified extract from isCompatibleWith(TypeBinding,Scope).
	if (this.shapeAnalysisComplete && this.binding != null)
		return this;
	
	targetType = targetType.uncapture(this.enclosingScope);
	// TODO: caching
	IErrorHandlingPolicy oldPolicy = this.enclosingScope.problemReporter().switchErrorHandlingPolicy(silentErrorHandlingPolicy);
	final CompilerOptions compilerOptions = this.enclosingScope.compilerOptions();
	boolean analyzeNPE = compilerOptions.isAnnotationBasedNullAnalysisEnabled;
	final LambdaExpression copy = copy();
	if (copy == null) {
		return null;
	}
	try {
		compilerOptions.isAnnotationBasedNullAnalysisEnabled = false;
		copy.setExpressionContext(this.expressionContext);
		copy.setExpectedType(targetType);
		this.hasIgnoredMandatoryErrors = false;
		TypeBinding type = copy.resolveType(this.enclosingScope);
		if (type == null || !type.isValidBinding())
			return null;
		if (this.body instanceof Block) {
			if (copy.returnsVoid) {
				copy.shapeAnalysisComplete = true;
			} else {
				copy.valueCompatible = this.returnsValue;
			}
		} else {
			copy.voidCompatible = ((Expression) this.body).statementExpression();
			TypeBinding resultType = ((Expression) this.body).resolvedType;
			if (resultType == null) // case of a yet-unresolved poly expression?
				copy.valueCompatible = true;
			else
				copy.valueCompatible = (resultType != TypeBinding.VOID);
			copy.shapeAnalysisComplete = true;
		}
		// Do not proceed with data/control flow analysis if resolve encountered errors.
		if (!this.hasIgnoredMandatoryErrors && !enclosingScopesHaveErrors()) {
			// value compatibility of block lambda's is the only open question.
			if (!copy.shapeAnalysisComplete)
				copy.valueCompatible = copy.doesNotCompleteNormally();
		} else {
			if (!copy.returnsVoid)
				copy.valueCompatible = true; // optimistically, TODO: is this OK??
		}
		
		copy.shapeAnalysisComplete = true;
		copy.resultExpressions = this.resultExpressions;
		this.resultExpressions = NO_EXPRESSIONS;
	} finally {
		compilerOptions.isAnnotationBasedNullAnalysisEnabled = analyzeNPE;
		this.hasIgnoredMandatoryErrors = false;
		this.enclosingScope.problemReporter().switchErrorHandlingPolicy(oldPolicy);
	}
	return copy;
}
 
Example #14
Source File: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void generateImplicitLambda(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
	
	final Parser parser = new Parser(this.enclosingScope.problemReporter(), false);
	final char[] source = this.compilationResult.getCompilationUnit().getContents();
	ReferenceExpression copy =  (ReferenceExpression) parser.parseExpression(source, this.sourceStart, this.sourceEnd - this.sourceStart + 1, 
									this.enclosingScope.referenceCompilationUnit(), false /* record line separators */);
	
	int argc = this.descriptor.parameters.length;
	
	LambdaExpression implicitLambda = new LambdaExpression(this.compilationResult, false);
	Argument [] arguments = new Argument[argc];
	for (int i = 0; i < argc; i++)
		arguments[i] = new Argument(("arg" + i).toCharArray(), 0, null, 0, true); //$NON-NLS-1$
	implicitLambda.setArguments(arguments);
	implicitLambda.setExpressionContext(this.expressionContext);
	implicitLambda.setExpectedType(this.expectedType);
	
	int parameterShift = this.receiverPrecedesParameters ? 1 : 0;
	Expression [] argv = new SingleNameReference[argc - parameterShift];
	for (int i = 0, length = argv.length; i < length; i++) {
		String name = "arg" + (i + parameterShift); //$NON-NLS-1$
		argv[i] = new SingleNameReference(name.toCharArray(), 0);
	}
	if (isMethodReference()) {
		MessageSend message = new MessageSend();
		message.selector = this.selector;
		message.receiver = this.receiverPrecedesParameters ? new SingleNameReference("arg0".toCharArray(), 0) : copy.lhs; //$NON-NLS-1$
		message.typeArguments = copy.typeArguments;
		message.arguments = argv;
		implicitLambda.setBody(message);
	} else if (isArrayConstructorReference()) {
		// We don't care for annotations, source positions etc. They are immaterial, just drop.
		ArrayAllocationExpression arrayAllocationExpression = new ArrayAllocationExpression();
		arrayAllocationExpression.dimensions = new Expression[] { argv[0] };
		if (this.lhs instanceof ArrayTypeReference) {
			ArrayTypeReference arrayTypeReference = (ArrayTypeReference) this.lhs;
			arrayAllocationExpression.type = arrayTypeReference.dimensions == 1 ? new SingleTypeReference(arrayTypeReference.token, 0L) : 
															new ArrayTypeReference(arrayTypeReference.token, arrayTypeReference.dimensions - 1, 0L);
		} else {
			ArrayQualifiedTypeReference arrayQualifiedTypeReference = (ArrayQualifiedTypeReference) this.lhs;
			arrayAllocationExpression.type = arrayQualifiedTypeReference.dimensions == 1 ? new QualifiedTypeReference(arrayQualifiedTypeReference.tokens, arrayQualifiedTypeReference.sourcePositions)
															: new ArrayQualifiedTypeReference(arrayQualifiedTypeReference.tokens, arrayQualifiedTypeReference.dimensions - 1, 
																	arrayQualifiedTypeReference.sourcePositions);
		}
		implicitLambda.setBody(arrayAllocationExpression);
	} else {
		AllocationExpression allocation = new AllocationExpression();
		if (this.lhs instanceof TypeReference) {
			allocation.type = (TypeReference) this.lhs;
		} else if (this.lhs instanceof SingleNameReference) {
			allocation.type = new SingleTypeReference(((SingleNameReference) this.lhs).token, 0);
		} else if (this.lhs instanceof QualifiedNameReference) {
			allocation.type = new QualifiedTypeReference(((QualifiedNameReference) this.lhs).tokens, new long [((QualifiedNameReference) this.lhs).tokens.length]);
		} else {
			throw new IllegalStateException("Unexpected node type"); //$NON-NLS-1$
		}
		allocation.typeArguments = copy.typeArguments;
		allocation.arguments = argv;
		implicitLambda.setBody(allocation);
	}
	
	// Process the lambda, taking care not to double report diagnostics. Don't expect any from resolve, Any from code generation should surface, but not those from flow analysis.
	implicitLambda.resolve(currentScope);
	IErrorHandlingPolicy oldPolicy = currentScope.problemReporter().switchErrorHandlingPolicy(silentErrorHandlingPolicy);
	try {
		implicitLambda.analyseCode(currentScope, 
				new ExceptionHandlingFlowContext(null, this, Binding.NO_EXCEPTIONS, null, currentScope, FlowInfo.DEAD_END), 
				UnconditionalFlowInfo.fakeInitializedFlowInfo(currentScope.outerMostMethodScope().analysisIndex, currentScope.referenceType().maxFieldCount));
	} finally {
		currentScope.problemReporter().switchErrorHandlingPolicy(oldPolicy);
	}
	SyntheticArgumentBinding[] outerLocals = this.receiverType.syntheticOuterLocalVariables();
	for (int i = 0, length = outerLocals == null ? 0 : outerLocals.length; i < length; i++)
		implicitLambda.addSyntheticArgument(outerLocals[i].actualOuterLocalVariable);
	
	implicitLambda.generateCode(currentScope, codeStream, valueRequired);
}
 
Example #15
Source File: ProblemHandler.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public ProblemHandler(IErrorHandlingPolicy policy, CompilerOptions options, IProblemFactory problemFactory) {
	this.policy = policy;
	this.problemFactory = problemFactory;
	this.options = options;
}
 
Example #16
Source File: ProblemHandler.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/** @return old policy. */
public IErrorHandlingPolicy switchErrorHandlingPolicy(IErrorHandlingPolicy newPolicy) {
	IErrorHandlingPolicy presentPolicy = this.policy;
	this.policy = newPolicy;
	return presentPolicy;
}
 
Example #17
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Answer a new CompilationUnitVisitor using the given name environment and compiler options.
 * The environment and options will be in effect for the lifetime of the compiler.
 * When the compiler is run, compilation results are sent to the given requestor.
 *
 *  @param environment org.eclipse.jdt.internal.compiler.api.env.INameEnvironment
 *      Environment used by the compiler in order to resolve type and package
 *      names. The name environment implements the actual connection of the compiler
 *      to the outside world (for example, in batch mode the name environment is performing
 *      pure file accesses, reuse previous build state or connection to repositories).
 *      Note: the name environment is responsible for implementing the actual classpath
 *            rules.
 *
 *  @param policy org.eclipse.jdt.internal.compiler.api.problem.IErrorHandlingPolicy
 *      Configurable part for problem handling, allowing the compiler client to
 *      specify the rules for handling problems (stop on first error or accumulate
 *      them all) and at the same time perform some actions such as opening a dialog
 *      in UI when compiling interactively.
 *      @see org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies
 *
 *	@param compilerOptions The compiler options to use for the resolution.
 *
 *  @param requestor org.eclipse.jdt.internal.compiler.api.ICompilerRequestor
 *      Component which will receive and persist all compilation results and is intended
 *      to consume them as they are produced. Typically, in a batch compiler, it is
 *      responsible for writing out the actual .class files to the file system.
 *      @see org.eclipse.jdt.internal.compiler.CompilationResult
 *
 *  @param problemFactory org.eclipse.jdt.internal.compiler.api.problem.IProblemFactory
 *      Factory used inside the compiler to create problem descriptors. It allows the
 *      compiler client to supply its own representation of compilation problems in
 *      order to avoid object conversions. Note that the factory is not supposed
 *      to accumulate the created problems, the compiler will gather them all and hand
 *      them back as part of the compilation unit result.
 */
public CompilationUnitResolver(
	INameEnvironment environment,
	IErrorHandlingPolicy policy,
	CompilerOptions compilerOptions,
	ICompilerRequestor requestor,
	IProblemFactory problemFactory,
	IProgressMonitor monitor,
	boolean fromJavaProject) {

	super(environment, policy, compilerOptions, requestor, problemFactory);
	this.hasCompilationAborted = false;
	this.monitor =monitor;
	this.fromJavaProject = fromJavaProject;
}