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

The following examples show how to use javax.tools.Diagnostic#getLineNumber() . 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: 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 2
Source File: DiagnosticsAssert.java    From spring-configuration-validation-processor with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the diagnostics passed contain exactly the single expected message on the expected line.
 *
 * @param expectedMessage the expected message
 * @param expectedLineNumber the expected line number
 * @param diagnostics the diagnostics to assert
 */
public static void assertContainsSingleMessage(SpringConfigurationMessage expectedMessage, long expectedLineNumber,
    List<Diagnostic<? extends JavaFileObject>> diagnostics) {

  if (diagnostics.size() != 1) {
    throw new AssertionFailedError("Number of diagnostic messages expected <1> but was <" + diagnostics.size() + ">");
  }

  Diagnostic<? extends JavaFileObject> diagnostic = diagnostics.get(0);
  if (!(expectedMessage.getKind() == diagnostic.getKind()
      && expectedLineNumber == diagnostic.getLineNumber()
      && expectedMessage.getMessage().equals(diagnostic.getMessage(Locale.getDefault())))) {
    throw new AssertionFailedError("Diagnostic message expected <" + expectedMessage.getKind() + ","
        + expectedMessage.getMessage() + ", on line " + expectedLineNumber + "> but was <" + diagnostic.getKind()
        + "," + diagnostic.getMessage(Locale.getDefault()) + ", on line " + diagnostic.getLineNumber() + ">");
  }
}
 
Example 3
Source File: DremioDiagnosticListener.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
  if (diagnostic.getKind() == javax.tools.Diagnostic.Kind.ERROR) {
    String message = diagnostic.toString() + " (" + diagnostic.getCode() + ")";
    logger.error(message);
    Location loc = new Location( //
        diagnostic.getSource().toString(), //
        (short) diagnostic.getLineNumber(), //
        (short) diagnostic.getColumnNumber() //
    );
    // Wrap the exception in a RuntimeException, because "report()"
    // does not declare checked exceptions.
    throw new RuntimeException(new CompileException(message, loc));
  } else if (logger.isTraceEnabled()) {
    logger.trace(diagnostic.toString() + " (" + diagnostic.getCode() + ")");
  }
}
 
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: DrillDiagnosticListener.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
  if (diagnostic.getKind() == javax.tools.Diagnostic.Kind.ERROR) {
    String message = diagnostic.toString() + " (" + diagnostic.getCode() + ")";
    logger.error(message);
    Location loc = new Location( //
        diagnostic.getSource().toString(), //
        (short) diagnostic.getLineNumber(), //
        (short) diagnostic.getColumnNumber() //
    );
    // Wrap the exception in a RuntimeException, because "report()"
    // does not declare checked exceptions.
    throw new RuntimeException(new CompileException(message, loc));
  } else if (logger.isTraceEnabled()) {
    logger.trace(diagnostic.toString() + " (" + diagnostic.getCode() + ")");
  }
}
 
Example 6
Source File: JavacParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String diagnosticToString(Diagnostic<JavaFileObject> d) {
    return d.getSource().toUri().toString() + ":" +
           d.getKind() + ":" +
           d.getStartPosition() + ":" +
           d.getPosition() + ":" +
           d.getEndPosition() + ":" +
           d.getLineNumber() + ":" +
           d.getColumnNumber() + ":" +
           d.getCode() + ":" +
           d.getMessage(null);
}
 
Example 7
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 8
Source File: HintTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void ensureCompilable(FileObject file) throws IOException, AssertionError, IllegalArgumentException {
    CompilationInfo info = parse(file);

    assertNotNull(info);

    for (Diagnostic d : info.getDiagnostics()) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getLineNumber() + ":" + d.getColumnNumber() + " " + d.getMessage(null));
    }
}
 
Example 9
Source File: HintTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void ensureCompilable(FileObject file) throws IOException, AssertionError, IllegalArgumentException {
    CompilationInfo info = parse(file);

    assertNotNull(info);

    for (Diagnostic d : info.getDiagnostics()) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getLineNumber() + ":" + d.getColumnNumber() + " " + d.getMessage(null));
    }
}
 
Example 10
Source File: JavaErrorHandling.java    From Recaf with MIT License 5 votes vote down vote up
@Override
public void report(Diagnostic<? extends VirtualJavaFileObject> diagnostic) {
	// Skip non-errors
	if (diagnostic.getKind() != Diagnostic.Kind.ERROR)
		return;
	// Convert the diagnostic to location data
	// 0-index the line number
	int line = (int) diagnostic.getLineNumber() - 1;
	int column = (int) diagnostic.getColumnNumber();
	int literalStart = calculate(Position.pos(line + 1, column));
	// TODO: Properly fix this not fetching the correct section of text in weird cases
	String[] split = codeArea.getText().substring(literalStart).split("[^\\w.]+");
	int wordLength = split.length == 0 ? 1 : split[0].length();
	int to = column + wordLength;
	String msg = diagnostic.getMessage(Locale.ENGLISH);
	Diagnostic.Kind kind = diagnostic.getKind();
	switch(kind) {
		case ERROR:
		case WARNING:
		case MANDATORY_WARNING:
			Log.warn("Line {}, Col {}: {}", line, column, msg);
			break;
		case NOTE:
		case OTHER:
		default:
			Log.info("Line {}, Col {}: {}", line, column, msg);
			break;
	}
	getProblems().add(new Pair<>(line, msg));
	setProblems(getProblems());
	// Mark problem, 0-indexing the column
	markProblem(line, column - 1, to - 1, literalStart, msg);
	refreshProblemGraphics();
}
 
Example 11
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 12
Source File: JavacTurbineCompiler.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static FormattedDiagnostic formatDiagnostic(
    Diagnostic<? extends JavaFileObject> diagnostic) {
  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(Locale.getDefault()));
  message.append(": ").append(diagnostic.getMessage(Locale.getDefault()));
  return new FormattedDiagnostic(diagnostic, message.toString());
}
 
Example 13
Source File: JavaCustomIndexer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static void brokenPlatform(
        @NonNull final Context ctx,
        @NonNull final Iterable<? extends CompileTuple> files,
        @NullAllowed final Diagnostic<JavaFileObject> diagnostic) {
    if (diagnostic == null) {
        return;
    }
    final Diagnostic<JavaFileObject> error = new Diagnostic<JavaFileObject>() {

        @Override
        public Kind getKind() {
            return Kind.ERROR;
        }

        @Override
        public JavaFileObject getSource() {
            return diagnostic.getSource();
        }

        @Override
        public long getPosition() {
            return diagnostic.getPosition();
        }

        @Override
        public long getStartPosition() {
            return diagnostic.getStartPosition();
        }

        @Override
        public long getEndPosition() {
            return diagnostic.getEndPosition();
        }

        @Override
        public long getLineNumber() {
            return diagnostic.getLineNumber();
        }

        @Override
        public long getColumnNumber() {
            return diagnostic.getColumnNumber();
        }

        @Override
        public String getCode() {
            return diagnostic.getCode();
        }

        @Override
        public String getMessage(Locale locale) {
            return diagnostic.getMessage(locale);
        }
    };
    for (CompileTuple file : files) {
        if (!file.virtual) {
            ErrorsCache.setErrors(
                ctx.getRootURI(),
                file.indexable,
                Collections.<Diagnostic<JavaFileObject>>singleton(error),
                ERROR_CONVERTOR);
        }
    }
}
 
Example 14
Source File: JavaCustomIndexer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public int getLineNumber(Diagnostic<?> t) {
    return (int) t.getLineNumber();
}
 
Example 15
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 16
Source File: BaseTest.java    From compiler with Apache License 2.0 4 votes vote down vote up
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");

	final StartContext ctx = typecheck(input);
	final Start p = ctx.ast;
	// use the whole input string to seed the RNG
	final int seed = new PrettyPrintVisitor().startAndReturn(p).hashCode();

	try {
		new VariableDeclRenameTransformer().start(p);
		new InheritedAttributeTransformer().start(p);
		new LocalAggregationTransformer().start(p);
		new VisitorOptimizingTransformer().start(p);

		final CodeGeneratingVisitor cg = new CodeGeneratingVisitor("Test", 64 * 1024 * 1024, seed, false);
		cg.start(p);

		try (final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile))) {
			o.write(cg.getCode().getBytes());
		}

		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;
}
 
Example 17
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());
}