@turingcode/cli 0.3.4 → 0.3.6

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 (140) hide show
  1. package/dist/cli/create-cli.js +6 -4
  2. package/dist/cli/index.js +1 -1
  3. package/dist/core/exact/fraction.js +2 -0
  4. package/dist/core/files.js +2 -2
  5. package/dist/core/json-shape.js +1 -0
  6. package/dist/core/query.js +2 -2
  7. package/dist/core/tables/csv.d.ts +13 -2
  8. package/dist/core/tables/csv.js +54 -25
  9. package/dist/core/tables/markdown.js +8 -2
  10. package/dist/features/contract/diagnostics.d.ts +3 -0
  11. package/dist/features/contract/diagnostics.js +7 -4
  12. package/dist/features/contract/load.js +4 -4
  13. package/dist/features/contract/rules.d.ts +12 -0
  14. package/dist/features/contract/rules.js +31 -4
  15. package/dist/features/debug/clear_breakpoint.d.ts +1 -0
  16. package/dist/features/debug/clear_breakpoint.js +1 -1
  17. package/dist/features/debug/command.js +2 -2
  18. package/dist/features/debug/continue.d.ts +1 -0
  19. package/dist/features/debug/continue.js +2 -2
  20. package/dist/features/debug/debug_start.d.ts +1 -0
  21. package/dist/features/debug/debug_start.js +2 -2
  22. package/dist/features/debug/debug_stop.d.ts +1 -0
  23. package/dist/features/debug/debug_stop.js +1 -1
  24. package/dist/features/debug/evaluate.d.ts +1 -0
  25. package/dist/features/debug/evaluate.js +5 -5
  26. package/dist/features/debug/get_stack.d.ts +1 -0
  27. package/dist/features/debug/get_stack.js +1 -1
  28. package/dist/features/debug/get_variables.d.ts +1 -0
  29. package/dist/features/debug/get_variables.js +2 -2
  30. package/dist/features/debug/halt.d.ts +1 -0
  31. package/dist/features/debug/halt.js +1 -1
  32. package/dist/features/debug/set_breakpoint.d.ts +1 -0
  33. package/dist/features/debug/set_breakpoint.js +1 -1
  34. package/dist/features/debug/step.d.ts +1 -0
  35. package/dist/features/debug/step.js +2 -2
  36. package/dist/features/install-mods/install.js +4 -3
  37. package/dist/features/install-skills/install.d.ts +1 -0
  38. package/dist/features/install-skills/install.js +1 -1
  39. package/dist/features/probe/command.d.ts +1 -1
  40. package/dist/features/probe/command.js +103 -35
  41. package/dist/features/probe/kill_all_debuggers.d.ts +1 -0
  42. package/dist/features/probe/kill_all_debuggers.js +5 -5
  43. package/dist/features/probe/list_probes.d.ts +1 -0
  44. package/dist/features/probe/list_probes.js +1 -1
  45. package/dist/features/probe/program_project.d.ts +1 -0
  46. package/dist/features/probe/program_project.js +3 -3
  47. package/dist/features/probe/read_fault_status.d.ts +1 -0
  48. package/dist/features/probe/read_fault_status.js +1 -1
  49. package/dist/features/probe/read_memory.d.ts +1 -0
  50. package/dist/features/probe/read_memory.js +2 -2
  51. package/dist/features/probe/read_peripheral.d.ts +1 -0
  52. package/dist/features/probe/read_peripheral.js +7 -5
  53. package/dist/features/probe/reset_probe_usb.d.ts +1 -0
  54. package/dist/features/probe/reset_probe_usb.js +1 -1
  55. package/dist/features/probe/reset_target.d.ts +1 -0
  56. package/dist/features/probe/reset_target.js +1 -1
  57. package/dist/features/probe/target_info.d.ts +1 -0
  58. package/dist/features/probe/target_info.js +1 -1
  59. package/dist/features/project/analysis_static.d.ts +1 -0
  60. package/dist/features/project/analysis_static.js +1 -1
  61. package/dist/features/project/analysis_syntax_check.d.ts +1 -0
  62. package/dist/features/project/analysis_syntax_check.js +1 -1
  63. package/dist/features/project/command.js +3 -8
  64. package/dist/features/project/project_download_template.d.ts +1 -0
  65. package/dist/features/project/project_download_template.js +4 -4
  66. package/dist/features/project/project_sync_to_server.js +2 -2
  67. package/dist/features/project/stm32_cubetools_download_drivers.d.ts +1 -0
  68. package/dist/features/project/stm32_cubetools_download_drivers.js +2 -2
  69. package/dist/features/status/get_status.d.ts +1 -0
  70. package/dist/features/status/get_status.js +1 -1
  71. package/dist/features/table/check.js +5 -5
  72. package/dist/features/table/read.js +9 -9
  73. package/dist/features/tool/command.d.ts +2 -2
  74. package/dist/features/tool/command.js +95 -66
  75. package/dist/lib.d.ts +4 -0
  76. package/dist/lib.js +4 -2
  77. package/dist/stm32/actions/DebugAction.d.ts +4 -2
  78. package/dist/stm32/actions/DebugAction.js +6 -5
  79. package/dist/stm32/actions/DebugActionInfo.d.ts +4 -0
  80. package/dist/stm32/actions/DebugActionInfo.js +4 -2
  81. package/dist/stm32/actions/DebugActionListProbes.d.ts +1 -0
  82. package/dist/stm32/actions/DebugActionListProbes.js +1 -1
  83. package/dist/stm32/actions/DebugActionProgram.d.ts +8 -2
  84. package/dist/stm32/actions/DebugActionProgram.js +9 -7
  85. package/dist/stm32/actions/DebugActionRead.d.ts +8 -7
  86. package/dist/stm32/actions/DebugActionRead.js +5 -3
  87. package/dist/stm32/actions/DebugActionReset.d.ts +2 -1
  88. package/dist/stm32/actions/DebugActionReset.js +1 -1
  89. package/dist/stm32/actions/DebugActionServer.d.ts +4 -0
  90. package/dist/stm32/actions/DebugActionServer.js +4 -2
  91. package/dist/stm32/analysis.d.ts +1 -0
  92. package/dist/stm32/build.d.ts +4 -4
  93. package/dist/stm32/build.js +1 -1
  94. package/dist/stm32/context.js +2 -2
  95. package/dist/stm32/daemon.d.ts +8 -6
  96. package/dist/stm32/daemon.js +25 -18
  97. package/dist/stm32/regen.js +14 -8
  98. package/dist/stm32/session.d.ts +9 -6
  99. package/dist/stm32/session.js +11 -10
  100. package/dist/stm32/sync.d.ts +1 -0
  101. package/dist/stm32/sync.js +5 -3
  102. package/dist/stm32/tool.d.ts +5 -3
  103. package/dist/stm32/toolCommand.d.ts +4 -4
  104. package/dist/stm32/toolCommand.js +1 -3
  105. package/dist/stm32/utils/discover_tools.d.ts +2 -1
  106. package/dist/stm32/utils/discover_tools.js +1 -1
  107. package/dist/stm32/utils/downloadzip_utils.js +4 -4
  108. package/dist/stm32/utils/faultUtils.d.ts +2 -1
  109. package/dist/stm32/utils/faultUtils.js +2 -2
  110. package/dist/stm32/utils/findElf.d.ts +1 -1
  111. package/dist/stm32/utils/findElf.js +1 -1
  112. package/dist/stm32/utils/listSyncFiles.js +12 -10
  113. package/dist/stm32/utils/mcu_utils.d.ts +5 -6
  114. package/dist/stm32/utils/mcu_utils.js +10 -9
  115. package/dist/stm32/utils/project_utils.d.ts +1 -1
  116. package/dist/stm32/utils/project_utils.js +5 -3
  117. package/dist/stm32/utils/usb_utils.js +2 -2
  118. package/dist/stm32/utils/user_code.d.ts +4 -1
  119. package/dist/stm32/utils/user_code.js +5 -3
  120. package/dist/stm32/utils/utils_mutex.js +34 -14
  121. package/dist/stm32/validate.d.ts +1 -0
  122. package/dist/stm32/validate.js +1 -1
  123. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +19 -23
  124. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +71 -23
  125. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/M_StatusEnum.md +33 -0
  126. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/app-startup.md +49 -0
  127. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/driver.md +103 -0
  128. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/host-protocol.md +48 -0
  129. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +24 -23
  130. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/storage.md +140 -0
  131. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/tasks-and-interrupts.md +66 -0
  132. package/package.json +4 -1
  133. package/dist/features/project/project_build.d.ts +0 -2
  134. package/dist/features/project/project_build.js +0 -22
  135. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/board-and-debug.md +0 -22
  136. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/build-and-check.md +0 -19
  137. package/mods/claude/turingcode-skills/skills/turingcode-cli/references/new-project.md +0 -9
  138. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +0 -42
  139. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +0 -35
  140. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +0 -34
@@ -36,7 +36,7 @@ export function createCli(args) {
36
36
  "- Tables: check Markdown or CSV tables against a contract (a JSON file of tables, columns and",
37
37
  " MongoDB-style checks): `contract describe` shows the tables to write; `table check` until PASS.",
38
38
  " Contract format: $0 contract --help.",
39
- "- STM32 projects: `project sync`, `project build` on the server, `probe program` to flash the board,",
39
+ "- STM32 projects: `project sync -b` to build on the server, `probe program` to flash the board,",
40
40
  " `probe read` and `probe peripheral` to inspect it, `debug start` ... `debug stop` for a live debug",
41
41
  " session; `status` shows the project and the installed debug tools.",
42
42
  "- Agent skills: `install-skills` copies them into ~/.agents/skills (Codex, OpenCode);",
@@ -50,13 +50,15 @@ export function createCli(args) {
50
50
  .hide("version")
51
51
  .wrap(null)
52
52
  .exitProcess(false)
53
- // yargs passes a message for argument errors (validation, coerce, check) and none when a
54
- // command's handler threw; a handler error keeps its own exit code.
53
+ /**
54
+ * yargs passes a message for argument errors (validation, coerce, check) and none when a
55
+ * command's handler threw; a handler error keeps its own exit code.
56
+ */
55
57
  .fail((message, error) => {
56
58
  if (!message && error)
57
59
  throw error;
58
60
  throw Object.assign(error ?? new Error(message), { exitCode: BAD_ARGUMENTS });
59
61
  });
60
- // Type tags such as [string] add tokens without information; the typings lack this yargs 17.7 method.
62
+ /** Type tags such as [string] add tokens without information; the typings lack this yargs 17.7 method. */
61
63
  return cli.usageConfiguration({ "hide-types": true });
62
64
  }
package/dist/cli/index.js CHANGED
@@ -16,7 +16,7 @@ export async function main(args = hideBin(process.argv)) {
16
16
  }
17
17
  catch (error) {
18
18
  process.exitCode = error.exitCode ?? 1;
19
- // the usage hint only helps with bad arguments, not after a failed request or a stopped regen
19
+ /** the usage hint only helps with bad arguments, not after a failed request or a stopped regen */
20
20
  const hint = process.exitCode === 2 ? `Run "turingcode <command> --help" for usage.\n` : "";
21
21
  process.stderr.write(`turingcode: ${error.message}\n${hint}`);
22
22
  }
@@ -168,6 +168,7 @@ export class Fraction {
168
168
  toDecimal(places = 10) {
169
169
  let d = this.d;
170
170
  let digits = 0;
171
+ /** A fraction terminates in decimal only when its denominator has no prime factors other than 2 and 5. */
171
172
  for (const p of [2n, 5n])
172
173
  while (d % p === 0n)
173
174
  d /= p;
@@ -180,6 +181,7 @@ export class Fraction {
180
181
  }
181
182
  }
182
183
  const k = exact ? digits : places;
184
+ /** Round half up: add half the denominator before dividing. */
183
185
  const scaled = (abs(this.n) * 10n ** BigInt(k) * 2n + this.d) / (this.d * 2n);
184
186
  const s = scaled.toString().padStart(k + 1, "0");
185
187
  const text = k ? `${s.slice(0, -k)}.${s.slice(-k)}` : s;
@@ -80,12 +80,12 @@ export function readJsonArg(value) {
80
80
  let text = value;
81
81
  if (!/^\s*[{[]/.test(value)) {
82
82
  try {
83
- text = readFileSync(value, "utf-8");
83
+ text = readFileSync(value, "utf-8").replace(/^/, "");
84
84
  }
85
85
  catch (e) {
86
86
  if (e.code !== "ENOENT")
87
87
  throw e;
88
- // A value shaped like a path is most likely a mistyped path, so say that instead of talking about JSON.
88
+ /** A value shaped like a path is most likely a mistyped path, so say that instead of talking about JSON. */
89
89
  if (/\.json$|[/\\]/i.test(value))
90
90
  throw new Error(`no such file: '${value}'`);
91
91
  throw new Error(`'${value}' is neither inline JSON (starting with {) nor an existing .json file`);
@@ -78,6 +78,7 @@ export function checkShape(value, shape, path) {
78
78
  }
79
79
  else {
80
80
  const obj = value;
81
+ /** Optional keys are declared with a trailing '?'; keep the original key to read its shape. */
81
82
  const keys = new Map(Object.keys(shape.obj).map(k => [k.replace(/\?$/, ""), k]));
82
83
  for (const [name, key] of keys) {
83
84
  if (obj[name] === undefined) {
@@ -92,7 +92,7 @@ export function prepareQuery(query) {
92
92
  out[op] = ops(arg, here);
93
93
  }
94
94
  else {
95
- // $every, $length: a query on each item / on the length, tested on the placeholder column.
95
+ /** $every, $length: a query on each item / on the length, tested on the placeholder column. */
96
96
  out[op] = field(ITEM, arg, here);
97
97
  }
98
98
  }
@@ -216,7 +216,7 @@ export function compileQuery(query, hooks) {
216
216
  return n !== null && test({ [ITEM]: String(n) });
217
217
  })(o, opt);
218
218
  },
219
- // ponytail: remembers every value it has seen; fine for one pass over a table's rows.
219
+ /** ponytail: remembers every value it has seen; fine for one pass over a table's rows. */
220
220
  $unique: (param, o, opt) => {
221
221
  const seen = new Set();
222
222
  return eq((v, k, own) => {
@@ -1,12 +1,23 @@
1
- import { TablesDoc } from "./types.js";
1
+ import { ParsedTable, TablesDoc } from "./types.js";
2
2
  /**
3
3
  * Parses CSV text (RFC 4180: quoted fields, doubled quotes, CRLF).
4
4
  *
5
5
  * @param {string} text - The CSV text.
6
+ * @param {number[]} [lines] - Filled with each returned record's 1-based starting line.
6
7
  * @returns {string[][]} Records; fields are not trimmed.
7
8
  * @throws {Error} On an unterminated quoted field.
8
9
  */
9
- export declare function parseCsv(text: string): string[][];
10
+ export declare function parseCsv(text: string, lines?: number[]): string[][];
11
+ /**
12
+ * Reads one `<Table>.csv` file's text as a table named after the file.
13
+ *
14
+ * @param {string} file - The file name, for the table name and messages.
15
+ * @param {string} text - The file's text.
16
+ * @param {number} maxRows - `bounds.max_table_rows`.
17
+ * @returns {ParsedTable | string} The table, or why it is malformed.
18
+ * @throws {BoundError} When the table has more than maxRows rows.
19
+ */
20
+ export declare function parseCsvTable(file: string, text: string, maxRows: number): ParsedTable | string;
10
21
  /**
11
22
  * Reads a folder of CSV tables: holding one `<Table>.csv` per table.
12
23
  *
@@ -5,14 +5,29 @@ import { BoundError } from "../bound-error.js";
5
5
  * Parses CSV text (RFC 4180: quoted fields, doubled quotes, CRLF).
6
6
  *
7
7
  * @param {string} text - The CSV text.
8
+ * @param {number[]} [lines] - Filled with each returned record's 1-based starting line.
8
9
  * @returns {string[][]} Records; fields are not trimmed.
9
10
  * @throws {Error} On an unterminated quoted field.
10
11
  */
11
- export function parseCsv(text) {
12
+ export function parseCsv(text, lines = []) {
12
13
  const records = [];
13
14
  let record = [];
14
15
  let field = "";
15
16
  let quoted = false;
17
+ let hadQuote = false;
18
+ let line = 1;
19
+ let start = 1;
20
+ /** Ends the record; a blank line (one empty unquoted field) is dropped. */
21
+ const endRecord = () => {
22
+ record.push(field);
23
+ if (hadQuote || record.length > 1 || field !== "") {
24
+ records.push(record);
25
+ lines.push(start);
26
+ }
27
+ record = [];
28
+ field = "";
29
+ hadQuote = false;
30
+ };
16
31
  const src = text.replace(/^/, "");
17
32
  for (let i = 0; i < src.length; i++) {
18
33
  const ch = src[i];
@@ -25,11 +40,14 @@ export function parseCsv(text) {
25
40
  quoted = false;
26
41
  }
27
42
  else {
43
+ if (ch === "\n" || (ch === "\r" && src[i + 1] !== "\n"))
44
+ line++;
28
45
  field += ch;
29
46
  }
30
47
  }
31
48
  else if (ch === '"' && field === "") {
32
49
  quoted = true;
50
+ hadQuote = true;
33
51
  }
34
52
  else if (ch === ",") {
35
53
  record.push(field);
@@ -38,10 +56,8 @@ export function parseCsv(text) {
38
56
  else if (ch === "\n" || ch === "\r") {
39
57
  if (ch === "\r" && src[i + 1] === "\n")
40
58
  i++;
41
- record.push(field);
42
- records.push(record);
43
- record = [];
44
- field = "";
59
+ endRecord();
60
+ start = ++line;
45
61
  }
46
62
  else {
47
63
  field += ch;
@@ -49,11 +65,35 @@ export function parseCsv(text) {
49
65
  }
50
66
  if (quoted)
51
67
  throw new Error("unterminated quoted field");
52
- if (field !== "" || record.length) {
53
- record.push(field);
54
- records.push(record);
68
+ if (field !== "" || record.length || hadQuote)
69
+ endRecord();
70
+ return records;
71
+ }
72
+ /**
73
+ * Reads one `<Table>.csv` file's text as a table named after the file.
74
+ *
75
+ * @param {string} file - The file name, for the table name and messages.
76
+ * @param {string} text - The file's text.
77
+ * @param {number} maxRows - `bounds.max_table_rows`.
78
+ * @returns {ParsedTable | string} The table, or why it is malformed.
79
+ * @throws {BoundError} When the table has more than maxRows rows.
80
+ */
81
+ export function parseCsvTable(file, text, maxRows) {
82
+ const name = basename(file, file.slice(-4));
83
+ const lines = [];
84
+ let records;
85
+ try {
86
+ records = parseCsv(text, lines);
55
87
  }
56
- return records.filter(r => !(r.length === 1 && r[0] === ""));
88
+ catch (e) {
89
+ return `${file}: ${e.message}`;
90
+ }
91
+ if (!records.length)
92
+ return `${file}: no header row`;
93
+ const rows = records.slice(1).map(r => r.map(c => c.trim()));
94
+ if (rows.length > maxRows)
95
+ throw new BoundError("max_table_rows", maxRows);
96
+ return { name, header: records[0].map(c => c.trim()), rows, rowLines: lines.slice(1) };
57
97
  }
58
98
  /**
59
99
  * Reads a folder of CSV tables: holding one `<Table>.csv` per table.
@@ -71,22 +111,11 @@ export function parseCsvFolder(dir, maxRows) {
71
111
  const name = basename(file, file.slice(-4));
72
112
  const text = readFileSync(join(dir, file), "utf-8");
73
113
  texts.set(name, text);
74
- let records;
75
- try {
76
- records = parseCsv(text);
77
- }
78
- catch (e) {
79
- malformed.push([name, `${file}: ${e.message}`]);
80
- continue;
81
- }
82
- if (!records.length) {
83
- malformed.push([name, `${file}: no header row`]);
84
- continue;
85
- }
86
- const rows = records.slice(1).map(r => r.map(c => c.trim()));
87
- if (rows.length > maxRows)
88
- throw new BoundError("max_table_rows", maxRows);
89
- tables.set(name, { name, header: records[0].map(c => c.trim()), rows, rowLines: rows.map((_, k) => k + 2) });
114
+ const table = parseCsvTable(file, text, maxRows);
115
+ if (typeof table === "string")
116
+ malformed.push([name, table]);
117
+ else
118
+ tables.set(name, table);
90
119
  }
91
120
  return {
92
121
  tables, duplicates: [], malformed, text: [...texts.values()].join("\n"),
@@ -1,6 +1,6 @@
1
1
  import { BoundError } from "../bound-error.js";
2
2
  const SEPARATOR = /^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
3
- const HEADING = /^##\s+(.+?)\s*#*\s*$/;
3
+ const HEADING = /^##\s+(.+?)(?:\s+#+)?\s*$/;
4
4
  /**
5
5
  * Splits one Markdown table line into trimmed cells; `\|` is a literal pipe.
6
6
  *
@@ -49,9 +49,11 @@ export function parseMarkdown(text, maxRows) {
49
49
  const tables = new Map();
50
50
  const duplicates = [];
51
51
  const malformed = [];
52
- /** [table name, first line index, end line index (exclusive)] of every pipe-table block. */
52
+ /** [table name, first line index, end line index (exclusive)] of each section's pipe-table block. */
53
53
  const blocks = [];
54
54
  let section = null;
55
+ /** The current section already had its pipe table; later ones are ignored. */
56
+ let taken = false;
55
57
  let fenced = false;
56
58
  for (let i = 0; i < lines.length; i++) {
57
59
  const line = lines[i];
@@ -64,6 +66,7 @@ export function parseMarkdown(text, maxRows) {
64
66
  const heading = HEADING.exec(line);
65
67
  if (heading || /^#\s/.test(line)) {
66
68
  section = heading ? heading[1] : null;
69
+ taken = false;
67
70
  continue;
68
71
  }
69
72
  if (section === null || !line.trim().startsWith("|"))
@@ -71,6 +74,9 @@ export function parseMarkdown(text, maxRows) {
71
74
  const start = i;
72
75
  while (i + 1 < lines.length && lines[i + 1].trim().startsWith("|"))
73
76
  i++;
77
+ if (taken)
78
+ continue;
79
+ taken = true;
74
80
  const block = lines.slice(start, i + 1);
75
81
  blocks.push([section, start, i + 1]);
76
82
  if (tables.has(section) || malformed.some(([n]) => n === section)) {
@@ -24,6 +24,7 @@ export interface Alternative {
24
24
  }
25
25
  /** Every code, with its fix hint. */
26
26
  declare const HINTS: {
27
+ /** Contract problems (contract check, and table check before it starts). */
27
28
  readonly "CONTRACT.BAD_JSON": "Fix the JSON syntax of the contract file.";
28
29
  readonly "CONTRACT.BAD_FIELD": "Give the field the type or value named in 'expected'; remove unknown fields.";
29
30
  readonly "CONTRACT.BAD_REGEX": "Write a valid JavaScript regular expression.";
@@ -35,6 +36,7 @@ declare const HINTS: {
35
36
  readonly "CONTRACT.CONFLICT": "Make the settings agree (e.g. minimum <= maximum, constraint fits the type).";
36
37
  readonly "CONTRACT.CYCLE": "Remove the circular depends_on.";
37
38
  readonly "CONTRACT.MISSING_FILE": "Check the path; the file must exist and be readable.";
39
+ /** Problems in the tables (table check). */
38
40
  readonly MISSING_TABLE: "Add the table under a '## <name>' heading (Markdown) or as <name>.csv.";
39
41
  readonly EXTRA_TABLE: "Remove the table, or declare it in the contract.";
40
42
  readonly DUPLICATE_TABLE: "Write each table once.";
@@ -60,6 +62,7 @@ declare const HINTS: {
60
62
  readonly NOT_MENTIONED: "Mention the value where the rule says.";
61
63
  readonly MATCH: "Correct the row so it matches the rule's query (shown in 'expected').";
62
64
  readonly NONE_OF: "Make the value meet one of the alternatives in 'expected'.";
65
+ /** Inputs. */
63
66
  readonly MISSING_FILE: "Check the path; the file must exist and be readable.";
64
67
  readonly MISSING_DEPENDENCY: "Pass the dependency's tables with --dep <alias>=<file>.";
65
68
  readonly TOO_LARGE: "Split the table; it exceeds the row limit.";
@@ -1,6 +1,6 @@
1
1
  /** Every code, with its fix hint. */
2
2
  const HINTS = {
3
- // Contract problems (contract check, and table check before it starts).
3
+ /** Contract problems (contract check, and table check before it starts). */
4
4
  "CONTRACT.BAD_JSON": "Fix the JSON syntax of the contract file.",
5
5
  "CONTRACT.BAD_FIELD": "Give the field the type or value named in 'expected'; remove unknown fields.",
6
6
  "CONTRACT.BAD_REGEX": "Write a valid JavaScript regular expression.",
@@ -12,7 +12,7 @@ const HINTS = {
12
12
  "CONTRACT.CONFLICT": "Make the settings agree (e.g. minimum <= maximum, constraint fits the type).",
13
13
  "CONTRACT.CYCLE": "Remove the circular depends_on.",
14
14
  "CONTRACT.MISSING_FILE": "Check the path; the file must exist and be readable.",
15
- // Problems in the tables (table check).
15
+ /** Problems in the tables (table check). */
16
16
  "MISSING_TABLE": "Add the table under a '## <name>' heading (Markdown) or as <name>.csv.",
17
17
  "EXTRA_TABLE": "Remove the table, or declare it in the contract.",
18
18
  "DUPLICATE_TABLE": "Write each table once.",
@@ -38,7 +38,7 @@ const HINTS = {
38
38
  "NOT_MENTIONED": "Mention the value where the rule says.",
39
39
  "MATCH": "Correct the row so it matches the rule's query (shown in 'expected').",
40
40
  "NONE_OF": "Make the value meet one of the alternatives in 'expected'.",
41
- // Inputs.
41
+ /** Inputs. */
42
42
  "MISSING_FILE": "Check the path; the file must exist and be readable.",
43
43
  "MISSING_DEPENDENCY": "Pass the dependency's tables with --dep <alias>=<file>.",
44
44
  "TOO_LARGE": "Split the table; it exceeds the row limit.",
@@ -94,7 +94,10 @@ export function formatDiagnostics(diags) {
94
94
  const groups = new Map();
95
95
  for (const d of diags) {
96
96
  const key = [d.severity, d.code, d.table, d.column, d.expected, d.rule, branchCodes(d)].join("\u0000");
97
- groups.set(key, [...(groups.get(key) ?? []), d]);
97
+ let g = groups.get(key);
98
+ if (!g)
99
+ groups.set(key, g = []);
100
+ g.push(d);
98
101
  }
99
102
  for (const [d, ...more] of groups.values()) {
100
103
  const rule = d.rule ? ` [${d.rule}]` : "";
@@ -60,7 +60,7 @@ export function validateContract(data, deps) {
60
60
  if (shapeIssues.length)
61
61
  return out;
62
62
  const c = data;
63
- // Checked here, not by the shape: the "string" shape rejects "", the most common missing value.
63
+ /** Checked here, not by the shape: the "string" shape rejects "", the most common missing value. */
64
64
  for (const v of c.missing_values ?? []) {
65
65
  if (typeof v !== "string")
66
66
  out.push(diag("CONTRACT.BAD_FIELD", "missing_values must be strings", { column: "missing_values" }, show(v), "a string"));
@@ -93,7 +93,7 @@ export function validateContract(data, deps) {
93
93
  }
94
94
  target = deps.get(alias)?.contract ?? null;
95
95
  if (!target)
96
- return null; // the dependency's own problems are reported with it
96
+ return null; /** the dependency's own problems are reported with it */
97
97
  }
98
98
  const table = target.tables.find(t => t.name === name);
99
99
  if (table)
@@ -178,7 +178,7 @@ export function loadContract(path, out, stack = []) {
178
178
  const full = resolve(path);
179
179
  const loaded = { path, label: basename(path), contract: null, deps: new Map() };
180
180
  const own = [];
181
- // Findings in a dependency name it; findings in the checked contract need no prefix.
181
+ /** Findings in a dependency name it; findings in the checked contract need no prefix. */
182
182
  const publish = () => out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
183
183
  const file = readJsonFile(path);
184
184
  if (!file.ok) {
@@ -196,7 +196,7 @@ export function loadContract(path, out, stack = []) {
196
196
  const dependsOn = data && typeof data === "object" && data.depends_on && typeof data.depends_on === "object" ? data.depends_on : {};
197
197
  for (const [alias, rel] of Object.entries(dependsOn)) {
198
198
  if (typeof rel !== "string")
199
- continue; // reported by the shape check
199
+ continue; /** reported by the shape check */
200
200
  const depPath = resolve(dirname(path), rel);
201
201
  if ([...stack, full].includes(depPath)) {
202
202
  own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
@@ -60,6 +60,18 @@ export declare const valueText: (v: Value | undefined) => string;
60
60
  * @returns {boolean} True when mentioned.
61
61
  */
62
62
  export declare function mentions(text: string, word: string): boolean;
63
+ /**
64
+ * Prepares `mentions` for many values over one text. A value of up to MAX_TOKEN_RUNS word runs
65
+ * joined by single `-` (e.g. `R-12`) is looked up in the text's tokens: every such sequence of runs
66
+ * in the text that is not followed by `-<digit>`. Anything else uses `mentions`.
67
+ *
68
+ * @param {string} text - Text to search.
69
+ * @returns {(word: string) => boolean} Whether a value is mentioned, as `mentions(text, word)`.
70
+ *
71
+ * @example
72
+ * mentionTester("see R-12-3")("12-3"); // true; ("R-12") is false
73
+ */
74
+ export declare function mentionTester(text: string): (word: string) => boolean;
63
75
  /** Number columns of a table: the names a `$calc` expression may use. */
64
76
  export declare const numberColumns: (t: Table) => Set<string>;
65
77
  /** A parsed `$calc`: `"Qty * Price == Total"` or `{"expr": "...", "tolerance": 0.01}`. */
@@ -23,6 +23,33 @@ export function mentions(text, word) {
23
23
  const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24
24
  return new RegExp(`(?<![A-Za-z0-9_])${escaped}(?![A-Za-z0-9_]|-\\d)`).test(text);
25
25
  }
26
+ /** Most `-`-joined word runs a value may have to be answered from the token set. */
27
+ const MAX_TOKEN_RUNS = 8;
28
+ /**
29
+ * Prepares `mentions` for many values over one text. A value of up to MAX_TOKEN_RUNS word runs
30
+ * joined by single `-` (e.g. `R-12`) is looked up in the text's tokens: every such sequence of runs
31
+ * in the text that is not followed by `-<digit>`. Anything else uses `mentions`.
32
+ *
33
+ * @param {string} text - Text to search.
34
+ * @returns {(word: string) => boolean} Whether a value is mentioned, as `mentions(text, word)`.
35
+ *
36
+ * @example
37
+ * mentionTester("see R-12-3")("12-3"); // true; ("R-12") is false
38
+ */
39
+ export function mentionTester(text) {
40
+ const tokens = new Set();
41
+ for (const chain of text.matchAll(/[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)*/g)) {
42
+ const runs = chain[0].split("-");
43
+ for (let i = 0; i < runs.length; i++) {
44
+ for (let j = i; j < Math.min(runs.length, i + MAX_TOKEN_RUNS); j++) {
45
+ if (!/^\d/.test(runs[j + 1] ?? ""))
46
+ tokens.add(runs.slice(i, j + 1).join("-"));
47
+ }
48
+ }
49
+ }
50
+ const token = new RegExp(`^[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+){0,${MAX_TOKEN_RUNS - 1}}$`);
51
+ return word => (token.test(word) ? tokens.has(word) : mentions(text, word));
52
+ }
26
53
  /** Number columns of a table: the names a `$calc` expression may use. */
27
54
  export const numberColumns = (t) => new Set(t.columns.filter(c => c.type === "integer" || c.type === "number").map(c => c.name));
28
55
  /**
@@ -48,7 +75,7 @@ export function parseCalc(param, allowed) {
48
75
  if (!tolerance || tolerance.cmp(new Fraction(0n)) < 0)
49
76
  return "tolerance must be a number >= 0";
50
77
  try {
51
- // Parse with every identifier allowed, then say which ones are not number columns.
78
+ /** Parse with every identifier allowed, then say which ones are not number columns. */
52
79
  const names = new Set(text.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? []);
53
80
  const left = parseExpression(l, MAX_EXPRESSION_NODES, names);
54
81
  const right = parseExpression(r, MAX_EXPRESSION_NODES, names);
@@ -87,7 +114,7 @@ export function evaluateCalc(c, doc, numbers) {
87
114
  return { left, right, holds };
88
115
  }
89
116
  catch {
90
- return null; // e.g. division by zero with these values: nothing to compare
117
+ return null; /** e.g. division by zero with these values: nothing to compare */
91
118
  }
92
119
  }
93
120
  /**
@@ -166,7 +193,7 @@ export function explain(part, doc, hooks) {
166
193
  found: cols.map(c => valueText(doc[c])).join(" / "), expected: "a unique combination" };
167
194
  }
168
195
  if (key === "$or" || key === "$and") {
169
- // The first failing part of each branch: all of them for $or, the first failing branch for $and.
196
+ /** The first failing part of each branch: all of them for $or, the first failing branch for $and. */
170
197
  const failures = arg.flatMap(branch => {
171
198
  const failing = splitQuery(branch).find(p => !queryTester(p, hooks)(doc));
172
199
  return failing ? [explain(failing, doc, hooks)] : [];
@@ -278,7 +305,7 @@ function explainCondition(column, cond, value, hooks) {
278
305
  break;
279
306
  }
280
307
  case "$every": {
281
- // Explain with the first failing item, against the item condition.
308
+ /** Explain with the first failing item, against the item condition. */
282
309
  const inner = isObject(arg) && Object.keys(arg).length === 1 ? arg : null;
283
310
  if (!inner)
284
311
  break;
@@ -1,2 +1,3 @@
1
+ /** Removes source breakpoints from the debug session. */
1
2
  declare const _default: import("../../stm32/tool.js").ToolDef;
2
3
  export default _default;
@@ -1,6 +1,6 @@
1
1
  import { _defineTool } from '../../stm32/tool.js';
2
2
  import { getSession, projectFile, syncBreakpoints } from '../../stm32/session.js';
3
- // Removes source breakpoints from the debug session.
3
+ /** Removes source breakpoints from the debug session. */
4
4
  export default _defineTool({
5
5
  name: 'clear_breakpoint',
6
6
  description: 'Remove a source breakpoint from the debug session. Without line, removes every breakpoint in the file; without file, removes all breakpoints.',
@@ -42,7 +42,7 @@ const subcommands = [
42
42
  toolCommand({ command: "vars", tool: getVariables, mode: "session", examples: [["$0 debug vars --frame 1", "locals of the caller's frame"]] }),
43
43
  toolCommand({ command: "eval", tool: evaluate, mode: "session", examples: [["$0 debug eval --expr 'count, cfg.mode, buf[2]'", "several expressions"]] }),
44
44
  ];
45
- // Hidden: the background process `debug start` launches in the project folder.
45
+ /** Hidden: the background process `debug start` launches in the project folder. */
46
46
  const daemon = {
47
47
  command: "daemon",
48
48
  describe: false,
@@ -58,7 +58,7 @@ const command = {
58
58
  "`debug start` launches a background daemon for the project that holds the probe-rs session; the other",
59
59
  "debug commands talk to it, so the session lives across runs until `debug stop` (the daemon then exits).",
60
60
  "Its files are in .turingcode/ (daemon.token, daemon.log, probe.lock). Needs probe-rs and a .elf in build/",
61
- "(`project build`). Breakpoint files are project-relative paths, e.g. Core/Src/main.c.",
61
+ "(`project sync -b`). Breakpoint files are project-relative paths, e.g. Core/Src/main.c.",
62
62
  PROJECT_HELP,
63
63
  ].join("\n")),
64
64
  handler: () => { },
@@ -1,2 +1,3 @@
1
+ /** Resumes the target, optionally waiting for it to stop again. */
1
2
  declare const _default: import("../../stm32/tool.js").ToolDef;
2
3
  export default _default;
@@ -1,6 +1,6 @@
1
1
  import { _defineTool } from '../../stm32/tool.js';
2
2
  import { getSession } from '../../stm32/session.js';
3
- // Resumes the target, optionally waiting for it to stop again.
3
+ /** Resumes the target, optionally waiting for it to stop again. */
4
4
  export default _defineTool({
5
5
  name: 'continue',
6
6
  description: 'Resume the target in the debug session. With wait > 0, waits up to that many seconds for it to stop (e.g. at a breakpoint) and reports where.',
@@ -9,7 +9,7 @@ export default _defineTool({
9
9
  const s = getSession();
10
10
  s.requireHalted();
11
11
  const stopped = s.waitEvent('stopped', (args.wait ?? 0) * 1000);
12
- // Set before the request: the stopped event of a short run can arrive before its response
12
+ /** Set before the request: the stopped event of a short run can arrive before its response */
13
13
  s.state = 'running';
14
14
  await s.request('continue', { threadId: s.threadId }).catch((e) => {
15
15
  s.state = 'halted';
@@ -1,2 +1,3 @@
1
+ /** Starts a probe-rs debug session on the project's board. */
1
2
  declare const _default: import("../../stm32/tool.js").ToolDef;
2
3
  export default _default;
@@ -3,7 +3,7 @@ import { findStm32Project } from '../../stm32/utils/project_utils.js';
3
3
  import { startSession } from '../../stm32/session.js';
4
4
  import { findElf } from '../../stm32/utils/findElf.js';
5
5
  import { getMcuFromIoc } from '../../stm32/utils/mcu_utils.js';
6
- // Starts a probe-rs debug session on the project's board.
6
+ /** Starts a probe-rs debug session on the project's board. */
7
7
  export default _defineTool({
8
8
  name: 'debug_start',
9
9
  description: "Start a probe-rs debug session on the project's board using the newest .elf in build/. By default it attaches to the running firmware (which must match that .elf); with flash=true it flashes the .elf first and halts after reset, so breakpoints can be set before continue. Takes ownership of the probe until `turingcode debug stop`.",
@@ -13,7 +13,7 @@ export default _defineTool({
13
13
  const project = await findStm32Project();
14
14
  const elf = await findElf(project.root);
15
15
  if (!elf)
16
- throw new Error("No .elf in the project's build/ folder: run `turingcode project build` first");
16
+ throw new Error("No .elf in the project's build/ folder: run `turingcode project sync -b` first");
17
17
  const chip = await getMcuFromIoc(project.root);
18
18
  const flash = args.flash === true;
19
19
  const s = await startSession({ root: project.root, chip, elf: elf.path, flash });
@@ -1,2 +1,3 @@
1
+ /** Ends the probe-rs debug session; the target keeps running. */
1
2
  declare const _default: import("../../stm32/tool.js").ToolDef;
2
3
  export default _default;
@@ -1,6 +1,6 @@
1
1
  import { _defineTool } from '../../stm32/tool.js';
2
2
  import { getSession } from '../../stm32/session.js';
3
- // Ends the probe-rs debug session; the target keeps running.
3
+ /** Ends the probe-rs debug session; the target keeps running. */
4
4
  export default _defineTool({
5
5
  name: 'debug_stop',
6
6
  description: 'Stop the debug session and release the probe. Breakpoints are removed and the target keeps running.',
@@ -1,2 +1,3 @@
1
+ /** Evaluates one or more comma-separated expressions in a frame of the halted target. */
1
2
  declare const _default: import("../../stm32/tool.js").ToolDef;
2
3
  export default _default;
@@ -1,10 +1,10 @@
1
1
  import { _defineTool } from '../../stm32/tool.js';
2
2
  import { frameId, getSession } from '../../stm32/session.js';
3
- // Assignments, increments and calls could change the target; comparisons (==, !=, <=, >=) are allowed.
3
+ /** Assignments, increments and calls could change the target; comparisons (==, !=, <=, >=) are allowed. */
4
4
  const SIDE_EFFECTS = /=|\+\+|--|[A-Za-z_]\w*\s*\(|[;{}]/;
5
- // Checked before comparisons are removed: removing the "<=" of "<<=" would leave no "=".
5
+ /** Checked before comparisons are removed: removing the "<=" of "<<=" would leave no "=". */
6
6
  const SHIFT_ASSIGN = /<<=|>>=/;
7
- // Evaluates one or more comma-separated expressions in a frame of the halted target.
7
+ /** Evaluates one or more comma-separated expressions in a frame of the halted target. */
8
8
  export default _defineTool({
9
9
  name: 'evaluate',
10
10
  description: 'Evaluate side-effect-free expressions (variable, member, element; no assignments or calls) ' +
@@ -15,7 +15,7 @@ export default _defineTool({
15
15
  },
16
16
  required: ['expr'],
17
17
  run: async (args) => {
18
- // Splitting on commas is safe: in C they only appear as the comma operator or in calls, and calls are refused.
18
+ /** Splitting on commas is safe: in C they only appear as the comma operator or in calls, and calls are refused. */
19
19
  const exprs = args.expr
20
20
  .split(',')
21
21
  .map((e) => e.trim())
@@ -37,7 +37,7 @@ export default _defineTool({
37
37
  lines.push(`${e} = ${r.result}${r.type ? ` (${r.type})` : ''}`);
38
38
  }
39
39
  catch (err) {
40
- // One bad expression should not hide the others' values.
40
+ /** One bad expression should not hide the others' values. */
41
41
  if (exprs.length === 1)
42
42
  throw err;
43
43
  lines.push(`${e}: ${err instanceof Error ? err.message : err}`);
@@ -1,2 +1,3 @@
1
+ /** Lists the call stack of the halted target. */
1
2
  declare const _default: import("../../stm32/tool.js").ToolDef;
2
3
  export default _default;
@@ -1,6 +1,6 @@
1
1
  import { _defineTool } from '../../stm32/tool.js';
2
2
  import { getSession } from '../../stm32/session.js';
3
- // Lists the call stack of the halted target.
3
+ /** Lists the call stack of the halted target. */
4
4
  export default _defineTool({
5
5
  name: 'get_stack',
6
6
  description: 'Call stack of the halted target in the debug session (frame 0 = innermost), with source file and line.',
@@ -1,2 +1,3 @@
1
+ /** Lists the local variables of a stack frame. */
1
2
  declare const _default: import("../../stm32/tool.js").ToolDef;
2
3
  export default _default;