Search in sources :

Example 26 with Diagnostic

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

the class DiagnosticTestHelper method assertHasDiagnosticOnAllMatchingLines.

/**
   * Asserts that the diagnostics contain a diagnostic on each line of the source file that
   * matches our bug marker pattern.  Parses the bug marker pattern for the specific string to
   * look for in the diagnostic.
   * @param source File in which to find matching lines
   *
   * TODO(eaftan): Switch to use assertThat instead of assertTrue.
   */
public void assertHasDiagnosticOnAllMatchingLines(JavaFileObject source, LookForCheckNameInDiagnostic lookForCheckNameInDiagnostic) throws IOException {
    final List<Diagnostic<? extends JavaFileObject>> diagnostics = getDiagnostics();
    final LineNumberReader reader = new LineNumberReader(CharSource.wrap(source.getCharContent(false)).openStream());
    do {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        List<Predicate<? super String>> predicates = null;
        if (line.contains(BUG_MARKER_COMMENT_INLINE)) {
            // Diagnostic must contain all patterns from the bug marker comment.
            List<String> patterns = extractPatterns(line, reader, BUG_MARKER_COMMENT_INLINE);
            predicates = new ArrayList<>(patterns.size());
            for (String pattern : patterns) {
                predicates.add(new SimpleStringContains(pattern));
            }
        } else if (line.contains(BUG_MARKER_COMMENT_LOOKUP)) {
            int markerLineNumber = reader.getLineNumber();
            List<String> lookupKeys = extractPatterns(line, reader, BUG_MARKER_COMMENT_LOOKUP);
            predicates = new ArrayList<>(lookupKeys.size());
            for (String lookupKey : lookupKeys) {
                assertTrue("No expected error message with key [" + lookupKey + "] as expected from line [" + markerLineNumber + "] with diagnostic [" + line.trim() + "]", expectedErrorMsgs.containsKey(lookupKey));
                predicates.add(expectedErrorMsgs.get(lookupKey));
                usedLookupKeys.add(lookupKey);
            }
        }
        if (predicates != null) {
            int lineNumber = reader.getLineNumber();
            for (Predicate<? super String> predicate : predicates) {
                Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> patternMatcher = hasItem(diagnosticOnLine(source.toUri(), lineNumber, predicate));
                assertTrue("Did not see an error on line " + lineNumber + " matching " + predicate + ". All errors:\n" + diagnostics, patternMatcher.matches(diagnostics));
            }
            if (checkName != null && lookForCheckNameInDiagnostic == LookForCheckNameInDiagnostic.YES) {
                // Diagnostic must contain check name.
                Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> checkNameMatcher = hasItem(diagnosticOnLine(source.toUri(), lineNumber, new SimpleStringContains("[" + checkName + "]")));
                assertTrue("Did not see an error on line " + lineNumber + " containing [" + checkName + "]. All errors:\n" + diagnostics, checkNameMatcher.matches(diagnostics));
            }
        } else {
            int lineNumber = reader.getLineNumber();
            Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = hasItem(diagnosticOnLine(source.toUri(), lineNumber));
            if (matcher.matches(diagnostics)) {
                fail("Saw unexpected error on line " + lineNumber + ". All errors:\n" + diagnostics);
            }
        }
    } while (true);
    reader.close();
}
Also used : ArrayList(java.util.ArrayList) Diagnostic(javax.tools.Diagnostic) Matchers.containsString(org.hamcrest.Matchers.containsString) LineNumberReader(java.io.LineNumberReader) Predicate(com.google.common.base.Predicate) JavaFileObject(javax.tools.JavaFileObject) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List)

Example 27 with Diagnostic

use of javax.tools.Diagnostic in project neo4j by neo4j.

the class ByteCodeVerifier method compilationFailure.

private static CompilationFailureException compilationFailure(List<Failure> failures) {
    List<Diagnostic<?>> diagnostics = new ArrayList<>(failures.size());
    for (Failure failure : failures) {
        diagnostics.add(new BytecodeDiagnostic(failure.message));
    }
    CompilationFailureException exception = new CompilationFailureException(diagnostics);
    for (Failure failure : failures) {
        exception.addSuppressed(failure.cause);
    }
    return exception;
}
Also used : ArrayList(java.util.ArrayList) Diagnostic(javax.tools.Diagnostic) CompilationFailureException(org.neo4j.codegen.CompilationFailureException)

Example 28 with Diagnostic

use of javax.tools.Diagnostic in project geode by apache.

the class ClassBuilder method compileClass.

/**
   * Compile the provided class. The className may have a package separated by /. For example:
   * my/package/myclass
   * 
   * @param className Name of the class to compile.
   * @param classCode Plain text contents of the class
   * @return The byte contents of the compiled class.
   * @throws IOException
   */
public byte[] compileClass(final String className, final String classCode) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    OutputStreamJavaFileManager<JavaFileManager> fileManager = new OutputStreamJavaFileManager<JavaFileManager>(javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);
    List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
    fileObjects.add(new JavaSourceFromString(className, classCode));
    List<String> options = Arrays.asList("-classpath", this.classPath);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
        StringBuilder errorMsg = new StringBuilder();
        for (Diagnostic d : diagnostics.getDiagnostics()) {
            String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(), d.getMessage(null));
            errorMsg.append(err);
            System.err.print(err);
        }
        throw new IOException(errorMsg.toString());
    }
    return byteArrayOutputStream.toByteArray();
}
Also used : JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 29 with Diagnostic

use of javax.tools.Diagnostic in project Gargoyle by callakrsos.

the class JavaSourceFromString method main.

public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    //		out.println("package pak;");
    out.println("public class HelloWorld {");
    out.println("  public static void main(String args[]) {");
    out.println("    System.out.println(\"This is in another java file\");");
    out.println("  }");
    out.println("}");
    out.close();
    JavaFileObject file = new JavaSourceFromString("pak/HelloWorld", writer.toString());
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        System.out.println(diagnostic.getCode());
        System.out.println(diagnostic.getKind());
        System.out.println(diagnostic.getPosition());
        System.out.println(diagnostic.getStartPosition());
        System.out.println(diagnostic.getEndPosition());
        System.out.println(diagnostic.getSource());
        System.out.println(diagnostic.getMessage(null));
    }
    System.out.println("Success: " + success);
    if (success) {
        try {
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
            Class.forName("HelloWorld", true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });
        } catch (ClassNotFoundException e) {
            System.err.println("Class not found: " + e);
        } catch (NoSuchMethodException e) {
            System.err.println("No such method: " + e);
        } catch (IllegalAccessException e) {
            System.err.println("Illegal access: " + e);
        } catch (InvocationTargetException e) {
            System.err.println("Invocation target: " + e);
        }
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) CompilationTask(javax.tools.JavaCompiler.CompilationTask) InvocationTargetException(java.lang.reflect.InvocationTargetException) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) StringWriter(java.io.StringWriter) URLClassLoader(java.net.URLClassLoader) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 30 with Diagnostic

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

the class TestPos method main.

public static void main(String... args) throws IOException {
    final boolean[] sawError = { false };
    final StringBuilder log = new StringBuilder();
    class MyFileObject extends SimpleJavaFileObject {

        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }

        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0123456789012345678901234567890123456789012345678901234
            return "class Test { { Object[] o = new <T,e,s,t>Object[0]; } }";
        }
    }
    class Scanner extends TreeScanner<Void, Trees> {

        CompilationUnitTree toplevel = null;

        @Override
        public Void visitCompilationUnit(CompilationUnitTree node, Trees trees) {
            toplevel = node;
            return super.visitCompilationUnit(node, trees);
        }

        @Override
        public Void visitErroneous(ErroneousTree node, Trees trees) {
            sawError[0] = true;
            long startPos = trees.getSourcePositions().getStartPosition(toplevel, node);
            long endPos = trees.getSourcePositions().getEndPosition(toplevel, node);
            log.append(String.format("begin=%s, end=%s : %s%n", startPos, endPos, node.getErrorTrees()));
            if (startPos != 28)
                error("Start pos for %s is incorrect (%s)!", node, startPos);
            if (endPos != 50)
                error("End pos for %s is incorrect (%s)!", node, endPos);
            return null;
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits = Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticListener<JavaFileObject> dl = new DiagnosticListener<JavaFileObject>() {

        public void report(Diagnostic<? extends JavaFileObject> diag) {
            log.append(String.format("%s @ %s%n", diag.getCode(), diag.getPosition()));
            if (!diag.getCode().equals(errCode))
                error("unexpected error");
            if (diag.getPosition() != 33)
                error("Error pos for %s is incorrect (%s)!", diag.getCode(), diag.getPosition());
            sawError[0] = true;
        }
    };
    JavacTask task = (JavacTask) javac.getTask(null, null, dl, null, null, compilationUnits);
    Trees trees = Trees.instance(task);
    Iterable<? extends Tree> toplevels = task.parse();
    if (!sawError[0])
        error("No parse error detected");
    sawError[0] = false;
    new Scanner().scan(toplevels, trees);
    if (!sawError[0])
        error("No error tree detected");
    if (!log.toString().equals(expected))
        error("Unexpected log message: %n%s%n", log);
    System.out.print(log);
    System.out.flush();
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) Trees(com.sun.source.util.Trees) TreeScanner(com.sun.source.util.TreeScanner) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) DiagnosticListener(javax.tools.DiagnosticListener) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) TreeScanner(com.sun.source.util.TreeScanner) ErroneousTree(com.sun.source.tree.ErroneousTree) JavacTask(com.sun.source.util.JavacTask)

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