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

The following examples show how to use org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies. 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: 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 #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: Evaluator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates and returns a compiler for this evaluator.
 */
Compiler getCompiler(ICompilerRequestor compilerRequestor) {
	CompilerOptions compilerOptions = new CompilerOptions(this.options);
	compilerOptions.performMethodsFullRecovery = true;
	compilerOptions.performStatementsRecovery = true;
	return new Compiler(
		this.environment,
		DefaultErrorHandlingPolicies.exitAfterAllProblems(),
		compilerOptions,
		compilerRequestor,
		this.problemFactory);
}
 
Example #5
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 #6
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 #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: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected Parser basicParser() {
	if (this.basicParser == null) {
		ProblemReporter problemReporter =
			new ProblemReporter(
				DefaultErrorHandlingPolicies.proceedWithAllProblems(),
				this.options,
				new DefaultProblemFactory());
		this.basicParser = new Parser(problemReporter, false);
		this.basicParser.reportOnlyOneSyntaxError = true;
	}
	return this.basicParser;
}
 
Example #9
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 #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: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Create a new parser for the given project, as well as a lookup environment.
 */
public void initialize(JavaProject project, int possibleMatchSize) throws JavaModelException {
	// clean up name environment only if there are several possible match as it is reused
	// when only one possible match (bug 58581)
	if (this.nameEnvironment != null && possibleMatchSize != 1) {
		this.nameEnvironment.cleanup();
		this.unitScope = null; // don't leak a reference to the cleaned-up name environment
	}

	SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(this.workingCopies);

	// if only one possible match, a file name environment costs too much,
	// so use the existing searchable  environment which will populate the java model
	// only for this possible match and its required types.
	this.nameEnvironment = possibleMatchSize == 1
		? (INameEnvironment) searchableEnvironment
		: (INameEnvironment) new JavaSearchNameEnvironment(project, this.workingCopies);

	// create lookup environment
	Map map = project.getOptions(true);
	map.put(CompilerOptions.OPTION_TaskTags, org.eclipse.jdt.internal.compiler.util.Util.EMPTY_STRING);
	this.options = new CompilerOptions(map);
	ProblemReporter problemReporter =
		new ProblemReporter(
			DefaultErrorHandlingPolicies.proceedWithAllProblems(),
			this.options,
			new DefaultProblemFactory());
	this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, this.nameEnvironment);
	this.lookupEnvironment.mayTolerateMissingType = true;
	this.parser = MatchLocatorParser.createParser(problemReporter, this);

	// basic parser needs also to be reset as project options may have changed
	// see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=163072
	this.basicParser = null;

	// remember project's name lookup
	this.nameLookup = searchableEnvironment.nameLookup;

	// initialize queue of units
	this.numberOfMatches = 0;
	this.matchesToProcess = new PossibleMatch[possibleMatchSize];

	this.lookupEnvironment.addResolutionListener(this.patternLocator);
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
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;
}