Java Code Examples for org.eclipse.jdt.core.dom.ASTParser#setStatementsRecovery()

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#setStatementsRecovery() . 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: OverrideCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) {
	CompilationUnit ast = CoreASTProvider.getInstance().getAST(fCompilationUnit, CoreASTProvider.WAIT_YES, null);
	if (ast != null) {
		recoveredDocument.set(document.get());
		return ast;
	}

	char[] content= document.get().toCharArray();

	// clear prefix to avoid compile errors
	int index= offset - 1;
	while (index >= 0 && Character.isJavaIdentifierPart(content[index])) {
		content[index]= ' ';
		index--;
	}

	recoveredDocument.set(new String(content));

	final ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);
	parser.setSource(content);
	parser.setUnitName(fCompilationUnit.getElementName());
	parser.setProject(fCompilationUnit.getJavaProject());
	return (CompilationUnit) parser.createAST(new NullProgressMonitor());
}
 
Example 2
Source File: ASTParserFactory.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected final ASTParser createDefaultJavaParser(final String javaVersion) {
  ASTParser parser = null;
  final Hashtable<String, String> options = JavaCore.getOptions();
  try {
    parser = ASTParser.newParser(ASTParserFactory.asJLS(javaVersion));
    JavaCore.setComplianceOptions(javaVersion, options);
  } catch (final Throwable _t) {
    if (_t instanceof IllegalArgumentException) {
      parser = ASTParser.newParser(ASTParserFactory.asJLS(this.minParserApiLevel));
      JavaCore.setComplianceOptions(this.minParserApiLevel, options);
    } else {
      throw Exceptions.sneakyThrow(_t);
    }
  }
  options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
  parser.setCompilerOptions(options);
  parser.setStatementsRecovery(true);
  parser.setResolveBindings(true);
  parser.setBindingsRecovery(true);
  return parser;
}
 
Example 3
Source File: OverrideCompletionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) {
	CompilationUnit ast= SharedASTProvider.getAST(fCompilationUnit, SharedASTProvider.WAIT_ACTIVE_ONLY, null);
	if (ast != null) {
		recoveredDocument.set(document.get());
		return ast;
	}

	char[] content= document.get().toCharArray();

	// clear prefix to avoid compile errors
	int index= offset - 1;
	while (index >= 0 && Character.isJavaIdentifierPart(content[index])) {
		content[index]= ' ';
		index--;
	}

	recoveredDocument.set(new String(content));

	final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);
	parser.setSource(content);
	parser.setUnitName(fCompilationUnit.getElementName());
	parser.setProject(fCompilationUnit.getJavaProject());
	return (CompilationUnit) parser.createAST(new NullProgressMonitor());
}
 
Example 4
Source File: SourceCompiler.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static ASTParser createParser(String sourceVersion) {
		ASTParser parser = ASTParser.newParser(AST.JLS10);

		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		parser.setResolveBindings(true);
		//TODO
//		parser.setUnitName(unitName);
		parser.setBindingsRecovery(true);
		parser.setStatementsRecovery(true);

		Map options = JavaCore.getOptions();
		
		options.put(JavaCore.COMPILER_COMPLIANCE, sourceVersion);
		options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, sourceVersion);
		options.put(JavaCore.COMPILER_SOURCE, sourceVersion);

		parser.setCompilerOptions(options);

		return parser;
	}
 
Example 5
Source File: PasteAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static List<ParsedCu> parseCus(IJavaProject javaProject, String compilerCompliance, String text) {
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	if (javaProject != null) {
		parser.setProject(javaProject);
	} else if (compilerCompliance != null) {
		Map<String, String> options= JavaCore.getOptions();
		JavaModelUtil.setComplianceOptions(options, compilerCompliance);
		parser.setCompilerOptions(options);
	}
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	CompilationUnit unit= (CompilationUnit) parser.createAST(null);

	if (unit.types().size() > 0)
		return parseAsTypes(text, unit);

	parser.setProject(javaProject);
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
	ASTNode root= parser.createAST(null);
	if (root instanceof TypeDeclaration) {
		List<BodyDeclaration> bodyDeclarations= ((TypeDeclaration) root).bodyDeclarations();
		if (bodyDeclarations.size() > 0)
			return Collections.singletonList(new ParsedCu(text, ASTParser.K_CLASS_BODY_DECLARATIONS, null, null));
	}

	parser.setProject(javaProject);
	parser.setSource(text.toCharArray());
	parser.setStatementsRecovery(true);
	parser.setKind(ASTParser.K_STATEMENTS);
	root= parser.createAST(null);
	if (root instanceof Block) {
		List<Statement> statements= ((Block) root).statements();
		if (statements.size() > 0)
			return Collections.singletonList(new ParsedCu(text, ASTParser.K_STATEMENTS, null, null));
	}

	return Collections.emptyList();
}
 
Example 6
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static CompilationUnit createQuickFixAST(ICompilationUnit compilationUnit, IProgressMonitor monitor) {
	ASTParser astParser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	astParser.setSource(compilationUnit);
	astParser.setResolveBindings(true);
	astParser.setStatementsRecovery(ASTProvider.SHARED_AST_STATEMENT_RECOVERY);
	astParser.setBindingsRecovery(ASTProvider.SHARED_BINDING_RECOVERY);
	return (CompilationUnit) astParser.createAST(monitor);
}
 
Example 7
Source File: LazyGenericTypeProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the type binding of the expected type as it is contained in the
 * code completion context.
 *
 * @return the binding of the expected type
 */
private ITypeBinding getExpectedType() {
	char[][] chKeys= fInvocationContext.getCoreContext().getExpectedTypesKeys();
	if (chKeys == null || chKeys.length == 0)
		return null;

	String[] keys= new String[chKeys.length];
	for (int i= 0; i < keys.length; i++) {
		keys[i]= String.valueOf(chKeys[0]);
	}

	final ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setProject(fCompilationUnit.getJavaProject());
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);

	final Map<String, IBinding> bindings= new HashMap<String, IBinding>();
	ASTRequestor requestor= new ASTRequestor() {
		@Override
		public void acceptBinding(String bindingKey, IBinding binding) {
			bindings.put(bindingKey, binding);
		}
	};
	parser.createASTs(new ICompilationUnit[0], keys, requestor, null);

	if (bindings.size() > 0)
		return (ITypeBinding) bindings.get(keys[0]);

	return null;
}
 
Example 8
Source File: CleanUpRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ASTParser createCleanUpASTParser() {
	ASTParser result= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);

	result.setResolveBindings(true);
	result.setStatementsRecovery(ASTProvider.SHARED_AST_STATEMENT_RECOVERY);
	result.setBindingsRecovery(ASTProvider.SHARED_BINDING_RECOVERY);

	return result;
}
 
Example 9
Source File: CompletionProposalReplacementProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private ITypeBinding getExpectedTypeForGenericParameters() {
	char[][] chKeys= context.getExpectedTypesKeys();
	if (chKeys == null || chKeys.length == 0) {
		return null;
	}

	String[] keys= new String[chKeys.length];
	for (int i= 0; i < keys.length; i++) {
		keys[i]= String.valueOf(chKeys[0]);
	}

	final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setProject(compilationUnit.getJavaProject());
	parser.setResolveBindings(true);
	parser.setStatementsRecovery(true);

	final Map<String, IBinding> bindings= new HashMap<>();
	ASTRequestor requestor= new ASTRequestor() {
		@Override
		public void acceptBinding(String bindingKey, IBinding binding) {
			bindings.put(bindingKey, binding);
		}
	};
	parser.createASTs(new ICompilationUnit[0], keys, requestor, null);

	if (bindings.size() > 0) {
		return (ITypeBinding) bindings.get(keys[0]);
	}

	return null;
}
 
Example 10
Source File: JavaASTExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Get the AST of a file, including additional source paths to resolve
 * cross-file bindings. It is assumed that a CompilationUnit will be
 * returned. A heuristic is used to set the file's path variable.
 * <p>
 * Note: this may only yield a big improvement if the above heuristic fails
 * and srcPaths contains the correct source path.
 *
 * @param file
 * @param srcPaths
 *            for binding resolution
 * @return the compilation unit of the file
 * @throws IOException
 */
public final CompilationUnit getAST(final File file,
		final Set<String> srcPaths) throws IOException {
	final String sourceFile = FileUtils.readFileToString(file);
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);

	final Map<String, String> options = new Hashtable<String, String>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
			JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	if (useJavadocs) {
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	}
	parser.setCompilerOptions(options);
	parser.setSource(sourceFile.toCharArray()); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	parser.setUnitName(file.getAbsolutePath());

	// Heuristic to retrieve source file path
	final String srcFilePath;
	if (file.getAbsolutePath().contains("/src")) {
		srcFilePath = file.getAbsolutePath().substring(0,
				file.getAbsolutePath().indexOf("src", 0) + 3);
	} else {
		srcFilePath = "";
	}

	// Add file to source paths if not already present
	srcPaths.add(srcFilePath);

	final String[] sourcePathEntries = srcPaths.toArray(new String[srcPaths
			.size()]);
	final String[] classPathEntries = new String[0];
	parser.setEnvironment(classPathEntries, sourcePathEntries, null, true);

	final CompilationUnit compilationUnit = (CompilationUnit) parser
			.createAST(null);
	return compilationUnit;
}
 
Example 11
Source File: JavaASTExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @param content
 * @return
 */
public final ASTNode getASTNode(final char[] content,
		final ParseType parseType) {
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	final int astKind;
	switch (parseType) {
	case CLASS_BODY:
	case METHOD:
		astKind = ASTParser.K_CLASS_BODY_DECLARATIONS;
		break;
	case COMPILATION_UNIT:
		astKind = ASTParser.K_COMPILATION_UNIT;
		break;
	case EXPRESSION:
		astKind = ASTParser.K_EXPRESSION;
		break;
	case STATEMENTS:
		astKind = ASTParser.K_STATEMENTS;
		break;
	default:
		astKind = ASTParser.K_COMPILATION_UNIT;
	}
	parser.setKind(astKind);

	final Map<String, String> options = new Hashtable<String, String>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
			JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	if (useJavadocs) {
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	}
	parser.setCompilerOptions(options);
	parser.setSource(content); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	if (parseType != ParseType.METHOD) {
		return parser.createAST(null);
	} else {
		final ASTNode cu = parser.createAST(null);
		return getFirstMethodDeclaration(cu);
	}
}
 
Example 12
Source File: JavaASTExtractor.java    From api-mining with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @param content
 * @return
 */
public final ASTNode getASTNode(final char[] content,
		final ParseType parseType) {
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	final int astKind;
	switch (parseType) {
	case CLASS_BODY:
	case METHOD:
		astKind = ASTParser.K_CLASS_BODY_DECLARATIONS;
		break;
	case COMPILATION_UNIT:
		astKind = ASTParser.K_COMPILATION_UNIT;
		break;
	case EXPRESSION:
		astKind = ASTParser.K_EXPRESSION;
		break;
	case STATEMENTS:
		astKind = ASTParser.K_STATEMENTS;
		break;
	default:
		astKind = ASTParser.K_COMPILATION_UNIT;
	}
	parser.setKind(astKind);

	final Map<String, String> options = new Hashtable<String, String>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
			JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	if (useJavadocs) {
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	}
	parser.setCompilerOptions(options);
	parser.setSource(content); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	if (parseType != ParseType.METHOD) {
		return parser.createAST(null);
	} else {
		final ASTNode cu = parser.createAST(null);
		return getFirstMethodDeclaration(cu);
	}
}
 
Example 13
Source File: JavaASTExtractor.java    From api-mining with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get the AST of a file, including additional source paths to resolve
 * cross-file bindings. It is assumed that a CompilationUnit will be
 * returned. A heuristic is used to set the file's path variable.
 * <p>
 * Note: this may only yield a big improvement if the above heuristic fails
 * and srcPaths contains the correct source path.
 *
 * @param file
 * @param srcPaths
 *            for binding resolution
 * @return the compilation unit of the file
 * @throws IOException
 */
public final CompilationUnit getAST(final File file,
		final Set<String> srcPaths) throws IOException {
	final String sourceFile = FileUtils.readFileToString(file);
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);

	final Map<String, String> options = new Hashtable<String, String>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
			JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	if (useJavadocs) {
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	}
	parser.setCompilerOptions(options);
	parser.setSource(sourceFile.toCharArray()); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	parser.setUnitName(file.getAbsolutePath());

	// Heuristic to retrieve source file path
	final String srcFilePath;
	if (file.getAbsolutePath().contains("/src")) {
		srcFilePath = file.getAbsolutePath().substring(0,
				file.getAbsolutePath().indexOf("src", 0) + 3);
	} else {
		srcFilePath = "";
	}

	// Add file to source paths if not already present
	srcPaths.add(srcFilePath);

	final String[] sourcePathEntries = srcPaths.toArray(new String[srcPaths
			.size()]);
	final String[] classPathEntries = new String[0];
	parser.setEnvironment(classPathEntries, sourcePathEntries, null, true);

	final CompilationUnit compilationUnit = (CompilationUnit) parser
			.createAST(null);
	return compilationUnit;
}
 
Example 14
Source File: JavaASTParser.java    From KodeBeagle with Apache License 2.0 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @param content
 * @return
 */
public final ASTNode getASTNode(final char[] content,
                                final ParseType parseType) {
    final ASTParser parser = ASTParser.newParser(AST.JLS8);
    final int astKind;
    switch (parseType) {
        case CLASS_BODY:
        case METHOD:
            astKind = ASTParser.K_CLASS_BODY_DECLARATIONS;
            break;
        case COMPILATION_UNIT:
            astKind = ASTParser.K_COMPILATION_UNIT;
            break;
        case EXPRESSION:
            astKind = ASTParser.K_EXPRESSION;
            break;
        case STATEMENTS:
            astKind = ASTParser.K_STATEMENTS;
            break;
        default:
            astKind = ASTParser.K_COMPILATION_UNIT;
    }
    parser.setKind(astKind);

    final Map<String, String> options = new HashMap<>();
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
            JavaCore.VERSION_1_8);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
    if (useJavadocs) {
        options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
    }
    parser.setCompilerOptions(options);
    parser.setSource(content);
    parser.setResolveBindings(useBindings);
    parser.setBindingsRecovery(useBindings);
    parser.setStatementsRecovery(true);

    if (parseType != ParseType.METHOD) {
        return parser.createAST(null);
    } else {
        final ASTNode cu = parser.createAST(null);
        return getFirstMethodDeclaration(cu);
    }
}
 
Example 15
Source File: JavaCodeAnalyzer.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
public JavaCodeAnalyzer.JavaParseResult<? extends ASTNode> determinateJavaType(final String javaCode) {
  ASTParser parser = this.parserFactory.createDefaultJavaParser(this.parserFactory.minParserApiLevel);
  parser.setSource(javaCode.toCharArray());
  parser.setStatementsRecovery(true);
  ASTNode _createAST = parser.createAST(null);
  CompilationUnit unit = ((CompilationUnit) _createAST);
  int _size = unit.types().size();
  boolean _greaterThan = (_size > 0);
  if (_greaterThan) {
    List<CompilationUnit> _singletonList = Collections.<CompilationUnit>singletonList(unit);
    return new JavaCodeAnalyzer.JavaParseResult<CompilationUnit>(javaCode, ASTParser.K_COMPILATION_UNIT, _singletonList);
  }
  parser.setSource(javaCode.toCharArray());
  parser.setStatementsRecovery(false);
  parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
  ASTNode root = parser.createAST(null);
  if ((root instanceof TypeDeclaration)) {
    List<BodyDeclaration> bodyDeclarations = ((TypeDeclaration)root).bodyDeclarations();
    int _size_1 = bodyDeclarations.size();
    boolean _greaterThan_1 = (_size_1 > 0);
    if (_greaterThan_1) {
      return new JavaCodeAnalyzer.JavaParseResult<BodyDeclaration>(javaCode, ASTParser.K_CLASS_BODY_DECLARATIONS, bodyDeclarations);
    }
  }
  parser.setSource(javaCode.toCharArray());
  parser.setStatementsRecovery(false);
  parser.setKind(ASTParser.K_STATEMENTS);
  root = parser.createAST(null);
  if ((root instanceof Block)) {
    List<Statement> statements = ((Block)root).statements();
    int _size_2 = statements.size();
    boolean _greaterThan_2 = (_size_2 > 0);
    if (_greaterThan_2) {
      return new JavaCodeAnalyzer.JavaParseResult<Statement>(javaCode, ASTParser.K_STATEMENTS, statements);
    }
  }
  parser.setSource(javaCode.toCharArray());
  parser.setStatementsRecovery(false);
  parser.setKind(ASTParser.K_EXPRESSION);
  root = parser.createAST(null);
  if ((root instanceof Expression)) {
    List<Expression> _singletonList_1 = Collections.<Expression>singletonList(((Expression)root));
    return new JavaCodeAnalyzer.JavaParseResult<Expression>(javaCode, ASTParser.K_EXPRESSION, _singletonList_1);
  }
  return null;
}
 
Example 16
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS3 JLS3} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS3}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @deprecated JLS3 has been deprecated. This method has been replaced by {@link #getAST4()} which returns an AST
 * with JLS4 level.
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST3() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS3 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example 17
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS4 JLS4} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS4}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @deprecated JLS4 has been deprecated. This method has been replaced by {@link #getAST8()} which returns an AST
 * with JLS8 level.
 * @since 3.7.1
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST4() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS4 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS4);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example 18
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS8 JLS8} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS8}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @since 3.10
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST8() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS8 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example 19
Source File: JavaASTExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Get the AST of a file, including additional source paths to resolve
 * cross-file bindings. It is assumed that a CompilationUnit will be
 * returned. A heuristic is used to set the file's path variable.
 * <p>
 * Note: this may only yield a big improvement if the above heuristic fails
 * and srcPaths contains the correct source path.
 *
 * @param file
 * @param srcPaths
 *            for binding resolution
 * @return the compilation unit of the file
 * @throws IOException
 */
public final CompilationUnit getAST(final File file,
		final Set<String> srcPaths) throws IOException {
	final String sourceFile = FileUtils.readFileToString(file);
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);

	final Map<String, String> options = new Hashtable<String, String>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
			JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	if (useJavadocs) {
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	}
	parser.setCompilerOptions(options);
	parser.setSource(sourceFile.toCharArray()); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	parser.setUnitName(file.getAbsolutePath());

	// Heuristic to retrieve source file path
	final String srcFilePath;
	if (file.getAbsolutePath().contains("/src")) {
		srcFilePath = file.getAbsolutePath().substring(0,
				file.getAbsolutePath().indexOf("src", 0) + 3);
	} else {
		srcFilePath = "";
	}

	// Add file to source paths if not already present
	srcPaths.add(srcFilePath);

	final String[] sourcePathEntries = srcPaths.toArray(new String[srcPaths
			.size()]);
	final String[] classPathEntries = new String[0];
	parser.setEnvironment(classPathEntries, sourcePathEntries, null, true);

	final CompilationUnit compilationUnit = (CompilationUnit) parser
			.createAST(null);
	return compilationUnit;
}
 
Example 20
Source File: JavaASTExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Return an ASTNode given the content
 *
 * @param content
 * @return
 */
public final ASTNode getASTNode(final char[] content,
		final ParseType parseType) {
	final ASTParser parser = ASTParser.newParser(AST.JLS8);
	final int astKind;
	switch (parseType) {
	case CLASS_BODY:
	case METHOD:
		astKind = ASTParser.K_CLASS_BODY_DECLARATIONS;
		break;
	case COMPILATION_UNIT:
		astKind = ASTParser.K_COMPILATION_UNIT;
		break;
	case EXPRESSION:
		astKind = ASTParser.K_EXPRESSION;
		break;
	case STATEMENTS:
		astKind = ASTParser.K_STATEMENTS;
		break;
	default:
		astKind = ASTParser.K_COMPILATION_UNIT;
	}
	parser.setKind(astKind);

	final Map<String, String> options = new Hashtable<String, String>();
	options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
			JavaCore.VERSION_1_8);
	options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
	if (useJavadocs) {
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
	}
	parser.setCompilerOptions(options);
	parser.setSource(content); // set source
	parser.setResolveBindings(useBindings);
	parser.setBindingsRecovery(useBindings);

	parser.setStatementsRecovery(true);

	if (parseType != ParseType.METHOD) {
		return parser.createAST(null);
	} else {
		final ASTNode cu = parser.createAST(null);
		return getFirstMethodDeclaration(cu);
	}
}