com.sun.tools.javac.main.JavaCompiler Java Examples

The following examples show how to use com.sun.tools.javac.main.JavaCompiler. 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 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 #2
Source File: JavacProcessingEnvironment.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/** Create a round (common code). */
private Round(Context context, int number, int priorErrors, int priorWarnings,
        Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
    this.context = context;
    this.number = number;

    compiler = JavaCompiler.instance(context);
    log = Log.instance(context);
    log.nerrors = priorErrors;
    log.nwarnings = priorWarnings;
    if (number == 1) {
        Assert.checkNonNull(deferredDiagnosticHandler);
        this.deferredDiagnosticHandler = deferredDiagnosticHandler;
    } else {
        this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
    }

    // the following is for the benefit of JavacProcessingEnvironment.getContext()
    JavacProcessingEnvironment.this.context = context;

    // the following will be populated as needed
    topLevelClasses  = List.nil();
    packageInfoFiles = List.nil();
}
 
Example #3
Source File: Dependencies.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build a Dependencies instance.
 */
GraphDependencies(Context context) {
    super(context);
    //fetch filename
    Options options = Options.instance(context);
    String[] modes = options.get("debug.completionDeps").split(",");
    for (String mode : modes) {
        if (mode.startsWith("file=")) {
            dependenciesFile = mode.substring(5);
        }
    }
    //parse modes
    dependenciesModes = DependenciesMode.getDependenciesModes(modes);
    //add to closeables
    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.closeables = compiler.closeables.prepend(this);
}
 
Example #4
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 #5
Source File: PubApiExtractor.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
     * Setup a compilation context, used for reading public apis of classes on the classpath
     * as well as annotation processors.
     */
    public PubApiExtractor(Options options) {
        JavacTool compiler = com.sun.tools.javac.api.JavacTool.create();
        fileManager = new SmartFileManager(compiler.getStandardFileManager(null, null, null));
        context = new com.sun.tools.javac.util.Context();
        String[] args = options.prepJavacArgs();
        task = compiler.getTask(new PrintWriter(System.err),
                                fileManager,
                                null,
                                Arrays.asList(args),
                                null,
                                null,
                                context);
        // Trigger a creation of the JavaCompiler, necessary to get a sourceCompleter for ClassFinder.
        // The sourceCompleter is used for build situations where a classpath class references other classes
        // that happens to be on the sourcepath.
        JavaCompiler.instance(context);

//        context.put(JavaFileManager.class, fileManager);
    }
 
Example #6
Source File: JavacProcessingEnvironment.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void initProcessorClassLoader() {
    JavaFileManager fileManager = context.get(JavaFileManager.class);
    try {
        // If processorpath is not explicitly set, use the classpath.
        processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
            ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH)
            : fileManager.getClassLoader(CLASS_PATH);

        if (processorClassLoader != null && processorClassLoader instanceof Closeable) {
            JavaCompiler compiler = JavaCompiler.instance(context);
            compiler.closeables = compiler.closeables.prepend((Closeable) processorClassLoader);
        }
    } catch (SecurityException e) {
        processorClassLoaderException = e;
    }
}
 
Example #7
Source File: JavacProcessingEnvironment.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/** Create a round (common code). */
private Round(Context context, int number, int priorErrors, int priorWarnings,
        Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
    this.context = context;
    this.number = number;

    compiler = JavaCompiler.instance(context);
    log = Log.instance(context);
    log.nerrors = priorErrors;
    log.nwarnings = priorWarnings;
    if (number == 1) {
        Assert.checkNonNull(deferredDiagnosticHandler);
        this.deferredDiagnosticHandler = deferredDiagnosticHandler;
    } else {
        this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
    }

    // the following is for the benefit of JavacProcessingEnvironment.getContext()
    JavacProcessingEnvironment.this.context = context;

    // the following will be populated as needed
    topLevelClasses  = List.nil();
    packageInfoFiles = List.nil();
}
 
Example #8
Source File: T6358168.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void testNoAnnotationProcessing(JavacFileManager fm, JavaFileObject f) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(new String[] { "-d", "." });

    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.compile(List.of(f));
    try {
        compiler.compile(List.of(f));
        throw new Error("Error: AssertionError not thrown after second call of compile");
    } catch (AssertionError e) {
        System.err.println("Exception from compiler (expected): " + e);
    }
}
 
Example #9
Source File: T6358166.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
static void test(JavacFileManager fm, JavaFileObject f, String... args) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(args);

    JavaCompiler c = JavaCompiler.instance(context);

    c.compile(List.of(f));

    if (c.errorCount() != 0)
        throw new AssertionError("compilation failed");

    long msec = c.elapsed_msec;
    if (msec < 0 || msec > 5 * 60 * 1000) // allow test 5 mins to execute, should be more than enough!
        throw new AssertionError("elapsed time is suspect: " + msec);
}
 
Example #10
Source File: T6358166.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
static void test(JavacFileManager fm, JavaFileObject f, String... args) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(args);

    JavaCompiler c = JavaCompiler.instance(context);

    c.compile(List.of(f));

    if (c.errorCount() != 0)
        throw new AssertionError("compilation failed");

    long msec = c.elapsed_msec;
    if (msec < 0 || msec > 5 * 60 * 1000) // allow test 5 mins to execute, should be more than enough!
        throw new AssertionError("elapsed time is suspect: " + msec);
}
 
Example #11
Source File: BlazeJavaCompiler.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Adds an initialization hook to the Context, such that requests for a JavaCompiler (i.e., a
 * lookup for 'compilerKey' of our superclass, JavaCompiler) will actually construct and return
 * BlazeJavaCompiler.
 *
 * <p>This is the preferred way for extending behavior within javac, per the documentation in
 * {@link Context}.
 *
 * <p>Prior to JDK-8038455 additional JavaCompilers were created for annotation processing rounds,
 * but we now expect a single compiler instance per compilation. The factory is still seems to be
 * necessary to avoid context-ordering issues, but we assert that the factory is only called once,
 * and save the output after its call for introspection.
 */
public static void preRegister(
    final Context context, final Iterable<BlazeJavaCompilerPlugin> plugins) {
  context.put(
      compilerKey,
      new Context.Factory<JavaCompiler>() {
        boolean first = true;

        @Override
        public JavaCompiler make(Context c) {
          if (!first) {
            throw new AssertionError("Expected a single creation of BlazeJavaCompiler.");
          }
          first = false;
          return new BlazeJavaCompiler(c, plugins);
        }
      });
}
 
Example #12
Source File: T6358166.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void test(JavacFileManager fm, JavaFileObject f, String... args) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(args);

    JavaCompiler c = JavaCompiler.instance(context);

    c.compile(List.of(f));

    if (c.errorCount() != 0)
        throw new AssertionError("compilation failed");

    long msec = c.elapsed_msec;
    if (msec < 0 || msec > 5 * 60 * 1000) // allow test 5 mins to execute, should be more than enough!
        throw new AssertionError("elapsed time is suspect: " + msec);
}
 
Example #13
Source File: T6358168.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void testNoAnnotationProcessing(JavacFileManager fm, JavaFileObject f) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(new String[] { "-d", "." });

    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.compile(List.of(f));
    try {
        compiler.compile(List.of(f));
        throw new Error("Error: AssertionError not thrown after second call of compile");
    } catch (AssertionError e) {
        System.err.println("Exception from compiler (expected): " + e);
    }
}
 
Example #14
Source File: T6358168.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void testAnnotationProcessing(JavacFileManager fm, JavaFileObject f) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(new String[] {
                                 "-XprintRounds",
                                 "-processorpath", testClasses,
                                 "-processor", self,
                                 "-d", "."});

    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.initProcessAnnotations(null);
    JavaCompiler compiler2 = compiler.processAnnotations(compiler.enterTrees(compiler.parseFiles(List.of(f))));
    try {
        compiler2.compile(List.of(f));
        throw new Error("Error: AssertionError not thrown after second call of compile");
    } catch (AssertionError e) {
        System.err.println("Exception from compiler (expected): " + e);
    }
}
 
Example #15
Source File: T4910483.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String... args) {
    JavaCompiler compiler = JavaCompiler.instance(new Context());
    compiler.keepComments = true;

    String testSrc = System.getProperty("test.src");
    JavacFileManager fm = new JavacFileManager(new Context(), false, null);
    JavaFileObject f = fm.getJavaFileObject(testSrc + File.separatorChar + "T4910483.java");

    JCTree.JCCompilationUnit cu = compiler.parse(f);
    JCTree classDef = cu.getTypeDecls().head;
    String commentText = cu.docComments.getCommentText(classDef);

    String expected = "Test comment abc*\\\\def"; // 4 '\' escapes to 2 in a string literal
    if (!expected.equals(commentText)) {
        throw new AssertionError("Incorrect comment text: [" + commentText + "], expected [" + expected + "]");
    }
}
 
Example #16
Source File: JStructPlugin.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void wrapCompiler(Context c) throws Exception {
	Context.Key<JavaCompiler> compilerKey = read(JavaCompiler.class, "compilerKey");
	JavaCompiler comp = c.get(compilerKey);
	
	Unsafe u = getUnsafe();
	JavaCompilerWrapper jcw = (JavaCompilerWrapper)u.allocateInstance(JavaCompilerWrapper.class);
	//now gotta copy all the nonstatic fields
	Class jc = JavaCompiler.class;
	Field[] fs = jc.getDeclaredFields();
	for(Field f : fs) {
		if(!Modifier.isStatic(f.getModifiers())) {
			f.setAccessible(true);
			f.set(jcw, f.get(comp));
		}
	}
	c.put(compilerKey, (JavaCompiler)null);
	c.put(compilerKey, (JavaCompiler)jcw);
}
 
Example #17
Source File: T6358168.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
static void testAnnotationProcessing(JavacFileManager fm, JavaFileObject f) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(new String[] {
                                 "-XprintRounds",
                                 "-processorpath", testClasses,
                                 "-processor", self,
                                 "-d", "."});

    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.initProcessAnnotations(null);
    JavaCompiler compiler2 = compiler.processAnnotations(compiler.enterTrees(compiler.parseFiles(List.of(f))));
    try {
        compiler2.compile(List.of(f));
        throw new Error("Error: AssertionError not thrown after second call of compile");
    } catch (AssertionError e) {
        System.err.println("Exception from compiler (expected): " + e);
    }
}
 
Example #18
Source File: T6358168.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
static void testNoAnnotationProcessing(JavacFileManager fm, JavaFileObject f) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(new String[] { "-d", "." });

    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.compile(List.of(f));
    try {
        compiler.compile(List.of(f));
        throw new Error("Error: AssertionError not thrown after second call of compile");
    } catch (AssertionError e) {
        System.err.println("Exception from compiler (expected): " + e);
    }
}
 
Example #19
Source File: T6358168.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static void testNoAnnotationProcessing(JavacFileManager fm, List<JavaFileObject> files) throws Throwable {
    Context context = new Context();

    String[] args = { "-d", "." };

    JavacTool tool = JavacTool.create();
    JavacTask task = tool.getTask(null, fm, null, List.from(args), null, files, context);
    // no need in this simple case to call task.prepareCompiler(false)

    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.compile(files);
    try {
        compiler.compile(files);
        throw new Error("Error: AssertionError not thrown after second call of compile");
    } catch (AssertionError e) {
        System.err.println("Exception from compiler (expected): " + e);
    }
}
 
Example #20
Source File: T6358168.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
static void testNoAnnotationProcessing(JavacFileManager fm, JavaFileObject f) throws Throwable {
    Context context = new Context();
    fm.setContext(context);

    Main compilerMain = new Main("javac", new PrintWriter(System.err, true));
    compilerMain.setOptions(Options.instance(context));
    compilerMain.filenames = new LinkedHashSet<File>();
    compilerMain.processArgs(new String[] { "-d", "." });

    JavaCompiler compiler = JavaCompiler.instance(context);
    compiler.compile(List.of(f));
    try {
        compiler.compile(List.of(f));
        throw new Error("Error: AssertionError not thrown after second call of compile");
    } catch (AssertionError e) {
        System.err.println("Exception from compiler (expected): " + e);
    }
}
 
Example #21
Source File: JavacProcessingEnvironment.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/** Create a round (common code). */
private Round(Context context, int number, int priorErrors, int priorWarnings,
        Log.DeferredDiagnosticHandler deferredDiagnosticHandler) {
    this.context = context;
    this.number = number;

    compiler = JavaCompiler.instance(context);
    log = Log.instance(context);
    log.nerrors = priorErrors;
    log.nwarnings = priorWarnings;
    if (number == 1) {
        Assert.checkNonNull(deferredDiagnosticHandler);
        this.deferredDiagnosticHandler = deferredDiagnosticHandler;
    } else {
        this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
    }

    // the following is for the benefit of JavacProcessingEnvironment.getContext()
    JavacProcessingEnvironment.this.context = context;

    // the following will be populated as needed
    topLevelClasses  = List.nil();
    packageInfoFiles = List.nil();
}
 
Example #22
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 #23
Source File: JavacElements.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected JavacElements(Context context) {
    context.put(JavacElements.class, this);
    javaCompiler = JavaCompiler.instance(context);
    syms = Symtab.instance(context);
    modules = Modules.instance(context);
    names = Names.instance(context);
    types = Types.instance(context);
    enter = Enter.instance(context);
    resolve = Resolve.instance(context);
    JavacTask t = context.get(JavacTask.class);
    javacTaskImpl = t instanceof JavacTaskImpl ? (JavacTaskImpl) t : null;
    log = Log.instance(context);
    Source source = Source.instance(context);
    allowModules = source.allowModules();
}
 
Example #24
Source File: PackageProcessor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void init(ProcessingEnvironment env) {
    super.init(env);
    JavacTask.instance(env).addTaskListener(listener);
    Context ctx = ((JavacProcessingEnvironment)processingEnv).getContext();
    JavaCompiler compiler = JavaCompiler.instance(ctx);
    compiler.shouldStopPolicyIfNoError = CompileState.max(compiler.shouldStopPolicyIfNoError,
            CompileState.FLOW);
}
 
Example #25
Source File: Hacks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Scope constructScope(CompilationInfo info, String... importedClasses) {
    StringBuilder clazz = new StringBuilder();

    clazz.append("package $$;\n");

    for (String i : importedClasses) {
        clazz.append("import ").append(i).append(";\n");
    }

    clazz.append("public class $$scopeclass$").append(inc++).append("{");

    clazz.append("private void test() {\n");
    clazz.append("}\n");
    clazz.append("}\n");

    JavacTaskImpl jti = JavaSourceAccessor.getINSTANCE().getJavacTask(info);
    Context context = jti.getContext();

    JavaCompiler jc = JavaCompiler.instance(context);
    Log.instance(context).nerrors = 0;

    JavaFileObject jfo = FileObjects.memoryFileObject("$$", "$", new File("/tmp/t.java").toURI(), System.currentTimeMillis(), clazz.toString());

    try {
        CompilationUnitTree cut = ParserFactory.instance(context).newParser(jfo.getCharContent(true), true, true, true).parseCompilationUnit();

        jti.analyze(jti.enter(Collections.singletonList(cut)));

        return new ScannerImpl().scan(cut, info);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        return null;
    } finally {
    }
}
 
Example #26
Source File: JavaCompilerWithDeps.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void preRegister(Context context, final CompilerThread t) {
    context.put(compilerKey, new Context.Factory<JavaCompiler>() {
        public JavaCompiler make(Context c) {
            JavaCompiler instance = new JavaCompilerWithDeps(c, t);
            c.put(JavaCompiler.class, instance);
            return instance;
        }
    });
}
 
Example #27
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(), (Parser.Factory)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 #28
Source File: JavacProcessingEnvironment.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected JavacProcessingEnvironment(Context context) {
    this.context = context;
    context.put(JavacProcessingEnvironment.class, this);
    log = Log.instance(context);
    source = Source.instance(context);
    diags = JCDiagnostic.Factory.instance(context);
    options = Options.instance(context);
    printProcessorInfo = options.isSet(XPRINTPROCESSORINFO);
    printRounds = options.isSet(XPRINTROUNDS);
    verbose = options.isSet(VERBOSE);
    lint = Lint.instance(context).isEnabled(PROCESSING);
    if (options.isSet(PROC, "only") || options.isSet(XPRINT)) {
        JavaCompiler compiler = JavaCompiler.instance(context);
        compiler.shouldStopPolicyIfNoError = CompileState.PROCESS;
    }
    fatalErrors = options.isSet("fatalEnterError");
    showResolveErrors = options.isSet("showResolveErrors");
    werror = options.isSet(WERROR);
    platformAnnotations = initPlatformAnnotations();

    // Initialize services before any processors are initialized
    // in case processors use them.
    filer = new JavacFiler(context);
    messager = new JavacMessager(context, this);
    elementUtils = JavacElements.instance(context);
    typeUtils = JavacTypes.instance(context);
    processorOptions = initProcessorOptions(context);
    unmatchedProcessorOptions = initUnmatchedProcessorOptions();
    messages = JavacMessages.instance(context);
    taskListener = MultiTaskListener.instance(context);
    initProcessorClassLoader();
}
 
Example #29
Source File: JavaParser.java    From rewrite with Apache License 2.0 5 votes vote down vote up
public JavaParser(@Nullable List<Path> classpath, Charset charset, boolean relaxedClassTypeMatching) {
    this.classpath = classpath;
    this.charset = charset;
    this.relaxedClassTypeMatching = relaxedClassTypeMatching;
    this.pfm = new JavacFileManager(context, true, charset);

    // otherwise, consecutive string literals in binary expressions are concatenated by the parser, losing the original
    // structure of the expression!
    Options.instance(context).put("allowStringFolding", "false");

    // MUST be created (registered with the context) after pfm and compilerLog
    compiler = new JavaCompiler(context);

    // otherwise the JavacParser will use EmptyEndPosTable, effectively setting -1 as the end position
    // for every tree element
    compiler.genEndPos = true;
    compiler.keepComments = true;

    compilerLog.setWriters(new PrintWriter(new Writer() {
        @Override
        public void write(char[] cbuf, int off, int len) {
            var log = new String(Arrays.copyOfRange(cbuf, off, len));
            if (logCompilationWarningsAndErrors && !log.isBlank()) {
                logger.warn(log);
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() {
        }
    }));
}
 
Example #30
Source File: PackageProcessor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void init(ProcessingEnvironment env) {
    super.init(env);
    JavacTask.instance(env).addTaskListener(listener);
    Context ctx = ((JavacProcessingEnvironment)processingEnv).getContext();
    JavaCompiler compiler = JavaCompiler.instance(ctx);
    compiler.shouldStopPolicyIfNoError = CompileState.max(compiler.shouldStopPolicyIfNoError,
            CompileState.FLOW);
}