behavior-contracts 0.10.1 → 0.11.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 +246 -350
- package/cli-contract.yaml +49 -51
- package/dist/authoring.d.ts +61 -424
- package/dist/authoring.d.ts.map +1 -1
- package/dist/authoring.js +53 -1157
- package/dist/authoring.js.map +1 -1
- package/dist/behavior.d.ts +7 -15
- package/dist/behavior.d.ts.map +1 -1
- package/dist/behavior.js.map +1 -1
- package/dist/builder.d.ts +4 -4
- package/dist/builder.d.ts.map +1 -1
- package/dist/builder.js +9 -11
- package/dist/builder.js.map +1 -1
- package/dist/cli.js +5 -5
- package/dist/cli.js.map +1 -1
- package/dist/commands/codegen.d.ts.map +1 -1
- package/dist/commands/codegen.js +12 -56
- package/dist/commands/codegen.js.map +1 -1
- package/dist/commands/ts-compile.d.ts +23 -0
- package/dist/commands/ts-compile.d.ts.map +1 -0
- package/dist/commands/ts-compile.js +724 -0
- package/dist/commands/ts-compile.js.map +1 -0
- package/dist/commands/ts-extract.d.ts +67 -1
- package/dist/commands/ts-extract.d.ts.map +1 -1
- package/dist/commands/ts-extract.js +162 -31
- package/dist/commands/ts-extract.js.map +1 -1
- package/dist/generated/contract.d.ts.map +1 -1
- package/dist/generated/contract.js +2 -2
- package/dist/generated/contract.js.map +1 -1
- package/dist/generated/program.js +4 -4
- package/dist/generated/program.js.map +1 -1
- package/dist/generator/core.d.ts +11 -1
- package/dist/generator/core.d.ts.map +1 -1
- package/dist/generator/core.js +5 -4
- package/dist/generator/core.js.map +1 -1
- package/dist/generator/emit-php.d.ts +0 -17
- package/dist/generator/emit-php.d.ts.map +1 -1
- package/dist/generator/emit-php.js +25 -1
- package/dist/generator/emit-php.js.map +1 -1
- package/dist/generator/emit-python.d.ts +0 -7
- package/dist/generator/emit-python.d.ts.map +1 -1
- package/dist/generator/emit-python.js +34 -1
- package/dist/generator/emit-python.js.map +1 -1
- package/dist/generator/emit-straightline-typed-typescript.js +1 -1
- package/dist/generator/emit-straightline-typed-typescript.js.map +1 -1
- package/dist/generator/emit-typed-native-go.d.ts +1 -1
- package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-go.js +110 -107
- package/dist/generator/emit-typed-native-go.js.map +1 -1
- package/dist/generator/emit-typed-native-rust.d.ts +3 -2
- package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
- package/dist/generator/emit-typed-native-rust.js +55 -123
- package/dist/generator/emit-typed-native-rust.js.map +1 -1
- package/dist/generator/emit-typescript-native.js +1 -1
- package/dist/generator/emit-typescript-native.js.map +1 -1
- package/dist/generator/emit-typescript.js +1 -1
- package/dist/generator/emit-typescript.js.map +1 -1
- package/dist/generator/typed.d.ts +5 -1
- package/dist/generator/typed.d.ts.map +1 -1
- package/dist/generator/typed.js +40 -9
- package/dist/generator/typed.js.map +1 -1
- package/dist/guard.d.ts +4 -0
- package/dist/guard.d.ts.map +1 -1
- package/dist/guard.js +26 -8
- package/dist/guard.js.map +1 -1
- package/dist/index.d.ts +19 -57
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +24 -101
- package/dist/index.js.map +1 -1
- package/dist/lowering.d.ts +251 -0
- package/dist/lowering.d.ts.map +1 -0
- package/dist/lowering.js +652 -0
- package/dist/lowering.js.map +1 -0
- package/dist/provenance.js +4 -4
- package/dist/provenance.js.map +1 -1
- package/dist/runtime.d.ts +52 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +77 -0
- package/dist/runtime.js.map +1 -0
- package/dist/spec-versions.d.ts +25 -0
- package/dist/spec-versions.d.ts.map +1 -0
- package/dist/spec-versions.js +26 -0
- package/dist/spec-versions.js.map +1 -0
- package/dist/type-gate.d.ts +12 -0
- package/dist/type-gate.d.ts.map +1 -1
- package/dist/type-gate.js +79 -3
- package/dist/type-gate.js.map +1 -1
- package/package.json +5 -1
- package/dist/bind.d.ts +0 -88
- package/dist/bind.d.ts.map +0 -1
- package/dist/bind.js +0 -155
- package/dist/bind.js.map +0 -1
- package/dist/lower.d.ts +0 -35
- package/dist/lower.d.ts.map +0 -1
- package/dist/lower.js +0 -118
- package/dist/lower.js.map +0 -1
|
@@ -0,0 +1,724 @@
|
|
|
1
|
+
// ════════════════════════════════════════════════════════════════════════════
|
|
2
|
+
// ts-compile — the SOURCE-AST SCP compiler: a behavior class' TS SOURCE → component-graph IR.
|
|
3
|
+
//
|
|
4
|
+
// This is the reader the spec prescribes ("The Compiler parses the AST" —
|
|
5
|
+
// docs/semantic-contract-programming.md §"Structured control syntax"): the method body is read
|
|
6
|
+
// STATICALLY as TS AST and never executed. Native control syntax (`?:` / `&&` / `if` / `.map`) is
|
|
7
|
+
// visible in the AST, so it is LOWERED rather than rejected.
|
|
8
|
+
//
|
|
9
|
+
// Authoring form (#191): `@behavior static` methods are root behaviors; each PARAMETER is one named
|
|
10
|
+
// input port; `@leaf static` methods (on a leaf class like `Db`) are leaves called positionally
|
|
11
|
+
// (`Db.query(sql, params)`). No `$`/`In`, no `defineLeaf` struct, no object-literal port escape.
|
|
12
|
+
//
|
|
13
|
+
// Responsibility boundary (do not blur):
|
|
14
|
+
// - THIS module owns only "how the body is READ" (AST walk + type-checker resolution).
|
|
15
|
+
// - `../lowering.ts` owns the LOWERING RULES (value → Expression IR, node emission, structured
|
|
16
|
+
// control, Component assembly). The runtime recorder in `../authoring.ts` is the second reader
|
|
17
|
+
// of the SAME rules; both call the same functions, so one source lowers to one IR.
|
|
18
|
+
// - Input-port / leaf TS types resolve through `ts-extract.ts` (`extractMethodPorts` for behavior
|
|
19
|
+
// args, `extractLeafMeta` for leaf signatures) — the single TS-type → Portable/PortSchema seam.
|
|
20
|
+
// - Leaf CatalogEntry is built from the signature via the shared `catalogEntryFromLeaf` — the same
|
|
21
|
+
// derivation the recorder path uses (no second catalog-derivation path).
|
|
22
|
+
//
|
|
23
|
+
// `typescript` is a build-time-only OPTIONAL PEER: imported dynamically here and nowhere on the
|
|
24
|
+
// runtime entry (../index.ts).
|
|
25
|
+
// ════════════════════════════════════════════════════════════════════════════
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
27
|
+
import { dirname } from "node:path";
|
|
28
|
+
import { catalogEntryFromLeaf } from "../authoring.js";
|
|
29
|
+
import { SPEC_VERSIONS } from "../spec-versions.js";
|
|
30
|
+
import { mintCompiled } from "../provenance.js";
|
|
31
|
+
import { assertPortableComponentGraph } from "../guard.js";
|
|
32
|
+
import { afail, assembleComponent, DEFAULT_PLAN_CONCURRENCY, declareInputPort, exprMetaOf, inputPortMeta, lowerAs, lowerBinOp, lowerConcat, lowerConditional, lowerFanout, lowerLeafCall, lowerMap, lowerMember, lowerOpt, lowerUnOp, newGraphFrame, nodeMeta, plainExpr, } from "../lowering.js";
|
|
33
|
+
import { createBehaviorProgram, extractLeafMeta, extractMethodPorts, findClass, loadTypeScript, mapSourceElemType, portableFromTypeNode } from "./ts-extract.js";
|
|
34
|
+
/** The BC package root the resolved declaration file of a BC import must live under (this module is
|
|
35
|
+
* `<root>/commands/ts-compile.{ts,js}`), so an authoring builder is recognised by ITS DECLARATION —
|
|
36
|
+
* aliases and re-exports (`./_bc-internal.ts` → `../src/index.ts` → `authoring.ts`) resolve. */
|
|
37
|
+
const BC_MODULE_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
38
|
+
// ── compile-time-only values(データと区別するためのタグ付き値)────────────────────────
|
|
39
|
+
const STATIC_TAG = Symbol("behavior-contracts.ts-compile.static");
|
|
40
|
+
function tagOf(v) {
|
|
41
|
+
if (v === null || typeof v !== "object")
|
|
42
|
+
return undefined;
|
|
43
|
+
return v[STATIC_TAG];
|
|
44
|
+
}
|
|
45
|
+
function childScope(parent) {
|
|
46
|
+
return { vars: new Map(), parent };
|
|
47
|
+
}
|
|
48
|
+
function lookup(scope, name) {
|
|
49
|
+
for (let s = scope; s !== null; s = s.parent)
|
|
50
|
+
if (s.vars.has(name))
|
|
51
|
+
return { hit: true, value: s.vars.get(name) };
|
|
52
|
+
return { hit: false, value: undefined };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* compileBehaviorsFromSource — behavior クラスの **ソース**(file + class 名)を component-graph IR
|
|
56
|
+
* へ lower する(#191 新形)。**各 `@behavior static` メソッド = 1 root Behavior**(`@behavior` は
|
|
57
|
+
* static メソッドマーカー)。各引数=名前付き入力 port、戻り値型=出力 port。本体は実行しない。
|
|
58
|
+
*
|
|
59
|
+
* 入力 port の型は各引数型から型チェッカで解決する(`extractMethodPorts` — 型解決の唯一の seam)。
|
|
60
|
+
*/
|
|
61
|
+
export async function compileBehaviorsFromSource(input, behaviorName, opts = {}) {
|
|
62
|
+
const label = typeof input === "string" ? input : (input.fileName ?? "<in-memory>");
|
|
63
|
+
const ts = await loadTypeScript(label);
|
|
64
|
+
const { checker, sourceFile } = createBehaviorProgram(ts, input);
|
|
65
|
+
const cls = findClass(ts, sourceFile, behaviorName);
|
|
66
|
+
if (cls === undefined)
|
|
67
|
+
afail("NOT_A_BEHAVIOR_CLASS", `class '${behaviorName}' is not declared in '${label}'`);
|
|
68
|
+
const cx = {
|
|
69
|
+
ts,
|
|
70
|
+
checker,
|
|
71
|
+
sf: sourceFile,
|
|
72
|
+
cls,
|
|
73
|
+
moduleDecls: collectModuleDecls(ts, sourceFile),
|
|
74
|
+
moduleValues: new Map(),
|
|
75
|
+
moduleInProgress: new Set(),
|
|
76
|
+
leafNamespaces: new Map(),
|
|
77
|
+
frame: newGraphFrame("<none>"),
|
|
78
|
+
};
|
|
79
|
+
const methods = behaviorMethods(cx, cls);
|
|
80
|
+
if (methods.length === 0)
|
|
81
|
+
afail("NO_PUBLIC_METHOD", `class '${behaviorName}' declares no @behavior static method (each is one root Behavior)`);
|
|
82
|
+
const components = [];
|
|
83
|
+
for (const m of methods) {
|
|
84
|
+
const name = m.name.text;
|
|
85
|
+
cx.frame = newGraphFrame(name);
|
|
86
|
+
const scope = childScope(null);
|
|
87
|
+
// 各引数 = 名前付き入力 port(bind name→ref・port を宣言)。型は overrides(extractMethodPorts)が供給。
|
|
88
|
+
for (const p of m.parameters) {
|
|
89
|
+
if (!ts.isIdentifier(p.name))
|
|
90
|
+
afail("NOT_STATIC", `method '${name}': each parameter must be a plain identifier`);
|
|
91
|
+
declareInputPort(cx.frame, p.name.text);
|
|
92
|
+
scope.vars.set(p.name.text, plainExpr(inputPortMeta(p.name.text)));
|
|
93
|
+
}
|
|
94
|
+
const overrides = m.parameters.length === 0 ? undefined : nonEmpty(extractMethodPorts(ts, checker, m, `class ${behaviorName} method '${name}'`));
|
|
95
|
+
if (m.body === undefined)
|
|
96
|
+
afail("NOT_STATIC", `method '${name}': has no body`);
|
|
97
|
+
const result = evalStatements(cx, m.body.statements, scope);
|
|
98
|
+
components.push(assembleComponent(cx.frame, result.returned ? result.value : undefined, overrides, opts.concurrency ?? DEFAULT_PLAN_CONCURRENCY));
|
|
99
|
+
}
|
|
100
|
+
const ir = {
|
|
101
|
+
irVersion: 3,
|
|
102
|
+
exprVersion: opts.exprVersion ?? SPEC_VERSIONS.expression,
|
|
103
|
+
components,
|
|
104
|
+
};
|
|
105
|
+
assertPortableComponentGraph(ir);
|
|
106
|
+
// AST reader は本体を実行しないので leaf impl は捕捉しない(bind ではなく codegen 用の IR)。
|
|
107
|
+
return mintCompiled(ir, Object.create(null));
|
|
108
|
+
}
|
|
109
|
+
function nonEmpty(ports) {
|
|
110
|
+
return Object.keys(ports).length > 0 ? ports : undefined;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* listBehaviorClasses — ソースファイル中で `@behavior static` メソッドを 1 つ以上持つ全クラス名を
|
|
114
|
+
* 宣言順に返す。新形 corpus はデコレータを持つため node の type-stripping では **import できない**
|
|
115
|
+
* (実行時列挙が不可)。ゲート/freeze はこの AST 列挙で対象クラスを得る(import せず解析だけ)。
|
|
116
|
+
*/
|
|
117
|
+
export async function listBehaviorClasses(fromPath) {
|
|
118
|
+
const ts = await loadTypeScript(fromPath);
|
|
119
|
+
const { checker, sourceFile } = createBehaviorProgram(ts, fromPath);
|
|
120
|
+
const out = [];
|
|
121
|
+
const visit = (node) => {
|
|
122
|
+
if (ts.isClassDeclaration(node) && node.name !== undefined) {
|
|
123
|
+
const hasBehavior = node.members.some((m) => ts.isMethodDeclaration(m) && ts.isIdentifier(m.name) && methodMarker(ts, checker, m) === "behavior");
|
|
124
|
+
if (hasBehavior)
|
|
125
|
+
out.push(node.name.text);
|
|
126
|
+
}
|
|
127
|
+
ts.forEachChild(node, visit);
|
|
128
|
+
};
|
|
129
|
+
visit(sourceFile);
|
|
130
|
+
return out;
|
|
131
|
+
}
|
|
132
|
+
/** メソッドの BC マーカー(`@behavior` / `@leaf`)を宣言元で識別する(名前一致ではなく `bcExportNameOf`)。 */
|
|
133
|
+
function methodMarker(ts, checker, method) {
|
|
134
|
+
for (const d of ts.getDecorators?.(method) ?? []) {
|
|
135
|
+
const expr = ts.isCallExpression(d.expression) ? d.expression.expression : d.expression;
|
|
136
|
+
const n = bcExportNameOf(ts, checker, expr);
|
|
137
|
+
if (n === "behavior" || n === "leaf")
|
|
138
|
+
return n;
|
|
139
|
+
}
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* `@behavior static` メソッド = 1 root Behavior(#191 新形)。マーカーが root を選ぶので、マーカーの
|
|
144
|
+
* 無いメソッド(ヘルパ)・`@leaf`・constructor は含めない。宣言順を保つ(component の並び)。
|
|
145
|
+
*/
|
|
146
|
+
function behaviorMethods(cx, cls) {
|
|
147
|
+
const out = [];
|
|
148
|
+
for (const member of cls.members) {
|
|
149
|
+
if (!cx.ts.isMethodDeclaration(member))
|
|
150
|
+
continue;
|
|
151
|
+
if (!cx.ts.isIdentifier(member.name))
|
|
152
|
+
continue; // `#`-private / computed
|
|
153
|
+
if (methodMarker(cx.ts, cx.checker, member) !== "behavior")
|
|
154
|
+
continue;
|
|
155
|
+
out.push(member);
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
function collectModuleDecls(ts, sf) {
|
|
160
|
+
const out = new Map();
|
|
161
|
+
for (const st of sf.statements) {
|
|
162
|
+
if (!ts.isVariableStatement(st))
|
|
163
|
+
continue;
|
|
164
|
+
for (const d of st.declarationList.declarations)
|
|
165
|
+
if (ts.isIdentifier(d.name) && d.initializer !== undefined)
|
|
166
|
+
out.set(d.name.text, d);
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
function evalStatements(cx, stmts, scope) {
|
|
171
|
+
const ts = cx.ts;
|
|
172
|
+
for (let i = 0; i < stmts.length; i++) {
|
|
173
|
+
const st = stmts[i];
|
|
174
|
+
if (ts.isVariableStatement(st)) {
|
|
175
|
+
for (const d of st.declarationList.declarations) {
|
|
176
|
+
if (!ts.isIdentifier(d.name))
|
|
177
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': destructuring declarations are not lowerable`);
|
|
178
|
+
if (d.initializer === undefined)
|
|
179
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': '${d.name.text}' must be initialised (authoring is declarative)`);
|
|
180
|
+
let value = evalExpr(cx, d.initializer, scope);
|
|
181
|
+
// #193: a binding's declared TYPE annotation IS the node's outType (`const m: T = <node>` — replaces
|
|
182
|
+
// the removed `as<T>(node, …)` builder). Applied through the SAME lowerAs seam `as()` used; the type
|
|
183
|
+
// node is read via the same tsTypeToPortable converter as arg/return types. Only when it annotates a
|
|
184
|
+
// node result (a plain-typed local of a literal/expr carries no node meta → left as-is).
|
|
185
|
+
if (d.type !== undefined) {
|
|
186
|
+
const meta = exprMetaOf(value);
|
|
187
|
+
if (meta !== undefined)
|
|
188
|
+
value = plainExpr(lowerAs(cx.frame, meta, portableFromTypeNode(cx.ts, cx.checker, d.type, `method '${cx.frame.method}' binding '${d.name.text}'`)));
|
|
189
|
+
}
|
|
190
|
+
scope.vars.set(d.name.text, value);
|
|
191
|
+
}
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
if (ts.isReturnStatement(st))
|
|
195
|
+
return { returned: true, value: st.expression === undefined ? undefined : evalExpr(cx, st.expression, scope) };
|
|
196
|
+
if (ts.isExpressionStatement(st)) {
|
|
197
|
+
evalExpr(cx, st.expression, scope);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (ts.isIfStatement(st)) {
|
|
201
|
+
const r = lowerIfStatement(cx, st, stmts.slice(i + 1), scope);
|
|
202
|
+
if (r !== null)
|
|
203
|
+
return r;
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (ts.isBlock(st)) {
|
|
207
|
+
const r = evalStatements(cx, st.statements, childScope(scope));
|
|
208
|
+
if (r.returned)
|
|
209
|
+
return r;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': ${ts.SyntaxKind[st.kind]} is not part of the statically lowerable body vocabulary`);
|
|
213
|
+
}
|
|
214
|
+
return { returned: false, value: undefined };
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* `if` 文の lowering(構造化制御の文形)。分岐が値を返すか副作用(Component 宣言)だけかで
|
|
218
|
+
* Conditional / Guard に分かれる — 判定規則そのものは {@link lowerConditional} が持つ:
|
|
219
|
+
*
|
|
220
|
+
* - `if (c) { … return X; } … return Y;` → then/else 分岐(`rest` が else 側)→ Φ or gate。
|
|
221
|
+
* - `if (c) { … return X; } else { … return Y; }` → 同上(`rest` は到達不能)。
|
|
222
|
+
* - `if (c) { … }`(return 無し)→ Guard 形(分岐内 Component は gate で実行選択される)。
|
|
223
|
+
*
|
|
224
|
+
* 戻り値 null = 「この if は値を produce しない(Guard 形)ので後続の文を続けろ」。
|
|
225
|
+
*/
|
|
226
|
+
function lowerIfStatement(cx, st, rest, scope) {
|
|
227
|
+
const ts = cx.ts;
|
|
228
|
+
const thenStmts = blockStatements(ts, st.thenStatement);
|
|
229
|
+
const elseStmts = st.elseStatement === undefined ? null : blockStatements(ts, st.elseStatement);
|
|
230
|
+
const thenReturns = thenStmts.some((x) => ts.isReturnStatement(x));
|
|
231
|
+
const elseReturns = elseStmts !== null && elseStmts.some((x) => ts.isReturnStatement(x));
|
|
232
|
+
const cond = evalExpr(cx, st.expression, scope);
|
|
233
|
+
const runBlock = (stmts) => () => evalStatements(cx, stmts, childScope(scope)).value;
|
|
234
|
+
// Guard 形: どの分岐も値を返さない(分岐内 Component が gate で実行選択されるだけ)。
|
|
235
|
+
if (!thenReturns && !elseReturns) {
|
|
236
|
+
if (elseStmts !== null)
|
|
237
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': an if/else that produces no value is not lowerable (make the branches return the merged value)`);
|
|
238
|
+
lowerConditional(cx.frame, cond, runBlock(thenStmts), null, plainExpr);
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
// Conditional / Φ 形: else 側は明示 else か、`if (…) return …;` の後続文。
|
|
242
|
+
if (elseStmts !== null) {
|
|
243
|
+
if (!thenReturns || !elseReturns)
|
|
244
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': both branches of an if/else must agree on producing a value (one returns, the other does not)`);
|
|
245
|
+
if (rest.length > 0)
|
|
246
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': statements after an if/else that returns on both branches are unreachable`);
|
|
247
|
+
return { returned: true, value: lowerConditional(cx.frame, cond, runBlock(thenStmts), runBlock(elseStmts), plainExpr) };
|
|
248
|
+
}
|
|
249
|
+
if (rest.length === 0 || !rest.some((x) => ts.isReturnStatement(x) || ts.isIfStatement(x)))
|
|
250
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': the statements after 'if (…) return …' must return the else-side value`);
|
|
251
|
+
return {
|
|
252
|
+
returned: true,
|
|
253
|
+
value: lowerConditional(cx.frame, cond, runBlock(thenStmts), () => evalStatements(cx, rest, childScope(scope)).value, plainExpr),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function blockStatements(ts, st) {
|
|
257
|
+
return ts.isBlock(st) ? st.statements : [st];
|
|
258
|
+
}
|
|
259
|
+
// ── 式の評価 ─────────────────────────────────────────────────────────────────
|
|
260
|
+
function evalExpr(cx, node, scope) {
|
|
261
|
+
const ts = cx.ts;
|
|
262
|
+
// 型のみの包み(`as any` / `satisfies` / `!` / `( )`)は剥がす。
|
|
263
|
+
if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isNonNullExpression(node) || ts.isTypeAssertionExpression(node))
|
|
264
|
+
return evalExpr(cx, node.expression, scope);
|
|
265
|
+
if (ts.isSatisfiesExpression(node))
|
|
266
|
+
return evalExpr(cx, node.expression, scope);
|
|
267
|
+
if (ts.isIdentifier(node))
|
|
268
|
+
return evalIdentifier(cx, node, scope);
|
|
269
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword)
|
|
270
|
+
return true;
|
|
271
|
+
if (node.kind === ts.SyntaxKind.FalseKeyword)
|
|
272
|
+
return false;
|
|
273
|
+
if (node.kind === ts.SyntaxKind.NullKeyword)
|
|
274
|
+
return null;
|
|
275
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
|
|
276
|
+
return node.text;
|
|
277
|
+
if (ts.isNumericLiteral(node))
|
|
278
|
+
return Number(node.text);
|
|
279
|
+
if (ts.isBigIntLiteral(node))
|
|
280
|
+
return BigInt(node.text.slice(0, -1));
|
|
281
|
+
if (ts.isTemplateExpression(node))
|
|
282
|
+
return evalTemplate(cx, node, scope);
|
|
283
|
+
if (ts.isArrayLiteralExpression(node))
|
|
284
|
+
return node.elements.map((e) => evalExpr(cx, e, scope));
|
|
285
|
+
if (ts.isObjectLiteralExpression(node))
|
|
286
|
+
return evalObjectLiteral(cx, node, scope);
|
|
287
|
+
if (ts.isArrowFunction(node))
|
|
288
|
+
return { [STATIC_TAG]: "arrow", node, scope };
|
|
289
|
+
if (ts.isPropertyAccessExpression(node))
|
|
290
|
+
return evalPropertyAccess(cx, node, scope);
|
|
291
|
+
if (ts.isElementAccessExpression(node)) {
|
|
292
|
+
const key = evalExpr(cx, node.argumentExpression, scope);
|
|
293
|
+
if (typeof key !== "string")
|
|
294
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': element access needs a static string key`);
|
|
295
|
+
const target = evalExpr(cx, node.expression, scope);
|
|
296
|
+
// `a?.[k]` は property の `a?.b` と同じ optional chaining(`{refOpt:[…]}`)— 素の `.` と同一視すると
|
|
297
|
+
// null 伝播が黙って落ちる(defect と同じクラス)。ここも lowerOpt を通す。
|
|
298
|
+
if (node.questionDotToken !== undefined)
|
|
299
|
+
return memberOf(cx, plainExpr(lowerOpt(cx.frame, target)), key);
|
|
300
|
+
return memberOf(cx, target, key);
|
|
301
|
+
}
|
|
302
|
+
if (ts.isCallExpression(node))
|
|
303
|
+
return evalCall(cx, node, scope);
|
|
304
|
+
if (ts.isConditionalExpression(node))
|
|
305
|
+
return lowerConditional(cx.frame, evalExpr(cx, node.condition, scope), () => evalExpr(cx, node.whenTrue, scope), () => evalExpr(cx, node.whenFalse, scope), plainExpr);
|
|
306
|
+
if (ts.isPrefixUnaryExpression(node))
|
|
307
|
+
return evalPrefixUnary(cx, node, scope);
|
|
308
|
+
if (ts.isBinaryExpression(node))
|
|
309
|
+
return evalBinary(cx, node, scope);
|
|
310
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': ${ts.SyntaxKind[node.kind]} is not part of the statically lowerable expression vocabulary`);
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* テンプレートリテラル。expression-ir.md §3 の `` `${a}-${b}` `` → **平坦な n-ary** `{concat:[…]}`
|
|
314
|
+
* (nested binaries にしない・全項 string 型)。補間が全て静的スカラなら 1 個の文字列に畳む
|
|
315
|
+
* (JS の評価と同じ結果で、`{concat:[…]}` を作る意味が無い)。
|
|
316
|
+
*/
|
|
317
|
+
function evalTemplate(cx, node, scope) {
|
|
318
|
+
const parts = [node.head.text];
|
|
319
|
+
let hasExpr = false;
|
|
320
|
+
for (const span of node.templateSpans) {
|
|
321
|
+
const v = evalExpr(cx, span.expression, scope);
|
|
322
|
+
if (exprMetaOf(v) !== undefined) {
|
|
323
|
+
if (scalarKindOf(cx, span.expression) !== "string")
|
|
324
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': template interpolation must be string-typed (implicit numeric toString is forbidden — expression-ir.md §3)`);
|
|
325
|
+
hasExpr = true;
|
|
326
|
+
}
|
|
327
|
+
else if (typeof v !== "string" && typeof v !== "number" && typeof v !== "boolean") {
|
|
328
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': template interpolation must be a static scalar or a string-typed port expression`);
|
|
329
|
+
}
|
|
330
|
+
parts.push(v, span.literal.text);
|
|
331
|
+
}
|
|
332
|
+
if (!hasExpr)
|
|
333
|
+
return parts.map((p) => String(p)).join("");
|
|
334
|
+
const kept = parts.filter((p) => p !== ""); // 空の文字列チャンクは連結に寄与しない
|
|
335
|
+
return plainExpr(lowerConcat(kept));
|
|
336
|
+
}
|
|
337
|
+
function evalObjectLiteral(cx, node, scope) {
|
|
338
|
+
const ts = cx.ts;
|
|
339
|
+
const out = {};
|
|
340
|
+
for (const p of node.properties) {
|
|
341
|
+
if (ts.isPropertyAssignment(p)) {
|
|
342
|
+
out[propertyName(cx, p.name)] = evalExpr(cx, p.initializer, scope);
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
if (ts.isShorthandPropertyAssignment(p)) {
|
|
346
|
+
out[p.name.text] = evalIdentifier(cx, p.name, scope);
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': only plain key: value properties are lowerable (no spread / methods / getters)`);
|
|
350
|
+
}
|
|
351
|
+
return out;
|
|
352
|
+
}
|
|
353
|
+
function propertyName(cx, name) {
|
|
354
|
+
const ts = cx.ts;
|
|
355
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name))
|
|
356
|
+
return name.text;
|
|
357
|
+
if (ts.isNumericLiteral(name))
|
|
358
|
+
return name.text;
|
|
359
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': computed property names are not lowerable`);
|
|
360
|
+
}
|
|
361
|
+
function evalIdentifier(cx, node, scope) {
|
|
362
|
+
const local = lookup(scope, node.text);
|
|
363
|
+
if (local.hit)
|
|
364
|
+
return local.value;
|
|
365
|
+
const mod = moduleBinding(cx, node.text);
|
|
366
|
+
if (mod.hit)
|
|
367
|
+
return mod.value;
|
|
368
|
+
// leaf クラス参照(`Db` — `@leaf static` メソッドを持つクラス)→ leaf 名前空間。
|
|
369
|
+
const ns = resolveLeafNamespace(cx, node);
|
|
370
|
+
if (ns !== undefined)
|
|
371
|
+
return ns;
|
|
372
|
+
if (node.text === "undefined")
|
|
373
|
+
return undefined;
|
|
374
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': '${node.text}' is not a statically resolvable binding (behavior bodies may only reference their own parameters, local consts, module consts, or a @leaf class of this compilation)`);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* 識別子を **leaf クラス**(`@leaf static` メソッドを持つ class)へ解決し、その leaf 名前空間を返す。
|
|
378
|
+
* 宣言元は checker で辿る(同一ファイルの class 宣言 / import された class の両方)。leaf メソッドの
|
|
379
|
+
* CatalogEntry はシグネチャから `extractLeafMeta` → `catalogEntryFromLeaf` の単一 SSoT で導く。
|
|
380
|
+
*/
|
|
381
|
+
function resolveLeafNamespace(cx, node) {
|
|
382
|
+
const ts = cx.ts;
|
|
383
|
+
let sym = cx.checker.getSymbolAtLocation(node);
|
|
384
|
+
if (sym === undefined)
|
|
385
|
+
return undefined;
|
|
386
|
+
if (sym.flags & ts.SymbolFlags.Alias)
|
|
387
|
+
sym = cx.checker.getAliasedSymbol(sym);
|
|
388
|
+
const decl = sym.declarations?.find((d) => ts.isClassDeclaration(d));
|
|
389
|
+
if (decl === undefined || decl.name === undefined)
|
|
390
|
+
return undefined;
|
|
391
|
+
const key = decl.name.text;
|
|
392
|
+
const cached = cx.leafNamespaces.get(key);
|
|
393
|
+
if (cached !== undefined)
|
|
394
|
+
return cached;
|
|
395
|
+
const entries = {};
|
|
396
|
+
for (const member of decl.members) {
|
|
397
|
+
if (!ts.isMethodDeclaration(member) || !ts.isIdentifier(member.name))
|
|
398
|
+
continue;
|
|
399
|
+
if (methodMarker(cx.ts, cx.checker, member) !== "leaf")
|
|
400
|
+
continue;
|
|
401
|
+
const leafName = member.name.text;
|
|
402
|
+
const meta = extractLeafMeta(ts, cx.checker, member, `@leaf ${key}.${leafName}`);
|
|
403
|
+
const entry = catalogEntryFromLeaf({ name: leafName, meta, fn: () => undefined });
|
|
404
|
+
entries[leafName] = { [STATIC_TAG]: "leafFn", name: leafName, entry, paramNames: member.parameters.map((p) => p.name.text) };
|
|
405
|
+
}
|
|
406
|
+
if (Object.keys(entries).length === 0)
|
|
407
|
+
return undefined; // @leaf メソッドが無い = leaf クラスではない
|
|
408
|
+
const ns = { [STATIC_TAG]: "leafNs", entries };
|
|
409
|
+
cx.leafNamespaces.set(key, ns);
|
|
410
|
+
return ns;
|
|
411
|
+
}
|
|
412
|
+
/** モジュールスコープの `const` を遅延評価してメモ化する。 */
|
|
413
|
+
function moduleBinding(cx, name) {
|
|
414
|
+
if (cx.moduleValues.has(name))
|
|
415
|
+
return { hit: true, value: cx.moduleValues.get(name) };
|
|
416
|
+
const decl = cx.moduleDecls.get(name);
|
|
417
|
+
if (decl === undefined)
|
|
418
|
+
return { hit: false, value: undefined };
|
|
419
|
+
if (cx.moduleInProgress.has(name))
|
|
420
|
+
afail("NOT_STATIC", `module const '${name}' is self-referential and cannot be statically evaluated`);
|
|
421
|
+
cx.moduleInProgress.add(name);
|
|
422
|
+
try {
|
|
423
|
+
const v = evalExpr(cx, decl.initializer, childScope(null));
|
|
424
|
+
cx.moduleValues.set(name, v);
|
|
425
|
+
return { hit: true, value: v };
|
|
426
|
+
}
|
|
427
|
+
finally {
|
|
428
|
+
cx.moduleInProgress.delete(name);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* プロパティアクセス。`?.`(optional chaining)は expression-ir.md §3 の `a?.b` → `{refOpt:[…]}`
|
|
433
|
+
* へ lower する(`opt(x).b` の record 形と同一の規則 = {@link lowerOpt})。`?.` を素の `.` と同じに
|
|
434
|
+
* 扱うと refOpt が ref に化けて **null 伝播の意味が黙って落ちる**ため、ここは分岐が必須。
|
|
435
|
+
*/
|
|
436
|
+
function evalPropertyAccess(cx, node, scope) {
|
|
437
|
+
const ts = cx.ts;
|
|
438
|
+
if (!ts.isIdentifier(node.name))
|
|
439
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': private-name property access is not lowerable outside a helper call`);
|
|
440
|
+
const target = evalExpr(cx, node.expression, scope);
|
|
441
|
+
if (node.questionDotToken !== undefined)
|
|
442
|
+
return memberOf(cx, plainExpr(lowerOpt(cx.frame, target)), node.name.text);
|
|
443
|
+
return memberOf(cx, target, node.name.text);
|
|
444
|
+
}
|
|
445
|
+
function memberOf(cx, obj, key) {
|
|
446
|
+
const tag = tagOf(obj);
|
|
447
|
+
if (tag === "leafNs") {
|
|
448
|
+
const fn = obj.entries[key];
|
|
449
|
+
if (fn === undefined)
|
|
450
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': '${key}' is not a component of this catalog`);
|
|
451
|
+
return fn;
|
|
452
|
+
}
|
|
453
|
+
const meta = exprMetaOf(obj);
|
|
454
|
+
if (meta !== undefined)
|
|
455
|
+
return plainExpr(lowerMember(cx.frame, meta, key));
|
|
456
|
+
if (obj !== null && typeof obj === "object" && !Array.isArray(obj) && tag === undefined)
|
|
457
|
+
return obj[key];
|
|
458
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': '.${key}' is not resolvable on this value`);
|
|
459
|
+
}
|
|
460
|
+
function evalPrefixUnary(cx, node, scope) {
|
|
461
|
+
const ts = cx.ts;
|
|
462
|
+
if (node.operator === ts.SyntaxKind.MinusToken) {
|
|
463
|
+
const v = evalExpr(cx, node.operand, scope);
|
|
464
|
+
if (typeof v === "number")
|
|
465
|
+
return -v;
|
|
466
|
+
if (typeof v === "bigint")
|
|
467
|
+
return -v;
|
|
468
|
+
return plainExpr(lowerUnOp("neg", v));
|
|
469
|
+
}
|
|
470
|
+
// `!x` は expression-ir の `not`(authoring の record 形 not(x) と同一の operator)。
|
|
471
|
+
if (node.operator === ts.SyntaxKind.ExclamationToken)
|
|
472
|
+
return plainExpr(lowerUnOp("not", evalExpr(cx, node.operand, scope)));
|
|
473
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': unary operator is not in the Expression IR vocabulary`);
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* ネイティブ 2 項構文 → Expression IR operator の 1:1 写像(authoring の record 形と同一)。
|
|
477
|
+
* `===`→eq / `!==`→ne / 比較→lt..ge / `??`→coalesce / `-`→sub / `*`→mul / `/`→div / `%`→mod。
|
|
478
|
+
* `||`/`&&`(→or/and or Guard・{@link evalBinary})と `+`(→静的型で concat/add・{@link evalPlus})と
|
|
479
|
+
* `==`/`!=`(loose equality・reject)はこの表に載せず evalBinary で個別に扱う。
|
|
480
|
+
*/
|
|
481
|
+
function nativeBinaryOp(ts, kind) {
|
|
482
|
+
const K = ts.SyntaxKind;
|
|
483
|
+
switch (kind) {
|
|
484
|
+
case K.EqualsEqualsEqualsToken:
|
|
485
|
+
return "eq";
|
|
486
|
+
case K.ExclamationEqualsEqualsToken:
|
|
487
|
+
return "ne";
|
|
488
|
+
case K.LessThanToken:
|
|
489
|
+
return "lt";
|
|
490
|
+
case K.LessThanEqualsToken:
|
|
491
|
+
return "le";
|
|
492
|
+
case K.GreaterThanToken:
|
|
493
|
+
return "gt";
|
|
494
|
+
case K.GreaterThanEqualsToken:
|
|
495
|
+
return "ge";
|
|
496
|
+
case K.QuestionQuestionToken:
|
|
497
|
+
return "coalesce";
|
|
498
|
+
case K.MinusToken:
|
|
499
|
+
return "sub";
|
|
500
|
+
case K.AsteriskToken:
|
|
501
|
+
return "mul";
|
|
502
|
+
case K.SlashToken:
|
|
503
|
+
return "div";
|
|
504
|
+
case K.PercentToken:
|
|
505
|
+
return "mod";
|
|
506
|
+
default:
|
|
507
|
+
return undefined;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* ネイティブ 2 項構文 → Expression IR / 構造化制御(expression-ir.md §3 の閉集合と
|
|
512
|
+
* semantic-contract-programming.md「構造化制御構文」):
|
|
513
|
+
*
|
|
514
|
+
* - `===`/`!==`/`<`/`<=`/`>`/`>=`/`??`/`-`/`*`/`/`/`%` → 同名 operator({@link nativeBinaryOp})。
|
|
515
|
+
* - `&&`/`||` は **bool×bool のときだけ** Expression の `and`/`or`(§3 は bool×bool のみと規定)。
|
|
516
|
+
* bool でない右辺を持つ `&&` は spec §"Conditional and Φ" の **Guard 形**(`cond && A(...)`)。
|
|
517
|
+
* どちらかは**静的型で決まる**(`+` と同じ「TS の overloaded 構文はコンパイル時に静的型で解決」規律)。
|
|
518
|
+
* - `+` は §5 のとおり静的型で `concat`(string)/ `add`(numeric)へ解決する({@link evalPlus})。
|
|
519
|
+
* - `==`/`!=` は §3 の明示的 reject リスト(loose equality)— loud に拒否する。
|
|
520
|
+
*/
|
|
521
|
+
function evalBinary(cx, node, scope) {
|
|
522
|
+
const K = cx.ts.SyntaxKind;
|
|
523
|
+
const kind = node.operatorToken.kind;
|
|
524
|
+
if (kind === K.PlusToken)
|
|
525
|
+
return evalPlus(cx, node, scope);
|
|
526
|
+
if (kind === K.AmpersandAmpersandToken || kind === K.BarBarToken) {
|
|
527
|
+
if (isBooleanOperand(cx, node.left) && isBooleanOperand(cx, node.right))
|
|
528
|
+
return plainExpr(lowerBinOp(kind === K.AmpersandAmpersandToken ? "and" : "or", evalExpr(cx, node.left, scope), evalExpr(cx, node.right, scope)));
|
|
529
|
+
if (kind === K.BarBarToken)
|
|
530
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': '||' is bool×bool only (expression-ir.md §3); for a default value use '??' (coalesce), and there is no else-less guard form for '||'`);
|
|
531
|
+
// Guard 形: 右辺に Component を含む `cond && A(...)`。
|
|
532
|
+
return lowerConditional(cx.frame, evalExpr(cx, node.left, scope), () => evalExpr(cx, node.right, scope), null, plainExpr);
|
|
533
|
+
}
|
|
534
|
+
const op = nativeBinaryOp(cx.ts, kind);
|
|
535
|
+
if (op !== undefined)
|
|
536
|
+
return plainExpr(lowerBinOp(op, evalExpr(cx, node.left, scope), evalExpr(cx, node.right, scope)));
|
|
537
|
+
if (kind === K.EqualsEqualsToken || kind === K.ExclamationEqualsToken)
|
|
538
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': loose equality '${node.operatorToken.getText(cx.sf)}' is outside the portable Expression closed set (expression-ir.md §3 rejects it) — use '===' / '!=='`);
|
|
539
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': binary '${node.operatorToken.getText(cx.sf)}' is outside the portable Expression closed set (expression-ir.md §3)`);
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* `+` の解決(expression-ir.md §5「TS の overloaded `+` は静的型でコンパイル時に解決」):
|
|
543
|
+
* 全項が string → **平坦な n-ary** `{concat:[…]}`(§3: nested binaries にしない)、全項が numeric →
|
|
544
|
+
* 左結合の `{add:[a,b]}` 連鎖。混在・静的型が取れない項は暗黙変換になるため loud に拒否する。
|
|
545
|
+
*/
|
|
546
|
+
function evalPlus(cx, node, scope) {
|
|
547
|
+
const parts = flattenPlus(cx, node);
|
|
548
|
+
const kinds = parts.map((p) => scalarKindOf(cx, p));
|
|
549
|
+
const values = parts.map((p) => evalExpr(cx, p, scope)); // 評価順はソース順(左→右)
|
|
550
|
+
if (kinds.every((k) => k === "string"))
|
|
551
|
+
return plainExpr(lowerConcat(values));
|
|
552
|
+
if (kinds.every((k) => k === "number"))
|
|
553
|
+
return values.slice(1).reduce((acc, v) => plainExpr(lowerBinOp("add", acc, v)), values[0]);
|
|
554
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': '+' needs operands whose static types are all string (concat) or all numeric (add) — there are no implicit conversions (expression-ir.md §5)`);
|
|
555
|
+
}
|
|
556
|
+
/** 左結合の `+` 連鎖を平坦化する(`a + b + c` → [a, b, c])。 */
|
|
557
|
+
function flattenPlus(cx, node) {
|
|
558
|
+
const ts = cx.ts;
|
|
559
|
+
if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken)
|
|
560
|
+
return [...flattenPlus(cx, node.left), ...flattenPlus(cx, node.right)];
|
|
561
|
+
return [node];
|
|
562
|
+
}
|
|
563
|
+
/** 式の静的スカラ種(型チェッカが読む宣言型。推論ではなく宣言の読み取り)。 */
|
|
564
|
+
function scalarKindOf(cx, node) {
|
|
565
|
+
const F = cx.ts.TypeFlags;
|
|
566
|
+
const t = cx.checker.getTypeAtLocation(node);
|
|
567
|
+
if (t.flags & F.StringLike)
|
|
568
|
+
return "string";
|
|
569
|
+
if (t.flags & F.NumberLike)
|
|
570
|
+
return "number";
|
|
571
|
+
// `Int`/`Float` ブランド(`number & {…}`)は intersection。
|
|
572
|
+
if (t.isIntersection() && t.types.some((x) => x.flags & F.NumberLike))
|
|
573
|
+
return "number";
|
|
574
|
+
return undefined;
|
|
575
|
+
}
|
|
576
|
+
/** オペランドの静的型が bool か(`&&`/`||` の Expression 形 ⇔ Guard 形の判別)。 */
|
|
577
|
+
function isBooleanOperand(cx, node) {
|
|
578
|
+
return (cx.checker.getTypeAtLocation(node).flags & cx.ts.TypeFlags.BooleanLike) !== 0;
|
|
579
|
+
}
|
|
580
|
+
// ── 呼び出し ─────────────────────────────────────────────────────────────────
|
|
581
|
+
function evalCall(cx, node, scope) {
|
|
582
|
+
const ts = cx.ts;
|
|
583
|
+
const callee = node.expression;
|
|
584
|
+
// `this.#helper(...)` / `this._helper(...)` — ヘルパはこの record にインライン展開される。
|
|
585
|
+
if (ts.isPropertyAccessExpression(callee) && callee.expression.kind === ts.SyntaxKind.ThisKeyword)
|
|
586
|
+
return inlineHelper(cx, callee.name, node, scope);
|
|
587
|
+
// ネイティブ `.map`(本物の Array.map)→ Map ノード。新形の `as`/`refsConnection` は standalone
|
|
588
|
+
// builder(fluent メソッドではない — 自然な TS では leaf 結果は本物の値でメソッドを持たない)。
|
|
589
|
+
if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.name) && callee.name.text === "map") {
|
|
590
|
+
const target = evalExpr(cx, callee.expression, scope);
|
|
591
|
+
const meta = exprMetaOf(target);
|
|
592
|
+
if (meta !== undefined)
|
|
593
|
+
return callMapOnResult(cx, meta, node, scope);
|
|
594
|
+
}
|
|
595
|
+
const fn = evalCallee(cx, callee, scope);
|
|
596
|
+
if (tagOf(fn) === "leafFn") {
|
|
597
|
+
const leaf = fn;
|
|
598
|
+
// 新形: positional 引数 → leaf のシグネチャ引数名で port を作る(object-literal エスケープなし)。
|
|
599
|
+
if (node.arguments.length > leaf.paramNames.length)
|
|
600
|
+
afail("BAD_PORT_VALUE", `leaf '${leaf.name}' takes ${leaf.paramNames.length} argument(s), got ${node.arguments.length}`);
|
|
601
|
+
const ports = {};
|
|
602
|
+
node.arguments.forEach((a, i) => {
|
|
603
|
+
ports[leaf.paramNames[i]] = evalExpr(cx, a, scope);
|
|
604
|
+
});
|
|
605
|
+
const id = lowerLeafCall(cx.frame, leaf.name, leaf.entry, ports);
|
|
606
|
+
return id === null
|
|
607
|
+
? plainExpr({ node: null, refPath: null, refOp: "ref", isInput: false, mapResult: true })
|
|
608
|
+
: plainExpr(nodeMeta(id));
|
|
609
|
+
}
|
|
610
|
+
if (tagOf(fn) === "builder")
|
|
611
|
+
return callBcBuilder(cx, fn.name, node, scope);
|
|
612
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': call target is not a @leaf component or an authoring builder`);
|
|
613
|
+
}
|
|
614
|
+
/** callee の静的解決: ローカル → モジュール const → BC の authoring builder(宣言元で判定)。 */
|
|
615
|
+
function evalCallee(cx, callee, scope) {
|
|
616
|
+
const ts = cx.ts;
|
|
617
|
+
if (ts.isIdentifier(callee)) {
|
|
618
|
+
const local = lookup(scope, callee.text);
|
|
619
|
+
if (local.hit)
|
|
620
|
+
return local.value;
|
|
621
|
+
const mod = moduleBinding(cx, callee.text);
|
|
622
|
+
if (mod.hit)
|
|
623
|
+
return mod.value;
|
|
624
|
+
const bc = bcExportNameOf(ts, cx.checker, callee);
|
|
625
|
+
if (bc !== undefined)
|
|
626
|
+
return { [STATIC_TAG]: "builder", name: bc };
|
|
627
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': '${callee.text}' is not a resolvable call target`);
|
|
628
|
+
}
|
|
629
|
+
return evalExpr(cx, callee, scope);
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* BC の import の **宣言元**(re-export/alias を辿った先)がこのパッケージなら、その export 名を返す。
|
|
633
|
+
* 名前一致ではなく宣言で判定するので、`import { concat as cat }` も consumer 側の同名関数との
|
|
634
|
+
* 取り違えも起こらない。
|
|
635
|
+
*/
|
|
636
|
+
function bcExportNameOf(ts, checker, node) {
|
|
637
|
+
if (!ts.isIdentifier(node))
|
|
638
|
+
return undefined;
|
|
639
|
+
let sym = checker.getSymbolAtLocation(node);
|
|
640
|
+
if (sym === undefined)
|
|
641
|
+
return undefined;
|
|
642
|
+
if (sym.flags & ts.SymbolFlags.Alias)
|
|
643
|
+
sym = checker.getAliasedSymbol(sym);
|
|
644
|
+
const decl = sym.declarations?.[0];
|
|
645
|
+
if (decl === undefined)
|
|
646
|
+
return undefined;
|
|
647
|
+
const file = decl.getSourceFile().fileName;
|
|
648
|
+
if (!file.startsWith(BC_MODULE_ROOT))
|
|
649
|
+
return undefined;
|
|
650
|
+
return sym.getName();
|
|
651
|
+
}
|
|
652
|
+
/** BC authoring builder 呼び。lowering 規則は lowering.ts の同名 lower* が持つ。 */
|
|
653
|
+
function callBcBuilder(cx, name, node, scope) {
|
|
654
|
+
// 式・構造化制御はネイティブ TS 構文(`+`/`?:`/`&&`/`if`/template/`?.`)で書き、`evalExpr` が直接 lower
|
|
655
|
+
// する。authoring builder の**関数呼び形**で残るのは、ネイティブ構文に対応の無い 2 つだけ:
|
|
656
|
+
// - `opt(x)` — optional-chain の source(`opt(x).f` / `opt(x)` = refOpt)。
|
|
657
|
+
// - `refsConnection(list, cb, opts)` — refs fanout(dedupe + implicit-source 剥がし)。
|
|
658
|
+
if (name === "opt")
|
|
659
|
+
return plainExpr(lowerOpt(cx.frame, evalExpr(cx, node.arguments[0], scope)));
|
|
660
|
+
if (name === "refsConnection") {
|
|
661
|
+
const overMeta = exprMetaOf(evalExpr(cx, node.arguments[0], scope));
|
|
662
|
+
if (overMeta === undefined)
|
|
663
|
+
afail("WHOLE_INPUT", `method '${cx.frame.method}': refsConnection(...) first argument must be a list expression`);
|
|
664
|
+
const arrow = evalExpr(cx, node.arguments[1], scope);
|
|
665
|
+
if (tagOf(arrow) !== "arrow")
|
|
666
|
+
afail("FANOUT_NOT_LOWERABLE", `method '${cx.frame.method}': refsConnection expects an inline arrow callback`);
|
|
667
|
+
const opts = node.arguments[2] === undefined ? undefined : evalExpr(cx, node.arguments[2], scope);
|
|
668
|
+
const run = (elem) => runArrow(cx, arrow, [plainExpr(elem)]);
|
|
669
|
+
return plainExpr(nodeMeta(lowerFanout(cx.frame, overMeta, run, opts)));
|
|
670
|
+
}
|
|
671
|
+
return afail("NOT_STATIC", `method '${cx.frame.method}': authoring builder '${name}' is not lowerable from source`);
|
|
672
|
+
}
|
|
673
|
+
/** arrow の本体(式形 / ブロック形)を読む。 */
|
|
674
|
+
function runArrow(cx, arrow, argValues) {
|
|
675
|
+
const ts = cx.ts;
|
|
676
|
+
const scope = childScope(arrow.scope);
|
|
677
|
+
arrow.node.parameters.forEach((p, i) => {
|
|
678
|
+
if (!ts.isIdentifier(p.name))
|
|
679
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': callback parameters must be plain identifiers`);
|
|
680
|
+
scope.vars.set(p.name.text, argValues[i]);
|
|
681
|
+
});
|
|
682
|
+
if (ts.isBlock(arrow.node.body)) {
|
|
683
|
+
const r = evalStatements(cx, arrow.node.body.statements, scope);
|
|
684
|
+
return r.returned ? r.value : undefined;
|
|
685
|
+
}
|
|
686
|
+
return evalExpr(cx, arrow.node.body, scope);
|
|
687
|
+
}
|
|
688
|
+
/** ネイティブ `list.map(cb, opts?)`(本物の Array.map)→ Map ノード。 */
|
|
689
|
+
function callMapOnResult(cx, meta, node, scope) {
|
|
690
|
+
const cb = evalExpr(cx, node.arguments[0], scope);
|
|
691
|
+
if (tagOf(cb) !== "arrow")
|
|
692
|
+
afail("MAP_NOT_LOWERABLE", `method '${cx.frame.method}': .map expects an inline arrow callback`);
|
|
693
|
+
const arrow = cb;
|
|
694
|
+
if (arrow.node.parameters.length > 1)
|
|
695
|
+
afail("MAP_NOT_LOWERABLE", `method '${cx.frame.method}': the .map callback takes exactly one element binding`);
|
|
696
|
+
const opts = node.arguments[1] === undefined ? undefined : evalExpr(cx, node.arguments[1], scope);
|
|
697
|
+
// `into` は augment 済み要素型(source ⊕ {into: leaf})を持つ。source 要素型は over 配列の TS 型から
|
|
698
|
+
// 読む(宣言由来)ので、リーダーがここで抽出し lowerMap の型導出へ渡す(注記は不要)。
|
|
699
|
+
const overExpr = node.expression.expression;
|
|
700
|
+
const intoSourceElem = opts?.into !== undefined ? mapSourceElemType(cx.ts, cx.checker, overExpr, `method '${cx.frame.method}' .map 'into'`) : undefined;
|
|
701
|
+
const run = (elem) => runArrow(cx, arrow, [plainExpr(elem)]);
|
|
702
|
+
return plainExpr(nodeMeta(lowerMap(cx.frame, meta, run, opts, intoSourceElem)));
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* `this.<helper>(...)` のインライン展開。ヘルパは publish されない(`#`-private / `_`-prefix)が、
|
|
706
|
+
* 本体からの呼び出しは呼び出し元メソッドの graph にインライン展開される(recorder 経路と同じ規約)。
|
|
707
|
+
*/
|
|
708
|
+
function inlineHelper(cx, name, call, scope) {
|
|
709
|
+
const ts = cx.ts;
|
|
710
|
+
const target = name.text;
|
|
711
|
+
const member = cx.cls.members.find((m) => ts.isMethodDeclaration(m) && m.name !== undefined && m.name.text === target);
|
|
712
|
+
if (member?.body === undefined)
|
|
713
|
+
afail("NOT_STATIC", `method '${cx.frame.method}': helper '${target}' is not a method of this class`);
|
|
714
|
+
const args = call.arguments.map((a) => evalExpr(cx, a, scope));
|
|
715
|
+
const inner = childScope(null);
|
|
716
|
+
member.parameters.forEach((p, i) => {
|
|
717
|
+
if (!ts.isIdentifier(p.name))
|
|
718
|
+
afail("NOT_STATIC", `helper '${target}': parameters must be plain identifiers`);
|
|
719
|
+
inner.vars.set(p.name.text, args[i]);
|
|
720
|
+
});
|
|
721
|
+
const r = evalStatements(cx, member.body.statements, inner);
|
|
722
|
+
return r.returned ? r.value : undefined;
|
|
723
|
+
}
|
|
724
|
+
//# sourceMappingURL=ts-compile.js.map
|