public static JavacTaskImpl createJavacTask ( @NonNull final ClasspathInfo cpInfo, @NullAllowed final DiagnosticListener<? super JavaFileObject> diagnosticListener, @NullAllowed final String sourceLevel, @NullAllowed final SourceLevelQuery.Profile sourceProfile, @NullAllowed FQN2Files fqn2Files, @NullAllowed final CancelService cancelService, @NullAllowed final APTUtils aptUtils, @NullAllowed final CompilerOptionsQuery.Result compilerOptions, @NonNull Iterable<? extends JavaFileObject> files) { return createJavacTask( cpInfo, diagnosticListener, sourceLevel, sourceProfile, EnumSet.of(ConfigFlags.BACKGROUND_COMPILATION, ConfigFlags.MULTI_SOURCE), fqn2Files, cancelService, aptUtils, compilerOptions, Collections.emptySet(), files); }
/** * Creates a new CompilationInfoImpl for given source file * @param parser used to parse the file * @param file to be parsed * @param root the owner of the parsed file * @param javacTask used javac or null if new one should be created * @param snapshot rendered content of the file * @param detached true if the CompilationInfoImpl is detached from parsing infrastructure. * @throws java.io.IOException */ CompilationInfoImpl (final JavacParser parser, final FileObject file, final FileObject root, final JavacTaskImpl javacTask, final DiagnosticListener<JavaFileObject> diagnosticListener, final Snapshot snapshot, final boolean detached) throws IOException { assert parser != null; this.parser = parser; this.cpInfo = parser.getClasspathInfo(); assert cpInfo != null; this.file = file; this.root = root; this.snapshot = snapshot; assert file == null || snapshot != null; this.jfo = file != null ? FileObjects.sourceFileObject(file, root, JavaFileFilterQuery.getFilter(file), snapshot.getText()) : null; this.javacTask = javacTask; this.diagnosticListener = diagnosticListener; this.isClassFile = false; this.isDetached = detached; }
public JavaFileObject getSourceFileForInput( Location location, String fqn, JavaFileObject.Kind kind, DiagnosticListener<JavaFileObject> errorHandler ) { try { JavaFileObject file = super.getJavaFileForInput( location, fqn, kind ); if( file != null ) { return file; } } catch( IOException ignore ) { } return findGeneratedFile( fqn.replace( '$', '.' ), ManifoldHost.getCurrentModule(), errorHandler ); }
public static int compileJava(Context context, JavaProjectFolder projectFile, @Nullable DiagnosticListener listener) { try { String[] args = new String[]{ "-verbose", "-cp", projectFile.getJavaClassPath(context), "-sourcepath", projectFile.getSourcePath(), //sourcepath "-d", projectFile.getDirBuildClasses().getPath(), //output dir projectFile.getMainClass().getPath(projectFile) //main class }; DLog.d(TAG, "compileJava args = " + Arrays.toString(args)); int compileStatus; compileStatus = Javac.compile(args, listener); return compileStatus; } catch (Throwable e) { e.printStackTrace(); } return Main.EXIT_ERROR; }
public JavapTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes) { this(out, fileManager, diagnosticListener); this.classes = new ArrayList<String>(); for (String classname: classes) { classname.getClass(); // null-check this.classes.add(classname); } try { if (options != null) handleOptions(options, false); } catch (BadArgs e) { throw new IllegalArgumentException(e.getMessage()); } }
private DiagnosticListener<JavaFileObject> getDiagnosticListenerForWriter(Writer w) { final PrintWriter pw = getPrintWriterForWriter(w); return new DiagnosticListener<JavaFileObject> () { public void report(Diagnostic<? extends JavaFileObject> diagnostic) { switch (diagnostic.getKind()) { case ERROR: pw.print(getMessage("err.prefix")); break; case WARNING: pw.print(getMessage("warn.prefix")); break; case NOTE: pw.print(getMessage("note.prefix")); break; } pw.print(" "); pw.println(diagnostic.getMessage(null)); } }; }
JavahTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes) { this(); this.log = getPrintWriterForWriter(out); this.fileManager = fileManager; this.diagnosticListener = diagnosticListener; try { handleOptions(options, false); } catch (BadArgs e) { throw new IllegalArgumentException(e.getMessage()); } this.classes = new ArrayList<String>(); if (classes != null) { for (String classname: classes) { classname.getClass(); // null-check this.classes.add(classname); } } }
/** Construct a log with given I/O redirections. */ protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) { super(JCDiagnostic.Factory.instance(context)); context.put(logKey, this); this.errWriter = errWriter; this.warnWriter = warnWriter; this.noticeWriter = noticeWriter; @SuppressWarnings("unchecked") // FIXME DiagnosticListener<? super JavaFileObject> dl = context.get(DiagnosticListener.class); this.diagListener = dl; diagnosticHandler = new DefaultDiagnosticHandler(); messages = JavacMessages.instance(context); messages.add(Main.javacBundleName); final Options options = Options.instance(context); initOptions(options); options.addListener(new Runnable() { public void run() { initOptions(options); } }); }
public JavapTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes) { this(out, fileManager, diagnosticListener); this.classes = new ArrayList<>(); for (String classname: classes) { Objects.requireNonNull(classname); this.classes.add(classname); } try { if (options != null) handleOptions(options, false); } catch (BadArgs e) { throw new IllegalArgumentException(e.getMessage()); } }
private DiagnosticListener<JavaFileObject> getDiagnosticListenerForWriter(Writer w) { final PrintWriter pw = getPrintWriterForWriter(w); return diagnostic -> { switch (diagnostic.getKind()) { case ERROR: pw.print(getMessage("err.prefix")); break; case WARNING: pw.print(getMessage("warn.prefix")); break; case NOTE: pw.print(getMessage("note.prefix")); break; } pw.print(" "); pw.println(diagnostic.getMessage(null)); }; }
void report( DiagnosticListener<JavaFileObject> errorHandler ) { if( errorHandler == null ) { return; } List<IIssue> issues = getIssues(); if( issues.isEmpty() ) { return; } JavaFileObject file = new SourceJavaFileObject( getFile().toURI() ); for( IIssue issue : issues ) { Diagnostic.Kind kind = issue.getKind() == IIssue.Kind.Error ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING; errorHandler.report( new JavacDiagnostic( file, kind, issue.getStartOffset(), issue.getLine(), issue.getColumn(), issue.getMessage() ) ); } }
JavahTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes) { this(); this.log = getPrintWriterForWriter(out); this.fileManager = fileManager; this.diagnosticListener = diagnosticListener; try { handleOptions(options, false); } catch (BadArgs e) { throw new IllegalArgumentException(e.getMessage()); } this.classes = new ArrayList<>(); if (classes != null) { for (String classname: classes) { Objects.requireNonNull(classname); this.classes.add(classname); } } }
/** * Creates a log. * @param context the context in which the log should be registered * @param writers a map of writers that can be accessed by the kind of writer required */ private Log(Context context, Map<WriterKind, PrintWriter> writers) { super(JCDiagnostic.Factory.instance(context)); context.put(logKey, this); this.writers = writers; @SuppressWarnings("unchecked") // FIXME DiagnosticListener<? super JavaFileObject> dl = context.get(DiagnosticListener.class); this.diagListener = dl; diagnosticHandler = new DefaultDiagnosticHandler(); messages = JavacMessages.instance(context); messages.add(Main.javacBundleName); final Options options = Options.instance(context); initOptions(options); options.addListener(() -> initOptions(options)); }
void clear() { drop(Arguments.argsKey); drop(DiagnosticListener.class); drop(Log.outKey); drop(Log.errKey); drop(JavaFileManager.class); drop(JavacTask.class); if (ht.get(Log.logKey) instanceof ReusableLog) { //log already inited - not first round ((ReusableLog)Log.instance(this)).clear(); Enter.instance(this).newRound(); ((ReusableJavaCompiler)ReusableJavaCompiler.instance(this)).clear(); Types.instance(this).newRound(); Check.instance(this).newRound(); Modules.instance(this).newRound(); Annotate.instance(this).newRound(); CompileStates.instance(this).clear(); MultiTaskListener.instance(this).clear(); //find if any of the roots have redefined java.* classes Symtab syms = Symtab.instance(this); pollutionScanner.scan(roots, syms); roots.clear(); } }
void clear() { recorded.clear(); sourceMap.clear(); nerrors = 0; nwarnings = 0; //Set a fake listener that will lazily lookup the context for the 'real' listener. Since //this field is never updated when a new task is created, we cannot simply reset the field //or keep old value. This is a hack to workaround the limitations in the current infrastructure. diagListener = new DiagnosticListener<JavaFileObject>() { DiagnosticListener<JavaFileObject> cachedListener; @Override @SuppressWarnings("unchecked") public void report(Diagnostic<? extends JavaFileObject> diagnostic) { if (cachedListener == null) { cachedListener = context.get(DiagnosticListener.class); } cachedListener.report(diagnostic); } }; }
@Override public JavaCompiler.CompilationTask getTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) { return compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits); }
public void compile(JavaCompiler javaCompiler, Writer out, File sourceDirectory, File outputDirectory, List<File> classpath, DiagnosticListener<? super JavaFileObject> diagnosticListener, String targetVersion ) { targetVersion = targetVersion == null ? "1.6" : targetVersion; StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null); if (outputDirectory != null) { try { fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputDirectory)); fileManager.setLocation(StandardLocation.CLASS_PATH, classpath); } catch (IOException e) { throw new RuntimeException("could not set output directory", e); } } Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(findAllSourceFiles(sourceDirectory)); ArrayList<String> options = new ArrayList<String>(); options.add("-source"); options.add(targetVersion); options.add("-target"); options.add(targetVersion); options.add("-encoding"); options.add("UTF8"); options.add("-Xlint:-options"); options.add("-Xlint:unchecked"); if (compilationUnits.iterator().hasNext()) { Boolean success = javaCompiler.getTask(out, fileManager, diagnosticListener, options, null, compilationUnits).call(); assertThat("Compilation was not successful, check stdout for errors", success, is(true)); } }
public static ClassLoader compile(JavaCompiler compiler, Writer out, File sourceDirectory, File outputDirectory, List<File> classpath, Map<String, Object> config, DiagnosticListener<? super JavaFileObject> listener) { List<File> fullClasspath = new ArrayList<File>(); fullClasspath.addAll(classpath); fullClasspath.addAll(CodeGenerationHelper.classpathToFileArray(System.getProperty("java.class.path"))); new Compiler().compile(compiler, out, sourceDirectory, outputDirectory, fullClasspath, listener, (String)config.get("targetVersion")); try { return URLClassLoader.newInstance(new URL[] { outputDirectory.toURI().toURL() }, Thread.currentThread().getContextClassLoader()); } catch (MalformedURLException e) { throw new RuntimeException(e); } }
private static CompilationInfoImpl createCurrentInfo (final JavacParser parser, final FileObject file, final FileObject root, final Snapshot snapshot, final JavacTaskImpl javac, final DiagnosticListener<JavaFileObject> diagnosticListener) throws IOException { CompilationInfoImpl info = new CompilationInfoImpl(parser, file, root, javac, diagnosticListener, snapshot, false); if (file != null) { Logger.getLogger("TIMER").log(Level.FINE, "CompilationInfo", //NOI18N new Object[] {file, info}); } return info; }
public void testGetTypeDeclaration() throws Exception { ClasspathInfo ci = ClasspathInfo.create( bootPath, classPath, null); JavacTaskImpl jTask = JavacParser.createJavacTask(ci, (DiagnosticListener) null, (String) null, null, null, null, null, null, Collections.emptyList()); jTask.enter(); List<String> notFound = new LinkedList<String>(); JarFile jf = new JarFile( rtJar ); for( Enumeration entries = jf.entries(); entries.hasMoreElements(); ) { JarEntry je = (JarEntry)entries.nextElement(); String jeName = je.getName(); if ( !je.isDirectory() && jeName.endsWith( ".class" ) ) { String typeName = jeName.substring( 0, jeName.length() - ".class".length() ); typeName = typeName.replace( "/", "." ); //.replace( "$", "." ); TypeElement te = ElementUtils.getTypeElementByBinaryName(jTask, typeName ); // assertNotNull( "Declaration for " + typeName + " should not be null.", td ); if ( te == null ) { if (!typeName.endsWith("package-info")) { notFound.add( typeName ); } } } } assertTrue( "Should be empty " + notFound, notFound.isEmpty() ); }
static Map<String, byte[]> compile(FileObject fo, JavaSource js, String newSource, DiagnosticListener<? super JavaFileObject> diagnostics) throws IOException { ClassPath classPath = ClassPath.getClassPath(fo, ClassPath.SOURCE); if (classPath == null) { return null; } FileObject root = classPath.findOwnerRoot(fo); if (root == null) { return null; } return JavaSourceUtil.generate(root, fo, newSource, diagnostics); }
@Override @NonNull public Map<String, byte[]> generate( @NonNull final JavaSourceUtilImpl spi, @NonNull final FileObject srcRoot, @NonNull final FileObject file, @NullAllowed final CharSequence content, @NullAllowed final DiagnosticListener<? super JavaFileObject> diagnostics) throws IOException { assert spi != null; return spi.generate(srcRoot, file, content, diagnostics); }
@Override protected String produce( String topLevelFqn, String existing, Model model, DiagnosticListener<JavaFileObject> errorHandler ) { List<IFile> files = findFilesForType( topLevelFqn ); SrcClass srcClass = new PropertiesCodeGen( model.getCache(), files.isEmpty() ? null : files.get( 0 ), topLevelFqn ).make(); StringBuilder sb = srcClass.render( new StringBuilder(), 0 ); return sb.toString(); }
/** * Construct a log with given I/O redirections. */ @Deprecated protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) { super(JCDiagnostic.Factory.instance(context)); context.put(logKey, this); this.errWriter = errWriter; this.warnWriter = warnWriter; this.noticeWriter = noticeWriter; Options options = Options.instance(context); this.dumpOnError = options.isSet(DOE); this.promptOnError = options.isSet(PROMPT); this.emitWarnings = options.isUnset(XLINT_CUSTOM, "none"); this.suppressNotes = options.isSet("suppressNotes"); this.MaxErrors = getIntOption(options, XMAXERRS, getDefaultMaxErrors()); this.MaxWarnings = getIntOption(options, XMAXWARNS, getDefaultMaxWarnings()); boolean rawDiagnostics = options.isSet("rawDiagnostics"); messages = JavacMessages.instance(context); this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) : new BasicDiagnosticFormatter(options, messages); @SuppressWarnings("unchecked") // FIXME DiagnosticListener<? super JavaFileObject> dl = context.get(DiagnosticListener.class); this.diagListener = dl; String ek = options.get("expectKeys"); if (ek != null) expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *"))); }
@Nullable public static File buildJarAchieve(Context context, JavaProjectFolder projectFile, DiagnosticListener listener) throws IOException { int status = compileJava(context, projectFile, listener); if (status != Main.EXIT_OK) { throw new RuntimeException("Compile time error... Exit code(" + status + ")"); } //now create normal jar file Jar.createJarArchive(projectFile); return projectFile.getOutJarArchive(); }
@Override protected Integer doInBackground(JavaProjectFolder... params) { if (params[0] == null) return null; this.projectFile = params[0]; DiagnosticListener listener = new DiagnosticListener() { @Override public void report(Diagnostic diagnostic) { mDiagnostics.add(diagnostic); } }; //clean task projectFile.clean(); projectFile.createBuildDir(); int status = CompileHelper.compileJava(context, projectFile, listener); if (status == Main.EXIT_OK) { try { CompileHelper.convertToDexFormat(context, projectFile); } catch (Throwable e) { this.error = e; Log.e(TAG, "doInBackground: ", e); publishProgress(e.getMessage().toCharArray(), 0, e.getMessage().length()); status = Main.EXIT_ERROR; } } return status; }
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); }
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; }
private void reportErrors( DiagnosticListener<JavaFileObject> errorHandler, ProgramNode programNode ) { if( programNode.errorCount() > 0 ) { JavaFileObject file = new SourceJavaFileObject( _file.toURI() ); for( ParseError error : programNode.getErrorList() ) { Token token = error.getToken(); errorHandler.report( new JavacDiagnostic( file, Diagnostic.Kind.ERROR, token.getOffset(), token.getLineNumber(), token.getCol(), error.getMessage() ) ); } } }
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; }
public JavapTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener) { this(); this.log = getPrintWriterForWriter(out); this.fileManager = fileManager; this.diagnosticListener = diagnosticListener; }
void report(DiagnosticListener errorHandler) { if (_issues.isEmpty() || errorHandler == null) { return; } JavaFileObject file = new SourceJavaFileObject(getFile().toURI()); for (IIssue issue : _issues.getIssues()) { Diagnostic.Kind kind = issue.getKind() == IIssue.Kind.Error ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING; errorHandler.report(new JavacDiagnostic(file, kind, issue.getStartOffset(), issue.getLine(), issue.getColumn(), issue.getMessage())); } }
public static JavapFileManager create(final DiagnosticListener<? super JavaFileObject> dl, PrintWriter log) { Context javac_context = new Context(); if (dl != null) javac_context.put(DiagnosticListener.class, dl); javac_context.put(com.sun.tools.javac.util.Log.outKey, log); return new JavapFileManager(javac_context, null); }
@Override protected String produce( String topLevelFqn, String existing, Model model, DiagnosticListener<JavaFileObject> errorHandler ) { SrcClass srcClass = new ImageCodeGen( model._url, topLevelFqn ).make(); StringBuilder sb = srcClass.render( new StringBuilder(), 0 ); return sb.toString(); }
public NativeHeaderTask getTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes) { return new JavahTask(out, fileManager, diagnosticListener, options, classes); }
@Override public Pair<JavaFileObject, String> findJavaSource( String fqn, DiagnosticListener<JavaFileObject> errorHandler ) { init(); if( _gfm == null ) { // short-circuit reentrancy during init() return null; } JavaFileObject fileObj = _gfm.getSourceFileForInput( StandardLocation.SOURCE_PATH, fqn, JavaFileObject.Kind.SOURCE, errorHandler ); if( fileObj == null ) { int iDot = fqn.lastIndexOf( '.' ); if( iDot > 0 ) { String enclosingFqn = fqn.substring( 0, iDot ); return findJavaSource( enclosingFqn, errorHandler ); } return null; } else { return new Pair<>( fileObj, fqn ); } }
private JavaFileObject findGeneratedFile( String fqn, IModule module, DiagnosticListener<JavaFileObject> errorHandler ) { FqnCacheNode<JavaFileObject> node = _generatedFiles.getNode( fqn ); if( node != null ) { return node.getUserData(); } JavaFileObject file = ManifoldHost.produceFile( fqn, module, errorHandler ); // note we cache even if file is null, fqn cache is also a miss cache _generatedFiles.add( fqn, file ); return file; }
private DiagnosticListener<JavaFileObject> getDiagnosticListenerForWriter(Writer w) { final PrintWriter pw = getPrintWriterForWriter(w); return new DiagnosticListener<JavaFileObject> () { public void report(Diagnostic<? extends JavaFileObject> diagnostic) { if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { pw.print(getMessage("err.prefix")); pw.print(" "); } pw.println(diagnostic.getMessage(null)); } }; }
@Override protected String produce( String topLevelFqn, String existing, Model model, DiagnosticListener<JavaFileObject> errorHandler ) { StringBuilder sb = new StringBuilder(); SrcClass srcClass = new JsonImplCodeGen( model.getType(), topLevelFqn ).make(); model.report( errorHandler ); srcClass.render( sb, 0 ); return sb.toString(); }
@Override public StandardJavaFileManager getStandardFileManager( DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) { Context context = new Context(); context.put(Locale.class, locale); if (diagnosticListener != null) context.put(DiagnosticListener.class, diagnosticListener); PrintWriter pw = (charset == null) ? new PrintWriter(System.err, true) : new PrintWriter(new OutputStreamWriter(System.err, charset), true); context.put(Log.outKey, pw); return new JavacFileManager(context, true, charset); }