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
@@ -14,15 +14,41 @@ import { createHash } from "node:crypto";
14
14
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
15
15
  import { basename, isAbsolute, join, resolve, sep } from "node:path";
16
16
  import { findIocFile, STATE_DIR } from "./generate.js";
17
- import { parseIocEntries, summarizeIoc } from "./ioc.js";
17
+ import { decodeIocKey, iocLogicalLines, parseIocEntries, summarizeIoc } from "./ioc.js";
18
+ import { CORE_EXCEPTIONS, checkIocRules, extiIrqName } from "./ioc-rules.js";
19
+ import { findPeripheralPreset, peripheralPresetNames, pinDbName } from "../data/ioc-presets.js";
20
+ import { derivePeripheralPreset } from "../data/db-presets.js";
21
+ import { auditIocKeys, iocSchemaCoverage, matchIocKey, renderIocKey } from "../data/ioc-schema.js";
22
+ import { hasIpInstance, instanceFamilyName, instancesWithPins, locateCubemxDb, readIpParameterNames, readMcuFacts, resolveDbPinName, } from "./cubemx-db.js";
23
+ import { loadSvdForLine, svdLineForChip } from "../data/svd.js";
24
+ import { resolveSearchConfig } from "../data/search-roots.js";
18
25
  import { emptyClockPlan, formatHz, planClock } from "./clock-plan.js";
26
+ import { clockFactsFromDb, readClockDbFacts } from "../data/clock-db.js";
27
+ import { planClockPllmn } from "./clock-pllmn.js";
28
+ import { planClockDirect } from "./clock-direct.js";
29
+ import { followDerivedClocks } from "./clock-derived.js";
19
30
  import { isKnownPin } from "../data/chips.js";
31
+ import { capabilityGap, familyProfileOf, isF1 } from "../data/family.js";
20
32
  export function sha256Hex(text) {
21
33
  return createHash("sha256").update(text, "utf8").digest("hex");
22
34
  }
23
- /** 写回时的转义:CubeMX 在值里把 ":" 和 "\\" 写成 "\\" 前缀。 */
35
+ /**
36
+ * 写回时的转义。值里要转义 "\\"、":"(NVIC 的 true\:0…)和 "#"
37
+ * (ADC1.IPParameters=Rank-0\#ChannelRegularConversion 是 CubeMX 自己的写法)。
38
+ */
24
39
  export function encodeIocValue(value) {
25
- return value.replace(/\\/gu, "\\\\").replace(/:/gu, "\\:");
40
+ const escaped = value.replace(/\\/gu, "\\\\").replace(/:/gu, "\\:").replace(/#/gu, "\\#");
41
+ // java.util.Properties#store 对**值开头的空格**也转义(`case ' ': if (x == 0 || escapeSpace) outBuffer.append('\\')`):
42
+ // 不转义的话读回来前导空白会被 properties 语法吃掉(GPIO_Label=" led" 就变成 "led")。
43
+ return escaped.replace(/^ +/u, (run) => run.replace(/ /gu, "\\ "));
44
+ }
45
+ /**
46
+ * 键名里的转义。键里出现空格/括号时**必须**转义:.ioc 走 java properties 语义,
47
+ * 未转义的空格会把键截断,于是 "TIM2.Channel-PWM Generation1 CH1" 变成
48
+ * "TIM2.Channel-PWM" —— CubeMX 读不到,通道配置静默失效。
49
+ */
50
+ export function encodeIocKey(key) {
51
+ return key.replace(/\\/gu, "\\\\").replace(/ /gu, "\\ ").replace(/#/gu, "\\#").replace(/:/gu, "\\:");
26
52
  }
27
53
  function splitLines(text) {
28
54
  return text.split(/\r?\n/u);
@@ -30,28 +56,107 @@ function splitLines(text) {
30
56
  function dominantEol(text) {
31
57
  return text.includes("\r\n") ? "\r\n" : "\n";
32
58
  }
59
+ /**
60
+ * .ioc 的键排序:**纯字典序**,与 CubeMX 落盘完全一致。
61
+ *
62
+ * 依据(jar.md「落盘」一节):CubeMX 走 mxsystem.ProjectFactory#saveConfigFile →
63
+ * db.DbConfProperties#store → com.st.components.util.SortedProperties(就是 java.util.Properties),
64
+ * 而 java.util.Properties 写盘前对键做 Collections.sort → String.compareTo,
65
+ * 也就是按 **UTF-16 码元**逐字符比。JS 的 `<` 比较同样是码元序,所以直接比字符串即可。
66
+ * 语料 504 份板级 .ioc 实测:6.x 的 266 份里 261 份(98.1%)是这种序。
67
+ *
68
+ * 以前这里按"数字段比数值"排(Mcu.Pin2 在 Mcu.Pin10 之前),是我们自己的审美:
69
+ * 键数一过 10 就和 CubeMX 的写法错位,用户拿我们的 .ioc 跟 CubeMX 另存的 diff 时满屏挪行。
70
+ */
71
+ export function compareIocKeys(left, right) {
72
+ return left < right ? -1 : left > right ? 1 : 0;
73
+ }
74
+ /** 一行对应的(解码后的)键;注释行、空行、没有 "=" 的垃圾行返回空串。 */
75
+ function lineKey(line) {
76
+ const trimmed = line.trim();
77
+ if (trimmed === "" || trimmed.startsWith("#"))
78
+ return "";
79
+ const eq = trimmed.indexOf("=");
80
+ if (eq <= 0)
81
+ return "";
82
+ return decodeIocKey(trimmed.slice(0, eq).trim());
83
+ }
84
+ export function inspectIocText(text) {
85
+ const counts = new Map();
86
+ const malformedLines = [];
87
+ const multiLineKeys = new Set();
88
+ for (const item of iocLogicalLines(text)) {
89
+ const trimmed = item.line.trim();
90
+ if (trimmed === "" || trimmed.startsWith("#"))
91
+ continue;
92
+ const eq = trimmed.indexOf("=");
93
+ if (eq <= 0) {
94
+ malformedLines.push(item.startIndex + 1);
95
+ continue;
96
+ }
97
+ const key = decodeIocKey(trimmed.slice(0, eq).trim());
98
+ counts.set(key, (counts.get(key) ?? 0) + 1);
99
+ if (item.lineCount > 1)
100
+ multiLineKeys.add(key);
101
+ }
102
+ const duplicates = new Map();
103
+ for (const [key, count] of counts)
104
+ if (count > 1)
105
+ duplicates.set(key, count);
106
+ return {
107
+ duplicates,
108
+ malformedLines,
109
+ multiLineKeys,
110
+ mixedEol: text.includes("\r\n") && text.replace(/\r\n/gu, "").includes("\n"),
111
+ finalNewline: /(\r?\n)$/u.test(text),
112
+ };
113
+ }
114
+ /**
115
+ * 读 .ioc:只接受 UTF-8(与 CubeMX 一致),别的编码直接报错。
116
+ *
117
+ * 为什么不做「猜编码」:CubeMX 写的是 UTF-8;文件被中文编辑器另存成 GBK 时,
118
+ * 按 UTF-8 解码会得到一堆替换字符,写回去就把整份工程改坏了。
119
+ * 这里用 fatal 解码器,宁可拒绝也不静默乱码。
120
+ * BOM 用 ignoreBOM 保留在字符串里,写回时原样往返。
121
+ */
122
+ export function readIocText(path) {
123
+ const raw = readFileSync(path);
124
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
125
+ try {
126
+ return decoder.decode(raw);
127
+ }
128
+ catch {
129
+ throw new Error("不是合法的 UTF-8:" + path +
130
+ "(多半是中文编辑器另存成了 GBK/ANSI)。请用 VS Code 以 UTF-8 另存后再改;" +
131
+ "插件不会替你猜编码,以免把整份 .ioc 写坏");
132
+ }
133
+ }
33
134
  function buildLineTable(text) {
34
135
  const lines = splitLines(text);
35
136
  const index = new Map();
36
137
  lines.forEach((line, position) => {
37
- const trimmed = line.trim();
38
- if (trimmed === "" || trimmed.startsWith("#"))
39
- return;
40
- const eq = trimmed.indexOf("=");
41
- if (eq <= 0)
138
+ const key = lineKey(line);
139
+ if (key === "")
42
140
  return;
43
- const key = trimmed.slice(0, eq).trim();
44
141
  const list = index.get(key) ?? [];
45
142
  list.push(position);
46
143
  index.set(key, list);
47
144
  });
48
- return { lines, index };
145
+ return { lines, index, changedKeys: 0 };
49
146
  }
50
- /** 把变更应用到 .ioc 文本上:已有键原地改、重复键只留第一条、新增键追加到末尾。 */
147
+ /**
148
+ * 把变更应用到 .ioc 文本上:已有键原地改、重复键只留第一条、新增键按 key 排序插入。
149
+ *
150
+ * 为什么是"插入"而不是"追加":CubeMX 自己写盘时整个文件按 key 排序
151
+ * (CAD.* → File.Version → GPIO.* → KeepUserPlacement → Mcu.* → MxCube.Version →
152
+ * MxDb.Version → NVIC.* → 引脚键 → PinOutPanel.* → ProjectManager.* → RCC.* → SH.* →
153
+ * VP_* → board)。以前新键一律追加到末尾,结果落在 Mcu.IPNb / Mcu.PinsNb 之后,
154
+ * 谁看 diff 都对不上 CubeMX 的格式,也让人误以为键没写进去。
155
+ */
51
156
  export function renderIocText(text, changes) {
52
157
  const table = buildLineTable(text);
53
158
  const removed = new Set();
54
- const appended = [];
159
+ const added = [];
55
160
  for (const change of changes) {
56
161
  const positions = table.index.get(change.key) ?? [];
57
162
  if (change.after === null) {
@@ -59,27 +164,48 @@ export function renderIocText(text, changes) {
59
164
  removed.add(position);
60
165
  continue;
61
166
  }
62
- const line = change.key + "=" + encodeIocValue(change.after);
167
+ const line = encodeIocKey(change.key) + "=" + encodeIocValue(change.after);
63
168
  if (positions.length === 0) {
64
- appended.push(line);
169
+ added.push(change);
65
170
  continue;
66
171
  }
67
172
  const first = positions[0];
68
173
  table.lines[first] = line;
174
+ table.changedKeys += 1;
69
175
  for (const position of positions.slice(1))
70
176
  removed.add(position);
71
177
  }
178
+ if (added.length === 0 && removed.size === 0 && table.changedKeys === 0)
179
+ return text;
72
180
  const eol = dominantEol(text);
73
181
  const out = [];
74
182
  table.lines.forEach((line, position) => {
75
183
  if (!removed.has(position))
76
- out.push(line);
184
+ out.push({ key: lineKey(line), line });
77
185
  });
78
- // 去掉末尾的空行,再把新增键接上,最后统一补一个换行。
79
- while (out.length > 0 && out[out.length - 1].trim() === "")
80
- out.pop();
81
- out.push(...appended);
82
- return out.join(eol) + eol;
186
+ // 新增键按 key 排序插到对应位置;末尾的空行是原文件的(可能是"文件末尾有换行"的表现),
187
+ // 不能吃掉,新键要插在它们**之前**。
188
+ let tail = out.length;
189
+ while (tail > 0 && out[tail - 1].line.trim() === "")
190
+ tail -= 1;
191
+ added.sort((left, right) => compareIocKeys(left.key, right.key));
192
+ for (const change of added) {
193
+ const item = { key: change.key, line: encodeIocKey(change.key) + "=" + encodeIocValue(change.after) };
194
+ let at = -1;
195
+ for (let index = 0; index < tail; index += 1) {
196
+ const key = out[index].key;
197
+ if (key !== "" && compareIocKeys(key, change.key) > 0) {
198
+ at = index;
199
+ break;
200
+ }
201
+ }
202
+ if (at < 0)
203
+ at = tail;
204
+ out.splice(at, 0, item);
205
+ tail += 1;
206
+ }
207
+ // 按行 split 后,文件末尾有换行会多出一个空串,join 回去正好还原原文,所以不再补 eol。
208
+ return out.map((item) => item.line).join(eol);
83
209
  }
84
210
  export function compareEntries(before, after) {
85
211
  const changes = [];
@@ -91,7 +217,7 @@ export function compareEntries(before, after) {
91
217
  continue;
92
218
  changes.push({ key, before: old, after: next });
93
219
  }
94
- return changes.sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0));
220
+ return changes.sort((left, right) => compareIocKeys(left.key, right.key));
95
221
  }
96
222
  const LABEL_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
97
223
  const PULL_VALUES = {
@@ -104,17 +230,97 @@ const SPEED_VALUES = {
104
230
  medium: "GPIO_SPEED_FREQ_MEDIUM",
105
231
  high: "GPIO_SPEED_FREQ_HIGH",
106
232
  };
233
+ /** EXTI 触发边沿 → <pin>.GPIO_ModeDefaultEXTI 的值(语料 504 份里只有这三个 token)。 */
234
+ const EXTI_MODES = {
235
+ rising: "GPIO_MODE_IT_RISING",
236
+ falling: "GPIO_MODE_IT_FALLING",
237
+ both: "GPIO_MODE_IT_RISING_FALLING",
238
+ };
239
+ /**
240
+ * 引脚属性键写进 <pin>.GPIOParameters 的顺序。
241
+ *
242
+ * 这不是"我们觉得好看"的顺序,而是 CubeMX 6.15.0 回写时自己用的顺序——它把 GPIOParameters 当
243
+ * 集合重新序列化,**无视我们写进去的排列**(所以排列只影响 diff 噪声,不影响功能)。
244
+ *
245
+ * 证据两条:
246
+ * 1) 真机探针(2026-11-02,demo.ioc 副本 load+save):写 `GPIO_Label,GPIO_PuPd,GPIO_ModeDefaultEXTI`
247
+ * 回写成 `GPIO_PuPd,GPIO_Label,GPIO_ModeDefaultEXTI`;写 `GPIO_Label,PinState,GPIO_Mode`
248
+ * 回写成 `PinState,GPIO_Label,GPIO_Mode`。
249
+ * 2) 语料 266 份 MxCube.Version=6.x 板级 .ioc 的 11808 条 GPIOParameters 两两先后统计(0 反例):
250
+ * GPIO_Speed < GPIO_PuPd(376/0)、GPIO_Speed < PinState(61/0)、PinState < GPIO_PuPd(54/0)、
251
+ * GPIO_PuPd < GPIO_Label(694/0)、GPIO_Label < GPIO_Mode(268/0)、
252
+ * GPIO_Label < GPIO_ModeDefaultEXTI(97/0)、GPIO_ModeDefaultEXTI < GPIO_PuPd→反(85/0)。
253
+ * 合成全序:Speed → PinState → PuPd → Label → ModeDefault* → GPIO_Mode。
254
+ */
255
+ const PIN_ATTRIBUTE_ORDER = [
256
+ "GPIO_Speed", "PinState", "GPIO_PuPd", "GPIO_Label",
257
+ "GPIO_ModeDefaultEXTI", "GPIO_ModeDefaultPP", "GPIO_ModeDefaultOutputPP", "GPIO_Mode",
258
+ ];
259
+ /** 引脚号 = EXTI 线号(PA5 → 5)。非 GPIO 名返回 null。 */
260
+ function extiLineOf(pin) {
261
+ const match = /^P[A-Z]([0-9]{1,2})(?:-|$)/u.exec(pin.trim().toUpperCase());
262
+ if (match === null)
263
+ return null;
264
+ const line = Number.parseInt(match[1], 10);
265
+ return line >= 0 && line <= 15 ? line : null;
266
+ }
267
+ /**
268
+ * NVIC.<name>_IRQn 的 9 段值:Enable:Preempt:Sub:Configurable:System:IrqHandlerGenerated:…
269
+ * 实测依据(6.15.0):给非 DMA 外设打开中断后 CubeMX 自己写的就是 true:0:0:false:false:true:true:true:true。
270
+ * DMA 通道是另一串(true:0:0:false:false:true:false:true:true),由 DMA 那段逻辑单独写。
271
+ */
272
+ export function nvicIrqValue(preempt, sub) {
273
+ return ["true", String(preempt), String(sub), "false", "false", "true", "true", "true", "true"].join(":");
274
+ }
275
+ /** RCC_ADCPCLK2_DIV2/4/6/8 → 2/4/6/8;认不出来返回 null(那就别动 ADCFreqValue)。 */
276
+ function adcPrescalerDiv(token) {
277
+ const match = /^RCC_ADCPCLK2_DIV([2468])$/u.exec(token.trim());
278
+ return match === null ? null : Number.parseInt(match[1], 10);
279
+ }
280
+ /**
281
+ * DMA 请求参数的白名单顺序(CubeMX 按这个顺序把参数名写进
282
+ * `Dma.<IP>.<n>.RequestParameters`)。F1 的 DMA 没有 FIFO,所以列到 Priority 为止;
283
+ * 后面几个是 F4/H7 才有的字段,留在这里是为了让我们写到它们时顺序仍然对。
284
+ * 实测依据:richhal.ioc:30(F1,8 个字段)与语料里 F4 的 9 字段版本(多一个 FIFOMode)。
285
+ */
286
+ export const DMA_PARAM_ORDER = [
287
+ "Instance", "Direction", "PeriphInc", "MemInc", "PeriphDataAlignment", "MemDataAlignment",
288
+ "Mode", "Priority", "FIFOMode", "SignalID", "Polarity", "RequestNumber",
289
+ ];
290
+ /**
291
+ * 解析 `Dma.<IP>.<n>.<参数>` 的分组(`Dma.{ip}.{n}.{name}` 这条 spec 的三段占位符)。
292
+ * 不走手写正则:键名的形状全部由 src/data/ioc-schema.ts 的真值表定义,这里只取它的参数。
293
+ * 返回 null 表示不是 DMA 请求参数键(含 Dma.RequestParameters 本身)。返回的 name 就是参数名。
294
+ */
295
+ function dmaGroupOf(key) {
296
+ const hit = matchIocKey(key);
297
+ if (hit === null || hit.spec.id !== "dma.request_group")
298
+ return null;
299
+ const ip = hit.params.ip ?? "";
300
+ const n = hit.params.n ?? "";
301
+ const name = hit.params.name ?? "";
302
+ if (ip === "" || n === "" || name === "")
303
+ return null;
304
+ return { ip, n, name };
305
+ }
306
+ /** 这个键算不算 DMA 家族的键(`Dma.<IP>.<n>…` 或 `Dma.Request<i>` 等)。 */
307
+ function isDmaKey(key) {
308
+ const hit = matchIocKey(key);
309
+ return hit !== null && hit.spec.id.startsWith("dma.");
310
+ }
107
311
  function readPinTable(entries, errors, warnings) {
108
- const count = Number.parseInt(entries.get("Mcu.PinsNb") ?? "0", 10);
312
+ const nbKey = renderIocKey("mcu.pins_nb");
313
+ const count = Number.parseInt(entries.get(nbKey) ?? "0", 10);
109
314
  if (!Number.isFinite(count) || count < 0) {
110
- errors.push("Mcu.PinsNb 不是合法数字(" + (entries.get("Mcu.PinsNb") ?? "<缺失>") + ")");
315
+ errors.push(nbKey + " 不是合法数字(" + (entries.get(nbKey) ?? "<缺失>") + ")");
111
316
  return { order: [], entries, errors, warnings };
112
317
  }
113
318
  const order = [];
114
319
  for (let position = 0; position < count; position += 1) {
115
- const pin = entries.get("Mcu.Pin" + String(position));
320
+ const indexKey = renderIocKey("mcu.pin_index", { index: position });
321
+ const pin = entries.get(indexKey);
116
322
  if (pin === undefined) {
117
- errors.push("Mcu.Pin" + String(position) + " 缺失(Mcu.PinsNb=" + String(count) + " 但列表不连续)");
323
+ errors.push(indexKey + " 缺失(" + nbKey + "=" + String(count) + " 但列表不连续)");
118
324
  continue;
119
325
  }
120
326
  order.push(pin);
@@ -131,16 +337,128 @@ function samePinOrder(left, right) {
131
337
  }
132
338
  return true;
133
339
  }
340
+ /**
341
+ * Mcu.Pin<i> 的排列规则(2026-11-02 真机确认,三次探针一致):
342
+ * **按 db 里 <Pin Position> 升序**,虚拟脚(VP_*)永远在最后。
343
+ *
344
+ * 证据:demo.ioc 原序 PC13-TAMPER-RTC(2), PC14-OSC32_IN(3), PC15-OSC32_OUT(4), PD0-OSC_IN(5),
345
+ * PD1-OSC_OUT(6), PA13, PA14, VP_SYS_VS_Systick 正是 Position 序;我们追加 PA5/PA6/PA7/PA0 之后
346
+ * CubeMX 回写成 PA0-WKUP(10), PA5(15), PA6(16), PA7(17)…PA13, PA14, VP_* —— 我们尾部追加的顺序被它重排。
347
+ * db 不可用(没装 CubeMX / 查不到这根脚)时保持原序,只在末尾放 VP_*。
348
+ */
349
+ function sortPinsByPosition(order, positionOf) {
350
+ const keyed = order.map((pin, index) => {
351
+ const position = positionOf(pin);
352
+ // 分三档:已知 Position 的真实脚(1)→ db 里查不到的真实脚(2,保持原相对序)→ 虚拟脚(3,永远最后)。
353
+ const bucket = pin.startsWith("VP_") ? 3 : position === null ? 2 : 1;
354
+ const rank = position === null ? index : position;
355
+ return { pin, index, bucket, rank };
356
+ });
357
+ keyed.sort((left, right) => {
358
+ if (left.bucket !== right.bucket)
359
+ return left.bucket - right.bucket;
360
+ if (left.rank !== right.rank)
361
+ return left.rank - right.rank;
362
+ return left.index - right.index;
363
+ });
364
+ return keyed.map((item) => item.pin);
365
+ }
134
366
  /** 把引脚列表整体重编号写回 entries(新增/删除都可能让下标变化,重写最稳)。 */
135
- function writePinOrder(entries, order) {
136
- const previous = Number.parseInt(entries.get("Mcu.PinsNb") ?? "0", 10);
367
+ function writePinOrder(entries, order, positionOf) {
368
+ const finalOrder = positionOf === undefined ? order : sortPinsByPosition(order, positionOf);
369
+ const previous = Number.parseInt(entries.get(renderIocKey("mcu.pins_nb")) ?? "0", 10);
137
370
  const oldCount = Number.isFinite(previous) ? previous : 0;
138
- order.forEach((pin, position) => entries.set("Mcu.Pin" + String(position), pin));
139
- for (let position = order.length; position < oldCount; position += 1)
140
- entries.delete("Mcu.Pin" + String(position));
141
- entries.set("Mcu.PinsNb", String(order.length));
371
+ finalOrder.forEach((pin, position) => {
372
+ entries.set(renderIocKey("mcu.pin_index", { index: position }), pin);
373
+ });
374
+ for (let position = finalOrder.length; position < oldCount; position += 1) {
375
+ entries.delete(renderIocKey("mcu.pin_index", { index: position }));
376
+ }
377
+ entries.set(renderIocKey("mcu.pins_nb"), String(finalOrder.length));
142
378
  }
143
- function addPin(table, request, chip) {
379
+ /**
380
+ * Mcu.IP<i> 的排列规则(2026-11-02 语料实测,504 份官方板级 .ioc):
381
+ * **实例名按 natural 序(数字段按数值比)升序,伪实例(板名,形如 NUCLEO-L552ZE-Q)永远在最后**。
382
+ *
383
+ * 证据:单核族全对——F0/F2/F3/F4/F7/G0/G4/L0/L1/L4/WB/WL3/C0/U0 共 302 份 0 反例,F1 12/12;
384
+ * 差别只在 TIM2…TIM4,TIM15(纯字典序会把 TIM15 排到 TIM2 前)。整语料:纯字典序 375/502、
385
+ * natural 392/502、natural + 伪实例置尾 435/502;剩下的反例全是双核/TrustZone 板
386
+ * (NVIC2 在 NVIC1 前、板名插在中间),CubeMX 对它们另有插入序,不在本项目当前范围(F1)。
387
+ *
388
+ * 我们原来只把新 IP 追加在尾部:只要它的字典序不在末尾,回写就必然被重排(真机往返 B 里
389
+ * ADC1/DMA 被挪到 NVIC/RCC/SYS 前面,5 条 changedValues、benign=false)。
390
+ */
391
+ function compareIpInstance(left, right) {
392
+ const leftPseudo = left.includes("-") ? 1 : 0;
393
+ const rightPseudo = right.includes("-") ? 1 : 0;
394
+ if (leftPseudo !== rightPseudo)
395
+ return leftPseudo - rightPseudo;
396
+ const leftTokens = left.match(/\d+|\D+/gu) ?? [];
397
+ const rightTokens = right.match(/\d+|\D+/gu) ?? [];
398
+ const length = Math.max(leftTokens.length, rightTokens.length);
399
+ for (let index = 0; index < length; index += 1) {
400
+ const a = leftTokens[index];
401
+ const b = rightTokens[index];
402
+ if (a === undefined)
403
+ return -1;
404
+ if (b === undefined)
405
+ return 1;
406
+ if (/^[0-9]+$/u.test(a) && /^[0-9]+$/u.test(b)) {
407
+ const delta = Number.parseInt(a, 10) - Number.parseInt(b, 10);
408
+ if (delta !== 0)
409
+ return delta;
410
+ continue;
411
+ }
412
+ if (a !== b)
413
+ return a < b ? -1 : 1;
414
+ }
415
+ return 0;
416
+ }
417
+ /** 按上面的规则重排 Mcu.IP<i>;顺序没变就一个字节都不动。返回是否真的重排了。 */
418
+ function sortIpSlots(entries) {
419
+ const slots = [];
420
+ for (const [key, value] of entries) {
421
+ const hit = matchIocKey(key);
422
+ if (hit === null || hit.spec.id !== "mcu.ip_index")
423
+ continue;
424
+ slots.push({ key, index: Number.parseInt(hit.params.index ?? "", 10), value: value.trim() });
425
+ }
426
+ if (slots.length < 2)
427
+ return false;
428
+ slots.sort((left, right) => left.index - right.index);
429
+ const values = slots.map((slot) => slot.value);
430
+ const sorted = [...values].sort(compareIpInstance);
431
+ if (values.every((value, index) => value === sorted[index]))
432
+ return false;
433
+ for (const slot of slots)
434
+ entries.delete(slot.key);
435
+ sorted.forEach((value, index) => {
436
+ entries.set(renderIocKey("mcu.ip_index", { index }), value);
437
+ });
438
+ entries.set(renderIocKey("mcu.ip_nb"), String(sorted.length));
439
+ return true;
440
+ }
441
+ /**
442
+ * 引脚属性名 → schema spec id。属性键必须登记在 src/data/ioc-schema.ts 里,
443
+ * 否则覆盖率检查会把它当未知键报出来(这正是我们要的保护:拼错的名字会被抓到)。
444
+ */
445
+ const PIN_ATTRIBUTE_SPEC = {
446
+ "GPIO_Label": "pin.gpio_label",
447
+ "GPIO_Speed": "pin.gpio_speed",
448
+ "GPIO_PuPd": "pin.gpio_pupd",
449
+ "PinState": "pin.pin_state",
450
+ "GPIO_Mode": "pin.gpio_mode",
451
+ "GPIO_ModeDefaultEXTI": "pin.gpio_mode_default_exti",
452
+ "GPIO_ModeDefaultPP": "pin.gpio_mode_default_pp",
453
+ "GPIO_ModeDefaultOutputPP": "pin.gpio_mode_default_output_pp",
454
+ };
455
+ function attributeSpecId(name) {
456
+ const id = PIN_ATTRIBUTE_SPEC[name];
457
+ if (id === undefined)
458
+ throw new Error("ioc-plan: 引脚属性 " + name + " 没有登记 schema spec id");
459
+ return id;
460
+ }
461
+ function addPin(table, request, profile) {
144
462
  const pin = request.pin.trim();
145
463
  if (pin === "") {
146
464
  table.errors.push("pins 里有空引脚名");
@@ -150,8 +468,9 @@ function addPin(table, request, chip) {
150
468
  table.errors.push("引脚 " + pin + " 已经在 .ioc 里配置过了(要改请用 entries 直接设置对应键)");
151
469
  return;
152
470
  }
153
- if (!isKnownPin(chip.cpn, pin)) {
154
- table.errors.push("引脚 " + pin + " 不在 " + (chip.cpn === "" ? "当前 MCU" : chip.cpn) + " 的引脚表里(见 src/data/chips.ts)");
471
+ if (!isKnownPin(pin)) {
472
+ table.errors.push("引脚名 " + pin + " 不是合法的 STM32 GPIO 引脚(形如 PA0..PG15,或 VP_ 开头的虚拟引脚);" +
473
+ "插件不再内置引脚表,这个封装到底有没有这根脚请用 stm32_doctor 对着本机 CubeMX db 校验");
155
474
  return;
156
475
  }
157
476
  const label = (request.label ?? "").trim();
@@ -169,24 +488,161 @@ function addPin(table, request, chip) {
169
488
  }
170
489
  }
171
490
  }
172
- const signal = request.signal === "input" ? "GPIO_Input" : "GPIO_Output";
491
+ const exti = request.interrupt;
492
+ const line = exti === undefined ? null : extiLineOf(pin);
493
+ if (exti !== undefined && line === null) {
494
+ table.errors.push("引脚 " + pin + " 不能做 EXTI(EXTI 线号取引脚号 0–15,虚拟引脚没有线号)");
495
+ return;
496
+ }
497
+ const signal = exti === undefined
498
+ ? (request.signal === "input" ? "GPIO_Input" : "GPIO_Output")
499
+ : "GPXTI" + String(line);
173
500
  const pull = request.pull === undefined ? "none" : request.pull;
174
501
  const speed = request.speed === undefined ? "low" : request.speed;
175
- const parameters = ["GPIO_Label", "GPIO_PuPd", "GPIO_Speed"];
176
- table.entries.set(pin + ".GPIOParameters", parameters.join(","));
502
+ // S1/S2:CubeMX 只写「非默认」的 GPIO 属性 —— 默认(无上下拉、低速、输出推挽、初始低电平)时这些键
503
+ // 根本不出现。语料 504 份 .ioc 实测:GPIO 输出脚最常见的 GPIOParameters 就是单独一个 GPIO_Label
504
+ // (14,357 次),75.2% 的输出脚连 Speed/PuPd 都没有;三个名字无条件全写等于每个脚自造 2–3 处伪 diff。
505
+ //
506
+ // 2026-11-02 真机(6.15.0)补充两条:
507
+ // - 写在引脚上的 GPIO_* 属性键,只有同时列进 <pin>.GPIOParameters 才会被保留,
508
+ // 否则 CubeMX 静默删掉(实测 PC13-TAMPER-RTC.PinState 就是这样丢的);
509
+ // - GPIO_Mode / PinState 的值它不规范化,写什么回写什么(GPIO_MODE_OUTPUT_OD / GPIO_PIN_SET 都逐字保留),
510
+ // 所以能不能表达开漏、初始电平只取决于我们写不写这两个键。
511
+ const attributes = new Map();
177
512
  if (label !== "")
178
- table.entries.set(pin + ".GPIO_Label", label);
179
- table.entries.set(pin + ".Locked", "true");
180
- table.entries.set(pin + ".Signal", signal);
181
- table.entries.set(pin + ".GPIO_PuPd", PULL_VALUES[pull]);
182
- table.entries.set(pin + ".GPIO_Speed", SPEED_VALUES[speed]);
513
+ attributes.set("GPIO_Label", label);
514
+ if (speed !== "low")
515
+ attributes.set("GPIO_Speed", SPEED_VALUES[speed]);
516
+ if (pull !== "none")
517
+ attributes.set("GPIO_PuPd", PULL_VALUES[pull]);
518
+ if (exti !== undefined) {
519
+ attributes.set("GPIO_ModeDefaultEXTI", EXTI_MODES[exti]);
520
+ }
521
+ else {
522
+ if (request.initial === "high")
523
+ attributes.set("PinState", "GPIO_PIN_SET");
524
+ if (request.signal !== "input" && request.outputType === "od") {
525
+ attributes.set("GPIO_Mode", "GPIO_MODE_OUTPUT_OD");
526
+ }
527
+ }
528
+ const parameters = PIN_ATTRIBUTE_ORDER.filter((name) => attributes.has(name));
529
+ if (parameters.length > 0)
530
+ table.entries.set(renderIocKey("pin.gpio_parameters", { pin }), parameters.join(","));
531
+ else
532
+ table.entries.delete(renderIocKey("pin.gpio_parameters", { pin }));
533
+ for (const name of PIN_ATTRIBUTE_ORDER) {
534
+ const key = renderIocKey(attributeSpecId(name), { pin });
535
+ if (attributes.has(name))
536
+ table.entries.set(key, attributes.get(name));
537
+ else
538
+ table.entries.delete(key);
539
+ }
540
+ table.entries.set(renderIocKey("pin.locked", { pin }), "true");
541
+ table.entries.set(renderIocKey("pin.signal", { pin }), signal);
542
+ // EXTI 引脚在 CubeMX 的 .ioc 里没有 .Mode(模式由 GPIO_ModeDefaultEXTI + SH 块表达)。
543
+ if (exti !== undefined)
544
+ table.entries.delete(renderIocKey("pin.mode", { pin }));
545
+ if (exti !== undefined && line !== null) {
546
+ enableExtiSharedLine(table, line);
547
+ // NVIC 向量的名字按内核分档(M0 是 EXTI4_15、M3 是 EXTI9_5/EXTI15_10、M33 是逐线):
548
+ // 拿 F1 的分组去写 C0/L0/U5 会得到一个该芯片不存在的向量名,CubeMX 静默丢弃。
549
+ // 没有向量(Cortex-A 的 MP1/MP2 不走这条模型)时明确告警,不写。
550
+ const vector = extiIrqName(line, profile);
551
+ if (vector === "") {
552
+ table.warnings.push("EXTI" + String(line) + " 没有写 NVIC 向量:" + (profile === null ? "读不到芯片族" : profile.id + " 不走 NVIC/EXTI 模型") +
553
+ ",中断不会被使能");
554
+ }
555
+ else {
556
+ const irqKey = renderIocKey("nvic.vector", { name: vector.replace(/_IRQn$/u, "") });
557
+ if (!table.entries.has(irqKey))
558
+ table.entries.set(irqKey, nvicIrqValue(0, 0));
559
+ }
560
+ if (pull === "none") {
561
+ table.warnings.push("EXTI 引脚 " + pin + " 没有上/下拉:边沿触发时悬空会乱触发(常见做法是 pull=up 配 falling)");
562
+ }
563
+ }
183
564
  if (signal === "GPIO_Input" && pull === "none") {
184
565
  table.warnings.push("引脚 " + pin + " 配成输入但没有上/下拉:悬空时读数会乱(常见做法是 pull=up)");
185
566
  }
186
567
  table.order.push(pin);
187
568
  }
188
- /** 确保 Serial Wire 调试口:PA13/PA14 用调试信号,同时清掉 VP_SYS_VS_ND(No_Debug)残留。 */
189
- function ensureSerialWire(table) {
569
+ /**
570
+ * 把实例名登记进 Mcu.IP<i>(已有就什么都不做)。
571
+ *
572
+ * 真机证据(F4 板级 .ioc 往返):只写 PA13/PA14 的 Serial_Wire 而不把 SYS 登记进 Mcu.IP<i> 时,
573
+ * CubeMX 会自己补一条 Mcu.IP2=SYS 并把 Mcu.IPNb 从 2 改成 3 —— 也就是"我们漏了一项",
574
+ * 在 ioc_verify 里表现为 Mcu.IPNb 值被改写 + addedKeys 多一个 Mcu.IP2。补上之后往返才干净。
575
+ */
576
+ function ensureIpInstance(entries, name) {
577
+ const slots = [];
578
+ for (const [key, value] of entries) {
579
+ const hit = matchIocKey(key);
580
+ if (hit === null || hit.spec.id !== "mcu.ip_index")
581
+ continue;
582
+ slots.push({ index: Number.parseInt(hit.params.index ?? "", 10), value: value.trim() });
583
+ }
584
+ if (slots.some((slot) => slot.value.toUpperCase() === name.toUpperCase()))
585
+ return false;
586
+ const next = slots.length;
587
+ entries.set(renderIocKey("mcu.ip_index", { index: next }), name);
588
+ entries.set(renderIocKey("mcu.ip_nb"), String(next + 1));
589
+ return true;
590
+ }
591
+ /**
592
+ * 把 DEBUG 实例登记进 `Mcu.IP<i>`(只在**本族 db 里有这个实例**且这次确实用了 `DEBUG_*` 信号时)。
593
+ *
594
+ * 真机证据(C0 板级 .ioc 往返,2026-11):C0 的 db 把调试口单列成一个 IP 实例
595
+ * (`STM32C031C(4-6)Tx.xml` 里有 `<IP InstanceName="DEBUG" Name="DEBUG"/>`;F1/F4 的 db 里**没有**这个实例)。
596
+ * 所以只要引脚上有 `PA13.Signal=DEBUG_SWDIO`,CubeMX 回写就会插一条 `Mcu.IP1=DEBUG`(紧跟 CORTEX_M0+`,
597
+ * 正好是 natural 序)并把 `Mcu.IPNb` 加一。我们不写就永远差这一条:`ioc_verify` 的 `addedKeys` 里挂着它,
598
+ * `Mcu.IP1..IP4` 还会整排位移,看起来像"5 个键的值被改写"。
599
+ *
600
+ * 判据用 db 而不是族 id:db 里没有 DEBUG 实例的族(F1/F4)补了反而多写一个它不认的实例。
601
+ */
602
+ function ensureDebugInstance(entries, facts) {
603
+ if (facts === null || !hasIpInstance(facts, "DEBUG"))
604
+ return false;
605
+ const usesDebugSignal = [...entries].some(([key, value]) => key.endsWith(".Signal") && /^DEBUG_/u.test(value.trim()));
606
+ if (!usesDebugSignal)
607
+ return false;
608
+ return ensureIpInstance(entries, "DEBUG");
609
+ }
610
+ /**
611
+ * 确保 `ProjectManager.functionlistsort` 里有 `2-MX_GPIO_Init-GPIO-false-HAL-true`。
612
+ *
613
+ * 真机证据(C0 板级 .ioc 往返,2026-11):只要 .ioc 里有引脚——哪怕只有 PA13/PA14 的 SWD——
614
+ * CubeMX 保存时都会把 MX_GPIO_Init 插到清单**第二位**(SystemClock_Config 之后、CORTEX 之前)。
615
+ * 因为是插在中间而不是追加到末尾,ioc_verify 里"纯追加 MX_*_Init 不算差异"的例外盖不住它,
616
+ * 会记成一条 valueChanged。族模板里本来就有这一项(G0/U0 实测都有),C0 模板是零引脚所以没有。
617
+ */
618
+ function ensureGpioInitEntry(entries) {
619
+ const key = renderIocKey("project.functionlistsort");
620
+ const current = entries.get(key);
621
+ if (current === undefined)
622
+ return false;
623
+ const items = current.split(",").map((item) => item.trim()).filter((item) => item !== "");
624
+ if (items.some((item) => item.includes("-MX_GPIO_Init-")))
625
+ return false;
626
+ // 判据是"有引脚"而不是"有 GPIO 引脚":H5 实测纯 SWD(PA13/PA14 的 Serial_Wire)也会被 CubeMX 插进
627
+ // MX_GPIO_Init;反过来 C0 模板零引脚时它不会插,我们插了反而被删掉(两条都是真机往返看到的)。
628
+ const hasPins = [...entries.keys()].some((key) => key.endsWith(".Mode"));
629
+ if (!hasPins)
630
+ return false;
631
+ items.splice(items.length > 0 ? 1 : 0, 0, "2-MX_GPIO_Init-GPIO-false-HAL-true");
632
+ entries.set(key, items.join(","));
633
+ return true;
634
+ }
635
+ /**
636
+ * 确保 Serial Wire 调试口:PA13/PA14 用调试信号,同时清掉 VP_SYS_VS_ND(No_Debug)残留。
637
+ *
638
+ * 脚名与信号名**不能写死 F1 的字面量**(2026-11 实测 C0 板级 .ioc 才发现的跨族 bug):
639
+ * - C0 的 db 脚名是 PA14-BOOT0(不是 PA14)→ 写 PA14 会让 R17 报"同一根脚写了两份";
640
+ * - C0 的调试信号叫 DEBUG_SWDIO / DEBUG_SWCLK,F1 叫 SYS_JTMS-SWDIO / SYS_JTCK-SWCLK
641
+ * → 写 F1 的名字会被 CubeMX 丢弃(R13 也会告警"不是这根脚支持的信号")。
642
+ * 所以按本机 db 的该脚信号清单挑:优先 F1 的写法,其次 C0 的写法,再按 /SWDIO|JTMS/ 兜;
643
+ * db 不可用时才回落到 F1 字面量(老行为,此时引脚名本来也走内置别名表)。
644
+ */
645
+ function ensureSerialWire(table, pins) {
190
646
  const noDebugPins = table.order.filter((pin) => pin === "VP_SYS_VS_ND");
191
647
  for (const pin of noDebugPins) {
192
648
  table.order = table.order.filter((item) => item !== pin);
@@ -196,18 +652,498 @@ function ensureSerialWire(table) {
196
652
  }
197
653
  table.warnings.push("已删除 " + pin + "(No_Debug 会让 CubeMX 生成 __HAL_AFIO_REMAP_SWJ_DISABLE())");
198
654
  }
655
+ // 调试口挂在哪个实例下由**本族 db** 决定,不能一律写 SYS:
656
+ // - F1/F4 的 db 里调试口就是 SYS(Pin 的 signal 叫 SYS_JTMS-SWDIO),要补 Mcu.IPn=SYS;
657
+ // - C0/U0 的 db 把它单列成 DEBUG 实例(signal 叫 DEBUG_SWDIO),此时写 SYS 反而多出来的一个
658
+ // ——2026-11 C0 板级 .ioc 往返实测:我们写的 Mcu.IP4=SYS 被 CubeMX 整条删掉、IPNb 5→4,
659
+ // ioc_verify 因此报了两条 valueChanged。
660
+ // DEBUG 实例由紧随其后的 ensureDebugInstance 按 db 补,这里只管 SYS。
661
+ const facts = pins.facts;
662
+ const debugSignals = [];
663
+ // preferred 的顺序就是"想写成什么"的优先级;fallback 是 db 里有别名笔误时的兜底正则。
199
664
  const debugPins = [
200
- { pin: "PA13", signal: "SYS_JTMS-SWDIO" },
201
- { pin: "PA14", signal: "SYS_JTCK-SWCLK" },
665
+ { logical: "PA13", role: "swdio", preferred: ["SYS_JTMS-SWDIO", "DEBUG_SWDIO"], fallback: /SWDIO|JTMS/u },
666
+ { logical: "PA14", role: "swclk", preferred: ["SYS_JTCK-SWCLK", "DEBUG_SWCLK"], fallback: /SWCLK|JTCK/u },
202
667
  ];
668
+ // 脚位从 db 里反查:WB0/WL3 的 SWD 不在 PA13/PA14,而是 PA2(DEBUG_SWDIO)/PA3(DEBUG_SWCLK)
669
+ // ——2026-11 合成 .ioc 往返实测:按 F1 的 PA13/PA14 写,CubeMX 把两条脚和 SYS 实例整段丢掉
670
+ // (Mcu.PinsNb 2→0、Mcu.IPNb 4→3,ioc_verify 报 4 条 valueChanged)。
671
+ const findDebugPin = (role) => {
672
+ if (facts === null)
673
+ return null;
674
+ const rankOf = (signal) => {
675
+ const preferred = role === "swdio" ? ["SYS_JTMS-SWDIO", "DEBUG_SWDIO"] : ["SYS_JTCK-SWCLK", "DEBUG_SWCLK"];
676
+ const index = preferred.indexOf(signal);
677
+ if (index >= 0)
678
+ return index;
679
+ const fallback = role === "swdio" ? /SWDIO|JTMS/u : /SWCLK|JTCK/u;
680
+ return fallback.test(signal) ? preferred.length : -1;
681
+ };
682
+ let best = null;
683
+ for (const [pinName, info] of facts.pins) {
684
+ for (const signal of info.signals.keys()) {
685
+ const rank = rankOf(signal);
686
+ if (rank < 0)
687
+ continue;
688
+ if (best === null || rank < best.rank)
689
+ best = { pin: pinName, signal, rank };
690
+ }
691
+ }
692
+ return best === null ? null : { pin: best.pin, signal: best.signal };
693
+ };
203
694
  for (const item of debugPins) {
204
- if (!table.order.includes(item.pin)) {
205
- table.order.push(item.pin);
206
- table.entries.set(item.pin + ".Locked", "true");
695
+ const found = findDebugPin(item.role);
696
+ let pin = facts === null ? item.logical : (resolveDbPinName(facts, item.logical) ?? item.logical);
697
+ let signal = item.preferred[0];
698
+ if (found !== null) {
699
+ pin = found.pin;
700
+ signal = found.signal;
701
+ }
702
+ const signals = facts === null || found !== null ? undefined : facts.pins.get(pin)?.signals;
703
+ if (signals !== undefined && signals.size > 0) {
704
+ const chosen = item.preferred.find((name) => signals.has(name)) ??
705
+ [...signals.keys()].find((name) => item.fallback.test(name));
706
+ if (chosen === undefined) {
707
+ table.warnings.push("db 里 " + pin + " 没有 SWD 调试信号(该脚支持:" + [...signals.keys()].join("、") + "):按 F1 的 " + signal + " 写入,可能被 CubeMX 丢弃");
708
+ }
709
+ else {
710
+ signal = chosen;
711
+ }
712
+ }
713
+ if (!table.order.includes(pin)) {
714
+ table.order.push(pin);
715
+ table.entries.set(renderIocKey("pin.locked", { pin }), "true");
716
+ }
717
+ table.entries.set(renderIocKey("pin.mode", { pin }), "Serial_Wire");
718
+ table.entries.set(renderIocKey("pin.signal", { pin }), signal);
719
+ debugSignals.push(signal);
720
+ }
721
+ if (!debugSignals.some((name) => /^DEBUG_/u.test(name)))
722
+ ensureIpInstance(table.entries, "SYS");
723
+ }
724
+ /** 解析 "USART1" / "USART1_IRQn" / "EXTI9_5:2:0" → { irq, preempt?, sub? }。 */
725
+ function parseInterruptText(text) {
726
+ const parts = text.split(":");
727
+ const irq = (parts[0] ?? "").trim();
728
+ const preempt = parts.length > 1 ? Number.parseInt((parts[1] ?? "").trim(), 10) : undefined;
729
+ const sub = parts.length > 2 ? Number.parseInt((parts[2] ?? "").trim(), 10) : undefined;
730
+ return {
731
+ irq,
732
+ ...(preempt === undefined || Number.isNaN(preempt) ? {} : { preempt }),
733
+ ...(sub === undefined || Number.isNaN(sub) ? {} : { sub }),
734
+ };
735
+ }
736
+ /**
737
+ * 打开中断:写 NVIC.<名字>_IRQn。
738
+ *
739
+ * 为什么值得单开一个参数:C1 —— 以前"启用 USART1"只写 Mcu.IPn + 引脚 + IPParameters,
740
+ * 中断一个都不写,用户还得自己去 entries 里手拼 9 段;拼错第一段位置(true/false)CubeMX 会
741
+ * 按默认值覆盖,而且不报错。名字先按「db 外设实例 / SVD 中断表 / Cortex-M 内核异常」校验,
742
+ * 查不到就报错——写一条没人认的 NVIC 键,生成代码里不会有任何使能,等于白写。
743
+ */
744
+ function applyInterrupts(table, requests, context, notes) {
745
+ for (const item of requests) {
746
+ // 字符串形式允许内联优先级:"USART1:2:0"(preempt:sub);对象形式直接给字段。
747
+ const request = typeof item === "string" ? parseInterruptText(item) : item;
748
+ const raw = request.irq.trim();
749
+ if (raw === "") {
750
+ table.errors.push("interrupts 里有空的中断名");
751
+ continue;
752
+ }
753
+ const name = raw.replace(/_IRQn$/iu, "");
754
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/u.test(name)) {
755
+ table.errors.push("中断名 " + JSON.stringify(raw) + " 不是合法标识符(例:USART1 / EXTI9_5 / SysTick)");
756
+ continue;
757
+ }
758
+ const inIps = context.facts !== null && context.facts.ips.has(name.toUpperCase());
759
+ const inSvd = context.interrupts !== null && context.interrupts.has(name);
760
+ // EXTI 线是按线号分组的(EXTI0…EXTI4 / EXTI9_5 / EXTI15_10),SVD 里就叫这么个名字,
761
+ // 但它不是外设实例,db 里查不到;写 pins 的 interrupt 时也是同一个名字来源,所以直接放行。
762
+ const isExtiGroup = /^EXTI[0-9]+(?:_[0-9]+)?$/u.test(name);
763
+ if (!CORE_EXCEPTIONS.has(name) && !inIps && !inSvd && !isExtiGroup) {
764
+ if (context.interrupts === null && context.facts === null) {
765
+ table.warnings.push("中断名 " + name + " 没法校验:本机既没有 CubeMX db 也没有 SVD 中断表");
766
+ }
767
+ else {
768
+ table.errors.push("中断名 " + name + " 既不在本机 CubeMX db 的外设实例里,也不在 SVD 的中断表里:".concat("CubeMX 会忽略 NVIC.", name, "_IRQn,生成代码里不会有这个中断"));
769
+ continue;
770
+ }
771
+ }
772
+ const preempt = request.preempt ?? 0;
773
+ const sub = request.sub ?? 0;
774
+ if (!Number.isInteger(preempt) || preempt < 0 || preempt > 15) {
775
+ table.errors.push("中断 " + name + " 的 preempt 必须是 0–15 的整数(F1 的 NVIC 只有 4 位)");
776
+ continue;
777
+ }
778
+ if (!Number.isInteger(sub) || sub < 0 || sub > 15) {
779
+ table.errors.push("中断 " + name + " 的 sub 必须是 0–15 的整数");
780
+ continue;
781
+ }
782
+ const key = renderIocKey("nvic.vector", { name });
783
+ const existing = table.entries.get(key);
784
+ if (existing !== undefined && request.preempt === undefined && request.sub === undefined) {
785
+ notes.push(key + " 已存在(" + existing + "),保留原值;要改优先级请显式传 preempt/sub");
786
+ continue;
787
+ }
788
+ table.entries.set(key, nvicIrqValue(preempt, sub));
789
+ notes.push("已打开中断 " + key + " = " + nvicIrqValue(preempt, sub));
790
+ }
791
+ }
792
+ /**
793
+ * 写共享信号块:`SH.<key>.<n>=<IP 信号>,<IP 模式>` + `SH.<key>.ConfNb=<条数>`。
794
+ *
795
+ * 2026-10-31 实测(C8T6 + CubeMX 6.15.0):定时器与 ADC 的引脚在 .ioc 里是共享信号
796
+ * (`PA0-WKUP.Signal=S_TIM2_CH1_ETR`、`PA1.Signal=ADCx_IN1`),CubeMX 靠
797
+ * `SH.S_TIM2_CH1_ETR.0=TIM2_CH1,PWM Generation1 CH1` 才能把「这根脚 → TIM2 CH1 PWM」
798
+ * 这件事还原出来。只写引脚 Signal + <ip>.IPParameters 时,TIM2/TIM3/TIM4/ADC1 全被
799
+ * 静默丢弃(生成结果里没有 MX_xxx_Init,日志里也没有任何报错)。
800
+ */
801
+ function enableSharedSignal(table, shared) {
802
+ const value = shared.ipSignal + "," + shared.ipMode;
803
+ const confKey = renderIocKey("shared_signal.conf_nb", { signal: shared.key });
804
+ const declared = Number.parseInt(table.entries.get(confKey) ?? "", 10);
805
+ const count = Number.isFinite(declared) ? declared : 0;
806
+ for (let index = 0; index < count; index += 1) {
807
+ if ((table.entries.get(renderIocKey("shared_signal.slot", { signal: shared.key, n: index })) ?? "").trim() === value)
808
+ return;
809
+ }
810
+ table.entries.set(renderIocKey("shared_signal.slot", { signal: shared.key, n: count }), value);
811
+ table.entries.set(confKey, String(count + 1));
812
+ }
813
+ export function createPinNameResolver(options) {
814
+ const roots = options.cubeMxRoots !== undefined
815
+ ? [...options.cubeMxRoots]
816
+ : resolveSearchConfig(options.env ?? process.env, {}).cubeMxRoots;
817
+ const mcuName = options.mcuName.trim();
818
+ let facts = null;
819
+ let dbVersion = "";
820
+ if (mcuName !== "") {
821
+ const db = locateCubemxDb(roots);
822
+ if (db !== null) {
823
+ facts = readMcuFacts(db, mcuName);
824
+ if (facts !== null)
825
+ dbVersion = db.version;
207
826
  }
208
- table.entries.set(item.pin + ".Mode", "Serial_Wire");
209
- table.entries.set(item.pin + ".Signal", item.signal);
210
827
  }
828
+ const hit = facts;
829
+ if (hit !== null) {
830
+ return {
831
+ resolve: (logical) => resolveDbPinName(hit, logical) ?? logical,
832
+ db: locateCubemxDb(roots),
833
+ facts: hit,
834
+ describe: () => "引脚名按本机 CubeMX db 解析(" + hit.name + "," + dbVersion + ")",
835
+ warning: () => "",
836
+ };
837
+ }
838
+ return {
839
+ resolve: (logical) => pinDbName(options.family, logical),
840
+ db: null,
841
+ facts: null,
842
+ describe: () => "引脚名按内置别名表解析(本机没有可用的 CubeMX db:Mcu.Name=" + (mcuName === "" ? "(空)" : mcuName) + ")",
843
+ warning: () => "没找到 CubeMX 的 db/mcu/" + (mcuName === "" ? "<Mcu.Name>" : mcuName) + ".xml(找过 " +
844
+ (roots.length === 0 ? "(无候选目录)" : roots.join("、")) +
845
+ "),引脚名退回内置别名表:只覆盖 F1 的 6 根带后缀的脚,db 里换过名的话会写错脚",
846
+ };
847
+ }
848
+ /**
849
+ * EXTI 的共享信号块:`SH.GPXTI<line>.0=GPIO_EXTI<line>` + `SH.GPXTI<line>.ConfNb=1`。
850
+ *
851
+ * 和定时器/ADC 的 SH 块同一个机制,但值不带「,<模式>」(EXTI 没有多模式):
852
+ * 语料里的实物形态是 SH.GPXTI13.0=GPIO_EXTI13、SH.GPXTI13.ConfNb=1;
853
+ * 实测 6.15.0 回写时逐字保留、不会补别的键。
854
+ */
855
+ function enableExtiSharedLine(table, line) {
856
+ const signal = "GPXTI" + String(line);
857
+ const value = "GPIO_EXTI" + String(line);
858
+ const confKey = renderIocKey("shared_signal.conf_nb", { signal });
859
+ const declared = Number.parseInt(table.entries.get(confKey) ?? "", 10);
860
+ const count = Number.isFinite(declared) ? declared : 0;
861
+ for (let index = 0; index < count; index += 1) {
862
+ if ((table.entries.get(renderIocKey("shared_signal.slot", { signal, n: index })) ?? "").trim() === value)
863
+ return;
864
+ }
865
+ table.entries.set(renderIocKey("shared_signal.slot", { signal, n: count }), value);
866
+ table.entries.set(confKey, String(count + 1));
867
+ }
868
+ function enablePeripheral(table, request, pinNames, notes, familyId) {
869
+ // 解析顺序:**db 优先**。内置表是"某个 db 版本的手抄快照"(PA9/PA10 做 USART1 只在特定族/版本上成立),
870
+ // 换族或换 db 版本后同一外设的可用脚位就变了,所以:
871
+ // - F1 用内置表(真机验过);
872
+ // - 非 F1 先用 db 派生(按这颗芯片的复用例表选脚);
873
+ // - 变体/DMA(`TIM3:timebase`、`ADC1:1,4,5`、`DMA:ADC1`)db 里没有对应事实,仍用内置表;
874
+ // 其余(串口 / 定时器 PWM / ADC 单通道)**一律先查 db**,查不到才回退内置表(没装 CubeMX 的离线场景)。
875
+ // 这条顺序对 F1 也成立:手写表里那些脚位本来就是从某个版本的 db 抄出来的,db 才是活的事实源。
876
+ const rawName = request.name.trim();
877
+ const isVariant = rawName.includes(":") || /^DMA:/iu.test(rawName);
878
+ const builtin = findPeripheralPreset(request.name);
879
+ let preset = isVariant ? builtin : null;
880
+ if (preset === null) {
881
+ const derived = derivePeripheralPreset(pinNames.facts, request.name, { familyId });
882
+ if (derived.preset !== null) {
883
+ preset = derived.preset;
884
+ notes.push("按 db 派生预设 " + preset.name + "(" + preset.label + ")");
885
+ }
886
+ else if (builtin !== null) {
887
+ preset = builtin;
888
+ notes.push("内置表兜底启用 " + preset.name + "(" + preset.label + "):db 派生不可用 —— " + derived.reason);
889
+ }
890
+ else {
891
+ table.errors.push("不能启用 " + JSON.stringify(request.name) + ":" + derived.reason +
892
+ ";内置表(F1 手写):" + peripheralPresetNames().join("、"));
893
+ return;
894
+ }
895
+ }
896
+ // Mcu.IPn:占了槽位就把 IPNb 按实际条数重算。
897
+ const used = new Set();
898
+ let slots = 0;
899
+ for (const [key, value] of table.entries) {
900
+ if (!/^Mcu\.IP\d+$/u.test(key))
901
+ continue;
902
+ slots += 1;
903
+ used.add(value.trim());
904
+ }
905
+ if (!used.has(preset.ip)) {
906
+ table.entries.set(renderIocKey("mcu.ip_index", { index: slots }), preset.ip);
907
+ slots += 1;
908
+ }
909
+ table.entries.set(renderIocKey("mcu.ip_nb"), String(slots));
910
+ // 引脚:Mode + Signal + Locked。
911
+ const overrodePins = request.pins !== undefined && Object.keys(request.pins).length > 0;
912
+ for (const role of preset.pins) {
913
+ const logical = (request.pins?.[role.role] ?? role.defaultPin).trim().toUpperCase();
914
+ if (logical === "") {
915
+ table.errors.push(preset.name + " 的引脚 " + role.role + " 被指定成空串");
916
+ continue;
917
+ }
918
+ if (!isKnownPin(logical)) {
919
+ table.errors.push("引脚名 " + logical + " 不是合法的 STM32 GPIO 引脚(形如 PA0..PG15)");
920
+ continue;
921
+ }
922
+ const dbName = pinNames.resolve(logical);
923
+ const existingSignal = (table.entries.get(renderIocKey("pin.signal", { pin: dbName })) ?? "").trim();
924
+ if (table.order.includes(dbName) && existingSignal !== "" && existingSignal !== role.signal) {
925
+ table.errors.push(preset.name + " 想用 " + dbName + " 做 " + role.signal + ",但这根脚已经配成 " + existingSignal +
926
+ "(同一根脚不能同时做两件事,换引脚请传 pins)");
927
+ continue;
928
+ }
929
+ if (!table.order.includes(dbName))
930
+ table.order.push(dbName);
931
+ table.entries.set(renderIocKey("pin.locked", { pin: dbName }), "true");
932
+ table.entries.set(renderIocKey("pin.signal", { pin: dbName }), role.signal);
933
+ if (role.shared === undefined) {
934
+ if (role.mode !== "")
935
+ table.entries.set(renderIocKey("pin.mode", { pin: dbName }), role.mode);
936
+ }
937
+ else {
938
+ // 共享信号引脚:CubeMX 自己的 .ioc 里不带 .Mode,功能由 SH 块表达。
939
+ table.entries.delete(renderIocKey("pin.mode", { pin: dbName }));
940
+ enableSharedSignal(table, role.shared);
941
+ }
942
+ }
943
+ // 逐字键(DMA 这类键名不受 <ip>.<名字> 约束):先写它们,再统一重算 Dma.RequestsNb。
944
+ for (const raw of preset.rawEntries ?? []) {
945
+ table.entries.set(raw.key, request.parameters?.[raw.key.replace("Dma.", "").replace(/\.0\./u, ".")] ?? raw.value);
946
+ }
947
+ // G1/G2:DMA 三件套。CubeMX 自己写的是
948
+ // Dma.<IP>.<n>.RequestParameters=Instance,Direction,...,Priority(白名单,与 IPParameters 同机制:
949
+ // 不在名单里的字段会被静默忽略)
950
+ // Dma.Request<i>=<IP>(把请求号绑回实例;只有 RequestsNb 时它只是个孤立计数)
951
+ // 语料 504 份里含 DMA 的 17 份全部三件套齐全,richhal.ioc:30-32 是 F1 的实物证据;
952
+ // 另有 64/64 的 Dma.Request<i> 值等于同号 Dma.<IP>.<n> 的 IP 名,且 RequestParameters 列出的
953
+ // 名字与真的写了的键一一对应(0 处不符)。
954
+ const dmaGroups = new Map();
955
+ for (const key of table.entries.keys()) {
956
+ const group = dmaGroupOf(key);
957
+ if (group === null)
958
+ continue;
959
+ dmaGroups.set(group.ip + "." + group.n, group);
960
+ }
961
+ if (dmaGroups.size > 0 || (preset.rawEntries ?? []).some((raw) => isDmaKey(raw.key))) {
962
+ let request = 0;
963
+ for (const info of dmaGroups.values()) {
964
+ const present = [];
965
+ for (const key of table.entries.keys()) {
966
+ const group = dmaGroupOf(key);
967
+ if (group === null || group.ip !== info.ip || group.n !== info.n)
968
+ continue;
969
+ present.push(group.name);
970
+ }
971
+ present.sort((left, right) => {
972
+ const a = DMA_PARAM_ORDER.indexOf(left);
973
+ const b = DMA_PARAM_ORDER.indexOf(right);
974
+ if (a < 0 && b < 0)
975
+ return 0;
976
+ if (a < 0)
977
+ return 1;
978
+ if (b < 0)
979
+ return -1;
980
+ return a - b;
981
+ });
982
+ table.entries.set(renderIocKey("dma.request_parameters", { ip: info.ip, n: info.n }), present.join(","));
983
+ table.entries.set(renderIocKey("dma.request_index", { n: request }), info.ip);
984
+ // CubeMX 见到 DMA 通道就顺手打开它的中断(实测 6.15.0 + F1:加一条 ADC1 DMA 后
985
+ // 保存,diff 里唯一多出来的键就是 NVIC.DMA1_Channel1_IRQn,值固定这一串)。
986
+ // 我们不补它的话,每次回写都要多一条 added-key 噪声;只在缺失时补,用户设过的不覆盖。
987
+ const instance = (table.entries.get(renderIocKey("dma.request_group", { ip: info.ip, n: info.n, name: "Instance" })) ?? "").trim();
988
+ const channelIrq = renderIocKey("nvic.vector", { name: instance });
989
+ if (/^DMA[12]_Channel[0-9]$/u.test(instance) && !table.entries.has(channelIrq)) {
990
+ table.entries.set(channelIrq, "true:0:0:false:false:true:false:true:true");
991
+ }
992
+ request += 1;
993
+ }
994
+ table.entries.set(renderIocKey("dma.requests_nb"), String(request));
995
+ for (const key of [...table.entries.keys()]) {
996
+ const hit = matchIocKey(key);
997
+ if (hit === null || hit.spec.id !== "dma.request_index")
998
+ continue;
999
+ if (Number.parseInt(hit.params.n ?? "", 10) >= request)
1000
+ table.entries.delete(key);
1001
+ }
1002
+ }
1003
+ // 参数:写 <ip>.<名字>=值,并把名字合并进 <ip>.IPParameters。
1004
+ const paramsKey = renderIocKey("periph.ip_parameters", { ip: preset.ip });
1005
+ const names = (table.entries.get(paramsKey) ?? "").split(",").map((item) => item.trim()).filter((item) => item !== "");
1006
+ for (const param of preset.parameters) {
1007
+ table.entries.set(renderIocKey("periph.parameter", { ip: preset.ip, name: param.name }), request.parameters?.[param.name] ?? param.value);
1008
+ if (!names.includes(param.name))
1009
+ names.push(param.name);
1010
+ if (overrodePins && request.parameters?.[param.name] === undefined && param.name.startsWith("Channel-")) {
1011
+ table.warnings.push(preset.name + " 换了引脚,但 " + param.name + " 仍是 " + param.value +
1012
+ ":通道号必须与引脚一致,请一并用 parameters 改");
1013
+ }
1014
+ }
1015
+ for (const [name, value] of Object.entries(request.parameters ?? {})) {
1016
+ if (names.includes(name))
1017
+ continue;
1018
+ names.push(name);
1019
+ table.entries.set(renderIocKey("periph.parameter", { ip: preset.ip, name }), value);
1020
+ }
1021
+ if (names.length > 0)
1022
+ table.entries.set(paramsKey, names.join(","));
1023
+ // 预设自带的全局键(目前只有 ADC 的 RCC.ADCPresc)。两条硬要求:
1024
+ // 1) RCC.IPParameters 必须**字典序**:jar.md 说 RCCService 自己写这份名单时走 Collections.sort,
1025
+ // 语料 504 份里 429 份有序;以前这里是"追加到末尾",键一多就和 CubeMX 的写法错位。
1026
+ // 2) 改了 ADCPresc 就得同步 RCC.ADCFreqValue:否则 .ioc 自相矛盾(÷6 却还写着 ÷2 的 36 MHz)。
1027
+ // 语料里 4 份带 ADCPresc 的文件全部满足 ADCFreqValue == APB2/分频 → 这是 CubeMX 自己维护的不变量。
1028
+ const extraRcc = [];
1029
+ const rccDerivedPrefix = renderIocKey("rcc.derived", { member: "" });
1030
+ for (const extra of preset.extraEntries ?? []) {
1031
+ table.entries.set(extra.key, extra.value);
1032
+ if (extra.key.startsWith(rccDerivedPrefix))
1033
+ extraRcc.push(extra.key.slice(rccDerivedPrefix.length));
1034
+ }
1035
+ if (extraRcc.length > 0) {
1036
+ const adcDiv = adcPrescalerDiv(table.entries.get(renderIocKey("rcc.adc_presc")) ?? "");
1037
+ const apb2 = Number(table.entries.get(renderIocKey("rcc.derived", { member: "APB2Freq_Value" })) ??
1038
+ table.entries.get(renderIocKey("rcc.derived", { member: "APB2TimFreq_Value" })) ?? "");
1039
+ if (adcDiv !== null && Number.isFinite(apb2) && apb2 > 0) {
1040
+ table.entries.set(renderIocKey("rcc.adc_freq"), String(Math.round(apb2 / adcDiv)));
1041
+ if (!extraRcc.includes("ADCFreqValue"))
1042
+ extraRcc.push("ADCFreqValue");
1043
+ }
1044
+ const names = new Set();
1045
+ for (const part of (table.entries.get(renderIocKey("rcc.ip_parameters")) ?? "").split(",")) {
1046
+ const trimmed = part.trim();
1047
+ if (trimmed !== "")
1048
+ names.add(trimmed);
1049
+ }
1050
+ for (const name of extraRcc)
1051
+ names.add(name);
1052
+ table.entries.set(renderIocKey("rcc.ip_parameters"), [...names].sort().join(","));
1053
+ }
1054
+ notes.push("已启用预设 " + preset.name + "(" + preset.label + ")");
1055
+ for (const note of preset.notes ?? [])
1056
+ notes.push(note);
1057
+ }
1058
+ /**
1059
+ * 自洽校验(都按 CubeMX 的真实推导规则,不是风格洁癖):
1060
+ * - Mcu.IPNb 必须等于 Mcu.IPn 的条数;
1061
+ * - 外设进了 Mcu.IPn 就得有引脚 .Signal 指向它;
1062
+ * - 多模式外设的引脚还得表达功能:普通外设(USART)用 `.Mode`,共享信号外设(定时器/ADC)
1063
+ * 用 `SH.<pin信号>.<n>=<IP 信号>,<IP 模式>` —— 两者都缺时 CubeMX 静默丢弃整个外设,不报错。
1064
+ */
1065
+ function validatePeripheralWiring(entries, warnings, facts) {
1066
+ let slots = 0;
1067
+ const devices = new Set();
1068
+ for (const [key, value] of entries) {
1069
+ if (!/^Mcu\.IP\d+$/u.test(key))
1070
+ continue;
1071
+ slots += 1;
1072
+ devices.add(value.trim());
1073
+ }
1074
+ const ipNbKey = renderIocKey("mcu.ip_nb");
1075
+ const declared = Number.parseInt(entries.get(ipNbKey) ?? "", 10);
1076
+ if (Number.isFinite(declared) && declared !== slots) {
1077
+ warnings.push(ipNbKey + "=" + String(declared) + " 但实际有 " + String(slots) + " 个 Mcu.IPn 键(CubeMX 打开时会自己重算)");
1078
+ }
1079
+ const pinsByDevice = new Map();
1080
+ for (const [key, value] of entries) {
1081
+ if (!key.endsWith(".Signal"))
1082
+ continue;
1083
+ const pin = key.slice(0, key.length - ".Signal".length);
1084
+ for (const device of devicesOfSignal(entries, value.trim())) {
1085
+ const list = pinsByDevice.get(device) ?? [];
1086
+ list.push(pin);
1087
+ pinsByDevice.set(device, list);
1088
+ }
1089
+ }
1090
+ // db 里"这根芯片的引脚复用中出现过哪些外设族":内核项(CORTEX_M0+)、板名(NUCLEO-C031C6)
1091
+ // 这些本来就不该有引脚,靠这张表自动排除,而不是再堆一份黑名单(2026-11 C0 实测踩过)。
1092
+ const chipFamilies = facts === null ? null : instancesWithPins(facts);
1093
+ for (const device of devices) {
1094
+ // 伪外设:没有自己的引脚(DMA/NVIC/RCC/SYS 以及 Cortex 内核项),不按「必须有引脚」校验。
1095
+ if (device === "" || device === "NVIC" || device === "RCC" || device === "SYS" || device === "DMA")
1096
+ continue;
1097
+ if (chipFamilies !== null && !chipFamilies.has(instanceFamilyName(device)))
1098
+ continue;
1099
+ const pins = pinsByDevice.get(device) ?? [];
1100
+ if (pins.length === 0) {
1101
+ warnings.push(device + " 在 Mcu.IPn 里,但没有引脚的 .Signal 指向它 → CubeMX 会忽略这个外设");
1102
+ continue;
1103
+ }
1104
+ const noMode = pins.filter((pin) => {
1105
+ const signal = (entries.get(pin + ".Signal") ?? "").trim();
1106
+ if (signal.startsWith("GPIO_"))
1107
+ return false;
1108
+ if ((entries.get(pin + ".Mode") ?? "").trim() !== "")
1109
+ return false;
1110
+ // 共享信号(定时器/ADC)本来就不带 .Mode,改由 SH.<signal>.<n>=<IP 信号>,<IP 模式> 表达。
1111
+ return (entries.get(renderIocKey("shared_signal.conf_nb", { signal })) ?? "") === "";
1112
+ });
1113
+ if (noMode.length > 0) {
1114
+ warnings.push(device + " 的引脚 " + noMode.join("、") + " 既没有 .Mode 也没有 SH." + " 共享信号块 → " +
1115
+ "CubeMX 实测会静默丢弃整个外设(用 peripherals 预设,或自己补 <pin>.Mode / SH 块)");
1116
+ }
1117
+ }
1118
+ }
1119
+ /**
1120
+ * 一根脚的 .Signal 指向哪个外设实例。
1121
+ *
1122
+ * 名字有三种来源:`USART1_TX`(普通外设)、`S_TIM2_CH1_ETR`(定时器共享信号,前缀 S_)、
1123
+ * `ADCx_IN1`(ADC 共享信号,本身不含实例名 —— 实例名在 `SH.ADCx_IN1.0=ADC1_IN1,IN1` 里)。
1124
+ */
1125
+ function devicesOfSignal(entries, signal) {
1126
+ const found = new Set();
1127
+ const add = (name) => {
1128
+ const match = /^([A-Z][A-Z0-9]*)_/u.exec(name);
1129
+ if (match === null)
1130
+ return;
1131
+ const device = match[1] ?? "";
1132
+ if (device === "" || device.endsWith("x"))
1133
+ return;
1134
+ found.add(device);
1135
+ };
1136
+ add(signal);
1137
+ if (signal.startsWith("S_"))
1138
+ add(signal.slice(2));
1139
+ const declared = Number.parseInt(entries.get(renderIocKey("shared_signal.conf_nb", { signal })) ?? "", 10);
1140
+ const count = Number.isFinite(declared) ? declared : 0;
1141
+ for (let index = 0; index < count; index += 1) {
1142
+ const value = (entries.get(renderIocKey("shared_signal.slot", { signal, n: index })) ?? "").trim();
1143
+ const target = value.split(",")[0] ?? "";
1144
+ add(target);
1145
+ }
1146
+ return [...found];
211
1147
  }
212
1148
  function planPaths(projectDir, planId) {
213
1149
  const dir = join(projectDir, STATE_DIR, "plans");
@@ -236,34 +1172,124 @@ export function planIocChanges(request) {
236
1172
  const empty = {
237
1173
  ok: false, projectDir, iocPath: iocPath ?? "", planId: "", sourceSha256: "", candidateSha256: "",
238
1174
  changes: [], warnings: [], notes: [], errors: [], message: "",
1175
+ dbVersion: "", dbRoot: "",
239
1176
  clockPlan: emptyClockPlan("还没读到 .ioc,时钟没算"),
240
1177
  };
241
1178
  if (iocPath === null || !existsSync(iocPath)) {
242
1179
  return { ...empty, errors: ["找不到 .ioc(工程根目录下必须有且只有一个 *.ioc,或用 iocPath 指定)"], message: "没生成计划:找不到 .ioc" };
243
1180
  }
244
- const source = readFileSync(iocPath, "utf8");
1181
+ let source = "";
1182
+ try {
1183
+ source = readIocText(iocPath);
1184
+ }
1185
+ catch (error) {
1186
+ const message = error instanceof Error ? error.message : String(error);
1187
+ return { ...empty, iocPath, errors: [message], message: "没生成计划:" + message };
1188
+ }
245
1189
  const sourceSha256 = sha256Hex(source);
246
1190
  const errors = [];
247
1191
  const warnings = [];
248
1192
  const notes = [];
1193
+ const diagnostics = inspectIocText(source);
1194
+ if (diagnostics.mixedEol) {
1195
+ warnings.push("这份 .ioc 的换行不一致(既有 CRLF 又有 LF):写回时会统一成多数的那种(CRLF)");
1196
+ }
1197
+ else if (source.includes("\n") && !source.includes("\r\n")) {
1198
+ // 纯 LF:CubeMX 自己保存时写 CRLF。我们保留原样(否则用户第一次 apply 就会看到整文件换行变化),
1199
+ // 但要说清代价——拿我们的文件跟 CubeMX 另存的结果逐字节 diff 时会差整文件换行(键值不受影响)。
1200
+ warnings.push("这份 .ioc 是纯 LF 换行(CubeMX 自己保存时用 CRLF):写回保持 LF,逐字节对比 CubeMX 另存的结果会整文件不同");
1201
+ }
1202
+ if (!diagnostics.finalNewline) {
1203
+ notes.push("源文件末尾没有换行:写回时保持原样(CubeMX 自己写的文件是有换行的,手工改出来的常常没有)");
1204
+ }
1205
+ if (diagnostics.malformedLines.length > 0) {
1206
+ warnings.push("这些行既不是 # 注释、也没有 \"=\",CubeMX 会当垃圾行丢掉(行号:" +
1207
+ diagnostics.malformedLines.slice(0, 8).join("、") +
1208
+ (diagnostics.malformedLines.length > 8 ? "…" : "") + ")");
1209
+ }
249
1210
  const before = parseIocEntries(source);
250
1211
  // 深拷贝成可写 Map(parseIocEntries 返回的就是新 Map,直接改即可)。
251
1212
  const after = new Map(before);
252
- const chipCpn = before.get("Mcu.CPN") ?? "";
253
1213
  const pinTable = readPinTable(after, errors, warnings);
254
1214
  // 先记下原始引脚表:只有真的变了才重写 Mcu.PinN,顺序没变就一个字节都不碰。
255
1215
  const originalOrder = [...pinTable.order];
1216
+ // 芯片族先判出来:SVD 中断名校验、时钟规划、外设预设表都按族开闸(画像在 data/family.ts)。
1217
+ // 依据是 .ioc 自己的 Mcu.Family(CubeMX 写死的族)。读不到时 familyProfile 为 null:
1218
+ // 不静默当成 F1 放行,而是按"读不到族"处理——该告警的告警(见下面 peripherals 那段),键照写。
1219
+ const family = (after.get(renderIocKey("mcu.family")) ?? "").trim();
1220
+ const familyProfile = family === "" ? null : familyProfileOf(family);
1221
+ const svdSupported = familyProfile === null || familyProfile.capabilities.svdValidation;
1222
+ // SVD 的中断表先准备好:interrupts 参数要拿它校验中断名,R20 也要用(同一个 set 复用,只读一次盘)。
1223
+ // .ioc 里只有 CPN(STM32F103C8T6),先换成 SVD 的 line(103);没有内置资源时 device 为 null,校验跳过。
1224
+ let interrupts = null;
1225
+ const cpn = (after.get(renderIocKey("mcu.cpn")) ?? "").trim();
1226
+ if (cpn !== "") {
1227
+ if (svdSupported) {
1228
+ const line = svdLineForChip(cpn);
1229
+ const device = line === null ? null : loadSvdForLine(line);
1230
+ if (device !== null && device.interruptNames.size > 0)
1231
+ interrupts = device.interruptNames;
1232
+ }
1233
+ else {
1234
+ // 内置资源里只有 F1 的 SVD:别的族查不到中断名。跳过校验而不是拿 F1 的名字硬比(那样会把对的名字判成错)。
1235
+ notes.push("中断名/寄存器名校验跳过:" + (familyProfile === null ? family : capabilityGap(familyProfile, "svdValidation")));
1236
+ }
1237
+ }
1238
+ // 引脚名解析器(本机 db)先建出来:Serial Wire 要按该芯片的脚名/信号名写,
1239
+ // 引脚表排序要 Position,外设预设要 db,都靠它。它只读 db,不改 .ioc。
1240
+ const pinNames = createPinNameResolver({ mcuName: (after.get(renderIocKey("mcu.name")) ?? "").trim(), family });
1241
+ // db 指纹写进报告:任何一条返回路径(包括"没有变化"、失败)都要带上,报 bug 时能一眼看出 db 版本差异。
1242
+ empty.dbVersion = pinNames.db?.version ?? "";
1243
+ empty.dbRoot = pinNames.db?.root ?? "";
256
1244
  for (const pin of request.pins ?? [])
257
- addPin(pinTable, pin, { cpn: chipCpn });
1245
+ addPin(pinTable, pin, familyProfile);
258
1246
  if (request.serialWire === true)
259
- ensureSerialWire(pinTable);
1247
+ ensureSerialWire(pinTable, pinNames);
1248
+ // 调试口要不要单独占一个 IP 实例由本族 db 决定(C0 有 DEBUG 实例,F1/F4 没有)。
1249
+ if (ensureDebugInstance(pinTable.entries, pinNames.facts)) {
1250
+ notes.push("把 DEBUG 登记进 Mcu.IP<i>:本族 db 把调试口单列成实例 DEBUG,CubeMX 回写时自己会补(C0 实证)");
1251
+ }
1252
+ // 有引脚就得有 MX_GPIO_Init 这一项(C0 模板零引脚缺它,CubeMX 保存时插在第二位)。
1253
+ if (pinTable.order.length > 0 && ensureGpioInitEntry(pinTable.entries)) {
1254
+ notes.push("ProjectManager.functionlistsort 补上 2-MX_GPIO_Init-GPIO-false-HAL-true:有引脚时 CubeMX 会自己插这一项(C0 实证)");
1255
+ }
1256
+ if (familyProfile !== null && !isF1(familyProfile) && ((request.pins ?? []).length > 0 || (request.interrupts ?? []).length > 0)) {
1257
+ warnings.push("引脚/中断的写入规则只在 F1 上做过真机往返(" + familyProfile.id + " 未验证):键名按本族 db 生成,落地前请用 stm32_ioc_verify 复核");
1258
+ }
1259
+ if (family === "" && (request.peripherals ?? []).length > 0) {
1260
+ warnings.push("读不到 Mcu.Family,引脚名按原样写入:F1 的 PA0 实际 db 名是 PA0-WKUP,写错会被 CubeMX 丢弃");
1261
+ }
1262
+ // 预设不再按族整体拒绝:内置表(F1 手写)之外,任何有 db 的族都能派生 USART/UART/LPUART 预设,
1263
+ // 派生不出来的(TIM/ADC/DMA、db 里没这个实例)由 enablePeripheral 逐条报人话。
1264
+ if ((request.peripherals ?? []).length > 0) {
1265
+ notes.push(pinNames.describe());
1266
+ const pinWarning = pinNames.warning();
1267
+ if (pinWarning !== "")
1268
+ warnings.push(pinWarning);
1269
+ for (const item of request.peripherals ?? [])
1270
+ enablePeripheral(pinTable, item, pinNames, notes, family);
1271
+ }
260
1272
  // 引脚表变化过才重写 Mcu.PinN。
261
1273
  // 为什么不再按"有没有 .Signal"过滤:F1 的 PB2 在 CubeMX 里只有 PB2.Mode=B2-BOOT1(BOOT1 是复用功能,
262
1274
  // 不带 .Signal)。按 .Signal 过滤会把它从 Mcu.PinN 里静默剔除——PinsNb 缩水,PB2.Mode / PB2.GPIO_*
263
1275
  // 成了没有引脚指向的孤儿键,CubeMX 下次打开就丢这段配置。所以:已在表里的引脚一个都不删,只追加。
264
1276
  // 虚拟引脚(VP_*)的清理归 ensureSerialWire 管,这里不掺和。
265
- if (!samePinOrder(originalOrder, pinTable.order))
266
- writePinOrder(after, pinTable.order);
1277
+ // 排序:CubeMX 自己按 db 的 <Pin Position> 升序写 Mcu.Pin<i>(虚拟脚在最后),我们以前只会尾部追加,
1278
+ // 所以每次加引脚都会多一条"引脚表被重排"的真 diff(三次真机探针一致)。
1279
+ // 没有 db 时所有脚都查不到 Position:排序退化成「原序 + 虚拟脚挪到最后」,仍然是我们想要的
1280
+ // (原文件本来就是 CubeMX 写的,顺序已经对;VP_* 无论哪种情况都在最后)。
1281
+ const positionOf = (pin) => {
1282
+ const fact = pinNames.facts === null ? undefined : pinNames.facts.pins.get(pin);
1283
+ return fact === undefined ? null : fact.position;
1284
+ };
1285
+ const finalOrder = sortPinsByPosition(pinTable.order, positionOf);
1286
+ if (!samePinOrder(originalOrder, finalOrder)) {
1287
+ const onlyReordered = samePinOrder(originalOrder, pinTable.order);
1288
+ writePinOrder(after, pinTable.order, positionOf);
1289
+ if (onlyReordered) {
1290
+ notes.push("Mcu.Pin<i> 按 CubeMX db 的引脚 Position 重排(虚拟脚在最后):CubeMX 自己保存时就是这个顺序");
1291
+ }
1292
+ }
267
1293
  for (const item of request.entries ?? []) {
268
1294
  const key = item.key.trim();
269
1295
  if (key === "" || key.includes("=")) {
@@ -284,12 +1310,59 @@ export function planIocChanges(request) {
284
1310
  }
285
1311
  after.delete(trimmed);
286
1312
  }
1313
+ // 中断放在 entries/unset 之后:entries 里手写的 NVIC 值优先,没显式给优先级时原样保留
1314
+ // (applyInterrupts 见到已存在的键只会记 note,不会覆盖)。
1315
+ if ((request.interrupts ?? []).length > 0) {
1316
+ applyInterrupts(pinTable, request.interrupts ?? [], { facts: pinNames.facts, interrupts }, notes);
1317
+ }
287
1318
  // 时钟:.ioc 里的一段键,和 entries 一起算(不单开工具)。复用 after,所以同一调用里的
288
1319
  // entries(例如 RCC.MCOSource)对时钟规划是可见的;规划出的键也是"候选文件"的一部分。
289
- const clockPlan = request.clock === undefined
290
- ? planClock(undefined, { entries: after })
291
- : planClock(request.clock, { entries: after });
292
- if (request.clock === undefined) {
1320
+ // 时钟事实优先从本机 CubeMX db 现算(PLLMUL/PLLM/PLLN 枚举、SYSCLK 上限):
1321
+ // - pllmul 模型(F0/F1/L0…)且有该族总线上限 → 直接规划(F1 的派生结果与手写表逐项相等,已在单测里钉住);
1322
+ // - direct 模型(C0:没有 PLL,SYSCLK 直接取源)→ 走 clock-direct.ts;
1323
+ // - unknown(H7/U5 分相 PLL 这类还没实现的模型)→ 明确拒绝,不套别的族的键名;
1324
+ // - 读不到 db(没装 CubeMX)→ F1 用 F1_FACTS 兜底,别的族拒绝。
1325
+ const clockDb = pinNames.facts === null || pinNames.db === null ? null : readClockDbFacts(pinNames.db, pinNames.facts);
1326
+ const clockDbFacts = clockDb === null ? null : clockFactsFromDb(clockDb, family === "" ? "STM32F1" : family);
1327
+ const clockSupported = familyProfile === null || familyProfile.capabilities.clockPlan || clockDbFacts !== null;
1328
+ // 拒绝原因按「先看事实、再看族画像」排:族画像里的 clockPlan 是早期「只按 F1 手写表」的粗粒度闸门,
1329
+ // 现在 24 个族都能从 db 现算,拿它当原因会盖掉真正缺口(H7 是分相 PLL 没实现,不是「只支持 F1」)。
1330
+ const clockRefusal = clockSupported
1331
+ ? ""
1332
+ : (clockDb === null
1333
+ ? (familyProfile === null ? family : capabilityGap(familyProfile, "clockPlan")) +
1334
+ ";也没读到本机 CubeMX db 的 RCC Modes(装 CubeMX 后重试)"
1335
+ : clockDb.model === "pllmn"
1336
+ ? family + ":这一族的 PLL 是 PLLM/PLLN/PLLP 模型,但 VCO 允许区间在 db 的 RCC Modes 与 override 表里都没有"
1337
+ : clockDb.model === "direct"
1338
+ ? family + ":这一族没有 PLL(SYSCLK 直接取源),但 db 的 SYSCLKSource 里没有 HSE/HSI"
1339
+ : clockDb.model === "unknown"
1340
+ ? family + ":" +
1341
+ // 具体是哪种没实现的模型(分相 PLL / MSI 直连)由 clock-db 写在 notes 里,原样带给用户:
1342
+ // 只说"不在已实现的三种之内"会让人以为是配置写错,实际是插件还不支持这一族的形状。
1343
+ (clockDb.notes.find((note) => /还没实现|还没建模/u.test(note)) ??
1344
+ "这一族的时钟模型还没实现(已实现 pllmul / pllmn / direct),不会给时钟计划")
1345
+ : family + ":这一族的 APB1/APB2 频率上限在 db 的 RCC Modes 里没读到(也可能这一族不在这份 db 里)");
1346
+ // 三种时钟模型各走各的规划器(pllmul:源 × PLLMUL;pllmn:源 ÷ PLLM × PLLN ÷ PLLP;
1347
+ // direct:没有 PLL,SYSCLK 直接取源),但输出同一种 ClockPlan,后面的写键逻辑不分叉。
1348
+ const clockPlan = !clockSupported
1349
+ ? emptyClockPlan(clockRefusal + ":clock 参数不会生效")
1350
+ : clockDbFacts !== null && clockDbFacts.model === "pllmn"
1351
+ ? planClockPllmn({ request: request.clock, entries: after, facts: clockDbFacts, familyId: family })
1352
+ : clockDbFacts !== null && clockDbFacts.model === "direct"
1353
+ ? planClockDirect({ request: request.clock, entries: after, facts: clockDbFacts, familyId: family })
1354
+ : (request.clock === undefined
1355
+ ? planClock(undefined, { entries: after, ...(clockDbFacts === null ? {} : { clockFacts: clockDbFacts }), ...(family === "" ? {} : { familyId: family }) })
1356
+ : planClock(request.clock, { entries: after, ...(clockDbFacts === null ? {} : { clockFacts: clockDbFacts }), ...(family === "" ? {} : { familyId: family }) }));
1357
+ if (!clockSupported) {
1358
+ if (request.clock === undefined) {
1359
+ notes.push("时钟:" + clockPlan.note);
1360
+ }
1361
+ else {
1362
+ errors.push("时钟:" + clockPlan.note);
1363
+ }
1364
+ }
1365
+ else if (request.clock === undefined) {
293
1366
  const achieved = clockPlan.achieved;
294
1367
  notes.push("时钟(只读,未请求改动):SYSCLK " + formatHz(achieved.sysclkHz) +
295
1368
  " / APB1 " + formatHz(achieved.apb1Hz) +
@@ -300,15 +1373,124 @@ export function planIocChanges(request) {
300
1373
  warnings.push(...clockPlan.warnings);
301
1374
  if (clockPlan.note !== "")
302
1375
  notes.push("时钟:" + clockPlan.note);
1376
+ // 派生频率键(RCC.<外设>Freq_Value)的“跟随改写”要在写键之前拍快照:它靠“旧值等于哪个时钟域”
1377
+ // 判断该跟着谁走,新旧值都从这张表里读。详见 clock-derived.ts 的注释。
1378
+ const beforeClockWrite = new Map(after);
303
1379
  for (const item of clockPlan.entries)
304
1380
  after.set(item.key, item.value);
305
1381
  for (const key of clockPlan.unset)
306
1382
  after.delete(key);
307
1383
  for (const error of clockPlan.errors)
308
1384
  errors.push("时钟:" + error);
1385
+ const followed = followDerivedClocks(after, beforeClockWrite, new Set(clockPlan.entries.map((item) => item.key)));
1386
+ if (followed.written.length > 0) {
1387
+ notes.push("顺带改写 " + String(followed.written.length) + " 个派生频率键(旧值等于同名时钟域的跟着走):" +
1388
+ followed.written.map((item) => item.key.replace("RCC.", "") + "→" + formatHz(item.to)).join("、"));
1389
+ }
1390
+ if (followed.skipped.length > 0) {
1391
+ notes.push("这些派生频率键新旧时钟域对不上、留 CubeMX 重算:" + followed.skipped.map((item) => item.key.replace("RCC.", "")).join("、"));
1392
+ }
1393
+ }
1394
+ // 外设接线自洽性(IPNb 条数、外设有没有引脚指向、多模式引脚缺不缺 .Mode)。
1395
+ validatePeripheralWiring(after, warnings, pinNames.facts);
1396
+ // 从 CubeMX 字节码还原出来的离线规则(docs §35):IPParameters 白名单、DMA 需要 Mcu.IP=DMA、
1397
+ // ADC Rank 一致性、NVIC 值 9 段、F1 的 ADC 时钟上限。
1398
+ // C6:把 entries 直接写进去的 <IP>.<标量键> 自动补进 <IP>.IPParameters。
1399
+ // CubeMX 只认白名单里的参数(R7 检查的就是这件事),漏写会被静默丢弃——这里主动补齐,而不是只告警。
1400
+ const instances = new Set();
1401
+ for (const [key, value] of after) {
1402
+ if (matchIocKey(key)?.spec.id === "mcu.ip_index")
1403
+ instances.add(value.trim());
1404
+ }
1405
+ for (const ip of instances) {
1406
+ // 只补真外设实例(ADC1/TIM3/USART1…)。NVIC / RCC / SYS / DMA 这些是"伪实例",
1407
+ // 它们的键(NVIC.TIM2_IRQn、RCC.SYSCLKSource…)不属于 IPParameters 白名单,补进去反而写错。
1408
+ if (!/^[A-Z]+[0-9]+$/u.test(ip))
1409
+ continue;
1410
+ const listed = (after.get(ip + ".IPParameters") ?? "").split(",").map((item) => item.trim()).filter((item) => item !== "");
1411
+ const known = new Set(listed);
1412
+ const added = [];
1413
+ for (const key of [...after.keys()]) {
1414
+ if (!key.startsWith(ip + "."))
1415
+ continue;
1416
+ const name = key.slice(ip.length + 1);
1417
+ if (name === "IPParameters" || name.includes("."))
1418
+ continue;
1419
+ if (known.has(name))
1420
+ continue;
1421
+ known.add(name);
1422
+ added.push(name);
1423
+ }
1424
+ if (added.length === 0)
1425
+ continue;
1426
+ after.set(ip + ".IPParameters", [...listed, ...added].join(","));
1427
+ notes.push("自动补 " + ip + ".IPParameters:" + added.join("、") + "(不补会被 CubeMX 静默丢弃)");
1428
+ }
1429
+ // schema 覆盖率闸门(两道,S5 收尾)。放在 C6 之后:自动补 IPParameters 会新增一个键,它同样要受审。
1430
+ // 第一道:键形状必须在真值表里(uncovered 就是"完全没登记的形状")。
1431
+ // 第二道:namespace 级命中({ip}.{name} / Dma.{ip}.{n}.{name} 这类模板)只证明了"前缀.某东西",
1432
+ // 拼错的键也能命中;所以要按上下文逐条判——是不是 Mcu.IP<i> 里真实启用的实例、参数名在不在
1433
+ // db 的 RefParameter 清单里、ip 位写的是不是引脚名、Dma 参数在不在白名单里。
1434
+ // 只审"这次计划写或改的键":文件里原有的键是 CubeMX 自己写的,审了只会误报。
1435
+ // 仍然只告警、不硬失败——老工程模板可能带我们没登记的键,卡死 plan 比漏报更糟;
1436
+ // 真正的闸门在单测里(schema 覆盖率 0 uncovered + 每类写键点都有 spec)。
1437
+ // C7:Mcu.IP<i> 顺序。只有这次动过 IP 槽位才重排——CubeMX 回写时按 natural 序重排
1438
+ // (见 sortIpSlots 注释),我们不排就等于每次启用字典序靠前的外设都制造 5 条假 diff。
1439
+ const ipTouched = [...after.keys()].some((key) => matchIocKey(key)?.spec.id === "mcu.ip_index" && after.get(key) !== before.get(key));
1440
+ if (ipTouched && sortIpSlots(after)) {
1441
+ notes.push("按 CubeMX 的 natural 序重排 Mcu.IP<i>(TIM2…TIM4,TIM15;板名置尾):它回写时也是这么排的");
1442
+ }
1443
+ const touched = [...after.keys()].filter((key) => after.get(key) !== before.get(key)).sort(compareIocKeys);
1444
+ const coverage = iocSchemaCoverage(touched);
1445
+ if (coverage.uncovered.length > 0) {
1446
+ warnings.push("[SCHEMA] " + String(coverage.uncovered.length) + " 个键不在 .ioc schema 真值表里(" +
1447
+ coverage.uncovered.slice(0, 5).join("、") + "):可能是 CubeMX 新版本加的键,也可能是我们拼错了键名" +
1448
+ "——拼错的键会被 CubeMX 静默忽略,确认后请补进 src/data/ioc-schema.ts");
1449
+ }
1450
+ if (coverage.weak.length > 0) {
1451
+ const db = pinNames.db;
1452
+ const facts = pinNames.facts;
1453
+ const auditContext = {
1454
+ instances,
1455
+ pins: facts === null ? [] : [...facts.pins.keys()],
1456
+ dbInstances: facts === null ? [] : [...facts.ips.keys()],
1457
+ // 没有 db 时返回 null:这条不校验,而不是"查不到就报错"。
1458
+ paramNamesOf: (instance) => {
1459
+ if (db === null || facts === null)
1460
+ return null;
1461
+ const names = readIpParameterNames(db, facts, instance);
1462
+ return names.length === 0 ? null : names;
1463
+ },
1464
+ dmaParamNames: DMA_PARAM_ORDER,
1465
+ };
1466
+ const findings = auditIocKeys(coverage.weak, auditContext).filter((finding) => finding.verdict !== "ok");
1467
+ if (findings.length > 0) {
1468
+ warnings.push("[SCHEMA] " + String(findings.length) + " 个键名形状对但上下文不对:" +
1469
+ findings.slice(0, 5).map((finding) => finding.key + "(" + finding.detail + ")").join(";") +
1470
+ "——这种键 CubeMX 会静默忽略,改键名或补进 src/data/ioc-schema.ts");
1471
+ }
1472
+ }
1473
+ // R20 用的中断表就是上面那份(interrupts 参数校验时已经读过一次盘,这里复用)。
1474
+ const ruleReport = checkIocRules(after, { db: pinNames.db, facts: pinNames.facts, interrupts });
1475
+ for (const issue of ruleReport.errors)
1476
+ errors.push("[" + issue.rule + "] " + issue.message);
1477
+ for (const issue of ruleReport.warnings)
1478
+ warnings.push("[" + issue.rule + "] " + issue.message);
1479
+ // 重复键 / 跨行值:CubeMX 只认最后一个键值,而跨行值(Java properties 续行)改第一行会留下续行残骸。
1480
+ const planned = compareEntries(before, after);
1481
+ const multiLine = planned.filter((change) => diagnostics.multiLineKeys.has(change.key));
1482
+ if (multiLine.length > 0) {
1483
+ errors.push("这些键的值跨了多行(Java properties 的续行):" + multiLine.map((change) => change.key).join("、") +
1484
+ "。改第一行会留下续行残骸,请先在 CubeMX 里重新保存一次再改");
1485
+ }
1486
+ const duplicated = planned.filter((change) => diagnostics.duplicates.has(change.key));
1487
+ if (duplicated.length > 0) {
1488
+ errors.push("这些键在 .ioc 里出现了不止一次(CubeMX 只认最后一个):" +
1489
+ duplicated.map((change) => change.key + "×" + String(diagnostics.duplicates.get(change.key) ?? 0)).join("、") +
1490
+ "。先在 CubeMX 里重新保存一次把重复键清掉,再来改");
309
1491
  }
310
1492
  // 安全闸:这两条是踩过坑的硬约束,不满足就不给 plan。
311
- const candidateText = renderIocText(source, compareEntries(before, after));
1493
+ const candidateText = renderIocText(source, planned);
312
1494
  const summary = summarizeIoc(candidateText, iocPath);
313
1495
  if (!summary.debug.serialWire) {
314
1496
  errors.push("改完之后没有 Serial Wire 调试口(PA13/PA14):CubeMX 会生成 __HAL_AFIO_REMAP_SWJ_DISABLE(),烧录后 SWD 连不上。加 serialWire:true 让插件补上。");
@@ -319,7 +1501,7 @@ export function planIocChanges(request) {
319
1501
  if (errors.length > 0) {
320
1502
  return { ...empty, iocPath, sourceSha256, errors, warnings, notes, clockPlan, message: "没生成计划:" + errors[0] };
321
1503
  }
322
- const changes = compareEntries(before, after);
1504
+ const changes = planned;
323
1505
  if (changes.length === 0) {
324
1506
  return { ...empty, iocPath, sourceSha256, warnings, notes, clockPlan, message: "没有变化:这些键本来就是这个值" };
325
1507
  }
@@ -346,6 +1528,8 @@ export function planIocChanges(request) {
346
1528
  ok: true, projectDir, iocPath, planId, sourceSha256, candidateSha256,
347
1529
  changes, warnings, notes,
348
1530
  errors: [],
1531
+ dbVersion: pinNames.db?.version ?? "",
1532
+ dbRoot: pinNames.db?.root ?? "",
349
1533
  message: "已生成计划 " + planId + ":" + String(changes.length) + " 个键变化(新增 " + String(added) + "、删除 " + String(removedCount) + "、修改 " + String(changes.length - added - removedCount) + ")",
350
1534
  summaryAfter: summary,
351
1535
  clockPlan,