-
Notifications
You must be signed in to change notification settings - Fork 0
/
Unchecked.java
65 lines (55 loc) · 2.42 KB
/
Unchecked.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package jamaica.unchecked;
import com.sun.source.util.*;
import com.sun.tools.javac.api.*;
import com.sun.tools.javac.util.*;
import java.lang.reflect.Method;
public class Unchecked implements Plugin {
@Override
public void init(final JavacTask task, final String... args) {
try {
// open access to the compiler packages
// requires -J--add-opens=java.base/java.lang=ALL-UNNAMED
Module unnamedModule = Unchecked.class.getModule();
Module compilerModule = ModuleLayer.boot().findModule("jdk.compiler").get();
Method opener = Module.class.getDeclaredMethod("implAddOpens", String.class, Module.class);
opener.setAccessible(true);
opener.invoke(compilerModule, "com.sun.tools.javac.api", unnamedModule);
opener.invoke(compilerModule, "com.sun.tools.javac.util", unnamedModule);
// check for nowarn parameter
boolean warn = true;
if (args.length > 0 && args[0].equals("nowarn")) {
warn = false;
} else if (args.length > 0) {
throw new IllegalArgumentException(args[0] +
" is not a valid plugin parameter");
}
// load custom diagnostic handler
Context context = ((BasicJavacTask) task).getContext();
new UncheckedDiagnosticHandler((Log) context.get(Log.logKey), warn);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static class UncheckedDiagnosticHandler extends Log.DiagnosticHandler {
final Log log;
final boolean warn;
public UncheckedDiagnosticHandler(Log log, boolean warn) {
this.log = log;
this.warn = warn;
install(log);
}
// convert checked exception errors to warnings
@Override
public void report(JCDiagnostic diag) {
if (diag.getCode().startsWith("compiler.err.unreported.exception")) {
if (warn) {
log.rawWarning((int) diag.getPosition(), "warning: unreported exception " +
diag.getArgs()[0] + " not caught or declared to be thrown");
}
} else if (!diag.getCode().equals("compiler.err.except.never.thrown.in.try")) {
prev.report(diag);
}
}
}
@Override public String getName() { return "unchecked"; }
}