org.eclipse.jdt.internal.compiler.parser.Parser Java Examples

The following examples show how to use org.eclipse.jdt.internal.compiler.parser.Parser. 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: CompilationUtils.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * <p>compileSource.</p>
 *
 * @param source a {@link java.lang.String} object.
 * @return a {@link ch.uzh.ifi.seal.changedistiller.ast.java.JavaCompilation} object.
 */
public static JavaCompilation compileSource(String source) {

	//Compiler Options
    CompilerOptions options = getDefaultCompilerOptions();

    //CommentRecorder
    Parser parser = createCommentRecorderParser(options);

    //Create Compilation Unit from Source
    ICompilationUnit cu = createCompilationunit(source, "");

    //Compilation Result
    CompilationResult compilationResult = createDefaultCompilationResult(cu, options);

    return new JavaCompilation(parser.parse(cu, compilationResult), parser.scanner);
}
 
Example #3
Source File: CompletionUnitStructureRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public CompletionUnitStructureRequestor(
		ICompilationUnit unit,
		CompilationUnitElementInfo unitInfo,
		Parser parser,
		ASTNode assistNode,
		Map bindingCache,
		Map elementCache,
		Map elementWithProblemCache,
		Map newElements) {
	super(unit, unitInfo, newElements);
	this.parser = parser;
	this.assistNode = assistNode;
	this.bindingCache = bindingCache;
	this.elementCache = elementCache;
	this.elementWithProblemCache = elementWithProblemCache;
}
 
Example #4
Source File: CompilationUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
   * Returns the generated {@link JavaCompilation} from the file identified by the given filename.
   *
   * @param _filename
   *            of the file to compile
   * @return the compilation of the file
   */
  public static JavaCompilation compileFile(String _filename) {
  	JavaCompilation jc = null;
try {
	final String src = FileUtil.readFile(_filename);
	final CompilerOptions options = getDefaultCompilerOptions();
       final Parser parser = createCommentRecorderParser(options);
       final ICompilationUnit cu = createCompilationunit(src, _filename);
       final CompilationResult compilationResult = createDefaultCompilationResult(cu, options);
       jc = new JavaCompilation(parser.parse(cu, compilationResult), parser.scanner);
} catch (IOException e) {
	log.error(e);
}
return jc;
  }
 
Example #5
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 #6
Source File: TransformEclipseAST.java    From EasyMPermission with MIT License 5 votes vote down vote up
/**
 * This method is called immediately after Eclipse finishes building a CompilationUnitDeclaration, which is
 * the top-level AST node when Eclipse parses a source file. The signature is 'magic' - you should not
 * change it!
 * 
 * Eclipse's parsers often operate in diet mode, which means many parts of the AST have been left blank.
 * Be ready to deal with just about anything being null, such as the Statement[] arrays of the Method AST nodes.
 * 
 * @param parser The Eclipse parser object that generated the AST. Not actually used; mostly there to satisfy parameter rules for lombok.patcher scripts.
 * @param ast The AST node belonging to the compilation unit (java speak for a single source file).
 */
public static void transform(Parser parser, CompilationUnitDeclaration ast) {
	if (disableLombok) return;
	
	if (Symbols.hasSymbol("lombok.disable")) return;
	
	// Do NOT abort if (ast.bits & ASTNode.HasAllMethodBodies) != 0 - that doesn't work.
	
	try {
		DebugSnapshotStore.INSTANCE.snapshot(ast, "transform entry");
		long histoToken = lombokTracker == null ? 0L : lombokTracker.start();
		EclipseAST existing = getAST(ast, false);
		new TransformEclipseAST(existing).go();
		if (lombokTracker != null) lombokTracker.end(histoToken);
		DebugSnapshotStore.INSTANCE.snapshot(ast, "transform exit");
	} catch (Throwable t) {
		DebugSnapshotStore.INSTANCE.snapshot(ast, "transform error: %s", t.getClass().getSimpleName());
		try {
			String message = "Lombok can't parse this source: " + t.toString();
			
			EclipseAST.addProblemToCompilationResult(ast.getFileName(), ast.compilationResult, false, message, 0, 0);
			t.printStackTrace();
		} catch (Throwable t2) {
			try {
				error(ast, "Can't create an error in the problems dialog while adding: " + t.toString(), t2);
			} catch (Throwable t3) {
				//This seems risky to just silently turn off lombok, but if we get this far, something pretty
				//drastic went wrong. For example, the eclipse help system's JSP compiler will trigger a lombok call,
				//but due to class loader shenanigans we'll actually get here due to a cascade of
				//ClassNotFoundErrors. This is the right action for the help system (no lombok needed for that JSP compiler,
				//of course). 'disableLombok' is static, but each context classloader (e.g. each eclipse OSGi plugin) has
				//it's own edition of this class, so this won't turn off lombok everywhere.
				disableLombok = true;
			}
		}
	}
}
 
Example #7
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 #8
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 #9
Source File: DiagnoseParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int[] getNTermTemplate(int sym) {
	int templateIndex = Parser.recovery_templates_index[sym];
   	if(templateIndex > 0) {
   		int[] result = new int[Parser.recovery_templates.length];
   		int count = 0;
   		for(int j = templateIndex; Parser.recovery_templates[j] != 0; j++) {
   			result[count++] = Parser.recovery_templates[j];
   		}
   		System.arraycopy(result, 0, result = new int[count], 0, count);
   		return result;
   	} else {
       	return null;
   	}
}
 
Example #10
Source File: DiagnoseParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getNtermIndex(int start, int sym, int buffer_position) {
	int highest_symbol = sym - NT_OFFSET,
		tok = this.lexStream.kind(this.buffer[buffer_position]);
	this.lexStream.reset(this.buffer[buffer_position + 1]);

	//
	// Initialize stack index of temp_stack and initialize maximum
	// position of state stack that is still useful.
	//
	this.tempStackTop = 0;
	this.tempStack[this.tempStackTop] = start;

	int act = Parser.ntAction(start, highest_symbol);
	if (act > NUM_RULES) { // goto action?
		this.tempStack[this.tempStackTop + 1] = act;
		act = Parser.tAction(act, tok);
	}

	while(act <= NUM_RULES) {
		//
		// Process all goto-reduce actions following reduction,
		// until a goto action is computed ...
		//
		do {
			this.tempStackTop -= (Parser.rhs[act]-1);
			if (this.tempStackTop < 0)
				return Parser.non_terminal_index[highest_symbol];
			if (this.tempStackTop == 0)
				highest_symbol = Parser.lhs[act];
			act = Parser.ntAction(this.tempStack[this.tempStackTop], Parser.lhs[act]);
		} while(act <= NUM_RULES);
		this.tempStack[this.tempStackTop + 1] = act;
		act = Parser.tAction(act, tok);
	}

	return Parser.non_terminal_index[highest_symbol];
}
 
Example #11
Source File: Clinit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
	//the clinit is filled by hand ....
}
 
Example #12
Source File: AnnotationMethodDeclaration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
	// nothing to do
	// annotation type member declaration don't have any body
}
 
Example #13
Source File: MethodDeclaration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void parseStatements(Parser parser, CompilationUnitDeclaration unit) {
	//fill up the method body with statement
	parser.parse(this, unit);
}
 
Example #14
Source File: ReferenceExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void generateImplicitLambda(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
	
	final Parser parser = new Parser(this.enclosingScope.problemReporter(), false);
	final char[] source = this.compilationResult.getCompilationUnit().getContents();
	ReferenceExpression copy =  (ReferenceExpression) parser.parseExpression(source, this.sourceStart, this.sourceEnd - this.sourceStart + 1, 
									this.enclosingScope.referenceCompilationUnit(), false /* record line separators */);
	
	int argc = this.descriptor.parameters.length;
	
	LambdaExpression implicitLambda = new LambdaExpression(this.compilationResult, false);
	Argument [] arguments = new Argument[argc];
	for (int i = 0; i < argc; i++)
		arguments[i] = new Argument(("arg" + i).toCharArray(), 0, null, 0, true); //$NON-NLS-1$
	implicitLambda.setArguments(arguments);
	implicitLambda.setExpressionContext(this.expressionContext);
	implicitLambda.setExpectedType(this.expectedType);
	
	int parameterShift = this.receiverPrecedesParameters ? 1 : 0;
	Expression [] argv = new SingleNameReference[argc - parameterShift];
	for (int i = 0, length = argv.length; i < length; i++) {
		String name = "arg" + (i + parameterShift); //$NON-NLS-1$
		argv[i] = new SingleNameReference(name.toCharArray(), 0);
	}
	if (isMethodReference()) {
		MessageSend message = new MessageSend();
		message.selector = this.selector;
		message.receiver = this.receiverPrecedesParameters ? new SingleNameReference("arg0".toCharArray(), 0) : copy.lhs; //$NON-NLS-1$
		message.typeArguments = copy.typeArguments;
		message.arguments = argv;
		implicitLambda.setBody(message);
	} else if (isArrayConstructorReference()) {
		// We don't care for annotations, source positions etc. They are immaterial, just drop.
		ArrayAllocationExpression arrayAllocationExpression = new ArrayAllocationExpression();
		arrayAllocationExpression.dimensions = new Expression[] { argv[0] };
		if (this.lhs instanceof ArrayTypeReference) {
			ArrayTypeReference arrayTypeReference = (ArrayTypeReference) this.lhs;
			arrayAllocationExpression.type = arrayTypeReference.dimensions == 1 ? new SingleTypeReference(arrayTypeReference.token, 0L) : 
															new ArrayTypeReference(arrayTypeReference.token, arrayTypeReference.dimensions - 1, 0L);
		} else {
			ArrayQualifiedTypeReference arrayQualifiedTypeReference = (ArrayQualifiedTypeReference) this.lhs;
			arrayAllocationExpression.type = arrayQualifiedTypeReference.dimensions == 1 ? new QualifiedTypeReference(arrayQualifiedTypeReference.tokens, arrayQualifiedTypeReference.sourcePositions)
															: new ArrayQualifiedTypeReference(arrayQualifiedTypeReference.tokens, arrayQualifiedTypeReference.dimensions - 1, 
																	arrayQualifiedTypeReference.sourcePositions);
		}
		implicitLambda.setBody(arrayAllocationExpression);
	} else {
		AllocationExpression allocation = new AllocationExpression();
		if (this.lhs instanceof TypeReference) {
			allocation.type = (TypeReference) this.lhs;
		} else if (this.lhs instanceof SingleNameReference) {
			allocation.type = new SingleTypeReference(((SingleNameReference) this.lhs).token, 0);
		} else if (this.lhs instanceof QualifiedNameReference) {
			allocation.type = new QualifiedTypeReference(((QualifiedNameReference) this.lhs).tokens, new long [((QualifiedNameReference) this.lhs).tokens.length]);
		} else {
			throw new IllegalStateException("Unexpected node type"); //$NON-NLS-1$
		}
		allocation.typeArguments = copy.typeArguments;
		allocation.arguments = argv;
		implicitLambda.setBody(allocation);
	}
	
	// Process the lambda, taking care not to double report diagnostics. Don't expect any from resolve, Any from code generation should surface, but not those from flow analysis.
	implicitLambda.resolve(currentScope);
	IErrorHandlingPolicy oldPolicy = currentScope.problemReporter().switchErrorHandlingPolicy(silentErrorHandlingPolicy);
	try {
		implicitLambda.analyseCode(currentScope, 
				new ExceptionHandlingFlowContext(null, this, Binding.NO_EXCEPTIONS, null, currentScope, FlowInfo.DEAD_END), 
				UnconditionalFlowInfo.fakeInitializedFlowInfo(currentScope.outerMostMethodScope().analysisIndex, currentScope.referenceType().maxFieldCount));
	} finally {
		currentScope.problemReporter().switchErrorHandlingPolicy(oldPolicy);
	}
	SyntheticArgumentBinding[] outerLocals = this.receiverType.syntheticOuterLocalVariables();
	for (int i = 0, length = outerLocals == null ? 0 : outerLocals.length; i < length; i++)
		implicitLambda.addSyntheticArgument(outerLocals[i].actualOuterLocalVariable);
	
	implicitLambda.generateCode(currentScope, codeStream, valueRequired);
}
 
Example #15
Source File: DiagnoseParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void secondaryDiagnosis(SecondaryRepairInfo repair) {
	switch(repair.code) {
		case SCOPE_CODE: {
            if (repair.stackPosition < this.stateStackTop) {
                reportError(DELETION_CODE,
                            Parser.terminal_index[ERROR_SYMBOL],
                            this.locationStack[repair.stackPosition],
                            this.buffer[1]);
            }
            for (int i = 0; i < this.scopeStackTop; i++) {
                reportError(SCOPE_CODE,
                            -this.scopeIndex[i],
                            this.locationStack[this.scopePosition[i]],
                            this.buffer[1],
                            Parser.non_terminal_index[Parser.scope_lhs[this.scopeIndex[i]]]);
            }

            repair.symbol = Parser.scope_lhs[this.scopeIndex[this.scopeStackTop]] + NT_OFFSET;
            this.stateStackTop = this.scopePosition[this.scopeStackTop];
            reportError(SCOPE_CODE,
                        -this.scopeIndex[this.scopeStackTop],
                        this.locationStack[this.scopePosition[this.scopeStackTop]],
                        this.buffer[1],
                        getNtermIndex(this.stack[this.stateStackTop],
                                      repair.symbol,
                                      repair.bufferPosition)
                       );
            break;
        }
		default: {
			reportError(repair.code,
						(repair.code == SECONDARY_CODE
									  ? getNtermIndex(this.stack[repair.stackPosition],
													  repair.symbol,
													  repair.bufferPosition)
									  : Parser.terminal_index[ERROR_SYMBOL]),
						this.locationStack[repair.stackPosition],
						this.buffer[repair.bufferPosition - 1]);
			this.stateStackTop = repair.stackPosition;
		}
	}
}
 
Example #16
Source File: DiagnoseParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public DiagnoseParser(Parser parser, int firstToken, int start, int end, int[] intervalStartToSkip, int[] intervalEndToSkip, int[] intervalFlagsToSkip, CompilerOptions options) {
	this.parser = parser;
	this.options = options;
	this.lexStream = new LexStream(BUFF_SIZE, parser.scanner, intervalStartToSkip, intervalEndToSkip, intervalFlagsToSkip, firstToken, start, end);
	this.recoveryScanner = parser.recoveryScanner;
}
 
Example #17
Source File: DiagnoseParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public DiagnoseParser(Parser parser, int firstToken, int start, int end, CompilerOptions options) {
	this(parser, firstToken, start, end, Util.EMPTY_INT_ARRAY, Util.EMPTY_INT_ARRAY, Util.EMPTY_INT_ARRAY, options);
}
 
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 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 #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 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 #21
Source File: SourceJavadocParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public SourceJavadocParser(Parser sourceParser) {
	super(sourceParser);
	this.kind = SOURCE_PARSER | TEXT_VERIF;
}
 
Example #22
Source File: TransformEclipseAST.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static void transform_swapped(CompilationUnitDeclaration ast, Parser parser) {
	transform(parser, ast);
}
 
Example #23
Source File: PatchFixesHider.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static void transform_swapped(CompilationUnitDeclaration ast, Parser parser) throws IOException {
	Util.invokeMethod(TRANSFORM_SWAPPED, ast, parser);
}
 
Example #24
Source File: PatchFixesHider.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static void transform(Parser parser, CompilationUnitDeclaration ast) throws IOException {
	Util.invokeMethod(TRANSFORM, parser, ast);
}