@toiroakr/chisel 0.0.0-stage → 0.2.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.
- package/README.md +693 -2
- package/dist/absence.d.ts +27 -0
- package/dist/absence.js +228 -0
- package/dist/absence.js.map +1 -0
- package/dist/behavior.d.ts +193 -0
- package/dist/behavior.js +589 -0
- package/dist/behavior.js.map +1 -0
- package/dist/beside.d.ts +27 -0
- package/dist/beside.js +88 -0
- package/dist/beside.js.map +1 -0
- package/dist/border.d.ts +61 -0
- package/dist/border.js +434 -0
- package/dist/border.js.map +1 -0
- package/dist/bounds.d.ts +1 -0
- package/dist/bounds.js +26 -0
- package/dist/bounds.js.map +1 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +835 -0
- package/dist/cli.js.map +1 -0
- package/dist/codec.d.ts +6 -0
- package/dist/codec.js +86 -0
- package/dist/codec.js.map +1 -0
- package/dist/codegen.d.ts +2 -0
- package/dist/codegen.js +61 -0
- package/dist/codegen.js.map +1 -0
- package/dist/composition.d.ts +38 -0
- package/dist/composition.js +242 -0
- package/dist/composition.js.map +1 -0
- package/dist/data.d.ts +17 -0
- package/dist/data.js +51 -0
- package/dist/data.js.map +1 -0
- package/dist/dependency.d.ts +101 -0
- package/dist/dependency.js +161 -0
- package/dist/dependency.js.map +1 -0
- package/dist/domain.d.ts +12 -0
- package/dist/domain.js +217 -0
- package/dist/domain.js.map +1 -0
- package/dist/ensures.d.ts +15 -0
- package/dist/ensures.js +88 -0
- package/dist/ensures.js.map +1 -0
- package/dist/equal.d.ts +1 -0
- package/dist/equal.js +135 -0
- package/dist/equal.js.map +1 -0
- package/dist/exact.d.ts +21 -0
- package/dist/exact.js +80 -0
- package/dist/exact.js.map +1 -0
- package/dist/feasibility.d.ts +63 -0
- package/dist/feasibility.js +1053 -0
- package/dist/feasibility.js.map +1 -0
- package/dist/guard-borders.d.ts +57 -0
- package/dist/guard-borders.js +760 -0
- package/dist/guard-borders.js.map +1 -0
- package/dist/guard-scope.d.ts +61 -0
- package/dist/guard-scope.js +364 -0
- package/dist/guard-scope.js.map +1 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/interleave.d.ts +31 -0
- package/dist/interleave.js +202 -0
- package/dist/interleave.js.map +1 -0
- package/dist/interval.d.ts +10 -0
- package/dist/interval.js +311 -0
- package/dist/interval.js.map +1 -0
- package/dist/isolated.d.ts +9 -0
- package/dist/isolated.js +41 -0
- package/dist/isolated.js.map +1 -0
- package/dist/machine-check.d.ts +73 -0
- package/dist/machine-check.js +215 -0
- package/dist/machine-check.js.map +1 -0
- package/dist/machine.d.ts +97 -0
- package/dist/machine.js +200 -0
- package/dist/machine.js.map +1 -0
- package/dist/model.d.ts +160 -0
- package/dist/model.js +778 -0
- package/dist/model.js.map +1 -0
- package/dist/outcomes.d.ts +7 -0
- package/dist/outcomes.js +38 -0
- package/dist/outcomes.js.map +1 -0
- package/dist/pairs.d.ts +26 -0
- package/dist/pairs.js +115 -0
- package/dist/pairs.js.map +1 -0
- package/dist/partition.d.ts +45 -0
- package/dist/partition.js +354 -0
- package/dist/partition.js.map +1 -0
- package/dist/proof.d.ts +21 -0
- package/dist/proof.js +556 -0
- package/dist/proof.js.map +1 -0
- package/dist/replay.d.ts +45 -0
- package/dist/replay.js +157 -0
- package/dist/replay.js.map +1 -0
- package/dist/report-json.d.ts +11 -0
- package/dist/report-json.js +94 -0
- package/dist/report-json.js.map +1 -0
- package/dist/rule.d.ts +186 -0
- package/dist/rule.js +866 -0
- package/dist/rule.js.map +1 -0
- package/dist/runtime.d.ts +12 -0
- package/dist/runtime.js +8 -0
- package/dist/runtime.js.map +1 -0
- package/dist/schema.d.ts +163 -0
- package/dist/schema.js +528 -0
- package/dist/schema.js.map +1 -0
- package/dist/specification.d.ts +266 -0
- package/dist/specification.js +2123 -0
- package/dist/specification.js.map +1 -0
- package/dist/temporal-global.d.ts +4 -0
- package/dist/temporal-global.js +11 -0
- package/dist/temporal-global.js.map +1 -0
- package/dist/temporal.d.ts +22 -0
- package/dist/temporal.js +113 -0
- package/dist/temporal.js.map +1 -0
- package/dist/text.d.ts +1 -0
- package/dist/text.js +11 -0
- package/dist/text.js.map +1 -0
- package/dist/tla.d.ts +54 -0
- package/dist/tla.js +579 -0
- package/dist/tla.js.map +1 -0
- package/dist/verification.d.ts +7 -0
- package/dist/verification.js +5 -0
- package/dist/verification.js.map +1 -0
- package/dist/ways.d.ts +28 -0
- package/dist/ways.js +86 -0
- package/dist/ways.js.map +1 -0
- package/dist/world.d.ts +98 -0
- package/dist/world.js +467 -0
- package/dist/world.js.map +1 -0
- package/package.json +76 -4
- package/schema/report.schema.json +1062 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
3
|
+
import { runIsolated } from "./isolated.js";
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { copyFile, link, mkdir, mkdtemp, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
6
|
+
import { resolve } from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { arg, defineCommand, runCommand as executeCommand } from "@politty/zod";
|
|
9
|
+
import { tsImport } from "tsx/esm/api";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { isBehavior, perform } from "./behavior.js";
|
|
12
|
+
import { decode, encode } from "./codec.js";
|
|
13
|
+
import { array, enumOf, int, object, string } from "./schema.js";
|
|
14
|
+
import { formatKey, formatTypeScriptValue } from "./codegen.js";
|
|
15
|
+
import { spec, check, examples, generate, isSpecification, } from "./specification.js";
|
|
16
|
+
import { verify } from "./proof.js";
|
|
17
|
+
import { isMachine, runMachine } from "./machine.js";
|
|
18
|
+
import { checkInterleavings } from "./interleave.js";
|
|
19
|
+
import { checkMachine, isMachineSpecification } from "./machine-check.js";
|
|
20
|
+
import { checkInterleavingsTla, checkMachineTla, proveMachine, toTla } from "./tla.js";
|
|
21
|
+
import { reportDocument } from "./report-json.js";
|
|
22
|
+
const fileArg = arg(z.string({ error: "Missing required argument <file>" }), {
|
|
23
|
+
positional: true,
|
|
24
|
+
description: "behaviorまたはspecificationをexportしたspecファイル",
|
|
25
|
+
});
|
|
26
|
+
const pairArgs = {
|
|
27
|
+
pairObligations: arg(z.coerce.number().int().positive().optional(), { description: "検査する組み合わせ義務の上限(既定20000)" }),
|
|
28
|
+
pairCandidates: arg(z.coerce.number().int().positive().optional(), { description: "組み合わせを構築する候補の上限(既定4096)" }),
|
|
29
|
+
};
|
|
30
|
+
function pairOptions(args) {
|
|
31
|
+
return { ...(args.pairObligations === undefined ? {} : { obligations: args.pairObligations }), ...(args.pairCandidates === undefined ? {} : { candidates: args.pairCandidates }) };
|
|
32
|
+
}
|
|
33
|
+
const behaviorArg = arg(z.string().optional(), {
|
|
34
|
+
description: "宣言したbehavior名に一致するspecificationだけを対象にする",
|
|
35
|
+
});
|
|
36
|
+
const checkCommand = defineCommand({
|
|
37
|
+
name: "check",
|
|
38
|
+
description: "specificationの充足度を報告する",
|
|
39
|
+
args: z.object({
|
|
40
|
+
file: fileArg,
|
|
41
|
+
behavior: behaviorArg,
|
|
42
|
+
timeout: arg(z.coerce.number().int().positive().default(30000), { description: "モジュール読込を含む実行上限(ミリ秒)" }),
|
|
43
|
+
strict: arg(z.boolean().default(false), {
|
|
44
|
+
description: "充足度が不完全なら終了コード1で失敗する",
|
|
45
|
+
}),
|
|
46
|
+
json: arg(z.boolean().default(false), {
|
|
47
|
+
description: "レポートをJSONで出力する",
|
|
48
|
+
}),
|
|
49
|
+
disregardCombinations: arg(z.coerce.number().int().positive().optional(), {
|
|
50
|
+
description: "disregardsの確認で試す組み合わせの上限(既定は255)",
|
|
51
|
+
}),
|
|
52
|
+
disregardCandidates: arg(z.coerce.number().int().positive().optional(), {
|
|
53
|
+
description: "disregardsの確認で数える候補の上限(既定は4096)",
|
|
54
|
+
}),
|
|
55
|
+
...pairArgs,
|
|
56
|
+
feasibilityCombinations: arg(z.coerce.number().int().positive().optional(), {
|
|
57
|
+
description: "不変条件とあわせて道筋や境界点を確かめるときに試す値の組の上限(既定は4096)",
|
|
58
|
+
}),
|
|
59
|
+
feasibilityWays: arg(z.coerce.number().int().positive().optional(), {
|
|
60
|
+
description: "decisionごとにたどる道筋の上限。超えたdecisionは計測しない(既定は10000)",
|
|
61
|
+
}),
|
|
62
|
+
}),
|
|
63
|
+
run: async (args) => {
|
|
64
|
+
const targets = await loadTargets(args.file, args.behavior);
|
|
65
|
+
const disregards = {
|
|
66
|
+
...(args.disregardCombinations === undefined ? {} : { combinations: args.disregardCombinations }),
|
|
67
|
+
...(args.disregardCandidates === undefined ? {} : { candidates: args.disregardCandidates }),
|
|
68
|
+
};
|
|
69
|
+
const reports = await Promise.all(targets.map(target => check(target.specification, {
|
|
70
|
+
disregards,
|
|
71
|
+
feasibility: feasibilityOptions(args),
|
|
72
|
+
pairs: pairOptions(args),
|
|
73
|
+
})));
|
|
74
|
+
if (args.json) {
|
|
75
|
+
const document = reportDocument(reports, { id: resolve(args.file), name: args.file });
|
|
76
|
+
console.log(JSON.stringify(document, undefined, 2));
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
for (const report of reports) {
|
|
80
|
+
console.log(formatReport(report));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (args.strict && reports.some(report => report.verdict !== "satisfied")) {
|
|
84
|
+
throw new Error("充足度が不完全なspecificationがあります");
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
const generateCommand = defineCommand({
|
|
89
|
+
name: "generate",
|
|
90
|
+
description: "未網羅の入力variantに対するexampleの雛形を出力する",
|
|
91
|
+
args: z.object({
|
|
92
|
+
file: fileArg,
|
|
93
|
+
behavior: behaviorArg,
|
|
94
|
+
timeout: arg(z.coerce.number().int().positive().default(30000), { description: "モジュール読込を含む実行上限(ミリ秒)" }),
|
|
95
|
+
ways: arg(z.boolean().default(false), {
|
|
96
|
+
description: "1か所を動かすだけでは通れない道筋も、有限の値をまとめて書き込んで行を出力する",
|
|
97
|
+
}),
|
|
98
|
+
...pairArgs,
|
|
99
|
+
feasibilityCombinations: arg(z.coerce.number().int().positive().optional(), {
|
|
100
|
+
description: "不変条件とあわせて行を組み立てるときに試す値の組の上限(既定は4096)",
|
|
101
|
+
}),
|
|
102
|
+
feasibilityWays: arg(z.coerce.number().int().positive().optional(), {
|
|
103
|
+
description: "decisionごとにたどる道筋の上限。超えたdecisionの道筋は組み立てない(既定は10000)",
|
|
104
|
+
}),
|
|
105
|
+
}),
|
|
106
|
+
run: async (args) => {
|
|
107
|
+
const targets = await loadTargets(args.file, args.behavior);
|
|
108
|
+
const printed = targets.map(target => {
|
|
109
|
+
const { rows: generated, notComposed } = generate(target.specification.examples, target.specification.implementation, {
|
|
110
|
+
ways: args.ways,
|
|
111
|
+
feasibility: feasibilityOptions(args),
|
|
112
|
+
pairs: pairOptions(args),
|
|
113
|
+
fakes: target.specification.fakes,
|
|
114
|
+
});
|
|
115
|
+
return [
|
|
116
|
+
formatGeneratedExamples(target, generated),
|
|
117
|
+
...notComposed.map(way => `// 組み立てられなかった道筋: ${way}`),
|
|
118
|
+
];
|
|
119
|
+
});
|
|
120
|
+
if (targets.some(target => target.synthesized)) {
|
|
121
|
+
// A decimal's rows are written with decimal.js, which the file then imports.
|
|
122
|
+
const decimal = printed.flat().some(line => line.includes("new Decimal("));
|
|
123
|
+
console.log(`import * as c from "@toiroakr/chisel/full";\n${decimal ? 'import { Decimal } from "decimal.js";\n' : ""}`);
|
|
124
|
+
}
|
|
125
|
+
for (const line of printed.flat()) {
|
|
126
|
+
console.log(line);
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
const runCommand = defineCommand({
|
|
131
|
+
name: "run",
|
|
132
|
+
description: "JSON入力で実装を1回実行し、結果と副作用をJSONで出力する",
|
|
133
|
+
args: z.object({
|
|
134
|
+
file: fileArg,
|
|
135
|
+
behavior: behaviorArg,
|
|
136
|
+
timeout: arg(z.coerce.number().int().positive().default(30000), { description: "モジュール読込を含む実行上限(ミリ秒)" }),
|
|
137
|
+
input: arg(z.string({ error: "Missing required option --input" }), {
|
|
138
|
+
description: "入力のJSON。DecimalとTemporalは文字列で指定する",
|
|
139
|
+
}),
|
|
140
|
+
}),
|
|
141
|
+
run: async (args) => {
|
|
142
|
+
const targets = await loadTargets(args.file, args.behavior, true);
|
|
143
|
+
const implementations = [...new Set(targets.flatMap(target => target.implementations ?? []))];
|
|
144
|
+
if (implementations.length !== 1) {
|
|
145
|
+
throw new Error(implementations.length === 0
|
|
146
|
+
? "実行できるimplementationがありません。specに実装を指定するかimplementationをexportしてください"
|
|
147
|
+
: "implementationを一意に選べません。--behaviorで実装が1つのbehaviorを指定してください");
|
|
148
|
+
}
|
|
149
|
+
const implementation = implementations[0];
|
|
150
|
+
const definition = implementation.behavior;
|
|
151
|
+
if (Object.keys(definition.dependencies).length > 0) {
|
|
152
|
+
throw new Error(`${definition.name}には依存関係があります。performで依存関係を渡して実行してください`);
|
|
153
|
+
}
|
|
154
|
+
let json;
|
|
155
|
+
try {
|
|
156
|
+
json = JSON.parse(args.input);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
throw new Error("--inputは有効なJSONで指定してください");
|
|
160
|
+
}
|
|
161
|
+
const input = decode(definition.input, json);
|
|
162
|
+
if (!input.success) {
|
|
163
|
+
throw new Error(input.issues.map(issue => `${issue.path}: ${issue.message}`).join("\n"));
|
|
164
|
+
}
|
|
165
|
+
const execution = await perform(implementation, input.value);
|
|
166
|
+
const output = encode(object({ result: definition.result, effects: array(definition.effects) }), execution);
|
|
167
|
+
if (!output.success) {
|
|
168
|
+
throw new Error(output.issues.map(issue => `${issue.path}: ${issue.message}`).join("\n"));
|
|
169
|
+
}
|
|
170
|
+
console.log(JSON.stringify(output.value, undefined, 2));
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
const verifyCommand = defineCommand({
|
|
174
|
+
name: "verify",
|
|
175
|
+
description: "全入力で構築と事後条件を証明できるか検査する(未判定も失敗)",
|
|
176
|
+
args: z.object({
|
|
177
|
+
file: fileArg, behavior: behaviorArg,
|
|
178
|
+
json: arg(z.boolean().default(false), { description: "証明結果をJSONで出力する" }),
|
|
179
|
+
timeout: arg(z.coerce.number().int().positive().default(30000), { description: "モジュール読込を含む実行上限(ミリ秒)" }),
|
|
180
|
+
candidates: arg(z.coerce.number().int().positive().default(4096), { description: "全入力の列挙上限" }),
|
|
181
|
+
ways: arg(z.coerce.number().int().positive().default(10000), { description: "構築経路の列挙上限" }),
|
|
182
|
+
}),
|
|
183
|
+
run: async (args) => {
|
|
184
|
+
const targets = await loadTargets(args.file, args.behavior, true);
|
|
185
|
+
const implementations = [...new Set(targets.flatMap(target => target.implementations ?? []))];
|
|
186
|
+
if (!implementations.length)
|
|
187
|
+
throw new Error("検証するimplementationがありません");
|
|
188
|
+
const proofs = implementations.map(implementation => ({ behavior: implementation.behavior.name, ...verify(implementation, { candidates: args.candidates, ways: args.ways }) }));
|
|
189
|
+
if (args.json)
|
|
190
|
+
console.log(JSON.stringify(proofs, jsonReplacer, 2));
|
|
191
|
+
else
|
|
192
|
+
for (const proof of proofs)
|
|
193
|
+
for (const decision of proof.decisions) {
|
|
194
|
+
console.log(decision.status === "verified" ? `${proof.behavior}/${decision.decision}: verified` : `${resolve(args.file)}: error CHISEL001: ${proof.behavior}/${decision.decision}: ${decision.status}: ${decision.reason}`);
|
|
195
|
+
}
|
|
196
|
+
if (proofs.some(proof => proof.status !== "verified"))
|
|
197
|
+
throw new Error("構築の保証を証明できないimplementationがあります");
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
const modelCheckCommand = defineCommand({
|
|
201
|
+
name: "model-check",
|
|
202
|
+
description: "有限コマンド領域の全到達状態を検査する",
|
|
203
|
+
args: z.object({
|
|
204
|
+
file: fileArg,
|
|
205
|
+
name: arg(z.string().optional(), { description: "検査するmachine名" }),
|
|
206
|
+
json: arg(z.boolean().default(false), { description: "検査結果をJSONで出力する" }),
|
|
207
|
+
engine: arg(z.enum(["chisel", "tla"]).default("chisel"), { description: "状態探索エンジン(chisel / tla)" }),
|
|
208
|
+
timeout: arg(z.coerce.number().int().positive().default(30000), { description: "モジュール読込と検査の実行上限(ミリ秒)" }),
|
|
209
|
+
maxStates: arg(z.coerce.number().int().positive().optional(), { description: "到達状態の上限(既定10000)" }),
|
|
210
|
+
maxCommands: arg(z.coerce.number().int().positive().optional(), { description: "後続コマンドの実行上限(既定1000)" }),
|
|
211
|
+
domainLimit: arg(z.coerce.number().int().positive().optional(), { description: "コマンドの列挙上限(既定10000)" }),
|
|
212
|
+
}),
|
|
213
|
+
run: async (args) => {
|
|
214
|
+
if (args.engine === "tla" && args.maxStates !== undefined) {
|
|
215
|
+
throw new Error("--max-statesは--engine tlaでは使えません");
|
|
216
|
+
}
|
|
217
|
+
const machines = await loadSpecifications(args.file, args.name);
|
|
218
|
+
const options = {
|
|
219
|
+
...(args.maxStates === undefined ? {} : { maxStates: args.maxStates }),
|
|
220
|
+
...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }),
|
|
221
|
+
...(args.domainLimit === undefined ? {} : { domainLimit: args.domainLimit }),
|
|
222
|
+
};
|
|
223
|
+
const reports = (await Promise.all(machines.map(async (declaration) => {
|
|
224
|
+
if (args.engine === "chisel") {
|
|
225
|
+
return [{ name: declaration.name, ...checkMachine(declaration, options) },
|
|
226
|
+
...(declaration.interleavings === undefined ? [] : [{ name: `${declaration.name} (interleavings)`,
|
|
227
|
+
...checkInterleavings(declaration, { ...declaration.interleavings, ...(args.maxStates === undefined ? {} : { maxStates: args.maxStates }),
|
|
228
|
+
...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }) }) }])];
|
|
229
|
+
}
|
|
230
|
+
const { module: _module, ...report } = await checkMachineTla(declaration, { ...(args.domainLimit === undefined ? {} : { domainLimit: args.domainLimit }),
|
|
231
|
+
...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }) });
|
|
232
|
+
return [{ name: declaration.name, ...report },
|
|
233
|
+
...(declaration.interleavings === undefined ? [] : [await (async () => {
|
|
234
|
+
const { module: _interleaved, ...interleaved } = await checkInterleavingsTla(declaration, { ...declaration.interleavings, ...(args.domainLimit === undefined ? {} : { domainLimit: args.domainLimit }) });
|
|
235
|
+
return { name: `${declaration.name} (interleavings)`, ...interleaved };
|
|
236
|
+
})()])];
|
|
237
|
+
}))).flat();
|
|
238
|
+
if (args.json)
|
|
239
|
+
console.log(JSON.stringify(reports, jsonReplacer, 2));
|
|
240
|
+
else
|
|
241
|
+
for (const report of reports) {
|
|
242
|
+
console.log(`${report.name}: ${report.status} (${report.states} states, ${"generatedStates" in report ? `${report.generatedStates} generated states` : "transitions" in report ? `${report.transitions} transitions` : "interleaved"})`);
|
|
243
|
+
if (report.reason)
|
|
244
|
+
console.log(` ${report.reason}`);
|
|
245
|
+
if ("counterexample" in report && report.counterexample)
|
|
246
|
+
console.log(` ${JSON.stringify(report.counterexample, jsonReplacer)}`);
|
|
247
|
+
if ("trace" in report && report.trace)
|
|
248
|
+
console.log(` ${JSON.stringify(report.trace)}`);
|
|
249
|
+
const matrix = "matrix" in report ? report.matrix : undefined;
|
|
250
|
+
if (matrix)
|
|
251
|
+
for (const row of matrix.rows) {
|
|
252
|
+
const show = (value) => typeof value === "string" || typeof value === "bigint" ? String(value) : JSON.stringify(value, jsonReplacer);
|
|
253
|
+
console.log(` ${matrix.columns.map(column => `${column}=${show(row.state[column])}`).join(", ")}`);
|
|
254
|
+
for (const cell of row.cells)
|
|
255
|
+
console.log(` ${JSON.stringify(cell.command, jsonReplacer)}: changes ${cell.changes}${cell.precondition === undefined ? "" : `, precondition ${cell.precondition}`}`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (reports.some(report => report.status !== "held"))
|
|
259
|
+
throw new Error("反例または未確定の結果が出たmachineがあります");
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
const tlaCommand = defineCommand({
|
|
263
|
+
name: "tla",
|
|
264
|
+
description: "実行可能なmachine定義からTLA+のモジュールと設定を生成する",
|
|
265
|
+
args: z.object({
|
|
266
|
+
file: fileArg,
|
|
267
|
+
name: arg(z.string().optional(), { description: "変換するmachine名" }),
|
|
268
|
+
outputDir: arg(z.string().optional(), { description: "生成した.tlaと.cfgを保存するディレクトリ" }),
|
|
269
|
+
force: arg(z.boolean().default(false), { description: "既存の.tlaと.cfgを置き換える" }),
|
|
270
|
+
domainLimit: arg(z.coerce.number().int().positive().optional(), { description: "状態とコマンドの列挙上限" }),
|
|
271
|
+
maxCommands: arg(z.coerce.number().int().positive().optional(), { description: "後続コマンドの実行上限(既定1000)" }),
|
|
272
|
+
timeout: arg(z.coerce.number().int().positive().default(30000), { description: "実行上限(ミリ秒)" }),
|
|
273
|
+
}),
|
|
274
|
+
run: async (args) => {
|
|
275
|
+
const declarations = await loadSpecifications(args.file, args.name);
|
|
276
|
+
if (declarations.length !== 1)
|
|
277
|
+
throw new Error("machineを一意に選べません。--nameで指定してください");
|
|
278
|
+
const module = toTla(declarations[0], {
|
|
279
|
+
...(args.domainLimit === undefined ? {} : { domainLimit: args.domainLimit }),
|
|
280
|
+
...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }),
|
|
281
|
+
});
|
|
282
|
+
if (args.outputDir === undefined)
|
|
283
|
+
console.log(JSON.stringify(module, undefined, 2));
|
|
284
|
+
else {
|
|
285
|
+
await writeTlaPair(args.outputDir, module.name, module.source, module.config, args.force);
|
|
286
|
+
console.log(`Generated ${module.name}.tla and ${module.name}.cfg`);
|
|
287
|
+
}
|
|
288
|
+
},
|
|
289
|
+
});
|
|
290
|
+
async function writeTlaPair(directory, name, source, config, force) {
|
|
291
|
+
await mkdir(directory, { recursive: true });
|
|
292
|
+
const staging = await mkdtemp(resolve(directory, ".chisel-tla-"));
|
|
293
|
+
const files = [
|
|
294
|
+
{ filename: `${name}.tla`, contents: `${source}\n` },
|
|
295
|
+
{ filename: `${name}.cfg`, contents: `${config}\n` },
|
|
296
|
+
];
|
|
297
|
+
const published = [];
|
|
298
|
+
try {
|
|
299
|
+
await Promise.all(files.map(file => writeFile(resolve(staging, file.filename), file.contents, { flag: "wx" })));
|
|
300
|
+
if (force) {
|
|
301
|
+
for (const file of files) {
|
|
302
|
+
const destination = resolve(directory, file.filename);
|
|
303
|
+
try {
|
|
304
|
+
await stat(destination);
|
|
305
|
+
await copyFile(destination, resolve(staging, `${file.filename}.backup`));
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
if (error.code !== "ENOENT")
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
for (const file of files) {
|
|
314
|
+
const destination = resolve(directory, file.filename);
|
|
315
|
+
const staged = resolve(staging, file.filename);
|
|
316
|
+
const backup = resolve(staging, `${file.filename}.backup`);
|
|
317
|
+
if (force)
|
|
318
|
+
await rename(staged, destination);
|
|
319
|
+
else
|
|
320
|
+
await link(staged, destination); // EEXIST keeps both previous files intact.
|
|
321
|
+
let existed = false;
|
|
322
|
+
try {
|
|
323
|
+
await stat(backup);
|
|
324
|
+
existed = true;
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
if (error.code !== "ENOENT")
|
|
328
|
+
throw error;
|
|
329
|
+
}
|
|
330
|
+
published.push({ destination, backup, existed });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
for (const file of published.reverse()) {
|
|
335
|
+
if (file.existed)
|
|
336
|
+
await copyFile(file.backup, file.destination);
|
|
337
|
+
else
|
|
338
|
+
await rm(file.destination, { force: true });
|
|
339
|
+
}
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
finally {
|
|
343
|
+
await rm(staging, { recursive: true, force: true });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
const proveMachineCommand = defineCommand({
|
|
347
|
+
name: "prove-machine",
|
|
348
|
+
description: "初期条件と状態遷移の帰納的な保存を静的に証明する",
|
|
349
|
+
args: z.object({
|
|
350
|
+
file: fileArg,
|
|
351
|
+
name: arg(z.string().optional(), { description: "証明するmachine名" }),
|
|
352
|
+
json: arg(z.boolean().default(false), { description: "証明義務をJSONで出力する" }),
|
|
353
|
+
timeout: arg(z.coerce.number().int().positive().default(30000), { description: "証明の実行上限(ミリ秒)" }),
|
|
354
|
+
}),
|
|
355
|
+
run: async (args) => {
|
|
356
|
+
const declarations = await loadSpecifications(args.file, args.name);
|
|
357
|
+
const reports = await Promise.all(declarations.map(async (declaration) => ({
|
|
358
|
+
name: declaration.name, ...await proveMachine(declaration),
|
|
359
|
+
})));
|
|
360
|
+
if (args.json)
|
|
361
|
+
console.log(JSON.stringify(reports, undefined, 2));
|
|
362
|
+
else
|
|
363
|
+
for (const report of reports) {
|
|
364
|
+
console.log(`${report.name}: ${report.status}`);
|
|
365
|
+
if (report.reason)
|
|
366
|
+
console.log(` ${report.reason}`);
|
|
367
|
+
for (const obligation of report.obligations)
|
|
368
|
+
console.log(` ${obligation.name}: ${obligation.status}${obligation.reason ? ` — ${obligation.reason}` : ""}`);
|
|
369
|
+
}
|
|
370
|
+
if (reports.some(report => report.status !== "proved"))
|
|
371
|
+
throw new Error("証明できないmachineがあります");
|
|
372
|
+
},
|
|
373
|
+
});
|
|
374
|
+
const runMachineCommand = defineCommand({
|
|
375
|
+
name: "run-machine",
|
|
376
|
+
description: "machineにコマンドを適用して次の状態と全遷移をJSONで出力する",
|
|
377
|
+
args: z.object({
|
|
378
|
+
file: fileArg,
|
|
379
|
+
name: arg(z.string().optional(), { description: "実行するmachine名" }),
|
|
380
|
+
state: arg(z.string({ error: "Missing required option --state" }), { description: "現在の状態(JSON)" }),
|
|
381
|
+
command: arg(z.string({ error: "Missing required option --command" }), { description: "コマンド(JSON)" }),
|
|
382
|
+
maxCommands: arg(z.coerce.number().int().positive().optional(), { description: "後続コマンドの実行上限(既定1000)" }),
|
|
383
|
+
fail: arg(z.string().optional(), { description: "失敗させるeffect名(カンマ区切り)" }),
|
|
384
|
+
dieAfter: arg(z.coerce.number().int().min(0).optional(), { description: "effectを持つコマンドをこの数のeffectの後でプロセスを死なせる(0なら最初のeffectの前)" }),
|
|
385
|
+
timeout: arg(z.coerce.number().int().positive().default(30000), { description: "モジュール読込と実行の上限(ミリ秒)" }),
|
|
386
|
+
}),
|
|
387
|
+
run: async (args) => {
|
|
388
|
+
const machines = await loadMachines(args.file, args.name);
|
|
389
|
+
if (machines.length !== 1)
|
|
390
|
+
throw new Error("machineを一意に選べません。--nameで指定してください");
|
|
391
|
+
const declaration = machines[0];
|
|
392
|
+
let state, command;
|
|
393
|
+
try {
|
|
394
|
+
state = JSON.parse(args.state);
|
|
395
|
+
command = JSON.parse(args.command);
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
throw new Error("--stateと--commandは有効なJSONで指定してください");
|
|
399
|
+
}
|
|
400
|
+
const decodedState = decode(declaration.state, state);
|
|
401
|
+
const decodedCommand = decode(declaration.command, command);
|
|
402
|
+
if (!decodedState.success || !decodedCommand.success) {
|
|
403
|
+
throw new Error([...(!decodedState.success ? decodedState.issues : []), ...(!decodedCommand.success ? decodedCommand.issues : [])]
|
|
404
|
+
.map(issue => `${issue.path}: ${issue.message}`).join("\n"));
|
|
405
|
+
}
|
|
406
|
+
const failing = new Set((args.fail ?? "").split(",").map(name => name.trim()).filter(Boolean));
|
|
407
|
+
const result = runMachine(declaration, decodedState.value, decodedCommand.value, { ...(args.maxCommands === undefined ? {} : { maxCommands: args.maxCommands }), fails: effect => failing.has(effect.name),
|
|
408
|
+
...(args.dieAfter === undefined ? {} : { dies: point => point.completed === args.dieAfter }) });
|
|
409
|
+
const output = encode(object({ state: declaration.state, steps: array(object({
|
|
410
|
+
command: declaration.command, before: declaration.state, after: declaration.state,
|
|
411
|
+
performed: array(object({ name: string(), outcome: enumOf(["succeeded", "failed"]) })).optional(),
|
|
412
|
+
died: object({ after: int() }).optional(),
|
|
413
|
+
})) }), result);
|
|
414
|
+
if (!output.success)
|
|
415
|
+
throw new Error(output.issues.map(issue => `${issue.path}: ${issue.message}`).join("\n"));
|
|
416
|
+
console.log(JSON.stringify(output.value, undefined, 2));
|
|
417
|
+
},
|
|
418
|
+
});
|
|
419
|
+
function jsonReplacer(_key, value) { return typeof value === "bigint" ? String(value) : value; }
|
|
420
|
+
export const cli = defineCommand({
|
|
421
|
+
name: "chisel",
|
|
422
|
+
description: "実行可能な業務仕様を段階的に育てるツールキット",
|
|
423
|
+
subCommands: {
|
|
424
|
+
check: checkCommand,
|
|
425
|
+
generate: generateCommand,
|
|
426
|
+
run: runCommand,
|
|
427
|
+
verify: verifyCommand,
|
|
428
|
+
"model-check": modelCheckCommand,
|
|
429
|
+
tla: tlaCommand,
|
|
430
|
+
"prove-machine": proveMachineCommand,
|
|
431
|
+
"run-machine": runMachineCommand,
|
|
432
|
+
},
|
|
433
|
+
});
|
|
434
|
+
async function loadMachines(file, name) {
|
|
435
|
+
const module = (await tsImport(pathToFileURL(resolve(file)).href, import.meta.url));
|
|
436
|
+
const declarations = [...new Set(Object.values(module).filter(isMachine))];
|
|
437
|
+
if (declarations.length === 0)
|
|
438
|
+
throw new Error(`${file}にexportされたmachineがありません`);
|
|
439
|
+
if (name === undefined)
|
|
440
|
+
return declarations;
|
|
441
|
+
const selected = declarations.filter(declaration => declaration.name === name);
|
|
442
|
+
if (selected.length === 0)
|
|
443
|
+
throw new Error(`machine ${name}がありません。選択できるmachine: ${declarations.map(item => item.name).join(", ")}`);
|
|
444
|
+
return selected;
|
|
445
|
+
}
|
|
446
|
+
async function loadSpecifications(file, name) {
|
|
447
|
+
const module = (await tsImport(pathToFileURL(resolve(file)).href, import.meta.url));
|
|
448
|
+
const declarations = [...new Set(Object.values(module).filter(isMachineSpecification))];
|
|
449
|
+
if (declarations.length === 0)
|
|
450
|
+
throw new Error(`${file}にexportされたmachine specificationがありません`);
|
|
451
|
+
const duplicate = declarations.find((declaration, index) => declarations.findIndex(other => other.name === declaration.name) !== index);
|
|
452
|
+
if (duplicate)
|
|
453
|
+
throw new Error(`machine specification ${duplicate.name} が重複しています。specifyMachineのnameで区別してください`);
|
|
454
|
+
if (name === undefined)
|
|
455
|
+
return declarations;
|
|
456
|
+
const selected = declarations.filter(declaration => declaration.name === name);
|
|
457
|
+
if (selected.length === 0)
|
|
458
|
+
throw new Error(`machine ${name}がありません。選択できるmachine: ${declarations.map(item => item.name).join(", ")}`);
|
|
459
|
+
return selected;
|
|
460
|
+
}
|
|
461
|
+
async function loadTargets(file, behavior, includeImplementations = false) {
|
|
462
|
+
const url = pathToFileURL(resolve(file)).href;
|
|
463
|
+
const module = (await tsImport(url, import.meta.url));
|
|
464
|
+
const exportedImplementations = Object.values(module).filter((value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "implementation" &&
|
|
465
|
+
"behavior" in value && isBehavior(value.behavior));
|
|
466
|
+
const exportedBehaviors = new Map();
|
|
467
|
+
for (const [name, value] of Object.entries(module)) {
|
|
468
|
+
if (isBehavior(value)) {
|
|
469
|
+
exportedBehaviors.set(value, name);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (includeImplementations) {
|
|
473
|
+
for (const implementation of exportedImplementations) {
|
|
474
|
+
if (!exportedBehaviors.has(implementation.behavior)) {
|
|
475
|
+
exportedBehaviors.set(implementation.behavior, toIdentifier(implementation.behavior.name));
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const targets = [];
|
|
480
|
+
const referenced = new Set();
|
|
481
|
+
for (const value of Object.values(module)) {
|
|
482
|
+
if (!isSpecification(value)) {
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
const definition = value.examples.behavior;
|
|
486
|
+
referenced.add(definition);
|
|
487
|
+
targets.push({
|
|
488
|
+
behaviorBinding: exportedBehaviors.get(definition) ?? toIdentifier(definition.name),
|
|
489
|
+
specification: value,
|
|
490
|
+
synthesized: false,
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
for (const [definition, binding] of exportedBehaviors) {
|
|
494
|
+
if (referenced.has(definition)) {
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
targets.push({
|
|
498
|
+
behaviorBinding: binding,
|
|
499
|
+
specification: spec(definition.name, {
|
|
500
|
+
examples: examples(definition, {}),
|
|
501
|
+
}),
|
|
502
|
+
synthesized: true,
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
if (targets.length === 0) {
|
|
506
|
+
throw new Error(`${file}にexportされたbehaviorまたはspecificationがありません`);
|
|
507
|
+
}
|
|
508
|
+
const loaded = targets.map(target => ({
|
|
509
|
+
...target,
|
|
510
|
+
implementations: [...new Set([
|
|
511
|
+
...(target.specification.implementation === undefined ? [] : [target.specification.implementation]),
|
|
512
|
+
...exportedImplementations.filter(implementation => implementation.behavior === target.specification.examples.behavior),
|
|
513
|
+
])],
|
|
514
|
+
}));
|
|
515
|
+
if (behavior !== undefined) {
|
|
516
|
+
const selected = loaded.filter(target => target.specification.examples.behavior.name === behavior);
|
|
517
|
+
if (selected.length === 0) {
|
|
518
|
+
const names = [...new Set(targets.map(target => target.specification.examples.behavior.name))];
|
|
519
|
+
throw new Error(`behavior ${behavior}がありません。選択できるbehavior: ${names.join(", ")}`);
|
|
520
|
+
}
|
|
521
|
+
return selected;
|
|
522
|
+
}
|
|
523
|
+
return loaded;
|
|
524
|
+
}
|
|
525
|
+
function formatReport(report) {
|
|
526
|
+
const implementation = report.implementation === "present" ? "あり" : "なし";
|
|
527
|
+
const lines = [
|
|
528
|
+
`${report.specification} (${report.behavior})`,
|
|
529
|
+
formatCoverage("入力variant", report.input),
|
|
530
|
+
formatCoverage("結果variant", report.result),
|
|
531
|
+
formatCoverage("作用variant", report.effects),
|
|
532
|
+
...formatPartitions(report.partitions),
|
|
533
|
+
...formatBorders(report.borders),
|
|
534
|
+
...formatPairs(report.pairs),
|
|
535
|
+
...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}`}`),
|
|
536
|
+
...countedPairs(report.measures.pairs.obligations),
|
|
537
|
+
...report.measures.pairs.notRead.map(reason => ` ? 組み合わせ未計測: ${reason}`),
|
|
538
|
+
...formatEvidence("証拠(入力)", report.evidence.input, ["specified", "executed", "verified"]),
|
|
539
|
+
...formatEvidence("証拠(結果)", report.evidence.result, ["specified", "observed", "verified"]),
|
|
540
|
+
...formatEvidence("証拠(作用)", report.evidence.effects, ["specified", "observed", "verified"]),
|
|
541
|
+
` 実装 ${implementation}`,
|
|
542
|
+
` 分岐 ${formatMeasure(report.measures.arms)}`,
|
|
543
|
+
...formatArms(report.measures.arms),
|
|
544
|
+
` 道筋 ${formatMeasure(report.measures.rules)}`,
|
|
545
|
+
...formatRules(report.measures.rules),
|
|
546
|
+
` 比較 ${report.measures.comparisons.status === "complete"
|
|
547
|
+
? "すべて読めた (complete)"
|
|
548
|
+
: `一部のみ (partial); 読めない比較: ${report.measures.comparisons.notRead.join(", ")}`}`,
|
|
549
|
+
...formatEnsures(report.ensures),
|
|
550
|
+
` 構築の保証 ${report.measures.constructions.status}`,
|
|
551
|
+
...report.measures.constructions.decisions.map(proof => ` ${proof.decision}: ${proof.status} — ${proof.reason}`),
|
|
552
|
+
];
|
|
553
|
+
for (const row of report.unanswered) {
|
|
554
|
+
lines.push(` ! 未回答のexample: ${row.name} — ${row.reason}`);
|
|
555
|
+
}
|
|
556
|
+
for (const pending of report.pendingDecisions) {
|
|
557
|
+
lines.push(` ! 実装保留: ${pending.variant} — ${pending.reason}`);
|
|
558
|
+
}
|
|
559
|
+
for (const gap of report.controlGaps) {
|
|
560
|
+
lines.push(` ! 制御未決定: ${gap.effect} — ${gap.reason}`);
|
|
561
|
+
}
|
|
562
|
+
for (const item of report.incompleteness) {
|
|
563
|
+
if (item.kind === "disregards not checked") {
|
|
564
|
+
lines.push(` ! disregardsを確かめていない行: ${item.subject} — ${item.reason}`);
|
|
565
|
+
}
|
|
566
|
+
else if (!report.failures.some(failure => failure.name === item.subject)) {
|
|
567
|
+
lines.push(` ! 実行できなかった行: ${item.subject} — ${item.reason}`);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
for (const issue of report.modelIssues) {
|
|
571
|
+
lines.push(` ! モデルの誤り: ${issue}`);
|
|
572
|
+
}
|
|
573
|
+
for (const issue of report.fakeIssues) {
|
|
574
|
+
lines.push(` ! fake の誤り: ${issue}`);
|
|
575
|
+
}
|
|
576
|
+
for (const warning of report.fakeWarnings) {
|
|
577
|
+
lines.push(` ! fake と記録済みの例の不一致(警告): ${warning}`);
|
|
578
|
+
}
|
|
579
|
+
for (const failure of report.failures) {
|
|
580
|
+
lines.push(` ✗ ${failure.name}: ${failure.message}`);
|
|
581
|
+
}
|
|
582
|
+
lines.push(`充足度: ${verdictLabels[report.verdict]} (${report.verdict})`);
|
|
583
|
+
return lines.join("\n");
|
|
584
|
+
}
|
|
585
|
+
const verdictLabels = {
|
|
586
|
+
satisfied: "完全",
|
|
587
|
+
not_satisfied: "不完全",
|
|
588
|
+
undetermined: "未確定",
|
|
589
|
+
};
|
|
590
|
+
function formatPartitions(partitions) {
|
|
591
|
+
const lines = [];
|
|
592
|
+
const divided = partitions.flatMap(partition => partition.kind === "divided" ? [partition] : []);
|
|
593
|
+
if (divided.length > 0) {
|
|
594
|
+
lines.push(" クラス");
|
|
595
|
+
for (const partition of divided) {
|
|
596
|
+
const total = partition.covered.length + partition.missing.length;
|
|
597
|
+
const missing = partition.missing.length === 0 ? "" : `; 未網羅 ${partition.missing.join(", ")}`;
|
|
598
|
+
const excluded = partition.excluded.length === 0
|
|
599
|
+
? ""
|
|
600
|
+
: `; 除外 ${partition.excluded.join(", ")} (excluded)`;
|
|
601
|
+
lines.push(` ${padDisplay(partition.path, 19)} ${partition.covered.length}/${total}${missing}${excluded}`);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
const undivided = partitions.filter(partition => partition.kind === "not-derivable");
|
|
605
|
+
if (undivided.length > 0) {
|
|
606
|
+
lines.push(` ${padDisplay("導出できない位置", 21)} ${undivided.map(partition => partition.path).join(", ")} (not derivable)`);
|
|
607
|
+
}
|
|
608
|
+
return lines;
|
|
609
|
+
}
|
|
610
|
+
const pointStatusLabels = {
|
|
611
|
+
met: "met",
|
|
612
|
+
gap: "! 行がない (gap)",
|
|
613
|
+
excluded: "除外 (excluded)",
|
|
614
|
+
"not named": "隣の値なし (not named)",
|
|
615
|
+
"no point": "点なし (no point)",
|
|
616
|
+
"no row owed": "行は不要 (no row owed)",
|
|
617
|
+
undecided: "未決 (undecided)",
|
|
618
|
+
};
|
|
619
|
+
function besideLabel(beside) {
|
|
620
|
+
switch (beside.status) {
|
|
621
|
+
case "told":
|
|
622
|
+
return "見分けた (told)";
|
|
623
|
+
case "not told":
|
|
624
|
+
return `! ${beside.another} と見分ける行がない${beside.input === undefined ? "" : `: ${beside.input} に行を書く`}`;
|
|
625
|
+
case "undecided":
|
|
626
|
+
return `未決 (undecided): ${beside.reason}`;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
function formatBorders(borders) {
|
|
630
|
+
if (borders.length === 0) {
|
|
631
|
+
return [];
|
|
632
|
+
}
|
|
633
|
+
return [
|
|
634
|
+
" 境界",
|
|
635
|
+
...borders.flatMap(border => [
|
|
636
|
+
` ${padDisplay(border.path, 19)} ${border.rule}`,
|
|
637
|
+
...border.points.map(point => ` ${point.role.padEnd(3)} ${padDisplay(point.relation, 20)} ${pointStatusLabels[point.status]}`),
|
|
638
|
+
...(border.beside === undefined ? [] : [` ${padDisplay("隣の線", 24)} ${besideLabel(border.beside)}`]),
|
|
639
|
+
]),
|
|
640
|
+
];
|
|
641
|
+
}
|
|
642
|
+
function formatPairs(pairs) {
|
|
643
|
+
if (pairs.length === 0) {
|
|
644
|
+
return [];
|
|
645
|
+
}
|
|
646
|
+
const counts = pairs.map(pair => `${pair.positions[0]} × ${pair.positions[1]} ${pair.reached}/${pair.total}`);
|
|
647
|
+
return [` ${padDisplay("組み合わせ (pairs)", 21)} ${counts.join(", ")}`];
|
|
648
|
+
}
|
|
649
|
+
function formatEvidence(label, evidence, grades) {
|
|
650
|
+
if (evidence.length === 0) {
|
|
651
|
+
return [];
|
|
652
|
+
}
|
|
653
|
+
const cases = evidence.map(item => {
|
|
654
|
+
const reached = grades.filter(grade => item[grade]);
|
|
655
|
+
return `${item.case}: ${reached.length === 0 ? "なし" : reached.join("・")}`;
|
|
656
|
+
});
|
|
657
|
+
return [` ${padDisplay(label, 21)} ${cases.join(", ")}`];
|
|
658
|
+
}
|
|
659
|
+
function padDisplay(value, width) {
|
|
660
|
+
const displayWidth = [...value].reduce((sum, char) => sum + (/[\u3000-\u30ff\u4e00-\u9fff\uff00-\uffef]/u.test(char) ? 2 : 1), 0);
|
|
661
|
+
return value + " ".repeat(Math.max(width - displayWidth, 0));
|
|
662
|
+
}
|
|
663
|
+
const armStatusLabels = {
|
|
664
|
+
met: "met",
|
|
665
|
+
gap: "! 行がない (gap)",
|
|
666
|
+
"answer owed": "! 期待結果が未回答 (answer owed)",
|
|
667
|
+
};
|
|
668
|
+
const countedLabels = {
|
|
669
|
+
"no row owed": "行は不要 (no row owed)",
|
|
670
|
+
undecided: "未決 (undecided)",
|
|
671
|
+
};
|
|
672
|
+
// A pair no row is owed is counted under its reason, as an arm or a way is.
|
|
673
|
+
function countedPairs(obligations) {
|
|
674
|
+
const counted = new Map();
|
|
675
|
+
for (const pair of obligations) {
|
|
676
|
+
if (pair.status !== "no row owed")
|
|
677
|
+
continue;
|
|
678
|
+
const key = `${countedLabels["no row owed"]}: ${pair.reason ?? ""}`;
|
|
679
|
+
counted.set(key, (counted.get(key) ?? 0) + 1);
|
|
680
|
+
}
|
|
681
|
+
return [...counted].map(([key, count]) => ` ${key} — ${count}件`);
|
|
682
|
+
}
|
|
683
|
+
function formatLines(items, describe) {
|
|
684
|
+
const lines = [];
|
|
685
|
+
const counted = new Map();
|
|
686
|
+
for (const item of items) {
|
|
687
|
+
if (item.status === "no row owed" || item.status === "undecided") {
|
|
688
|
+
const key = `${countedLabels[item.status]}: ${item.reason ?? ""}`;
|
|
689
|
+
counted.set(key, (counted.get(key) ?? 0) + 1);
|
|
690
|
+
}
|
|
691
|
+
else {
|
|
692
|
+
lines.push(` ${describe(item)} ${armStatusLabels[item.status]}`);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
for (const [key, count] of counted) {
|
|
696
|
+
lines.push(` ${key} — ${count}件`);
|
|
697
|
+
}
|
|
698
|
+
return lines;
|
|
699
|
+
}
|
|
700
|
+
function formatArms(measure) {
|
|
701
|
+
if (measure.status === "unavailable") {
|
|
702
|
+
return [];
|
|
703
|
+
}
|
|
704
|
+
return formatLines(measure.arms, arm => `${arm.decision}: guard ${arm.guard} ${arm.arm.padEnd(5)}`);
|
|
705
|
+
}
|
|
706
|
+
function formatRules(measure) {
|
|
707
|
+
if (measure.status === "unavailable") {
|
|
708
|
+
return [];
|
|
709
|
+
}
|
|
710
|
+
return formatLines(measure.rules, rule => `${rule.decision}: ${rule.way}`);
|
|
711
|
+
}
|
|
712
|
+
const classificationLabels = {
|
|
713
|
+
derivable: "導出可能 (derivable)",
|
|
714
|
+
"exact match": "完全一致 (exact match)",
|
|
715
|
+
"always holds": "常に成立 (always holds)",
|
|
716
|
+
"never holds": "決して成立しない (never holds)",
|
|
717
|
+
"runtime only": "実行時のみ (runtime only)",
|
|
718
|
+
};
|
|
719
|
+
function formatEnsures(ensures) {
|
|
720
|
+
if (ensures.rules.length === 0) {
|
|
721
|
+
return [];
|
|
722
|
+
}
|
|
723
|
+
return [
|
|
724
|
+
" ensures",
|
|
725
|
+
...ensures.rules.map(rule => ` ${rule.clause}: ${rule.conjunct} — ${classificationLabels[rule.classification]}`),
|
|
726
|
+
...(ensures.unstated.length === 0
|
|
727
|
+
? []
|
|
728
|
+
: [` 述べられていない結果: ${ensures.unstated.join(", ")}`]),
|
|
729
|
+
];
|
|
730
|
+
}
|
|
731
|
+
function formatMeasure(measure) {
|
|
732
|
+
switch (measure.status) {
|
|
733
|
+
case "complete":
|
|
734
|
+
return "計測済み (complete)";
|
|
735
|
+
case "partial":
|
|
736
|
+
return `一部のみ (partial); 読めないdecision: ${measure.notRead.join(", ")}`;
|
|
737
|
+
case "unavailable":
|
|
738
|
+
return measure.reason === "not applicable"
|
|
739
|
+
? "対象なし (not applicable)"
|
|
740
|
+
: `計測不能 (not measured); 読めないdecision: ${measure.notRead.join(", ")}`;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
function formatCoverage(label, coverage) {
|
|
744
|
+
const missing = coverage.missing.length === 0 ? "" : `; 未網羅 ${coverage.missing.join(", ")}`;
|
|
745
|
+
const excluded = coverage.excluded.length === 0 ? "" : `; 除外 ${coverage.excluded.join(", ")} (excluded)`;
|
|
746
|
+
return ` ${label.padEnd(19)} ${coverage.covered.length}/${coverage.total}${missing}${excluded}`;
|
|
747
|
+
}
|
|
748
|
+
function formatGeneratedExamples(target, generated) {
|
|
749
|
+
const binding = target.behaviorBinding;
|
|
750
|
+
if (generated.length === 0) {
|
|
751
|
+
return `${binding}: 未網羅の入力variantはありません`;
|
|
752
|
+
}
|
|
753
|
+
const rows = generated.map(row => `${formatGeneratedExample(row)},\n`).join("");
|
|
754
|
+
if (!target.synthesized) {
|
|
755
|
+
return target.specification.implementation === undefined
|
|
756
|
+
? `${rows.trimEnd()}\n\n${formatImplementationScaffold(target)}`
|
|
757
|
+
: rows.trimEnd();
|
|
758
|
+
}
|
|
759
|
+
return [
|
|
760
|
+
`export const ${binding}Examples = c.examples(${binding}, {\n${rows}});`,
|
|
761
|
+
"",
|
|
762
|
+
formatImplementationScaffold(target),
|
|
763
|
+
"",
|
|
764
|
+
`export const ${binding}Specification = c.spec(${JSON.stringify(target.specification.name)}, {`,
|
|
765
|
+
` examples: ${binding}Examples,`,
|
|
766
|
+
` implementation: ${binding}Implementation,`,
|
|
767
|
+
"});",
|
|
768
|
+
].join("\n");
|
|
769
|
+
}
|
|
770
|
+
function formatImplementationScaffold(target) {
|
|
771
|
+
const definition = target.specification.examples.behavior;
|
|
772
|
+
const entries = (tags, what) => tags.map(tag => ` ${formatKey(tag)}: c.todo(${JSON.stringify(`${tag}の${what}を決める必要があります`)}),`);
|
|
773
|
+
const controls = definition.effects.variantTags;
|
|
774
|
+
return [
|
|
775
|
+
`export const ${target.behaviorBinding}Implementation = c.implement(${target.behaviorBinding}, {`,
|
|
776
|
+
" cases: {",
|
|
777
|
+
...entries(definition.input.variantTags, "判断"),
|
|
778
|
+
" },",
|
|
779
|
+
...(controls.length === 0 ? [] : [" controls: {", ...entries(controls, "制御"), " },"]),
|
|
780
|
+
"});",
|
|
781
|
+
].join("\n");
|
|
782
|
+
}
|
|
783
|
+
function formatGeneratedExample(generated) {
|
|
784
|
+
const given = indent(formatTypeScriptValue(generated.given), 4);
|
|
785
|
+
const written = generated.with === undefined
|
|
786
|
+
? ""
|
|
787
|
+
: `\n with: ${indent(formatTypeScriptValue(generated.with), 4).trimStart()},`;
|
|
788
|
+
return ` ${JSON.stringify(generated.name)}: {\n given: ${given.trimStart()},${written}\n expect: c.todo(${JSON.stringify(generated.reason)}),\n }`;
|
|
789
|
+
}
|
|
790
|
+
function indent(value, spaces) {
|
|
791
|
+
const prefix = " ".repeat(spaces);
|
|
792
|
+
return value
|
|
793
|
+
.split("\n")
|
|
794
|
+
.map((line, index) => (index === 0 ? line : `${prefix}${line}`))
|
|
795
|
+
.join("\n");
|
|
796
|
+
}
|
|
797
|
+
function toIdentifier(value) {
|
|
798
|
+
const words = value.split(/[^A-Za-z0-9_$]+/).filter(Boolean);
|
|
799
|
+
const [first = "behavior", ...rest] = words;
|
|
800
|
+
return [first, ...rest.map(word => word[0]?.toUpperCase() + word.slice(1))].join("");
|
|
801
|
+
}
|
|
802
|
+
function isRunAsScript() {
|
|
803
|
+
if (process.argv[1] === undefined) {
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
try {
|
|
807
|
+
return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
|
|
808
|
+
}
|
|
809
|
+
catch {
|
|
810
|
+
return false;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (!isMainThread && workerData?.chisel === true) {
|
|
814
|
+
const result = await executeCommand(cli, workerData.argv, { captureLogs: true });
|
|
815
|
+
parentPort.postMessage({ exitCode: result.exitCode, logs: result.logs.entries.map(entry => ({ stream: entry.stream, message: entry.message })), ...(result.error ? { error: result.error.message } : {}) });
|
|
816
|
+
}
|
|
817
|
+
else if (isRunAsScript()) {
|
|
818
|
+
const argv = process.argv.slice(2);
|
|
819
|
+
const at = argv.indexOf("--timeout");
|
|
820
|
+
const assigned = argv.find(arg => arg.startsWith("--timeout="));
|
|
821
|
+
const timeout = Number(assigned?.slice("--timeout=".length) ?? (at >= 0 ? argv[at + 1] : 30000));
|
|
822
|
+
const result = await runIsolated(argv, Number.isSafeInteger(timeout) && timeout > 0 ? timeout : 30000);
|
|
823
|
+
for (const entry of result.logs)
|
|
824
|
+
(entry.stream === "stderr" ? console.error : console.log)(entry.message);
|
|
825
|
+
if (result.error)
|
|
826
|
+
console.error(`Error: ${result.error}`);
|
|
827
|
+
process.exitCode = result.exitCode;
|
|
828
|
+
}
|
|
829
|
+
function feasibilityOptions(args) {
|
|
830
|
+
return {
|
|
831
|
+
...(args.feasibilityCombinations === undefined ? {} : { combinations: args.feasibilityCombinations }),
|
|
832
|
+
...(args.feasibilityWays === undefined ? {} : { ways: args.feasibilityWays }),
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
//# sourceMappingURL=cli.js.map
|