org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory. 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: JavaDerivedStateComputer.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
public void installStubs(Resource resource) {
	if (isInfoFile(resource)) {
		return;
	}
	CompilationUnit compilationUnit = getCompilationUnit(resource);
	ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
			getCompilerOptions(resource), new DefaultProblemFactory());
	Parser parser = new Parser(problemReporter, true);
	CompilationResult compilationResult = new CompilationResult(compilationUnit, 0, 1, -1);
	CompilationUnitDeclaration result = parser.dietParse(compilationUnit, compilationResult);
	if (result.types != null) {
		for (TypeDeclaration type : result.types) {
			ImportReference currentPackage = result.currentPackage;
			String packageName = null;
			if (currentPackage != null) {
				char[][] importName = currentPackage.getImportName();
				if (importName != null) {
					packageName = CharOperation.toString(importName);
				}
			}
			JvmDeclaredType jvmType = createType(type, packageName);
			resource.getContents().add(jvmType);
		}
	}
}
 
Example #2
Source File: AppCompiler.java    From actframework with Apache License 2.0 6 votes vote down vote up
public void compile(String className) {
    Timer timer = metric.startTimer("act:classload:compile:" + className);
    ICompilationUnit[] compilationUnits = new ICompilationUnit[1];
    compilationUnits[0] = classLoader.source(className).compilationUnit();
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);

    org.eclipse.jdt.internal.compiler.Compiler jdtCompiler = new Compiler(
            nameEnv, policy, compilerOptions, requestor, problemFactory) {
        @Override
        protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud, CompilationResult result) {
        }
    };

    jdtCompiler.compile(compilationUnits);
    timer.stop();
}
 
Example #3
Source File: IndexManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public SourceElementParser getSourceElementParser(IJavaProject project, ISourceElementRequestor requestor) {
	// disable task tags to speed up parsing
	Map options = project.getOptions(true);
	options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$

	SourceElementParser parser = new IndexingParser(
		requestor,
		new DefaultProblemFactory(Locale.getDefault()),
		new CompilerOptions(options),
		true, // index local declarations
		true, // optimize string literals
		false); // do not use source javadoc parser to speed up parsing
	parser.reportOnlyOneSyntaxError = true;

	// Always check javadoc while indexing
	parser.javadocParser.checkDocComment = true;
	parser.javadocParser.reportProblems = false;

	return parser;
}
 
Example #4
Source File: AppCompiler.java    From actframework with Apache License 2.0 6 votes vote down vote up
public void compile(Collection<Source> sources) {
    Timer timer = metric.startTimer("act:classload:compile:_all");
    int len = sources.size();
    ICompilationUnit[] compilationUnits = new ICompilationUnit[len];
    int i = 0;
    for (Source source: sources) {
        compilationUnits[i++] = source.compilationUnit();
    }
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);

    org.eclipse.jdt.internal.compiler.Compiler jdtCompiler = new Compiler(
            nameEnv, policy, compilerOptions, requestor, problemFactory) {
        @Override
        protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud, CompilationResult result) {
        }
    };

    jdtCompiler.compile(compilationUnits);
    timer.stop();
}
 
Example #5
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 #6
Source File: JdtCompiler.java    From jetbrick-template-1x with Apache License 2.0 5 votes vote down vote up
@Override
protected void generateJavaClass(JavaSource source) throws IOException {
    INameEnvironment env = new NameEnvironment(source);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    CompilerOptions options = getCompilerOptions();
    CompilerRequestor requestor = new CompilerRequestor();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);
    compiler.compile(new ICompilationUnit[] { new CompilationUnit(source) });

    if (requestor.hasErrors()) {
        String sourceCode = source.getSourceCode();
        String[] sourceCodeLines = sourceCode.split("(\r\n|\r|\n)", -1);
        StringBuilder sb = new StringBuilder();
        sb.append("Compilation failed.");
        sb.append('\n');
        for (IProblem p : requestor.getErrors()) {
            sb.append(p.getMessage()).append('\n');
            int start = p.getSourceStart();
            int column = start; // default
            for (int i = start; i >= 0; i--) {
                char c = sourceCode.charAt(i);
                if (c == '\n' || c == '\r') {
                    column = start - i;
                    break;
                }
            }
            sb.append(StringUtils.getPrettyError(sourceCodeLines, p.getSourceLineNumber(), column, p.getSourceStart(), p.getSourceEnd(), 3));
        }
        sb.append(requestor.getErrors().length);
        sb.append(" error(s)\n");
        throw new CompileErrorException(sb.toString());
    }

    requestor.save(source.getOutputdir());
}
 
Example #7
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Expression parseExpression(char[] source, int offset, int length, Map settings, boolean recordParsingInformation) {

		if (source == null) {
			throw new IllegalArgumentException();
		}
		CompilerOptions compilerOptions = new CompilerOptions(settings);
		// in this case we don't want to ignore method bodies since we are parsing only an expression
		final ProblemReporter problemReporter = new ProblemReporter(
					DefaultErrorHandlingPolicies.proceedWithAllProblems(),
					compilerOptions,
					new DefaultProblemFactory(Locale.getDefault()));

		CommentRecorderParser parser = new CommentRecorderParser(problemReporter, false);

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

		CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
		CompilationUnitDeclaration unit = new CompilationUnitDeclaration(problemReporter, compilationResult, source.length);
		Expression result = parser.parseExpression(source, offset, length, unit, true /* record line separators */);

		if (recordParsingInformation) {
			this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, unit.comments);
		}
		return result;
	}
 
Example #8
Source File: CompilationUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 *  Create a CommentRecorderParser
 * @param options - compiler options
 * @return
 */
private static Parser createCommentRecorderParser(CompilerOptions options) {
    Parser parser =
            new CommentRecorderParser(new ProblemReporter(
                    DefaultErrorHandlingPolicies.proceedWithAllProblems(),
                    options,
                    new DefaultProblemFactory()), false);
    return parser;
}
 
Example #9
Source File: HierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public HierarchyBuilder(TypeHierarchy hierarchy) throws JavaModelException {

		this.hierarchy = hierarchy;
		JavaProject project = (JavaProject) hierarchy.javaProject();

		IType focusType = hierarchy.getType();
		org.eclipse.jdt.core.ICompilationUnit unitToLookInside = focusType == null ? null : focusType.getCompilationUnit();
		org.eclipse.jdt.core.ICompilationUnit[] workingCopies = this.hierarchy.workingCopies;
		org.eclipse.jdt.core.ICompilationUnit[] unitsToLookInside;
		if (unitToLookInside != null) {
			int wcLength = workingCopies == null ? 0 : workingCopies.length;
			if (wcLength == 0) {
				unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[] {unitToLookInside};
			} else {
				unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[wcLength+1];
				unitsToLookInside[0] = unitToLookInside;
				System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength);
			}
		} else {
			unitsToLookInside = workingCopies;
		}
		if (project != null) {
			SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside);
			this.nameLookup = searchableEnvironment.nameLookup;
			this.hierarchyResolver =
				new HierarchyResolver(
					searchableEnvironment,
					project.getOptions(true),
					this,
					new DefaultProblemFactory());
		}
		this.infoToHandle = new HashMap(5);
		this.focusQualifiedName = focusType == null ? null : focusType.getFullyQualifiedName();
	}
 
Example #10
Source File: BasicSearchEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Parser getParser() {
	if (this.parser == null) {
		this.compilerOptions = new CompilerOptions(JavaCore.getOptions());
		ProblemReporter problemReporter =
			new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				this.compilerOptions,
				new DefaultProblemFactory());
		this.parser = new Parser(problemReporter, true);
	}
	return this.parser;
}
 
Example #11
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 #12
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 #13
Source File: DOMBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a new parser.
 */
protected DocumentElementParser getParser(Map settings) {
	return new DocumentElementParser(this, new DefaultProblemFactory(), new CompilerOptions(settings));
}
 
Example #14
Source File: SimpleDOMBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a new parser.
 */
protected SourceElementParser getParser(Map settings) {
	return new SourceElementParser(this, new DefaultProblemFactory(), new CompilerOptions(settings), false/*don't report local declarations*/, true/*optimize string literals*/);
}
 
Example #15
Source File: IndexBasedHierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void buildForProject(JavaProject project, ArrayList potentialSubtypes, org.eclipse.jdt.core.ICompilationUnit[] workingCopies, HashSet localTypes, IProgressMonitor monitor) throws JavaModelException {
	// resolve
	int openablesLength = potentialSubtypes.size();
	if (openablesLength > 0) {
		// copy vectors into arrays
		Openable[] openables = new Openable[openablesLength];
		potentialSubtypes.toArray(openables);

		// sort in the order of roots and in reverse alphabetical order for .class file
		// since requesting top level types in the process of caching an enclosing type is
		// not supported by the lookup environment
		IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
		int rootsLength = roots.length;
		final HashtableOfObjectToInt indexes = new HashtableOfObjectToInt(openablesLength);
		for (int i = 0; i < openablesLength; i++) {
			IJavaElement root = openables[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
			int index;
			for (index = 0; index < rootsLength; index++) {
				if (roots[index].equals(root))
					break;
			}
			indexes.put(openables[i], index);
		}
		Arrays.sort(openables, new Comparator() {
			public int compare(Object a, Object b) {
				int aIndex = indexes.get(a);
				int bIndex = indexes.get(b);
				if (aIndex != bIndex)
					return aIndex - bIndex;
				return ((Openable) b).getElementName().compareTo(((Openable) a).getElementName());
			}
		});

		IType focusType = getType();
		boolean inProjectOfFocusType = focusType != null && focusType.getJavaProject().equals(project);
		org.eclipse.jdt.core.ICompilationUnit[] unitsToLookInside = null;
		if (inProjectOfFocusType) {
			org.eclipse.jdt.core.ICompilationUnit unitToLookInside = focusType.getCompilationUnit();
			if (unitToLookInside != null) {
				int wcLength = workingCopies == null ? 0 : workingCopies.length;
				if (wcLength == 0) {
					unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[] {unitToLookInside};
				} else {
					unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[wcLength+1];
					unitsToLookInside[0] = unitToLookInside;
					System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength);
				}
			} else {
				unitsToLookInside = workingCopies;
			}
		}

		SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside);
		this.nameLookup = searchableEnvironment.nameLookup;
		Map options = project.getOptions(true);
		// disable task tags to speed up parsing
		options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
		this.hierarchyResolver =
			new HierarchyResolver(searchableEnvironment, options, this, new DefaultProblemFactory());
		if (focusType != null) {
			Member declaringMember = ((Member)focusType).getOuterMostLocalContext();
			if (declaringMember == null) {
				// top level or member type
				if (!inProjectOfFocusType) {
					char[] typeQualifiedName = focusType.getTypeQualifiedName('.').toCharArray();
					String[] packageName = ((PackageFragment) focusType.getPackageFragment()).names;
					if (searchableEnvironment.findType(typeQualifiedName, Util.toCharArrays(packageName)) == null) {
						// focus type is not visible in this project: no need to go further
						return;
					}
				}
			} else {
				// local or anonymous type
				Openable openable;
				if (declaringMember.isBinary()) {
					openable = (Openable)declaringMember.getClassFile();
				} else {
					openable = (Openable)declaringMember.getCompilationUnit();
				}
				localTypes = new HashSet();
				localTypes.add(openable.getPath().toString());
				this.hierarchyResolver.resolve(new Openable[] {openable}, localTypes, monitor);
				return;
			}
		}
		this.hierarchyResolver.resolve(openables, localTypes, monitor);
	}
}
 
Example #16
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public CompilationUnitDeclaration parseCompilationUnit(char[] source, Map settings, boolean recordParsingInformation) {
	if (source == null) {
		throw new IllegalArgumentException();
	}
	CompilerOptions compilerOptions = new CompilerOptions(settings);
	compilerOptions.ignoreMethodBodies = this.ignoreMethodBodies;
	CommentRecorderParser parser =
		new CommentRecorderParser(
			new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				compilerOptions,
				new DefaultProblemFactory(Locale.getDefault())),
		false);

	ICompilationUnit sourceUnit =
		new CompilationUnit(
			source,
			"", //$NON-NLS-1$
			compilerOptions.defaultEncoding);
	final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
	CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult);

	if (recordParsingInformation) {
		this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments);
	}

	if (compilationUnitDeclaration.ignoreMethodBodies) {
		compilationUnitDeclaration.ignoreFurtherInvestigation = true;
		// if initial diet parse did not work, no need to dig into method bodies.
		return compilationUnitDeclaration;
	}

	//fill the methods bodies in order for the code to be generated
	//real parse of the method....
	parser.scanner.setSource(compilationResult);
	org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
	if (types != null) {
		for (int i = 0, length = types.length; i < length; i++) {
			types[i].parseMethods(parser, compilationUnitDeclaration);
		}
	}

	if (recordParsingInformation) {
		this.recordedParsingInformation.updateRecordedParsingInformation(compilationResult);
	}
	return compilationUnitDeclaration;
}
 
Example #17
Source File: CodeSnippetParsingUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public ConstructorDeclaration parseStatements(
		char[] source,
		int offset,
		int length,
		Map settings,
		boolean recordParsingInformation,
		boolean enabledStatementRecovery) {
	if (source == null) {
		throw new IllegalArgumentException();
	}
	CompilerOptions compilerOptions = new CompilerOptions(settings);
	// in this case we don't want to ignore method bodies since we are parsing only statements
	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);

	final CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
	CompilationUnitDeclaration compilationUnitDeclaration = new CompilationUnitDeclaration(problemReporter, compilationResult, length);

	ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult);
	constructorDeclaration.sourceEnd  = -1;
	constructorDeclaration.declarationSourceEnd = offset + length - 1;
	constructorDeclaration.bodyStart = offset;
	constructorDeclaration.bodyEnd = offset + length - 1;

	parser.scanner.setSource(compilationResult);
	parser.scanner.resetTo(offset, offset + length);
	parser.parse(constructorDeclaration, compilationUnitDeclaration, true);

	if (recordParsingInformation) {
		this.recordedParsingInformation = getRecordedParsingInformation(compilationResult, compilationUnitDeclaration.comments);
	}
	return constructorDeclaration;
}
 
Example #18
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void parse(ICompilationUnit[] compilationUnits, ASTRequestor astRequestor, int apiLevel, Map options, int flags, IProgressMonitor monitor) {
	try {
		CompilerOptions compilerOptions = new CompilerOptions(options);
		compilerOptions.ignoreMethodBodies = (flags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
		Parser parser = new CommentRecorderParser(
			new ProblemReporter(
					DefaultErrorHandlingPolicies.proceedWithAllProblems(),
					compilerOptions,
					new DefaultProblemFactory()),
			false);
		int unitLength = compilationUnits.length;
		if (monitor != null) monitor.beginTask("", unitLength); //$NON-NLS-1$
		for (int i = 0; i < unitLength; i++) {
			org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) compilationUnits[i];
			CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
			CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult);

			if (compilationUnitDeclaration.ignoreMethodBodies) {
				compilationUnitDeclaration.ignoreFurtherInvestigation = true;
				// if initial diet parse did not work, no need to dig into method bodies.
				continue;
			}

			//fill the methods bodies in order for the code to be generated
			//real parse of the method....
			org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
			if (types != null) {
				for (int j = 0, typeLength = types.length; j < typeLength; j++) {
					types[j].parseMethods(parser, compilationUnitDeclaration);
				}
			}

			// convert AST
			CompilationUnit node = convert(compilationUnitDeclaration, parser.scanner.getSource(), apiLevel, options, false/*don't resolve binding*/, null/*no owner needed*/, null/*no binding table needed*/, flags /* flags */, monitor, true);
			node.setTypeRoot(compilationUnits[i]);

			// accept AST
			astRequestor.acceptAST(compilationUnits[i], node);

			if (monitor != null) monitor.worked(1);
		}
	} finally {
		if (monitor != null) monitor.done();
	}
}
 
Example #19
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void parse(
		String[] sourceUnits,
		String[] encodings,
		FileASTRequestor astRequestor,
		int apiLevel,
		Map options,
		int flags,
		IProgressMonitor monitor) {
	try {
		CompilerOptions compilerOptions = new CompilerOptions(options);
		compilerOptions.ignoreMethodBodies = (flags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
		Parser parser = new CommentRecorderParser(
			new ProblemReporter(
					DefaultErrorHandlingPolicies.proceedWithAllProblems(),
					compilerOptions,
					new DefaultProblemFactory()),
			false);
		int unitLength = sourceUnits.length;
		if (monitor != null) monitor.beginTask("", unitLength); //$NON-NLS-1$
		for (int i = 0; i < unitLength; i++) {
			char[] contents = null;
			String encoding = encodings != null ? encodings[i] : null;
			try {
				contents = Util.getFileCharContent(new File(sourceUnits[i]), encoding);
			} catch(IOException e) {
				// go to the next unit
				continue;
			}
			if (contents == null) {
				// go to the next unit
				continue;
			}
			org.eclipse.jdt.internal.compiler.batch.CompilationUnit compilationUnit = new org.eclipse.jdt.internal.compiler.batch.CompilationUnit(contents, sourceUnits[i], encoding);
			org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit = compilationUnit;
			CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
			CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult);

			if (compilationUnitDeclaration.ignoreMethodBodies) {
				compilationUnitDeclaration.ignoreFurtherInvestigation = true;
				// if initial diet parse did not work, no need to dig into method bodies.
				continue;
			}

			//fill the methods bodies in order for the code to be generated
			//real parse of the method....
			org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
			if (types != null) {
				for (int j = 0, typeLength = types.length; j < typeLength; j++) {
					types[j].parseMethods(parser, compilationUnitDeclaration);
				}
			}

			// convert AST
			CompilationUnit node = convert(compilationUnitDeclaration, parser.scanner.getSource(), apiLevel, options, false/*don't resolve binding*/, null/*no owner needed*/, null/*no binding table needed*/, flags /* flags */, monitor, true);
			node.setTypeRoot(null);

			// accept AST
			astRequestor.acceptAST(sourceUnits[i], node);

			if (monitor != null) monitor.worked(1);
		}
	} finally {
		if (monitor != null) monitor.done();
	}
}
 
Example #20
Source File: CompilationUnitResolver.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static CompilationUnitDeclaration parse(
		org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit,
		NodeSearcher nodeSearcher,
		Map settings,
		int flags) {
	if (sourceUnit == null) {
		throw new IllegalStateException();
	}
	CompilerOptions compilerOptions = new CompilerOptions(settings);
	boolean statementsRecovery = (flags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0;
	compilerOptions.performMethodsFullRecovery = statementsRecovery;
	compilerOptions.performStatementsRecovery = statementsRecovery;
	compilerOptions.ignoreMethodBodies = (flags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
	Parser parser = new CommentRecorderParser(
		new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				compilerOptions,
				new DefaultProblemFactory()),
		false);
	CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, compilerOptions.maxProblemsPerUnit);
	CompilationUnitDeclaration compilationUnitDeclaration = parser.dietParse(sourceUnit, compilationResult);

	if (compilationUnitDeclaration.ignoreMethodBodies) {
		compilationUnitDeclaration.ignoreFurtherInvestigation = true;
		// if initial diet parse did not work, no need to dig into method bodies.
		return compilationUnitDeclaration;
	}

	if (nodeSearcher != null) {
		char[] source = parser.scanner.getSource();
		int searchPosition = nodeSearcher.position;
		if (searchPosition < 0 || searchPosition > source.length) {
			// the position is out of range. There is no need to search for a node.
			return compilationUnitDeclaration;
		}

		compilationUnitDeclaration.traverse(nodeSearcher, compilationUnitDeclaration.scope);

		org.eclipse.jdt.internal.compiler.ast.ASTNode node = nodeSearcher.found;
		if (node == null) {
			return compilationUnitDeclaration;
		}

		org.eclipse.jdt.internal.compiler.ast.TypeDeclaration enclosingTypeDeclaration = nodeSearcher.enclosingType;

		if (node instanceof AbstractMethodDeclaration) {
			((AbstractMethodDeclaration)node).parseStatements(parser, compilationUnitDeclaration);
		} else if (enclosingTypeDeclaration != null) {
			if (node instanceof org.eclipse.jdt.internal.compiler.ast.Initializer) {
				((org.eclipse.jdt.internal.compiler.ast.Initializer) node).parseStatements(parser, enclosingTypeDeclaration, compilationUnitDeclaration);
			} else if (node instanceof org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) {
				((org.eclipse.jdt.internal.compiler.ast.TypeDeclaration)node).parseMethods(parser, compilationUnitDeclaration);
			}
		}
	} else {
			//fill the methods bodies in order for the code to be generated
			//real parse of the method....			
			org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = compilationUnitDeclaration.types;
			if (types != null) {
				for (int j = 0, typeLength = types.length; j < typeLength; j++) {
					types[j].parseMethods(parser, compilationUnitDeclaration);
				}
			}
	}
	return compilationUnitDeclaration;
}
 
Example #21
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 #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;
}