Java Code Examples for com.sun.tools.javac.main.JavaCompiler#instance()
The following examples show how to use
com.sun.tools.javac.main.JavaCompiler#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: T6358166.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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 2
Source File: T6358168.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
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 3
Source File: JavacProcessingEnvironment.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** 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 4
Source File: T6358168.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
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 5
Source File: T6358168.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
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 6
Source File: T6358168.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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 7
Source File: JavacTaskImpl.java From javaide with GNU General Public License v3.0 | 6 votes |
/** * 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 8
Source File: JavacTaskImpl.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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: JavacTaskImpl.java From java-n-IDE-for-Android with Apache License 2.0 | 6 votes |
/** * 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 10
Source File: JavacProcessingEnvironment.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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 11
Source File: PubApiExtractor.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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 12
Source File: JavacElements.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
/** * Use a new context. May be called from outside to update * internal state for a new annotation-processing round. */ public void setContext(Context context) { context.put(JavacElements.class, this); javaCompiler = JavaCompiler.instance(context); syms = Symtab.instance(context); names = Names.instance(context); types = Types.instance(context); enter = Enter.instance(context); }
Example 13
Source File: TypeProcOnly.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
@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 14
Source File: TypeProcOnly.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
@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 15
Source File: TestResolveIdent.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws IOException { javax.tools.JavaCompiler tool = ToolProvider.getSystemJavaCompiler(); JavacTaskImpl task = (JavacTaskImpl)tool.getTask(null, null, null, null, null, null); JavaCompiler compiler = JavaCompiler.instance(task.getContext()); Symtab syms = Symtab.instance(task.getContext()); task.ensureEntered(); System.out.println(compiler.resolveIdent(syms.unnamedModule, getDeprecatedClass().getCanonicalName())); }
Example 16
Source File: JavacTaskImpl.java From lua-for-android with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void prepareCompiler(boolean forParse) { if (used.getAndSet(true)) { if (compiler == null) throw new PropagatedException(new IllegalStateException()); } else { args.validate(); //initialize compiler's default locale context.put(Locale.class, locale); // hack JavacMessages messages = context.get(JavacMessages.messagesKey); if (messages != null && !messages.getCurrentLocale().equals(locale)) messages.setCurrentLocale(locale); initPlugins(args.getPluginOpts()); // init JavaCompiler and queues compiler = JavaCompiler.instance(context); compiler.keepComments = true; compiler.genEndPos = true; notYetEntered = new HashMap<>(); if (forParse) { compiler.initProcessAnnotations(processors, args.getFileObjects(), args.getClassNames()); for (JavaFileObject file: args.getFileObjects()) notYetEntered.put(file, null); genList = new ListBuffer<>(); } } }
Example 17
Source File: ElementsTable.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * Creates the table to manage included and excluded elements. * * @param context the context to locate commonly used objects * @param location the location used to locate source files */ ElementsTable(Context context, Map<ToolOption, Object> opts) { this.toolEnv = ToolEnvironment.instance(context); this.syms = Symtab.instance(context); this.names = Names.instance(context); this.fm = toolEnv.fileManager; this.modules = Modules.instance(context); this.opts = opts; this.messager = Messager.instance0(context); this.compiler = JavaCompiler.instance(context); Source source = Source.instance(context); List<Location> locs = new ArrayList<>(); if (modules.multiModuleMode) { locs.add(StandardLocation.MODULE_SOURCE_PATH); } else { if (toolEnv.fileManager.hasLocation(StandardLocation.SOURCE_PATH)) locs.add(StandardLocation.SOURCE_PATH); else locs.add(StandardLocation.CLASS_PATH); } if (source.allowModules() && toolEnv.fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH)) locs.add(StandardLocation.PATCH_MODULE_PATH); this.locations = Collections.unmodifiableList(locs); getEntry("").excluded = false; accessFilter = new ModifierFilter(opts); xclasses = (boolean)opts.getOrDefault(ToolOption.XCLASSES, false); expandRequires = (AccessKind)opts.get(ToolOption.EXPAND_REQUIRES); }
Example 18
Source File: TestSymtabItems.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
void run() throws Exception { Context c = new Context(); JavacFileManager.preRegister(c); Symtab syms = Symtab.instance(c); JavacTypes types = JavacTypes.instance(c); JavaCompiler.instance(c); // will init ClassReader.sourceCompleter // print("noSymbol", syms.noSymbol); // print("errSymbol", syms.errSymbol); // print("unknownSymbol", syms.unknownSymbol); // print("botType", syms.botType); // print("errType", syms.errType); // print("unknownType", syms.unknownType); for (Field f: Symtab.class.getDeclaredFields()) { // System.err.println(f.getType() + " " + f.getName()); // Temporarily ignore methodHandle and transientMethodHandle // during API evolution if (f.getName().toLowerCase().contains("methodhandle")) continue; Class<?> ft = f.getType(); if (TypeMirror.class.isAssignableFrom(ft)) print(f.getName(), (TypeMirror) f.get(syms), types); else if(Element.class.isAssignableFrom(ft)) print(f.getName(), (Element) f.get(syms)); } if (errors > 0) throw new Exception(errors + " errors occurred"); }
Example 19
Source File: PackageProcessor.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
@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 20
Source File: StaticCompiler.java From manifold with Apache License 2.0 | 4 votes |
void compileRemainingTypes_ByTypeNameRegexes() { if( _enterGuard ) { return; } _enterGuard = true; Map<String, String> others = JavacPlugin.instance().getOtherSourceMappings(); Map<ITypeManifold, Set<String>> classToRegex = new HashMap<>(); for( Map.Entry<String, String> entry: others.entrySet() ) { mapTypeManifoldToTypeNameRegexes( classToRegex, entry.getKey(), entry.getValue() ); } IModule module = JavacPlugin.instance().getHost().getSingleModule(); Context ctx = JavacPlugin.instance().getContext(); for( Map.Entry<ITypeManifold, Set<String>> mapping: classToRegex.entrySet() ) { ITypeManifold tm = mapping.getKey(); Collection<String> types = computeNamesToPrecompile( tm.getAllTypeNames(), mapping.getValue() ); if( types.isEmpty() ) { //todo: add compile error continue; } // signal the type manifold for post Java compilation tm.enterPostJavaCompilation(); // Cause the types to compile by entering ClassSymbols into javac's "todos" if( !enterClassSymbols( module, ctx, types ) ) { return; } } JavaCompiler javaCompiler = JavaCompiler.instance( ctx ); if( !javaCompiler.todo.isEmpty() ) { // compile resource types we just loaded compileTodo( javaCompiler ); } _enterGuard = false; }