dsh-stm32 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/README.md +92 -40
  2. package/README_EN.md +85 -36
  3. package/assets/README.md +85 -0
  4. package/assets/VERSION +1 -0
  5. package/assets/device/c0/chips.json +1108 -0
  6. package/assets/device/f0/chips.json +1570 -0
  7. package/assets/device/f1/chips.json +1238 -0
  8. package/assets/device/f1/svd/100.json +943 -0
  9. package/assets/device/f1/svd/101.json +901 -0
  10. package/assets/device/f1/svd/102.json +522 -0
  11. package/assets/device/f1/svd/103.json +1139 -0
  12. package/assets/device/f1/svd/105.json +1117 -0
  13. package/assets/device/f1/svd/107.json +1195 -0
  14. package/assets/device/f2/chips.json +674 -0
  15. package/assets/device/f3/chips.json +1318 -0
  16. package/assets/device/f4/chips.json +2942 -0
  17. package/assets/device/f7/chips.json +1710 -0
  18. package/assets/device/g0/chips.json +2102 -0
  19. package/assets/device/g4/chips.json +2494 -0
  20. package/assets/device/h5/chips.json +898 -0
  21. package/assets/device/h7/chips.json +1948 -0
  22. package/assets/device/l0/chips.json +2494 -0
  23. package/assets/device/l1/chips.json +1234 -0
  24. package/assets/device/l4/chips.json +2130 -0
  25. package/assets/device/l4+/chips.json +856 -0
  26. package/assets/device/l5/chips.json +226 -0
  27. package/assets/device/u0/chips.json +688 -0
  28. package/assets/device/u3/chips.json +310 -0
  29. package/assets/device/u5/chips.json +884 -0
  30. package/assets/device/wba/chips.json +506 -0
  31. package/assets/device/wl/chips.json +184 -0
  32. package/assets/headers/f1/stm32f100xb.h +5972 -0
  33. package/assets/headers/f1/stm32f100xe.h +6587 -0
  34. package/assets/headers/f1/stm32f101x6.h +5315 -0
  35. package/assets/headers/f1/stm32f101xb.h +5446 -0
  36. package/assets/headers/f1/stm32f101xe.h +6503 -0
  37. package/assets/headers/f1/stm32f101xg.h +6713 -0
  38. package/assets/headers/f1/stm32f102x6.h +6448 -0
  39. package/assets/headers/f1/stm32f102xb.h +6570 -0
  40. package/assets/headers/f1/stm32f103x6.h +10109 -0
  41. package/assets/headers/f1/stm32f103xb.h +10240 -0
  42. package/assets/headers/f1/stm32f103xe.h +11767 -0
  43. package/assets/headers/f1/stm32f103xg.h +11951 -0
  44. package/assets/headers/f1/stm32f105xc.h +14340 -0
  45. package/assets/headers/f1/stm32f107xc.h +15253 -0
  46. package/assets/headers/f1/stm32f1xx.h +273 -0
  47. package/assets/headers/f1/system_stm32f1xx.h +96 -0
  48. package/assets/ioc/family/C0.ioc +82 -0
  49. package/assets/ioc/family/F0.ioc +71 -0
  50. package/assets/ioc/family/F2.ioc +91 -0
  51. package/assets/ioc/family/F3.ioc +94 -0
  52. package/assets/ioc/family/F4.ioc +91 -0
  53. package/assets/ioc/family/F7.ioc +102 -0
  54. package/assets/ioc/family/G0.ioc +90 -0
  55. package/assets/ioc/family/G4.ioc +110 -0
  56. package/assets/ioc/family/H5.ioc +116 -0
  57. package/assets/ioc/family/H7.ioc +133 -0
  58. package/assets/ioc/family/L0.ioc +92 -0
  59. package/assets/ioc/family/L1.ioc +87 -0
  60. package/assets/ioc/family/L4+.ioc +92 -0
  61. package/assets/ioc/family/L4.ioc +93 -0
  62. package/assets/ioc/family/L5.ioc +91 -0
  63. package/assets/ioc/family/U0.ioc +103 -0
  64. package/assets/ioc/family/U3.ioc +113 -0
  65. package/assets/ioc/family/U5.ioc +102 -0
  66. package/assets/ioc/family/WBA.ioc +100 -0
  67. package/assets/ioc/family/WL.ioc +93 -0
  68. package/assets/ioc/minimal/STM32F100C8Tx.ioc +113 -0
  69. package/assets/ioc/minimal/STM32F100RCTx.ioc +113 -0
  70. package/assets/ioc/minimal/STM32F101C4Tx.ioc +113 -0
  71. package/assets/ioc/minimal/STM32F101C8Tx.ioc +113 -0
  72. package/assets/ioc/minimal/STM32F101RCTx.ioc +113 -0
  73. package/assets/ioc/minimal/STM32F101RFTx.ioc +113 -0
  74. package/assets/ioc/minimal/STM32F102C4Tx.ioc +113 -0
  75. package/assets/ioc/minimal/STM32F102C8Tx.ioc +113 -0
  76. package/assets/ioc/minimal/STM32F103C4Tx.ioc +113 -0
  77. package/assets/ioc/minimal/STM32F103C8Tx.ioc +113 -0
  78. package/assets/ioc/minimal/STM32F103RCTx.ioc +113 -0
  79. package/assets/ioc/minimal/STM32F103RFTx.ioc +113 -0
  80. package/assets/ioc/minimal/STM32F105RCTx.ioc +113 -0
  81. package/assets/ioc/minimal/STM32F107RCTx.ioc +113 -0
  82. package/assets/ld/f1/STM32F100C8Tx_FLASH.ld +249 -0
  83. package/assets/ld/f1/STM32F100RCTx_FLASH.ld +249 -0
  84. package/assets/ld/f1/STM32F101C4Tx_FLASH.ld +249 -0
  85. package/assets/ld/f1/STM32F101C8Tx_FLASH.ld +249 -0
  86. package/assets/ld/f1/STM32F101RCTx_FLASH.ld +249 -0
  87. package/assets/ld/f1/STM32F101RFTx_FLASH.ld +249 -0
  88. package/assets/ld/f1/STM32F102C4Tx_FLASH.ld +249 -0
  89. package/assets/ld/f1/STM32F102C8Tx_FLASH.ld +249 -0
  90. package/assets/ld/f1/STM32F103C4Tx_FLASH.ld +249 -0
  91. package/assets/ld/f1/STM32F103C8Tx_FLASH.ld +249 -0
  92. package/assets/ld/f1/STM32F103RCTx_FLASH.ld +249 -0
  93. package/assets/ld/f1/STM32F103RFTx_FLASH.ld +249 -0
  94. package/assets/ld/f1/STM32F105RCTx_FLASH.ld +249 -0
  95. package/assets/ld/f1/STM32F107RCTx_FLASH.ld +249 -0
  96. package/assets/manifest.json +1130 -0
  97. package/assets/startup/f1/startup_stm32f100xb.s +407 -0
  98. package/assets/startup/f1/startup_stm32f100xe.s +449 -0
  99. package/assets/startup/f1/startup_stm32f101x6.s +322 -0
  100. package/assets/startup/f1/startup_stm32f101xb.s +338 -0
  101. package/assets/startup/f1/startup_stm32f101xe.s +423 -0
  102. package/assets/startup/f1/startup_stm32f101xg.s +439 -0
  103. package/assets/startup/f1/startup_stm32f102x6.s +330 -0
  104. package/assets/startup/f1/startup_stm32f102xb.s +346 -0
  105. package/assets/startup/f1/startup_stm32f103x6.s +348 -0
  106. package/assets/startup/f1/startup_stm32f103xb.s +364 -0
  107. package/assets/startup/f1/startup_stm32f103xe.s +470 -0
  108. package/assets/startup/f1/startup_stm32f103xg.s +466 -0
  109. package/assets/startup/f1/startup_stm32f105xc.s +463 -0
  110. package/assets/startup/f1/startup_stm32f107xc.s +472 -0
  111. package/assets/templates/family/C0.ioc +82 -0
  112. package/assets/templates/family/F0.ioc +71 -0
  113. package/assets/templates/family/F2.ioc +91 -0
  114. package/assets/templates/family/F3.ioc +94 -0
  115. package/assets/templates/family/F4.ioc +91 -0
  116. package/assets/templates/family/F7.ioc +102 -0
  117. package/assets/templates/family/G0.ioc +90 -0
  118. package/assets/templates/family/G4.ioc +110 -0
  119. package/assets/templates/family/H5.ioc +116 -0
  120. package/assets/templates/family/H7.ioc +133 -0
  121. package/assets/templates/family/L0.ioc +92 -0
  122. package/assets/templates/family/L1.ioc +87 -0
  123. package/assets/templates/family/L4+.ioc +92 -0
  124. package/assets/templates/family/L4.ioc +93 -0
  125. package/assets/templates/family/L5.ioc +91 -0
  126. package/assets/templates/family/U0.ioc +103 -0
  127. package/assets/templates/family/U3.ioc +113 -0
  128. package/assets/templates/family/U5.ioc +102 -0
  129. package/assets/templates/family/WB.ioc +81 -0
  130. package/assets/templates/family/WBA.ioc +100 -0
  131. package/assets/templates/family/WL.ioc +93 -0
  132. package/docs/reading-guide.md +94 -71
  133. package/lib/data/chips.js +38 -51
  134. package/lib/data/clock-db.js +830 -0
  135. package/lib/data/clock-f1.js +12 -45
  136. package/lib/data/cmsis-sources.js +264 -17
  137. package/lib/data/db-presets.js +252 -0
  138. package/lib/data/device-facts.js +274 -0
  139. package/lib/data/family.js +515 -0
  140. package/lib/data/firmware-packages.js +562 -0
  141. package/lib/data/install-guides.js +2 -2
  142. package/lib/data/ioc-presets.js +248 -0
  143. package/lib/data/ioc-schema.js +1058 -0
  144. package/lib/data/rm-topics/stm32c0.json +227 -0
  145. package/lib/data/rm-topics.js +103 -0
  146. package/lib/data/search-roots.js +42 -1
  147. package/lib/data/stm32f1.js +95 -150
  148. package/lib/data/svd.js +643 -0
  149. package/lib/data/toolchain-config.js +0 -14
  150. package/lib/engine/assets.js +659 -0
  151. package/lib/engine/breakpoints.js +297 -0
  152. package/lib/engine/clock-derived.js +101 -0
  153. package/lib/engine/clock-direct.js +313 -0
  154. package/lib/engine/clock-plan.js +96 -52
  155. package/lib/engine/clock-pllmn.js +319 -0
  156. package/lib/engine/cmake-sources.js +67 -13
  157. package/lib/engine/cube-mx-guard.js +44 -0
  158. package/lib/engine/cube-programmer.js +137 -0
  159. package/lib/engine/cubemx-db.js +273 -0
  160. package/lib/engine/debug-session.js +576 -22
  161. package/lib/engine/debug.js +99 -46
  162. package/lib/engine/doctor.js +162 -19
  163. package/lib/engine/facts-acquire.js +416 -0
  164. package/lib/engine/facts.js +134 -0
  165. package/lib/engine/firmware-install.js +176 -5
  166. package/lib/engine/firmware-official.js +451 -0
  167. package/lib/engine/flash.js +317 -76
  168. package/lib/engine/gdb-mi.js +476 -0
  169. package/lib/engine/generate.js +9 -2
  170. package/lib/engine/hal-chip.js +124 -41
  171. package/lib/engine/ioc-plan.js +1247 -63
  172. package/lib/engine/ioc-rules.js +698 -0
  173. package/lib/engine/ioc-verify.js +706 -0
  174. package/lib/engine/ioc.js +43 -4
  175. package/lib/engine/msys2-install.js +4 -4
  176. package/lib/engine/probe-error.js +231 -0
  177. package/lib/engine/probe-session.js +347 -0
  178. package/lib/engine/probe.js +18 -3
  179. package/lib/engine/register-clock.js +41 -0
  180. package/lib/engine/register-gpio.js +115 -0
  181. package/lib/engine/register-linker.js +12 -7
  182. package/lib/engine/register-template.js +130 -45
  183. package/lib/engine/regs.js +43 -8
  184. package/lib/engine/rm-extract.js +144 -0
  185. package/lib/engine/rm-sources.js +360 -0
  186. package/lib/engine/rm-text.js +56 -0
  187. package/lib/engine/rtt.js +758 -0
  188. package/lib/engine/scaffold.js +185 -18
  189. package/lib/engine/toolchain-gate.js +0 -4
  190. package/lib/engine/watch.js +227 -0
  191. package/lib/index.js +12 -2
  192. package/lib/skill/stm32-workflow.js +2 -2
  193. package/lib/tools/assets.js +272 -0
  194. package/lib/tools/cache.js +8 -0
  195. package/lib/tools/debug-session.js +41 -6
  196. package/lib/tools/debug.js +41 -11
  197. package/lib/tools/doctor.js +65 -4
  198. package/lib/tools/firmware-install.js +31 -6
  199. package/lib/tools/flash.js +47 -10
  200. package/lib/tools/generate.js +25 -0
  201. package/lib/tools/ioc-apply.js +2 -0
  202. package/lib/tools/ioc-inspect.js +2 -0
  203. package/lib/tools/ioc-plan.js +59 -2
  204. package/lib/tools/ioc-verify.js +237 -0
  205. package/lib/tools/project-create.js +63 -3
  206. package/lib/tools/regs.js +453 -61
  207. package/lib/tools/route-plan.js +3 -0
  208. package/lib/tools/rtt.js +470 -0
  209. package/lib/tools/watch.js +256 -0
  210. package/package.json +5 -4
  211. package/templates/openocd/stm32c0x.cfg +83 -0
  212. package/templates/openocd/stm32u0x.cfg +64 -0
  213. package/templates/register/CMakeLists.txt +8 -2
  214. package/templates/register/Core/Inc/rtt.h +138 -0
  215. package/templates/register/Core/Src/main.c +42 -25
  216. package/templates/register/Core/Src/rtt.c +373 -0
  217. package/templates/scaffold/RTT.md +90 -0
  218. package/templates/scaffold/STM32F103XX_FLASH.ld +3 -0
  219. package/templates/scaffold/cmake/user/CMakeLists.txt +7 -0
  220. package/templates/scaffold/openocd.cfg +5 -3
  221. package/templates/scaffold/vscode/launch.json +8 -4
  222. package/docs/development-notes.md +0 -2116
  223. package/docs/dsh-stm32-plugin-/350/247/204/346/240/274.md +0 -673
  224. package/docs/logic-audit.md +0 -607
  225. package/lib/data/f1-ram.generated.js +0 -34
@@ -13,23 +13,28 @@ import fs from "node:fs";
13
13
  import path from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { CMSIS_FAMILIES, cmsisTemplatePlan, startupChoiceFor } from "../data/cmsis-sources.js";
16
+ import { deviceFactsSource } from "../data/device-facts.js";
16
17
  import { cacheRootInfo, checkCacheEntry, readCacheIndex, resolveCacheEntry, sha256OfFile, upsertCacheEntry } from "./cache.js";
17
18
  import { fetchAll } from "./fetch.js";
18
- import { planRegisterClock, renderClockInit } from "./register-clock.js";
19
+ import { planGenericClock, planRegisterClock, renderClockInit, renderGenericClockInit } from "./register-clock.js";
20
+ import { renderLedFunctions } from "./register-gpio.js";
19
21
  import { planRegisterLinker, renderLinkerScript } from "./register-linker.js";
20
- import { backupBeforeOverwrite, backupWarning, cleanupAfterFailure, mkdirTracked, preflightTarget, templateDir } from "./scaffold.js";
22
+ import { backupBeforeOverwrite, backupWarning, cleanupAfterFailure, mkdirTracked, preflightTarget, templateDir, writeVscodeConfigs } from "./scaffold.js";
21
23
  /** 寄存器版模板目录:lib/engine/register-template.js → ../../templates/register。 */
22
24
  export function registerTemplateDir() {
23
25
  return fileURLToPath(new URL("../../templates/register/", import.meta.url));
24
26
  }
25
27
  /** 型号/族 → 启动文件与设备宏;认不出返回 null(不猜文件名)。 */
26
- export function resolveStartupChoice(request) {
28
+ export function resolveStartupChoice(request, env = process.env) {
27
29
  const mcu = (request.mcu ?? "").trim();
28
30
  if (mcu !== "")
29
- return startupChoiceFor(mcu);
31
+ return startupChoiceFor(mcu, env);
30
32
  const family = (request.family ?? "F1").trim().toUpperCase();
31
- // 只给族时按中容量档(F1 → xB):蓝丸 C8T6 正是这一档,也是最常见的入门芯片。
32
- return startupChoiceFor(family + ":B");
33
+ // 只给族时只有 F1 有默认档(中容量 xB,蓝丸 C8T6 正是这一档)。
34
+ // 其它族必须给具体型号:同一族里不同 line 的启动文件/设备头完全不同,猜一个就是编文件名。
35
+ if (family !== "F1")
36
+ return null;
37
+ return startupChoiceFor("F1:B", env);
33
38
  }
34
39
  function emptyResult(cacheRoot, error, message) {
35
40
  return { ok: false, family: "", id: "", cacheRoot, entryDir: "", cacheHit: false, startup: "", deviceDefine: "", deviceHeader: "", files: 0, bytes: 0, error, message };
@@ -44,15 +49,24 @@ function emptyResult(cacheRoot, error, message) {
44
49
  export async function ensureCmsisTemplate(request = {}) {
45
50
  const env = request.env ?? process.env;
46
51
  const info = cacheRootInfo(env);
47
- const choice = resolveStartupChoice(request);
52
+ const choice = resolveStartupChoice(request, env);
48
53
  if (choice === null) {
49
54
  const asked = (request.mcu ?? request.family ?? "").trim();
55
+ // 内置资源不全时,型号解析必然是空——这种时候要说清「先确认内置资源完整」,别让人以为型号写错了。
56
+ if (deviceFactsSource({ ...process.env, ...env }) === "none") {
57
+ return emptyResult(info.root, "facts-missing", "设备事实还没就绪:找不到插件内置的芯片表(assets/device/…);先跑 stm32_assets verify 确认安装完整(缺文件就重装插件),再建工程。");
58
+ }
50
59
  // F103 家族里上游没有的容量档要单独说清楚(A24):说"认不出"会让人以为插件坏了。
51
60
  const f103 = /^STM32F103([A-Z])([0-9A-Z])/u.exec(asked.toUpperCase());
52
- const densityNote = f103 !== null
53
- ? "上游 CMSIS 只有 x6 / xB / xE 三套启动文件,没有容量档 " + (f103[2] ?? "") + " 这一套:F103 的 4/8/6 档归到 x6 或 xB,C/D/E 档归到 xE。换 STM32F103C8T6 / CBT6 这类型号,"
54
- : "换 F103 型号,";
55
- return emptyResult(info.root, "unsupported-mcu", "认不出这颗芯片的启动文件(目前只做 STM32F1 的 F103 系列):" + (asked || "(没给型号)") + "。" + densityNote + "或改用 HAL 路线(.ioc + CubeMX)。");
61
+ if (/^STM32F1/u.test(asked.toUpperCase())) {
62
+ const densityNote = f103 !== null
63
+ ? "上游 CMSIS 只有 x6 / xB / xE 三套启动文件,没有容量档 " + (f103[2] ?? "") + " 这一套:F103 的 4/8/6 档归到 x6 或 xB,C/D/E 档归到 xE。换 STM32F103C8T6 / CBT6 这类型号,"
64
+ : "换一颗内置资源里收录的 F1 型号,";
65
+ return emptyResult(info.root, "unsupported-mcu", "认不出这颗芯片的启动文件:" + (asked || "(没给型号)") + "。" + densityNote + "或改用 HAL 路线(.ioc + CubeMX)。");
66
+ }
67
+ return emptyResult(info.root, "unsupported-mcu", "寄存器版暂时不支持这颗芯片:" + (asked || "(没给型号)") + "。支持 " + Object.keys(CMSIS_FAMILIES).join("/") + " 这 " + String(Object.keys(CMSIS_FAMILIES).length) +
68
+ " 族(芯片事实来自内置资源 chips.json:先跑 stm32_assets verify,或确认这一版内置资源收了该族);" +
69
+ "其它族走 HAL 路线(stm32_project_create route=hal,需要 CubeMX 固件包)。");
56
70
  }
57
71
  const plan = cmsisTemplatePlan(choice);
58
72
  if (plan === null)
@@ -63,9 +77,15 @@ export async function ensureCmsisTemplate(request = {}) {
63
77
  // 用别名解析而不是精确匹配:0.1 建过的 cmsis:F1:startup_stm32f103xb 条目内容完全一样,
64
78
  // 认不出就会白下一遍 14 个文件(还可能在慢网里失败)。
65
79
  const existing = resolveCacheEntry(index, plan.id);
80
+ /** 复用已有目录但只补缺的文件(见下面"清单变长"的说明)。 */
81
+ let reuseRoot = "";
66
82
  if (existing !== null) {
67
83
  const health = checkCacheEntry(existing);
68
- if (health.ok) {
84
+ // 索引只记"上次写了哪些文件",不会自动知道清单变长。插件升级给同一族加了文件
85
+ // (例如补 mpu_armv7.h)之后,旧缓存按索引看是完整的,但编译会 fatal error 缺头文件。
86
+ // 所以缓存命中前还要按当前清单逐个确认文件在盘上,缺的补下。
87
+ const missing = plan.targets.filter((target) => !fs.existsSync(path.join(existing.root, ...target.path.split("/"))));
88
+ if (health.ok && missing.length === 0) {
69
89
  return {
70
90
  ok: true,
71
91
  family: plan.family,
@@ -83,7 +103,13 @@ export async function ensureCmsisTemplate(request = {}) {
83
103
  };
84
104
  }
85
105
  const broken = health.missing.length + health.changed.length;
86
- request.onProgress?.("缓存条目 " + plan.id + " 有 " + String(broken) + " 个文件缺失或大小不对,重新下载。");
106
+ if (health.ok && missing.length > 0) {
107
+ reuseRoot = existing.root;
108
+ request.onProgress?.("缓存条目 " + plan.id + " 比当前清单少 " + String(missing.length) + " 个文件(" + missing.map((target) => target.path).join("、") + "),只补这几个。");
109
+ }
110
+ else {
111
+ request.onProgress?.("缓存条目 " + plan.id + " 有 " + String(broken) + " 个文件缺失或大小不对,重新下载。");
112
+ }
87
113
  }
88
114
  if (request.download === false) {
89
115
  return {
@@ -95,9 +121,13 @@ export async function ensureCmsisTemplate(request = {}) {
95
121
  deviceHeader: choice.deviceHeader,
96
122
  };
97
123
  }
98
- const entryDir = path.join(info.root, plan.dirName);
124
+ const entryDir = reuseRoot === "" ? path.join(info.root, plan.dirName) : reuseRoot;
99
125
  fs.mkdirSync(entryDir, { recursive: true });
100
- request.onProgress?.("下载 " + String(plan.targets.length) + " 个模板文件到 " + entryDir + "(第一次用需要联网,以后复用缓存)。");
126
+ // 复用旧目录时只下缺的:已经有的文件不重复拉,也避免把刚补的文件覆盖成半截。
127
+ const pending = reuseRoot === ""
128
+ ? plan.targets
129
+ : plan.targets.filter((target) => !fs.existsSync(path.join(entryDir, ...target.path.split("/"))));
130
+ request.onProgress?.("下载 " + String(pending.length) + " 个模板文件到 " + entryDir + "(第一次用需要联网,以后复用缓存)。");
101
131
  const options = {
102
132
  onProgress: (outcome, done, total) => {
103
133
  request.onProgress?.("下载 " + String(done) + "/" + String(total) + ":" + outcome.path + (outcome.ok ? " ✓" : " ✗ " + outcome.error));
@@ -108,8 +138,8 @@ export async function ensureCmsisTemplate(request = {}) {
108
138
  if (request.signal !== undefined)
109
139
  options.signal = request.signal;
110
140
  const targets = request.hashes === undefined
111
- ? plan.targets
112
- : plan.targets.map((target) => ({ ...target, sha256: request.hashes?.[target.path] }));
141
+ ? pending
142
+ : pending.map((target) => ({ ...target, sha256: request.hashes?.[target.path] }));
113
143
  const fetched = await fetchAll(targets, entryDir, options);
114
144
  if (fetched.failed > 0) {
115
145
  const failures = fetched.results.filter((item) => !item.ok).slice(0, 3).map((item) => item.path + ":" + item.error);
@@ -141,7 +171,7 @@ export async function ensureCmsisTemplate(request = {}) {
141
171
  ? (cleaned ? "已把半截目录改名后清掉(" + staleDir + ")。" : "半截目录已改名成 " + staleDir + ",但没删掉(可能被占用),可以手工删。")
142
172
  : "半截目录 " + entryDir + " 被占用,改名失败也没删(下次会重下覆盖)。";
143
173
  return {
144
- ...emptyResult(info.root, "download-failed", "模板没下下来(" + String(fetched.failed) + "/" + String(plan.targets.length) + " 个文件失败)。" + cleanupNote + "第一条失败原因:" + (failures[0] ?? "(未知)") + "。"
174
+ ...emptyResult(info.root, "download-failed", "模板没下下来(" + String(fetched.failed) + "/" + String(pending.length) + " 个文件失败)。" + cleanupNote + "第一条失败原因:" + (failures[0] ?? "(未知)") + "。"
145
175
  + (allNotFound ? "这几个文件在上游就是 404:多半是这一代/这一档的模板清单写错了(插件 bug),换型号没用,先走 HAL 路线或报告这个问题。" : "多半是网络/代理问题:换网络重试,或手动把 ST 固件包(STM32Cube_FW_F1_*)装到 CubeMX 的 Repository 里走 HAL 路线。")),
146
176
  family: plan.family,
147
177
  id: plan.id,
@@ -151,7 +181,12 @@ export async function ensureCmsisTemplate(request = {}) {
151
181
  };
152
182
  }
153
183
  // 每个下载的文件登记 sha256(A38):字节数挡不住"同样大小、内容被换掉"。
154
- const files = fetched.results.map((outcome) => {
184
+ // 复用旧目录时,旧文件也要留在索引里(否则下次 checkCacheEntry 会把它们判成"缺失"再下一遍)。
185
+ const noticesName = "THIRD_PARTY_NOTICES.md";
186
+ const keptFiles = reuseRoot === "" || existing === null
187
+ ? []
188
+ : existing.files.filter((item) => item.path !== noticesName && fetched.results.every((outcome) => outcome.path !== item.path));
189
+ const files = keptFiles.concat(fetched.results.map((outcome) => {
155
190
  const item = { path: outcome.path, bytes: outcome.bytes, url: outcome.url };
156
191
  try {
157
192
  item.sha256 = sha256OfFile(path.join(entryDir, ...outcome.path.split("/")));
@@ -160,14 +195,13 @@ export async function ensureCmsisTemplate(request = {}) {
160
195
  // 落盘文件读不出来就别登记哈希,校验时退回只看字节数。
161
196
  }
162
197
  return item;
163
- });
198
+ }));
164
199
  const upstream = new Set();
165
200
  for (const target of plan.targets)
166
201
  for (const url of target.urls)
167
202
  upstream.add(url);
168
203
  // notices 也是条目的一部分,必须进 files[](A24):否则 checkCacheEntry 永远不校验它,
169
204
  // 人手删掉之后索引照样显示"完整"。
170
- const noticesName = "THIRD_PARTY_NOTICES.md";
171
205
  const noticesPath = path.join(entryDir, noticesName);
172
206
  fs.writeFileSync(noticesPath, plan.license, "utf8");
173
207
  const noticesFile = { path: noticesName, bytes: Buffer.byteLength(plan.license, "utf8"), url: "" };
@@ -178,7 +212,7 @@ export async function ensureCmsisTemplate(request = {}) {
178
212
  // 同上。
179
213
  }
180
214
  files.push(noticesFile);
181
- const totalBytes = fetched.bytes + noticesFile.bytes;
215
+ const totalBytes = fetched.bytes + noticesFile.bytes + keptFiles.reduce((sum, item) => sum + item.bytes, 0);
182
216
  const entry = {
183
217
  id: plan.id,
184
218
  kind: "cmsis",
@@ -214,7 +248,8 @@ export async function ensureCmsisTemplate(request = {}) {
214
248
  *
215
249
  * 链接脚本不在这张表里:它是寄存器路线里唯一必须按型号改的模板(ST 那份写死
216
250
  * 64K FLASH / 20K RAM),所以从 HAL 骨架读原文本、改 MEMORY 两行、另存为
217
- * <DeviceId>_FLASH.ld(见 register-linker.ts)。拷贝数不变,工程文件总数还是 7 个。
251
+ * <DeviceId>_FLASH.ld(见 register-linker.ts)。这四个文件数目固定;工程文件总数由
252
+ * templateFiles 计数(CMakeLists + main.c + rtt.c/rtt.h + 这四个 + 链接脚本 + .vscode 三份 = 12)。
218
253
  */
219
254
  const SHARED_TEMPLATE_FILES = ["CMakePresets.json", ".gitignore", "cmake/gcc-arm-none-eabi.cmake", "openocd.cfg"];
220
255
  /** 链接脚本的"源模板"(HAL 骨架里那份,按型号渲染后另存)。 */
@@ -234,8 +269,12 @@ function countFiles(root) {
234
269
  return count;
235
270
  }
236
271
  /**
237
- * 建一个寄存器版工程:模板(CMakeLists + main.c)来自插件,CMSIS/启动文件来自缓存,
238
- * 工具链与链接脚本复用 HAL 骨架里那几份**不含 HAL 内容**的文件。
272
+ * 建一个寄存器版工程:模板(CMakeLists + main.c + 可选 RTT 的 rtt.c/rtt.h)来自插件,
273
+ * CMSIS/启动文件来自缓存,工具链与链接脚本复用 HAL 骨架里那几份**不含 HAL 内容**的文件。
274
+ *
275
+ * RTT 那两个文件是"编进来但默认不启用":main.c 里 rtt_init() 是注释掉的,工具链开了
276
+ * --gc-sections,所以不调用时 rtt.c 的代码与 3 KB 控制块缓冲会被链接器丢掉,不占 RAM/Flash。
277
+ * 这样模板既能被 stm32_rtt 直接支持,又不给不用 RTT 的人增加成本。
239
278
  */
240
279
  export async function createRegisterProject(request) {
241
280
  const startedAt = Date.now();
@@ -288,20 +327,25 @@ export async function createRegisterProject(request) {
288
327
  });
289
328
  if (!template.ok)
290
329
  return fail(template.message);
291
- const choice = resolveStartupChoice({ ...(request.mcu === undefined ? {} : { mcu: request.mcu }), ...(request.family === undefined ? {} : { family: request.family }) });
330
+ const choice = resolveStartupChoice({ ...(request.mcu === undefined ? {} : { mcu: request.mcu }), ...(request.family === undefined ? {} : { family: request.family }) }, request.env);
292
331
  if (choice === null || cmsisTemplatePlan(choice) === null)
293
332
  return fail("内部错误:缓存条目对应的下载清单没了(" + template.family + ")。");
294
333
  const chip = choice.chip;
295
- if (chip === undefined)
334
+ const facts = choice.facts;
335
+ if (chip === undefined && facts === undefined)
296
336
  return fail("内部错误:缓存条目没带回芯片信息(" + template.family + ")。");
297
- // 链接脚本与时钟初始化都按型号现算:寄存器路线没有 CubeMX 替我们算这两样,
298
- // 写死 C8T6 的 64K/20K 与 8 MHz HSI 会让 F103ZE / F100C6 这类芯片要么链不下、要么跑得莫名其妙。
299
- const linker = planRegisterLinker(chip);
300
- const clock = planRegisterClock(chip);
301
337
  const spec = CMSIS_FAMILIES[template.family];
302
338
  if (spec === undefined)
303
339
  return fail("内部错误:这一代没有设备头规格(" + template.family + ")。");
340
+ // 链接脚本按型号现算:寄存器路线没有 CubeMX 替我们算,写死 C8T6 的 64K/20K
341
+ // 会让 F103ZE / F100C6 这类芯片要么链不下、要么把栈顶伸到不存在的 RAM。
342
+ const linker = planRegisterLinker(chip ?? facts);
343
+ // 时钟分两路:F1 有验证过的 PLL 配方;其它族如实留空(复位时钟),不猜 PLL 字段。
344
+ const f1Clock = chip === undefined ? null : planRegisterClock(chip);
345
+ const clock = f1Clock
346
+ ?? planGenericClock({ cpn: mcu, family: template.family, systemC: spec.systemC });
304
347
  const familyDir = spec.deviceDefinePrefix + "xx";
348
+ const led = renderLedFunctions(template.family);
305
349
  const regTpl = registerTemplateDir();
306
350
  const halTpl = templateDir();
307
351
  if (!fs.existsSync(regTpl))
@@ -315,6 +359,10 @@ export async function createRegisterProject(request) {
315
359
  const required = [
316
360
  path.join(regTpl, "CMakeLists.txt"),
317
361
  path.join(regTpl, "Core", "Src", "main.c"),
362
+ // 极简 RTT:CMakeLists 已经 add_executable 了 Core/Src/rtt.c,缺了会 link error;
363
+ // main.c 里也 include 了 rtt.h,缺了连编译都过不了。所以两个都算必需文件。
364
+ path.join(regTpl, "Core", "Src", "rtt.c"),
365
+ path.join(regTpl, "Core", "Inc", "rtt.h"),
318
366
  // 链接脚本模板:按型号渲染的那份是从它改出来的,缺了就只能建 C8T6 尺寸的工程
319
367
  path.join(halTpl, LINKER_TEMPLATE_FILE),
320
368
  ...SHARED_TEMPLATE_FILES.filter((rel) => rel !== ".gitignore").map((rel) => path.join(halTpl, rel)),
@@ -334,15 +382,17 @@ export async function createRegisterProject(request) {
334
382
  // 覆盖前先备份将被覆盖的同名文件;备份失败就一个字节都不写(否则用户的 main.c 就没了)。
335
383
  let backup;
336
384
  try {
337
- backup = backupBeforeOverwrite(targetDir, ["CMakeLists.txt", "Core/Src/main.c", linker.fileName, ...SHARED_TEMPLATE_FILES], "register");
385
+ backup = backupBeforeOverwrite(targetDir, ["CMakeLists.txt", "Core/Src/main.c", "Core/Src/rtt.c", "Core/Inc/rtt.h", linker.fileName, ...SHARED_TEMPLATE_FILES], "register");
338
386
  }
339
387
  catch (error) {
340
388
  return fail("没写任何文件:覆盖前的备份失败(" + String(error.message) + ")。目标目录 " + targetDir + " 未被改动。");
341
389
  }
342
390
  const backupNote = backupWarning(backup);
343
- // 1) 寄存器版 CMakeLists / main.c:替换七个占位符
344
- const chipBanner = (chip.cpn.toUpperCase().startsWith("STM32") ? chip.cpn : "STM32F" + clock.line + "(" + chip.group + " 档)")
345
- + " · " + linker.summary + " · SYSCLK " + String(Math.round(clock.sysclkHz / 1e6)) + " MHz";
391
+ // 1) 寄存器版 CMakeLists / main.c:替换占位符
392
+ const clockText = clock.sysclkHz > 0
393
+ ? "SYSCLK " + String(Math.round(clock.sysclkHz / 1e6)) + " MHz"
394
+ : "复位时钟(未配 PLL)";
395
+ const chipBanner = mcu.toUpperCase() + " · " + linker.summary + " · " + clockText;
346
396
  const replacements = {
347
397
  __PROJECT_NAME__: projectName,
348
398
  __FAMILY_DIR__: familyDir,
@@ -350,7 +400,10 @@ export async function createRegisterProject(request) {
350
400
  __DEVICE_DEFINE__: template.deviceDefine,
351
401
  __LINKER_SCRIPT__: linker.fileName,
352
402
  __MCU_BANNER__: chipBanner,
353
- __CLOCK_INIT__: renderClockInit(clock),
403
+ __CLOCK_INIT__: f1Clock === null ? renderGenericClockInit(clock) : renderClockInit(clock),
404
+ __SYSTEM_C__: spec.systemC,
405
+ __DEVICE_UMBRELLA__: spec.deviceHeaders[0] ?? "",
406
+ __LED_INIT__: led.text,
354
407
  };
355
408
  const fill = (text) => {
356
409
  let out = text;
@@ -368,7 +421,8 @@ export async function createRegisterProject(request) {
368
421
  const targetExistedBefore = fs.existsSync(targetDir);
369
422
  const driversExistedBefore = fs.existsSync(path.join(targetDir, "Drivers"));
370
423
  const createdDirs = [];
371
- let templateFiles = 2;
424
+ // 2 = CMakeLists.txt + Core/Src/main.c;rtt.c/rtt.h 也是模板直接拷的,一并计数(见下面 3)。
425
+ let templateFiles = 4;
372
426
  try {
373
427
  mkdirTracked(path.join(targetDir, "Core", "Src"), createdDirs);
374
428
  mkdirTracked(path.join(targetDir, "Core", "Inc"), createdDirs);
@@ -376,19 +430,30 @@ export async function createRegisterProject(request) {
376
430
  fs.writeFileSync(path.join(targetDir, "CMakeLists.txt"), fill(fs.readFileSync(path.join(regTpl, "CMakeLists.txt"), "utf8")), "utf8");
377
431
  // 2) 寄存器版 main.c:芯片注释 + 按型号生成的 clock_init()
378
432
  fs.writeFileSync(path.join(targetDir, "Core", "Src", "main.c"), fill(fs.readFileSync(path.join(regTpl, "Core", "Src", "main.c"), "utf8")), "utf8");
379
- // 3) 与 HAL 无关的公共文件:工具链 / presets(.gitignore 缺失时跳过,见上面 missingOptional)
433
+ // 3) 极简 RTT(SEGGER 兼容控制块 + 我们的 4+1+8+payload 帧):原样拷,不做占位符替换。
434
+ // CMakeLists 已经编它,main.c 已经 include 它;rtt_init() 是否调用由用户在 USER CODE 2 决定。
435
+ fs.writeFileSync(path.join(targetDir, "Core", "Src", "rtt.c"), fs.readFileSync(path.join(regTpl, "Core", "Src", "rtt.c"), "utf8"), "utf8");
436
+ fs.writeFileSync(path.join(targetDir, "Core", "Inc", "rtt.h"), fs.readFileSync(path.join(regTpl, "Core", "Inc", "rtt.h"), "utf8"), "utf8");
437
+ // 4) 与 HAL 无关的公共文件:工具链 / presets(.gitignore 缺失时跳过,见上面 missingOptional)
380
438
  for (const rel of SHARED_TEMPLATE_FILES) {
381
439
  if (rel === ".gitignore" && missingOptional.includes(rel))
382
440
  continue;
383
441
  const dest = path.join(targetDir, rel);
384
442
  mkdirTracked(path.dirname(dest), createdDirs);
385
- fs.copyFileSync(path.join(halTpl, rel), dest);
443
+ if (rel === "openocd.cfg" && request.interfaceConfig !== undefined && request.interfaceConfig !== "" && request.interfaceConfig !== "interface/cmsis-dap.cfg") {
444
+ // 与 .vscode/launch.json 同口径:实见 ST-Link 却写 cmsis-dap,F5 会撞 transport 不支持。
445
+ const text = fs.readFileSync(path.join(halTpl, rel), "utf8").split("interface/cmsis-dap.cfg").join(request.interfaceConfig);
446
+ fs.writeFileSync(dest, text, "utf8");
447
+ }
448
+ else {
449
+ fs.copyFileSync(path.join(halTpl, rel), dest);
450
+ }
386
451
  templateFiles += 1;
387
452
  }
388
- // 4) 按型号渲染的链接脚本:MEMORY 两行 + 注释两行换成本芯片的真实 Flash/RAM
453
+ // 5) 按型号渲染的链接脚本:MEMORY 两行 + 注释两行换成本芯片的真实 Flash/RAM
389
454
  fs.writeFileSync(path.join(targetDir, linker.fileName), linkerText, "utf8");
390
455
  templateFiles += 1;
391
- // 5) CMSIS:缓存条目里的 Drivers 整棵拷进工程(与 HAL 工程布局一致)
456
+ // 6) CMSIS:缓存条目里的 Drivers 整棵拷进工程(与 HAL 工程布局一致)
392
457
  fs.cpSync(driversSrc, path.join(targetDir, "Drivers"), { recursive: true });
393
458
  }
394
459
  catch (error) {
@@ -405,6 +470,15 @@ export async function createRegisterProject(request) {
405
470
  return fail("写盘失败(已写 " + String(templateFiles) + " 个工程文件):" + String(error.message) + ";路径:" + targetDir + "。" + cleanup, backupNote === null ? [] : [backupNote]);
406
471
  }
407
472
  const driverFiles = countFiles(path.join(targetDir, "Drivers"));
473
+ // .vscode:register 路线不走 scaffold,但用户在 VSCode 里按 F5 烧录/调试靠的就是这三份文件。
474
+ // 放在引擎里而不是工具里,是为了让直接调引擎的调用方(测试、别的工具)也拿到同样的工程。
475
+ const vscode = writeVscodeConfigs({
476
+ targetDir,
477
+ projectName,
478
+ ...(request.interfaceConfig === undefined ? {} : { interfaceConfig: request.interfaceConfig }),
479
+ binDirs: [],
480
+ });
481
+ templateFiles += vscode.files.length;
408
482
  const warnings = [];
409
483
  if (missingOptional.includes(".gitignore")) {
410
484
  warnings.push("插件包里没有 .gitignore(npm 打包会排除它):工程功能不受影响,只是 git 状态会多出 build/ 目录。" +
@@ -413,10 +487,21 @@ export async function createRegisterProject(request) {
413
487
  // 备份清单放第一条:用户看到"覆盖成功"时,第一眼得知道旧文件去哪了。
414
488
  if (backupNote !== null)
415
489
  warnings.push(backupNote);
416
- warnings.push("模板里的 LED 是蓝丸的 PC13;换板子改 Core/Src/main.c 顶部的 LED_PORT / LED_PIN。", "寄存器版没有 .ioc:不需要 CubeMX,也不需要固件包;要换成 HAL 版就用 stm32_project_create route=hal。", "链接脚本已按型号渲染:" + linker.fileName + "(" + linker.summary + "),拷自 templates/scaffold/" + LINKER_TEMPLATE_FILE + "。", "时钟在 main.c 的 clock_init() 里现配:" + clock.summary + "(HSE 不起振就自动退回 HSI/2 ×" + String(clock.hsiMul) + ")。");
417
- // 链接脚本/时钟的告警来自按型号推导本身(RAM 用了保守下限、F100 没有延迟位、HSI 到不了上限…),
418
- // 用户需要知道"为什么是 64 MHz 而不是 72"。
419
- warnings.push(...linker.warnings, ...clock.warnings);
490
+ if (vscode.error !== "")
491
+ warnings.push(vscode.error);
492
+ for (const w of vscode.warnings)
493
+ warnings.push(w);
494
+ warnings.push("模板里的 LED 是蓝丸的 PC13(低电平点亮);换板子改 Core/Src/main.c 的 LED_PIN 与 led_init()。", "寄存器版没有 .ioc:不需要 CubeMX,也不需要固件包;要换成 HAL 版就用 stm32_project_create route=hal。", "链接脚本已按型号渲染:" + linker.fileName + "(" + linker.summary + "),拷自 templates/scaffold/" + LINKER_TEMPLATE_FILE + "。", f1Clock === null
495
+ ? "时钟:" + clock.summary + "(没有替你配 PLL,理由见 main.c 的 clock_init() 注释)。"
496
+ : "时钟在 main.c 的 clock_init() 里现配:" + clock.summary + "(HSE 不起振就自动退回 HSI/2 ×" + String(f1Clock.hsiMul) + ")。");
497
+ // 链接脚本/时钟/LED 的告警来自按型号推导本身(RAM 用了保守下限、HSI 到不了上限、这一族没有验证过的 GPIO 写法…),
498
+ // 用户需要知道"为什么是 64 MHz 而不是 72"、"为什么灯不闪"。
499
+ warnings.push(...linker.warnings, ...clock.warnings, ...led.warnings);
500
+ // RTT 是"编进来但默认不启用",用户得知道怎么开、以及它会吃多少 RAM——
501
+ // 否则 dump 时只会看到"控制块是空的",得回头翻模板。
502
+ warnings.push("RTT 已随工程就位(Core/Src/rtt.c + Core/Inc/rtt.h,SEGGER 兼容控制块、通道 0 按 4+1+8+payload 写帧)," +
503
+ "但默认没启用:取消 main.c 里 USER CODE BEGIN 2 的 rtt_init() 注释才会链进来(否则 --gc-sections 会丢掉它)。" +
504
+ "启用后 3 个通道 × 1 KB = 3 KB RAM;dump 前先用 nm 拿 _SEGGER_RTT 地址再 stm32_rtt action=start addr=…。");
420
505
  if (template.cacheHit)
421
506
  warnings.push("这次用的是缓存模板(" + template.entryDir + "),没有联网。");
422
507
  else
@@ -7,11 +7,13 @@
7
7
  * 收尾用 resume 而不是 reset run:reset run 会把芯片复位,固件里的计数/状态全部从头开始,
8
8
  * "只读一眼"就变成了副作用(实测 led_prg 的计数器被清零)。halt 只是暂停,resume 原样继续跑。
9
9
  */
10
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
10
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
11
  import { join, resolve } from "node:path";
12
12
  import { resolveSearchConfig } from "../data/search-roots.js";
13
13
  import { STATE_DIR } from "./generate.js";
14
- import { defaultConfigs, findProjectConfig, quoteForDisplay, toOpenOcdPath } from "./flash.js";
14
+ import { chooseOpenocdTarget, readProjectFamily } from "../data/family.js";
15
+ import { findProjectConfig, quoteForDisplay, toOpenOcdPath } from "./flash.js";
16
+ import { liveProbeChoice, openocdTransportArgs } from "./doctor.js";
15
17
  import { resolveToolIn } from "./probe.js";
16
18
  import { runStreaming } from "./subprocess-runner.js";
17
19
  /** "4001100c" / "0x4001100C" → "0x4001100C";非法返回 null。 */
@@ -78,6 +80,7 @@ export async function runRegsRead(subprocess, request) {
78
80
  const errors = [];
79
81
  const notes = [];
80
82
  const base = {
83
+ reusedSession: false,
81
84
  projectDir,
82
85
  configFile: "",
83
86
  command: "",
@@ -118,9 +121,23 @@ export async function runRegsRead(subprocess, request) {
118
121
  configs.push(toOpenOcdPath(projectConfig));
119
122
  }
120
123
  else {
121
- const fallback = defaultConfigs();
122
- configs.push(fallback.interfaceConfig, fallback.targetConfig);
124
+ // 按 .ioc 的 Mcu.Family 选 target:换族之后不能再用 F1 的脚本硬连。
125
+ const family = readProjectFamily(projectDir);
126
+ const choice = chooseOpenocdTarget(family);
127
+ if (choice.error !== "") {
128
+ return {
129
+ ...base,
130
+ ok: false,
131
+ errors: [choice.error],
132
+ message: "没读:" + (family === null ? "认不出芯片族" : "本机 openocd 没有 " + family.id + " 的 target 脚本"),
133
+ };
134
+ }
135
+ const live = await liveProbeChoice(subprocess, request.signal);
136
+ const interfaceConfig = live.swdProbes.length > 0 ? live.cfg : "interface/cmsis-dap.cfg";
137
+ configs.push(interfaceConfig, choice.targetConfig);
123
138
  notes.push("工程里没有 openocd 配置文件,回退到 " + configs.join(" + "));
139
+ if (choice.note !== "")
140
+ notes.push(choice.note);
124
141
  }
125
142
  const script = buildRegsScript(addresses);
126
143
  const tmpDir = join(projectDir, STATE_DIR, "tmp");
@@ -142,8 +159,28 @@ export async function runRegsRead(subprocess, request) {
142
159
  };
143
160
  }
144
161
  const args = [openOcd];
145
- for (const cfg of configs)
162
+ for (let i = 0; i < configs.length; i += 1) {
163
+ const cfg = configs[i] ?? "";
146
164
  args.push("-f", cfg);
165
+ if (i !== 0)
166
+ continue;
167
+ // J-Link 要在 interface 与 target 之间补 transport:它的 interface 配置不选 transport,openocd 默认 jtag。
168
+ const transport = openocdTransportArgs(cfg);
169
+ if (transport.length > 0) {
170
+ args.push(...transport);
171
+ }
172
+ else if (projectConfig !== null) {
173
+ let projectText = "";
174
+ try {
175
+ projectText = readFileSync(projectConfig, "utf8");
176
+ }
177
+ catch {
178
+ projectText = "";
179
+ }
180
+ if (/interface\/jlink\.cfg/u.test(projectText))
181
+ args.push("-c", "transport select swd");
182
+ }
183
+ }
147
184
  if (request.adapterSpeed !== undefined)
148
185
  args.push("-c", "adapter speed " + String(request.adapterSpeed));
149
186
  args.push("-c", "source " + toOpenOcdPath(scriptPath));
@@ -192,6 +229,7 @@ export async function runRegsRead(subprocess, request) {
192
229
  : "读寄存器失败:" + (errors[0] ?? "未知原因");
193
230
  return {
194
231
  ok,
232
+ reusedSession: false,
195
233
  projectDir,
196
234
  configFile: configs.join(" "),
197
235
  command,
@@ -206,6 +244,3 @@ export async function runRegsRead(subprocess, request) {
206
244
  notes,
207
245
  };
208
246
  }
209
- export function describeSample(sample) {
210
- return sample.address + " = " + (sample.ok ? sample.value : "(读不到)");
211
- }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * rm-facts 自动抽取与两道机检(替代人核)。
3
+ *
4
+ * 流程:主题规格(id/statement/page/anchors/svd)+ PDF 页面文本 + 各线 SVD 结构
5
+ * → 逐条核验 → 只把全过的条目写进 rm-facts(带逐字 quote 与实证页码),拒的带原因。
6
+ * 机检①「锚点/引文」:anchors 全部要在 page±3 的归一化文本里逐字出现,
7
+ * evidence.quote 直接从命中页按锚点窗口截取(不是人重写),RM 改版/页码漂移即失败——
8
+ * 这专门钉死 §4 那类推断错:旧中文 Rev 1 时代写的「SYSCLK 第 4 个上升沿锁存」
9
+ * 在 EN Rev 6 全文找不到锚点 → 自动拒收(RM0490 实际写的是 latched after a reset
10
+ * + BOOT0 pin sampling is done on NRST rising edge)。
11
+ * 机检②「SVD 交叉」:spec.svd 要求的 {reg, field, bitOffset} 必须在该线 SVD 里存在
12
+ * (字段名大小写不敏感——C071 是小写 nBOOT_SEL,其余线大写),枚举值命中才适用;
13
+ * 不适用的线从 appliesTo 剔除。声明只给结构不给的组合规则,这里只做一致性核验。
14
+ */
15
+ /** 归一化:折叠空白 + 小写(锚点与引文回查的公共口径)。 */
16
+ export function normQuote(text) {
17
+ return text.replace(/\s+/gu, " ").trim().toLowerCase();
18
+ }
19
+ /**
20
+ * 页文本核验口径:只折叠空白、保留原大小写(引文要能读回原文写法)。
21
+ * 匹配在它的 toLowerCase 副本上做;两者对 ASCII 等长,稀有 Unicode(如 İ)
22
+ * 理论上会让下标偏移,但命中与否用的都是同一份副本,偏移只影响引文截取边界,
23
+ * 不会把「没锚点」判成「有锚点」。
24
+ */
25
+ export function normalizedPage(text) {
26
+ return text.replace(/\s+/gu, " ").trim();
27
+ }
28
+ function findNormalized(hayLower, needle) {
29
+ return hayLower.indexOf(normQuote(needle));
30
+ }
31
+ /**
32
+ * 逐主题核验。pages 只需覆盖 spec 里各 page±3(CLI 从 PDF 抽好喂进来)。
33
+ */
34
+ export function extractRmFacts(spec, pages, svdByLine) {
35
+ const items = [];
36
+ const rejected = [];
37
+ const lineNotes = spec.lines.map((l) => ({ line: l, accepted: 0, dropped: [] }));
38
+ for (const topic of spec.topics) {
39
+ if (!Array.isArray(topic.anchors) || topic.anchors.length === 0) {
40
+ rejected.push({ id: topic.id, reason: "规格没给锚点:无语料回查等于没核验" });
41
+ continue;
42
+ }
43
+ const window = pages.filter((p) => Math.abs(p.page - topic.page) <= 3);
44
+ let hitHay = "";
45
+ let hitIdx = -1;
46
+ let anchorIdx = -1;
47
+ for (const p of window) {
48
+ const hay = normalizedPage(p.text);
49
+ const lower = hay.toLowerCase();
50
+ const idx = findNormalized(lower, topic.anchors[0] ?? "");
51
+ if (idx < 0)
52
+ continue;
53
+ const rest = topic.anchors.slice(1).every((a) => findNormalized(lower, a) >= 0);
54
+ if (!rest)
55
+ continue;
56
+ hitHay = hay;
57
+ anchorIdx = idx;
58
+ hitIdx = p.page;
59
+ break;
60
+ }
61
+ if (hitIdx < 0) {
62
+ rejected.push({ id: topic.id, reason: "锚点在 p" + String(topic.page) + "±3 的逐字回查没过(改版/换族/推断错的结论都会在这里被拒):" + (topic.anchors[0] ?? "").slice(0, 48) });
63
+ continue;
64
+ }
65
+ const hay = hitHay;
66
+ const lower = hay.toLowerCase();
67
+ let quote;
68
+ if (topic.anchorEnd) {
69
+ const endIdx = findNormalized(lower.slice(anchorIdx), topic.anchorEnd);
70
+ if (endIdx < 0) {
71
+ rejected.push({ id: topic.id, reason: "引文终止锚点不在同一页:" + topic.anchorEnd.slice(0, 48) });
72
+ continue;
73
+ }
74
+ quote = hay.slice(anchorIdx, anchorIdx + endIdx + topic.anchorEnd.length);
75
+ }
76
+ else {
77
+ quote = hay.slice(anchorIdx, anchorIdx + 700);
78
+ }
79
+ // 表格逐行回查:声明的行必须都在这页里逐字出现
80
+ if (topic.rows !== undefined && topic.rows.length > 0) {
81
+ const missRows = topic.rows.filter((row) => findNormalized(lower, row.join(" ")) < 0);
82
+ if (missRows.length > 0) {
83
+ rejected.push({ id: topic.id, reason: "表格有 " + String(missRows.length) + " 行在 p" + String(hitIdx) + " 逐字找不到(首行:" + (missRows[0] ?? []).join(" ").slice(0, 40) + ")" });
84
+ continue;
85
+ }
86
+ }
87
+ // 机检②:逐线 SVD 交叉
88
+ const applies = [];
89
+ for (const line of spec.lines) {
90
+ const st = svdByLine[line];
91
+ if (st === undefined) {
92
+ lineNotes.find((x) => x.line === line)?.dropped.push(topic.id + "(该线 SVD 没取到)");
93
+ continue;
94
+ }
95
+ const miss = [];
96
+ for (const want of topic.svd ?? []) {
97
+ const reg = st[want.reg];
98
+ const f = reg?.fields.find((y) => y.name.toLowerCase() === want.field.toLowerCase());
99
+ if (f === undefined) {
100
+ miss.push(want.reg + "." + want.field);
101
+ continue;
102
+ }
103
+ if (f.bitOffset !== want.bitOffset) {
104
+ miss.push(want.reg + "." + want.field + " 位不对(" + String(f.bitOffset) + "≠" + String(want.bitOffset) + ")");
105
+ continue;
106
+ }
107
+ for (const v of want.enums ?? []) {
108
+ if (!f.enums.some((e) => e.value.toLowerCase() === v.toLowerCase()))
109
+ miss.push(want.reg + "." + want.field + " 缺枚举 " + v);
110
+ }
111
+ }
112
+ if (miss.length === 0)
113
+ applies.push(line);
114
+ else
115
+ lineNotes.find((x) => x.line === line)?.dropped.push(topic.id + "(" + miss.join("/") + ")");
116
+ }
117
+ if (applies.length === 0 && (topic.svd?.length ?? 0) > 0) {
118
+ rejected.push({ id: topic.id, reason: "没有任何一条线通过 SVD 交叉" });
119
+ continue;
120
+ }
121
+ if (applies.length === 0)
122
+ applies.push(...spec.lines); // 无 svd 要求的纯文本条目:线适用性只由锚点回查决定
123
+ items.push({
124
+ id: topic.id,
125
+ statement: topic.statement,
126
+ source: { page: hitIdx },
127
+ evidence: { quote, normalized: true },
128
+ appliesTo: applies,
129
+ ...(topic.rows === undefined ? {} : { table: topic.rows.map((row) => row.reduce((acc, cell, i) => { acc["c" + String(i)] = cell; return acc; }, {})) }),
130
+ });
131
+ for (const l of applies) {
132
+ const note = lineNotes.find((x) => x.line === l);
133
+ if (note !== undefined)
134
+ note.accepted += 1;
135
+ }
136
+ }
137
+ return { ok: rejected.length === 0 && items.length > 0, items, rejected, lineNotes };
138
+ }
139
+ /** 把核验结果组装成 build-facts 认识的 rm-facts 文档(doc.lines = 全部条目 appliesTo 交集的并集口径见 notes)。 */
140
+ export function assembleRmFacts(doc, items) {
141
+ const union = [...new Set(items.flatMap((i) => i.appliesTo))];
142
+ const outDoc = { ...doc, lines: union };
143
+ return { doc: outDoc, items: items.map((i) => ({ id: i.id, statement: i.statement, source: i.source, evidence: i.evidence, appliesTo: i.appliesTo, ...(i.table === undefined ? {} : { table: i.table }) })) };
144
+ }