Skip to content

8354216: Small cleanups relating to Log.DiagnosticHandler #24553

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -357,8 +357,7 @@ public TypeMirror getType(DocTreePath path) {
if (tree instanceof DCReference dcReference) {
JCTree qexpr = dcReference.qualifierExpression;
if (qexpr != null) {
Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
new Log.DeferredDiagnosticHandler(log);
Log.DeferredDiagnosticHandler deferredDiagnosticHandler = log.new DeferredDiagnosticHandler();
try {
Env<AttrContext> env = getAttrContext(path.getTreePath());
Type t = attr.attribType(dcReference.qualifierExpression, env);
Expand Down Expand Up @@ -388,8 +387,7 @@ private Symbol attributeDocReference(TreePath path, DCReference ref) {
// module name and member name without type
return null;
}
Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
new Log.DeferredDiagnosticHandler(log);
Log.DeferredDiagnosticHandler deferredDiagnosticHandler = log.new DeferredDiagnosticHandler();
try {
final TypeSymbol tsym;
final Name memberName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,7 @@ class RewritingContext {
* Simple deferred diagnostic handler which filters out all messages and keep track of errors.
*/
Log.DeferredDiagnosticHandler diagHandler() {
return new Log.DeferredDiagnosticHandler(log, d -> {
return log.new DeferredDiagnosticHandler(d -> {
if (d.getType() == DiagnosticType.ERROR) {
erroneous = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2038,7 +2038,7 @@ void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resou
types.asSuper(resource, syms.autoCloseableType.tsym) != null &&
!types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself
Symbol close = syms.noSymbol;
Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log);
Log.DiagnosticHandler discardHandler = log.new DiscardDiagnosticHandler();
try {
close = rs.resolveQualifiedMethod(pos,
env,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3675,7 +3675,7 @@ private Name[] defaultTargetMetaInfo() {
*/
public boolean validateAnnotationDeferErrors(JCAnnotation a) {
boolean res = false;
final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
final Log.DiagnosticHandler diagHandler = log.new DiscardDiagnosticHandler();
try {
res = validateAnnotation(a);
} finally {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -547,7 +547,7 @@ public void scan(JCTree tree) {
}

DeferredAttrDiagHandler(Log log, JCTree newTree) {
super(log, d -> {
log.super(d -> {
PosScanner posScanner = new PosScanner(d.getDiagnosticPosition());
posScanner.scan(newTree);
return posScanner.found;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public void analyzeLambda(Env<AttrContext> env, JCLambda that, TreeMaker make, b
//step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
//related errors, which will allow for more errors to be detected
if (!speculative) {
diagHandler = new Log.DiscardDiagnosticHandler(log);
diagHandler = log.new DiscardDiagnosticHandler();
}
try {
new LambdaAliveAnalyzer().analyzeTree(env, that, make);
Expand All @@ -257,7 +257,7 @@ public List<Type> analyzeLambdaThrownTypes(final Env<AttrContext> env,
//message will be reported and will cause compilation to skip the flow analysis
//step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
//related errors, which will allow for more errors to be detected
Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
Log.DiagnosticHandler diagHandler = log.new DiscardDiagnosticHandler();
try {
new LambdaAssignAnalyzer(env).analyzeTree(env, that, make);
LambdaFlowAnalyzer flowAnalyzer = new LambdaFlowAnalyzer();
Expand All @@ -274,7 +274,7 @@ public boolean aliveAfter(Env<AttrContext> env, JCTree that, TreeMaker make) {
//message will be reported and will cause compilation to skip the flow analysis
//step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
//related errors, which will allow for more errors to be detected
Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
Log.DiagnosticHandler diagHandler = log.new DiscardDiagnosticHandler();
try {
SnippetAliveAnalyzer analyzer = new SnippetAliveAnalyzer();

Expand All @@ -291,7 +291,7 @@ public boolean breaksToTree(Env<AttrContext> env, JCTree breakTo, JCTree body, T
//message will be reported and will cause compilation to skip the flow analysis
//step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
//related errors, which will allow for more errors to be detected
Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
Log.DiagnosticHandler diagHandler = log.new DiscardDiagnosticHandler();
try {
SnippetBreakToAnalyzer analyzer = new SnippetBreakToAnalyzer(breakTo);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1166,7 +1166,7 @@ public void initProcessAnnotations(Iterable<? extends Processor> processors,
genEndPos = true;
if (!taskListener.isEmpty())
taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
deferredDiagnosticHandler = log.new DeferredDiagnosticHandler();
procEnvImpl.getFiler().setInitialState(initialFiles, initialClassNames);
}
} else { // free resources
Expand Down Expand Up @@ -1898,7 +1898,7 @@ private Name findPackageInFile(JavaFileObject fo) {

private Name parseAndGetName(JavaFileObject fo,
Function<JCTree.JCCompilationUnit, Name> tree2Name) {
DiagnosticHandler dh = new DiscardDiagnosticHandler(log);
DiagnosticHandler dh = log.new DiscardDiagnosticHandler();
JavaFileObject prevSource = log.useSource(fo);
try {
JCTree.JCCompilationUnit t = parse(fo, fo.getCharContent(false), true);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -119,7 +119,7 @@ public Reference parse(String sig, Mode mode) throws ParseException {
Name member;
List<JCTree> paramTypes;

Log.DeferredDiagnosticHandler dh = new Log.DeferredDiagnosticHandler(fac.log);
Log.DeferredDiagnosticHandler dh = fac.log.new DeferredDiagnosticHandler();

try {
int slash = sig.indexOf("/");
Expand Down Expand Up @@ -278,9 +278,10 @@ private List<JCTree> parseParams(String sig, int beginIndex, int endIndex, Log.D
}

private void checkDiags(Log.DeferredDiagnosticHandler h, int offset) throws ParseException {
JCDiagnostic d = h.getDiagnostics().peek();
if (d != null) {
throw new ParseException(offset + ((int) d.getPosition()), "dc.ref.syntax.error");
java.util.List<JCDiagnostic> diagnostics = h.getDiagnostics();
if (!diagnostics.isEmpty()) {
int pos = offset + (int)diagnostics.get(0).getPosition();
throw new ParseException(pos, "dc.ref.syntax.error");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.util.*;
import javax.tools.Diagnostic;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
Expand Down Expand Up @@ -1004,7 +1005,7 @@ private Round(int number, Set<JCCompilationUnit> treesToClean,
Assert.checkNonNull(deferredDiagnosticHandler);
this.deferredDiagnosticHandler = deferredDiagnosticHandler;
} else {
this.deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
this.deferredDiagnosticHandler = log.new DeferredDiagnosticHandler();
compiler.setDeferredDiagnosticHandler(this.deferredDiagnosticHandler);
}

Expand Down Expand Up @@ -1107,21 +1108,9 @@ boolean unrecoverableError() {
if (messager.errorRaised())
return true;

for (JCDiagnostic d: deferredDiagnosticHandler.getDiagnostics()) {
switch (d.getKind()) {
case WARNING:
if (werror)
return true;
break;

case ERROR:
if (fatalErrors || !d.isFlagSet(RECOVERABLE))
return true;
break;
}
}

return false;
return deferredDiagnosticHandler.getDiagnostics().stream()
.anyMatch(d -> (d.getKind() == Diagnostic.Kind.WARNING && werror) ||
(d.getKind() == Diagnostic.Kind.ERROR && (fatalErrors || !d.isFlagSet(RECOVERABLE))));
}

/** Find the set of annotations present in the set of top level
Expand Down
72 changes: 33 additions & 39 deletions src/jdk.compiler/share/classes/com/sun/tools/javac/util/Log.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@
package com.sun.tools.javac.util;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;

Expand Down Expand Up @@ -83,26 +85,26 @@ public String key(String k) {
/**
* DiagnosticHandler's provide the initial handling for diagnostics.
* When a diagnostic handler is created and has been initialized, it
* should install itself as the current diagnostic handler. When a
* will install itself as the current diagnostic handler. When a
* client has finished using a handler, the client should call
* {@code log.removeDiagnosticHandler();}
*
* Note that javax.tools.DiagnosticListener (if set) is called later in the
* diagnostic pipeline.
*/
public abstract static class DiagnosticHandler {
public abstract class DiagnosticHandler {
/**
* The previously installed diagnostic handler.
*/
protected DiagnosticHandler prev;
protected final DiagnosticHandler prev;

/**
* Install this diagnostic handler as the current one,
* recording the previous one.
*/
protected void install(Log log) {
prev = log.diagnosticHandler;
log.diagnosticHandler = this;
protected DiagnosticHandler() {
prev = diagnosticHandler;
diagnosticHandler = this;
}

/**
Expand All @@ -114,11 +116,7 @@ protected void install(Log log) {
/**
* A DiagnosticHandler that discards all diagnostics.
*/
public static class DiscardDiagnosticHandler extends DiagnosticHandler {
@SuppressWarnings("this-escape")
public DiscardDiagnosticHandler(Log log) {
install(log);
}
public class DiscardDiagnosticHandler extends DiagnosticHandler {

@Override
public void report(JCDiagnostic diag) { }
Expand All @@ -131,39 +129,38 @@ public void report(JCDiagnostic diag) { }
* with reportAllDiagnostics(), it will be reported to the previously
* active diagnostic handler.
*/
public static class DeferredDiagnosticHandler extends DiagnosticHandler {
private Queue<JCDiagnostic> deferred = new ListBuffer<>();
public class DeferredDiagnosticHandler extends DiagnosticHandler {
private List<JCDiagnostic> deferred = new ArrayList<>();
private final Predicate<JCDiagnostic> filter;
private final boolean passOnNonDeferrable;

public DeferredDiagnosticHandler(Log log) {
this(log, null);
public DeferredDiagnosticHandler() {
this(null);
}

public DeferredDiagnosticHandler(Log log, Predicate<JCDiagnostic> filter) {
this(log, filter, true);
public DeferredDiagnosticHandler(Predicate<JCDiagnostic> filter) {
this(filter, true);
}

@SuppressWarnings("this-escape")
public DeferredDiagnosticHandler(Log log, Predicate<JCDiagnostic> filter, boolean passOnNonDeferrable) {
this.filter = filter;
public DeferredDiagnosticHandler(Predicate<JCDiagnostic> filter, boolean passOnNonDeferrable) {
this.filter = Optional.ofNullable(filter).orElse(d -> true);
this.passOnNonDeferrable = passOnNonDeferrable;
install(log);
}

private boolean deferrable(JCDiagnostic diag) {
return !(diag.isFlagSet(DiagnosticFlag.NON_DEFERRABLE) && passOnNonDeferrable) && filter.test(diag);
}

@Override
public void report(JCDiagnostic diag) {
boolean deferrable = !passOnNonDeferrable ||
!diag.isFlagSet(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE);
if (deferrable &&
(filter == null || filter.test(diag))) {
if (deferrable(diag)) {
deferred.add(diag);
} else {
prev.report(diag);
}
}

public Queue<JCDiagnostic> getDiagnostics() {
public List<JCDiagnostic> getDiagnostics() {
return deferred;
}

Expand All @@ -174,22 +171,18 @@ public void reportDeferredDiagnostics() {

/** Report selected deferred diagnostics. */
public void reportDeferredDiagnostics(Predicate<JCDiagnostic> accepter) {
JCDiagnostic d;
while ((d = deferred.poll()) != null) {
if (accepter.test(d))
prev.report(d);
}

// Flush matching reports to the previous handler
deferred.stream()
.filter(accepter)
.forEach(prev::report);
deferred = null; // prevent accidental ongoing use
}

/** Report selected deferred diagnostics. */
/** Report all deferred diagnostics in the specified order. */
public void reportDeferredDiagnostics(Comparator<JCDiagnostic> order) {
JCDiagnostic[] diags = deferred.toArray(s -> new JCDiagnostic[s]);
Arrays.sort(diags, order);
for (JCDiagnostic d : diags) {
prev.report(d);
}
deferred = null; // prevent accidental ongoing use
deferred.sort(order);
reportDeferredDiagnostics();
}
}

Expand Down Expand Up @@ -483,6 +476,7 @@ public void setWriters(PrintWriter pw) {
*/
public void popDiagnosticHandler(DiagnosticHandler h) {
Assert.check(diagnosticHandler == h);
Assert.check(h.prev != null);
diagnosticHandler = h.prev;
}

Expand Down
4 changes: 2 additions & 2 deletions src/jdk.jshell/share/classes/jdk/jshell/TaskFactory.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -717,7 +717,7 @@ private void setVariableType(VarSnippet s) {
//if it was not enhanced yet:
//ignore any errors:
JavaFileObject prev = log.useSource(null);
DiscardDiagnosticHandler h = new DiscardDiagnosticHandler(log);
DiscardDiagnosticHandler h = log.new DiscardDiagnosticHandler();
parserFactory.runPermitIntersectionTypes(() -> {
try {
//parse the type as a cast, i.e. "(<typeName>) x". This is to support
Expand Down