com.sun.tools.javac.tree.JCTree.JCCompilationUnit Java Examples
The following examples show how to use
com.sun.tools.javac.tree.JCTree.JCCompilationUnit.
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: CompilerBasedTest.java From Refaster with Apache License 2.0 | 6 votes |
protected void compile(TreeScanner scanner, JavaFileObject fileObject) { JavaCompiler compiler = JavacTool.create(); DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, Locale.ENGLISH, UTF_8); JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, ImmutableList.<String>of(), null, ImmutableList.of(fileObject)); try { this.sourceFile = SourceFile.create(fileObject); Iterable<? extends CompilationUnitTree> trees = task.parse(); task.analyze(); for (CompilationUnitTree tree : trees) { scanner.scan((JCCompilationUnit) tree); } } catch (IOException e) { throw new RuntimeException(e); } this.context = task.getContext(); }
Example #2
Source File: JavacProcessingEnvironment.java From lua-for-android with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** Create the first round. */ Round(List<JCCompilationUnit> roots, List<ClassSymbol> classSymbols, Set<JCCompilationUnit> treesToClean, Log.DeferredDiagnosticHandler deferredDiagnosticHandler) { this(1, treesToClean, deferredDiagnosticHandler); this.roots = roots; genClassFiles = new HashMap<>(); // The reverse() in the following line is to maintain behavioural // compatibility with the previous revision of the code. Strictly speaking, // it should not be necessary, but a javah golden file test fails without it. topLevelClasses = getTopLevelClasses(roots).prependList(classSymbols.reverse()); packageInfoFiles = getPackageInfoFiles(roots); moduleInfoFiles = getModuleInfoFiles(roots); findAnnotationsPresent(); }
Example #3
Source File: JavaCompiler.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * Resolve an identifier. * * @param name The identifier to resolve */ public Symbol resolveIdent(String name) { if (name.equals("")) return syms.errSymbol; JavaFileObject prev = log.useSource(null); try { JCExpression tree = null; for (String s : name.split("\\.", -1)) { if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords return syms.errSymbol; tree = (tree == null) ? make.Ident(names.fromString(s)) : make.Select(tree, names.fromString(s)); } JCCompilationUnit toplevel = make.TopLevel(List.<JCAnnotation>nil(), null, List.<JCTree>nil()); toplevel.packge = syms.unnamedPackage; return attr.attribIdent(tree, toplevel); } finally { log.useSource(prev); } }
Example #4
Source File: TreePosTest.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * Read a file. * @param file the file to be read * @return the tree for the content of the file * @throws IOException if any IO errors occur * @throws TreePosTest.ParseException if any errors occur while parsing the file */ JCCompilationUnit read(File file) throws IOException, ParseException { JavacTool tool = JavacTool.create(); r.errors = 0; Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file); JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files); Iterable<? extends CompilationUnitTree> trees = task.parse(); pw.flush(); if (r.errors > 0) throw new ParseException(sw.toString()); Iterator<? extends CompilationUnitTree> iter = trees.iterator(); if (!iter.hasNext()) throw new Error("no trees found"); JCCompilationUnit t = (JCCompilationUnit) iter.next(); if (iter.hasNext()) throw new Error("too many trees found"); return t; }
Example #5
Source File: MissingSemicolonTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public List<int[]> gatherTreeSpans(File file, String content) throws IOException { JCCompilationUnit unit = read(file.toURI(), content); List<int[]> spans = new ArrayList<>(); new TreePathScanner<Void, Void>() { @Override public Void scan(Tree tree, Void p) { if (tree != null) { int start = ((JCTree) tree).getStartPosition(); int end = ((JCTree) tree).getEndPosition(unit.endPositions); spans.add(new int[] {start, end}); } return super.scan(tree, p); } }.scan(unit, null); return spans; }
Example #6
Source File: TreePosTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * Read a file. * @param file the file to be read * @return the tree for the content of the file * @throws IOException if any IO errors occur * @throws TreePosTest.ParseException if any errors occur while parsing the file */ JCCompilationUnit read(File file) throws IOException, ParseException { JavacTool tool = JavacTool.create(); r.errors = 0; Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file); JavacTask task = tool.getTask(pw, fm, r, Collections.<String>emptyList(), null, files); Iterable<? extends CompilationUnitTree> trees = task.parse(); pw.flush(); if (r.errors > 0) throw new ParseException(sw.toString()); Iterator<? extends CompilationUnitTree> iter = trees.iterator(); if (!iter.hasNext()) throw new Error("no trees found"); JCCompilationUnit t = (JCCompilationUnit) iter.next(); if (iter.hasNext()) throw new Error("too many trees found"); return t; }
Example #7
Source File: TreePosTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Read a file. * @param file the file to be read * @return the tree for the content of the file * @throws IOException if any IO errors occur * @throws TreePosTest.ParseException if any errors occur while parsing the file */ JCCompilationUnit read(File file) throws IOException, ParseException { JavacTool tool = JavacTool.create(); r.errors = 0; Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(file); JavacTask task = tool.getTask(pw, fm, r, List.of("-proc:none"), null, files); Iterable<? extends CompilationUnitTree> trees = task.parse(); pw.flush(); if (r.errors > 0) throw new ParseException(sw.toString()); Iterator<? extends CompilationUnitTree> iter = trees.iterator(); if (!iter.hasNext()) throw new Error("no trees found"); JCCompilationUnit t = (JCCompilationUnit) iter.next(); if (iter.hasNext()) throw new Error("too many trees found"); return t; }
Example #8
Source File: JavaCompiler.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** Resolve an identifier. * @param msym The module in which the search should be performed * @param name The identifier to resolve */ public Symbol resolveIdent(ModuleSymbol msym, String name) { if (name.equals("")) return syms.errSymbol; JavaFileObject prev = log.useSource(null); try { JCExpression tree = null; for (String s : name.split("\\.", -1)) { if (!SourceVersion.isIdentifier(s)) // TODO: check for keywords return syms.errSymbol; tree = (tree == null) ? make.Ident(names.fromString(s)) : make.Select(tree, names.fromString(s)); } JCCompilationUnit toplevel = make.TopLevel(List.nil()); toplevel.modle = msym; toplevel.packge = msym.unnamedPackage; return attr.attribIdent(tree, toplevel); } finally { log.useSource(prev); } }
Example #9
Source File: VanillaPartialReparser.java From netbeans with Apache License 2.0 | 6 votes |
public JCTree.JCBlock reparseMethodBody(Context ctx, CompilationUnitTree topLevel, MethodTree methodToReparse, String newBodyText, final Map<JCTree, Object> docComments) throws IllegalArgumentException, IllegalAccessException { int startPos = ((JCTree.JCBlock)methodToReparse.getBody()).pos; char[] body = new char[startPos + newBodyText.length() + 1]; Arrays.fill(body, 0, startPos, ' '); for (int i = 0; i < newBodyText.length(); i++) { body[startPos + i] = newBodyText.charAt(i); } body[startPos + newBodyText.length()] = '\u0000'; CharBuffer buf = CharBuffer.wrap(body, 0, body.length - 1); com.sun.tools.javac.parser.JavacParser parser = newParser(ctx, buf, ((JCTree.JCBlock)methodToReparse.getBody()).pos, ((JCTree.JCCompilationUnit)topLevel).endPositions); final JCTree.JCStatement statement = parser.parseStatement(); if (statement.getKind() == Tree.Kind.BLOCK) { if (docComments != null) { docComments.putAll((Map<JCTree, Object>) lazyDocCommentsTable.get(parserDocComments.get(parser))); } return (JCTree.JCBlock) statement; } return null; }
Example #10
Source File: Check.java From lua-for-android with BSD 3-Clause "New" or "Revised" License | 6 votes |
public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) { OUTER: for (JCImport imp : toplevel.getImports()) { if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) { TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym; if (toplevel.modle.visiblePackages != null) { //TODO - unclear: selects like javax.* will get resolved from the current module //(as javax is not an exported package from any module). And as javax in the current //module typically does not contain any classes or subpackages, we need to go through //the visible packages to find a sub-package: for (PackageSymbol known : toplevel.modle.visiblePackages.values()) { if (Convert.packagePart(known.fullname) == tsym.flatName()) continue OUTER; } } if (tsym.kind == PCK && tsym.members().isEmpty() && !tsym.exists()) { log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, Errors.DoesntExist(tsym)); } } } }
Example #11
Source File: JavaCompiler.java From lua-for-android with BSD 3-Clause "New" or "Revised" License | 5 votes |
public List<JCCompilationUnit> initModules(List<JCCompilationUnit> roots) { modules.initModules(roots); if (roots.isEmpty()) { enterDone(); } return roots; }
Example #12
Source File: Modules.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private String singleModuleOverride(List<JCCompilationUnit> trees) { if (!fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH)) { return null; } Set<String> override = new LinkedHashSet<>(); for (JCCompilationUnit tree : trees) { JavaFileObject fo = tree.sourcefile; try { Location loc = fileManager.getLocationForModule(StandardLocation.PATCH_MODULE_PATH, fo); if (loc != null) { override.add(fileManager.inferModuleName(loc)); } } catch (IOException ex) { throw new Error(ex); } } switch (override.size()) { case 0: return null; case 1: return override.iterator().next(); default: log.error(Errors.TooManyPatchedModules(override)); return null; } }
Example #13
Source File: PackageDocImpl.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Constructor */ public PackageDocImpl(DocEnv env, PackageSymbol sym, TreePath treePath) { super(env, treePath); this.sym = sym; this.tree = (treePath == null) ? null : (JCCompilationUnit) treePath.getCompilationUnit(); foundDoc = (documentation != null); }
Example #14
Source File: Modules.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private void checkSourceLocation(JCCompilationUnit tree, ModuleSymbol msym) { try { JavaFileObject fo = tree.sourcefile; if (fileManager.contains(msym.sourceLocation, fo)) { return; } if (msym.patchLocation != null && fileManager.contains(msym.patchLocation, fo)) { return; } if (fileManager.hasLocation(StandardLocation.SOURCE_OUTPUT)) { if (fileManager.contains(StandardLocation.SOURCE_OUTPUT, fo)) { return; } } else { if (fileManager.contains(StandardLocation.CLASS_OUTPUT, fo)) { return; } } } catch (IOException e) { throw new Error(e); } JavaFileObject prev = log.useSource(tree.sourcefile); try { log.error(tree.pos(), "file.sb.on.source.or.patch.path.for.module"); } finally { log.useSource(prev); } }
Example #15
Source File: JavaCompiler.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** Parse contents of file. * @param filename The name of the file to be parsed. */ public JCTree.JCCompilationUnit parse(JavaFileObject filename) { JavaFileObject prev = log.useSource(filename); try { JCTree.JCCompilationUnit t = parse(filename, readSource(filename)); if (t.endPositions != null) log.setEndPosTable(filename, t.endPositions); return t; } finally { log.useSource(prev); } }
Example #16
Source File: JavaCompiler.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private Name parseAndGetName(JavaFileObject fo, Function<JCTree.JCCompilationUnit, Name> tree2Name) { DiagnosticHandler dh = new DiscardDiagnosticHandler(log); try { JCTree.JCCompilationUnit t = parse(fo, fo.getCharContent(false)); return tree2Name.apply(t); } catch (IOException e) { return null; } finally { log.popDiagnosticHandler(dh); } }
Example #17
Source File: DocImpl.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
private static String getCommentText(TreePath p) { if (p == null) return null; JCCompilationUnit topLevel = (JCCompilationUnit) p.getCompilationUnit(); JCTree tree = (JCTree) p.getLeaf(); return topLevel.docComments.getCommentText(tree); }
Example #18
Source File: JavadocTool.java From hottub with GNU General Public License v2.0 | 5 votes |
private void parse(JavaFileObject fo, ListBuffer<JCCompilationUnit> trees, boolean trace) { if (uniquefiles.add(fo)) { // ignore duplicates if (trace) docenv.notice("main.Loading_source_file", fo.getName()); trees.append(parse(fo)); } }
Example #19
Source File: Modules.java From lua-for-android with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Determine the location for the module on the module source path * or source output directory which contains a given CompilationUnit. * If the source output directory is unset, the class output directory * will be checked instead. * {@code null} is returned if no such module can be found. * @param tree the compilation unit tree * @return the location for the enclosing module * @throws IOException if there is a problem while searching for the module. */ private Location getModuleLocation(JCCompilationUnit tree) throws IOException { JavaFileObject fo = tree.sourcefile; Location loc = fileManager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, fo); if (loc == null) { Location sourceOutput = fileManager.hasLocation(StandardLocation.SOURCE_OUTPUT) ? StandardLocation.SOURCE_OUTPUT : StandardLocation.CLASS_OUTPUT; loc = fileManager.getLocationForModule(sourceOutput, fo); } return loc; }
Example #20
Source File: PartialReparserService.java From netbeans with Apache License 2.0 | 5 votes |
public BlockTree reflowMethodBody(CompilationUnitTree topLevel, ClassTree ownerClass, MethodTree methodToReparse) { Flow flow = Flow.instance(context); TreeMaker make = TreeMaker.instance(context); flow.reanalyzeMethod(make.forToplevel((JCCompilationUnit)topLevel), (JCClassDecl)ownerClass); return methodToReparse.getBody(); }
Example #21
Source File: Enter.java From javaide with GNU General Public License v3.0 | 5 votes |
public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) { Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext()); localEnv.toplevel = tree; localEnv.enclClass = predefClassDef; localEnv.info.scope = tree.namedImportScope; localEnv.info.lint = lint; return localEnv; }
Example #22
Source File: JavacTrees.java From lua-for-android with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override @DefinedBy(Api.COMPILER_TREE) public TreePath getPath(Element e, AnnotationMirror a, AnnotationValue v) { final Pair<JCTree, JCCompilationUnit> treeTopLevel = elements.getTreeAndTopLevel(e, a, v); if (treeTopLevel == null) return null; return TreePath.getPath(treeTopLevel.snd, treeTopLevel.fst); }
Example #23
Source File: Enter.java From java-n-IDE-for-Android with Apache License 2.0 | 5 votes |
/** Create a fresh environment for toplevels. * @param tree The toplevel tree. */ Env<AttrContext> topLevelEnv(JCCompilationUnit tree) { Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext()); localEnv.toplevel = tree; localEnv.enclClass = predefClassDef; tree.namedImportScope = new ImportScope(tree.packge); tree.starImportScope = new StarImportScope(tree.packge); localEnv.info.scope = tree.namedImportScope; localEnv.info.lint = lint; return localEnv; }
Example #24
Source File: CodeTransformerTestHelper.java From Refaster with Apache License 2.0 | 5 votes |
public JavaFileObject transform(JavaFileObject original) { JavaCompiler compiler = JavacTool.create(); DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, Locale.ENGLISH, UTF_8); JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, ImmutableList.<String>of(), null, ImmutableList.of(original)); try { SourceFile sourceFile = SourceFile.create(original); Iterable<? extends CompilationUnitTree> trees = task.parse(); task.analyze(); JCCompilationUnit tree = FluentIterable.from(trees).filter(JCCompilationUnit.class).getOnlyElement(); DescriptionBasedDiff diff = DescriptionBasedDiff.create(tree); transformer().apply(tree, task.getContext(), diff); diff.applyDifferences(sourceFile); return JavaFileObjects.forSourceString( FluentIterable.from(tree.getTypeDecls()) .filter(JCClassDecl.class) .getOnlyElement() .sym.getQualifiedName().toString(), sourceFile.getSourceText()); } catch (IOException e) { throw new RuntimeException(e); } }
Example #25
Source File: MissingSemicolonTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Read a file. * @param file the file to be read * @return the tree for the content of the file * @throws IOException if any IO errors occur * @throws MissingSemicolonTest.ParseException if any errors occur while parsing the file */ JCCompilationUnit read(URI uri, String content) throws IOException { JavacTool tool = JavacTool.create(); JavacTask task = tool.getTask(null, fm, devNull, Collections.<String>emptyList(), null, Arrays.<JavaFileObject>asList(new JavaSource(uri, content))); Iterable<? extends CompilationUnitTree> trees = task.parse(); Iterator<? extends CompilationUnitTree> iter = trees.iterator(); if (!iter.hasNext()) throw new Error("no trees found"); JCCompilationUnit t = (JCCompilationUnit) iter.next(); if (iter.hasNext()) throw new Error("too many trees found"); return t; }
Example #26
Source File: DocImpl.java From hottub with GNU General Public License v2.0 | 5 votes |
private static String getCommentText(TreePath p) { if (p == null) return null; JCCompilationUnit topLevel = (JCCompilationUnit) p.getCompilationUnit(); JCTree tree = (JCTree) p.getLeaf(); return topLevel.docComments.getCommentText(tree); }
Example #27
Source File: ExpressionTemplateIntegrationTest.java From Refaster with Apache License 2.0 | 5 votes |
private CodeTransformer extractRefasterRule(JavaFileObject object) { compile(object); JCCompilationUnit compilationUnit = Iterables.getOnlyElement(compilationUnits); JCClassDecl classDecl = FluentIterable.from(compilationUnit.getTypeDecls()) .filter(JCClassDecl.class).getOnlyElement(); return Iterables.getOnlyElement(RefasterRuleBuilderScanner.extractRules(classDecl, context)); }
Example #28
Source File: Enter.java From javaide with GNU General Public License v3.0 | 5 votes |
/** Main method: enter one class from a list of toplevel trees and * place the rest on uncompleted for later processing. * @param trees The list of trees to be processed. * @param c The class symbol to be processed. */ public void complete(List<JCCompilationUnit> trees, ClassSymbol c) { annotate.enterStart(); ListBuffer<ClassSymbol> prevUncompleted = uncompleted; if (memberEnter.completionEnabled) uncompleted = new ListBuffer<ClassSymbol>(); try { // enter all classes, and construct uncompleted list classEnter(trees, null); // complete all uncompleted classes in memberEnter if (memberEnter.completionEnabled) { while (uncompleted.nonEmpty()) { ClassSymbol clazz = uncompleted.next(); if (c == null || c == clazz || prevUncompleted == null) clazz.complete(); else // defer prevUncompleted.append(clazz); } // if there remain any unimported toplevels (these must have // no classes at all), process their import statements as well. for (JCCompilationUnit tree : trees) { if (tree.starImportScope.elems == null) { JavaFileObject prev = log.useSource(tree.sourcefile); Env<AttrContext> topEnv = topLevelEnv(tree); memberEnter.memberEnter(tree, topEnv); log.useSource(prev); } } } } finally { uncompleted = prevUncompleted; annotate.enterDone(); } }
Example #29
Source File: PackageDocImpl.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Constructor */ public PackageDocImpl(DocEnv env, PackageSymbol sym, TreePath treePath) { super(env, treePath); this.sym = sym; this.tree = (treePath == null) ? null : (JCCompilationUnit) treePath.getCompilationUnit(); foundDoc = (documentation != null); }
Example #30
Source File: JavadocTool.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * From a list of top level trees, return the list of contained class definitions */ List<JCClassDecl> listClasses(List<JCCompilationUnit> trees) { ListBuffer<JCClassDecl> result = new ListBuffer<>(); for (JCCompilationUnit t : trees) { for (JCTree def : t.defs) { if (def.hasTag(JCTree.Tag.CLASSDEF)) result.append((JCClassDecl)def); } } return result.toList(); }