Search in sources :

Example 6 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project error-prone by google.

the class CodeTransformerTestHelper method transform.

public JavaFileObject transform(JavaFileObject original) {
    JavaCompiler compiler = JavacTool.create();
    DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, Locale.ENGLISH, UTF_8);
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, ImmutableList.<String>of(), null, ImmutableList.of(original));
    try {
        SourceFile sourceFile = SourceFile.create(original);
        Iterable<? extends CompilationUnitTree> trees = task.parse();
        task.analyze();
        JCCompilationUnit tree = Iterables.getOnlyElement(Iterables.filter(trees, JCCompilationUnit.class));
        DescriptionBasedDiff diff = DescriptionBasedDiff.create(tree);
        transformer().apply(new TreePath(tree), task.getContext(), diff);
        diff.applyDifferences(sourceFile);
        return JavaFileObjects.forSourceString(Iterables.getOnlyElement(Iterables.filter(tree.getTypeDecls(), JCClassDecl.class)).sym.getQualifiedName().toString(), sourceFile.getSourceText());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) DescriptionBasedDiff(com.google.errorprone.apply.DescriptionBasedDiff) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) JCClassDecl(com.sun.tools.javac.tree.JCTree.JCClassDecl) JavaCompiler(javax.tools.JavaCompiler) IOException(java.io.IOException) JavaFileObject(javax.tools.JavaFileObject) TreePath(com.sun.source.util.TreePath) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) SourceFile(com.google.errorprone.apply.SourceFile)

Example 7 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project error-prone by google.

the class ErrorProneJavacPluginTest method hello.

@Test
public void hello() throws IOException {
    FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
    Path source = fileSystem.getPath("Test.java");
    Files.write(source, ImmutableList.of("import java.util.HashSet;", "import java.util.Set;", "class Test {", "  public static void main(String[] args) {", "    Set<Short> s = new HashSet<>();", "    for (short i = 0; i < 100; i++) {", "      s.add(i);", "      s.remove(i - 1);", "    }", "    System.out.println(s.size());", "  }", "}"), UTF_8);
    JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
    JavacTask task = JavacTool.create().getTask(null, fileManager, diagnosticCollector, ImmutableList.of("-Xplugin:ErrorProne"), ImmutableList.of(), fileManager.getJavaFileObjects(source));
    assertThat(task.call()).isFalse();
    Diagnostic<? extends JavaFileObject> diagnostic = diagnosticCollector.getDiagnostics().stream().filter(d -> d.getKind() == Diagnostic.Kind.ERROR).collect(onlyElement());
    assertThat(diagnostic.getMessage(ENGLISH)).contains("[CollectionIncompatibleType]");
}
Also used : Path(java.nio.file.Path) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) Context(com.sun.tools.javac.util.Context) Configuration(com.google.common.jimfs.Configuration) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) JavacTask(com.sun.source.util.JavacTask) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) RunWith(org.junit.runner.RunWith) IOException(java.io.IOException) Test(org.junit.Test) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) FileSystem(java.nio.file.FileSystem) MoreCollectors.onlyElement(com.google.common.collect.MoreCollectors.onlyElement) JavaFileObject(javax.tools.JavaFileObject) ImmutableList(com.google.common.collect.ImmutableList) JavacTool(com.sun.tools.javac.api.JavacTool) Jimfs(com.google.common.jimfs.Jimfs) Diagnostic(javax.tools.Diagnostic) Context(com.sun.tools.javac.util.Context) ENGLISH(java.util.Locale.ENGLISH) Path(java.nio.file.Path) DiagnosticCollector(javax.tools.DiagnosticCollector) JavaFileObject(javax.tools.JavaFileObject) FileSystem(java.nio.file.FileSystem) DiagnosticCollector(javax.tools.DiagnosticCollector) JavacTask(com.sun.source.util.JavacTask) Test(org.junit.Test)

Example 8 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project j2objc by google.

the class JavacParser method createEnvironment.

// Creates a javac environment from a collection of files and/or file objects.
private JavacEnvironment createEnvironment(List<File> files, List<JavaFileObject> fileObjects, boolean processAnnotations) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    JavacFileManager fileManager = getFileManager(compiler, diagnostics);
    List<String> javacOptions = getJavacOptions(processAnnotations);
    if (fileObjects == null) {
        fileObjects = new ArrayList<>();
    }
    for (JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(files)) {
        fileObjects.add(jfo);
    }
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fileManager, diagnostics, javacOptions, null, fileObjects);
    return new JavacEnvironment(task, fileManager, diagnostics);
}
Also used : JavacFileManager(com.sun.tools.javac.file.JavacFileManager) JavaFileObject(javax.tools.JavaFileObject) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) JavaCompiler(javax.tools.JavaCompiler) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 9 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project symmetric-ds by JumpMind.

the class SimpleClassCompiler method getCompiledClass.

public Object getCompiledClass(String javaCode) throws Exception {
    Integer id = javaCode.hashCode();
    Object javaObject = objectMap.get(id);
    if (javaObject == null) {
        String className = getNextClassName();
        String origClassName = null;
        Pattern pattern = Pattern.compile(REGEX_CLASS);
        Matcher matcher = pattern.matcher(javaCode);
        if (matcher.find()) {
            origClassName = matcher.group(1);
        }
        javaCode = javaCode.replaceAll(REGEX_CLASS, "public class " + className);
        log.info("Compiling class '" + origClassName + "'");
        if (log.isDebugEnabled()) {
            log.debug("Compiling code: \n" + javaCode);
        }
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            throw new SimpleClassCompilerException("Missing Java compiler: the JDK is required for compiling classes.");
        }
        JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
        DiagnosticCollector<JavaFileObject> diag = new DiagnosticCollector<JavaFileObject>();
        List<JavaFileObject> javaFiles = new ArrayList<JavaFileObject>();
        javaFiles.add(new JavaObjectFromString(className, javaCode));
        Boolean success = compiler.getTask(null, fileManager, diag, null, null, javaFiles).call();
        if (success) {
            log.debug("Compilation has succeeded");
            Class<?> clazz = fileManager.getClassLoader(null).loadClass(className);
            if (clazz != null) {
                javaObject = clazz.newInstance();
                objectMap.put(id, javaObject);
            } else {
                throw new SimpleClassCompilerException("The '" + className + "' class could not be located");
            }
        } else {
            log.error("Compilation of '" + origClassName + "' failed");
            for (Diagnostic diagnostic : diag.getDiagnostics()) {
                log.error(origClassName + " at line " + diagnostic.getLineNumber() + ", column " + diagnostic.getColumnNumber() + ": " + diagnostic.getMessage(null));
            }
            throw new SimpleClassCompilerException(diag.getDiagnostics());
        }
    }
    return javaObject;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) FileObject(javax.tools.FileObject) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 10 with DiagnosticCollector

use of javax.tools.DiagnosticCollector in project incubator-systemml by apache.

the class CodegenUtils method compileClassJavac.

////////////////////////////
//JAVAC-specific methods (used for hadoop environments)
private static Class<?> compileClassJavac(String name, String src) throws DMLRuntimeException {
    try {
        //create working dir on demand
        if (_workingDir == null)
            createWorkingDir();
        //write input file (for debugging / classpath handling)
        File ftmp = new File(_workingDir + "/" + name.replace(".", "/") + ".java");
        if (!ftmp.getParentFile().exists())
            ftmp.getParentFile().mkdirs();
        LocalFileUtils.writeTextFile(ftmp, src);
        //get system java compiler
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null)
            throw new RuntimeException("Unable to obtain system java compiler.");
        //prepare file manager
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        //prepare input source code
        Iterable<? extends JavaFileObject> sources = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(ftmp));
        //prepare class path 
        URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
        String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath();
        List<String> options = Arrays.asList("-classpath", classpath);
        //compile source code
        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources);
        Boolean success = task.call();
        //output diagnostics and error handling
        for (Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics()) if (tmp.getKind() == Kind.ERROR)
            System.err.println("ERROR: " + tmp.toString());
        if (success == null || !success)
            throw new RuntimeException("Failed to compile class " + name);
        //dynamically load compiled class
        URLClassLoader classLoader = null;
        try {
            classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir }, CodegenUtils.class.getClassLoader());
            return classLoader.loadClass(name);
        } finally {
            IOUtilFunctions.closeSilently(classLoader);
        }
    } catch (Exception ex) {
        throw new DMLRuntimeException(ex);
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) URL(java.net.URL) CompilationTask(javax.tools.JavaCompiler.CompilationTask) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) IOException(java.io.IOException) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) JavaFileObject(javax.tools.JavaFileObject) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) URLClassLoader(java.net.URLClassLoader) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File)

Aggregations

DiagnosticCollector (javax.tools.DiagnosticCollector)28 JavaFileObject (javax.tools.JavaFileObject)28 JavaCompiler (javax.tools.JavaCompiler)24 StandardJavaFileManager (javax.tools.StandardJavaFileManager)16 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)9 Diagnostic (javax.tools.Diagnostic)9 CompilationTask (javax.tools.JavaCompiler.CompilationTask)9 File (java.io.File)8 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)8 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)4 Test (org.junit.Test)4 FileOutputStream (java.io.FileOutputStream)3 PrintWriter (java.io.PrintWriter)3 StringWriter (java.io.StringWriter)3 ImmutableList (com.google.common.collect.ImmutableList)2 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 DescriptionBasedDiff (com.google.errorprone.apply.DescriptionBasedDiff)2 SourceFile (com.google.errorprone.apply.SourceFile)2 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)2