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 . 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: JavacTrees.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public String getDocComment(TreePath path) {
    CompilationUnitTree t = path.getCompilationUnit();
    Tree leaf = path.getLeaf();
    if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
        JCCompilationUnit cu = (JCCompilationUnit) t;
        if (cu.docComments != null) {
            return cu.docComments.getCommentText((JCTree) leaf);
        }
    }
    return null;
}
 
Example 2
Source File: JavaParser.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Nullable
public JCTree.JCCompilationUnit parse(final String src) {
    if (!canParse) return null;
    long time = System.currentTimeMillis();

    SimpleJavaFileObject source = new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return src;
        }
    };
    Log.instance(context).useSource(source);
    Parser parser = parserFactory.newParser(src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    JCTree.JCCompilationUnit unit;
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
    android.util.Log.d(TAG, "parse: time " + (System.currentTimeMillis() - time) + " ms");
    return unit;
}
 
Example 3
Source File: ClassSymbols.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Pair<Symbol.ClassSymbol, JCTree.JCCompilationUnit> getClassSymbolForProducedClass( String fqn, BasicJavacTask[] task )
{
  StringWriter errors = new StringWriter();

  // need javac with ManifoldJavaFileManager because the produced class must come from manifold
  task[0] = getJavacTask_ManFileMgr();

  Symbol.ClassSymbol e = IDynamicJdk.instance().getTypeElement( task[0].getContext(), null, fqn );

  if( e != null && e.getSimpleName().contentEquals( ManClassUtil.getShortClassName( fqn ) ) )
  {
    JavacTrees trees = JavacTrees.instance( task[0].getContext() );
    TreePath path = trees.getPath( e );
    if( path != null )
    {
      return new Pair<>( e, (JCTree.JCCompilationUnit)path.getCompilationUnit() );
    }
    else
    {
      // TreePath is only applicable to a source file;
      // if fqn is not a source file, there is no compilation unit available
      return new Pair<>( e, null );
    }
  }

  StringBuffer errorText = errors.getBuffer();
  if( errorText.length() > 0 )
  {
    throw new RuntimeException( "Compile errors:\n" + errorText );
  }

  return null;
}
 
Example 4
Source File: TestJavacParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public void test1() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 5
Source File: JavacTrees.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public String getDocComment(TreePath path) {
    CompilationUnitTree t = path.getCompilationUnit();
    Tree leaf = path.getLeaf();
    if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
        JCCompilationUnit cu = (JCCompilationUnit) t;
        if (cu.docComments != null) {
            return cu.docComments.getCommentText((JCTree) leaf);
        }
    }
    return null;
}
 
Example 6
Source File: JavaCompiler.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 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 7
Source File: JavaParser.java    From rewrite with Apache License 2.0 5 votes vote down vote up
/**
 * Enter symbol definitions into each compilation unit's scope
 */
private void enterAll(Collection<JCTree.JCCompilationUnit> cus) {
    var enter = Enter.instance(context);
    var compilationUnits = com.sun.tools.javac.util.List.from(
            cus.toArray(JCTree.JCCompilationUnit[]::new));
    enter.main(compilationUnits);
}
 
Example 8
Source File: TestJavacParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public void test3() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 9
Source File: JavacTrees.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public String getDocComment(TreePath path) {
    CompilationUnitTree t = path.getCompilationUnit();
    Tree leaf = path.getLeaf();
    if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
        JCCompilationUnit cu = (JCCompilationUnit) t;
        if (cu.docComments != null) {
            return cu.docComments.getCommentText((JCTree) leaf);
        }
    }
    return null;
}
 
Example 10
Source File: NBJavaCompiler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void processAnnotations(List<JCTree.JCCompilationUnit> roots, Collection<String> classnames) {
    if (roots.isEmpty()) {
        super.processAnnotations(roots, classnames);
    } else {
        setOrigin(roots.head.sourcefile.toUri().toString());
        try {
            super.processAnnotations(roots, classnames);
        } finally {
            setOrigin("");
        }
    }
}
 
Example 11
Source File: JavacTrees.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public String getDocComment(TreePath path) {
    CompilationUnitTree t = path.getCompilationUnit();
    Tree leaf = path.getLeaf();
    if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
        JCCompilationUnit cu = (JCCompilationUnit) t;
        if (cu.docComments != null) {
            return cu.docComments.getCommentText((JCTree) leaf);
        }
    }
    return null;
}
 
Example 12
Source File: TestLog.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static void test(boolean genEndPos) throws IOException {
    Context context = new Context();

    Options options = Options.instance(context);
    options.put("diags", "%b:%s/%o/%e:%_%t%m|%p%m");

    Log log = Log.instance(context);
    log.multipleErrors = true;

    JavacFileManager.preRegister(context);
    ParserFactory pfac = ParserFactory.instance(context);

    final String text =
          "public class Foo {\n"
        + "  public static void main(String[] args) {\n"
        + "    if (args.length == 0)\n"
        + "      System.out.println(\"no args\");\n"
        + "    else\n"
        + "      System.out.println(args.length + \" args\");\n"
        + "  }\n"
        + "}\n";
    JavaFileObject fo = new StringJavaFileObject("Foo", text);
    log.useSource(fo);

    CharSequence cs = fo.getCharContent(true);
    Parser parser = pfac.newParser(cs, false, genEndPos, false);
    JCTree.JCCompilationUnit tree = parser.parseCompilationUnit();
    log.setEndPosTable(fo, tree.endPositions);

    TreeScanner ts = new LogTester(log, tree.endPositions);
    ts.scan(tree);

    check(log.nerrors, 4, "errors");
    check(log.nwarnings, 4, "warnings");
}
 
Example 13
Source File: TestJavacParser.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
public void test3() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 14
Source File: JavacTrees.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public DocCommentTree getDocCommentTree(TreePath path) {
    CompilationUnitTree t = path.getCompilationUnit();
    Tree leaf = path.getLeaf();
    if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
        JCCompilationUnit cu = (JCCompilationUnit) t;
        if (cu.docComments != null) {
            return cu.docComments.getCommentTree((JCTree) leaf);
        }
    }
    return null;
}
 
Example 15
Source File: TestLog.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static void test(boolean genEndPos) throws IOException {
    Context context = new Context();

    Options options = Options.instance(context);
    options.put("diags", "%b:%s/%o/%e:%_%t%m|%p%m");

    Log log = Log.instance(context);
    log.multipleErrors = true;

    JavacFileManager.preRegister(context);
    ParserFactory pfac = ParserFactory.instance(context);

    final String text =
          "public class Foo {\n"
        + "  public static void main(String[] args) {\n"
        + "    if (args.length == 0)\n"
        + "      System.out.println(\"no args\");\n"
        + "    else\n"
        + "      System.out.println(args.length + \" args\");\n"
        + "  }\n"
        + "}\n";
    JavaFileObject fo = new StringJavaFileObject("Foo", text);
    log.useSource(fo);

    CharSequence cs = fo.getCharContent(true);
    Parser parser = pfac.newParser(cs, false, genEndPos, false);
    JCTree.JCCompilationUnit tree = parser.parseCompilationUnit();
    log.setEndPosTable(fo, tree.endPositions);

    TreeScanner ts = new LogTester(log, tree.endPositions);
    ts.scan(tree);

    check(log.nerrors, 4, "errors");
    check(log.nwarnings, 4, "warnings");
}
 
Example 16
Source File: StringWrapper.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
/** Parses the given Java source. */
private static JCTree.JCCompilationUnit parse(String source, boolean allowStringFolding)
    throws FormatterException {
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
  Context context = new Context();
  context.put(DiagnosticListener.class, diagnostics);
  Options.instance(context).put("--enable-preview", "true");
  Options.instance(context).put("allowStringFolding", Boolean.toString(allowStringFolding));
  JCTree.JCCompilationUnit unit;
  JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
  try {
    fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.of());
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
  SimpleJavaFileObject sjfo =
      new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
          return source;
        }
      };
  Log.instance(context).useSource(sjfo);
  ParserFactory parserFactory = ParserFactory.instance(context);
  JavacParser parser =
      parserFactory.newParser(
          source, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true);
  unit = parser.parseCompilationUnit();
  unit.sourcefile = sjfo;
  Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics =
      Iterables.filter(diagnostics.getDiagnostics(), Formatter::errorDiagnostic);
  if (!Iterables.isEmpty(errorDiagnostics)) {
    // error handling is done during formatting
    throw FormatterException.fromJavacDiagnostics(errorDiagnostics);
  }
  return unit;
}
 
Example 17
Source File: ExtensionTransformer.java    From manifold with Apache License 2.0 5 votes vote down vote up
private Symbol.VarSymbol resolveField( JCDiagnostic.DiagnosticPosition pos, Context ctx, Name name, Type qual )
{
  Resolve rs = Resolve.instance( ctx );
  AttrContext attrContext = new AttrContext();
  Env<AttrContext> env = new AttrContextEnv( pos.getTree(), attrContext );
  env.toplevel = (JCTree.JCCompilationUnit)_tp.getCompilationUnit();
  return rs.resolveInternalField( pos, env, qual, name );
}
 
Example 18
Source File: GeneratorUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
static <T extends Tree> T importComments(CompilationInfo info, T original, CompilationUnitTree cut) {
    try {
        CommentSetImpl comments = CommentHandlerService.instance(info.impl.getJavacTask().getContext()).getComments(original);

        if (comments.areCommentsMapped()) {
            //optimalization, if comments are already mapped, do not even try to
            //map them again, would not be attached anyway:
            return original;
        }
        
        JCTree.JCCompilationUnit unit = (JCCompilationUnit) cut;
        TokenHierarchy<?> tokens =   unit.getSourceFile() instanceof AbstractSourceFileObject
                                   ? ((AbstractSourceFileObject) unit.getSourceFile()).getTokenHierarchy()
                                   : TokenHierarchy.create(unit.getSourceFile().getCharContent(true), JavaTokenId.language());
        TokenSequence<JavaTokenId> seq = tokens.tokenSequence(JavaTokenId.language());
        TreePath tp = TreePath.getPath(cut, original);
        Tree toMap = original;
        Tree mapTarget = null;
        
        if (tp != null && original.getKind() != Kind.COMPILATION_UNIT) {
            // find some 'nice' place like method/class/field so the comments get an appropriate contents
            // Javadocs or other comments may be assigned inappropriately with wider surrounding contents.
            TreePath p2 = tp;
            boolean first = true;
            B: while (p2 != null) {
                Tree.Kind k = p2.getLeaf().getKind();
                if (StatementTree.class.isAssignableFrom(k.asInterface())) {
                    mapTarget = p2.getLeaf();
                    p2 = p2.getParentPath();
                    break;
                }
               switch (p2.getLeaf().getKind()) {
                   case CLASS: case INTERFACE: case ENUM:
                   case METHOD:
                   case BLOCK:
                   case VARIABLE:
                       if (mapTarget == null) {
                           mapTarget = p2.getLeaf();
                       }
                       if (first) {
                           p2 = p2 = p2.getParentPath();
                       }
                       break B;
               } 
               first = false;
               p2 = p2.getParentPath();
            }
            if (p2 != null) {
                toMap = p2.getLeaf();
            }
            if (toMap == tp.getLeaf()) {
                // go at least one level up in a hope it's sufficient.
                toMap = tp.getParentPath().getLeaf();
            }
        }
        if (mapTarget == null) {
            mapTarget = original;
        }
        AssignComments translator = new AssignComments(info, mapTarget, seq, unit);
        
        translator.scan(toMap, null);

        return original;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    return original;
}
 
Example 19
Source File: JavaParser.java    From rewrite with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize modules
 */
private void initModules(Collection<JCTree.JCCompilationUnit> cus) {
    var modules = Modules.instance(context);
    modules.initModules(com.sun.tools.javac.util.List.from(cus));
}
 
Example 20
Source File: TestLog.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static void test(boolean genEndPos) throws Exception {
    Context context = new Context();

    Options options = Options.instance(context);
    options.put("diags", "%b:%s/%o/%e:%_%t%m|%p%m");

    Log log = Log.instance(context);
    Factory diagnosticFactory = JCDiagnostic.Factory.instance(context);
    Field defaultErrorFlagsField =
            JCDiagnostic.Factory.class.getDeclaredField("defaultErrorFlags");

    defaultErrorFlagsField.setAccessible(true);

    Set<DiagnosticFlag> defaultErrorFlags =
            (Set<DiagnosticFlag>) defaultErrorFlagsField.get(diagnosticFactory);

    defaultErrorFlags.add(DiagnosticFlag.MULTIPLE);

    JavacFileManager.preRegister(context);
    ParserFactory pfac = ParserFactory.instance(context);

    final String text =
          "public class Foo {\n"
        + "  public static void main(String[] args) {\n"
        + "    if (args.length == 0)\n"
        + "      System.out.println(\"no args\");\n"
        + "    else\n"
        + "      System.out.println(args.length + \" args\");\n"
        + "  }\n"
        + "}\n";
    JavaFileObject fo = new StringJavaFileObject("Foo", text);
    log.useSource(fo);

    CharSequence cs = fo.getCharContent(true);
    Parser parser = pfac.newParser(cs, false, genEndPos, false);
    JCTree.JCCompilationUnit tree = parser.parseCompilationUnit();
    log.setEndPosTable(fo, tree.endPositions);

    TreeScanner ts = new LogTester(log, tree.endPositions);
    ts.scan(tree);

    check(log.nerrors, 4, "errors");
    check(log.nwarnings, 4, "warnings");
}