Search in sources :

Example 11 with Diagnostic

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

the class ErrorProneCompilerIntegrationTest method ignoreGeneratedConstructors.

@Test
public void ignoreGeneratedConstructors() throws Exception {
    compilerBuilder.report(ScannerSupplier.fromBugCheckerClasses(ConstructorMatcher.class));
    compiler = compilerBuilder.build();
    Result exitCode = compiler.compile(Arrays.asList(compiler.fileManager().forSourceLines("Test.java", "public class Test {}")));
    Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = not(hasItem(diagnosticMessage(containsString("[ConstructorMatcher]"))));
    assertTrue("Warning should be found. " + diagnosticHelper.describe(), matcher.matches(diagnosticHelper.getDiagnostics()));
    assertThat(outputStream.toString(), exitCode, is(Result.OK));
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Diagnostic(javax.tools.Diagnostic) Result(com.sun.tools.javac.main.Main.Result) Test(org.junit.Test)

Example 12 with Diagnostic

use of javax.tools.Diagnostic 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 13 with Diagnostic

use of javax.tools.Diagnostic in project intellij-community by JetBrains.

the class ExternalJavacProcess method compile.

private static JavacRemoteProto.Message compile(final ChannelHandlerContext context, final UUID sessionId, List<String> options, Collection<File> files, Collection<File> classpath, Collection<File> platformCp, Collection<File> modulePath, Collection<File> sourcePath, Map<File, Set<File>> outs, final CanceledStatus canceledStatus) {
    //final long compileStart = System.currentTimeMillis();
    //System.err.println("Compile start; since global start: " + (compileStart - myGlobalStart));
    final DiagnosticOutputConsumer diagnostic = new DiagnosticOutputConsumer() {

        @Override
        public void javaFileLoaded(File file) {
            context.channel().writeAndFlush(JavacProtoUtil.toMessage(sessionId, JavacProtoUtil.createSourceFileLoadedResponse(file)));
        }

        @Override
        public void outputLineAvailable(String line) {
            context.channel().writeAndFlush(JavacProtoUtil.toMessage(sessionId, JavacProtoUtil.createStdOutputResponse(line)));
        }

        @Override
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            final JavacRemoteProto.Message.Response response = JavacProtoUtil.createBuildMessageResponse(diagnostic);
            context.channel().writeAndFlush(JavacProtoUtil.toMessage(sessionId, response));
        }

        @Override
        public void registerImports(String className, Collection<String> imports, Collection<String> staticImports) {
            final JavacRemoteProto.Message.Response response = JavacProtoUtil.createClassDataResponse(className, imports, staticImports);
            context.channel().writeAndFlush(JavacProtoUtil.toMessage(sessionId, response));
        }

        @Override
        public void customOutputData(String pluginId, String dataName, byte[] data) {
            final JavacRemoteProto.Message.Response response = JavacProtoUtil.createCustomDataResponse(pluginId, dataName, data);
            context.channel().writeAndFlush(JavacProtoUtil.toMessage(sessionId, response));
        }
    };
    final OutputFileConsumer outputSink = new OutputFileConsumer() {

        @Override
        public void save(@NotNull OutputFileObject fileObject) {
            context.channel().writeAndFlush(JavacProtoUtil.toMessage(sessionId, JavacProtoUtil.createOutputObjectResponse(fileObject)));
        }
    };
    try {
        JavaCompilingTool tool = getCompilingTool();
        final boolean rc = JavacMain.compile(options, files, classpath, platformCp, modulePath, sourcePath, outs, diagnostic, outputSink, canceledStatus, tool);
        return JavacProtoUtil.toMessage(sessionId, JavacProtoUtil.createBuildCompletedResponse(rc));
    } catch (Throwable e) {
        //noinspection UseOfSystemOutOrSystemErr
        e.printStackTrace(System.err);
        return JavacProtoUtil.toMessage(sessionId, JavacProtoUtil.createFailure(e.getMessage(), e));
    }
//finally {
//  final long compileEnd = System.currentTimeMillis();
//  System.err.println("Compiled in " + (compileEnd - compileStart) + " ms; since global start: " + (compileEnd - myGlobalStart));
//}
}
Also used : JavaCompilingTool(org.jetbrains.jps.builders.java.JavaCompilingTool) Diagnostic(javax.tools.Diagnostic) NotNull(org.jetbrains.annotations.NotNull) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File)

Example 14 with Diagnostic

use of javax.tools.Diagnostic in project compiler by boalang.

the class BaseTest method codegen.

protected StartContext codegen(final String input, final String error) throws IOException {
    final File outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);
    final File outputFile = new File(outputSrcDir, "Test.java");
    CodeGeneratingVisitor.combineAggregatorStrings.clear();
    CodeGeneratingVisitor.reduceAggregatorStrings.clear();
    final List<String> jobnames = new ArrayList<String>();
    final List<String> jobs = new ArrayList<String>();
    final List<Integer> seeds = new ArrayList<Integer>();
    final StartContext ctx = typecheck(input);
    // use the whole input string to seed the RNG
    seeds.add(input.hashCode());
    final Start p = ctx.ast;
    try {
        new InheritedAttributeTransformer().start(p);
        new LocalAggregationTransformer().start(p);
        new VisitorOptimizingTransformer().start(p);
        final CodeGeneratingVisitor cg = new CodeGeneratingVisitor("1");
        cg.start(p);
        jobs.add(cg.getCode());
        jobnames.add("1");
        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");
        st.add("name", "Test");
        st.add("numreducers", 1);
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", 64 * 1024 * 1024);
        st.add("seeds", seeds);
        final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
        try {
            o.write(st.render().getBytes());
        } finally {
            o.close();
        }
        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File[] { outputFile }));
        if (!compiler.getTask(null, fileManager, diagnostics, Arrays.asList(new String[] { "-cp", System.getProperty("java.class.path") }), null, compilationUnits).call())
            for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) throw new RuntimeException("Error on line " + diagnostic.getLineNumber() + ": " + diagnostic.getMessage(null));
        if (error != null)
            fail("expected to see exception: " + error);
    } catch (final Exception e) {
        if (error == null) {
            if (e.getMessage() == null) {
                e.printStackTrace();
                fail("unexpected exception");
            } else
                fail("found unexpected exception: " + e.getMessage());
        } else
            assertEquals(error, e.getMessage());
    }
    delete(outputSrcDir);
    return ctx;
}
Also used : Start(boa.compiler.ast.Start) ArrayList(java.util.ArrayList) Diagnostic(javax.tools.Diagnostic) JavaFileObject(javax.tools.JavaFileObject) VisitorOptimizingTransformer(boa.compiler.transforms.VisitorOptimizingTransformer) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) BufferedOutputStream(java.io.BufferedOutputStream) ST(org.stringtemplate.v4.ST) InheritedAttributeTransformer(boa.compiler.transforms.InheritedAttributeTransformer) JavaCompiler(javax.tools.JavaCompiler) LocalAggregationTransformer(boa.compiler.transforms.LocalAggregationTransformer) IOException(java.io.IOException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) IOException(java.io.IOException) RecognitionException(org.antlr.v4.runtime.RecognitionException) StartContext(boa.parser.BoaParser.StartContext) FileOutputStream(java.io.FileOutputStream) AbstractCodeGeneratingVisitor(boa.compiler.visitors.AbstractCodeGeneratingVisitor) CodeGeneratingVisitor(boa.compiler.visitors.CodeGeneratingVisitor) File(java.io.File)

Example 15 with Diagnostic

use of javax.tools.Diagnostic in project ceylon-compiler by ceylon.

the class JavahTask method getDiagnosticListenerForWriter.

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));
        }
    };
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Diagnostic(javax.tools.Diagnostic) DiagnosticListener(javax.tools.DiagnosticListener) PrintWriter(java.io.PrintWriter)

Aggregations

Diagnostic (javax.tools.Diagnostic)31 JavaFileObject (javax.tools.JavaFileObject)30 Test (org.junit.Test)13 JavaCompiler (javax.tools.JavaCompiler)11 Result (com.sun.tools.javac.main.Main.Result)10 DiagnosticCollector (javax.tools.DiagnosticCollector)9 File (java.io.File)7 IOException (java.io.IOException)7 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)7 PrintWriter (java.io.PrintWriter)6 Matchers.containsString (org.hamcrest.Matchers.containsString)6 ArrayList (java.util.ArrayList)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 DiagnosticListener (javax.tools.DiagnosticListener)4 ImmutableList (com.google.common.collect.ImmutableList)3 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)2 JavacTask (com.sun.source.util.JavacTask)2 OutputStreamWriter (java.io.OutputStreamWriter)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2