package com.nanri.aiimage.config; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; /** * catch 块静默形状的扫描器(测试期工具,不进生产 jar 的行为面)。 * *

四个口径,单位一律是**处**(一个 catch 块算一处),不是文件数: *

* {@code empty} 与 {@code notRethrow} 是并列的两格(空体不计入 notRethrow), * 恒等式 {@code total = rethrow + notRethrow + empty} 由 {@code CatchSilenceRatchetTest} 检查, * 保证没有第五种形状从分类缝里漏掉。 * *

词法是第一号的坑:简陋的"剥字符串"会把 {@code '"} 或 {@code \"} 读歪, * 从整棵树上抹掉半棵树的内容(实测翻车版本:扫出 818 处 vs 真实 1000 处)。 * 这里 {@link #stripNonCode} 是一个手写的单遍扫描,依次处理 * 行注释 / 块注释 / 文本块 {@code """..."""} / 字符串字面量 / 字符字面量, * 并且**保持长度与换行位置不变**(这样行号仍然对得上)。 * 即便如此,测试仍不信任它自己的分母:那条用例会把扫描器数出的 total 与 * 一份独立口径(原始文件里 {@code "catch ("} 的字面量出现次数)对撞,不一致就红。 */ public final class SilentCatchScanner { /** 一个 catch 块的分类结果。 */ public enum Kind { /** 块体里有 throw(重抛或抛新异常)——不属于静默出口。 */ RETHROW, /** 块体非空、不含 throw,且每条顶层语句都是 log 调用。 */ LOG_ONLY, /** 块体非空、不含 throw,还干了别的(或干脆 return/吞掉)。 */ NOT_RETHROW, /** 块体剥掉注释后为空。 */ EMPTY } /** * 一处 catch 的定位与判类结果。 * * @param rawBody 未剥词法的块体原文——判断"有没有留下锚点"必须看这个, * 因为 {@code log.warn("[xxx] ...")} 的方括号就在字符串里,剥完就没了。 */ public record Site(String file, int line, Kind kind, String body, String rawBody) { /** 块体原文里是否存在 {@code [tag]} 形式的锚点。 */ public boolean hasAnchor() { return ANCHOR.matcher(rawBody).find(); } /** 锚点清单(可能多个),用于人工核对。 */ public java.util.List anchors() { java.util.List out = new ArrayList<>(); java.util.regex.Matcher m = ANCHOR.matcher(rawBody); while (m.find()) { out.add(m.group()); } return out; } } private static final Pattern ANCHOR = Pattern.compile("\\[[A-Za-z0-9_.-]{3,}\\]"); /** 一次扫描的汇总。 */ public record Result(List sites) { public int total() { return sites.size(); } public int count(Kind kind) { return (int) sites.stream().filter(s -> s.kind() == kind).count(); } /** {@code notRethrow} 这一格按用户口径 = 非空且不含 throw,即 LOG_ONLY 也计入。 */ public int notRethrowIncludingLogOnly() { return count(Kind.NOT_RETHROW) + count(Kind.LOG_ONLY); } public Map byFile() { Map out = new LinkedHashMap<>(); for (Site s : sites) { int[] cell = out.computeIfAbsent(s.file(), k -> new int[4]); cell[0]++; if (s.kind() == Kind.NOT_RETHROW || s.kind() == Kind.LOG_ONLY) { cell[1]++; } if (s.kind() == Kind.LOG_ONLY) { cell[2]++; } if (s.kind() == Kind.EMPTY) { cell[3]++; } } return out; } } /** log 调用语句:接收者只认 slf4j 那几个常见名字,实测全树 log 调用的接收者只有 {@code log} 一个。 */ private static final Pattern LOG_CALL = Pattern.compile("^(?:this\\.)?(?:log|logger|LOG|LOGGER)\\s*\\.\\s*[A-Za-z_$][\\w$]*\\s*\\(.*\\)\\z", Pattern.DOTALL); /** 独立简单口径:原始字节里的字面量 {@code "catch ("},与 {@code grep -o "catch (" | wc -l} 同一件事。 */ public static final String NAIVE_LITERAL = "catch ("; private SilentCatchScanner() { } /** 扫一棵树(通常是 {@code src/main/java})。 */ public static Result scanTree(Path root) { Map sources = new LinkedHashMap<>(); try (Stream walk = Files.walk(root)) { for (Path p : walk.filter(Files::isRegularFile) .filter(p -> p.getFileName().toString().endsWith(".java")) .sorted() .toList()) { sources.put(root.relativize(p).toString().replace('\\', '/'), new String(Files.readAllBytes(p), StandardCharsets.UTF_8)); } } catch (IOException e) { throw new UncheckedIOException("扫描失败: " + root, e); } return scanSources(sources); } /** * 扫内存里的源码集合(名字 -> 内容)。注入反例走这个入口, * 于是"能不能数出来"这件事不必往主树上写文件就能自证。 */ public static Result scanSources(Map sources) { List sites = new ArrayList<>(); for (Map.Entry e : sources.entrySet()) { collect(e.getKey(), e.getValue(), sites); } return new Result(List.copyOf(sites)); } /** 原始字节里有 {@value #NAIVE_LITERAL} 字样、但落在注释/字面量里(因此不是真 catch)的那一处。 */ public record Decoy(String file, int line, String context) { } /** 原始内容里 {@value #NAIVE_LITERAL} 的字面量出现次数(独立分母,不经任何词法处理)。 */ public static int countNaiveLiteral(Map sources) { int n = 0; for (String src : sources.values()) { int at = 0; while ((at = src.indexOf(NAIVE_LITERAL, at)) >= 0) { n++; at += NAIVE_LITERAL.length(); } } return n; } /** * 找出"grep 会数到、但根本不是 catch"的那些位置:原始文本里有 {@code catch (} 字样, * 而 {@link #stripNonCode} 把同一位置的内容抹掉了(说明它在注释或字面量里)。 * *

这个清单是扫描器自己的解毒剂:词法一旦写坏(把真代码当成字符串吃掉), * total 会**变小**、棘轮的"≤ 基线"照样绿——只有 decoy 清单会同步变大。 * 所以判据是 {@code total + decoy == 字面量口径} 且 {@code decoy} 不许超过基线。 */ public static List decoyOccurrences(Map sources) { List out = new ArrayList<>(); for (Map.Entry e : sources.entrySet()) { String raw = e.getValue(); String code = stripNonCode(raw); int at = 0; while (true) { int i = raw.indexOf(NAIVE_LITERAL, at); if (i < 0) { break; } if (!code.startsWith(NAIVE_LITERAL, i)) { out.add(new Decoy(e.getKey(), lineOf(raw, i), contextOf(raw, i))); } at = i + NAIVE_LITERAL.length(); } } return out; } private static String contextOf(String raw, int index) { int start = raw.lastIndexOf('\n', index) + 1; int end = raw.indexOf('\n', index); if (end < 0) { end = raw.length(); } String line = raw.substring(start, end).trim(); return line.length() > 100 ? line.substring(0, 100) + "..." : line; } private static void collect(String file, String source, List out) { String code = stripNonCode(source); int at = 0; while (true) { int hit = indexOfCatch(code, at); if (hit < 0) { return; } int open = code.indexOf('(', hit); int close = matchParen(code, open); if (close < 0) { return; } int brace = code.indexOf('{', close); int end = brace < 0 ? -1 : matchBrace(code, brace); if (end < 0) { // 结构读不出来就明说:静默跳过会让分母变小而棘轮照样绿 throw new IllegalStateException("解析不出 " + file + " 第 " + lineOf(code, hit) + " 行那个 catch 的块体(括号没配好?)"); } String body = code.substring(brace + 1, end); // stripNonCode 保持长度与换行位置不变,所以同一个下标区间在原文上取到的就是块体原文 String rawBody = source.substring(brace + 1, end); out.add(new Site(file, lineOf(code, hit), classify(body), body, rawBody)); // 游标只前进到 "catch" 这个词之后,**不跳过块体**: // catch 体里再套 try/catch 是常态(外层兜底、内层只吞某一步), // 整段跳过的话这 7 处嵌套 catch 就从分母里消失了(实测 994 vs 字面量 1001)。 at = hit + "catch".length(); } } /** {@code catch} 关键字后面(允许空白/换行)紧跟 {@code (} 的那一处。 */ private static int indexOfCatch(String code, int from) { int at = from; while (true) { int i = code.indexOf("catch", at); if (i < 0) { return -1; } boolean leftOk = i == 0 || !isIdentPart(code.charAt(i - 1)); int j = i + "catch".length(); while (j < code.length() && Character.isWhitespace(code.charAt(j))) { j++; } if (leftOk && j < code.length() && code.charAt(j) == '(') { return i; } at = i + "catch".length(); } } private static Kind classify(String body) { String trimmed = body.trim(); if (trimmed.isEmpty()) { return Kind.EMPTY; } if (containsKeyword(trimmed, "throw")) { return Kind.RETHROW; } List statements = topLevelStatements(trimmed); if (!statements.isEmpty()) { boolean allLog = true; for (String s : statements) { String one = s.trim(); if (!one.isEmpty() && !LOG_CALL.matcher(one).matches()) { allLog = false; break; } } if (allLog) { return Kind.LOG_ONLY; } } return Kind.NOT_RETHROW; } private static boolean containsKeyword(String text, String keyword) { int at = 0; while (true) { int i = text.indexOf(keyword, at); if (i < 0) { return false; } boolean leftOk = i == 0 || !isIdentPart(text.charAt(i - 1)); int after = i + keyword.length(); boolean rightOk = after >= text.length() || !isIdentPart(text.charAt(after)); if (leftOk && rightOk) { return true; } at = after; } } private static boolean isIdentPart(char c) { return Character.isLetterOrDigit(c) || c == '_' || c == '$'; } /** 按顶层 {@code ;} 切语句({@code ()[]{} } 内部的分号不算分隔符,for(;;) 就是这一类)。 */ static List topLevelStatements(String body) { List out = new ArrayList<>(); int depth = 0; StringBuilder cur = new StringBuilder(); for (int i = 0; i < body.length(); i++) { char c = body.charAt(i); if (c == '(' || c == '[' || c == '{') { depth++; } else if (c == ')' || c == ']') { depth--; } else if (c == '}' && depth > 0) { depth--; } else if (c == ';' && depth == 0) { out.add(cur.toString()); cur.setLength(0); continue; } cur.append(c); } if (cur.toString().trim().isEmpty()) { return out; } out.add(cur.toString()); return out; } private static int matchParen(String s, int open) { return match(s, open, '(', ')'); } private static int matchBrace(String s, int open) { return match(s, open, '{', '}'); } private static int match(String s, int open, char lo, char hi) { if (open < 0 || open >= s.length() || s.charAt(open) != lo) { return -1; } int depth = 0; for (int i = open; i < s.length(); i++) { char c = s.charAt(i); if (c == lo) { depth++; } else if (c == hi) { depth--; if (depth == 0) { return i; } } } return -1; } private static int lineOf(String code, int index) { int line = 1; for (int i = 0; i < index && i < code.length(); i++) { if (code.charAt(i) == '\n') { line++; } } return line; } /** * 把注释与字面量的内容换成空格,长度与换行位置一律不变。 * *

顺序即词法:先看 {@code /} 的两种注释,再看文本块(必须在普通字符串之前, * 否则 {@code """} 会被当成一个空串加一个串),然后普通串,最后字符字面量。 * 反斜杠一律跳过下一个字符——于是 {@code "\""} 里的引号不会终结字符串、 * {@code '\\'} 不会让下一个 {@code '\''} 变成孤儿引号(这正是 818/1000 那版翻车的地方)。 */ static String stripNonCode(String src) { char[] c = src.toCharArray(); int n = c.length; int i = 0; while (i < n) { char ch = c[i]; if (ch == '/' && i + 1 < n && c[i + 1] == '/') { int j = i; while (j < n && c[j] != '\n') { c[j] = ' '; j++; } i = j; } else if (ch == '/' && i + 1 < n && c[i + 1] == '*') { int j = i; int close = src.indexOf("*/", i + 2); int end = close < 0 ? n : close + 2; while (j < end) { if (c[j] != '\n') { c[j] = ' '; } j++; } i = end; } else if (ch == '"' && startsTextBlock(src, i)) { int j = endOfTextBlock(src, i); for (int k = i; k < j; k++) { if (c[k] != '\n') { c[k] = ' '; } } i = j; } else if (ch == '"') { int j = i + 1; while (j < n) { if (c[j] == '\\') { j += 2; continue; } if (c[j] == '\n') { break; // 普通串不跨行:行尾就是终结,别把下一行吃掉 } if (c[j] == '"') { j++; break; } j++; } for (int k = i + 1; k < j; k++) { c[k] = ' '; } i = j; } else if (ch == '\'') { int j = i + 1; while (j < n) { if (c[j] == '\\') { j += 2; continue; } if (c[j] == '\n') { break; } if (c[j] == '\'') { j++; break; } j++; } for (int k = i + 1; k < j; k++) { c[k] = ' '; } i = j; } else { i++; } } return new String(c); } private static boolean startsTextBlock(String src, int i) { return src.startsWith("\"\"\"", i); } /** 文本块的终点 = 结束定界符之后(找不到就走到文件尾,绝不吃掉后续代码)。 */ private static int endOfTextBlock(String src, int i) { int j = i + 3; int n = src.length(); while (j < n) { if (src.charAt(j) == '\\') { j += 2; continue; } if (src.startsWith("\"\"\"", j)) { return j + 3; } j++; } return n; } }