com.sun.tools.javac.parser.JavacParser Java Examples

The following examples show how to use com.sun.tools.javac.parser.JavacParser. 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: JavacPlugin.java    From manifold with Apache License 2.0 6 votes vote down vote up
private static void loadJavacParserClass()
{
  synchronized( JavacPlugin.class )
  {
    ClassLoader classLoader = JavacParser.class.getClassLoader();
    if( null == ReflectUtil.method( classLoader, "findLoadedClass", String.class )
      .invoke( "com.sun.tools.javac.parser.ManJavacParser" ) )
    {
      InputStream is1 = JavacPlugin.class.getClassLoader().getResourceAsStream(
        "manifold/internal/javac/ManJavacParser.clazz" );
      try
      {
        byte[] content = StreamUtil.getContent( is1 );
        ReflectUtil.method( classLoader, "defineClass", String.class, byte[].class, int.class, int.class )
          .invoke( "com.sun.tools.javac.parser.ManJavacParser", content, 0, content.length );
      }
      catch( IOException e )
      {
        throw new RuntimeException( e );
      }
    }
  }
}
 
Example #2
Source File: TreePrunerTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
JCCompilationUnit parseLines(String... lines) {
  Context context = new Context();
  try (JavacFileManager fm = new JavacFileManager(context, true, UTF_8)) {
    ParserFactory parserFactory = ParserFactory.instance(context);
    String input = Joiner.on('\n').join(lines);
    JavacParser parser =
        parserFactory.newParser(
            input, /*keepDocComments=*/ false, /*keepEndPos=*/ false, /*keepLineMap=*/ false);
    return parser.parseCompilationUnit();
  } catch (IOException e) {
    throw new IOError(e);
  }
}
 
Example #3
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 #4
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static JCStatement parseStatement(Context context, CharSequence stmt, SourcePositions[] pos, final List<Diagnostic<? extends JavaFileObject>> errors) {
    if (stmt == null || (pos != null && pos.length != 1))
        throw new IllegalArgumentException();
    JavaCompiler compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(new DummyJFO());
    Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
        @Override
        public void report(JCDiagnostic diag) {
            errors.add(diag);
        }            
    };
    try {
        CharBuffer buf = CharBuffer.wrap((stmt+"\u0000").toCharArray(), 0, stmt.length());
        ParserFactory factory = ParserFactory.instance(context);
        ScannerFactory scannerFactory = ScannerFactory.instance(context);
        Names names = Names.instance(context);
        Parser parser = newParser(context, (NBParserFactory) factory, scannerFactory.newScanner(buf, false), false, false, CancelService.instance(context), names);
        if (parser instanceof JavacParser) {
            if (pos != null)
                pos[0] = new ParserSourcePositions((JavacParser)parser);
            return parser.parseStatement();
        }
        return null;
    } finally {
        compiler.log.useSource(prev);
        compiler.log.popDiagnosticHandler(discardHandler);
    }
}
 
Example #5
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static JCExpression parseExpression(Context context, CharSequence expr, boolean onlyFullInput, SourcePositions[] pos, final List<Diagnostic<? extends JavaFileObject>> errors) {
    if (expr == null || (pos != null && pos.length != 1))
        throw new IllegalArgumentException();
    JavaCompiler compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(new DummyJFO());
    Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
        @Override
        public void report(JCDiagnostic diag) {
            errors.add(diag);
        }            
    };
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        ParserFactory factory = ParserFactory.instance(context);
        ScannerFactory scannerFactory = ScannerFactory.instance(context);
        Names names = Names.instance(context);
        Scanner scanner = scannerFactory.newScanner(buf, false);
        Parser parser = newParser(context, (NBParserFactory) factory, scanner, false, false, CancelService.instance(context), names);
        if (parser instanceof JavacParser) {
            if (pos != null)
                pos[0] = new ParserSourcePositions((JavacParser)parser);
            JCExpression result = parser.parseExpression();

            if (!onlyFullInput || scanner.token().kind == TokenKind.EOF) {
                return result;
            }
        }
        return null;
    } finally {
        compiler.log.useSource(prev);
        compiler.log.popDiagnosticHandler(discardHandler);
    }
}
 
Example #6
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static synchronized Parser newParser(Context ctx, NBParserFactory fac,
                                             Lexer S, boolean keepDocComments,
                                             boolean keepLineMap, CancelService cancelService,
                                             Names names) {
    try {
        if (parserClass == null) {
            Method switchBlockStatementGroup = JavacParser.class.getDeclaredMethod("switchBlockStatementGroup");
            Method delegate;
            if (switchBlockStatementGroup.getReturnType().equals(com.sun.tools.javac.util.List.class)) {
                delegate = JackpotJavacParser.class.getDeclaredMethod("switchBlockStatementGroupListImpl");
            } else {
                delegate = JackpotJavacParser.class.getDeclaredMethod("switchBlockStatementGroupImpl");
            }
            parserClass = load(new ByteBuddy()
                                .subclass(JackpotJavacParser.class)
                                .method(ElementMatchers.named("switchBlockStatementGroup")).intercept(MethodCall.invoke(delegate))
                                .make())
                        .getLoaded();
        }
        return (Parser) parserClass.getConstructor(Context.class, NBParserFactory.class, Lexer.class, boolean.class, boolean.class, CancelService.class, Names.class)
                .newInstance(ctx, fac, S, keepDocComments, keepLineMap, cancelService, names);
    } catch (ReflectiveOperationException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #7
Source File: RemoveUnusedImports.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
private static JCCompilationUnit parse(Context context, String javaInput)
    throws FormatterException {
  DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
  context.put(DiagnosticListener.class, diagnostics);
  Options.instance(context).put("--enable-preview", "true");
  Options.instance(context).put("allowStringFolding", "false");
  JCCompilationUnit unit;
  JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
  try {
    fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.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 javaInput;
        }
      };
  Log.instance(context).useSource(source);
  ParserFactory parserFactory = ParserFactory.instance(context);
  JavacParser parser =
      parserFactory.newParser(
          javaInput, /*keepDocComments=*/ true, /*keepEndPos=*/ true, /*keepLineMap=*/ true);
  unit = parser.parseCompilationUnit();
  unit.sourcefile = source;
  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 #8
Source File: PartialReparserService.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public JCBlock reparseMethodBody(CompilationUnitTree topLevel, MethodTree methodToReparse, String newBodyText, int annonIndex,
        final Map<? super JCTree,? super LazyDocCommentTable.Entry> docComments) {
    CharBuffer buf = CharBuffer.wrap((newBodyText+"\u0000").toCharArray(), 0, newBodyText.length());
    JavacParser parser = newParser(context, buf, ((JCBlock)methodToReparse.getBody()).pos, ((JCCompilationUnit)topLevel).endPositions);
    final JCStatement statement = parser.parseStatement();
    NBParserFactory.assignAnonymousClassIndices(Names.instance(context), statement, Names.instance(context).empty, annonIndex);
    if (statement.getKind() == Tree.Kind.BLOCK) {
        if (docComments != null) {
            docComments.putAll(((LazyDocCommentTable) parser.getDocComments()).table);
        }
        return (JCBlock) statement;
    }
    return null;
}
 
Example #9
Source File: CommentCollectingParserFactory.java    From EasyMPermission with MIT License 5 votes vote down vote up
public JavacParser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap) {
	ScannerFactory scannerFactory = ScannerFactory.instance(context);
	Lexer lexer = scannerFactory.newScanner(input, true);
	Object x = new CommentCollectingParser(this, lexer, true, keepLineMap, keepEndPos);
	return (JavacParser) x;
	// CCP is based on a stub which extends nothing, but at runtime the stub is replaced with either
	//javac6's EndPosParser which extends Parser, or javac8's JavacParser which implements Parser.
	//Either way this will work out.
}
 
Example #10
Source File: ManParserFactory.java    From manifold with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
public JavacParser newParser( CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap, boolean parseModuleInfo )
{
  input = _preprocessor.process( _taskEvent.getSourceFile(), input );
  mapInput( _taskEvent.getSourceFile(), input );
  Lexer lexer = ((ScannerFactory)ReflectUtil.field( this, "scannerFactory" ).get()).newScanner(input, keepDocComments);
  return (JavacParser)ReflectUtil.constructor( "com.sun.tools.javac.parser.ManJavacParser",
    ParserFactory.class, Lexer.class, boolean.class, boolean.class, boolean.class, boolean.class )
    .newInstance( this, lexer, keepDocComments, keepLineMap, keepEndPos, parseModuleInfo );
}
 
Example #11
Source File: ReplParserFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public JavacParser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap) {
    com.sun.tools.javac.parser.Lexer lexer = scannerFactory.newScanner(input, keepDocComments);
    return new ReplParser(this, lexer, keepDocComments, keepLineMap, keepEndPos, forceExpression);
}
 
Example #12
Source File: ManParserFactory.java    From manifold with Apache License 2.0 4 votes vote down vote up
@Override
public JavacParser newParser( CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap )
{
  return newParser( input, keepDocComments, keepEndPos, keepLineMap, false );
}
 
Example #13
Source File: TrialParserFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public JavacParser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap, boolean parseModuleInfo) {
    return newParser(input, keepDocComments, keepEndPos, keepLineMap);
}
 
Example #14
Source File: TrialParserFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public JavacParser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap) {
    com.sun.tools.javac.parser.Lexer lexer = scannerFactory.newScanner(input, keepDocComments);
    return new TrialParser(this, lexer, keepDocComments, keepLineMap, keepEndPos);
}
 
Example #15
Source File: ReplParserFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public JavacParser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap, boolean parseModuleInfo) {
    return newParser(input, keepDocComments, keepEndPos, keepLineMap);
}
 
Example #16
Source File: NBParserFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private EndPosTableImpl(Lexer lexer, JavacParser parser, SimpleEndPosTable delegate) {
    super(parser);
    this.lexer = lexer;
    this.delegate = delegate;
}
 
Example #17
Source File: NBParserFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public JavacParser newParser(CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap, boolean parseModuleInfo) {
    Lexer lexer = scannerFactory.newScanner(input, keepDocComments);
    return new NBJavacParser(this, lexer, keepDocComments, keepLineMap, keepEndPos, parseModuleInfo, cancelService);
}
 
Example #18
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private ParserSourcePositions(JavacParser parser) {
    this.parser = parser;
}
 
Example #19
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private ParserSourcePositions(JavacParser parser, int offset) {
    this.parser = parser;
    this.offset = offset;
}
 
Example #20
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static <T extends Tree> T doParse(JavacTaskImpl task, String text, SourcePositions[] sourcePositions, int offset, Function<Parser, T> actualParse) {
    if (text == null || (sourcePositions != null && sourcePositions.length != 1))
        throw new IllegalArgumentException();
    //use a working init order:
    com.sun.tools.javac.main.JavaCompiler.instance(task.getContext());
    com.sun.tools.javac.tree.TreeMaker jcMaker = com.sun.tools.javac.tree.TreeMaker.instance(task.getContext());
    int oldPos = jcMaker.pos;
    
    try {
        //from org/netbeans/modules/java/hints/spiimpl/Utilities.java:
        Context context = task.getContext();
        JavaCompiler compiler = JavaCompiler.instance(context);
        JavaFileObject prev = compiler.log.useSource(new DummyJFO());
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
            @Override
            public void report(JCDiagnostic diag) {
                //ignore:
            }            
        };
        try {
            CharBuffer buf = CharBuffer.wrap((text+"\u0000").toCharArray(), 0, text.length());
            ParserFactory factory = ParserFactory.instance(context);
            Parser parser = factory.newParser(buf, false, true, false, false);
            if (parser instanceof JavacParser) {
                if (sourcePositions != null)
                    sourcePositions[0] = new ParserSourcePositions((JavacParser)parser, offset);
                return actualParse.apply(parser);
            }
            return null;
        } finally {
            compiler.log.useSource(prev);
            compiler.log.popDiagnosticHandler(discardHandler);
        }
    } finally {
        jcMaker.pos = oldPos;
    }
}
 
Example #21
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/**Parses given variable initializer.
 * 
 * @param init initializer code
 * @param sourcePositions return value - new SourcePositions for the new tree
 * @return parsed {@link ExpressionTree} or null?
 */
public ExpressionTree parseVariableInitializer(String init, SourcePositions[] sourcePositions) {
    return doParse(init, sourcePositions, 0, p -> ((JavacParser) p).variableInitializer());
}