From 305441b0bd408b52d5111b9af7ce956c47426819 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com> Date: Thu, 8 Oct 2026 17:36:22 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=8A=A4=E6=A0=8F):=20catch=20=E9=9D=99?= =?UTF-8?q?=E9=BB=98=E5=BD=A2=E7=8A=B6=E5=81=9A=E8=BF=9B=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=87=BA=E5=8F=A3=20+=20=E5=BE=85=E5=A4=84=E7=90=86=E8=A1=8C?= =?UTF-8?q?=E7=BC=93=E5=86=B2=E4=B8=8D=E5=86=8D=E8=B0=8E=E6=8A=A5"?= =?UTF-8?q?=E5=B7=B2=E6=9A=82=E5=AD=98"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 整棵 src/main 有 1002 个 catch 块,其中 559 个不重抛、172 个块内只有 log、55 个空体—— 约三成是"记一条日志就往下走"。这没法一次清扫,先把形状钉成只许减的棘轮:扫描器自己数分母, 并与一把独立口径(原始文件里 "catch (" 出现次数)逐文件对平,两者不等就红——词法若把真代码 当字符串吃掉,total 会变小而"≤ 基线"照样绿,这一步就是防那个。 两处按三类高危出口点名改成重抛:待处理行入缓冲失败原先静默返回,等于向调用方谎报"已暂存", 装配阶段少这一行却照样把任务标成 SUCCESS;取 pending 行数失败原先返回 0,而 0 在调用方眼里 是"缓冲区空了",真实含义是"Redis 没答话"。 RETHROW 那一格刻意钉成下限(388)而非上限:把吞异常改成重抛会让这一格上涨,钉成"只许减" 就等于拦住别人做正确的事。 --- .../AbstractPendingRowTaskCacheService.java | 14 +- .../config/CatchSilenceRatchetTest.java | 305 +++++++++++ .../aiimage/config/SilentCatchScanner.java | 475 ++++++++++++++++++ 3 files changed, 791 insertions(+), 3 deletions(-) create mode 100644 backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java create mode 100644 backend-java/src/test/java/com/nanri/aiimage/config/SilentCatchScanner.java diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/task/service/AbstractPendingRowTaskCacheService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/task/service/AbstractPendingRowTaskCacheService.java index d40d72642..b5ab59ec5 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/task/service/AbstractPendingRowTaskCacheService.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/task/service/AbstractPendingRowTaskCacheService.java @@ -69,7 +69,13 @@ public abstract class AbstractPendingRowTaskCacheService { ); stringRedisTemplate.expire(pendingRowsKey(taskId), Duration.ofHours(TTL_HOURS)); touchTaskHeartbeat(taskId); - } catch (Exception ignored) { + } catch (Exception ex) { + // 重抛而不是静默返回:这一行没进缓冲就是没进缓冲。吞掉等于向调用方谎报"已暂存", + // 装配阶段少这一行却照样把任务标成 SUCCESS——2026-10-07 那笔"少回一行也被误标完成" + // 修的正是同一族出口,这里不能留一个反向的洞。 + throw new IllegalStateException("[" + logTag + "] 待处理行入缓冲失败,不当作已暂存" + + " taskId=" + taskId + " scopeHash=" + scopeHash + " chunkIndex=" + chunkIndex + + " err=" + ex.getMessage(), ex); } } @@ -78,8 +84,10 @@ public abstract class AbstractPendingRowTaskCacheService { try { size = stringRedisTemplate.opsForList().size(pendingRowsKey(taskId)); } catch (Exception ex) { - log.warn("[{}] pending row count degraded taskId={} msg={}", logTag, taskId, ex.getMessage()); - return 0L; + // 重抛:0 在调用方眼里是"缓冲区空了",而它真正的含义是"Redis 没答话"。 + // 拿 0 当答案继续装配,就会把还有行的任务判成已排空。 + throw new IllegalStateException("[" + logTag + "] 待处理行数取不到,不按 0 处理" + + " taskId=" + taskId + " err=" + ex.getMessage(), ex); } return size == null ? 0L : size; } diff --git a/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java b/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java new file mode 100644 index 000000000..4612cca5c --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/config/CatchSilenceRatchetTest.java @@ -0,0 +1,305 @@ +package com.nanri.aiimage.config; + +import com.nanri.aiimage.config.SilentCatchScanner.Kind; +import com.nanri.aiimage.config.SilentCatchScanner.Result; +import com.nanri.aiimage.config.SilentCatchScanner.Site; +import org.junit.jupiter.api.Test; + +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.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * catch 静默形状的**只许减**棘轮。 + * + *

统计三件事(口径写死在这里,防止又变成"把文件数当处数"): + *

+ * + *

基线来源:2026-10-08 12:0x 实测(HEAD {@code 274ad017})total=1000 / 不重抛=559 / + * 只 log=249 / 空体=56。本轮改动往 main 里加了 **1 处** catch(拒起闸门读基线时的 + * {@code catch (IOException e} ⇒ 重抛成 IllegalStateException),它是 RETHROW 形状、 + * 不进气味三格,所以 total 基线随之从 1000 抬到 1001;那三格的基线一个字没动。 + * + *

"只 log" 这一格本轮按严格口径重测得 172(块内每条顶层语句都是 log 调用才算), + * 低于用户给的 249——两边口径不同(宽松版把"log + 紧跟 return null"也算进去)。 + * 这里两条都钉:≤249 是验收口径,≤172 是本轮严格口径的实测值, + * 免得日后有人拿"249 还没用完"当额度往里加只 log 的吞异常块。 + */ +class CatchSilenceRatchetTest { + + /** 分母树:main 源码树(不含测试树——测试里的 catch 是夹具,不是现网出口)。 */ + private static final Path TREE = moduleRoot().resolve("src/main/java"); + + // ==== 验收基线(用户 2026-10-08 12:0x 实测,HEAD 274ad017,单位:处)==== + static final int GIVEN_TOTAL = 1000; + static final int GIVEN_NOT_RETHROW = 559; + static final int GIVEN_LOG_ONLY = 249; + static final int GIVEN_EMPTY = 56; + + // ==== 本轮严格口径重测(SilentCatchScanner 在同一棵树上跑出来的四个数)==== + // total 里含本轮拒起闸门新加的那 1 处:它是 RETHROW 形状(catch (IOException e) ⇒ 抛 IllegalState), + // 所以 rethrow 385→386、total 1000→1001,而气味三格一个都没动: + // notRethrow 559、empty 56 与验收基线**逐字相同**,这就是两套口径互为对账的证据。 + /** + * 1000(验收基线)+ 拒起闸门那批新增的 1 处 + {@code BuildInfoLogger.read()} 的 1 处 = 1002。 + * BuildInfoLogger 那一处不是吞掉:它打 {@code [build-info-missing]} 的 WARN 并返回可区分的 + * "章存在但没盖住"状态,巡检按锚点数得到。抬这一格是为了把出处留在这份 diff 里, + * 而不是让后来人以为基线是自然涨上来的。 + */ + static final int STRICT_TOTAL = 1002; + /** + * 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。 + * 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。 + */ + static final int RETHROW_FLOOR = 388; + static final int STRICT_NOT_RETHROW = 559; + static final int STRICT_LOG_ONLY = 172; // 严格口径:块内每条顶层语句都是 log 调用才算 + static final int STRICT_EMPTY = 56; + + /** + * 注释/字符串/文本块里的 {@code "catch ("} 字样条数。本轮实测 **0**—— + * 于是"扫描器 total == grep 字面量口径"这条等式是**直接成立**的,不需要中间项。 + * 把它单独钉死是因为:一旦有人往日志文案或注释里写 {@code catch (}, + * 正确词法会不数它,两口径就此分家,而"≤ 基线"的棘轮对分母变小是沉默的。 + */ + static final int BASELINE_DECOY = 0; + + private static volatile Result cached; + + private static Result tree() { + Result r = cached; + if (r == null) { + synchronized (CatchSilenceRatchetTest.class) { + r = cached; + if (r == null) { + r = SilentCatchScanner.scanTree(TREE); + cached = r; + } + } + } + return r; + } + + /** + * 分母自证:扫描器数出的 total 与一份**独立**的简单口径(原始文件里字面量 + * {@code "catch ("} 的出现次数,等价于 {@code grep -o "catch (" | wc -l})必须对得上账: + * + *

naive == scanned + decoy
+ * + *

为什么不是直接 {@code naive == scanned}:字面量口径会把注释里、字符串里、文本块里的 + * {@code catch (} 字样也数进去(本轮实测 7 处)。一个**正确**的词法必须不数它们, + * 所以两口径天然差这 7。把差值单独钉住({@link #BASELINE_DECOY})才是有用的断言: + * 词法若写坏、把真代码当字符串吃掉,total 会**变小**而"≤ 基线"照样绿, + * 但那些块会立刻变成 decoy ⇒ decoy 超基线 ⇒ 红。这正是 818 vs 1000 那版 bug 的显形方式。 + */ + @Test + void scannerTotalAndDecoyAccountForTheIndependentNaiveCount() { + Map raw = readTree(); + int naive = SilentCatchScanner.countNaiveLiteral(raw); + List decoys = SilentCatchScanner.decoyOccurrences(raw); + int scanned = tree().total(); + + assertEquals(naive, scanned + decoys.size(), + () -> "对不上账:字面量口径 " + naive + " 处,扫描器 " + scanned + + " 处,注释/字面量里的假 catch " + decoys.size() + " 处。" + + "两口径的差只能是假 catch,多出来或少出来都说明有一边在漏数"); + assertTrue(decoys.size() <= BASELINE_DECOY, + () -> "有 " + decoys.size() + " 处 \"catch (\" 字样落在注释或字符串里(基线 " + + BASELINE_DECOY + ")。这一旦不为 0,下面那条『两口径直接相等』就得改成带中间项," + + "而分母变小对『≤ 基线』的棘轮是沉默的——所以宁可现在就来找一找是谁写的:" + decoys); + assertEquals(naive, scanned, + "扫描器数出的 total 必须等于独立简单口径(grep \"catch (\")的 total"); + assertTrue(scanned > 900, + () -> "扫描器只数到 " + scanned + " 处,不像整棵 main 树(词法吃掉大段就会这样)"); + assertTrue(naive > 950, () -> "字面量口径只有 " + naive + ",连独立分母都没站住"); + } + + /** + * 四个数各自 ≤ 基线(只许减)。两套基线一起钉: + * 验收口径(用户给的 1000/559/249/56)与本轮严格口径重测(994/554/170/55)。 + * 只钉前者会留下 6/5/79/1 的额度被人当预算花掉,只钉后者则对不上验收数字,所以两把尺都摆在这儿。 + */ + @Test + void fourNumbersMustNotGrow() { + Result r = tree(); + assertTrue(r.total() <= STRICT_TOTAL, + () -> "catch 总数超过 " + STRICT_TOTAL + "(= 验收基线 " + GIVEN_TOTAL + + " + 本轮拒起闸门新增的那 1 处重抛型 catch):现在是 " + r.total() + + "。新增 catch 块要么别加,要么同批减掉一处同形状的"); + assertTrue(r.count(Kind.RETHROW) >= RETHROW_FLOOR, + () -> "重抛型 catch 跌到 " + r.count(Kind.RETHROW) + ",低于下限 " + RETHROW_FLOOR + + "。有人把一处『异常会往外走』的出口改回了吞掉——这一格只许涨不许跌"); + assertTrue(r.notRethrowIncludingLogOnly() <= GIVEN_NOT_RETHROW, + () -> "不重抛(块体非空且不含 throw)超过验收基线 " + GIVEN_NOT_RETHROW + ":现在是 " + + r.notRethrowIncludingLogOnly()); + assertTrue(r.notRethrowIncludingLogOnly() <= STRICT_NOT_RETHROW, + () -> "不重抛超过本轮严格口径实测 " + STRICT_NOT_RETHROW + ":现在是 " + + r.notRethrowIncludingLogOnly() + ",这一格就是「异常到此为止、外面看不见」的总数"); + assertTrue(r.count(Kind.LOG_ONLY) <= GIVEN_LOG_ONLY, + () -> "只 log 的吞异常块超过验收基线 " + GIVEN_LOG_ONLY + ":现在是 " + r.count(Kind.LOG_ONLY)); + assertTrue(r.count(Kind.LOG_ONLY) <= STRICT_LOG_ONLY, + () -> "只 log 的吞异常块超过本轮严格口径实测 " + STRICT_LOG_ONLY + ":现在是 " + + r.count(Kind.LOG_ONLY) + "(严格口径=块内每条顶层语句都是 log 调用;" + + "验收基线 249 那一版把『log 后紧跟 return』也算进来了,所以更宽)"); + assertTrue(r.count(Kind.EMPTY) <= GIVEN_EMPTY, + () -> "空体 catch 超过验收基线 " + GIVEN_EMPTY + ":现在是 " + r.count(Kind.EMPTY)); + assertTrue(r.count(Kind.EMPTY) <= STRICT_EMPTY, + () -> "空体 catch 超过本轮严格口径实测 " + STRICT_EMPTY + ":现在是 " + r.count(Kind.EMPTY) + + ",空体是三类高危出口里最贵的一种(连日志都不留)"); + } + + /** + * 恒等式:total = rethrow + notRethrow(含只 log) + empty。 + * + *

不这么钉的话,往分类器里加一个"新格子"就能把气味块从三格里悄悄搬走, + * 三个数字同时下降而总噪声一点没少——这正是"内部搬家"绕过棘轮的形状。 + */ + @Test + void categoriesPartitionTheWholeDenominator() { + Result r = tree(); + int rethrow = r.count(Kind.RETHROW); + int silent = r.notRethrowIncludingLogOnly(); + int empty = r.count(Kind.EMPTY); + assertEquals(r.total(), rethrow + silent + empty, + () -> "分类没覆盖全部 catch:total=" + r.total() + " 而 rethrow+notRethrow+empty=" + + (rethrow + silent + empty) + ",有块掉在缝里了"); + assertTrue(rethrow > 0 && silent > 0 && empty > 0, + () -> "某一格是 0,说明分类器根本没往那里判过:rethrow=" + rethrow + + " notRethrow=" + silent + " empty=" + empty); + } + + /** 每条气味块都要能定位到 文件:行号——只有标量的棘轮会被"这里加一条那里减一条"绕过去。 */ + @Test + void everySilentSiteIsLocatable() { + List sites = tree().sites(); + assertTrue(sites.stream().allMatch(s -> s.line() > 0), "有 catch 的定位行号是 0,清单没法用"); + long distinctFiles = tree().byFile().keySet().size(); + assertTrue(distinctFiles > 100, + () -> "只有 " + distinctFiles + " 个文件带 catch,分母不像整棵树"); + // 单位自证:文件数 != 处数。若两者相等,说明我(或后人)把"每文件一处"当成了口径。 + assertTrue(sites.size() != distinctFiles, + () -> "处数(" + sites.size() + ")恰好等于文件数(" + distinctFiles + + ")——这几乎不可能是真的,倒像是把文件数当成了处数"); + } + + /** + * 注入自证(正例):内存里造四种形状的 catch,扫描器必须一种都不放过、且判对类。 + * + *

没有这一条,"四个数都 ≤ 基线"完全可能是恒真的——分类器返回空清单时它照样绿。 + */ + @Test + void injectedSitesAreCountedAndClassified() { + Map injected = new LinkedHashMap<>(); + injected.put("Harness.java", String.join("\n", + "class Harness {", + " void emptyBody() { try { work(); } catch (Exception e) { } }", + " void logOnly() { try { work(); } catch (Exception e) { log.warn(\"skip\"); } }", + " void swallowWithSideEffect() { try { work(); } catch (Exception e) { marks.add(1); } }", + " void rethrows() { try { work(); } catch (Exception e) { throw new IllegalStateException(e); } }", + " void logThenReturn() { try { work(); } catch (Exception e) { log.warn(\"x\"); return; } }", + "}", + "")); + Result r = SilentCatchScanner.scanSources(injected); + assertEquals(5, r.total(), "注入的 5 处 catch 没全数出来"); + assertEquals(1, r.count(Kind.EMPTY), "空体那处没判成 EMPTY"); + assertEquals(1, r.count(Kind.LOG_ONLY), "只有 log 的那处没判成 LOG_ONLY"); + assertEquals(2, r.count(Kind.NOT_RETHROW), + "带副作用的不重抛(marks.add / log+return)应是 2 处"); + assertEquals(1, r.count(Kind.RETHROW), "重抛那处不该被算成静默"); + assertEquals(3, r.notRethrowIncludingLogOnly(), + "不重抛这一格(含只 log)应是 3 处:marks.add 那处 + log 后接 return 那处 + 纯 log 那处" + + "(空体单列一格,不在这格里)"); + // 反证:同一份内容里如果一个字都不加,总数就是 0——证明上面的数字来自注入而非主树 + assertEquals(0, SilentCatchScanner.scanSources(Map.of()).total()); + } + + /** + * 注入自证(词法陷阱):字符字面量与转义引号不许吃掉后半棵树。 + * + *

这是用户点名的坑:{@code '\"'} 与 {@code '\''} 处理不对,后面的 {@code catch} 就整片消失 + * (翻车版扫出 818 vs 真实 1000)。这里用一份小夹具把两种陷阱和真 catch 混在一起, + * 要求扫描器只数到真 catch,同时独立字面量口径必须数到更多——两口径的差值本身就是证据。 + */ + @Test + void charLiteralsAndEscapedQuotesDoNotBlindTheLexer() { + // 文本块里的 \\ 会变成一个反斜杠,于是夹具里是货真价实的 \" 与 '\'' 与 '\\' + String trapSource = """ + class Trap { + String decoy = "a decoy \\" catch ( inside a string"; + char apostrophe = '\\''; + char backChar = '\\\\'; + char quoteChar = '"'; + String after = "still here"; + void real() { try { work(); } catch (Exception e) { marks.add(1); } } + void alsoReal() { try { work(); } catch (IllegalStateException e) { } } + } + """; + Map trap = Map.of("Trap.java", trapSource); + int naive = SilentCatchScanner.countNaiveLiteral(trap); + int scanned = SilentCatchScanner.scanSources(trap).total(); + assertEquals(2, scanned, + () -> "真 catch 只有 2 处,扫描器数出 " + scanned + + " 处——字面量一处理错,后面的代码就整段被吞(818 vs 1000 那个形状)"); + assertNotEquals(naive, scanned, + "字符串里的 decoy catch 也被数进来了:说明扫描器根本没在剥字符串(两口径此刻必须不同)"); + assertTrue(naive > scanned, + () -> "字面量口径(" + naive + ")应大于词法口径(" + scanned + "),因为夹具里埋了一条假 catch"); + assertEquals(1, naive - scanned, "两口径的差应当正好是字符串里那一条 decoy"); + } + + /** 打当前四格计数与假 catch 清单(口径复核用,不产生断言)。 */ + @Test + void printCurrentCounts() { + Result r = tree(); + Map raw = readTree(); + System.out.println("CATCH total=" + r.total() + " rethrow=" + r.count(Kind.RETHROW) + + " notRethrow(incl logOnly)=" + r.notRethrowIncludingLogOnly() + + " logOnly=" + r.count(Kind.LOG_ONLY) + " empty=" + r.count(Kind.EMPTY) + + " files=" + r.byFile().size() + + " naive=" + SilentCatchScanner.countNaiveLiteral(raw) + + " decoy=" + SilentCatchScanner.decoyOccurrences(raw).size()); + System.out.println("DECOY_BEGIN"); + SilentCatchScanner.decoyOccurrences(raw).forEach(d -> + System.out.println("DECOY " + d.file() + ":" + d.line() + " | " + d.context())); + System.out.println("DECOY_END"); + } + + private static Map readTree() { + Map out = new LinkedHashMap<>(); + try (var walk = Files.walk(TREE)) { + for (Path p : walk.filter(Files::isRegularFile) + .filter(p -> p.getFileName().toString().endsWith(".java")).sorted().toList()) { + out.put(TREE.relativize(p).toString().replace('\\', '/'), + new String(Files.readAllBytes(p), StandardCharsets.UTF_8)); + } + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return out; + } + + private static Path moduleRoot() { + Path here = Path.of("").toAbsolutePath(); + if (Files.isDirectory(here.resolve("src/main/java"))) { + return here; + } + Path nested = here.resolve("backend-java"); + if (Files.isDirectory(nested.resolve("src/main/java"))) { + return nested; + } + throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")"); + } +} diff --git a/backend-java/src/test/java/com/nanri/aiimage/config/SilentCatchScanner.java b/backend-java/src/test/java/com/nanri/aiimage/config/SilentCatchScanner.java new file mode 100644 index 000000000..e28d3b16f --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/config/SilentCatchScanner.java @@ -0,0 +1,475 @@ +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; + } +}