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

The following examples show how to use org.eclipse.jdt.internal.compiler.IProblemFactory. 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: 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 #2
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 #3
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 #4
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.eclipse.jdt.core.eval.IEvaluationContext
 * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
 */
public void evaluateVariables(INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException {
	deployCodeSnippetClassIfNeeded(requestor);
	VariablesEvaluator evaluator = new VariablesEvaluator(this, environment, options, requestor, problemFactory);
	ClassFile[] classes = evaluator.getClasses();
	if (classes != null) {
		if (classes.length > 0) {
			// Sort classes so that enclosing types are cached before nested types
			// otherwise an AbortCompilation is thrown in 1.5 mode since the enclosing type
			// is needed to resolve a nested type
			Util.sort(classes, new Util.Comparer() {
				public int compare(Object a, Object b) {
					if (a == b) return 0;
					ClassFile enclosing = ((ClassFile) a).enclosingClassFile;
					while (enclosing != null) {
						if (enclosing == b)
							return 1;
						enclosing = enclosing.enclosingClassFile;
					}
					return -1;
				}
			});

			// Send classes
			if (!requestor.acceptClassFiles(classes, null)) {
				throw new InstallException();
			}

			// Remember that the variables have been installed
			int count = this.variableCount;
			GlobalVariable[] variablesCopy = new GlobalVariable[count];
			System.arraycopy(this.variables, 0, variablesCopy, 0, count);
			this.installedVars = new VariablesInfo(evaluator.getPackageName(), evaluator.getClassName(), classes, variablesCopy, count);
			VAR_CLASS_COUNTER++;
		}
		this.varsChanged = false;
	}
}
 
Example #5
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.eclipse.jdt.core.eval.IEvaluationContext
 * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
 */
public void evaluate(char[] codeSnippet, INameEnvironment environment, Map options, final IRequestor requestor, IProblemFactory problemFactory) throws InstallException {
	this.evaluate(
		codeSnippet,
		null,
		null,
		null,
		null,
		true,
		false,
		environment,
		options,
		requestor,
		problemFactory);
}
 
Example #6
Source File: Evaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new evaluator.
 */
Evaluator(EvaluationContext context, INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) {
	this.context = context;
	this.environment = environment;
	this.options = options;
	this.requestor = requestor;
	this.problemFactory = problemFactory;
}
 
Example #7
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 #8
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 #9
Source File: VariablesEvaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a new global variables evaluator.
 */
VariablesEvaluator(EvaluationContext context, INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) {
	super(context, environment, options, requestor, problemFactory);
}
 
Example #10
Source File: EvaluationContextWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the problem factory to be used during evaluation.
 */
protected IProblemFactory getProblemFactory() {
	return ProblemFactory.getProblemFactory(Locale.getDefault());
}
 
Example #11
Source File: CodeSnippetEvaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a new code snippet evaluator.
 */
CodeSnippetEvaluator(char[] codeSnippet, EvaluationContext context, INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) {
	super(context, environment, options, requestor, problemFactory);
	this.codeSnippet = codeSnippet;
}
 
Example #12
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @see org.eclipse.jdt.core.eval.IEvaluationContext
 * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
 */
public void evaluate(
	char[] codeSnippet,
	char[][] contextLocalVariableTypeNames,
	char[][] contextLocalVariableNames,
	int[] contextLocalVariableModifiers,
	char[] contextDeclaringTypeName,
	boolean contextIsStatic,
	boolean contextIsConstructorCall,
	INameEnvironment environment,
	Map options,
	final IRequestor requestor,
	IProblemFactory problemFactory) throws InstallException {

	// Initialialize context
	this.localVariableTypeNames = contextLocalVariableTypeNames;
	this.localVariableNames = contextLocalVariableNames;
	this.localVariableModifiers = contextLocalVariableModifiers;
	this.declaringTypeName = contextDeclaringTypeName;
	this.isStatic = contextIsStatic;
	this.isConstructorCall = contextIsConstructorCall;

	deployCodeSnippetClassIfNeeded(requestor);

	try {
		// Install new variables if needed
		class ForwardingRequestor implements IRequestor {
			boolean hasErrors = false;
			public boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName) {
				return requestor.acceptClassFiles(classFiles, codeSnippetClassName);
			}
			public void acceptProblem(CategorizedProblem problem, char[] fragmentSource, int fragmentKind) {
				requestor.acceptProblem(problem, fragmentSource, fragmentKind);
				if (problem.isError()) {
					this.hasErrors = true;
				}
			}
		}
		ForwardingRequestor forwardingRequestor = new ForwardingRequestor();
		if (this.varsChanged) {
			evaluateVariables(environment, options, forwardingRequestor, problemFactory);
		}

		// Compile code snippet if there was no errors while evaluating the variables
		if (!forwardingRequestor.hasErrors) {
			Evaluator evaluator =
				new CodeSnippetEvaluator(
					codeSnippet,
					this,
					environment,
					options,
					requestor,
					problemFactory);
			ClassFile[] classes = evaluator.getClasses();
			// Send code snippet on target
			if (classes != null && classes.length > 0) {
				char[] simpleClassName = evaluator.getClassName();
				char[] pkgName = getPackageName();
				char[] qualifiedClassName =
					pkgName.length == 0 ?
						simpleClassName :
						CharOperation.concat(pkgName, simpleClassName, '.');
				CODE_SNIPPET_COUNTER++;
				if (!requestor.acceptClassFiles(classes, qualifiedClassName))
					throw new InstallException();
			}
		}
	} finally {
		// Reinitialize context to default values
		this.localVariableTypeNames = null;
		this.localVariableNames = null;
		this.localVariableModifiers = null;
		this.declaringTypeName = null;
		this.isStatic = true;
		this.isConstructorCall = false;
	}
}
 
Example #13
Source File: IndexingParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public IndexingParser(ISourceElementRequestor requestor, IProblemFactory problemFactory, CompilerOptions options, boolean reportLocalDeclarations, boolean optimizeStringLiterals, boolean useSourceJavadocParser) {
	super(requestor, problemFactory, options, reportLocalDeclarations,
			optimizeStringLiterals, useSourceJavadocParser);
}
 
Example #14
Source File: Main.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public IProblemFactory getProblemFactory() {
	return new DefaultProblemFactory(this.compilerLocale);
}
 
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: 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 #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;
}
 
Example #18
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * @see org.eclipse.jdt.core.eval.IEvaluationContext
 * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
 * @exception java.lang.IllegalArgumentException if the global has not been installed yet.
 */
public void evaluateVariable(GlobalVariable variable, INameEnvironment environment, Map options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException {
	this.evaluate(variable.getName(), environment, options, requestor, problemFactory);
}