@toiroakr/chisel 0.1.0 → 0.3.0

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 (191) hide show
  1. package/README.md +354 -21
  2. package/dist/absence.d.ts +28 -0
  3. package/dist/absence.js +266 -0
  4. package/dist/absence.js.map +1 -0
  5. package/dist/behavior.d.ts +26 -19
  6. package/dist/behavior.js +193 -203
  7. package/dist/behavior.js.map +1 -1
  8. package/dist/beside.d.ts +5 -0
  9. package/dist/beside.js +10 -0
  10. package/dist/beside.js.map +1 -1
  11. package/dist/border.d.ts +7 -8
  12. package/dist/border.js +88 -36
  13. package/dist/border.js.map +1 -1
  14. package/dist/bounds.d.ts +1 -0
  15. package/dist/bounds.js +27 -0
  16. package/dist/bounds.js.map +1 -0
  17. package/dist/changes.d.ts +23 -0
  18. package/dist/changes.js +355 -0
  19. package/dist/changes.js.map +1 -0
  20. package/dist/checks.d.ts +1 -0
  21. package/dist/checks.js +295 -0
  22. package/dist/checks.js.map +1 -0
  23. package/dist/cli.d.ts +4 -0
  24. package/dist/cli.js +351 -14
  25. package/dist/cli.js.map +1 -1
  26. package/dist/codec.js +16 -7
  27. package/dist/codec.js.map +1 -1
  28. package/dist/codegen.js +6 -8
  29. package/dist/codegen.js.map +1 -1
  30. package/dist/composition.d.ts +3 -3
  31. package/dist/composition.js +9 -8
  32. package/dist/composition.js.map +1 -1
  33. package/dist/conformance.d.ts +24 -0
  34. package/dist/conformance.js +44 -0
  35. package/dist/conformance.js.map +1 -0
  36. package/dist/data.d.ts +3 -2
  37. package/dist/data.js +7 -3
  38. package/dist/data.js.map +1 -1
  39. package/dist/decimal-js.d.ts +2 -0
  40. package/dist/decimal-js.js +5 -0
  41. package/dist/decimal-js.js.map +1 -0
  42. package/dist/decimal.d.ts +2 -0
  43. package/dist/decimal.js +3 -0
  44. package/dist/decimal.js.map +1 -0
  45. package/dist/dependency.d.ts +9 -6
  46. package/dist/dependency.js +23 -17
  47. package/dist/dependency.js.map +1 -1
  48. package/dist/domain.d.ts +6 -2
  49. package/dist/domain.js +65 -25
  50. package/dist/domain.js.map +1 -1
  51. package/dist/ensures.js +3 -3
  52. package/dist/ensures.js.map +1 -1
  53. package/dist/equal.d.ts +1 -0
  54. package/dist/equal.js +135 -0
  55. package/dist/equal.js.map +1 -0
  56. package/dist/errors.d.ts +18 -0
  57. package/dist/errors.js +25 -0
  58. package/dist/errors.js.map +1 -0
  59. package/dist/exact.d.ts +13 -1
  60. package/dist/exact.js +52 -3
  61. package/dist/exact.js.map +1 -1
  62. package/dist/feasibility.d.ts +5 -3
  63. package/dist/feasibility.js +309 -53
  64. package/dist/feasibility.js.map +1 -1
  65. package/dist/guard-borders.d.ts +14 -5
  66. package/dist/guard-borders.js +229 -190
  67. package/dist/guard-borders.js.map +1 -1
  68. package/dist/guard-scope.d.ts +65 -0
  69. package/dist/guard-scope.js +384 -0
  70. package/dist/guard-scope.js.map +1 -0
  71. package/dist/hooks.d.ts +22 -0
  72. package/dist/hooks.js +2 -0
  73. package/dist/hooks.js.map +1 -0
  74. package/dist/index.d.ts +30 -8
  75. package/dist/index.js +18 -5
  76. package/dist/index.js.map +1 -1
  77. package/dist/interleave.d.ts +31 -0
  78. package/dist/interleave.js +202 -0
  79. package/dist/interleave.js.map +1 -0
  80. package/dist/interval.d.ts +8 -0
  81. package/dist/interval.js +213 -23
  82. package/dist/interval.js.map +1 -1
  83. package/dist/isolated.d.ts +7 -1
  84. package/dist/isolated.js +53 -5
  85. package/dist/isolated.js.map +1 -1
  86. package/dist/kinds/decimal.d.ts +1 -0
  87. package/dist/kinds/decimal.js +16 -0
  88. package/dist/kinds/decimal.js.map +1 -0
  89. package/dist/kinds/rational.d.ts +1 -0
  90. package/dist/kinds/rational.js +13 -0
  91. package/dist/kinds/rational.js.map +1 -0
  92. package/dist/kinds/temporal.d.ts +1 -0
  93. package/dist/kinds/temporal.js +15 -0
  94. package/dist/kinds/temporal.js.map +1 -0
  95. package/dist/lean/behavior.d.ts +29 -0
  96. package/dist/lean/behavior.js +76 -0
  97. package/dist/lean/behavior.js.map +1 -0
  98. package/dist/lean/given.d.ts +10 -0
  99. package/dist/lean/given.js +15 -0
  100. package/dist/lean/given.js.map +1 -0
  101. package/dist/lean/index.d.ts +11 -0
  102. package/dist/lean/index.js +8 -0
  103. package/dist/lean/index.js.map +1 -0
  104. package/dist/lean/model.d.ts +20 -0
  105. package/dist/lean/model.js +133 -0
  106. package/dist/lean/model.js.map +1 -0
  107. package/dist/lean/protocol.d.ts +14 -0
  108. package/dist/lean/protocol.js +34 -0
  109. package/dist/lean/protocol.js.map +1 -0
  110. package/dist/lean/rule.d.ts +54 -0
  111. package/dist/lean/rule.js +149 -0
  112. package/dist/lean/rule.js.map +1 -0
  113. package/dist/lean/schema.d.ts +46 -0
  114. package/dist/lean/schema.js +155 -0
  115. package/dist/lean/schema.js.map +1 -0
  116. package/dist/machine-check.d.ts +73 -0
  117. package/dist/machine-check.js +215 -0
  118. package/dist/machine-check.js.map +1 -0
  119. package/dist/machine.d.ts +122 -0
  120. package/dist/machine.js +271 -0
  121. package/dist/machine.js.map +1 -0
  122. package/dist/model.d.ts +110 -11
  123. package/dist/model.js +724 -80
  124. package/dist/model.js.map +1 -1
  125. package/dist/off-grid.d.ts +4 -0
  126. package/dist/off-grid.js +92 -0
  127. package/dist/off-grid.js.map +1 -0
  128. package/dist/outcomes.d.ts +15 -0
  129. package/dist/outcomes.js +120 -0
  130. package/dist/outcomes.js.map +1 -0
  131. package/dist/pairs.js +14 -5
  132. package/dist/pairs.js.map +1 -1
  133. package/dist/partition.d.ts +1 -0
  134. package/dist/partition.js +101 -19
  135. package/dist/partition.js.map +1 -1
  136. package/dist/placeholders.d.ts +3 -0
  137. package/dist/placeholders.js +44 -0
  138. package/dist/placeholders.js.map +1 -0
  139. package/dist/proof.d.ts +6 -0
  140. package/dist/proof.js +282 -56
  141. package/dist/proof.js.map +1 -1
  142. package/dist/protocol.d.ts +22 -0
  143. package/dist/protocol.js +12 -0
  144. package/dist/protocol.js.map +1 -0
  145. package/dist/relations.d.ts +30 -0
  146. package/dist/relations.js +235 -0
  147. package/dist/relations.js.map +1 -0
  148. package/dist/replay.d.ts +45 -0
  149. package/dist/replay.js +157 -0
  150. package/dist/replay.js.map +1 -0
  151. package/dist/rewrites.d.ts +41 -0
  152. package/dist/rewrites.js +180 -0
  153. package/dist/rewrites.js.map +1 -0
  154. package/dist/rule.d.ts +74 -11
  155. package/dist/rule.js +429 -22
  156. package/dist/rule.js.map +1 -1
  157. package/dist/runtime.d.ts +12 -0
  158. package/dist/runtime.js +8 -0
  159. package/dist/runtime.js.map +1 -0
  160. package/dist/schema.d.ts +44 -28
  161. package/dist/schema.js +50 -113
  162. package/dist/schema.js.map +1 -1
  163. package/dist/specification.d.ts +23 -3
  164. package/dist/specification.js +1001 -96
  165. package/dist/specification.js.map +1 -1
  166. package/dist/stops.d.ts +20 -0
  167. package/dist/stops.js +221 -0
  168. package/dist/stops.js.map +1 -0
  169. package/dist/temporal-global.d.ts +4 -0
  170. package/dist/temporal-global.js +11 -0
  171. package/dist/temporal-global.js.map +1 -0
  172. package/dist/temporal.d.ts +22 -0
  173. package/dist/temporal.js +113 -0
  174. package/dist/temporal.js.map +1 -0
  175. package/dist/tla-validate.d.ts +31 -0
  176. package/dist/tla-validate.js +151 -0
  177. package/dist/tla-validate.js.map +1 -0
  178. package/dist/tla.d.ts +61 -0
  179. package/dist/tla.js +722 -0
  180. package/dist/tla.js.map +1 -0
  181. package/dist/verification.d.ts +9 -0
  182. package/dist/verification.js +7 -0
  183. package/dist/verification.js.map +1 -0
  184. package/dist/ways.d.ts +11 -5
  185. package/dist/ways.js +51 -45
  186. package/dist/ways.js.map +1 -1
  187. package/dist/world.d.ts +98 -0
  188. package/dist/world.js +463 -0
  189. package/dist/world.js.map +1 -0
  190. package/package.json +49 -10
  191. package/schema/report.schema.json +169 -1
package/dist/cli.js CHANGED
@@ -1,7 +1,10 @@
1
1
  #!/usr/bin/env node
2
+ import "./decimal-js.js";
3
+ import "./checks.js";
2
4
  import { isMainThread, parentPort, workerData } from "node:worker_threads";
3
5
  import { runIsolated } from "./isolated.js";
4
6
  import { realpathSync } from "node:fs";
7
+ import { copyFile, link, mkdir, mkdtemp, rename, rm, stat, writeFile } from "node:fs/promises";
5
8
  import { resolve } from "node:path";
6
9
  import { pathToFileURL } from "node:url";
7
10
  import { arg, defineCommand, runCommand as executeCommand } from "@politty/zod";
@@ -9,10 +12,15 @@ import { tsImport } from "tsx/esm/api";
9
12
  import { z } from "zod";
10
13
  import { isBehavior, perform } from "./behavior.js";
11
14
  import { decode, encode } from "./codec.js";
12
- import { array, object } from "./schema.js";
15
+ import { array, enumOf, int, object, string } from "./schema.js";
13
16
  import { formatKey, formatTypeScriptValue } from "./codegen.js";
14
- import { spec, check, examples, generate, isSpecification, } from "./specification.js";
17
+ import { spec, check, examples, generate, isSpecification, modelChanges, } from "./specification.js";
18
+ import { describeWalk } from "./rewrites.js";
15
19
  import { verify } from "./proof.js";
20
+ import { isMachine, runMachine } from "./machine.js";
21
+ import { checkInterleavings } from "./interleave.js";
22
+ import { checkMachine, isMachineSpecification } from "./machine-check.js";
23
+ import { checkInterleavingsTla, checkMachineTla, proveMachine, toTla } from "./tla.js";
16
24
  import { reportDocument } from "./report-json.js";
17
25
  const fileArg = arg(z.string({ error: "Missing required argument <file>" }), {
18
26
  positional: true,
@@ -61,10 +69,22 @@ const checkCommand = defineCommand({
61
69
  ...(args.disregardCombinations === undefined ? {} : { combinations: args.disregardCombinations }),
62
70
  ...(args.disregardCandidates === undefined ? {} : { candidates: args.disregardCandidates }),
63
71
  };
72
+ if (!args.json) {
73
+ // Said before the measurement, which may take long and does not change it.
74
+ const changes = targets.flatMap(target => modelChanges(target.specification, { feasibility: feasibilityOptions(args) }));
75
+ if (changes.length > 0) {
76
+ const text = formatChanges(changes);
77
+ if (!isMainThread && workerData?.chisel === true)
78
+ parentPort.postMessage({ kind: "early", message: text });
79
+ else
80
+ console.log(text);
81
+ }
82
+ }
64
83
  const reports = await Promise.all(targets.map(target => check(target.specification, {
65
84
  disregards,
66
85
  feasibility: feasibilityOptions(args),
67
86
  pairs: pairOptions(args),
87
+ progress: postProgress,
68
88
  })));
69
89
  if (args.json) {
70
90
  const document = reportDocument(reports, { id: resolve(args.file), name: args.file });
@@ -105,6 +125,8 @@ const generateCommand = defineCommand({
105
125
  ways: args.ways,
106
126
  feasibility: feasibilityOptions(args),
107
127
  pairs: pairOptions(args),
128
+ fakes: target.specification.fakes,
129
+ progress: postProgress,
108
130
  });
109
131
  return [
110
132
  formatGeneratedExamples(target, generated),
@@ -114,7 +136,7 @@ const generateCommand = defineCommand({
114
136
  if (targets.some(target => target.synthesized)) {
115
137
  // A decimal's rows are written with decimal.js, which the file then imports.
116
138
  const decimal = printed.flat().some(line => line.includes("new Decimal("));
117
- console.log(`import * as c from "@toiroakr/chisel";\n${decimal ? 'import { Decimal } from "decimal.js";\n' : ""}`);
139
+ console.log(`import * as c from "@toiroakr/chisel/full";\n${decimal ? 'import { Decimal } from "decimal.js";\n' : ""}`);
118
140
  }
119
141
  for (const line of printed.flat()) {
120
142
  console.log(line);
@@ -142,7 +164,7 @@ const runCommand = defineCommand({
142
164
  }
143
165
  const implementation = implementations[0];
144
166
  const definition = implementation.behavior;
145
- if (Object.keys(definition.requires).length > 0) {
167
+ if (Object.keys(definition.dependencies).length > 0) {
146
168
  throw new Error(`${definition.name}には依存関係があります。performで依存関係を渡して実行してください`);
147
169
  }
148
170
  let json;
@@ -191,6 +213,230 @@ const verifyCommand = defineCommand({
191
213
  throw new Error("構築の保証を証明できないimplementationがあります");
192
214
  },
193
215
  });
216
+ const modelCheckCommand = defineCommand({
217
+ name: "model-check",
218
+ description: "有限コマンド領域の全到達状態を検査する",
219
+ args: z.object({
220
+ file: fileArg,
221
+ name: arg(z.string().optional(), { description: "検査するmachine名" }),
222
+ json: arg(z.boolean().default(false), { description: "検査結果をJSONで出力する" }),
223
+ engine: arg(z.enum(["chisel", "tla"]).default("chisel"), { description: "状態探索エンジン(chisel / tla)" }),
224
+ timeout: arg(z.coerce.number().int().positive().default(30000), { description: "モジュール読込と検査の実行上限(ミリ秒)" }),
225
+ maxStates: arg(z.coerce.number().int().positive().optional(), { description: "到達状態の上限(既定10000)" }),
226
+ maxCommands: arg(z.coerce.number().int().positive().optional(), { description: "後続コマンドの実行上限(既定1000)" }),
227
+ domainLimit: arg(z.coerce.number().int().positive().optional(), { description: "コマンドの列挙上限(既定10000)" }),
228
+ validationLimit: arg(z.coerce.number().int().positive().optional(), { description: "With --engine tla, the most (state, command) pairs the translation is compared with TypeScript on (default 20000; a spread over more is sampled)" }),
229
+ }),
230
+ run: async (args) => {
231
+ if (args.engine === "tla" && args.maxStates !== undefined) {
232
+ throw new Error("--max-statesは--engine tlaでは使えません");
233
+ }
234
+ if (args.engine !== "tla" && args.validationLimit !== undefined) {
235
+ throw new Error("--validation-limit is only used with --engine tla");
236
+ }
237
+ const machines = await loadSpecifications(args.file, args.name);
238
+ const options = {
239
+ ...(args.maxStates === undefined ? {} : { maxStates: args.maxStates }),
240
+ ...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }),
241
+ ...(args.domainLimit === undefined ? {} : { domainLimit: args.domainLimit }),
242
+ };
243
+ const reports = (await Promise.all(machines.map(async (declaration) => {
244
+ if (args.engine === "chisel") {
245
+ return [{ name: declaration.name, ...checkMachine(declaration, options) },
246
+ ...(declaration.interleavings === undefined ? [] : [{ name: `${declaration.name} (interleavings)`,
247
+ ...checkInterleavings(declaration, { ...declaration.interleavings, ...(args.maxStates === undefined ? {} : { maxStates: args.maxStates }),
248
+ ...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }) }) }])];
249
+ }
250
+ const { module: _module, ...report } = await checkMachineTla(declaration, { ...(args.domainLimit === undefined ? {} : { domainLimit: args.domainLimit }),
251
+ ...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }),
252
+ ...(args.validationLimit === undefined ? {} : { validationLimit: args.validationLimit }) });
253
+ return [{ name: declaration.name, ...report },
254
+ ...(declaration.interleavings === undefined ? [] : [await (async () => {
255
+ const { module: _interleaved, ...interleaved } = await checkInterleavingsTla(declaration, { ...declaration.interleavings, ...(args.domainLimit === undefined ? {} : { domainLimit: args.domainLimit }) });
256
+ return { name: `${declaration.name} (interleavings)`, ...interleaved };
257
+ })()])];
258
+ }))).flat();
259
+ if (args.json)
260
+ console.log(JSON.stringify(reports, jsonReplacer, 2));
261
+ else
262
+ for (const report of reports) {
263
+ console.log(`${report.name}: ${report.status} (${report.states} states, ${"generatedStates" in report ? `${report.generatedStates} generated states` : "transitions" in report ? `${report.transitions} transitions` : "interleaved"})`);
264
+ if (report.reason)
265
+ console.log(` ${report.reason}`);
266
+ if ("counterexample" in report && report.counterexample)
267
+ console.log(` ${JSON.stringify(report.counterexample, jsonReplacer)}`);
268
+ if ("trace" in report && report.trace)
269
+ console.log(` ${JSON.stringify(report.trace)}`);
270
+ const matrix = "matrix" in report ? report.matrix : undefined;
271
+ if (matrix)
272
+ for (const row of matrix.rows) {
273
+ const show = (value) => typeof value === "string" || typeof value === "bigint" ? String(value) : JSON.stringify(value, jsonReplacer);
274
+ console.log(` ${matrix.columns.map(column => `${column}=${show(row.state[column])}`).join(", ")}`);
275
+ for (const cell of row.cells)
276
+ console.log(` ${JSON.stringify(cell.command, jsonReplacer)}: changes ${cell.changes}${cell.precondition === undefined ? "" : `, precondition ${cell.precondition}`}`);
277
+ }
278
+ }
279
+ if (reports.some(report => report.status !== "held"))
280
+ throw new Error("反例または未確定の結果が出たmachineがあります");
281
+ },
282
+ });
283
+ const tlaCommand = defineCommand({
284
+ name: "tla",
285
+ description: "実行可能なmachine定義からTLA+のモジュールと設定を生成する",
286
+ args: z.object({
287
+ file: fileArg,
288
+ name: arg(z.string().optional(), { description: "変換するmachine名" }),
289
+ outputDir: arg(z.string().optional(), { description: "生成した.tlaと.cfgを保存するディレクトリ" }),
290
+ force: arg(z.boolean().default(false), { description: "既存の.tlaと.cfgを置き換える" }),
291
+ domainLimit: arg(z.coerce.number().int().positive().optional(), { description: "状態とコマンドの列挙上限" }),
292
+ maxCommands: arg(z.coerce.number().int().positive().optional(), { description: "後続コマンドの実行上限(既定1000)" }),
293
+ timeout: arg(z.coerce.number().int().positive().default(30000), { description: "実行上限(ミリ秒)" }),
294
+ }),
295
+ run: async (args) => {
296
+ const declarations = await loadSpecifications(args.file, args.name);
297
+ if (declarations.length !== 1)
298
+ throw new Error("machineを一意に選べません。--nameで指定してください");
299
+ const module = toTla(declarations[0], {
300
+ ...(args.domainLimit === undefined ? {} : { domainLimit: args.domainLimit }),
301
+ ...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }),
302
+ });
303
+ if (args.outputDir === undefined)
304
+ console.log(JSON.stringify(module, undefined, 2));
305
+ else {
306
+ await writeTlaPair(args.outputDir, module.name, module.source, module.config, args.force);
307
+ console.log(`Generated ${module.name}.tla and ${module.name}.cfg`);
308
+ }
309
+ },
310
+ });
311
+ async function writeTlaPair(directory, name, source, config, force) {
312
+ await mkdir(directory, { recursive: true });
313
+ const staging = await mkdtemp(resolve(directory, ".chisel-tla-"));
314
+ const files = [
315
+ { filename: `${name}.tla`, contents: `${source}\n` },
316
+ { filename: `${name}.cfg`, contents: `${config}\n` },
317
+ ];
318
+ const published = [];
319
+ try {
320
+ await Promise.all(files.map(file => writeFile(resolve(staging, file.filename), file.contents, { flag: "wx" })));
321
+ if (force) {
322
+ for (const file of files) {
323
+ const destination = resolve(directory, file.filename);
324
+ try {
325
+ await stat(destination);
326
+ await copyFile(destination, resolve(staging, `${file.filename}.backup`));
327
+ }
328
+ catch (error) {
329
+ if (error.code !== "ENOENT")
330
+ throw error;
331
+ }
332
+ }
333
+ }
334
+ for (const file of files) {
335
+ const destination = resolve(directory, file.filename);
336
+ const staged = resolve(staging, file.filename);
337
+ const backup = resolve(staging, `${file.filename}.backup`);
338
+ if (force)
339
+ await rename(staged, destination);
340
+ else
341
+ await link(staged, destination); // EEXIST keeps both previous files intact.
342
+ let existed = false;
343
+ try {
344
+ await stat(backup);
345
+ existed = true;
346
+ }
347
+ catch (error) {
348
+ if (error.code !== "ENOENT")
349
+ throw error;
350
+ }
351
+ published.push({ destination, backup, existed });
352
+ }
353
+ }
354
+ catch (error) {
355
+ for (const file of published.reverse()) {
356
+ if (file.existed)
357
+ await copyFile(file.backup, file.destination);
358
+ else
359
+ await rm(file.destination, { force: true });
360
+ }
361
+ throw error;
362
+ }
363
+ finally {
364
+ await rm(staging, { recursive: true, force: true });
365
+ }
366
+ }
367
+ const proveMachineCommand = defineCommand({
368
+ name: "prove-machine",
369
+ description: "初期条件と状態遷移の帰納的な保存を静的に証明する",
370
+ args: z.object({
371
+ file: fileArg,
372
+ name: arg(z.string().optional(), { description: "証明するmachine名" }),
373
+ json: arg(z.boolean().default(false), { description: "証明義務をJSONで出力する" }),
374
+ timeout: arg(z.coerce.number().int().positive().default(30000), { description: "証明の実行上限(ミリ秒)" }),
375
+ }),
376
+ run: async (args) => {
377
+ const declarations = await loadSpecifications(args.file, args.name);
378
+ const reports = await Promise.all(declarations.map(async (declaration) => ({
379
+ name: declaration.name, ...await proveMachine(declaration),
380
+ })));
381
+ if (args.json)
382
+ console.log(JSON.stringify(reports, undefined, 2));
383
+ else
384
+ for (const report of reports) {
385
+ console.log(`${report.name}: ${report.status}`);
386
+ if (report.reason)
387
+ console.log(` ${report.reason}`);
388
+ for (const obligation of report.obligations)
389
+ console.log(` ${obligation.name}: ${obligation.status}${obligation.reason ? ` — ${obligation.reason}` : ""}`);
390
+ }
391
+ if (reports.some(report => report.status !== "proved"))
392
+ throw new Error("証明できないmachineがあります");
393
+ },
394
+ });
395
+ const runMachineCommand = defineCommand({
396
+ name: "run-machine",
397
+ description: "machineにコマンドを適用して次の状態と全遷移をJSONで出力する",
398
+ args: z.object({
399
+ file: fileArg,
400
+ name: arg(z.string().optional(), { description: "実行するmachine名" }),
401
+ state: arg(z.string({ error: "Missing required option --state" }), { description: "現在の状態(JSON)" }),
402
+ command: arg(z.string({ error: "Missing required option --command" }), { description: "コマンド(JSON)" }),
403
+ maxCommands: arg(z.coerce.number().int().positive().optional(), { description: "後続コマンドの実行上限(既定1000)" }),
404
+ fail: arg(z.string().optional(), { description: "失敗させるeffect名(カンマ区切り)" }),
405
+ dieAfter: arg(z.coerce.number().int().min(0).optional(), { description: "effectを持つコマンドをこの数のeffectの後でプロセスを死なせる(0なら最初のeffectの前)" }),
406
+ timeout: arg(z.coerce.number().int().positive().default(30000), { description: "モジュール読込と実行の上限(ミリ秒)" }),
407
+ }),
408
+ run: async (args) => {
409
+ const machines = await loadMachines(args.file, args.name);
410
+ if (machines.length !== 1)
411
+ throw new Error("machineを一意に選べません。--nameで指定してください");
412
+ const declaration = machines[0];
413
+ let state, command;
414
+ try {
415
+ state = JSON.parse(args.state);
416
+ command = JSON.parse(args.command);
417
+ }
418
+ catch {
419
+ throw new Error("--stateと--commandは有効なJSONで指定してください");
420
+ }
421
+ const decodedState = decode(declaration.state, state);
422
+ const decodedCommand = decode(declaration.command, command);
423
+ if (!decodedState.success || !decodedCommand.success) {
424
+ throw new Error([...(!decodedState.success ? decodedState.issues : []), ...(!decodedCommand.success ? decodedCommand.issues : [])]
425
+ .map(issue => `${issue.path}: ${issue.message}`).join("\n"));
426
+ }
427
+ const failing = new Set((args.fail ?? "").split(",").map(name => name.trim()).filter(Boolean));
428
+ const result = runMachine(declaration, decodedState.value, decodedCommand.value, { ...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }), fails: effect => failing.has(effect.name),
429
+ ...(args.dieAfter === undefined ? {} : { dies: point => point.completed === args.dieAfter }) });
430
+ const output = encode(object({ state: declaration.state, steps: array(object({
431
+ command: declaration.command, before: declaration.state, after: declaration.state,
432
+ performed: array(object({ name: string(), outcome: enumOf(["succeeded", "failed"]) })).optional(),
433
+ died: object({ after: int() }).optional(),
434
+ })) }), result);
435
+ if (!output.success)
436
+ throw new Error(output.issues.map(issue => `${issue.path}: ${issue.message}`).join("\n"));
437
+ console.log(JSON.stringify(output.value, undefined, 2));
438
+ },
439
+ });
194
440
  function jsonReplacer(_key, value) { return typeof value === "bigint" ? String(value) : value; }
195
441
  export const cli = defineCommand({
196
442
  name: "chisel",
@@ -200,8 +446,39 @@ export const cli = defineCommand({
200
446
  generate: generateCommand,
201
447
  run: runCommand,
202
448
  verify: verifyCommand,
449
+ "model-check": modelCheckCommand,
450
+ tla: tlaCommand,
451
+ "prove-machine": proveMachineCommand,
452
+ "run-machine": runMachineCommand,
203
453
  },
204
454
  });
455
+ async function loadMachines(file, name) {
456
+ const module = (await tsImport(pathToFileURL(resolve(file)).href, import.meta.url));
457
+ const declarations = [...new Set(Object.values(module).filter(isMachine))];
458
+ if (declarations.length === 0)
459
+ throw new Error(`${file}にexportされたmachineがありません`);
460
+ if (name === undefined)
461
+ return declarations;
462
+ const selected = declarations.filter(declaration => declaration.name === name);
463
+ if (selected.length === 0)
464
+ throw new Error(`machine ${name}がありません。選択できるmachine: ${declarations.map(item => item.name).join(", ")}`);
465
+ return selected;
466
+ }
467
+ async function loadSpecifications(file, name) {
468
+ const module = (await tsImport(pathToFileURL(resolve(file)).href, import.meta.url));
469
+ const declarations = [...new Set(Object.values(module).filter(isMachineSpecification))];
470
+ if (declarations.length === 0)
471
+ throw new Error(`${file}にexportされたmachine specificationがありません`);
472
+ const duplicate = declarations.find((declaration, index) => declarations.findIndex(other => other.name === declaration.name) !== index);
473
+ if (duplicate)
474
+ throw new Error(`machine specification ${duplicate.name} が重複しています。specifyMachineのnameで区別してください`);
475
+ if (name === undefined)
476
+ return declarations;
477
+ const selected = declarations.filter(declaration => declaration.name === name);
478
+ if (selected.length === 0)
479
+ throw new Error(`machine ${name}がありません。選択できるmachine: ${declarations.map(item => item.name).join(", ")}`);
480
+ return selected;
481
+ }
205
482
  async function loadTargets(file, behavior, includeImplementations = false) {
206
483
  const url = pathToFileURL(resolve(file)).href;
207
484
  const module = (await tsImport(url, import.meta.url));
@@ -276,15 +553,16 @@ function formatReport(report) {
276
553
  ...formatPartitions(report.partitions),
277
554
  ...formatBorders(report.borders),
278
555
  ...formatPairs(report.pairs),
279
- ...report.measures.pairs.obligations.filter(pair => pair.status !== "met").map(pair => ` ${pair.status === "gap" || pair.status === "answer owed" ? "!" : "?"} ${pair.positions.join(" × ")}: ${pair.classes.join(" × ")} (${pair.status})${pair.reason === undefined ? "" : ` — ${pair.reason}`}`),
556
+ ...report.measures.pairs.obligations.filter(pair => pair.status !== "met" && pair.status !== "no row owed").map(pair => ` ${pair.status === "gap" || pair.status === "answer owed" ? "!" : "?"} ${pair.positions.join(" × ")}: ${pair.classes.join(" × ")} (${pair.status})${pair.reason === undefined ? "" : ` — ${pair.reason}`}`),
557
+ ...countedPairs(report.measures.pairs.obligations),
280
558
  ...report.measures.pairs.notRead.map(reason => ` ? 組み合わせ未計測: ${reason}`),
281
559
  ...formatEvidence("証拠(入力)", report.evidence.input, ["specified", "executed", "verified"]),
282
560
  ...formatEvidence("証拠(結果)", report.evidence.result, ["specified", "observed", "verified"]),
283
561
  ...formatEvidence("証拠(作用)", report.evidence.effects, ["specified", "observed", "verified"]),
284
562
  ` 実装 ${implementation}`,
285
- ` 分岐 ${formatMeasure(report.measures.arms)}`,
563
+ ` 分岐 ${formatMeasure(report.measures.arms, report.toBeChangedFirst)}`,
286
564
  ...formatArms(report.measures.arms),
287
- ` 道筋 ${formatMeasure(report.measures.rules)}`,
565
+ ` 道筋 ${formatMeasure(report.measures.rules, report.toBeChangedFirst)}`,
288
566
  ...formatRules(report.measures.rules),
289
567
  ` 比較 ${report.measures.comparisons.status === "complete"
290
568
  ? "すべて読めた (complete)"
@@ -292,6 +570,8 @@ function formatReport(report) {
292
570
  ...formatEnsures(report.ensures),
293
571
  ` 構築の保証 ${report.measures.constructions.status}`,
294
572
  ...report.measures.constructions.decisions.map(proof => ` ${proof.decision}: ${proof.status} — ${proof.reason}`),
573
+ ...formatWalks(report.walks),
574
+ ...formatStops(report.stops),
295
575
  ];
296
576
  for (const row of report.unanswered) {
297
577
  lines.push(` ! 未回答のexample: ${row.name} — ${row.reason}`);
@@ -306,6 +586,9 @@ function formatReport(report) {
306
586
  if (item.kind === "disregards not checked") {
307
587
  lines.push(` ! disregardsを確かめていない行: ${item.subject} — ${item.reason}`);
308
588
  }
589
+ else if (item.kind === "out of room") {
590
+ lines.push(` ? 実行環境の余地が足りず答えを書けなかった行(OutOfRoom): ${item.subject} — ${item.reason}`);
591
+ }
309
592
  else if (!report.failures.some(failure => failure.name === item.subject)) {
310
593
  lines.push(` ! 実行できなかった行: ${item.subject} — ${item.reason}`);
311
594
  }
@@ -412,6 +695,17 @@ const countedLabels = {
412
695
  "no row owed": "行は不要 (no row owed)",
413
696
  undecided: "未決 (undecided)",
414
697
  };
698
+ // A pair no row is owed is counted under its reason, as an arm or a way is.
699
+ function countedPairs(obligations) {
700
+ const counted = new Map();
701
+ for (const pair of obligations) {
702
+ if (pair.status !== "no row owed")
703
+ continue;
704
+ const key = `${countedLabels["no row owed"]}: ${pair.reason ?? ""}`;
705
+ counted.set(key, (counted.get(key) ?? 0) + 1);
706
+ }
707
+ return [...counted].map(([key, count]) => ` ${key} — ${count}件`);
708
+ }
415
709
  function formatLines(items, describe) {
416
710
  const lines = [];
417
711
  const counted = new Map();
@@ -460,18 +754,53 @@ function formatEnsures(ensures) {
460
754
  : [` 述べられていない結果: ${ensures.unstated.join(", ")}`]),
461
755
  ];
462
756
  }
463
- function formatMeasure(measure) {
757
+ function formatMeasure(measure, changes = []) {
758
+ const toChange = new Set(changes.map(change => change.decision));
759
+ const named = (ids) => ids.map(id => (toChange.has(id) ? `${id}(先に変更する)` : id)).join(", ");
464
760
  switch (measure.status) {
465
761
  case "complete":
466
762
  return "計測済み (complete)";
467
763
  case "partial":
468
- return `一部のみ (partial); 読めないdecision: ${measure.notRead.join(", ")}`;
764
+ return `一部のみ (partial); 読めないdecision: ${named(measure.notRead)}`;
469
765
  case "unavailable":
470
- return measure.reason === "not applicable"
471
- ? "対象なし (not applicable)"
472
- : `計測不能 (not measured); 読めないdecision: ${measure.notRead.join(", ")}`;
766
+ if (measure.reason === "not applicable")
767
+ return "対象なし (not applicable)";
768
+ return measure.notRead.every(id => toChange.has(id))
769
+ ? `計測しない (not measured, to be changed first): ${named(measure.notRead)}`
770
+ : `計測不能 (not measured); 読めないdecision: ${named(measure.notRead)}`;
473
771
  }
474
772
  }
773
+ function formatStops(stops) {
774
+ const shown = stops.filter(stop => stop.status !== "never stops");
775
+ if (shown.length === 0)
776
+ return [];
777
+ const count = (status) => stops.filter(stop => stop.status === status).length;
778
+ return [
779
+ ` 停止 止まりうる ${count("may stop")} 未解決 ${count("not resolved")}`,
780
+ ...shown.map(stop => stop.status === "may stop"
781
+ ? ` ! 実行が止まりうる: ${stop.decision}: ${stop.at} — 入力 ${formatTypeScriptValue(stop.input)}${stop.with === undefined ? "" : `、with ${formatTypeScriptValue(stop.with)}`}${stop.keeping === undefined ? "" : `。${stop.keeping}`}`
782
+ : ` ? 停止が未解決: ${stop.decision}: ${stop.at} — ${stop.reason}`),
783
+ ];
784
+ }
785
+ function formatWalks(walks) {
786
+ if (walks.length === 0)
787
+ return [];
788
+ const told = walks.filter(walk => walk.status === "told" || walk.status === "no row owed").length;
789
+ return [
790
+ ` foldの書き換え ${told}/${walks.length}`,
791
+ ...walks.filter(walk => walk.status === "not told" || walk.status === "undecided").map(walk => walk.status === "not told"
792
+ ? ` ! ${describeWalk(walk)}${walk.reason === undefined ? "" : ` — ${walk.reason}`}`
793
+ : ` ? ${walk.decision}: ${walk.walk}の書き換え(${walk.rewrite})を見分けられたか決められない${walk.reason === undefined ? "" : ` — ${walk.reason}`}`),
794
+ ];
795
+ }
796
+ // What to change in the model, printed before the measurement starts.
797
+ function formatChanges(changes) {
798
+ return [
799
+ "計測の前に:",
800
+ ...changes.map(change => ` ↻ ${change.message}`),
801
+ " ここに述べたことは計測の結果で変わらない。計測を待たずにモデルを変更し、変更してから計測できる。",
802
+ ].join("\n");
803
+ }
475
804
  function formatCoverage(label, coverage) {
476
805
  const missing = coverage.missing.length === 0 ? "" : `; 未網羅 ${coverage.missing.join(", ")}`;
477
806
  const excluded = coverage.excluded.length === 0 ? "" : `; 除外 ${coverage.excluded.join(", ")} (excluded)`;
@@ -482,7 +811,9 @@ function formatGeneratedExamples(target, generated) {
482
811
  if (generated.length === 0) {
483
812
  return `${binding}: 未網羅の入力variantはありません`;
484
813
  }
485
- const rows = generated.map(row => `${formatGeneratedExample(row)},\n`).join("");
814
+ const suggested = generated.filter(row => row.suggested === true).length;
815
+ const header = suggested === 0 ? "" : `// 義務のある行 ${generated.length - suggested}件、提案する行 ${suggested}件(義務はない)\n`;
816
+ const rows = header + generated.map(row => `${formatGeneratedExample(row)},\n`).join("");
486
817
  if (!target.synthesized) {
487
818
  return target.specification.implementation === undefined
488
819
  ? `${rows.trimEnd()}\n\n${formatImplementationScaffold(target)}`
@@ -551,13 +882,19 @@ else if (isRunAsScript()) {
551
882
  const at = argv.indexOf("--timeout");
552
883
  const assigned = argv.find(arg => arg.startsWith("--timeout="));
553
884
  const timeout = Number(assigned?.slice("--timeout=".length) ?? (at >= 0 ? argv[at + 1] : 30000));
554
- const result = await runIsolated(argv, Number.isSafeInteger(timeout) && timeout > 0 ? timeout : 30000);
885
+ const result = await runIsolated(argv, Number.isSafeInteger(timeout) && timeout > 0 ? timeout : 30000, { early: line => console.log(line) });
555
886
  for (const entry of result.logs)
556
887
  (entry.stream === "stderr" ? console.error : console.log)(entry.message);
557
888
  if (result.error)
558
889
  console.error(`Error: ${result.error}`);
559
890
  process.exitCode = result.exitCode;
560
891
  }
892
+ // In the worker, each phase is posted to the parent, which says it on stderr
893
+ // once the run has gone on a while; run in process, nothing is said.
894
+ function postProgress(phase) {
895
+ if (!isMainThread && workerData?.chisel === true)
896
+ parentPort.postMessage({ kind: "progress", message: phase });
897
+ }
561
898
  function feasibilityOptions(args) {
562
899
  return {
563
900
  ...(args.feasibilityCombinations === undefined ? {} : { combinations: args.feasibilityCombinations }),