Java Code Examples for javax.tools.Diagnostic#getSource()

The following examples show how to use javax.tools.Diagnostic#getSource() . 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: ClassBodyWrapper.java    From Quicksql with MIT License 6 votes vote down vote up
String buildCompilationReport(DiagnosticCollector<JavaFileObject> collector,
    List<String> options) {
    int count = 0;
    StringBuilder resultBuilder = new StringBuilder();

    for (Object o : collector.getDiagnostics()) {
        Diagnostic<?> diagnostic = (Diagnostic) o;
        ++ count;
        JavaSourceFromString javaSource = (JavaSourceFromString) diagnostic.getSource();
        resultBuilder.append(javaSource.getCharContent(false)).append("\n");
        resultBuilder.append("Compiler options: ").append(options).append("\n\n");
        resultBuilder.append(diagnostic.getKind()).append("|").append(diagnostic.getCode())
            .append("\n");
        resultBuilder.append("LINE:COLUMN ").append(diagnostic.getLineNumber()).append(":")
            .append(diagnostic.getColumnNumber()).append("\n")
            .append(diagnostic.getMessage(null)).append("\n\n");
    }

    String diagnosticString = resultBuilder.toString();
    String compilationErrorsOverview = count + " class(es) failed to compile";
    return "Compilation error\n" + compilationErrorsOverview + "\n" + diagnosticString;
}
 
Example 2
Source File: SpanUtil.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
public static Spannable createSrcSpan(Resources resources, @NonNull Diagnostic diagnostic) {
    if (diagnostic.getSource() == null) {
        return new SpannableString("Unknown");
    }
    if (!(diagnostic.getSource() instanceof JavaFileObject)) {
        return new SpannableString(diagnostic.getSource().toString());
    }
    try {
        JavaFileObject source = (JavaFileObject) diagnostic.getSource();
        File file = new File(source.getName());
        String name = file.getName();
        String line = diagnostic.getLineNumber() + ":" + diagnostic.getColumnNumber();
        SpannableString span = new SpannableString(name + ":" + line);
        span.setSpan(new ForegroundColorSpan(resources.getColor(R.color.dark_color_diagnostic_file)),
                0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return span;
    } catch (Exception e) {

    }
    return new SpannableString(diagnostic.getSource().toString());
}
 
Example 3
Source File: DiagnosticPresenter.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void click(Diagnostic diagnostic) {
    Log.d(TAG, "click() called with: diagnostic = [" + diagnostic + "]");
    mMainActivity.closeDrawer(GravityCompat.START);

    Object source = diagnostic.getSource();
    if (source instanceof JavaFileObject && diagnostic.getKind() == Diagnostic.Kind.ERROR) {
        String path = ((JavaFileObject) source).getName();
        int i = mPagePresenter.gotoPage(path);
        if (i == -1) {
            mPagePresenter.addPage(path, true);
        }
        EditPageContract.SourceView editor = mPagePresenter.getCurrentPage();
        if (editor == null) {
            Log.d(TAG, "click: editor null");
            return;
        }
        int startPosition = (int) diagnostic.getStartPosition();
        int endPosition = (int) diagnostic.getEndPosition();
        editor.highlightError(startPosition, endPosition);
        editor.setCursorPosition(endPosition);
    } else {
        // TODO: 19/07/2017 implement other
    }
}
 
Example 4
Source File: CompilerHelper.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static String summarize(Diagnostic<? extends JavaFileObject> diagnostic) {
    StringBuilder sb = new StringBuilder();
    sb.append(diagnostic.getKind()).append(": ");
    JavaFileObject sourceObject = diagnostic.getSource();
    if (sourceObject != null) {
        sb.append("file ").append(sourceObject.toString()).append(" ");
    }
    String message = diagnostic.getMessage(Locale.ROOT);
    if (message != null && !message.isEmpty()) {
        sb.append(message).append(" ");
    }
    long line = diagnostic.getLineNumber();
    long column = diagnostic.getColumnNumber();
    if (line != -1 || column != -1) {
        sb.append("at line ").append(line).append(" column ").append(column);
    }
    return sb.toString().trim();
}
 
Example 5
Source File: JavaCodeScriptEngine.java    From chaosblade-exec-jvm with Apache License 2.0 6 votes vote down vote up
private static void generateDiagnosticReport(
    DiagnosticCollector<JavaFileObject> collector, StringBuilder reporter) throws IOException {
    List<Diagnostic<? extends JavaFileObject>> diagnostics = collector.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
        JavaFileObject source = diagnostic.getSource();
        if (source != null) {
            reporter.append("Source: ").append(source.getName()).append('\n');
            reporter.append("Line ").append(diagnostic.getLineNumber()).append(": ")
                .append(diagnostic.getMessage(Locale.ENGLISH)).append('\n');
            CharSequence content = source.getCharContent(true);
            BufferedReader reader = new BufferedReader(new StringReader(content.toString()));
            int i = 1;
            String line;
            while ((line = reader.readLine()) != null) {
                reporter.append(i).append('\t').append(line).append('\n');
                ++i;
            }
        } else {
            reporter.append("Source: (null)\n");
            reporter.append("Line ").append(diagnostic.getLineNumber()).append(": ")
                .append(diagnostic.getMessage(Locale.ENGLISH)).append('\n');
        }
        reporter.append('\n');
    }
}
 
Example 6
Source File: CompilationInfoImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> message) {
    if (partialReparseErrors != null) {
        if (this.jfo != null && this.jfo == message.getSource()) {
            partialReparseErrors.add(message);
            if (message.getKind() == Kind.ERROR) {
                partialReparseRealErrors = true;
            }
        }
    } else {
        Diagnostics errors = getErrors(message.getSource());
        errors.add((int) message.getPosition(), message);
    }
}
 
Example 7
Source File: T6458823.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 8
Source File: T6458823.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        List<String> options = new ArrayList<String>();
        options.add("-processor");
        options.add("MyProcessor");
        options.add("-proc:only");
        List<File> files = new ArrayList<File>();
        files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
        final CompilationTask task = compiler.getTask(null, fm, diagColl,
            options, null, fm.getJavaFileObjectsFromFiles(files));
        task.call();
        int diagCount = 0;
        for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
            if (diag.getKind() != Diagnostic.Kind.WARNING) {
                throw new AssertionError("Only warnings expected");
            }
            System.out.println(diag);
            if (diag.getPosition() == Diagnostic.NOPOS) {
                throw new AssertionError("No position info in message");
            }
            if (diag.getSource() == null) {
                throw new AssertionError("No source info in message");
            }
            diagCount++;
        }
        if (diagCount != 2) {
            throw new AssertionError("unexpected number of warnings: " +
                diagCount + ", expected: 2");
        }
    }
}
 
Example 9
Source File: TaskFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Diag diag(Diagnostic<? extends JavaFileObject> d) {
    SourceMemoryJavaFileObject smjfo = (SourceMemoryJavaFileObject) d.getSource();
    if (smjfo == null) {
        // Handle failure that doesn't preserve mapping
        return new StringSourceHandler().diag(d);
    }
    OuterWrap w = (OuterWrap) smjfo.getOrigin();
    return w.wrapDiag(d);
}
 
Example 10
Source File: PartialReparseTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public DiagnosticDescription(Diagnostic diag) {
    this.code = diag.getCode();
    this.message = diag.getMessage(Locale.ROOT);
    this.column = diag.getColumnNumber();
    this.endPos = diag.getEndPosition();
    this.kind = diag.getKind();
    this.line = diag.getLineNumber();
    this.pos = diag.getPosition();
    this.source = diag.getSource();
    this.startPos = diag.getStartPosition();
}
 
Example 11
Source File: T6458823.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 12
Source File: T6458823.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 13
Source File: Diagnostics.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
/**
 * Appends a human-readable form of {@code diagnostic} to {@code appendable}.
 */
public static void appendTo(
    StringBuilder appendable,
    Diagnostic<? extends JavaFileObject> diagnostic,
    int indentLevel) {
  String indent = "\n" + Strings.repeat(" ", indentLevel);
  appendable.append(diagnostic.getMessage(Locale.getDefault()).replace("\n", indent));
  JavaFileObject source = diagnostic.getSource();
  long line = diagnostic.getLineNumber();
  if (source != null && line != Diagnostic.NOPOS) {
    File sourceFile = new File(source.getName());
    appendable.append(" (").append(sourceFile.getName()).append(":").append(line).append(")");
  }
}
 
Example 14
Source File: T6458823.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 15
Source File: CompilerJavac.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
private void compile(JavaCompiler compiler, StandardJavaFileManager javaFileManager, Map<File, Resource<File>> sources) throws IOException {
  final DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
  final Iterable<? extends JavaFileObject> javaSources = javaFileManager.getJavaFileObjectsFromFiles(sources.keySet());

  final Map<File, Output<File>> outputs = new HashMap<File, Output<File>>();

  final Iterable<String> options = getCompilerOptions();
  final RecordingJavaFileManager recordingFileManager = new RecordingJavaFileManager(javaFileManager, getSourceEncoding()) {
    @Override
    protected void record(File inputFile, File outputFile) {
      outputs.put(outputFile, context.processOutput(outputFile));
    }
  };

  Writer stdout = new PrintWriter(System.out, true);
  final JavaCompiler.CompilationTask task = compiler.getTask(stdout, // Writer out
      recordingFileManager, // file manager
      diagnosticCollector, // diagnostic listener
      options, //
      null, // Iterable<String> classes to process by annotation processor(s)
      javaSources);

  final boolean success = task.call();

  for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
    final JavaFileObject source = diagnostic.getSource();
    final MessageSeverity severity = toSeverity(diagnostic.getKind(), success);
    final String message = diagnostic.getMessage(null);

    if (isShowWarnings() || severity != MessageSeverity.WARNING) {
      if (source != null) {
        File file = FileObjects.toFile(source);
        if (file != null) {
          Resource<File> resource = sources.get(file);
          if (resource == null) {
            resource = outputs.get(file);
          }
          if (resource != null) {
            resource.addMessage((int) diagnostic.getLineNumber(), (int) diagnostic.getColumnNumber(), message, severity, null);
          } else {
            log.warn("Unexpected java {} resource {}", source.getKind(), source.toUri().toASCIIString());
          }
        } else {
          log.warn("Unsupported compiler message on {} resource {}: {}", source.getKind(), source.toUri(), message);
        }
      } else {
        context.addPomMessage(message, severity, null);
      }
    }
  }
}
 
Example 16
Source File: CompilerJavacForked.java    From takari-lifecycle with Eclipse Public License 1.0 4 votes vote down vote up
private static void compile(final CompilerConfiguration config, final CompilerOutput output) {

    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
      output.addMessage(".", 0, 0, "No compiler is provided in this environment. " + "Perhaps you are running on a JRE rather than a JDK?", Kind.ERROR);
      return;
    }

    final Charset sourceEncoding = config.getSourceEncoding();
    final DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
    final StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(diagnosticCollector, null, sourceEncoding);
    final Iterable<? extends JavaFileObject> fileObjects = standardFileManager.getJavaFileObjectsFromFiles(config.getSources());
    final Iterable<String> options = config.getCompilerOptions();
    final RecordingJavaFileManager recordingFileManager = new RecordingJavaFileManager(standardFileManager, sourceEncoding) {
      @Override
      protected void record(File inputFile, File outputFile) {
        output.processOutput(inputFile, outputFile);
      }
    };

    Writer stdout = new PrintWriter(System.out, true);
    final JavaCompiler.CompilationTask task = compiler.getTask(stdout, // Writer out
        recordingFileManager, // file manager
        diagnosticCollector, // diagnostic listener
        options, //
        null, // Iterable<String> classes to process by annotation processor(s)
        fileObjects);

    boolean success = task.call();

    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
      JavaFileObject source = diagnostic.getSource();

      // when doing annotation processing, javac 6 reports errors when handwritten sources
      // depend on generated sources even when overall compilation is reported as success
      // to prevent false build failures, never issue ERROR messages after successful compilation
      Kind kind = diagnostic.getKind();
      if (success && kind == Kind.ERROR) {
        kind = Kind.WARNING;
      }

      if (source != null) {
        File file = FileObjects.toFile(source);
        if (file != null) {
          output.addMessage(file.getAbsolutePath(), (int) diagnostic.getLineNumber(), (int) diagnostic.getColumnNumber(), diagnostic.getMessage(null), kind);
        } else {
          output.addLogMessage(String.format("Unsupported compiler message on %s resource %s: %s", source.getKind(), source.toUri(), diagnostic.getMessage(null)));
        }
      } else {
        output.addMessage(".", 0, 0, diagnostic.getMessage(null), kind);
      }
    }
  }
 
Example 17
Source File: DiagnosticPrettyPrinter.java    From buck with Apache License 2.0 4 votes vote down vote up
public static String format(Diagnostic<? extends JavaFileObject> diagnostic) {
  /*
  In BasicDiagnosticFormatter.class, the default format used is: "%f:%l:%_%p%L%m"
  This expands to:

  "filename":"line":" ""kind""lint category""format message"

  Format message is implemented in the BasicDiagnosticFormatter. This splits the message into
  lines and picks the first one as the summary (seems reasonable to do). If details are
  requested, then the remaining lines are added. Details are always requested.
  */

  StringBuilder builder = new StringBuilder();

  JavaFileObject source = diagnostic.getSource();
  if (source != null && !source.getName().isEmpty()) {
    builder.append(source.getName()).append(":").append(diagnostic.getLineNumber());
  }

  builder
      .append(": ")
      .append(diagnostic.getKind().toString().toLowerCase(Locale.US))
      .append(": ");

  String formattedMessage = diagnostic.getMessage(Locale.getDefault());
  String[] parts = formattedMessage.split(System.lineSeparator());
  if (parts.length == 0) {
    parts = new String[] {""};
  }

  // Use the first line as a summary. With the normal Oracle JSR199 javac, the remaining lines are
  // more detailed diagnostics, which we don't normally display. With ECJ, there's no additional
  // information anyway, so it doesn't matter that we discard the remaining output.
  builder.append(parts[0]).append(System.lineSeparator());

  appendContext(builder, diagnostic, source);

  // If there was additional information in the message, append it now.
  for (int i = 1; i < parts.length; i++) {
    builder.append(System.lineSeparator()).append(parts[i]);
  }

  return builder.toString();
}
 
Example 18
Source File: CompileResult.java    From meghanada-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void store(StoreTransaction txn, Entity entity) {

  long now = Instant.now().getEpochSecond();
  entity.setProperty("createdAt", now);
  entity.setProperty("result", this.success);
  entity.setProperty("problems", this.diagnostics.size());

  for (Diagnostic<? extends JavaFileObject> diagnostic : this.diagnostics) {
    String kind = diagnostic.getKind().toString();
    long line = diagnostic.getLineNumber();
    long column = diagnostic.getColumnNumber();

    String message = diagnostic.getMessage(null);
    if (isNull(message)) {
      message = "";
    }
    JavaFileObject fileObject = diagnostic.getSource();
    String path = null;
    if (fileObject != null) {
      final URI uri = fileObject.toUri();
      final File file = new File(uri);
      try {
        path = file.getCanonicalPath();
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
    }

    String code = diagnostic.getCode();
    Entity subEntity = txn.newEntity(CompileResult.DIAGNOSTIC_ENTITY_TYPE);
    subEntity.setProperty("kind", kind);
    subEntity.setProperty("line", line);
    subEntity.setProperty("column", column);
    subEntity.setProperty("message", message);
    if (nonNull(path)) {
      subEntity.setProperty("path", path);
    }
    if (nonNull(code)) {
      subEntity.setProperty("code", code);
    }

    entity.addLink("diagnostic", entity);
  }
}
 
Example 19
Source File: TypeSimplifierTest.java    From RetroFacebook with Apache License 2.0 4 votes vote down vote up
private void doTestTypeSimplifier(
    AbstractTestProcessor testProcessor, File tmpDir, ImmutableMap<String, String> classToSource)
    throws IOException {
  JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
  DiagnosticCollector<JavaFileObject> diagnosticCollector =
      new DiagnosticCollector<JavaFileObject>();
  StandardJavaFileManager fileManager =
      javac.getStandardFileManager(diagnosticCollector, null, null);

  StringWriter compilerOut = new StringWriter();

  List<String> options = ImmutableList.of(
      "-sourcepath", tmpDir.getPath(),
      "-d", tmpDir.getPath(),
      "-Xlint");
  javac.getTask(compilerOut, fileManager, diagnosticCollector, options, null, null);
  // This doesn't compile anything but communicates the paths to the JavaFileManager.

  ImmutableList.Builder<JavaFileObject> javaFilesBuilder = ImmutableList.builder();
  for (String className : classToSource.keySet()) {
    JavaFileObject sourceFile = fileManager.getJavaFileForInput(
        StandardLocation.SOURCE_PATH, className, Kind.SOURCE);
    javaFilesBuilder.add(sourceFile);
  }

  // Compile the empty source file to trigger the annotation processor.
  // (Annotation processors are somewhat misnamed because they run even on classes with no
  // annotations.)
  JavaCompiler.CompilationTask javacTask = javac.getTask(
      compilerOut, fileManager, diagnosticCollector, options,
      classToSource.keySet(), javaFilesBuilder.build());
  javacTask.setProcessors(ImmutableList.of(testProcessor));
  javacTask.call();
  List<Diagnostic<? extends JavaFileObject>> diagnostics =
      new ArrayList<Diagnostic<? extends JavaFileObject>>(diagnosticCollector.getDiagnostics());

  // In the ErrorTestProcessor case, the code being compiled contains a deliberate reference to an
  // undefined type, so that we can capture an instance of ErrorType. (Synthesizing one ourselves
  // leads to ClassCastException inside javac.) So remove any errors for that from the output, and
  // only fail if there were other errors.
  for (Iterator<Diagnostic<? extends JavaFileObject>> it = diagnostics.iterator();
       it.hasNext(); ) {
    Diagnostic<? extends JavaFileObject> diagnostic = it.next();
    if (diagnostic.getSource() != null
        && diagnostic.getSource().getName().contains("ExtendsUndefinedType")) {
      it.remove();
    }
  }
  // In the ErrorTestProcessor case, compilerOut.toString() will include the error for
  // ExtendsUndefinedType, which can safely be ignored, as well as stack traces for any failing
  // assertion.
  assertEquals(compilerOut.toString() + diagnosticCollector.getDiagnostics(),
      ImmutableList.of(), diagnostics);
}
 
Example 20
Source File: VanillaJavaBuilder.java    From bazel with Apache License 2.0 4 votes vote down vote up
public VanillaJavaBuilderResult run(List<String> args) throws IOException {
  OptionsParser optionsParser;
  try {
    optionsParser = new OptionsParser(args);
  } catch (InvalidCommandLineException e) {
    return new VanillaJavaBuilderResult(false, e.getMessage());
  }
  DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
  StringWriter output = new StringWriter();
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Path tempDir = Paths.get(firstNonNull(optionsParser.getTempDir(), "_tmp"));
  Path nativeHeaderDir = tempDir.resolve("native_headers");
  Files.createDirectories(nativeHeaderDir);
  boolean ok;
  try (StandardJavaFileManager fileManager =
      javaCompiler.getStandardFileManager(diagnosticCollector, ENGLISH, UTF_8)) {
    setLocations(optionsParser, fileManager, nativeHeaderDir);
    ImmutableList<JavaFileObject> sources = getSources(optionsParser, fileManager);
    if (sources.isEmpty()) {
      ok = true;
    } else {
      CompilationTask task =
          javaCompiler.getTask(
              new PrintWriter(output, true),
              fileManager,
              diagnosticCollector,
              JavacOptions.removeBazelSpecificFlags(optionsParser.getJavacOpts()),
              ImmutableList.<String>of() /*classes*/,
              sources);
      setProcessors(optionsParser, fileManager, task);
      ok = task.call();
    }
  }
  if (ok) {
    writeOutput(optionsParser);
    writeNativeHeaderOutput(optionsParser, nativeHeaderDir);
  }
  writeGeneratedSourceOutput(optionsParser);
  // the jdeps output doesn't include any information about dependencies, but Bazel still expects
  // the file to be created
  if (optionsParser.getOutputDepsProtoFile() != null) {
    try (OutputStream os =
        Files.newOutputStream(Paths.get(optionsParser.getOutputDepsProtoFile()))) {
      Deps.Dependencies.newBuilder()
          .setRuleLabel(optionsParser.getTargetLabel())
          .setSuccess(ok)
          .build()
          .writeTo(os);
    }
  }
  // TODO(cushon): support manifest protos & genjar
  if (optionsParser.getManifestProtoPath() != null) {
    try (OutputStream os =
        Files.newOutputStream(Paths.get(optionsParser.getManifestProtoPath()))) {
      Manifest.getDefaultInstance().writeTo(os);
    }
  }

  for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
    String code = diagnostic.getCode();
    if (code.startsWith("compiler.note.deprecated")
        || code.startsWith("compiler.note.unchecked")
        || code.equals("compiler.warn.sun.proprietary")) {
      continue;
    }
    StringBuilder message = new StringBuilder();
    if (diagnostic.getSource() != null) {
      message.append(diagnostic.getSource().getName());
      if (diagnostic.getLineNumber() != -1) {
        message.append(':').append(diagnostic.getLineNumber());
      }
      message.append(": ");
    }
    message.append(diagnostic.getKind().toString().toLowerCase(ENGLISH));
    message.append(": ").append(diagnostic.getMessage(ENGLISH)).append(System.lineSeparator());
    output.write(message.toString());
  }
  return new VanillaJavaBuilderResult(ok, output.toString());
}