Search in sources :

Example 11 with Log

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);
    }
}
Also used : JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) Kind(com.sun.source.util.TaskEvent.Kind) Supplier(com.google.common.base.Supplier) ScannerSupplier(com.google.errorprone.scanner.ScannerSupplier) ErrorProneScannerTransformer(com.google.errorprone.scanner.ErrorProneScannerTransformer) HashSet(java.util.HashSet) Verify.verify(com.google.common.base.Verify.verify) Log(com.sun.tools.javac.util.Log) Suppliers(com.google.common.base.Suppliers) Tree(com.sun.source.tree.Tree) TreePath(com.sun.source.util.TreePath) Trusted(com.sun.tools.javac.api.ClientCodeWrapper.Trusted) TaskEvent(com.sun.source.util.TaskEvent) PropagatedException(com.sun.tools.javac.util.PropagatedException) TaskListener(com.sun.source.util.TaskListener) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Set(java.util.Set) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) Throwables.getStackTraceAsString(com.google.common.base.Throwables.getStackTraceAsString) JavaFileObject(javax.tools.JavaFileObject) JavacTrees(com.sun.tools.javac.api.JavacTrees) CompletionFailure(com.sun.tools.javac.code.Symbol.CompletionFailure) JavaCompiler(com.sun.tools.javac.main.JavaCompiler) Pattern(java.util.regex.Pattern) Context(com.sun.tools.javac.util.Context) SeverityLevel(com.google.errorprone.BugPattern.SeverityLevel) ASTHelpers(com.google.errorprone.util.ASTHelpers) JavaFileObject(javax.tools.JavaFileObject) TreePath(com.sun.source.util.TreePath) Log(com.sun.tools.javac.util.Log) CompletionFailure(com.sun.tools.javac.code.Symbol.CompletionFailure) Throwables.getStackTraceAsString(com.google.common.base.Throwables.getStackTraceAsString)

Example 12 with Log

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();
    }
}
Also used : JavaFileObject(javax.tools.JavaFileObject) Log(com.sun.tools.javac.util.Log) JCTree(com.sun.tools.javac.tree.JCTree) ArrayDeque(java.util.ArrayDeque)

Example 13 with Log

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);
}
Also used : Context(com.sun.tools.javac.util.Context) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) Log(com.sun.tools.javac.util.Log) ArrayList(java.util.ArrayList) DeferredDiagnosticHandler(com.sun.tools.javac.util.Log.DeferredDiagnosticHandler) IOException(java.io.IOException) JavacFileManager(com.sun.tools.javac.file.JavacFileManager) TokenKind(com.sun.tools.javac.parser.Tokens.TokenKind) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) RawTok(com.palantir.javaformat.java.JavacTokens.RawTok) RawTok(com.palantir.javaformat.java.JavacTokens.RawTok) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 14 with Log

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);
}
Also used : Log(com.sun.tools.javac.util.Log)

Example 15 with Log

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;
    }
}
Also used : Context(com.sun.tools.javac.util.Context) Log(com.sun.tools.javac.util.Log) JavacProcessingEnvironment(com.sun.tools.javac.processing.JavacProcessingEnvironment)

Aggregations

Log (com.sun.tools.javac.util.Log)24 AttrContext (com.sun.tools.javac.comp.AttrContext)9 Element (javax.lang.model.element.Element)8 VariableElement (javax.lang.model.element.VariableElement)8 Context (com.sun.tools.javac.util.Context)7 JavaFileObject (javax.tools.JavaFileObject)6 ExecutableElement (javax.lang.model.element.ExecutableElement)5 Nullable (org.checkerframework.checker.nullness.qual.Nullable)5 JCTree (com.sun.tools.javac.tree.JCTree)4 JavacScope (com.sun.tools.javac.api.JavacScope)3 JavacProcessingEnvironment (com.sun.tools.javac.processing.JavacProcessingEnvironment)3 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)3 Type (com.sun.tools.javac.code.Type)2 Parser (com.sun.tools.javac.parser.Parser)2 ParserFactory (com.sun.tools.javac.parser.ParserFactory)2 Name (com.sun.tools.javac.util.Name)2 TypeMirror (javax.lang.model.type.TypeMirror)2 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 Supplier (com.google.common.base.Supplier)1 Suppliers (com.google.common.base.Suppliers)1