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

The following examples show how to use com.sun.tools.javac.parser.ParserFactory. 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: JavacTaskImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #2
Source File: ParsingUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static CompilationUnitTree parseArbitrarySource(JavacTask task, JavaFileObject file) throws IOException {
    JavacTaskImpl taskImpl = (JavacTaskImpl) task;
    com.sun.tools.javac.util.Context context = taskImpl.getContext();
    Log log = Log.instance(context);
    JavaFileObject prevSource = log.useSource(file);
    try {
        ParserFactory fac = ParserFactory.instance(context);
        JCCompilationUnit cut = fac.newParser(file.getCharContent(true), true, true, true).parseCompilationUnit();
        
        cut.sourcefile = file;
        
        return cut;
    } finally {
        log.useSource(prevSource);
    }
}
 
Example #3
Source File: JavacTaskImpl.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 * @param expr the type expression to be analyzed
 * @param scope the scope in which to analyze the type expression
 * @return the type
 * @throws IllegalArgumentException if the type expression of null or empty
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #4
Source File: JavacTrees.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void init(Context context) {
    modules = Modules.instance(context);
    attr = Attr.instance(context);
    enter = Enter.instance(context);
    elements = JavacElements.instance(context);
    log = Log.instance(context);
    resolve = Resolve.instance(context);
    treeMaker = TreeMaker.instance(context);
    memberEnter = MemberEnter.instance(context);
    names = Names.instance(context);
    types = Types.instance(context);
    docTreeMaker = DocTreeMaker.instance(context);
    parser = ParserFactory.instance(context);
    syms = Symtab.instance(context);
    fileManager = context.get(JavaFileManager.class);
    JavacTask t = context.get(JavacTask.class);
    if (t instanceof JavacTaskImpl)
        javacTaskImpl = (JavacTaskImpl) t;
}
 
Example #5
Source File: JavacTaskImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #6
Source File: JavacTaskImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #7
Source File: JavacTaskImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #8
Source File: JavacTaskImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 * @param expr the type expression to be analyzed
 * @param scope the scope in which to analyze the type expression
 * @return the type
 * @throws IllegalArgumentException if the type expression of null or empty
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #9
Source File: JavacTrees.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void init(Context context) {
    modules = Modules.instance(context);
    attr = Attr.instance(context);
    enter = Enter.instance(context);
    elements = JavacElements.instance(context);
    log = Log.instance(context);
    resolve = Resolve.instance(context);
    treeMaker = TreeMaker.instance(context);
    memberEnter = MemberEnter.instance(context);
    names = Names.instance(context);
    types = Types.instance(context);
    docTreeMaker = DocTreeMaker.instance(context);
    parser = ParserFactory.instance(context);
    syms = Symtab.instance(context);
    fileManager = context.get(JavaFileManager.class);
    JavacTask t = context.get(JavacTask.class);
    if (t instanceof JavacTaskImpl)
        javacTaskImpl = (JavacTaskImpl) t;
}
 
Example #10
Source File: JavacTaskImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #11
Source File: JavacTaskImpl.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #12
Source File: JavacTaskImpl.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #13
Source File: JavacTaskImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #14
Source File: JavacTaskImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * For internal use only.  This method will be
 * removed without warning.
 */
public Type parseType(String expr, TypeElement scope) {
    if (expr == null || expr.equals(""))
        throw new IllegalArgumentException();
    compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(null);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Attr attr = Attr.instance(context);
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        Parser parser = parserFactory.newParser(buf, false, false, false);
        JCTree tree = parser.parseType();
        return attr.attribType(tree, (Symbol.TypeSymbol)scope);
    } finally {
        compiler.log.useSource(prev);
    }
}
 
Example #15
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 #16
Source File: DocTreeMaker.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/** Create a tree maker with NOPOS as initial position.
 */
protected DocTreeMaker(Context context) {
    context.put(treeMakerKey, this);
    diags = JCDiagnostic.Factory.instance(context);
    this.pos = Position.NOPOS;
    trees = JavacTrees.instance(context);
    referenceParser = new ReferenceParser(ParserFactory.instance(context));
    sentenceBreakTags = EnumSet.of(H1, H2, H3, H4, H5, H6, PRE, P);
}
 
Example #17
Source File: ReplParser.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public ReplParser(ParserFactory fac,
        com.sun.tools.javac.parser.Lexer S,
        boolean keepDocComments,
        boolean keepLineMap,
        boolean keepEndPositions,
        boolean forceExpression) {
    super(fac, S, keepDocComments, keepLineMap, keepEndPositions);
    this.forceExpression = forceExpression;
}
 
Example #18
Source File: TrialParser.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public TrialParser(ParserFactory fac,
        com.sun.tools.javac.parser.Lexer S,
        boolean keepDocComments,
        boolean keepLineMap,
        boolean keepEndPositions) {
    super(fac, S, keepDocComments, keepLineMap, keepEndPositions);
}
 
Example #19
Source File: TestJavacParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public void test2() {
    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 #20
Source File: ManParserFactory.java    From manifold with Apache License 2.0 5 votes vote down vote up
public static ManParserFactory instance( Context ctx )
{
  ParserFactory parserFactory = ctx.get( parserFactoryKey );
  if( !(parserFactory instanceof ManParserFactory) )
  {
    ctx.put( parserFactoryKey, (ParserFactory)null );
    parserFactory = new ManParserFactory( ctx );
  }

  return (ManParserFactory)parserFactory;
}
 
Example #21
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 #22
Source File: TestLog.java    From hottub 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 #23
Source File: TestLog.java    From openjdk-8-source 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 #24
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 #25
Source File: CommentCollectingParserFactory.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static void setInCompiler(JavaCompiler compiler, Context context) {
	context.put(CommentCollectingParserFactory.key(), (ParserFactory) null);
	Field field;
	try {
		field = JavaCompiler.class.getDeclaredField("parserFactory");
		field.setAccessible(true);
		field.set(compiler, new CommentCollectingParserFactory(context));
	} catch (Exception e) {
		throw new IllegalStateException("Could not set comment sensitive parser in the compiler", e);
	}
}
 
Example #26
Source File: CommentCollectingParserFactory.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static void setInCompiler(JavaCompiler compiler, Context context) {
	context.put(CommentCollectingParserFactory.key(), (ParserFactory)null);
	Field field;
	try {
		field = JavaCompiler.class.getDeclaredField("parserFactory");
		field.setAccessible(true);
		field.set(compiler, new CommentCollectingParserFactory(context));
	} catch (Exception e) {
		throw new IllegalStateException("Could not set comment sensitive parser in the compiler", e);
	}
}
 
Example #27
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 #28
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 #29
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 #30
Source File: TestLog.java    From openjdk-jdk8u 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");
}