Java Code Examples for com.sun.tools.javac.parser.ParserFactory#instance()

The following examples show how to use com.sun.tools.javac.parser.ParserFactory#instance() . 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 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 2
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 3
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 4
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 5
Source File: TestJavacParser.java    From java-n-IDE-for-Android with Apache License 2.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 6
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 7
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 8
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 9
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 10
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 11
Source File: JavaParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public JavaParser() {
    context = new Context();
    diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        canParse = false;
    }
    parserFactory = ParserFactory.instance(context);
}
 
Example 12
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 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: TestJavacParser.java    From java-n-IDE-for-Android with Apache License 2.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 15
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 16
Source File: Formatter.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Construct a {@code Formatter} given a Java compilation unit. Parses the code; builds a {@link
 * JavaInput} and the corresponding {@link JavaOutput}.
 *
 * @param javaInput  the input, a Java compilation unit
 * @param javaOutput the {@link JavaOutput}
 * @param options    the {@link JavaFormatterOptions}
 */
static void format(
        final JavaInput javaInput, JavaOutput javaOutput, JavaFormatterOptions options) {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    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 javaInput.getText();
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    javaInput.getText(),
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;

    javaInput.setCompilationUnit(unit);
    Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics =
            Iterables.filter(diagnostics.getDiagnostics(), ERROR_DIAGNOSTIC);
    if (!Iterables.isEmpty(errorDiagnostics)) {
        throw FormattingError.fromJavacDiagnostics(errorDiagnostics);
    }
    OpsBuilder builder = new OpsBuilder(javaInput, javaOutput);
    // Output the compilation unit.
    new JavaInputAstVisitor(builder, options.indentationMultiplier()).scan(unit, null);
    builder.sync(javaInput.getText().length());
    builder.drain();
    Doc doc = new DocBuilder().withOps(builder.build()).build();
    doc.computeBreaks(
            javaOutput.getCommentsHelper(), options.maxLineLength(), new Doc.State(+0, 0));
    doc.write(javaOutput);
    javaOutput.flush();
}
 
Example 17
Source File: ParserTest.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
public void test1() {
    final String src = "package com.duy;\n" +
            "\n" +
            "import java.util.ArrayList;\n" +
            "/** * Created by Duy on 17-Jul-17. */\n" +
            "public class Main {\n" +
            "    public static void main(String[] args) {\n" +
            "        ArrayList list = new ArrayList();\n" +
            "        for (int i = 0; i < 1000; i++) {\n" +
            "            list.add(i);\n" +
            "        }\n" +
            "    }\n" +
            "\n";
    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();
    System.out.println(unit.getImports());

}
 
Example 18
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");
}
 
Example 19
Source File: JavaCompiler.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Construct a new compiler using a shared context.
 */
public JavaCompiler(Context context) {
    this.context = context;
    context.put(compilerKey, this);

    // if fileManager not already set, register the JavacFileManager to be used
    if (context.get(JavaFileManager.class) == null)
        JavacFileManager.preRegister(context);

    names = Names.instance(context);
    log = Log.instance(context);
    diagFactory = JCDiagnostic.Factory.instance(context);
    reader = ClassReader.instance(context);
    make = TreeMaker.instance(context);
    writer = ClassWriter.instance(context);
    enter = Enter.instance(context);
    todo = Todo.instance(context);

    fileManager = context.get(JavaFileManager.class);
    parserFactory = ParserFactory.instance(context);

    try {
        // catch completion problems with predefineds
        syms = Symtab.instance(context);
    } catch (CompletionFailure ex) {
        // inlined Check.completionError as it is not initialized yet
        log.error("cant.access", ex.sym, ex.getDetailValue());
        if (ex instanceof ClassReader.BadClassFile)
            throw new Abort();
    }
    source = Source.instance(context);
    attr = Attr.instance(context);
    chk = Check.instance(context);
    gen = Gen.instance(context);
    flow = Flow.instance(context);
    transTypes = TransTypes.instance(context);
    lower = Lower.instance(context);
    annotate = Annotate.instance(context);
    types = Types.instance(context);
    taskListener = context.get(TaskListener.class);

    reader.sourceCompleter = this;

    options = Options.instance(context);

    verbose = options.isSet(VERBOSE);
    sourceOutput = options.isSet(PRINTSOURCE); // used to be -s
    stubOutput = options.isSet("-stubs");
    relax = options.isSet("-relax");
    printFlat = options.isSet("-printflat");
    attrParseOnly = options.isSet("-attrparseonly");
    encoding = options.get(ENCODING);
    lineDebugInfo = options.isUnset(G_CUSTOM) ||
            options.isSet(G_CUSTOM, "lines");
    genEndPos = options.isSet(XJCOV) ||
            context.get(DiagnosticListener.class) != null;
    devVerbose = options.isSet("dev");
    processPcks = options.isSet("process.packages");
    werror = options.isSet(WERROR);

    if (source.compareTo(Source.DEFAULT) < 0) {
        if (options.isUnset(XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option)) {
            if (fileManager instanceof BaseFileManager) {
                if (((BaseFileManager) fileManager).isDefaultBootClassPath())
                    log.warning(LintCategory.OPTIONS, "source.no.bootclasspath", source.name);
            }
        }
    }

    verboseCompilePolicy = options.isSet("verboseCompilePolicy");

    if (attrParseOnly)
        compilePolicy = CompilePolicy.ATTR_ONLY;
    else
        compilePolicy = CompilePolicy.decode(options.get("compilePolicy"));

    implicitSourcePolicy = ImplicitSourcePolicy.decode(options.get("-implicit"));

    completionFailureName =
            options.isSet("failcomplete")
                    ? names.fromString(options.get("failcomplete"))
                    : null;

    shouldStopPolicy =
            options.isSet("shouldStopPolicy")
                    ? CompileState.valueOf(options.get("shouldStopPolicy"))
                    : null;
    if (options.isUnset("oldDiags"))
        log.setDiagnosticFormatter(RichDiagnosticFormatter.instance(context));
}
 
Example 20
Source File: Formatter.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Construct a {@code Formatter} given a Java compilation unit. Parses the code; builds a {@link
 * JavaInput} and the corresponding {@link JavaOutput}.
 *
 * @param javaInput  the input, a Java compilation unit
 * @param javaOutput the {@link JavaOutput}
 * @param options    the {@link JavaFormatterOptions}
 */
static void format(
        final JavaInput javaInput, JavaOutput javaOutput, JavaFormatterOptions options) {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    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 javaInput.getText();
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    javaInput.getText(),
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;

    javaInput.setCompilationUnit(unit);
    Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics =
            Iterables.filter(diagnostics.getDiagnostics(), ERROR_DIAGNOSTIC);
    if (!Iterables.isEmpty(errorDiagnostics)) {
        throw FormattingError.fromJavacDiagnostics(errorDiagnostics);
    }
    OpsBuilder builder = new OpsBuilder(javaInput, javaOutput);
    // Output the compilation unit.
    new JavaInputAstVisitor(builder, options.indentationMultiplier()).scan(unit, null);
    builder.sync(javaInput.getText().length());
    builder.drain();
    Doc doc = new DocBuilder().withOps(builder.build()).build();
    doc.computeBreaks(
            javaOutput.getCommentsHelper(), options.maxLineLength(), new Doc.State(+0, 0));
    doc.write(javaOutput);
    javaOutput.flush();
}