@liminalia/runtime 0.0.0-stage → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +106 -0
  2. package/dist/src/chat.js +60 -0
  3. package/dist/src/commands-play.js +300 -0
  4. package/dist/src/commands.js +534 -0
  5. package/dist/src/coverage.js +208 -0
  6. package/dist/src/headless.js +109 -0
  7. package/dist/src/host.js +1 -0
  8. package/dist/src/index.js +15 -0
  9. package/dist/src/prefetch.js +80 -0
  10. package/dist/src/program.js +131 -0
  11. package/dist/src/project-options.js +84 -0
  12. package/dist/src/retranslate.js +44 -0
  13. package/dist/src/route.js +242 -0
  14. package/dist/src/runtime.js +1929 -0
  15. package/dist/src/save.js +51 -0
  16. package/dist/src/scenario-test.js +200 -0
  17. package/dist/src/state.js +62 -0
  18. package/dist/src/value.js +464 -0
  19. package/dist/src/voice-observe.js +82 -0
  20. package/package.json +33 -4
  21. package/src/chat.ts +109 -0
  22. package/src/commands-play.ts +280 -0
  23. package/src/commands.ts +457 -0
  24. package/src/coverage.ts +257 -0
  25. package/src/headless.ts +139 -0
  26. package/src/host.ts +116 -0
  27. package/src/index.ts +16 -0
  28. package/src/prefetch.ts +78 -0
  29. package/src/program.ts +186 -0
  30. package/src/project-options.ts +128 -0
  31. package/src/retranslate.ts +67 -0
  32. package/src/route.ts +365 -0
  33. package/src/runtime.ts +2143 -0
  34. package/src/save.ts +60 -0
  35. package/src/scenario-test.ts +218 -0
  36. package/src/state.ts +353 -0
  37. package/src/value.ts +443 -0
  38. package/src/voice-observe.ts +85 -0
  39. package/types/src/chat.d.ts +63 -0
  40. package/types/src/commands-play.d.ts +2 -0
  41. package/types/src/commands.d.ts +2 -0
  42. package/types/src/coverage.d.ts +100 -0
  43. package/types/src/headless.d.ts +77 -0
  44. package/types/src/host.d.ts +140 -0
  45. package/types/src/index.d.ts +16 -0
  46. package/types/src/prefetch.d.ts +18 -0
  47. package/types/src/program.d.ts +107 -0
  48. package/types/src/project-options.d.ts +103 -0
  49. package/types/src/retranslate.d.ts +39 -0
  50. package/types/src/route.d.ts +181 -0
  51. package/types/src/runtime.d.ts +553 -0
  52. package/types/src/save.d.ts +21 -0
  53. package/types/src/scenario-test.d.ts +43 -0
  54. package/types/src/state.d.ts +357 -0
  55. package/types/src/value.d.ts +61 -0
  56. package/types/src/voice-observe.d.ts +26 -0
  57. package/README.md +0 -3
@@ -0,0 +1,208 @@
1
+ import { parse } from "@liminalia/lang";
2
+ import { explore } from "./route.js";
3
+ /** ファイルごとに流す回数の上限の既定(lim coverage --runs、制作画面の全ルートテスト)。選び方を試し終えれば、上限より前に止める。 */
4
+ export const DEFAULT_COVERAGE_RUNS = 8;
5
+ /** 実行器の設定から、流し方が使うもの(onStep・onAssign)を外す。 */
6
+ function runtimeFor(o, seed, defaults) {
7
+ const { onStep: _onStep, onAssign: _onAssign, ...rest } = o ?? {};
8
+ return { onError: "continue", ...defaults, ...rest, seed };
9
+ }
10
+ /** 一回分の診断を、同じものをまとめて数える控えに足す。 */
11
+ function addDiagnostics(into, found) {
12
+ for (const d of found) {
13
+ const key = `${d.code} ${d.file}:${d.line} ${d.message}`;
14
+ const seen = into.get(key);
15
+ if (seen)
16
+ seen.count++;
17
+ else
18
+ into.set(key, { diagnostic: d, count: 1 });
19
+ }
20
+ }
21
+ /**
22
+ * 全ファイルを画面なしで、選択肢の選び方を変えながら何通りか流し、本文の網羅と実行時の診断を集める(lim coverage・制作画面の全ルートテスト)。
23
+ * ファイルごとに先頭から、まだ試していない選び方へ広げながら(route.ts の explore)runs 回まで流す。選び方をすべて試し終えたら、そこで止める。
24
+ * 別のファイルへ移ったら、そのファイルの網羅はそのファイル自身の実行に任せて打ち切る。
25
+ * random は種で決まるので、種を変えないと同じ分かれ方しか通らない。seeds を複数渡すと種ごとに流し直す。
26
+ * promised があれば、通った命令が教えた行き先のうち選択肢に一度も出なかったものを "target-never-offered" の警告にする
27
+ * (画面なしの選び方に入れ忘れた行き先は、網羅でも道筋の探索でも通れないため)。
28
+ */
29
+ export async function coverage(o) {
30
+ const runs = o.runs ?? DEFAULT_COVERAGE_RUNS;
31
+ const seeds = o.seeds?.length ? o.seeds : [1];
32
+ const speakers = o.runtime?.speakers ?? [];
33
+ const files = [];
34
+ for (const f of o.files) {
35
+ const lines = new Set();
36
+ const walk = (body) => {
37
+ for (const s of body) {
38
+ if (s.kind === "say" || s.kind === "prose")
39
+ lines.add(s.line);
40
+ if (s.kind === "if")
41
+ for (const b of s.branches)
42
+ walk(b.body);
43
+ if (s.kind === "define")
44
+ walk(s.body);
45
+ }
46
+ };
47
+ const script = parse(await o.loadSource(f), f, { speakers });
48
+ // 下書き(// lim: draft)は遊ぶ人に届かないので、流さず、網羅率にも数えない
49
+ if (script.draft)
50
+ continue;
51
+ walk(script.body);
52
+ files.push({ file: f, lines: [...lines].sort((a, b) => a - b), reached: new Set(), complete: true });
53
+ }
54
+ const diagnostics = new Map();
55
+ const endings = new Map();
56
+ /** 通った命令の行("ファイル:行")と、そこで選択肢に出た飛び先。 */
57
+ const visited = new Set();
58
+ const offered = new Map();
59
+ const total = files.length * seeds.length * runs;
60
+ let done = 0;
61
+ const onStep = o.runtime?.onStep;
62
+ for (const entry of files) {
63
+ const f = entry.file;
64
+ for (const seed of seeds) {
65
+ if (o.signal?.aborted)
66
+ break;
67
+ let left = false;
68
+ let found = [];
69
+ const explored = await explore({
70
+ start: f,
71
+ runs,
72
+ ...(o.signal ? { signal: o.signal } : {}),
73
+ loadSource: (file) => o.loadSource(file),
74
+ // @call で呼ぶだけのファイルも先頭から流すので、呼ばれていない @return は誤りにせずに次の行へ進む(ラベルごとの続きも網羅に数える)
75
+ runtime: { ...runtimeFor(o.runtime, seed, { maxSteps: 200_000 }), returnWithoutCall: "continue" },
76
+ ...(o.promised || onStep
77
+ ? {
78
+ step: (at) => {
79
+ visited.add(`${at.file}:${at.line}`);
80
+ onStep?.(at);
81
+ },
82
+ }
83
+ : {}),
84
+ present: (e, w) => {
85
+ if (e.type !== "page")
86
+ return;
87
+ if (e.at.file !== f) {
88
+ left = true;
89
+ w.runtime.stop();
90
+ return;
91
+ }
92
+ entry.reached.add(e.at.line);
93
+ },
94
+ choice: (at, _options, _w, targets) => {
95
+ const site = `${at.file}:${at.line}`;
96
+ if (!o.promised?.has(site))
97
+ return;
98
+ const seen = offered.get(site) ?? new Set();
99
+ for (const t of targets ?? [])
100
+ if (t)
101
+ seen.add(t);
102
+ offered.set(site, seen);
103
+ },
104
+ onDiagnostic: (d) => found.push(d),
105
+ begin: () => {
106
+ left = false;
107
+ found = [];
108
+ },
109
+ ran: async ({ result, merged }) => {
110
+ if (!merged) {
111
+ const ending = left ? "別ファイルへ" : result.reason;
112
+ endings.set(ending, (endings.get(ending) ?? 0) + 1);
113
+ }
114
+ addDiagnostics(diagnostics, found);
115
+ if (o.onProgress) {
116
+ o.onProgress({ done: ++done, total, file: f });
117
+ // 経過を画面へ流し、ほかの頼みにも答えられるよう、一回ごとに手を離す
118
+ await new Promise((r) => setTimeout(r, 0));
119
+ }
120
+ },
121
+ });
122
+ if (!explored.complete)
123
+ entry.complete = false;
124
+ // 早く試し終えた分も、経過は上限の回数まで進める
125
+ done += runs - explored.runs;
126
+ }
127
+ }
128
+ for (const [site, targets] of o.promised ?? []) {
129
+ if (!visited.has(site))
130
+ continue;
131
+ const seen = offered.get(site);
132
+ const missing = targets.filter((t) => !seen?.has(t));
133
+ if (missing.length === 0)
134
+ continue;
135
+ const at = site.lastIndexOf(":");
136
+ const diagnostic = {
137
+ severity: "warning",
138
+ code: "target-never-offered",
139
+ message: `命令が教えた行き先 ${missing.join("・")} が、画面なしで流したとき一度も選択肢に出ませんでした(全ルートテストでもルートの探索でも通れません)`,
140
+ file: site.slice(0, at),
141
+ line: Number(site.slice(at + 1)),
142
+ hint: "この命令の run で、描画側が答えを返さないときに選ぶ一覧(ctx.pick か ctx.choose)にこの行き先を入れてください。targets と同じ一覧から作ると漏れません",
143
+ };
144
+ diagnostics.set(`${diagnostic.code} ${site}`, { diagnostic, count: 1 });
145
+ }
146
+ return { files, diagnostics: [...diagnostics.values()], endings };
147
+ }
148
+ /**
149
+ * 「はじめから」の位置から、ファイルをまたいで最後まで流す(lim coverage のルートの網羅)。ほかのファイルで決めた変数を引き継いだまま進むので、
150
+ * 前の章の選択で分かれる先も通る。選び方は、まだ試していないものへ広げていく(coverage と同じ。route.ts の explore)。
151
+ * プレイを終える命令(endings)に来たら、そのエンディングに届いたとして止める。
152
+ */
153
+ export async function routeCoverage(o) {
154
+ const runs = o.runs ?? 8;
155
+ const seeds = o.seeds?.length ? o.seeds : [1];
156
+ const reached = new Map();
157
+ const endings = new Map();
158
+ const diagnostics = new Map();
159
+ const out = [];
160
+ let complete = true;
161
+ const onStep = o.runtime?.onStep;
162
+ for (const seed of seeds) {
163
+ let ending = null;
164
+ let last = null;
165
+ let found = [];
166
+ const explored = await explore({
167
+ start: o.entry,
168
+ runs,
169
+ loadSource: (file) => o.loadSource(file),
170
+ runtime: runtimeFor(o.runtime, seed, { maxSteps: 400_000 }),
171
+ step: (at, w) => {
172
+ last = at;
173
+ const name = o.endings?.get(`${at.file}:${at.line}`);
174
+ if (name !== undefined && ending === null) {
175
+ ending = name;
176
+ w.runtime.stop();
177
+ }
178
+ onStep?.(at);
179
+ },
180
+ present: (e) => {
181
+ if (e.type !== "page")
182
+ return;
183
+ const set = reached.get(e.at.file) ?? new Set();
184
+ set.add(e.at.line);
185
+ reached.set(e.at.file, set);
186
+ },
187
+ onDiagnostic: (d) => found.push(d),
188
+ begin: () => {
189
+ ending = null;
190
+ last = null;
191
+ found = [];
192
+ },
193
+ ran: ({ index, result, walk, merged }) => {
194
+ const at = last;
195
+ const where = at ? `${at.file}:${at.line}` : o.entry;
196
+ const reason = ending;
197
+ const name = reason ?? (result.reason === "end" ? `ファイルの終わり(${where})` : result.reason === "max-steps" ? `終わらない(${where} で手数の上限)` : result.reason === "error" ? `エラーで止まった(${where})` : `止まった(${where})`);
198
+ if (!merged)
199
+ endings.set(name, (endings.get(name) ?? 0) + 1);
200
+ out.push({ seed, run: index, ending: name, choices: walk.choices.length, at, ...(merged ? { merged: true } : {}) });
201
+ addDiagnostics(diagnostics, found);
202
+ },
203
+ });
204
+ if (!explored.complete)
205
+ complete = false;
206
+ }
207
+ return { reached, endings, runs: out, complete, diagnostics: [...diagnostics.values()] };
208
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * 画面なしで実行する Host。待ちはすべて即座に終わり、出来事を trace に記録する。
3
+ * テスト・CLI の trace・AI による動作確認に使う。
4
+ */
5
+ export class HeadlessHost {
6
+ options;
7
+ /**
8
+ * 人が操作せずに流すので、命令の autoplay の答えで進める(Host.automated)。描画側の代わりに答えを返すテスト
9
+ * (present を差し替えて、遊ぶ人の操作を真似る)は false にする。
10
+ */
11
+ automated = true;
12
+ trace = [];
13
+ page = null;
14
+ pages = 0;
15
+ choices;
16
+ seenChoices = new Map();
17
+ /** 選択肢(場所と文)ごとの、前に出たときのページの数と、ページを挟まずに続けて出た回数(選択肢だけの輪を見つける)。 */
18
+ choiceLoops = new Map();
19
+ onLimit = null;
20
+ /** 今の場所(実行器の at)。選択肢の輪と、選ぶ選択肢が無いときの診断に、選択肢のある行を入れる(無ければ場所なし)。 */
21
+ where = null;
22
+ constructor(options) {
23
+ this.options = options;
24
+ this.choices = [...(options.choices ?? [])];
25
+ }
26
+ loadSource(file) {
27
+ return this.options.loadSource(file);
28
+ }
29
+ loadData(name) {
30
+ return this.options.loadData ? this.options.loadData(name) : Promise.resolve(undefined);
31
+ }
32
+ async present(event) {
33
+ switch (event.type) {
34
+ case "page":
35
+ this.page = { type: "page", file: event.at.file, line: event.at.line, speaker: event.speaker, ...(event.label ? { label: event.label } : {}), text: "", ...(event.voice ? { voice: `${event.voice.folder}/${event.voice.file}` } : {}) };
36
+ this.trace.push(this.page);
37
+ if (++this.pages >= (this.options.maxPages ?? Infinity))
38
+ this.onLimit?.();
39
+ break;
40
+ case "text":
41
+ if (this.page)
42
+ this.page.text += event.text;
43
+ break;
44
+ case "br":
45
+ if (this.page)
46
+ this.page.text += "\n";
47
+ break;
48
+ case "command":
49
+ this.trace.push({ type: "command", name: event.name, args: event.args });
50
+ break;
51
+ }
52
+ }
53
+ async waitClick() { }
54
+ /** 診断の場所(where が無ければ場所なし)。 */
55
+ place() {
56
+ const at = this.where?.() ?? null;
57
+ return at ? { file: at.file, line: at.line } : { file: "", line: 0 };
58
+ }
59
+ async choose(texts, _signal, looks) {
60
+ // 画像のボタン・押せる範囲で文のないものは、画像の名前で記録する。
61
+ const options = texts.map((t, i) => t || looks?.[i]?.image || t);
62
+ const key = options.join("\u0000");
63
+ // 本文を出さずに同じ選択肢へ戻り続ける輪(どれを選んでも本文の無い選択肢へ戻る)。選び方を一巡しても抜けなければ止める
64
+ // (止めないと実行器の手数の上限まで記録が膨らむ)
65
+ // 同じ文でも台本の別の場所の選択肢は別に数える(「次へ」だけのメニューを続けて並べた作りを輪と見ない)
66
+ const at = this.where?.();
67
+ const loopKey = at ? `${at.file}:${at.line}\u0000${key}` : key;
68
+ const loop = this.choiceLoops.get(loopKey);
69
+ const repeats = loop && loop.pages === this.pages ? loop.repeats + 1 : 0;
70
+ this.choiceLoops.set(loopKey, { pages: this.pages, repeats });
71
+ if (repeats > Math.max(2, options.length * 2)) {
72
+ this.trace.push({ type: "choice", options, selected: null });
73
+ this.trace.push({
74
+ type: "diagnostic",
75
+ diagnostic: { severity: "warning", code: "choice-loop", message: `選択肢「${options.join(" / ")}」に、本文を挟まずに ${repeats} 回続けて戻ったため止めました(どれを選んでも本文の無い選択肢へ戻ります)`, ...this.place(), hint: "抜ける選択肢を足すか、--choose で選ぶものを決めます" },
76
+ });
77
+ this.onLimit?.();
78
+ return null;
79
+ }
80
+ let next = this.choices.shift();
81
+ if (typeof next === "string") {
82
+ const text = next;
83
+ const exact = options.indexOf(text);
84
+ next = exact >= 0 ? exact : options.findIndex((o) => o.includes(text));
85
+ if (next < 0) {
86
+ this.trace.push({ type: "diagnostic", diagnostic: { severity: "warning", code: "unknown-option", message: `選ぶ選択肢「${text}」がありません(${options.join(" / ")})`, ...this.place() } });
87
+ next = undefined;
88
+ }
89
+ }
90
+ const policy = this.options.whenChoicesRunOut ?? "rotate";
91
+ let selected;
92
+ if (next !== undefined)
93
+ selected = next;
94
+ else if (policy === "stop")
95
+ selected = null;
96
+ else if (policy === "first")
97
+ selected = 0;
98
+ else {
99
+ const seen = this.seenChoices.get(key) ?? 0;
100
+ this.seenChoices.set(key, seen + 1);
101
+ selected = seen % options.length;
102
+ }
103
+ this.trace.push({ type: "choice", options, selected });
104
+ return selected;
105
+ }
106
+ onDiagnostic(diagnostic) {
107
+ this.trace.push({ type: "diagnostic", diagnostic });
108
+ }
109
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ export { Runtime } from "./runtime.js";
2
+ export { buildProgram } from "./program.js";
3
+ export { createState, initialStage, toSaveData, voiceFile } from "./state.js";
4
+ export { CHAT_KEEP, CHAT_KEY, chatDialogueActive, chatPartsText, chatQuoteStripper, clearChatMessages, pushChatMessage, readChat } from "./chat.js";
5
+ export { argOrigin, textOrigins, I18N_FIELD } from "./retranslate.js";
6
+ export { display, equals, evaluate, EvalError, setPluginFunctionImpls, truthy } from "./value.js";
7
+ export { CORE_IMPLEMENTATIONS } from "./commands.js";
8
+ export { HeadlessHost } from "./headless.js";
9
+ export { collectPrefetch } from "./prefetch.js";
10
+ export { capture, explore, findRoute, walk } from "./route.js";
11
+ export { coverage, DEFAULT_COVERAGE_RUNS, routeCoverage } from "./coverage.js";
12
+ export { observeVoiceNumbers } from "./voice-observe.js";
13
+ export { projectRuntimeOptions, RUNTIME_OPTION_OWNERS } from "./project-options.js";
14
+ export { DEFAULT_TEST_LIMIT, runScenarioTest } from "./scenario-test.js";
15
+ export { migrateSave, migrateWith, saveProblem, SAVE_VERSION, SaveVersionError } from "./save.js";
@@ -0,0 +1,80 @@
1
+ import { CHOICE_OPTION, normalizeBooleanArgs } from "@liminalia/lang";
2
+ /** 画像のフォルダ。命令が folder 引数を持つときは、それで探し先が替わる。 */
3
+ const IMAGE_FOLDERS = new Set(["bgimage", "fgimage", "image"]);
4
+ /** ボイスを探せるフォルダ(@voice の folder=)。 */
5
+ const VOICE_FOLDERS = new Set(["voice", "sound"]);
6
+ /**
7
+ * index から先の limit 個の命令(本文中の命令と、選択肢の画像も含む)が使う素材を集める。
8
+ * 分岐は両方とも見る(どちらへ進んでも間に合うように)。式で書いた引数は評価せずに飛ばす(副作用を起こさないため)。
9
+ */
10
+ export function collectPrefetch(unit, index, registry, limit = 40) {
11
+ const out = [];
12
+ const seen = new Set();
13
+ const push = (item) => {
14
+ const key = JSON.stringify(item);
15
+ if (seen.has(key))
16
+ return;
17
+ seen.add(key);
18
+ out.push(item);
19
+ };
20
+ const end = Math.min(unit.instructions.length, index + limit);
21
+ for (let i = index; i < end; i++) {
22
+ const ins = unit.instructions[i];
23
+ if (ins.op === "command")
24
+ fromCommand(ins.name, ins.args, registry, push);
25
+ else if (ins.op === "say")
26
+ fromInline(ins.content, registry, push);
27
+ else if (ins.op === "choice")
28
+ for (const o of ins.options)
29
+ fromSpec(CHOICE_OPTION, o.args, push);
30
+ }
31
+ return out;
32
+ }
33
+ function fromInline(nodes, registry, push) {
34
+ for (const n of nodes) {
35
+ if (n.kind === "command")
36
+ fromCommand(n.name, n.args, registry, push);
37
+ else if ("children" in n)
38
+ fromInline(n.children, registry, push);
39
+ }
40
+ }
41
+ function fromCommand(name, args, registry, push) {
42
+ const spec = registry.get(name);
43
+ if (spec)
44
+ fromSpec(spec, args, push);
45
+ }
46
+ function fromSpec(spec, args, push) {
47
+ const values = literalArgs(spec, args);
48
+ let who = null;
49
+ let variant = null;
50
+ let appearance = "";
51
+ for (const [param, value] of Object.entries(values)) {
52
+ const type = spec.params[param]?.type;
53
+ if (!type)
54
+ continue;
55
+ if (type.kind === "asset" && value !== "") {
56
+ const given = typeof values.folder === "string" ? values.folder : null;
57
+ const folder = given !== null && ((IMAGE_FOLDERS.has(type.folder) && IMAGE_FOLDERS.has(given)) || (VOICE_FOLDERS.has(type.folder) && VOICE_FOLDERS.has(given))) ? given : type.folder;
58
+ push({ kind: "asset", folder, path: value });
59
+ }
60
+ if (type.kind === "cast")
61
+ who = value;
62
+ if (type.kind === "variant")
63
+ variant = value;
64
+ if (type.kind === "appearance")
65
+ appearance = value;
66
+ }
67
+ if (who !== null && variant !== null)
68
+ push({ kind: "sprite", who, appearance, variant });
69
+ }
70
+ /** 文字列で書かれた引数だけを、引数名ごとに取り出す。 */
71
+ function literalArgs(spec, args) {
72
+ const out = {};
73
+ let position = 0;
74
+ for (const a of normalizeBooleanArgs(spec, args)) {
75
+ const name = a.key ?? spec.positional[position++];
76
+ if (name !== undefined && a.value.kind === "string")
77
+ out[name] = a.value.value;
78
+ }
79
+ return out;
80
+ }
@@ -0,0 +1,131 @@
1
+ import { pageKeys, voiceLines } from "@liminalia/lang";
2
+ export function buildProgram(script) {
3
+ const main = { id: script.file, file: script.file, instructions: [], labels: {} };
4
+ const defines = new Map();
5
+ emitBlock(script.body, main, defines, false, { withs: 0, loops: 0 });
6
+ const uses = script.body.flatMap((s) => (s.kind === "use" ? [s.file] : []));
7
+ const functions = new Map();
8
+ for (const s of script.body)
9
+ if (s.kind === "function" && !functions.has(s.name))
10
+ functions.set(s.name, { file: script.file, params: s.params, body: s.body });
11
+ return { file: script.file, main, defines, uses, voiceKeys: new Map(voiceLines(script).map((l) => [l.line, l.key])), pageKeys: pageKeys(script), functions };
12
+ }
13
+ /**
14
+ * withs は @with の中身に振る番号(ファイルの中で書いた順。中身の実行単位は `ファイル::@with:番号` で、defines に置く)。
15
+ */
16
+ function emitBlock(body, unit, defines, inIf, counter) {
17
+ const out = unit.instructions;
18
+ for (const s of body) {
19
+ switch (s.kind) {
20
+ case "prose":
21
+ out.push({ op: "say", speaker: null, content: s.content, line: s.line, ...(s.id ? { id: s.id } : {}) });
22
+ break;
23
+ case "say":
24
+ out.push({ op: "say", speaker: s.speaker, ...(s.name ? { name: s.name } : {}), content: s.content, line: s.line, ...(s.id ? { id: s.id } : {}) });
25
+ break;
26
+ case "label":
27
+ unit.labels[s.name] ??= out.length;
28
+ if (inIf)
29
+ (unit.nestedLabels ??= new Set()).add(s.name);
30
+ out.push({ op: "label", name: s.name, line: s.line });
31
+ break;
32
+ case "command":
33
+ out.push({ op: "command", name: s.name, args: s.args, ...(s.body ? { body: s.body.text } : {}), line: s.line });
34
+ break;
35
+ case "if": {
36
+ if (s.with) {
37
+ // @with: 中身を別の実行単位にして、マクロの呼び出しに渡す(マクロの中の @content がそこへ入る)
38
+ const key = `@with:${++counter.withs}`;
39
+ const child = { id: `${unit.file}::${key}`, file: unit.file, instructions: [], labels: {} };
40
+ emitBlock(s.branches[0]?.body ?? [], child, defines, true, counter);
41
+ child.instructions.push({ op: "return", line: s.line });
42
+ defines.set(key, child);
43
+ out.push({ op: "command", name: s.with.name, args: s.with.args, content: child.id, line: s.line });
44
+ break;
45
+ }
46
+ if (s.each) {
47
+ // @for 名前 in 式: 配列(辞書ならキーの並び)を一度だけ求めて隠れた局所変数に置き、番号を進めながら要素を名前に入れてくり返す。
48
+ // 隠れた名前は @ で始まるので、式からは書けない(台本の変数とぶつからない)
49
+ const b = s.branches[0];
50
+ const n = ++counter.loops;
51
+ const list = { kind: "name", name: `@for${n}:list` };
52
+ const index = { kind: "name", name: `@for${n}:i` };
53
+ out.push({ op: "let", name: `@for${n}:list`, value: { kind: "call", callee: EACH_FUNCTION, args: [s.each.list] }, line: s.line });
54
+ out.push({ op: "let", name: `@for${n}:i`, value: { kind: "literal", value: 0 }, line: s.line });
55
+ const start = out.length;
56
+ const branch = { op: "branch", condition: { kind: "binary", op: "<", left: index, right: { kind: "call", callee: "len", args: [list] } }, otherwise: -1, line: s.line };
57
+ out.push(branch);
58
+ out.push({ op: "let", name: s.each.name, value: { kind: "index", object: list, index }, line: s.line });
59
+ out.push({ op: "let", name: `@for${n}:i`, value: { kind: "binary", op: "+", left: index, right: { kind: "literal", value: 1 } }, line: s.line });
60
+ emitBlock(b.body, unit, defines, true, counter);
61
+ out.push({ op: "goto", to: start, line: s.line });
62
+ branch.otherwise = out.length;
63
+ break;
64
+ }
65
+ if (s.loop) {
66
+ // @while: 条件が偽なら @end の後ろへ。中を終えたら条件へ戻る
67
+ const start = out.length;
68
+ const b = s.branches[0];
69
+ const branch = { op: "branch", condition: b.condition, otherwise: -1, line: b.line };
70
+ out.push(branch);
71
+ emitBlock(b.body, unit, defines, true, counter);
72
+ out.push({ op: "goto", to: start, line: b.line });
73
+ branch.otherwise = out.length;
74
+ break;
75
+ }
76
+ const exits = [];
77
+ for (const b of s.branches) {
78
+ let branch = null;
79
+ if (b.condition) {
80
+ branch = { op: "branch", condition: b.condition, otherwise: -1, line: b.line };
81
+ out.push(branch);
82
+ }
83
+ emitBlock(b.body, unit, defines, true, counter);
84
+ const exit = { op: "goto", to: -1, line: b.line };
85
+ out.push(exit);
86
+ exits.push(exit);
87
+ if (branch)
88
+ branch.otherwise = out.length;
89
+ }
90
+ for (const e of exits)
91
+ e.to = out.length;
92
+ break;
93
+ }
94
+ case "choice":
95
+ out.push({ op: "choice", options: s.options, ...(s.args ? { args: s.args } : {}), line: s.line });
96
+ break;
97
+ case "define": {
98
+ const id = `${unit.file}::${s.name}`;
99
+ const child = { id, file: unit.file, instructions: [], labels: {}, params: s.params };
100
+ emitBlock(s.body, child, defines, false, counter);
101
+ child.instructions.push({ op: "return", line: s.line });
102
+ defines.set(s.name, child);
103
+ break;
104
+ }
105
+ case "script":
106
+ out.push({ op: "script", code: s.code, line: s.line });
107
+ break;
108
+ case "set":
109
+ out.push({ op: "set", target: s.target, operator: s.op, value: s.value, line: s.line });
110
+ break;
111
+ case "let":
112
+ out.push({ op: "let", name: s.name, value: s.value, line: s.line });
113
+ break;
114
+ case "jump":
115
+ case "call":
116
+ out.push({ op: s.kind, target: s.target, line: s.line });
117
+ break;
118
+ case "return":
119
+ out.push({ op: "return", ...(s.value ? { value: s.value } : {}), line: s.line });
120
+ break;
121
+ case "content":
122
+ out.push({ op: "content", line: s.line });
123
+ break;
124
+ case "use":
125
+ case "function":
126
+ break;
127
+ }
128
+ }
129
+ }
130
+ /** @for が回すものを配列にする式の関数(実行器だけが呼ぶ。名前は式からは書けない。value.ts)。 */
131
+ export const EACH_FUNCTION = "@each";
@@ -0,0 +1,84 @@
1
+ import { achievementGoals, autoLayoutRules, cgMatcher, chatDialogueOption, endingAchievements, uiForLanguage } from "@liminalia/lang";
2
+ /**
3
+ * 作品の設定から実行器の設定(RuntimeOptions)を作る。遊ぶ側(packages/web)と、画面なしで流すもの(lim trace、lim test、lim coverage、
4
+ * lim reach、lim build --seed、lim voice-lock、制作画面の現在地と全ルートテスト、VS Code の「ここからテストプレイ」)は、どれもこれで作り、
5
+ * 流し方で変えるもの(RUNTIME_OPTION_OWNERS で caller にしたもの)だけを呼ぶ側が足す。片方にだけ作品の設定を渡して、
6
+ * 同じ台本を流した結果が食い違う(自動配置が外れる、言語や章や版で分かれる先が違う、台詞の括弧やボイスの番号が違う)ことを防ぐ。
7
+ */
8
+ /**
9
+ * 実行器の設定の一つ一つを、だれが決めるか。
10
+ * - "project": projectRuntimeOptions が作品の設定から埋める
11
+ * - { caller }: 呼ぶ側が決める(その理由)
12
+ * 実行器の設定を足したら、ここで分けるまで型の確かめが通らない(project-options.test.ts は、関数が埋める項目がここの "project" と
13
+ * ちょうど同じことを見る)。
14
+ */
15
+ export const RUNTIME_OPTION_OWNERS = {
16
+ speakers: "project",
17
+ commands: "project",
18
+ commandDefaults: "project",
19
+ variables: "project",
20
+ afterLoad: "project",
21
+ gameVersion: "project",
22
+ chapters: "project",
23
+ achievementGoals: "project",
24
+ endingAchievements: "project",
25
+ endingKinds: "project",
26
+ cast: "project",
27
+ autoLayout: "project",
28
+ voiceLock: "project",
29
+ cg: "project",
30
+ chatDialogue: "project",
31
+ // 選択肢を本文の流れに出す(ui.choice.position: inline。@nvl の間、選んだものを本文の一部として残す)
32
+ inlineChoices: "project",
33
+ stripQuotes: "project",
34
+ language: "project",
35
+ translator: "project",
36
+ loadData: "project",
37
+ seed: { caller: "乱数の種。遊ぶ側は決めず、台本のテストと網羅は回ごとに決める" },
38
+ maxSteps: { caller: "命令の数の上限。流し方ごとに、終わらない繰り返しで止める所が違う" },
39
+ onError: { caller: "実行時のエラーで止めるか。遊ぶ側と画面なしの流しは続けて知らせる(continue)が、実行器の既定は止める" },
40
+ returnWithoutCall: { caller: "呼ばれていない @return の扱い。網羅のファイルごとの流しだけが、@call で呼ぶだけのファイルを先頭から流すので続ける" },
41
+ onAssign: { caller: "変数を入れたときの知らせ。制作画面が値を決めた行を控えるためのもので、流し方が使う" },
42
+ onStep: { caller: "命令の前の知らせ。網羅と台本のテストが通った行を数えるためのもので、流し方が使う" },
43
+ beforeStep: { caller: "命令の前で待つ。遊ぶ側の作品の画面とブレークポイントだけが使う" },
44
+ programCache: { caller: "読んだ台本の控え。遊ぶ側が一回のプレイを作り直しても読み解き直さないためのもので、流し方が持つ" },
45
+ platform: { caller: "遊んでいる機種。遊ぶ側は調べて入れ、画面なしの流しは省いてパソコンのブラウザとする" },
46
+ };
47
+ const isRecord = (v) => !!v && typeof v === "object" && !Array.isArray(v);
48
+ /** 作品の設定から実行器の設定を作る(RUNTIME_OPTION_OWNERS で "project" にしたもの)。 */
49
+ export function projectRuntimeOptions(src) {
50
+ const c = src.config;
51
+ const extra = isRecord(c.extra) ? c.extra : undefined;
52
+ const ui = isRecord(c.ui) ? c.ui : undefined;
53
+ const languages = Array.isArray(c.languages) ? c.languages : [];
54
+ const language = src.language ?? (typeof languages[0] === "string" ? languages[0] : "");
55
+ const autoLayout = autoLayoutRules(c.autoLayout);
56
+ const cg = cgMatcher(extra);
57
+ const chatDialogue = chatDialogueOption(ui);
58
+ const strip = uiForLanguage(ui, language)?.text?.quotes === "strip";
59
+ return {
60
+ speakers: [...src.speakers],
61
+ commands: [...src.commands],
62
+ cast: src.cast,
63
+ ...(isRecord(c.variables) ? { variables: c.variables } : {}),
64
+ ...(typeof c.afterLoad === "string" && c.afterLoad !== "" ? { afterLoad: c.afterLoad } : {}),
65
+ // 作品の版(セーブに入り、式の save.version で読める。書き出したゲームは project/build.json の版)
66
+ ...(typeof c.version === "string" && c.version !== "" ? { gameVersion: c.version } : {}),
67
+ ...(isRecord(c.commandDefaults) ? { commandDefaults: c.commandDefaults } : {}),
68
+ ...(Array.isArray(c.chapters) ? { chapters: c.chapters } : {}),
69
+ achievementGoals: achievementGoals(extra),
70
+ endingAchievements: endingAchievements(extra),
71
+ ...(isRecord(c.endingKinds) ? { endingKinds: c.endingKinds } : {}),
72
+ ...(autoLayout ? { autoLayout } : {}),
73
+ voiceLock: src.voiceLock ?? null,
74
+ ...(cg ? { cg } : {}),
75
+ ...(chatDialogue ? { chatDialogue } : {}),
76
+ // 選択肢を本文の流れに出す(ui.choice.position: inline。@nvl の間、選んだものを本文の一部として残す。遊ぶ言語の ui.languages を重ねたもの)
77
+ ...(uiForLanguage(ui, language)?.choice?.position === "inline" ? { inlineChoices: true } : {}),
78
+ // 台詞の外側の括弧(ui.text.quotes。遊ぶ言語の ui.languages を重ねたもの)
79
+ stripQuotes: () => strip,
80
+ language,
81
+ translator: src.translator ?? null,
82
+ ...(src.loadData ? { loadData: src.loadData } : {}),
83
+ };
84
+ }