List of usage examples for org.eclipse.jdt.core.dom FileASTRequestor FileASTRequestor
FileASTRequestor
From source file:com.google.dart.java2dart.Context.java
License:Open Source License
/** * @return the Java AST of the given Java {@link File} in context of {@link #sourceFolders}. */// w w w. jav a 2s . c o m private Map<File, CompilationUnit> parseJavaFiles(final List<File> javaFiles) throws Exception { String paths[] = new String[javaFiles.size()]; final Map<String, File> pathToFile = Maps.newHashMap(); for (int i = 0; i < javaFiles.size(); i++) { File javaFile = javaFiles.get(i); String javaPath = javaFile.getAbsolutePath(); paths[i] = javaPath; pathToFile.put(javaPath, javaFile); } // prepare Java parser ASTParser parser = ASTParser.newParser(AST.JLS4); { String[] classpathEntries = new String[classpathFiles.size()]; for (int i = 0; i < classpathFiles.size(); i++) { classpathEntries[i] = classpathFiles.get(i).getAbsolutePath(); } String[] sourceEntries = new String[sourceFolders.size()]; for (int i = 0; i < sourceFolders.size(); i++) { sourceEntries[i] = sourceFolders.get(i).getAbsolutePath(); } parser.setEnvironment(classpathEntries, sourceEntries, null, true); } parser.setResolveBindings(true); parser.setCompilerOptions(ImmutableMap.of(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5, JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED)); // do parse final Map<File, CompilationUnit> units = Maps.newLinkedHashMap(); parser.createASTs(paths, null, ArrayUtils.EMPTY_STRING_ARRAY, new FileASTRequestor() { @Override public void acceptAST(String sourceFilePath, org.eclipse.jdt.core.dom.CompilationUnit javaUnit) { File astFile = pathToFile.get(sourceFilePath); CompilationUnit dartUnit = SyntaxTranslator.translate(Context.this, javaUnit); units.put(astFile, dartUnit); } }, null); return units; }
From source file:com.google.devtools.j2objc.jdt.JdtParser.java
License:Apache License
@Override public void parseFiles(Collection<String> paths, final Handler handler, SourceVersion sourceVersion) { ASTParser parser = newASTParser(true, sourceVersion); FileASTRequestor astRequestor = new FileASTRequestor() { @Override/*from w w w. j ava 2 s.c om*/ public void acceptAST(String sourceFilePath, CompilationUnit ast) { logger.fine("acceptAST: " + sourceFilePath); if (checkCompilationErrors(sourceFilePath, ast)) { RegularInputFile file = new RegularInputFile(sourceFilePath); try { String source = options.fileUtil().readFile(file); ParserEnvironment parserEnv = new JdtParserEnvironment(ast.getAST()); TranslationEnvironment env = new TranslationEnvironment(options, parserEnv); com.google.devtools.j2objc.ast.CompilationUnit unit = TreeConverter.convertCompilationUnit( env, ast, sourceFilePath, FileUtil.getMainTypeName(file), source); handler.handleParsedUnit(sourceFilePath, unit); } catch (IOException e) { ErrorUtil.error("Error reading file " + file.getOriginalLocation() + ": " + e.getMessage()); } } } }; // JDT fails to resolve all secondary bindings unless there are the same // number of "binding key" strings as source files. It doesn't appear to // matter what the binding key strings should be (as long as they're non- // null), so the paths array is reused. String[] pathsArray = paths.toArray(new String[paths.size()]); parser.createASTs(pathsArray, getEncodings(pathsArray.length), pathsArray, astRequestor, null); }
From source file:com.google.devtools.j2objc.util.JdtParser.java
License:Apache License
public void parseFiles(List<InputFile> files, final Handler handler) { // We need the whole SourceFile to correctly handle a parsed ADT, so we keep track of it here. final Map<String, InputFile> reverseMap = new LinkedHashMap<String, InputFile>(); for (InputFile file : files) { reverseMap.put(file.getPath(), file); }//from w ww .jav a 2 s. co m ASTParser parser = newASTParser(true); FileASTRequestor astRequestor = new FileASTRequestor() { @Override public void acceptAST(String sourceFilePath, CompilationUnit ast) { logger.fine("acceptAST: " + sourceFilePath); if (checkCompilationErrors(sourceFilePath, ast)) { handler.handleParsedUnit(reverseMap.get(sourceFilePath), ast); } } }; // JDT fails to resolve all secondary bindings unless there are the same // number of "binding key" strings as source files. It doesn't appear to // matter what the binding key strings should be (as long as they're non- // null), so the paths array is reused. String[] paths = reverseMap.keySet().toArray(new String[reverseMap.size()]); parser.createASTs(paths, getEncodings(paths.length), paths, astRequestor, null); }
From source file:com.j2swift.util.JdtParser.java
License:Apache License
public void parseFiles(Collection<String> paths, final Handler handler) { ASTParser parser = newASTParser(true); FileASTRequestor astRequestor = new FileASTRequestor() { @Override//w ww .j av a 2 s. c o m public void acceptAST(String sourceFilePath, CompilationUnit ast) { logger.fine("acceptAST: " + sourceFilePath); if (checkCompilationErrors(sourceFilePath, ast)) { handler.handleParsedUnit(sourceFilePath, ast); } } }; // JDT fails to resolve all secondary bindings unless there are the same // number of "binding key" strings as source files. It doesn't appear to // matter what the binding key strings should be (as long as they're non- // null), so the paths array is reused. String[] pathsArray = paths.toArray(new String[paths.size()]); parser.createASTs(pathsArray, getEncodings(pathsArray.length), pathsArray, astRequestor, null); }
From source file:org.juniversal.translator.core.Translator.java
License:Open Source License
/** * Translate all source files configured for the translator. If a user errors occurs during translation for a file * (e.g. a SourceNotSupported exception is thrown), an error message is output for that file, the translation * continues on with remaining files, and false is eventually returned from this method as the translate failed. If * an internal occurs during translation (e.g. the translator has a bug), an exception is thrown. * * @return true if all files were translated without error, false if some failed *///from w ww . j a v a 2 s .c om public boolean translate() { ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setKind(ASTParser.K_COMPILATION_UNIT); //parser.setEnvironment(new String[0], new String[0], null, false); //TODO: Set classpath & sourcepath differently probably; this just uses the current VM (I think), but I can //see that it doesn't resolve everything for some reason parser.setEnvironment(classpath, sourcepath, null, true); parser.setResolveBindings(true); Map options = JavaCore.getOptions(); JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options); parser.setCompilerOptions(options); Var<Boolean> failed = new Var<>(false); FileASTRequestor astRequestor = new FileASTRequestor() { public void acceptAST(String sourceFilePath, CompilationUnit compilationUnit) { SourceFile sourceFile = new SourceFile(compilationUnit, new File(sourceFilePath), sourceTabStop); //boolean outputErrorForFile = false; for (IProblem problem : compilationUnit.getProblems()) { if (problem.isError()) { System.err.println("Error: " + problem.getMessage()); System.err.println(sourceFile.getPositionDescription(problem.getSourceStart())); } } // Translate each file as it's returned; if a user error occurs while translating (e.g. a // SourceNotSupported exception is thrown), print the message for that, note the failure, and continue // on System.out.println("Translating " + sourceFilePath); try { translateFile(sourceFile); } catch (UserViewableException e) { System.err.println("Error: " + e.getMessage()); failed.set(true); } } }; parser.createASTs(getJavaFiles(), null, new String[0], astRequestor, null); return !failed.value(); /* * String source = readFile(jUniversal.getJavaProjectDirectories().get(0).getPath()); * parser.setSource(source.toCharArray()); * * CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null); * * * TypeDeclaration typeDeclaration = ASTUtil.getFirstTypeDeclaration(compilationUnit); * * FileWriter writer; try { writer = new FileWriter(jUniversal.getOutputDirectory()); } * catch (IOException e) { throw new RuntimeException(e); } * * CPPProfile profile = new CPPProfile(); // profile.setTabStop(4); * * CPPWriter cppWriter = new CPPWriter(writer, profile); * * Context context = new Context((CompilationUnit) compilationUnit.getRoot(), source, 8, * profile, cppWriter, OutputType.SOURCE); * * context.setPosition(typeDeclaration.getStartPosition()); * * ASTWriters astWriters = new ASTWriters(); * * try { context.setPosition(typeDeclaration.getStartPosition()); * skipSpaceAndComments(); * * astWriters.writeNode(typeDeclaration, context); } catch (UserViewableException e) { * System.err.println(e.getMessage()); System.exit(1); } catch (RuntimeException e) { if (e * instanceof ContextPositionMismatchException) throw e; else throw new * JUniversalException(e.getMessage() + "\nError occurred with context at position\n" + * context.getPositionDescription(context.getPosition()), e); } * * try { writer.close(); } catch (IOException e) { throw new RuntimeException(e); } */ }
From source file:org.rascalmpl.library.lang.java.m3.internal.EclipseJavaCompiler.java
License:Open Source License
protected void buildCompilationUnits(ISet files, boolean resolveBindings, boolean errorRecovery, IList sourcePath, IList classPath, IString javaVersion, BiConsumer<ISourceLocation, CompilationUnit> buildNotifier) throws IOException { boolean fastPath = true; for (IValue f : files) { fastPath &= safeResolve((ISourceLocation) f).getScheme().equals("file"); }//from w w w. ja v a 2 s .c om if (fastPath) { Map<String, ISourceLocation> reversePathLookup = new HashMap<>(); String[] absolutePaths = new String[files.size()]; String[] encodings = new String[absolutePaths.length]; int i = 0; for (IValue p : files) { ISourceLocation loc = (ISourceLocation) p; if (!URIResolverRegistry.getInstance().isFile(loc)) { throw RuntimeExceptionFactory.io(VF.string("" + loc + " is not a file"), null, null); } if (!URIResolverRegistry.getInstance().exists(loc)) { throw RuntimeExceptionFactory.io(VF.string("" + loc + " doesn't exist"), null, null); } absolutePaths[i] = new File(safeResolve(loc).getPath()).getAbsolutePath(); reversePathLookup.put(absolutePaths[i], loc); encodings[i] = guessEncoding(loc); i++; } ASTParser parser = constructASTParser(resolveBindings, errorRecovery, javaVersion, translatePaths(sourcePath), translatePaths(classPath)); parser.createASTs(absolutePaths, encodings, new String[0], new FileASTRequestor() { @Override public void acceptAST(String sourceFilePath, CompilationUnit ast) { buildNotifier.accept(reversePathLookup.get(sourceFilePath), ast); } }, null); } else { for (IValue file : files) { ISourceLocation loc = (ISourceLocation) file; CompilationUnit cu = getCompilationUnit(loc.getPath(), getFileContents(loc), resolveBindings, errorRecovery, javaVersion, translatePaths(sourcePath), translatePaths(classPath)); buildNotifier.accept(loc, cu); } } }
From source file:org.springframework.ide.vscode.boot.java.utils.SpringIndexerJava.java
License:Open Source License
private void scanFiles(IJavaProject project, String[] javaFiles) throws Exception { SymbolCacheKey cacheKey = getCacheKey(project); CachedSymbol[] symbols = this.cache.retrieve(cacheKey, javaFiles); if (symbols == null) { List<CachedSymbol> generatedSymbols = new ArrayList<CachedSymbol>(); ASTParser parser = createParser(project); FileASTRequestor requestor = new FileASTRequestor() { @Override//from w w w . j a v a2s. c om public void acceptAST(String sourceFilePath, CompilationUnit cu) { File file = new File(sourceFilePath); String docURI = UriUtil.toUri(file).toString(); long lastModified = file.lastModified(); AtomicReference<TextDocument> docRef = new AtomicReference<>(); scanAST(project, cu, docURI, lastModified, docRef, null, generatedSymbols); } }; parser.createASTs(javaFiles, null, new String[0], requestor, null); this.cache.store(cacheKey, javaFiles, generatedSymbols); symbols = (CachedSymbol[]) generatedSymbols.toArray(new CachedSymbol[generatedSymbols.size()]); } else { log.info("scan java files used cached data: " + project.getElementName() + " - no. of cached symbols retrieved: " + symbols.length); } if (symbols != null) { for (int i = 0; i < symbols.length; i++) { CachedSymbol symbol = symbols[i]; symbolHandler.addSymbol(project, symbol.getDocURI(), symbol.getEnhancedSymbol()); } } }
From source file:parser.AnnotationType.java
License:Open Source License
public void parseTypeInformationOfProject(File dir, boolean isParsingType) { String[] arrSourceExtension = { ".java" }; String[] arrJarExtension = { ".jar" }; String[] arrAllExtension = { ".java", ".jar" }; String[] sources = { fop_jdk }; HashMap<String, List<File>> arrAllSources = getFilteredRecursiveFiles2(dir, arrAllExtension); List<File> files = arrAllSources.get(".java"); if (files == null) { files = new ArrayList<File>(); }//ww w.ja va 2 s .c o m List<File> arrJars = arrAllSources.get(".jar"); if (arrJars == null) { arrJars = new ArrayList<File>(); } classpath = new String[arrJars.size() + 1]; classpath[0] = "C:\\Program Files\\Java\\jre1.8.0_51\\lib\\rt.jar"; this.isParsingType = isParsingType; for (int i = 0; i < arrJars.size(); i++) { classpath[i + 1] = arrJars.get(i).getAbsolutePath(); } String[] paths = new String[files.size()]; for (int i = 0; i < files.size(); i++) { paths[i] = files.get(i).getAbsolutePath(); } final HashMap<String, CompilationUnit> cus = new HashMap<>(); FileASTRequestor r = new FileASTRequestor() { @Override public void acceptAST(String sourceFilePath, CompilationUnit ast) { cus.put(sourceFilePath, ast); } }; @SuppressWarnings("rawtypes") Map options = JavaCore.getOptions(); options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8); options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8); options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); parser = ASTParser.newParser(AST.JLS4); parser.setCompilerOptions(options); parser.setEnvironment(classpath == null ? new String[0] : classpath, sources, new String[] { "UTF-8" }, true); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setResolveBindings(true); parser.setBindingsRecovery(true); // parser.setEnvironment(classpath, sources, new String[] { "UTF-8"}, true); // parser.setResolveBindings(true); // parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.createASTs(paths, null, new String[0], r, null); setSequencesOfMethods = new HashMap<String, String>(); for (String item : cus.keySet()) { CompilationUnit ast = cus.get(item); fp_currentFile = item; ast.accept(this); } }