use of com.sun.tools.javac.util.Log in project error-prone by google.
the class ErrorProneAnalyzer method finished.
@Override
public void finished(TaskEvent taskEvent) {
if (taskEvent.getKind() != Kind.ANALYZE) {
return;
}
if (JavaCompiler.instance(context).errorCount() > errorProneErrors) {
return;
}
TreePath path = JavacTrees.instance(context).getPath(taskEvent.getTypeElement());
if (path == null) {
path = new TreePath(taskEvent.getCompilationUnit());
}
// Assert that the event is unique and scan the current tree.
verify(seen.add(path.getLeaf()), "Duplicate FLOW event for: %s", taskEvent.getTypeElement());
Log log = Log.instance(context);
JCCompilationUnit compilation = (JCCompilationUnit) path.getCompilationUnit();
DescriptionListener descriptionListener = descriptionListenerFactory.getDescriptionListener(log, compilation);
DescriptionListener countingDescriptionListener = d -> {
if (d.severity == SeverityLevel.ERROR) {
errorProneErrors++;
}
descriptionListener.onDescribed(d);
};
JavaFileObject originalSource = log.useSource(compilation.getSourceFile());
try {
if (shouldExcludeSourceFile(compilation)) {
return;
}
if (path.getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) {
// We only get TaskEvents for compilation units if they contain no package declarations
// (e.g. package-info.java files). In this case it's safe to analyze the
// CompilationUnitTree immediately.
transformer.get().apply(path, context, countingDescriptionListener);
} else if (finishedCompilation(path.getCompilationUnit())) {
// Otherwise this TaskEvent is for a ClassTree, and we can scan the whole
// CompilationUnitTree once we've seen all the enclosed classes.
transformer.get().apply(new TreePath(compilation), context, countingDescriptionListener);
}
} catch (ErrorProneError e) {
e.logFatalError(log, context);
// terminate with Result.ABNORMAL
throw e;
} catch (LinkageError e) {
// similar to ErrorProneError
String version = ErrorProneVersion.loadVersionFromPom().or("unknown version");
log.error("error.prone.crash", getStackTraceAsString(e), version, "(see stack trace)");
throw e;
} catch (CompletionFailure e) {
// A CompletionFailure can be triggered when error-prone tries to complete a symbol
// that isn't on the compilation classpath. This can occur when a check performs an
// instanceof test on a symbol, which requires inspecting the transitive closure of the
// symbol's supertypes. If javac didn't need to check the symbol's assignability
// then a normal compilation would have succeeded, and no diagnostics will have been
// reported yet, but we don't want to crash javac.
log.error("proc.cant.access", e.sym, getDetailValue(e), getStackTraceAsString(e));
} finally {
log.useSource(originalSource);
}
}
use of com.sun.tools.javac.util.Log in project lombok by rzwitserloot.
the class JavacResolution method resolveMethodMember.
public Map<JCTree, JCTree> resolveMethodMember(JavacNode node) {
ArrayDeque<JCTree> stack = new ArrayDeque<JCTree>();
{
JavacNode n = node;
while (n != null) {
stack.push(n.get());
n = n.up();
}
}
messageSuppressor.disableLoggers();
try {
EnvFinder finder = new EnvFinder(node.getContext());
while (!stack.isEmpty()) stack.pop().accept(finder);
TreeMirrorMaker mirrorMaker = new TreeMirrorMaker(node.getTreeMaker(), node.getContext());
JCTree copy = mirrorMaker.copy(finder.copyAt());
Log log = Log.instance(node.getContext());
JavaFileObject oldFileObject = log.useSource(((JCCompilationUnit) node.top().get()).getSourceFile());
try {
memberEnterAndAttribute(copy, finder.get(), node.getContext());
return mirrorMaker.getOriginalToCopyMap();
} finally {
log.useSource(oldFileObject);
}
} finally {
messageSuppressor.enableLoggers();
}
}
use of com.sun.tools.javac.util.Log in project palantir-java-format by palantir.
the class JavaInput method buildToks.
/**
* Lex the input and build the list of toks.
*
* @param text the text to be lexed.
* @param stopTokens a set of tokens which should cause lexing to stop. If one of these is found, the returned list
* will include tokens up to but not including that token.
*/
static ImmutableList<Tok> buildToks(String text, ImmutableSet<TokenKind> stopTokens) throws FormatterException {
stopTokens = ImmutableSet.<TokenKind>builder().addAll(stopTokens).add(TokenKind.EOF).build();
Context context = new Context();
Options.instance(context).put("--enable-preview", "true");
new JavacFileManager(context, true, UTF_8);
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
context.put(DiagnosticListener.class, diagnosticCollector);
Log log = Log.instance(context);
log.useSource(new SimpleJavaFileObject(URI.create("Source.java"), Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return text;
}
});
DeferredDiagnosticHandler diagnostics = new DeferredDiagnosticHandler(log);
ImmutableList<RawTok> rawToks = JavacTokens.getTokens(text, context, stopTokens);
if (diagnostics.getDiagnostics().stream().anyMatch(d -> d.getKind() == Diagnostic.Kind.ERROR)) {
// EOF
return ImmutableList.of(new Tok(0, "", "", 0, 0, true, null));
}
int kN = 0;
List<Tok> toks = new ArrayList<>();
int charI = 0;
int columnI = 0;
for (RawTok t : rawToks) {
if (stopTokens.contains(t.kind())) {
break;
}
int charI0 = t.pos();
// Get string, possibly with Unicode escapes.
String originalTokText = text.substring(charI0, t.endPos());
String tokText = t.kind() == TokenKind.STRINGLITERAL ? // Unicode escapes removed.
t.stringVal() : originalTokText;
// The token's first character.
char tokText0 = tokText.charAt(0);
// Is this tok a token?
final boolean isToken;
// Is this tok numbered? (tokens and comments)
final boolean isNumbered;
// Extra newline at end?
String extraNewline = null;
List<String> strings = new ArrayList<>();
if (Character.isWhitespace(tokText0)) {
isToken = false;
isNumbered = false;
Iterator<String> it = Newlines.lineIterator(originalTokText);
while (it.hasNext()) {
String line = it.next();
String newline = Newlines.getLineEnding(line);
if (newline != null) {
String spaces = line.substring(0, line.length() - newline.length());
if (!spaces.isEmpty()) {
strings.add(spaces);
}
strings.add(newline);
} else if (!line.isEmpty()) {
strings.add(line);
}
}
} else if (tokText.startsWith("'") || tokText.startsWith("\"")) {
isToken = true;
isNumbered = true;
strings.add(originalTokText);
} else if (tokText.startsWith("//") || tokText.startsWith("/*")) {
// For compatibility with an earlier lexer, the newline after a // comment is its own tok.
if (tokText.startsWith("//") && (originalTokText.endsWith("\n") || originalTokText.endsWith("\r"))) {
extraNewline = Newlines.getLineEnding(originalTokText);
tokText = tokText.substring(0, tokText.length() - extraNewline.length());
originalTokText = originalTokText.substring(0, originalTokText.length() - extraNewline.length());
}
isToken = false;
isNumbered = true;
strings.add(originalTokText);
} else if (Character.isJavaIdentifierStart(tokText0) || Character.isDigit(tokText0) || (tokText0 == '.' && tokText.length() > 1 && Character.isDigit(tokText.charAt(1)))) {
// Identifier, keyword, or numeric literal (a dot may begin a number, as in .2D).
isToken = true;
isNumbered = true;
strings.add(tokText);
} else {
// Other tokens ("+" or "++" or ">>" are broken into one-character toks, because ">>"
// cannot be lexed without syntactic knowledge. This implementation fails if the token
// contains Unicode escapes.
isToken = true;
isNumbered = true;
for (int i = 0; i < tokText.length(); i++) {
char c = tokText.charAt(i);
strings.add(String.valueOf(c));
}
}
if (strings.size() == 1) {
toks.add(new Tok(isNumbered ? kN++ : -1, originalTokText, tokText, charI, columnI, isToken, t.kind()));
charI += originalTokText.length();
columnI = updateColumn(columnI, originalTokText);
} else {
if (strings.size() != 1 && !tokText.equals(originalTokText)) {
throw new FormatterException("Unicode escapes not allowed in whitespace or multi-character operators");
}
for (String str : strings) {
toks.add(new Tok(isNumbered ? kN++ : -1, str, str, charI, columnI, isToken, null));
charI += str.length();
columnI = updateColumn(columnI, originalTokText);
}
}
if (extraNewline != null) {
toks.add(new Tok(-1, extraNewline, extraNewline, charI, columnI, false, null));
columnI = 0;
charI += extraNewline.length();
}
}
// EOF tok.
toks.add(new Tok(kN, "", "", charI, columnI, true, null));
return ImmutableList.copyOf(toks);
}
use of com.sun.tools.javac.util.Log in project nullness-checker-for-checker-framework by jspecify.
the class NullSpecChecker method typeProcess.
@Override
public void typeProcess(TypeElement element, TreePath path) {
Log log = Log.instance(((JavacProcessingEnvironment) processingEnv).getContext());
int errorsBefore = log.nerrors;
super.typeProcess(element, path);
reportedNullnessError |= (log.nerrors > errorsBefore);
}
use of com.sun.tools.javac.util.Log in project checker-framework by typetools.
the class AggregateChecker method typeProcess.
// AbstractTypeProcessor delegation
@Override
public final void typeProcess(TypeElement element, TreePath tree) {
Context context = ((JavacProcessingEnvironment) processingEnv).getContext();
Log log = Log.instance(context);
if (log.nerrors > this.errsOnLastExit) {
// If there is a Java error, do not perform any of the component type checks, but come back
// for the next compilation unit.
this.errsOnLastExit = log.nerrors;
return;
}
if (!allCheckersInited) {
// error was already output. Just quit.
return;
}
for (SourceChecker checker : checkers) {
checker.errsOnLastExit = this.errsOnLastExit;
checker.typeProcess(element, tree);
if (checker.javacErrored) {
this.javacErrored = true;
return;
}
this.errsOnLastExit = checker.errsOnLastExit;
}
}
Aggregations