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

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#setBindingsRecovery() . 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: ValidationTestBase.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
protected CompilationUnit prepareAST(String javaFile) throws IOException {
	File projectRoot = new File(VALIDATION_EXAMPLES_ROOT).getAbsoluteFile();
	File sourceFile = new File(projectRoot.getCanonicalPath() + getValidationExamplesPackage() + javaFile);

	ASTParser parser = ASTParser.newParser(AST.JLS8);
	char[] content = SharedUtils.getFileContents(sourceFile);

	String[] classpath = {};
	String[] sourcepath = { projectRoot.getCanonicalPath(), new File(API_SRC_LOC).getCanonicalPath() };
	String[] encodings = { "UTF-8", "UTF-8" };

	parser.setSource(content);

	parser.setResolveBindings(true);
	parser.setBindingsRecovery(true);
	parser.setUnitName(sourceFile.getName());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setEnvironment(classpath, sourcepath, encodings, true);

	return (CompilationUnit) parser.createAST(null);
}
 
Example 2
Source File: JavaFile.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
public static CompilationUnit genASTFromSource(String icu, String[] classPath, String[] sourcePath){
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setResolveBindings(true);
		parser.setBindingsRecovery(true);
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		Map<?, ?> options = JavaCore.getOptions();
		JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
		parser.setCompilerOptions(options);
 
//		String[] sources = { "C:\\Users\\pc\\workspace\\asttester\\src" }; 
//		String[] classpath = {"C:\\Program Files\\Java\\jre1.8.0_25\\lib\\rt.jar"};
 
		parser.setEnvironment(classPath, sourcePath, new String[] { "UTF-8"}, true);
		parser.setSource(icu.toCharArray());
		return (CompilationUnit) parser.createAST(null);
	}
 
Example 3
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 4
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static IBinding getHoveredNodeBinding(IJavaElement element, ITypeRoot typeRoot, IRegion region) {
	if (typeRoot == null || region == null) {
		return null;
	}
	IBinding binding;
	ASTNode node = getHoveredASTNode(typeRoot, region);
	if (node == null) {
		ASTParser p = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		p.setProject(element.getJavaProject());
		p.setBindingsRecovery(true);
		try {
			binding = p.createBindings(new IJavaElement[] { element }, null)[0];
		} catch (OperationCanceledException e) {
			return null;
		}
	} else {
		binding = resolveBinding(node);
	}
	return binding;
}
 
Example 5
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 6
Source File: JavaParser.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
@Override
public AST generate(String filename, String source, String[] srcFolders) {
	AST ast = new AST();
	ast.setFileName(filename);
	ast.setSource(source);

	ASTParser parser = ASTParser.newParser(org.eclipse.jdt.core.dom.AST.JLS10);
	parser.setResolveBindings(true);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setBindingsRecovery(true);
	parser.setCompilerOptions(JavaCore.getOptions());
	parser.setUnitName(filename);
	parser.setSource(source.toCharArray());

	parser.setEnvironment(null, srcFolders, null, true);
	
	CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	FileVisitor visitor = new FileVisitor();
	cu.accept(visitor);

	ast.setImports(visitor.getImports());
	ast.setPackageDeclaration(visitor.getPackageName());
	ast.setTypes(visitor.getTypes());
	ast.setLanguage(Language.JAVA);

	return ast;
}
 
Example 7
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 8
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private CompilationUnit createSourceCuNode() {
	Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null);
	Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null);
	ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
	parser.setBindingsRecovery(true);
	parser.setResolveBindings(true);
	if (getSourceCu() != null) {
		parser.setSource(getSourceCu());
	} else {
		parser.setSource(getSourceClassFile());
	}
	return (CompilationUnit) parser.createAST(null);
}
 
Example 9
Source File: ASTProcessor.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Parses the provided file, using the given libraryPaths and sourcePaths as context. The libraries may be either
 * jar files or references to directories containing class files.
 *
 * The sourcePaths must be a reference to the top level directory for sources (eg, for a file
 * src/main/java/org/example/Foo.java, the source path would be src/main/java).
 *
 * The wildcard resolver provides a fallback for processing wildcard imports that the underlying parser was unable
 * to resolve.
 */
public static List<ClassReference> analyze(WildcardImportResolver importResolver, Set<String> libraryPaths, Set<String> sourcePaths,
            Path sourceFile)
{
    ASTParser parser = ASTParser.newParser(AST.JLS11);
    parser.setEnvironment(libraryPaths.toArray(new String[libraryPaths.size()]), sourcePaths.toArray(new String[sourcePaths.size()]), null, true);
    parser.setBindingsRecovery(false);
    parser.setResolveBindings(true);
    Map options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);
    String fileName = sourceFile.getFileName().toString();
    parser.setUnitName(fileName);
    try
    {
        parser.setSource(FileUtils.readFileToString(sourceFile.toFile()).toCharArray());
    }
    catch (IOException e)
    {
        throw new ASTException("Failed to get source for file: " + sourceFile.toString() + " due to: " + e.getMessage(), e);
    }
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    ReferenceResolvingVisitor visitor = new ReferenceResolvingVisitor(importResolver, cu, sourceFile.toString());
    cu.accept(visitor);
    return visitor.getJavaClassReferences();
}
 
Example 10
Source File: Utils.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public static ASTNode genASTFromSource(String icu, int type) {
	ASTParser astParser = ASTParser.newParser(AST.JLS8);
	Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
	astParser.setCompilerOptions(options);
	astParser.setSource(icu.toCharArray());
	astParser.setKind(type);
	astParser.setResolveBindings(true);
	astParser.setBindingsRecovery(true);
	return astParser.createAST(null);
}
 
Example 11
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private CompilationUnit createSourceCuNode() {
	Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null);
	Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null);
	ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	parser.setBindingsRecovery(true);
	parser.setResolveBindings(true);
	if (getSourceCu() != null)
		parser.setSource(getSourceCu());
	else
		parser.setSource(getSourceClassFile());
	return (CompilationUnit) parser.createAST(null);
}
 
Example 12
Source File: ReferencedClassesParser.java    From BUILD_file_generator with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a source file, attempting to resolve references in the AST. Valid Java files will usually
 * have errors in the CompilationUnit returned by this method, because classes, imports and
 * methods will be undefined (because we're only looking at a single file from a whole project).
 * Consequently, do not assume the returned object's getProblems() is an empty list. On the other
 * hand, {@link @parseSource} returns a CompilationUnit fit for syntax checking purposes.
 */
private static CompilationUnit parseAndResolveSource(String source) {
  ASTParser parser = createCompilationUnitParser();
  parser.setSource(source.toCharArray());
  parser.setResolveBindings(true);
  parser.setBindingsRecovery(true);
  parser.setEnvironment(
      EMPTY_STRING_ARRAY,
      EMPTY_STRING_ARRAY,
      EMPTY_STRING_ARRAY,
      true /* includeRunningVMBootclasspath */);
  parser.setUnitName("dontCare");

  return (CompilationUnit) parser.createAST(null);
}
 
Example 13
Source File: JavaParser.java    From SnowGraph with Apache License 2.0 4 votes vote down vote up
public static ElementInfoPool parse(String srcDir) {
    ElementInfoPool elementInfoPool = new ElementInfoPool(srcDir);

    Collection<File> javaFiles = FileUtils.listFiles(new File(srcDir), new String[]{"java"}, true);
    Set<String> srcPathSet = new HashSet<>();
    Set<String> srcFolderSet = new HashSet<>();
    for (File javaFile : javaFiles) {
        String srcPath = javaFile.getAbsolutePath();
        String srcFolderPath = javaFile.getParentFile().getAbsolutePath();
        srcPathSet.add(srcPath);
        srcFolderSet.add(srcFolderPath);
    }
    String[] srcPaths = new String[srcPathSet.size()];
    srcPathSet.toArray(srcPaths);
    NameResolver.setSrcPathSet(srcPathSet);
    String[] srcFolderPaths = new String[srcFolderSet.size()];
    srcFolderSet.toArray(srcFolderPaths);

    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setEnvironment(null, srcFolderPaths, null, true);
    parser.setResolveBindings(true);
    Map<String, String> options = new Hashtable<>();
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
    options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
    options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
    parser.setCompilerOptions(options);
    parser.setBindingsRecovery(true);
    System.out.println(javaFiles.size());
    parser.createASTs(srcPaths, null, new String[]{}, new FileASTRequestor() {
        @Override
        public void acceptAST(String sourceFilePath, CompilationUnit javaUnit) {
            try {
                javaUnit.accept(new JavaASTVisitor(elementInfoPool, FileUtils.readFileToString(new File(sourceFilePath))));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }, null);

    return elementInfoPool;
}
 
Example 14
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static String getAnnotations(IJavaElement element, ITypeRoot editorInputElement, IRegion hoverRegion) throws URISyntaxException, JavaModelException {
	if (!(element instanceof IPackageFragment)) {
		if (!(element instanceof IAnnotatable))
			return null;
		
		if (((IAnnotatable)element).getAnnotations().length == 0)
			return null;
	}
	
	IBinding binding;
	ASTNode node= getHoveredASTNode(editorInputElement, hoverRegion);
	
	if (node == null) {
		ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		p.setProject(element.getJavaProject());
		p.setBindingsRecovery(true);
		try {
			binding= p.createBindings(new IJavaElement[] { element }, null)[0];
		} catch (OperationCanceledException e) {
			return null;
		}
		
	} else {
		binding= resolveBinding(node);
	}
	
	if (binding == null)
		return null;
	
	IAnnotationBinding[] annotations= binding.getAnnotations();
	if (annotations.length == 0)
		return null;
	
	StringBuffer buf= new StringBuffer();
	for (int i= 0; i < annotations.length; i++) {
		//TODO: skip annotations that don't have an @Documented annotation?
		addAnnotation(buf, element, annotations[i]);
		buf.append("<br>"); //$NON-NLS-1$
	}
	
	return buf.toString();
}
 
Example 15
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 16
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 17
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);
	}
}
 
Example 18
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 19
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 20
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);
	}
}