Java Code Examples for com.sun.tools.javac.tree.JCTree.JCCompilationUnit

The following examples show how to use com.sun.tools.javac.tree.JCTree.JCCompilationUnit. These examples are extracted from open source projects. 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 Project: openjdk-jdk9   Source File: JavaCompiler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** 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 2
Source Project: netbeans   Source File: VanillaPartialReparser.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: java-n-IDE-for-Android   Source File: JavaCompiler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: hottub   Source File: TreePosTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 Project: Refaster   Source File: CompilerBasedTest.java    License: Apache License 2.0 6 votes vote down vote up
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 6
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 7
/**
 * 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 8
/** 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 9
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 10
Source Project: openjdk-jdk9   Source File: TreePosTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 11
Source Project: annotation-tools   Source File: TreeFinder.java    License: MIT License 5 votes vote down vote up
/**
 * Scans the given tree with the given {@link Insertions} and returns
 * the mapping from source position to insertion text.
 *
 * <p>
 * <i>N.B.:</i> This method calls {@code scan()} internally.
 * </p>
 *
 * @param node the tree to scan
 * @param insertions the insertion criteria
 * @return the source position to insertion text mapping
 */
public SetMultimap<Pair<Integer, ASTPath>, Insertion>
getPositions(JCCompilationUnit node, Insertions insertions) {
  List<Insertion> list = new ArrayList<>();
  treePathCache.clear();
  if (annotator.Main.temporaryDebug) {
    System.out.println("insertions size: " + insertions.size());
    System.out.println("insertions.forOuterClass(\"\") size: " + insertions.forOuterClass(node, "").size());
    System.out.println("list pre-size: " + list.size());
  }
  list.addAll(insertions.forOuterClass(node, ""));
  if (annotator.Main.temporaryDebug) {
    System.out.println("list post-size: " + list.size());
  }
  for (JCTree decl : node.getTypeDecls()) {
    if (decl.getTag() == JCTree.Tag.CLASSDEF) {
      String name = ((JCClassDecl) decl).sym.className();
      Collection<Insertion> forClass = insertions.forOuterClass(node, name);
      if (annotator.Main.temporaryDebug) {
        System.out.println("insertions size: " + insertions.size());
        System.out.println("insertions.forOuterClass("+name+") size: " + forClass.size());
        System.out.println("list pre-size: " + list.size());
      }
      list.addAll(forClass);
      if (annotator.Main.temporaryDebug) {
        System.out.println("list post-size: " + list.size());
      }
    }
  }
  return getInsertionsByPosition(node, list);
}
 
Example 12
Source Project: javaide   Source File: Enter.java    License: GNU General Public License v3.0 5 votes vote down vote up
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 13
Source Project: TencentKona-8   Source File: PackageDocImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 Project: openjdk-8-source   Source File: DocImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 15
Source Project: TencentKona-8   Source File: JavadocTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 16
/** Main method: enter classes from the list of toplevel trees, possibly
 *  skipping TypeEnter for all but 'c' by placing them on the uncompleted
 *  list.
 *  @param trees      The list of trees to be processed.
 *  @param c          The class symbol to be processed or null to process all.
 */
public void complete(List<JCCompilationUnit> trees, ClassSymbol c) {
    annotate.blockAnnotations();
    ListBuffer<ClassSymbol> prevUncompleted = uncompleted;
    if (typeEnter.completionEnabled) uncompleted = new ListBuffer<>();

    try {
        // enter all classes, and construct uncompleted list
        classEnter(trees, null);

        // complete all uncompleted classes in memberEnter
        if (typeEnter.completionEnabled) {
            while (uncompleted.nonEmpty()) {
                ClassSymbol clazz = uncompleted.next();
                if (c == null || c == clazz || prevUncompleted == null)
                    clazz.complete();
                else
                    // defer
                    prevUncompleted.append(clazz);
            }

            if (!modules.modulesInitialized()) {
                for (JCCompilationUnit cut : trees) {
                    if (cut.getModuleDecl() != null) {
                        unfinishedModules.append(cut);
                    } else {
                        typeEnter.ensureImportsChecked(List.of(cut));
                    }
                }
            } else {
                typeEnter.ensureImportsChecked(unfinishedModules.toList());
                unfinishedModules.clear();
                typeEnter.ensureImportsChecked(trees);
            }
        }
    } finally {
        uncompleted = prevUncompleted;
        annotate.unblockAnnotations();
    }
}
 
Example 17
/** Complete entering a class.
 *  @param sym         The symbol of the class to be completed.
 */
@Override
public void complete(Symbol sym) throws CompletionFailure {
    // Suppress some (recursive) MemberEnter invocations
    if (!completionEnabled) {
        // Re-install same completer for next time around and return.
        Assert.check((sym.flags() & Flags.COMPOUND) == 0);
        sym.completer = this;
        return;
    }

    try {
        annotate.blockAnnotations();
        sym.flags_field |= UNATTRIBUTED;

        List<Env<AttrContext>> queue;

        dependencies.push((ClassSymbol) sym, CompletionCause.MEMBER_ENTER);
        try {
            queue = completeClass.completeEnvs(List.of(typeEnvs.get((ClassSymbol) sym)));
        } finally {
            dependencies.pop();
        }

        if (!queue.isEmpty()) {
            Set<JCCompilationUnit> seen = new HashSet<>();

            for (Env<AttrContext> env : queue) {
                if (env.toplevel.defs.contains(env.enclClass) && seen.add(env.toplevel)) {
                    finishImports(env.toplevel, () -> {});
                }
            }
        }
    } finally {
        annotate.unblockAnnotations();
    }
}
 
Example 18
Source Project: hottub   Source File: JavadocTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 Project: javaide   Source File: JavaCompiler.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parse contents of file.
 *
 * @param filename The name of the file to be parsed.
 */
public JCCompilationUnit parse(JavaFileObject filename) {
    JavaFileObject prev = log.useSource(filename);
    try {
        JCCompilationUnit t = parse(filename, readSource(filename));
        if (t.endPositions != null)
            log.setEndPosTable(filename, t.endPositions);
        return t;
    } finally {
        log.useSource(prev);
    }
}
 
Example 20
Source Project: jdk8u60   Source File: PackageDocImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 21
/** Create a fresh environment for toplevels.
 *  @param tree     The toplevel tree.
 */
Env<AttrContext> topLevelEnv(JCCompilationUnit tree) {
    Env<AttrContext> localEnv = new Env<>(tree, new AttrContext());
    localEnv.toplevel = tree;
    localEnv.enclClass = predefClassDef;
    tree.toplevelScope = WriteableScope.create(tree.packge);
    tree.namedImportScope = new NamedImportScope(tree.packge, tree.toplevelScope);
    tree.starImportScope = new StarImportScope(tree.packge);
    localEnv.info.scope = tree.toplevelScope;
    localEnv.info.lint = lint;
    return localEnv;
}
 
Example 22
Source Project: openjdk-jdk9   Source File: JavadocTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * From a list of top level trees, return the list of contained class definitions
 */
List<JCClassDecl> listClasses(List<JCCompilationUnit> trees) {
    List<JCClassDecl> result = new ArrayList<>();
    for (JCCompilationUnit t : trees) {
        for (JCTree def : t.defs) {
            if (def.hasTag(JCTree.Tag.CLASSDEF))
                result.add((JCClassDecl)def);
        }
    }
    return result;
}
 
Example 23
Source Project: openjdk-8   Source File: JavadocTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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<JCClassDecl>();
    for (JCCompilationUnit t : trees) {
        for (JCTree def : t.defs) {
            if (def.hasTag(JCTree.Tag.CLASSDEF))
                result.append((JCClassDecl)def);
        }
    }
    return result.toList();
}
 
Example 24
Source Project: openjdk-jdk9   Source File: JavaCompiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** 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 25
Source Project: openjdk-jdk9   Source File: Modules.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 26
public List<JCCompilationUnit> initModules(List<JCCompilationUnit> roots) {
    modules.initModules(roots);
    if (roots.isEmpty()) {
        enterDone();
    }
    return roots;
}
 
Example 27
/**
 * 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 28
Source Project: openjdk-jdk9   Source File: JavaCompiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 29
/**
 * 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 30
Source Project: netbeans   Source File: PartialReparserService.java    License: Apache License 2.0 5 votes vote down vote up
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();
}