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

The following examples show how to use org.eclipse.jdt.core.dom.ASTParser#setUnitName() . 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: SORecommender.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
private HashMap<String, HashSet<String>> parseKStatements(String snippet) throws IOException {
	HashMap<String, HashSet<String>> tokens = new HashMap<String, HashSet<String>>();
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setResolveBindings(true);
	parser.setKind(ASTParser.K_STATEMENTS);
	parser.setBindingsRecovery(true);
	Map<String, String> options = JavaCore.getOptions();
	parser.setCompilerOptions(options);
	parser.setUnitName("test");
	String src = snippet;
	String[] sources = {};
	String[] classpath = { "/usr/lib/jvm/java-8-openjdk-amd64" };
	parser.setEnvironment(classpath, sources, new String[] {}, true);
	parser.setSource(src.toCharArray());
	try {
		Block block = (Block) parser.createAST(null);
		MyASTVisitor myVisitor = new MyASTVisitor();
		block.accept(myVisitor);
		tokens = myVisitor.getTokens();
	} catch (Exception exc) {
		logger.error("JDT parsing error");
	}
	return tokens;
}
 
Example 2
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 3
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 4
Source File: SharedUtils.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses the specified Java source file located in the given Java project.
 * 
 * @param sourceFile
 *            The specified Java source file.
 * @param project
 *            The given Java project.
 * @return The parsed compilation unit.
 * @throws IOException
 *             Thrown when I/O error occurs during reading the file.
 * @throws JavaModelException
 */
public static CompilationUnit parseJavaSource(File sourceFile, IJavaProject project)
		throws IOException, JavaModelException {
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	char[] content = SharedUtils.getFileContents(sourceFile);

	parser.setSource(content);
	parser.setProject(project);

	parser.setResolveBindings(true);
	parser.setBindingsRecovery(true);
	parser.setUnitName(sourceFile.getName());
	parser.setKind(ASTParser.K_COMPILATION_UNIT);

	CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
	return compilationUnit;
}
 
Example 5
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 6
Source File: APIVersion.java    From apidiff with MIT License 5 votes vote down vote up
public void parse(String str, File source, final Boolean ignoreTreeDiff) throws IOException {
		
		if(this.mapModifications.size() > 0 && !this.isFileModification(source,ignoreTreeDiff)){
			return;
		}
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setSource(str.toCharArray());
		parser.setKind(ASTParser.K_COMPILATION_UNIT);
		String[] classpath = java.lang.System.getProperty("java.class.path").split(";");
		String[] sources = { source.getParentFile().getAbsolutePath() };

		Hashtable<String, String> options = JavaCore.getOptions();
		options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
		options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8);
		options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8);
		parser.setUnitName(source.getAbsolutePath());

		parser.setCompilerOptions(options);
//		parser.setEnvironment(null, sources, new String[] { "UTF-8" },	true);
		parser.setResolveBindings(true);
		parser.setBindingsRecovery(true);

//		parser.setEnvironment(classpath, sources, new String[] { "UTF-8" },	true);
//		CompilationUnit compilationUnit = null;
		try {
			parser.setEnvironment(null, null, null,	true);
			CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
			TypeDeclarationVisitor visitorType = new TypeDeclarationVisitor();
			EnumDeclarationVisitor visitorEnum = new EnumDeclarationVisitor();
			
			compilationUnit.accept(visitorType);
			compilationUnit.accept(visitorEnum);
			
			this.configureAcessiblesAndNonAccessibleTypes(visitorType);
			this.configureAcessiblesAndNonAccessibleEnums(visitorEnum);
		} catch (Exception e) {
			this.logger.error("Erro ao criar AST sem source", e);
		}

	}
 
Example 7
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 8
Source File: CompilationUnitParser.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public CompilationUnit parse(ICompilationUnit unit) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(unit);
    parser.setResolveBindings(true);
    parser.setProject(unit.getJavaProject());
    parser.setUnitName(unit.getPath().toString());
    return (CompilationUnit) parser.createAST(null);
}
 
Example 9
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 10
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 11
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 12
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 13
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;
}