org.eclipse.jdt.internal.compiler.env.INameEnvironment Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.env.INameEnvironment. 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: EvaluationContextWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see IEvaluationContext#evaluateCodeSnippet(String, ICodeSnippetRequestor, IProgressMonitor)
 */
public void evaluateCodeSnippet(String codeSnippet, ICodeSnippetRequestor requestor, IProgressMonitor progressMonitor) throws JavaModelException {

	checkBuilderState();
	INameEnvironment environment = null;
	try {
		this.context.evaluate(
			codeSnippet.toCharArray(),
			environment = getBuildNameEnvironment(),
			this.project.getOptions(true),
			getInfrastructureEvaluationRequestor(requestor),
			getProblemFactory());
	} catch (InstallException e) {
		handleInstallException(e);
	} finally {
		if (environment != null) environment.cleanup();
	}
}
 
Example #2
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 #3
Source File: EvaluationContextWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see IEvaluationContext#evaluateVariable(IGlobalVariable, ICodeSnippetRequestor, IProgressMonitor)
 */
public void evaluateVariable(IGlobalVariable variable, ICodeSnippetRequestor requestor, IProgressMonitor progressMonitor) throws JavaModelException {

	checkBuilderState();
	INameEnvironment environment = null;
	try {
		this.context.evaluateVariable(
			((GlobalVariableWrapper)variable).variable,
			environment = getBuildNameEnvironment(),
			this.project.getOptions(true),
			getInfrastructureEvaluationRequestor(requestor),
			getProblemFactory());
	} catch (InstallException e) {
		handleInstallException(e);
	} finally {
		if (environment != null) environment.cleanup();
	}
}
 
Example #4
Source File: PackageElementImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public List<? extends Element> getEnclosedElements() {
	PackageBinding binding = (PackageBinding)_binding;
	LookupEnvironment environment = binding.environment;
	char[][][] typeNames = null;
	INameEnvironment nameEnvironment = binding.environment.nameEnvironment;
	if (nameEnvironment instanceof FileSystem) {
		typeNames = ((FileSystem) nameEnvironment).findTypeNames(binding.compoundName);
	}
	HashSet<Element> set = new HashSet<Element>(); 
	if (typeNames != null) {
		for (char[][] typeName : typeNames) {
			ReferenceBinding type = environment.getType(typeName);
			if (type != null && type.isValidBinding()) {
				set.add(_env.getFactory().newElement(type));
			}
		}
	}
	ArrayList<Element> list = new ArrayList<Element>(set.size());
	list.addAll(set);
	return Collections.unmodifiableList(list);
}
 
Example #5
Source File: PackageBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IJavaElement getJavaElement() {
	INameEnvironment nameEnvironment = this.binding.environment.nameEnvironment; // a package binding always has a LooupEnvironment set
	if (!(nameEnvironment instanceof SearchableEnvironment)) return null;
	// this is not true in standalone DOM/AST
	NameLookup nameLookup = ((SearchableEnvironment) nameEnvironment).nameLookup;
	if (nameLookup == null) return null;
	IJavaElement[] pkgs = nameLookup.findPackageFragments(getName(), false/*exact match*/);
	if (pkgs == null) return null;
	if (pkgs.length == 0) {
		// add additional tracing as this should not happen
		org.eclipse.jdt.internal.core.util.Util.log(
			new Status(
					IStatus.WARNING,
					JavaCore.PLUGIN_ID,
					"Searching for package " + getName() + " returns an empty array")); //$NON-NLS-1$ //$NON-NLS-2$
		return null;
	}
	return pkgs[0];
}
 
Example #6
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 #7
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 #8
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 #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: ExtractAnnotationsDriver.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
private static Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> parseSources(
        @NonNull List<File> sourcePaths,
        @NonNull List<String> classpath,
        @NonNull String encoding,
        long languageLevel)
        throws IOException {
    List<ICompilationUnit> sourceUnits = Lists.newArrayListWithExpectedSize(100);

    for (File source : gatherJavaSources(sourcePaths)) {
        char[] contents = Util.getFileCharContent(source, encoding);
        ICompilationUnit unit = new CompilationUnit(contents, source.getPath(), encoding);
        sourceUnits.add(unit);
    }

    Map<ICompilationUnit, CompilationUnitDeclaration> outputMap = Maps.newHashMapWithExpectedSize(
            sourceUnits.size());

    CompilerOptions options = EcjParser.createCompilerOptions();
    options.docCommentSupport = true; // So I can find @hide

    // Note: We can *not* set options.ignoreMethodBodies=true because it disables
    // type attribution!

    options.sourceLevel = languageLevel;
    options.complianceLevel = options.sourceLevel;
    // We don't generate code, but just in case the parser consults this flag
    // and makes sure that it's not greater than the source level:
    options.targetJDK = options.sourceLevel;
    options.originalComplianceLevel = options.sourceLevel;
    options.originalSourceLevel = options.sourceLevel;
    options.inlineJsrBytecode = true; // >= 1.5

    INameEnvironment environment = EcjParser.parse(options, sourceUnits, classpath,
            outputMap, null);
    Collection<CompilationUnitDeclaration> parsedUnits = outputMap.values();
    return Pair.of(parsedUnits, environment);
}
 
Example #11
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 #12
Source File: EvaluationContextWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see IEvaluationContext#validateImports(ICodeSnippetRequestor)
 */
public void validateImports(ICodeSnippetRequestor requestor) {

	checkBuilderState();
	INameEnvironment environment = null;
	try {
		this.context.evaluateImports(
			environment = getBuildNameEnvironment(),
			getInfrastructureEvaluationRequestor(requestor),
			getProblemFactory());
	} finally {
		if (environment != null) environment.cleanup();
	}
}
 
Example #13
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 #14
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 #15
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 #16
Source File: ExtractAnnotations.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@NonNull
private Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> parseSources() {
    final List<ICompilationUnit> sourceUnits = Lists.newArrayListWithExpectedSize(100);

    getSource().visit(new EmptyFileVisitor() {
        @Override
        public void visitFile(FileVisitDetails fileVisitDetails) {
            File file = fileVisitDetails.getFile();
            String path = file.getPath();
            if (path.endsWith(DOT_JAVA) && file.isFile()) {
                char[] contents = new char[0];
                try {
                    contents = Util.getFileCharContent(file, encoding);
                    ICompilationUnit unit = new CompilationUnit(contents, path, encoding);
                    sourceUnits.add(unit);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    });

    Map<ICompilationUnit, CompilationUnitDeclaration> outputMap = Maps.newHashMapWithExpectedSize(((ArrayList<ICompilationUnit>) sourceUnits).size());
    List<String> jars = Lists.newArrayList();
    if (bootClasspath != null) {
        ((ArrayList<String>) jars).addAll(bootClasspath);
    }

    if (getClasspath() != null) {
        for (File jar : getClasspath()) {
            ((ArrayList<String>) jars).add(jar.getPath());
        }

    }


    CompilerOptions options = EcjParser.createCompilerOptions();
    options.docCommentSupport = true;// So I can find @hide

    // Note: We can *not* set options.ignoreMethodBodies=true because it disables
    // type attribution!

    long level = getLanguageLevel(getSourceCompatibility());
    options.sourceLevel = level;
    options.complianceLevel = options.sourceLevel;
    // We don't generate code, but just in case the parser consults this flag
    // and makes sure that it's not greater than the source level:
    options.targetJDK = options.sourceLevel;
    options.originalComplianceLevel = options.sourceLevel;
    options.originalSourceLevel = options.sourceLevel;
    options.inlineJsrBytecode = true;// >= 1.5

    INameEnvironment environment = EcjParser.parse(options, sourceUnits, jars, outputMap, null);
    Collection<CompilationUnitDeclaration> parsedUnits = ((HashMap<ICompilationUnit, CompilationUnitDeclaration>) outputMap).values();
    return Pair.of(parsedUnits, environment);
}
 
Example #17
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 #18
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 #19
Source File: CodeSnippetEnvironment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a new wrapper for the given environment.
 */
public CodeSnippetEnvironment(INameEnvironment env, EvaluationContext context) {
	this.env = env;
	this.context = context;
}
 
Example #20
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 #21
Source File: EvaluationContextWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a name environment for the last built state.
 */
protected INameEnvironment getBuildNameEnvironment() {
	return new NameEnvironment(getProject());
}
 
Example #22
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 #23
Source File: ExtractAnnotations.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@Override
@TaskAction
protected void compile() {
    if (!hasAndroidAnnotations()) {
        return;

    }


    if (encoding == null) {
        encoding = "UTF_8";
    }


    Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> result = parseSources();
    Collection<CompilationUnitDeclaration> parsedUnits = result.getFirst();
    INameEnvironment environment = result.getSecond();

    try {
        if (!allowErrors) {
            for (CompilationUnitDeclaration unit : parsedUnits) {
                // so maybe I don't need my map!!
                CategorizedProblem[] problems = unit.compilationResult().getAllProblems();
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        System.out.println("Not extracting annotations (compilation problems encountered)");
                        System.out.println("Error: " + problem.getOriginatingFileName() + ":" + problem.getSourceLineNumber() + ": " + problem.getMessage());
                        // TODO: Consider whether we abort the build at this point!
                        return;

                    }

                }

            }

        }


        // API definition file
        ApiDatabase database = null;
        if (apiFilter != null && apiFilter.exists()) {
            try {
                database = new ApiDatabase(apiFilter);
            } catch (IOException e) {
                throw new BuildException("Could not open API database " + apiFilter, e);
            }

        }


        boolean displayInfo = getProject().getLogger().isEnabled(LogLevel.INFO);
        Boolean includeClassRetentionAnnotations = false;
        Boolean sortAnnotations = false;

        Extractor extractor = new Extractor(database, classDir, displayInfo, includeClassRetentionAnnotations, sortAnnotations);
        extractor.extractFromProjectSource(parsedUnits);
        if (mergeJars != null) {
            for (File jar : mergeJars) {
                extractor.mergeExisting(jar);
            }

        }

        extractor.export(output, proguard);
        extractor.removeTypedefClasses();
    } finally {
        if (environment != null) {
            environment.cleanup();
        }

    }

}
 
Example #24
Source File: CompilationUnitProblemFinder.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 (e.g. 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.
 */
protected CompilationUnitProblemFinder(
	INameEnvironment environment,
	IErrorHandlingPolicy policy,
	CompilerOptions compilerOptions,
	ICompilerRequestor requestor,
	IProblemFactory problemFactory) {

	super(environment,
		policy,
		compilerOptions,
		requestor,
		problemFactory
	);
}
 
Example #25
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 #26
Source File: CodeSnippetEvaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns an environment that wraps the client's name environment.
 * This wrapper always considers the wrapped environment then if the name is
 * not found, it search in the code snippet support. This includes the superclass
 * org.eclipse.jdt.internal.eval.target.CodeSnippet as well as the global variable classes.
 */
private INameEnvironment getWrapperEnvironment() {
	return new CodeSnippetEnvironment(this.environment, this.context);
}
 
Example #27
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);
}