@native-sdk/cli 0.4.4 → 0.5.1
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/build/app.zig +371 -5
- package/build/ts_run.mjs +102 -0
- package/build.zig +255 -1
- package/build.zig.zon +1 -0
- package/package.json +19 -10
- package/packages/core/package-lock.json +44 -0
- package/packages/core/package.json +38 -0
- package/packages/core/rt/rt.zig +1579 -0
- package/packages/core/sdk/bytes_text_methods.d.ts +88 -0
- package/packages/core/sdk/core.ts +694 -0
- package/packages/core/sdk/events.ts +137 -0
- package/packages/core/sdk/text.ts +519 -0
- package/packages/core/src/checker.ts +1869 -0
- package/packages/core/src/cli.ts +68 -0
- package/packages/core/src/devhost.ts +291 -0
- package/packages/core/src/devhost_resolver.mjs +22 -0
- package/packages/core/src/diagnostics.ts +417 -0
- package/packages/core/src/emitter.ts +8815 -0
- package/packages/core/src/infer.ts +1515 -0
- package/packages/core/src/modules.ts +173 -0
- package/packages/core/src/ownership.ts +740 -0
- package/packages/core/src/text_polyfill.ts +337 -0
- package/packages/core/src/text_tables.ts +408 -0
- package/packages/core/src/transpile.ts +146 -0
- package/packages/core/src/typed_ast.ts +546 -0
- package/packages/core/src/types.ts +815 -0
- package/skill-data/native-ui/SKILL.md +14 -0
- package/skill-data/ts-core/SKILL.md +493 -0
- package/skill-data/zig/SKILL.md +10 -0
- package/src/app_runner/root.zig +24 -0
- package/src/app_runner/ts_core_main.zig +231 -0
- package/src/platform/windows/webview2_host.cpp +24 -0
- package/src/primitives/app_manifest/comptime_scene.zig +341 -0
- package/src/primitives/app_manifest/root.zig +5 -0
- package/src/primitives/canvas/commands.zig +14 -7
- package/src/primitives/canvas/layout_audit.zig +5 -5
- package/src/primitives/canvas/lazy_tls.zig +73 -0
- package/src/primitives/canvas/render_generic_resources.zig +22 -15
- package/src/primitives/canvas/root.zig +11 -0
- package/src/primitives/canvas/tests.zig +1 -0
- package/src/primitives/canvas/text_atlas.zig +40 -32
- package/src/primitives/canvas/text_layout_cache.zig +29 -22
- package/src/primitives/canvas/text_measure_cache.zig +56 -41
- package/src/primitives/canvas/text_spans.zig +39 -26
- package/src/primitives/canvas/tokens.zig +69 -0
- package/src/primitives/canvas/ui.zig +125 -0
- package/src/primitives/canvas/ui_markup.zig +22 -3
- package/src/primitives/canvas/ui_markup_compiled.zig +97 -7
- package/src/primitives/canvas/ui_markup_compiled_tests.zig +275 -0
- package/src/primitives/canvas/ui_markup_contract.zig +68 -14
- package/src/primitives/canvas/ui_markup_contract_tests.zig +257 -2
- package/src/primitives/canvas/ui_markup_reflect.zig +214 -0
- package/src/primitives/canvas/ui_markup_view.zig +105 -1
- package/src/primitives/canvas/ui_markup_view_tests.zig +336 -0
- package/src/primitives/canvas/ui_schema.zig +8 -0
- package/src/primitives/canvas/ui_schema_tests.zig +5 -4
- package/src/primitives/canvas/widget_builtin_tests.zig +309 -5
- package/src/primitives/canvas/widget_invalidation.zig +14 -7
- package/src/primitives/canvas/widget_layout.zig +138 -2
- package/src/primitives/canvas/widget_metrics.zig +16 -8
- package/src/primitives/canvas/widget_render.zig +25 -15
- package/src/primitives/canvas/widget_render_controls.zig +15 -9
- package/src/primitives/canvas/widget_runtime_tests.zig +44 -0
- package/src/root.zig +7 -0
- package/src/runtime/canvas_frame.zig +57 -36
- package/src/runtime/canvas_images.zig +9 -3
- package/src/runtime/canvas_widget_control_tests.zig +5 -6
- package/src/runtime/canvas_widget_runtime.zig +7 -4
- package/src/runtime/core.zig +16 -0
- package/src/runtime/effects.zig +1525 -133
- package/src/runtime/effects_fetch_tests.zig +42 -0
- package/src/runtime/effects_file_tests.zig +220 -0
- package/src/runtime/effects_host_tests.zig +594 -0
- package/src/runtime/effects_tests.zig +287 -0
- package/src/runtime/root.zig +18 -0
- package/src/runtime/session_replay.zig +7 -1
- package/src/runtime/tests.zig +2 -0
- package/src/runtime/ts_core_host.zig +1505 -0
- package/src/runtime/ts_core_host_tests.zig +1408 -0
- package/src/runtime/ts_ui_app.zig +469 -0
- package/src/runtime/ui_app.zig +189 -38
- package/src/runtime/ui_app_tests.zig +221 -0
- package/src/runtime/ui_app_window_tests.zig +182 -0
- package/src/runtime/view_canvas.zig +24 -17
- package/src/runtime/view_widget_tree.zig +2 -2
- package/src/tooling/codesign.zig +212 -105
- package/src/tooling/doctor.zig +78 -0
- package/src/tooling/manifest.zig +47 -0
- package/src/tooling/package.zig +435 -20
- package/src/tooling/raw_manifest.zig +15 -0
- package/src/tooling/root.zig +1 -0
- package/src/tooling/templates.zig +777 -34
- package/src/tooling/ts_core.zig +1099 -0
- package/src/tooling/verbs.zig +105 -2
|
@@ -0,0 +1,1869 @@
|
|
|
1
|
+
// The subset checker: everything tsc cannot enforce, with teaching errors.
|
|
2
|
+
//
|
|
3
|
+
// Layering (spec section 5): tsc's own readonly/type errors fire first; this
|
|
4
|
+
// checker adds the subset rules on the typed AST; the emitter re-derives every
|
|
5
|
+
// rule during emission and turns any gap into a loud internal error.
|
|
6
|
+
|
|
7
|
+
import { ts, TypedAst, lineColumn, hasExportModifier, exportListBindings, type ExportListBinding } from "./typed_ast.ts";
|
|
8
|
+
import { makeDiagnostic, type SubsetDiagnostic, type RuleId } from "./diagnostics.ts";
|
|
9
|
+
import type { TypeTable } from "./types.ts";
|
|
10
|
+
import {
|
|
11
|
+
arrayOwnership,
|
|
12
|
+
constFunctionValue,
|
|
13
|
+
functionValueLegality,
|
|
14
|
+
instanceOwnership,
|
|
15
|
+
mutatingArrayMethods,
|
|
16
|
+
ownedMutatingMethods,
|
|
17
|
+
valuePositionStep,
|
|
18
|
+
} from "./ownership.ts";
|
|
19
|
+
|
|
20
|
+
/// The VariableDeclaration a function value is const-bound to (through
|
|
21
|
+
/// paren/as wrappers), else null.
|
|
22
|
+
function owningConstDecl(fn: ts.Node): ts.VariableDeclaration | null {
|
|
23
|
+
let cur: ts.Node = fn;
|
|
24
|
+
while (ts.isParenthesizedExpression(cur.parent) || ts.isAsExpression(cur.parent) || ts.isSatisfiesExpression(cur.parent)) {
|
|
25
|
+
cur = cur.parent;
|
|
26
|
+
}
|
|
27
|
+
return ts.isVariableDeclaration(cur.parent) && cur.parent.initializer !== undefined ? cur.parent : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const stringObservers = new Set(["charCodeAt", "codePointAt", "charAt", "at"]);
|
|
31
|
+
|
|
32
|
+
/// The STAYS-OUT tail of the byte-text method surface (declared ambient on
|
|
33
|
+
/// Uint8Array only so these spellings reach a teaching here instead of a
|
|
34
|
+
/// bare tsc "property does not exist"). Each entry names its rule and why:
|
|
35
|
+
/// UTF-16 code units and normalization (NS1060), ambient locale state
|
|
36
|
+
/// (NS1005), regex engines (NS1040).
|
|
37
|
+
const bytesTextStaysOut = new Map<string, { readonly id: RuleId; readonly site: string }>([
|
|
38
|
+
["charCodeAt", { id: "NS1060", site: "`.charCodeAt` reads UTF-16 code units, which byte text does not have — read the byte (`b[i]`, `.at(i)`)." }],
|
|
39
|
+
["charAt", { id: "NS1060", site: "`.charAt` reads UTF-16 code units, which byte text does not have — slice the byte range (`.subarray(i, j)`)." }],
|
|
40
|
+
["codePointAt", { id: "NS1060", site: "`.codePointAt` walks UTF-16 code-unit indices, which byte text does not have — read bytes, or decode where the host renders." }],
|
|
41
|
+
["normalize", { id: "NS1060", site: "`.normalize` applies Unicode normalization forms, a table set with no place in the byte model — compare exact bytes, or normalize at the host edge." }],
|
|
42
|
+
["replace", { id: "NS1060", site: "`.replace` is not in v1 — rebuild the text with `.split(sep)`, slices, and a push-builder of parts." }],
|
|
43
|
+
["replaceAll", { id: "NS1060", site: "`.replaceAll` is not in v1 — rebuild the text with `.split(sep)`, slices, and a push-builder of parts." }],
|
|
44
|
+
["localeCompare", { id: "NS1005", site: "`.localeCompare` orders by the ambient locale (use `orderIgnoreCase` from \"@native-sdk/core/text\", or compare bytes)." }],
|
|
45
|
+
["toLocaleUpperCase", { id: "NS1005", site: "`.toLocaleUpperCase` cases by the ambient locale (`.toUpperCase()` is the locale-free simple mapping)." }],
|
|
46
|
+
["toLocaleLowerCase", { id: "NS1005", site: "`.toLocaleLowerCase` cases by the ambient locale (`.toLowerCase()` is the locale-free simple mapping)." }],
|
|
47
|
+
["match", { id: "NS1040", site: "`.match` takes a regular expression." }],
|
|
48
|
+
["matchAll", { id: "NS1040", site: "`.matchAll` takes a regular expression." }],
|
|
49
|
+
["search", { id: "NS1040", site: "`.search` takes a regular expression." }],
|
|
50
|
+
]);
|
|
51
|
+
|
|
52
|
+
const ambientGlobals = new Set(["Date", "console", "fetch", "setTimeout", "setInterval", "performance", "process", "globalThis"]);
|
|
53
|
+
|
|
54
|
+
/// Every assignment operator, `=` and the compound family alike — for the
|
|
55
|
+
/// NS1043 statement-position rule (the emitter maps them as statements).
|
|
56
|
+
const compoundAndPlainAssignmentOps = new Set<ts.SyntaxKind>([
|
|
57
|
+
ts.SyntaxKind.EqualsToken,
|
|
58
|
+
ts.SyntaxKind.PlusEqualsToken,
|
|
59
|
+
ts.SyntaxKind.MinusEqualsToken,
|
|
60
|
+
ts.SyntaxKind.AsteriskEqualsToken,
|
|
61
|
+
ts.SyntaxKind.SlashEqualsToken,
|
|
62
|
+
ts.SyntaxKind.PercentEqualsToken,
|
|
63
|
+
ts.SyntaxKind.AsteriskAsteriskEqualsToken,
|
|
64
|
+
ts.SyntaxKind.AmpersandEqualsToken,
|
|
65
|
+
ts.SyntaxKind.BarEqualsToken,
|
|
66
|
+
ts.SyntaxKind.CaretEqualsToken,
|
|
67
|
+
ts.SyntaxKind.LessThanLessThanEqualsToken,
|
|
68
|
+
ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,
|
|
69
|
+
ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
|
|
70
|
+
ts.SyntaxKind.AmpersandAmpersandEqualsToken,
|
|
71
|
+
ts.SyntaxKind.BarBarEqualsToken,
|
|
72
|
+
ts.SyntaxKind.QuestionQuestionEqualsToken,
|
|
73
|
+
]);
|
|
74
|
+
|
|
75
|
+
/// An arrow inside a call's argument expression — the inline-callback
|
|
76
|
+
/// position (array methods), reached through literal wrappers so more
|
|
77
|
+
/// specific teachings (e.g. NS1027 on routing objects) stay in charge.
|
|
78
|
+
/// Everything else is a STORED function value (NS1046).
|
|
79
|
+
function isCallArgument(fn: ts.ArrowFunction): boolean {
|
|
80
|
+
let cur: ts.Node = fn;
|
|
81
|
+
for (;;) {
|
|
82
|
+
const p: ts.Node = cur.parent;
|
|
83
|
+
if (ts.isCallExpression(p) && (p.arguments as readonly ts.Node[]).includes(cur)) return true;
|
|
84
|
+
if (
|
|
85
|
+
ts.isParenthesizedExpression(p) ||
|
|
86
|
+
ts.isPropertyAssignment(p) ||
|
|
87
|
+
ts.isObjectLiteralExpression(p) ||
|
|
88
|
+
ts.isArrayLiteralExpression(p) ||
|
|
89
|
+
ts.isAsExpression(p) ||
|
|
90
|
+
ts.isSatisfiesExpression(p)
|
|
91
|
+
) {
|
|
92
|
+
cur = p;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/// Whether an expression sits inside a classic for-loop's incrementor slot
|
|
100
|
+
/// (walking up through comma chains and parens) — the one home for comma
|
|
101
|
+
/// sequences and statement-position assignment forms in expression syntax.
|
|
102
|
+
function inForIncrementor(node: ts.Expression): boolean {
|
|
103
|
+
let cur: ts.Node = node;
|
|
104
|
+
for (;;) {
|
|
105
|
+
const p: ts.Node = cur.parent;
|
|
106
|
+
if (ts.isForStatement(p) && p.incrementor === cur) return true;
|
|
107
|
+
const chains =
|
|
108
|
+
ts.isParenthesizedExpression(p) ||
|
|
109
|
+
(ts.isBinaryExpression(p) && p.operatorToken.kind === ts.SyntaxKind.CommaToken);
|
|
110
|
+
if (!chains) return false;
|
|
111
|
+
cur = p;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/// `xs.push(...)` / `xs.unshift(...)` / `xs.splice(...)` — spread arguments
|
|
116
|
+
/// there keep the emitter's tailored teaching (one element per iteration)
|
|
117
|
+
/// instead of the arity rule.
|
|
118
|
+
function isMutatingAppendCall(call: ts.CallExpression): boolean {
|
|
119
|
+
return (
|
|
120
|
+
ts.isPropertyAccessExpression(call.expression) &&
|
|
121
|
+
["push", "unshift", "splice"].includes(call.expression.name.text)
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/// `for (const [i, x] of xs.entries())` — the entries() teach (use the
|
|
126
|
+
/// classic loop) is more useful than the destructuring rule for this shape.
|
|
127
|
+
function isEntriesLoopBinding(pattern: ts.ArrayBindingPattern): boolean {
|
|
128
|
+
const decl = pattern.parent;
|
|
129
|
+
if (!ts.isVariableDeclaration(decl) || !ts.isVariableDeclarationList(decl.parent)) return false;
|
|
130
|
+
const loop = decl.parent.parent;
|
|
131
|
+
if (!ts.isForOfStatement(loop)) return false;
|
|
132
|
+
let iter = loop.expression;
|
|
133
|
+
while (ts.isParenthesizedExpression(iter)) iter = iter.expression;
|
|
134
|
+
return (
|
|
135
|
+
ts.isCallExpression(iter) &&
|
|
136
|
+
ts.isPropertyAccessExpression(iter.expression) &&
|
|
137
|
+
iter.expression.name.text === "entries"
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/// The core's single thrown shape (NS1057): every `throw` carries a value
|
|
142
|
+
/// of one type, because the value unwinds through one native payload slot.
|
|
143
|
+
/// The shape comes from catch assertions (`const err = e as ParseError;`)
|
|
144
|
+
/// when any exist — all must agree — else structurally from the throw
|
|
145
|
+
/// expressions themselves (each must resolve to the same named table type,
|
|
146
|
+
/// number, boolean, or bytes). Shared by the checker (teaching) and the
|
|
147
|
+
/// emitter (layer-3 re-derivation + the slot's emitted type).
|
|
148
|
+
export interface ThrownShapeResult {
|
|
149
|
+
readonly shape: import("./types.ts").ZType | null;
|
|
150
|
+
/// The declared type node the shape came from (a catch assertion), used
|
|
151
|
+
/// for tsc-assignability checks on every throw; null when structural.
|
|
152
|
+
readonly shapeNode: ts.TypeNode | null;
|
|
153
|
+
/// True when `shape` is the checker-SYNTHESIZED union of several distinct
|
|
154
|
+
/// thrown shapes (registered in the table under THROWN_UNION_NAME so the
|
|
155
|
+
/// whole narrowing pipeline sees an ordinary union); false when one shape
|
|
156
|
+
/// — or a DECLARED union whose arms equal the thrown set — carries it.
|
|
157
|
+
readonly synthesized: boolean;
|
|
158
|
+
readonly problems: readonly { readonly node: ts.Node; readonly msg: string }[];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/// The emitted name of the synthesized thrown union (heterogeneous throws
|
|
162
|
+
/// with no declared union matching the thrown set). Reserved alongside the
|
|
163
|
+
/// `Thrown` error set and the `thrown_payload` slot.
|
|
164
|
+
export const THROWN_UNION_NAME = "ThrownPayload";
|
|
165
|
+
|
|
166
|
+
/// The kind-tagged arm(s) a thrown shape contributes to the core's thrown
|
|
167
|
+
/// union: a registered union contributes its arms; an interface with a
|
|
168
|
+
/// string-literal `kind` field contributes one arm (its other fields as the
|
|
169
|
+
/// payload). Anything else cannot join a heterogeneous thrown set.
|
|
170
|
+
export function thrownArmsOfShape(
|
|
171
|
+
ty: import("./types.ts").ZType,
|
|
172
|
+
table: TypeTable,
|
|
173
|
+
): readonly { readonly tag: string; readonly fields: readonly import("./types.ts").ZField[] }[] | null {
|
|
174
|
+
if (ty.k === "union") return table.unions.get(ty.name)?.arms ?? null;
|
|
175
|
+
if (ty.k !== "struct") return null;
|
|
176
|
+
const info = table.structs.get(ty.name);
|
|
177
|
+
if (!info) return null;
|
|
178
|
+
const kindField = info.fields.find((f) => f.tsName === "kind");
|
|
179
|
+
if (!kindField) return null;
|
|
180
|
+
const decl = kindField.decl;
|
|
181
|
+
if (!ts.isPropertySignature(decl) || !decl.type) return null;
|
|
182
|
+
if (!ts.isLiteralTypeNode(decl.type) || !ts.isStringLiteral(decl.type.literal)) return null;
|
|
183
|
+
return [{ tag: decl.type.literal.text, fields: info.fields.filter((f) => f.tsName !== "kind") }];
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function thrownShapeOf(
|
|
187
|
+
tast: TypedAst,
|
|
188
|
+
table: TypeTable,
|
|
189
|
+
files: readonly ts.SourceFile[],
|
|
190
|
+
): ThrownShapeResult {
|
|
191
|
+
const throws: ts.ThrowStatement[] = [];
|
|
192
|
+
const catchVars = new Set<ts.Node>();
|
|
193
|
+
const assertions: ts.AsExpression[] = [];
|
|
194
|
+
const collect = (n: ts.Node): void => {
|
|
195
|
+
if (ts.isThrowStatement(n)) throws.push(n);
|
|
196
|
+
if (ts.isCatchClause(n) && n.variableDeclaration && ts.isIdentifier(n.variableDeclaration.name)) {
|
|
197
|
+
catchVars.add(n.variableDeclaration);
|
|
198
|
+
}
|
|
199
|
+
ts.forEachChild(n, collect);
|
|
200
|
+
};
|
|
201
|
+
for (const f of files) collect(f);
|
|
202
|
+
if (throws.length === 0 && catchVars.size === 0) return { shape: null, shapeNode: null, synthesized: false, problems: [] };
|
|
203
|
+
const findAssertions = (n: ts.Node): void => {
|
|
204
|
+
if (ts.isAsExpression(n) && ts.isIdentifier(n.expression)) {
|
|
205
|
+
const d = tast.declarationOf(n.expression);
|
|
206
|
+
if (d && catchVars.has(d)) assertions.push(n);
|
|
207
|
+
}
|
|
208
|
+
ts.forEachChild(n, findAssertions);
|
|
209
|
+
};
|
|
210
|
+
for (const f of files) findAssertions(f);
|
|
211
|
+
|
|
212
|
+
const canonRef = (t: import("./types.ts").ZType): string =>
|
|
213
|
+
table.zigTypeRef(t.k === "number" ? { k: "f64" } : t);
|
|
214
|
+
const problems: { node: ts.Node; msg: string }[] = [];
|
|
215
|
+
|
|
216
|
+
/// A throw expression's shape: an assertion resolves its named type; an
|
|
217
|
+
/// identifier resolves its declared/inferred named type; numbers and
|
|
218
|
+
/// booleans and bytes resolve directly. A rethrow of the catch binding
|
|
219
|
+
/// is shape-neutral (it IS the slot).
|
|
220
|
+
const typeOfThrow = (e: ts.Expression): import("./types.ts").ZType | "rethrow" | null => {
|
|
221
|
+
let cur = e;
|
|
222
|
+
while (ts.isParenthesizedExpression(cur)) cur = cur.expression;
|
|
223
|
+
if (ts.isIdentifier(cur)) {
|
|
224
|
+
const d = tast.declarationOf(cur);
|
|
225
|
+
if (d && catchVars.has(d)) return "rethrow";
|
|
226
|
+
}
|
|
227
|
+
if (ts.isAsExpression(cur) || ts.isSatisfiesExpression(cur)) {
|
|
228
|
+
const t = table.resolveTypeNode(cur.type);
|
|
229
|
+
return t.k === "void" ? null : t;
|
|
230
|
+
}
|
|
231
|
+
const flags = tast.typeOf(cur).flags;
|
|
232
|
+
if ((flags & (ts.TypeFlags.Number | ts.TypeFlags.NumberLiteral)) !== 0) return { k: "f64" };
|
|
233
|
+
if ((flags & (ts.TypeFlags.Boolean | ts.TypeFlags.BooleanLiteral)) !== 0) return { k: "bool" };
|
|
234
|
+
const str = tast.typeToString(tast.typeOf(cur));
|
|
235
|
+
if (str === "Uint8Array" || str.startsWith("Uint8Array<")) return { k: "bytes" };
|
|
236
|
+
return table.resolveName(str);
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
// Structural pre-pass: the DISTINCT shapes the core actually throws.
|
|
240
|
+
// Two or more distinct shapes take the heterogeneous path — the thrown
|
|
241
|
+
// union — and the single-shape path below stays byte-for-byte what it
|
|
242
|
+
// always was.
|
|
243
|
+
const distinct = new Map<string, { readonly ty: import("./types.ts").ZType; readonly node: ts.Node }>();
|
|
244
|
+
for (const t of throws) {
|
|
245
|
+
const ty = typeOfThrow(t.expression);
|
|
246
|
+
if (ty === "rethrow" || ty === null) continue;
|
|
247
|
+
const key = canonRef(ty);
|
|
248
|
+
if (!distinct.has(key)) distinct.set(key, { ty, node: t });
|
|
249
|
+
}
|
|
250
|
+
if (distinct.size >= 2) {
|
|
251
|
+
return thrownUnionOf(table, distinct, throws, assertions, typeOfThrow, canonRef, problems);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
let shape: import("./types.ts").ZType | null = null;
|
|
255
|
+
let shapeNode: ts.TypeNode | null = null;
|
|
256
|
+
for (const a of assertions) {
|
|
257
|
+
const t = table.resolveTypeNode(a.type);
|
|
258
|
+
if (t.k === "void") {
|
|
259
|
+
problems.push({ node: a, msg: `the catch assertion's type does not resolve to a subset shape.` });
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
if (shape === null) {
|
|
263
|
+
shape = t;
|
|
264
|
+
shapeNode = a.type;
|
|
265
|
+
} else if (canonRef(shape) !== canonRef(t)) {
|
|
266
|
+
problems.push({
|
|
267
|
+
node: a,
|
|
268
|
+
msg: `this catch narrows to \`${a.type.getText()}\`, but the core's error shape is already \`${shapeNode?.getText() ?? canonRef(shape)}\`.`,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
for (const t of throws) {
|
|
274
|
+
const e = t.expression;
|
|
275
|
+
if (shapeNode !== null) {
|
|
276
|
+
let cur = e;
|
|
277
|
+
while (ts.isParenthesizedExpression(cur)) cur = cur.expression;
|
|
278
|
+
if (ts.isIdentifier(cur)) {
|
|
279
|
+
const d = tast.declarationOf(cur);
|
|
280
|
+
if (d && catchVars.has(d)) continue; // rethrow
|
|
281
|
+
}
|
|
282
|
+
if (!tast.isAssignableToNode(e, shapeNode)) {
|
|
283
|
+
problems.push({
|
|
284
|
+
node: t,
|
|
285
|
+
msg: `this \`throw\` does not carry the core's error shape \`${shapeNode.getText()}\` (tsc says the value is not assignable to it).`,
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
const ty = typeOfThrow(e);
|
|
291
|
+
if (ty === "rethrow") continue;
|
|
292
|
+
if (ty === null) {
|
|
293
|
+
problems.push({
|
|
294
|
+
node: t,
|
|
295
|
+
msg: `the thrown value's shape does not resolve — throw a named value (\`const err: ParseError = {...}; throw err;\` or \`throw {...} as ParseError\`).`,
|
|
296
|
+
});
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
if (shape === null) shape = ty;
|
|
300
|
+
else if (canonRef(shape) !== canonRef(ty)) {
|
|
301
|
+
problems.push({
|
|
302
|
+
node: t,
|
|
303
|
+
msg: `this \`throw\` carries \`${canonRef(ty)}\`, but the core already throws \`${canonRef(shape)}\`.`,
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (shape !== null && shape.k === "number") shape = { k: "f64" };
|
|
308
|
+
return { shape, shapeNode, synthesized: false, problems };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/// The heterogeneous path: merge every distinct thrown shape's kind-tagged
|
|
312
|
+
/// arms into ONE union — a declared union whose arms equal the merged set
|
|
313
|
+
/// when one exists, else a synthesized union registered in the table under
|
|
314
|
+
/// THROWN_UNION_NAME. Catch assertions must name that union (arm shapes
|
|
315
|
+
/// narrow with kind tests, not `as`).
|
|
316
|
+
function thrownUnionOf(
|
|
317
|
+
table: TypeTable,
|
|
318
|
+
distinct: ReadonlyMap<string, { readonly ty: import("./types.ts").ZType; readonly node: ts.Node }>,
|
|
319
|
+
throws: readonly ts.ThrowStatement[],
|
|
320
|
+
assertions: readonly ts.AsExpression[],
|
|
321
|
+
typeOfThrow: (e: ts.Expression) => import("./types.ts").ZType | "rethrow" | null,
|
|
322
|
+
canonRef: (t: import("./types.ts").ZType) => string,
|
|
323
|
+
problems: { node: ts.Node; msg: string }[],
|
|
324
|
+
): ThrownShapeResult {
|
|
325
|
+
type Arm = { readonly tag: string; readonly fields: readonly import("./types.ts").ZField[] };
|
|
326
|
+
const arms: Arm[] = [];
|
|
327
|
+
const tagOwner = new Map<string, string>();
|
|
328
|
+
for (const [key, { ty, node }] of distinct) {
|
|
329
|
+
const memberArms = thrownArmsOfShape(ty, table);
|
|
330
|
+
if (memberArms === null) {
|
|
331
|
+
problems.push({
|
|
332
|
+
node,
|
|
333
|
+
msg: `this \`throw\` carries \`${key}\`, which cannot join the core's thrown union — heterogeneous throws narrow by \`kind\`, so give each thrown value a kind-discriminated record shape (an interface with a string-literal \`kind\` field, or a \`kind\`-discriminated union).`,
|
|
334
|
+
});
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
for (const arm of memberArms) {
|
|
338
|
+
const owner = tagOwner.get(arm.tag);
|
|
339
|
+
if (owner !== undefined) {
|
|
340
|
+
// The same tag from two member shapes is ONE arm when the payloads
|
|
341
|
+
// agree (a shape overlapping a declared union's arm); different
|
|
342
|
+
// payloads under one tag could never be told apart in a catch.
|
|
343
|
+
const prior = arms.find((a) => a.tag === arm.tag);
|
|
344
|
+
const samePayload =
|
|
345
|
+
prior !== undefined &&
|
|
346
|
+
prior.fields.length === arm.fields.length &&
|
|
347
|
+
prior.fields.every((f, i) => arm.fields[i].tsName === f.tsName && canonRef(arm.fields[i].type) === canonRef(f.type));
|
|
348
|
+
if (owner !== key && !samePayload) {
|
|
349
|
+
problems.push({
|
|
350
|
+
node,
|
|
351
|
+
msg: `thrown shapes \`${owner}\` and \`${key}\` both carry kind "${arm.tag}" with different payloads — a catch could not tell them apart; give each shape its own tag.`,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
tagOwner.set(arm.tag, key);
|
|
357
|
+
arms.push(arm);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
// Unresolvable throws still teach the naming fix.
|
|
361
|
+
for (const t of throws) {
|
|
362
|
+
if (typeOfThrow(t.expression) === null) {
|
|
363
|
+
problems.push({
|
|
364
|
+
node: t,
|
|
365
|
+
msg: `the thrown value's shape does not resolve — throw a named value (\`const err: ParseError = {...}; throw err;\` or \`throw {...} as ParseError\`).`,
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// A declared union whose arm set equals the merged set IS the thrown
|
|
371
|
+
// union (assertions may name it; nothing synthesizes).
|
|
372
|
+
const armsEqual = (a: readonly Arm[], b: readonly Arm[]): boolean => {
|
|
373
|
+
if (a.length !== b.length) return false;
|
|
374
|
+
return a.every((arm) => {
|
|
375
|
+
const other = b.find((x) => x.tag === arm.tag);
|
|
376
|
+
if (!other || other.fields.length !== arm.fields.length) return false;
|
|
377
|
+
return arm.fields.every(
|
|
378
|
+
(f, i) => other.fields[i].tsName === f.tsName && canonRef(other.fields[i].type) === canonRef(f.type),
|
|
379
|
+
);
|
|
380
|
+
});
|
|
381
|
+
};
|
|
382
|
+
let name: string | null = null;
|
|
383
|
+
let synthesized = false;
|
|
384
|
+
for (const info of table.unions.values()) {
|
|
385
|
+
if (info.name === THROWN_UNION_NAME) continue;
|
|
386
|
+
if (armsEqual(info.arms, arms)) {
|
|
387
|
+
name = info.name;
|
|
388
|
+
break;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (name === null) {
|
|
392
|
+
name = THROWN_UNION_NAME;
|
|
393
|
+
synthesized = true;
|
|
394
|
+
if (!table.unions.has(THROWN_UNION_NAME)) {
|
|
395
|
+
// The registered entry is what lets zigTypeRef, kind narrowing, and
|
|
396
|
+
// the switch lowering treat the thrown union as an ordinary union;
|
|
397
|
+
// `decl` is never consulted for it (no source statement matches).
|
|
398
|
+
const anyUnion = [...distinct.values()].find((d) => d.ty.k === "union");
|
|
399
|
+
const decl = (anyUnion ? table.unions.get((anyUnion.ty as { name: string }).name)?.decl : undefined) as ts.TypeAliasDeclaration;
|
|
400
|
+
table.unions.set(THROWN_UNION_NAME, { name: THROWN_UNION_NAME, decl, arms, exported: false });
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
for (const a of assertions) {
|
|
405
|
+
const t = table.resolveTypeNode(a.type);
|
|
406
|
+
if (!(t.k === "union" && t.name === name)) {
|
|
407
|
+
problems.push({
|
|
408
|
+
node: a,
|
|
409
|
+
msg: `this catch narrows to \`${a.type.getText()}\`, but the core throws several shapes — test \`kind\` in the catch (\`if (e.kind === ...)\`) instead of asserting one of them.`,
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
return { shape: { k: "union", name }, shapeNode: null, synthesized, problems };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export interface CheckResult {
|
|
418
|
+
readonly diagnostics: SubsetDiagnostic[];
|
|
419
|
+
/// Teaching notices that do NOT stop the build (today: NS1028, the
|
|
420
|
+
/// not-yet-host-backed persist op). Same shape as diagnostics, surfaced
|
|
421
|
+
/// as warnings by the CLI.
|
|
422
|
+
readonly warnings: SubsetDiagnostic[];
|
|
423
|
+
/// Local names bound to the SDK `Cmd` surface (import from
|
|
424
|
+
/// "@native-sdk/core"). The emitter lowers references through these names
|
|
425
|
+
/// onto the rt command builders.
|
|
426
|
+
readonly cmdNames: Set<string>;
|
|
427
|
+
/// Local names bound to the SDK `Sub` surface, lowered onto the rt
|
|
428
|
+
/// subscription builders the same way.
|
|
429
|
+
readonly subNames: Set<string>;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export class SubsetChecker {
|
|
433
|
+
private readonly diagnostics: SubsetDiagnostic[] = [];
|
|
434
|
+
private readonly warnings: SubsetDiagnostic[] = [];
|
|
435
|
+
readonly cmdNames = new Set<string>();
|
|
436
|
+
readonly subNames = new Set<string>();
|
|
437
|
+
/// Local names bound by `import * as ns` over in-graph modules — a fast
|
|
438
|
+
/// pre-filter for the NS1039 bare-alias check (confirmed by symbol).
|
|
439
|
+
private readonly nsAliasNames = new Set<string>();
|
|
440
|
+
|
|
441
|
+
private readonly tast: TypedAst;
|
|
442
|
+
private readonly table: TypeTable;
|
|
443
|
+
/// The core's modules in canonical order; files[0] is the entry
|
|
444
|
+
/// (src/core.ts), the one module the entry-point exports may live in.
|
|
445
|
+
private readonly files: readonly ts.SourceFile[];
|
|
446
|
+
private readonly entry: ts.SourceFile;
|
|
447
|
+
private readonly fileSet: Set<ts.SourceFile>;
|
|
448
|
+
|
|
449
|
+
constructor(tast: TypedAst, table: TypeTable, files: readonly ts.SourceFile[] | ts.SourceFile) {
|
|
450
|
+
this.tast = tast;
|
|
451
|
+
this.table = table;
|
|
452
|
+
this.files = Array.isArray(files) ? files : [files as ts.SourceFile];
|
|
453
|
+
this.entry = this.files[0];
|
|
454
|
+
this.fileSet = new Set(this.files);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
check(): CheckResult {
|
|
458
|
+
for (const file of this.files) this.findCmdNames(file);
|
|
459
|
+
for (const file of this.files) this.checkModuleShape(file);
|
|
460
|
+
this.checkEntryContract();
|
|
461
|
+
this.checkNameCollisions();
|
|
462
|
+
this.checkModelHoldsData();
|
|
463
|
+
this.checkModelTextIsBytes();
|
|
464
|
+
this.checkCmdPurity();
|
|
465
|
+
this.checkSubPurity();
|
|
466
|
+
this.checkModelBindingSurface();
|
|
467
|
+
this.checkViewUnbound();
|
|
468
|
+
for (const file of this.files) this.walk(file);
|
|
469
|
+
this.checkExceptions();
|
|
470
|
+
return {
|
|
471
|
+
diagnostics: this.diagnostics,
|
|
472
|
+
warnings: this.warnings,
|
|
473
|
+
cmdNames: this.cmdNames,
|
|
474
|
+
subNames: this.subNames,
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
private report(id: RuleId, site: string, node: ts.Node): void {
|
|
479
|
+
const file = node.getSourceFile();
|
|
480
|
+
const { line, column } = lineColumn(file, node.getStart());
|
|
481
|
+
this.diagnostics.push(makeDiagnostic(id, site, file.fileName, line, column));
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
private warn(id: RuleId, site: string, node: ts.Node): void {
|
|
485
|
+
const file = node.getSourceFile();
|
|
486
|
+
const { line, column } = lineColumn(file, node.getStart());
|
|
487
|
+
this.warnings.push(makeDiagnostic(id, site, file.fileName, line, column));
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// ---------------------------------------------------------- cmd namespace
|
|
491
|
+
|
|
492
|
+
/// Local names bound to the SDK `Cmd`/`Sub` exports by an import from
|
|
493
|
+
/// "@native-sdk/core" (usually just `Cmd`/`Sub`; renames are honored).
|
|
494
|
+
private findCmdNames(file: ts.SourceFile): void {
|
|
495
|
+
for (const stmt of file.statements) {
|
|
496
|
+
if (!ts.isImportDeclaration(stmt)) continue;
|
|
497
|
+
const spec = stmt.moduleSpecifier;
|
|
498
|
+
if (!ts.isStringLiteral(spec)) continue;
|
|
499
|
+
if (stmt.importClause?.isTypeOnly) continue;
|
|
500
|
+
const bindings = stmt.importClause?.namedBindings;
|
|
501
|
+
if (spec.text !== "@native-sdk/core") {
|
|
502
|
+
// NS1039 (half 1): `import * as ns` over an in-graph module is the
|
|
503
|
+
// supported dot-syntax alias; record the local name for the
|
|
504
|
+
// bare-value check in walk().
|
|
505
|
+
if (bindings && ts.isNamespaceImport(bindings)) this.nsAliasNames.add(bindings.name.text);
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (bindings && ts.isNamespaceImport(bindings)) {
|
|
509
|
+
// NS1039 (half 2): the intrinsic SDK surface is imported by name —
|
|
510
|
+
// the purity rules (NS1017/NS1025) and the asciiBytes fold recognize
|
|
511
|
+
// the factories by their imported names.
|
|
512
|
+
this.report("NS1039", `\`import * as ${bindings.name.text}\` aliases the intrinsic SDK module.`, bindings);
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
if (bindings && ts.isNamedImports(bindings)) {
|
|
516
|
+
for (const el of bindings.elements) {
|
|
517
|
+
if ((el.propertyName ?? el.name).text === "Cmd") this.cmdNames.add(el.name.text);
|
|
518
|
+
if ((el.propertyName ?? el.name).text === "Sub") this.subNames.add(el.name.text);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/// NS1017 — the purity rule: `Cmd` appears in exactly two places. As a
|
|
525
|
+
/// type, in `update`'s or `initialModel`'s return annotation; as a value,
|
|
526
|
+
/// in factory calls inside the command slot of that function's returned
|
|
527
|
+
/// `[model, cmd]` tuple. Anywhere else a command could escape the
|
|
528
|
+
/// dispatch cycle.
|
|
529
|
+
private checkCmdPurity(): void {
|
|
530
|
+
if (this.cmdNames.size === 0) return;
|
|
531
|
+
const visit = (node: ts.Node): void => {
|
|
532
|
+
if (ts.isImportDeclaration(node)) return;
|
|
533
|
+
if (ts.isIdentifier(node) && this.cmdNames.has(node.text) && this.isSdkReference(node)) {
|
|
534
|
+
if (!this.cmdUseIsLegal(node)) {
|
|
535
|
+
this.report("NS1017", `\`${node.getText()}\` puts a Cmd outside update's return path.`, node);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
ts.forEachChild(node, visit);
|
|
539
|
+
};
|
|
540
|
+
for (const file of this.files) visit(file);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/// NS1025 — the same purity rule for subscriptions: `Sub` appears as a
|
|
544
|
+
/// type in `subscriptions`' return annotation and as factory calls in its
|
|
545
|
+
/// return path, nowhere else.
|
|
546
|
+
private checkSubPurity(): void {
|
|
547
|
+
if (this.subNames.size === 0) return;
|
|
548
|
+
const visit = (node: ts.Node): void => {
|
|
549
|
+
if (ts.isImportDeclaration(node)) return;
|
|
550
|
+
if (ts.isIdentifier(node) && this.subNames.has(node.text) && this.isSdkReference(node)) {
|
|
551
|
+
if (!this.subUseIsLegal(node)) {
|
|
552
|
+
this.report(
|
|
553
|
+
"NS1025",
|
|
554
|
+
`\`${node.getText()}\` puts a Sub outside subscriptions' return path.`,
|
|
555
|
+
node,
|
|
556
|
+
);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
ts.forEachChild(node, visit);
|
|
560
|
+
};
|
|
561
|
+
for (const file of this.files) visit(file);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/// Whether an identifier refers to an ambient global — i.e. is NOT
|
|
565
|
+
/// shadowed by a declaration in one of the core's own modules (lib.d.ts
|
|
566
|
+
/// declarations do not count as shadowing).
|
|
567
|
+
private isAmbientRef(node: ts.Identifier): boolean {
|
|
568
|
+
const decl = this.tast.declarationOf(node);
|
|
569
|
+
return decl === undefined || !this.fileSet.has(decl.getSourceFile());
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/// A use of the imported name, not e.g. a property called `Cmd` or a
|
|
573
|
+
/// shadowing local (a declaration in any of the core's own modules).
|
|
574
|
+
private isSdkReference(node: ts.Identifier): boolean {
|
|
575
|
+
const parent = node.parent;
|
|
576
|
+
if (ts.isPropertyAccessExpression(parent) && parent.name === node) return false;
|
|
577
|
+
if (ts.isPropertySignature(parent) || ts.isPropertyAssignment(parent)) {
|
|
578
|
+
if (parent.name === node) return false;
|
|
579
|
+
}
|
|
580
|
+
const decl = this.tast.declarationOf(node);
|
|
581
|
+
return decl === undefined || !this.fileSet.has(decl.getSourceFile());
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
private cmdUseIsLegal(node: ts.Identifier): boolean {
|
|
585
|
+
// Cmd may ride update's dispatch returns and initialModel's boot pair.
|
|
586
|
+
return this.effectUseIsLegal(node, new Set(["update", "initialModel"]), true);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
private subUseIsLegal(node: ts.Identifier): boolean {
|
|
590
|
+
// Sub values are the whole return value of subscriptions, no tuple.
|
|
591
|
+
return this.effectUseIsLegal(node, new Set(["subscriptions"]), false);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/// Shared purity shape for the inert-effect surfaces. Type position: the
|
|
595
|
+
/// name inside the return type annotation of one of `fnNames`. Value
|
|
596
|
+
/// position: `X.<factory>` reached from the effect slot of a `return`
|
|
597
|
+
/// directly inside one of `fnNames` (not inside a callback) — the cmd
|
|
598
|
+
/// slot of a returned `[model, cmd]` tuple when `tupleSlot`, else the
|
|
599
|
+
/// whole return expression.
|
|
600
|
+
private effectUseIsLegal(node: ts.Identifier, fnNames: Set<string>, tupleSlot: boolean): boolean {
|
|
601
|
+
// The effect surfaces belong to the ENTRY module's entry points: a
|
|
602
|
+
// dispatch function in an imported file is not the app's (NS1014
|
|
603
|
+
// teaches the export; this keeps a private homonym from smuggling one).
|
|
604
|
+
if (node.getSourceFile() !== this.entry) return false;
|
|
605
|
+
if (ts.isTypeReferenceNode(node.parent) && node.parent.typeName === node) {
|
|
606
|
+
let fn: ts.Node | undefined = node.parent;
|
|
607
|
+
while (fn && !ts.isFunctionDeclaration(fn)) fn = fn.parent;
|
|
608
|
+
if (!fn || !ts.isFunctionDeclaration(fn) || !fnNames.has(fn.name?.text ?? "") || !fn.type) return false;
|
|
609
|
+
return node.getStart() >= fn.type.getStart() && node.getEnd() <= fn.type.getEnd();
|
|
610
|
+
}
|
|
611
|
+
if (!ts.isPropertyAccessExpression(node.parent) || node.parent.expression !== node) return false;
|
|
612
|
+
let cur: ts.Node = node;
|
|
613
|
+
while (cur.parent && !ts.isReturnStatement(cur.parent)) {
|
|
614
|
+
if (
|
|
615
|
+
ts.isFunctionDeclaration(cur.parent) ||
|
|
616
|
+
ts.isArrowFunction(cur.parent) ||
|
|
617
|
+
ts.isFunctionExpression(cur.parent)
|
|
618
|
+
) {
|
|
619
|
+
return false;
|
|
620
|
+
}
|
|
621
|
+
cur = cur.parent;
|
|
622
|
+
}
|
|
623
|
+
const ret = cur.parent;
|
|
624
|
+
if (!ret || !ts.isReturnStatement(ret)) return false;
|
|
625
|
+
let fn: ts.Node | undefined = ret;
|
|
626
|
+
while (fn && !ts.isFunctionDeclaration(fn) && !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) {
|
|
627
|
+
fn = fn.parent;
|
|
628
|
+
}
|
|
629
|
+
if (!fn || !ts.isFunctionDeclaration(fn) || !fnNames.has(fn.name?.text ?? "")) return false;
|
|
630
|
+
if (!tupleSlot) return true;
|
|
631
|
+
let retExpr = ret.expression;
|
|
632
|
+
while (retExpr && ts.isParenthesizedExpression(retExpr)) retExpr = retExpr.expression;
|
|
633
|
+
if (!retExpr || !ts.isArrayLiteralExpression(retExpr) || retExpr.elements.length !== 2) return false;
|
|
634
|
+
const slot = retExpr.elements[1];
|
|
635
|
+
return node.getStart() >= slot.getStart() && node.getEnd() <= slot.getEnd();
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/// NS1031 — exported single-Model-parameter helpers also emit as Model
|
|
639
|
+
/// declarations markup binds by their own names (`doneCount` →
|
|
640
|
+
/// `{doneCount}`), so each emitted name must be unique across the Model's
|
|
641
|
+
/// fields, the helpers, and the `view_unbound` opt-out declaration.
|
|
642
|
+
private checkModelBindingSurface(): void {
|
|
643
|
+
const model = this.table.structs.get("Model");
|
|
644
|
+
if (!model) return;
|
|
645
|
+
const taken = new Map<string, string>();
|
|
646
|
+
for (const f of model.fields) taken.set(f.zigName, `Model field \`${f.tsName}\``);
|
|
647
|
+
taken.set("view_unbound", "the `view_unbound` opt-out declaration");
|
|
648
|
+
for (const h of this.table.modelHelperDecls()) {
|
|
649
|
+
const holder = taken.get(h.zigName);
|
|
650
|
+
if (holder !== undefined) {
|
|
651
|
+
this.report(
|
|
652
|
+
"NS1031",
|
|
653
|
+
`Exported helper \`${h.name}\` emits the Model declaration \`${h.zigName}\`, which collides with ${holder}.`,
|
|
654
|
+
h.decl.name ?? h.decl,
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
taken.set(h.zigName, `exported helper \`${h.name}\``);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/// NS1032 — `export const viewUnbound = [...] as const`: the dead-state
|
|
662
|
+
/// lint opt-out. Every entry must be a string literal naming a Model
|
|
663
|
+
/// field, an exported model helper, or a Msg kind; the emitter routes the
|
|
664
|
+
/// list into the Model/Msg `view_unbound` declarations `native check`
|
|
665
|
+
/// reads.
|
|
666
|
+
private checkViewUnbound(): void {
|
|
667
|
+
for (const stmt of this.entry.statements) {
|
|
668
|
+
if (!ts.isVariableStatement(stmt)) continue;
|
|
669
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
670
|
+
if (!ts.isIdentifier(decl.name) || decl.name.text !== "viewUnbound") continue;
|
|
671
|
+
if (!decl.initializer) {
|
|
672
|
+
this.report("NS1032", "`viewUnbound` has no initializer.", decl);
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
let init = decl.initializer;
|
|
676
|
+
while (ts.isParenthesizedExpression(init) || ts.isAsExpression(init)) init = init.expression;
|
|
677
|
+
if (!ts.isArrayLiteralExpression(init)) {
|
|
678
|
+
this.report("NS1032", "`viewUnbound` is not an array literal.", decl);
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
const fields = new Set((this.table.structs.get("Model")?.fields ?? []).map((f) => f.tsName));
|
|
682
|
+
const helpers = new Set(this.table.modelHelperDecls().map((h) => h.name));
|
|
683
|
+
const kinds = new Set((this.table.unions.get("Msg")?.arms ?? []).map((a) => a.tag));
|
|
684
|
+
for (const el of init.elements) {
|
|
685
|
+
if (!ts.isStringLiteral(el)) {
|
|
686
|
+
this.report("NS1032", "`viewUnbound` holds a non-literal entry.", el);
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
if (!fields.has(el.text) && !helpers.has(el.text) && !kinds.has(el.text)) {
|
|
690
|
+
this.report("NS1032", `\`"${el.text}"\` names no Model field, exported model helper, or Msg kind.`, el);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// --------------------------------------------------------- module surface
|
|
698
|
+
|
|
699
|
+
private checkModuleShape(file: ts.SourceFile): void {
|
|
700
|
+
for (const stmt of file.statements) {
|
|
701
|
+
if (ts.isClassDeclaration(stmt)) {
|
|
702
|
+
this.checkClassDeclaration(stmt);
|
|
703
|
+
} else if (ts.isEnumDeclaration(stmt)) {
|
|
704
|
+
this.report("NS1008", `\`enum ${stmt.name.text}\` is non-erasable syntax.`, stmt);
|
|
705
|
+
} else if (ts.isModuleDeclaration(stmt)) {
|
|
706
|
+
this.report("NS1008", `\`namespace ${stmt.name.getText()}\` is non-erasable syntax.`, stmt);
|
|
707
|
+
} else if (ts.isVariableStatement(stmt)) {
|
|
708
|
+
const isConst = (stmt.declarationList.flags & ts.NodeFlags.Const) !== 0;
|
|
709
|
+
if (!isConst) {
|
|
710
|
+
this.report("NS1010", `Module-level \`let\` makes mutable global state.`, stmt);
|
|
711
|
+
}
|
|
712
|
+
} else if (ts.isExportAssignment(stmt)) {
|
|
713
|
+
this.report(
|
|
714
|
+
"NS1047",
|
|
715
|
+
stmt.isExportEquals ? "`export =` exports an anonymous value." : "`export default` exports an anonymous value.",
|
|
716
|
+
stmt,
|
|
717
|
+
);
|
|
718
|
+
} else if (ts.isExportDeclaration(stmt) && !stmt.isTypeOnly) {
|
|
719
|
+
if (!stmt.exportClause || !ts.isNamedExports(stmt.exportClause)) {
|
|
720
|
+
this.report("NS1047", "`export * from` re-exports a whole module surface without naming anything.", stmt);
|
|
721
|
+
} else {
|
|
722
|
+
this.checkExportList(stmt, file);
|
|
723
|
+
}
|
|
724
|
+
} else if (
|
|
725
|
+
ts.isFunctionDeclaration(stmt) &&
|
|
726
|
+
stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)
|
|
727
|
+
) {
|
|
728
|
+
this.report("NS1047", "`export default` exports the function anonymously.", stmt);
|
|
729
|
+
}
|
|
730
|
+
// Import-boundary rules (relative imports inside src/, npm specifiers,
|
|
731
|
+
// cycles, missing files) live in the module-graph resolver
|
|
732
|
+
// (modules.ts, NS1034-NS1037), which runs before the program is built.
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/// Export lists and value re-exports (`export { a, b as c }`,
|
|
737
|
+
/// `export { x } from "./m.ts"`) bind names over EXISTING declarations in
|
|
738
|
+
/// the flat emitted namespace — real, because every consumer resolves by
|
|
739
|
+
/// name and NS1038 keeps exported names unique. What teaches here is the
|
|
740
|
+
/// genuinely unsound tail: names from outside the core's modules, renamed
|
|
741
|
+
/// bindings over things that have no single emitted value (generic
|
|
742
|
+
/// templates, classes, wiring config), and non-identifier export names.
|
|
743
|
+
private checkExportList(stmt: ts.ExportDeclaration, file: ts.SourceFile): void {
|
|
744
|
+
const bindings = exportListBindings(this.tast, file).filter((b) => b.spec.parent.parent === stmt);
|
|
745
|
+
for (const b of bindings) {
|
|
746
|
+
if (!ts.isIdentifier(b.nameNode)) {
|
|
747
|
+
this.report("NS1047", `\`export { ... as "${b.exportedName}" }\` exports a name no identifier can bind.`, b.spec);
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
const target = b.target;
|
|
751
|
+
if (!target) {
|
|
752
|
+
this.report("NS1047", `\`${b.exportedName}\` resolves to no declaration the emitted module can bind.`, b.spec);
|
|
753
|
+
continue;
|
|
754
|
+
}
|
|
755
|
+
if (ts.isInterfaceDeclaration(target) || ts.isTypeAliasDeclaration(target)) {
|
|
756
|
+
continue; // type re-exported without `type` — tsc's isolatedModules error teaches
|
|
757
|
+
}
|
|
758
|
+
if (!this.fileSet.has(target.getSourceFile())) {
|
|
759
|
+
this.report(
|
|
760
|
+
"NS1047",
|
|
761
|
+
`\`${b.exportedName}\` re-exports a declaration from outside the core's modules (the SDK surface and ambient names are not the core's to re-export).`,
|
|
762
|
+
b.spec,
|
|
763
|
+
);
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
if (b.renamed && ts.isClassDeclaration(target)) {
|
|
767
|
+
this.report(
|
|
768
|
+
"NS1047",
|
|
769
|
+
`\`${b.exportedName}\` renames class \`${target.name?.text}\` — a class exports under its declared name (\`new\` sites and the emitted struct resolve by it).`,
|
|
770
|
+
b.spec,
|
|
771
|
+
);
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
if (b.renamed && ts.isFunctionDeclaration(target) && target.typeParameters && target.typeParameters.length > 0) {
|
|
775
|
+
this.report(
|
|
776
|
+
"NS1047",
|
|
777
|
+
`\`${b.exportedName}\` renames generic \`${target.name?.text}\` — a generic template emits one function per instantiation, so there is no single value to bind a new name over.`,
|
|
778
|
+
b.spec,
|
|
779
|
+
);
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
const targetName = ts.isFunctionDeclaration(target) || ts.isVariableDeclaration(target) ? target.name?.getText() : undefined;
|
|
783
|
+
if (b.renamed && (targetName === "viewUnbound" || targetName === "envMsgs")) {
|
|
784
|
+
this.report(
|
|
785
|
+
"NS1047",
|
|
786
|
+
`\`${b.exportedName}\` renames \`${targetName}\`, which is wiring config the build reads by its own name, not an emitted value.`,
|
|
787
|
+
b.spec,
|
|
788
|
+
);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/// NS1014 — the entry contract: the build wires the dispatch surface and
|
|
794
|
+
/// the host-event channels from src/core.ts only. Imports may FEED those
|
|
795
|
+
/// entry points, but the exports themselves live in the entry module.
|
|
796
|
+
private static readonly entryOnlyExports = new Set([
|
|
797
|
+
"update", "initialModel", "subscriptions",
|
|
798
|
+
"commandMsg", "keyMsg", "frameMsg", "appearanceMsg", "chromeMsg", "envMsgs",
|
|
799
|
+
"viewUnbound",
|
|
800
|
+
]);
|
|
801
|
+
|
|
802
|
+
private checkEntryContract(): void {
|
|
803
|
+
// Export lists claim entry-surface names too: an imported module
|
|
804
|
+
// list-exporting `update` is as silently inert as declaring it there,
|
|
805
|
+
// and the entry re-exporting (or rename-binding) an entry point leaves
|
|
806
|
+
// the wiring nothing to wire — the dispatch machinery keys on the
|
|
807
|
+
// DECLARATION (its name, its return shape), so the entry point must be
|
|
808
|
+
// declared in core.ts and exported under its own name.
|
|
809
|
+
for (const file of this.files) {
|
|
810
|
+
for (const b of exportListBindings(this.tast, file)) {
|
|
811
|
+
if (!SubsetChecker.entryOnlyExports.has(b.exportedName)) continue;
|
|
812
|
+
if (file !== this.entry) {
|
|
813
|
+
this.report("NS1014", `\`${b.exportedName}\` is exported from an imported module.`, b.spec);
|
|
814
|
+
} else if (b.target && b.target.getSourceFile() !== this.entry) {
|
|
815
|
+
this.report("NS1014", `\`${b.exportedName}\` is re-exported from an imported module — declare it in core.ts.`, b.spec);
|
|
816
|
+
} else if (b.renamed) {
|
|
817
|
+
this.report(
|
|
818
|
+
"NS1014",
|
|
819
|
+
`\`${b.exportedName}\` is bound by a renamed export — the build wires the declaration itself, so declare \`${b.exportedName}\` and export it under its own name.`,
|
|
820
|
+
b.spec,
|
|
821
|
+
);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
for (const file of this.files) {
|
|
826
|
+
if (file === this.entry) continue;
|
|
827
|
+
for (const stmt of file.statements) {
|
|
828
|
+
if (ts.isFunctionDeclaration(stmt) && stmt.name && hasExportModifier(stmt)) {
|
|
829
|
+
if (SubsetChecker.entryOnlyExports.has(stmt.name.text)) {
|
|
830
|
+
this.report("NS1014", `\`${stmt.name.text}\` is exported from an imported module.`, stmt.name);
|
|
831
|
+
}
|
|
832
|
+
} else if (ts.isVariableStatement(stmt)) {
|
|
833
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
834
|
+
if (!ts.isIdentifier(decl.name)) continue;
|
|
835
|
+
const name = decl.name.text;
|
|
836
|
+
// envMsgs/viewUnbound are wiring CONFIG the emitter reads by
|
|
837
|
+
// name from the entry module; even unexported copies elsewhere
|
|
838
|
+
// would be silently inert (or worse, silently wired).
|
|
839
|
+
if (name === "envMsgs" || name === "viewUnbound" || (hasExportModifier(stmt) && SubsetChecker.entryOnlyExports.has(name))) {
|
|
840
|
+
this.report("NS1014", `\`${name}\` is declared in an imported module.`, decl.name);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/// NS1038 — one flat emitted namespace: type names (which the whole
|
|
849
|
+
/// pipeline resolves by name) and EXPORTED value names must be unique
|
|
850
|
+
/// across the core's modules. Private value collisions are fine — the
|
|
851
|
+
/// emitter uniques those with a per-module prefix.
|
|
852
|
+
private checkNameCollisions(): void {
|
|
853
|
+
interface Claim {
|
|
854
|
+
readonly file: ts.SourceFile;
|
|
855
|
+
/// The underlying declaration, so a name exported twice OVER THE SAME
|
|
856
|
+
/// declaration (`export function f` re-exported down a chain) never
|
|
857
|
+
/// reads as a collision — one declaration is one emitted name.
|
|
858
|
+
readonly decl: ts.Node;
|
|
859
|
+
}
|
|
860
|
+
const types = new Map<string, Claim>();
|
|
861
|
+
const exportedValues = new Map<string, Claim>();
|
|
862
|
+
for (const file of this.files) {
|
|
863
|
+
for (const stmt of file.statements) {
|
|
864
|
+
if (ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)) {
|
|
865
|
+
const name = stmt.name.text;
|
|
866
|
+
const prior = types.get(name) ?? exportedValues.get(name);
|
|
867
|
+
if (prior) {
|
|
868
|
+
// Same-file collisions count too: a type and an exported value
|
|
869
|
+
// (or two interface declarations — TS merges them, the emitted
|
|
870
|
+
// module cannot) would emit one Zig name twice.
|
|
871
|
+
const where = prior.file === file ? "in this module" : `in ${prior.file.fileName}`;
|
|
872
|
+
this.report("NS1038", `Type \`${name}\` is also declared ${where}.`, stmt.name);
|
|
873
|
+
} else {
|
|
874
|
+
types.set(name, { file, decl: stmt });
|
|
875
|
+
}
|
|
876
|
+
} else if (ts.isFunctionDeclaration(stmt) && stmt.name && hasExportModifier(stmt)) {
|
|
877
|
+
this.recordExportedValue(stmt.name.text, stmt.name, stmt, types, exportedValues, file);
|
|
878
|
+
} else if (ts.isVariableStatement(stmt) && hasExportModifier(stmt)) {
|
|
879
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
880
|
+
if (ts.isIdentifier(decl.name)) this.recordExportedValue(decl.name.text, decl.name, decl, types, exportedValues, file);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
// Export lists bind names into the same exported-value namespace: a
|
|
885
|
+
// renamed export claims its NEW name; an un-renamed one claims the
|
|
886
|
+
// declaration's own name (deduped by declaration identity above).
|
|
887
|
+
for (const b of exportListBindings(this.tast, file)) {
|
|
888
|
+
const t = b.target;
|
|
889
|
+
if (!t || !this.fileSet.has(t.getSourceFile())) continue;
|
|
890
|
+
if (!ts.isFunctionDeclaration(t) && !ts.isVariableDeclaration(t) && !ts.isClassDeclaration(t)) continue;
|
|
891
|
+
this.recordExportedValue(b.exportedName, b.spec.name, t, types, exportedValues, file);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
private recordExportedValue(
|
|
897
|
+
name: string,
|
|
898
|
+
site: ts.Node,
|
|
899
|
+
decl: ts.Node,
|
|
900
|
+
types: Map<string, { readonly file: ts.SourceFile; readonly decl: ts.Node }>,
|
|
901
|
+
exportedValues: Map<string, { readonly file: ts.SourceFile; readonly decl: ts.Node }>,
|
|
902
|
+
file: ts.SourceFile,
|
|
903
|
+
): void {
|
|
904
|
+
const prior = exportedValues.get(name) ?? types.get(name);
|
|
905
|
+
if (prior) {
|
|
906
|
+
if (prior.decl === decl) return; // the same declaration under the same name — one emitted binding
|
|
907
|
+
const where = prior.file === file ? "in this module" : `in ${prior.file.fileName}`;
|
|
908
|
+
this.report("NS1038", `Exported \`${name}\` is also declared ${where}.`, site);
|
|
909
|
+
} else {
|
|
910
|
+
exportedValues.set(name, { file, decl });
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/// NS1003: no function-typed fields anywhere in the model/message tree.
|
|
915
|
+
private checkModelHoldsData(): void {
|
|
916
|
+
const scanFields = (typeName: string, seen: Set<string>): void => {
|
|
917
|
+
if (seen.has(typeName)) return;
|
|
918
|
+
seen.add(typeName);
|
|
919
|
+
const struct = this.table.structs.get(typeName);
|
|
920
|
+
const fields = struct
|
|
921
|
+
? struct.fields
|
|
922
|
+
: this.table.unions.get(typeName)?.arms.flatMap((a) => [...a.fields]) ?? [];
|
|
923
|
+
for (const f of fields) {
|
|
924
|
+
const decl = f.decl;
|
|
925
|
+
if (ts.isPropertySignature(decl) && decl.type && ts.isFunctionTypeNode(decl.type)) {
|
|
926
|
+
this.report("NS1003", `\`${f.tsName}\` stores a function in the ${typeName} tree.`, decl);
|
|
927
|
+
}
|
|
928
|
+
const t = f.type;
|
|
929
|
+
const nested = t.k === "slice" ? t.elem : t.k === "optional" ? t.inner : t;
|
|
930
|
+
if (nested.k === "struct" || nested.k === "union") scanFields(nested.name, seen);
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
const seen = new Set<string>();
|
|
934
|
+
scanFields("Model", seen);
|
|
935
|
+
scanFields("Msg", seen);
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/// NS1024: a `string`-typed field anywhere in the MODEL tree (a
|
|
939
|
+
/// literal-union tag is not a string — it compiles to an enum). Reported
|
|
940
|
+
/// at the field's declaration, before any use, so the fix lands where the
|
|
941
|
+
/// edit goes: retype as `Uint8Array` (+ `asciiBytes` for literals) or a
|
|
942
|
+
/// string-literal union for closed sets.
|
|
943
|
+
private checkModelTextIsBytes(): void {
|
|
944
|
+
const seen = new Set<string>();
|
|
945
|
+
const scanType = (typeName: string): void => {
|
|
946
|
+
if (seen.has(typeName)) return;
|
|
947
|
+
seen.add(typeName);
|
|
948
|
+
const struct = this.table.structs.get(typeName);
|
|
949
|
+
const fields = struct
|
|
950
|
+
? struct.fields.map((f) => ({ f, owner: typeName }))
|
|
951
|
+
: (this.table.unions.get(typeName)?.arms.flatMap((a) =>
|
|
952
|
+
a.fields.map((f) => ({ f, owner: `${typeName}.${a.tag}` })),
|
|
953
|
+
) ?? []);
|
|
954
|
+
for (const { f, owner } of fields) {
|
|
955
|
+
const t = f.type.k === "optional" ? f.type.inner : f.type;
|
|
956
|
+
const nested = t.k === "slice" ? (t.elem.k === "optional" ? t.elem.inner : t.elem) : t;
|
|
957
|
+
if (t.k === "string" || (t.k === "slice" && nested.k === "string")) {
|
|
958
|
+
this.report(
|
|
959
|
+
"NS1024",
|
|
960
|
+
`Model field \`${f.tsName}\` on \`${owner}\` is typed \`string\`${t.k === "slice" ? " elements" : ""}.`,
|
|
961
|
+
f.decl,
|
|
962
|
+
);
|
|
963
|
+
}
|
|
964
|
+
if (nested.k === "struct" || nested.k === "union") scanType(nested.name);
|
|
965
|
+
}
|
|
966
|
+
};
|
|
967
|
+
scanType("Model");
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
// ---------------------------------------------------------- data classes
|
|
971
|
+
|
|
972
|
+
/// A data class: annotated fields, at most one constructor, plain methods.
|
|
973
|
+
/// The banned tail teaches — inheritance (NS1055), accessors/statics/
|
|
974
|
+
/// privacy/auto-accessors (NS1056), generics (NS1053), parameter
|
|
975
|
+
/// properties (NS1008, non-erasable) — each named at its construct.
|
|
976
|
+
private checkClassDeclaration(stmt: ts.ClassDeclaration): void {
|
|
977
|
+
const name = stmt.name?.text;
|
|
978
|
+
if (!name) {
|
|
979
|
+
this.report("NS1006", "An anonymous class has no name to construct with `new`.", stmt);
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
if (stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.AbstractKeyword)) {
|
|
983
|
+
this.report("NS1055", `\`abstract class ${name}\` exists to be subclassed.`, stmt);
|
|
984
|
+
}
|
|
985
|
+
if (stmt.typeParameters && stmt.typeParameters.length > 0) {
|
|
986
|
+
this.report(
|
|
987
|
+
"NS1053",
|
|
988
|
+
`generic \`class ${name}<...>\`: a class emits as one concrete struct — make the varying piece a generic function or a generic record type.`,
|
|
989
|
+
stmt,
|
|
990
|
+
);
|
|
991
|
+
}
|
|
992
|
+
for (const h of stmt.heritageClauses ?? []) {
|
|
993
|
+
// `implements` is an erasable type-level promise and stays legal.
|
|
994
|
+
if (h.token === ts.SyntaxKind.ExtendsKeyword) {
|
|
995
|
+
this.report("NS1055", `\`class ${name} extends ...\` declares inheritance.`, h);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
if (this.table.classes.has(name) && this.table.isPointerStruct(name)) {
|
|
999
|
+
// FLAGGED follow-up: heap-node class instances (Model storage) need
|
|
1000
|
+
// the pointer-repr construction path; v1 keeps instances local values.
|
|
1001
|
+
this.report(
|
|
1002
|
+
"NS1056",
|
|
1003
|
+
`class \`${name}\` is stored in the Model tree — class instances stay local values in v1; store a record (interface) in the Model and construct the class from it where behavior is needed.`,
|
|
1004
|
+
stmt,
|
|
1005
|
+
);
|
|
1006
|
+
}
|
|
1007
|
+
let sawCtor = false;
|
|
1008
|
+
for (const m of stmt.members) {
|
|
1009
|
+
const memberName = m.name?.getText() ?? "<member>";
|
|
1010
|
+
if (ts.isGetAccessorDeclaration(m) || ts.isSetAccessorDeclaration(m)) {
|
|
1011
|
+
this.report("NS1056", `\`${ts.isGetAccessorDeclaration(m) ? "get" : "set"} ${memberName}\` declares an accessor.`, m);
|
|
1012
|
+
continue;
|
|
1013
|
+
}
|
|
1014
|
+
if (ts.isClassStaticBlockDeclaration(m)) {
|
|
1015
|
+
this.report("NS1056", "`static { }` runs code at module load.", m);
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
if (ts.isIndexSignatureDeclaration(m)) {
|
|
1019
|
+
this.report("NS1041", "An index signature makes the instance shape dynamic.", m);
|
|
1020
|
+
continue;
|
|
1021
|
+
}
|
|
1022
|
+
if (ts.isSemicolonClassElement(m)) continue;
|
|
1023
|
+
const mods = ts.canHaveModifiers(m) ? (ts.getModifiers(m) ?? []) : [];
|
|
1024
|
+
const flag = (kind: ts.SyntaxKind): boolean => mods.some((x) => x.kind === kind);
|
|
1025
|
+
// `private`/`protected` keywords are ERASED: tsc enforces them at the
|
|
1026
|
+
// type level, which is their whole meaning (runtime #-privacy below
|
|
1027
|
+
// stays taught).
|
|
1028
|
+
if (flag(ts.SyntaxKind.StaticKeyword) && ts.isPropertyDeclaration(m)) {
|
|
1029
|
+
// `static readonly` fields with initializers are module consts;
|
|
1030
|
+
// a MUTABLE static is module state, and an uninitialized one has
|
|
1031
|
+
// no value to emit.
|
|
1032
|
+
if (!flag(ts.SyntaxKind.ReadonlyKeyword)) {
|
|
1033
|
+
this.report("NS1010", `\`static ${memberName}\` is mutable per-class state — module state by another spelling.`, m);
|
|
1034
|
+
} else if (!m.initializer) {
|
|
1035
|
+
this.report("NS1056", `\`static readonly ${memberName}\` has no initializer (a static const IS its value).`, m);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
if (flag(ts.SyntaxKind.AccessorKeyword)) {
|
|
1039
|
+
this.report("NS1056", `\`accessor ${memberName}\` declares an auto-accessor pair.`, m);
|
|
1040
|
+
}
|
|
1041
|
+
if (flag(ts.SyntaxKind.AbstractKeyword)) {
|
|
1042
|
+
this.report("NS1055", `\`abstract ${memberName}\` exists for subclasses to fill in.`, m);
|
|
1043
|
+
}
|
|
1044
|
+
if (m.name && ts.isPrivateIdentifier(m.name)) {
|
|
1045
|
+
this.report("NS1056", `\`${m.name.text}\` declares a #-private member (a runtime privacy brand).`, m);
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
if (ts.isPropertyDeclaration(m)) {
|
|
1049
|
+
if (!m.name || !ts.isIdentifier(m.name)) {
|
|
1050
|
+
this.report("NS1056", "A computed field name makes the shape dynamic.", m);
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
// Static consts follow the module-const rules (annotation optional
|
|
1054
|
+
// for foldable numbers/strings); the checks below are instance-layout
|
|
1055
|
+
// rules.
|
|
1056
|
+
if (flag(ts.SyntaxKind.StaticKeyword)) continue;
|
|
1057
|
+
if (!m.type) {
|
|
1058
|
+
this.report("NS1056", `field \`${m.name.text}\` has no type annotation (spell it: \`${m.name.text}: number = ...\`).`, m);
|
|
1059
|
+
}
|
|
1060
|
+
if (m.questionToken) {
|
|
1061
|
+
this.report("NS1056", `optional field \`${m.name.text}?\` — spell the empty explicitly (\`${m.name.text}: T | null\`).`, m);
|
|
1062
|
+
}
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
if (ts.isConstructorDeclaration(m)) {
|
|
1066
|
+
if (!m.body) {
|
|
1067
|
+
this.report("NS1056", "A constructor overload signature declares no body.", m);
|
|
1068
|
+
continue;
|
|
1069
|
+
}
|
|
1070
|
+
if (sawCtor) this.report("NS1056", "A class has one constructor.", m);
|
|
1071
|
+
sawCtor = true;
|
|
1072
|
+
for (const pm of m.parameters) {
|
|
1073
|
+
if (ts.canHaveModifiers(pm) && (ts.getModifiers(pm)?.length ?? 0) > 0) {
|
|
1074
|
+
this.report("NS1008", `constructor parameter property \`${pm.name.getText()}\` is non-erasable syntax.`, pm);
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
continue;
|
|
1078
|
+
}
|
|
1079
|
+
if (ts.isMethodDeclaration(m)) {
|
|
1080
|
+
if (!ts.isIdentifier(m.name)) {
|
|
1081
|
+
this.report("NS1056", "A computed method name makes dispatch dynamic.", m);
|
|
1082
|
+
}
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
/// The class member (method or constructor body of a table-registered
|
|
1089
|
+
/// data class) a node sits in, looking through arrows (which inherit
|
|
1090
|
+
/// `this`) and stopping at any function that re-binds it.
|
|
1091
|
+
private enclosingClassMember(node: ts.Node): ts.MethodDeclaration | ts.ConstructorDeclaration | null {
|
|
1092
|
+
let cur: ts.Node | undefined = node.parent;
|
|
1093
|
+
while (cur && !ts.isSourceFile(cur)) {
|
|
1094
|
+
if (ts.isFunctionDeclaration(cur) || ts.isFunctionExpression(cur)) return null;
|
|
1095
|
+
if (ts.isPropertyDeclaration(cur)) return null; // field initializers stay taught
|
|
1096
|
+
if (ts.isMethodDeclaration(cur) || ts.isConstructorDeclaration(cur)) {
|
|
1097
|
+
const cls = cur.parent;
|
|
1098
|
+
if (ts.isClassDeclaration(cls) && cls.name && this.table.classes.get(cls.name.text)?.decl === cls) {
|
|
1099
|
+
return cur;
|
|
1100
|
+
}
|
|
1101
|
+
return null;
|
|
1102
|
+
}
|
|
1103
|
+
cur = cur.parent;
|
|
1104
|
+
}
|
|
1105
|
+
return null;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// ------------------------------------------------------------- exceptions
|
|
1109
|
+
|
|
1110
|
+
/// NS1058: `finally` runs on every exit path via a scoped defer, which
|
|
1111
|
+
/// cannot carry control flow — so returns, throws, and breaks/continues
|
|
1112
|
+
/// that leave the finally block teach.
|
|
1113
|
+
private checkFinallyBlock(fin: ts.Block): void {
|
|
1114
|
+
const visit = (n: ts.Node, loopDepth: number, switchDepth: number, labels: Set<string>): void => {
|
|
1115
|
+
if (ts.isFunctionDeclaration(n) || ts.isArrowFunction(n) || ts.isFunctionExpression(n)) return;
|
|
1116
|
+
if (ts.isReturnStatement(n)) {
|
|
1117
|
+
this.report("NS1058", "`return` inside `finally` overrides the pending return or exception.", n);
|
|
1118
|
+
} else if (ts.isThrowStatement(n)) {
|
|
1119
|
+
this.report("NS1058", "`throw` inside `finally` replaces the pending return or exception.", n);
|
|
1120
|
+
} else if (ts.isBreakStatement(n) || ts.isContinueStatement(n)) {
|
|
1121
|
+
const kw = ts.isBreakStatement(n) ? "break" : "continue";
|
|
1122
|
+
const local = n.label
|
|
1123
|
+
? labels.has(n.label.text)
|
|
1124
|
+
: ts.isBreakStatement(n)
|
|
1125
|
+
? loopDepth > 0 || switchDepth > 0
|
|
1126
|
+
: loopDepth > 0;
|
|
1127
|
+
if (!local) {
|
|
1128
|
+
this.report("NS1058", `\`${kw}\` inside \`finally\` jumps out of it, overriding the pending exit.`, n);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
const isLoop =
|
|
1132
|
+
ts.isForStatement(n) || ts.isForOfStatement(n) || ts.isForInStatement(n) || ts.isWhileStatement(n) || ts.isDoStatement(n);
|
|
1133
|
+
const nextLabels = ts.isLabeledStatement(n) ? new Set([...labels, n.label.text]) : labels;
|
|
1134
|
+
ts.forEachChild(n, (c) =>
|
|
1135
|
+
visit(c, loopDepth + (isLoop ? 1 : 0), switchDepth + (ts.isSwitchStatement(n) ? 1 : 0), nextLabels),
|
|
1136
|
+
);
|
|
1137
|
+
};
|
|
1138
|
+
for (const stmt of fin.statements) visit(stmt, 0, 0, new Set());
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
/// NS1057: the checker types a catch binding as the core's thrown shape
|
|
1142
|
+
/// (the thrown union when shapes differ), so it is read IN PLACE — kind
|
|
1143
|
+
/// tests (`if (e.kind === "parse")`), field reads off the narrowed arm,
|
|
1144
|
+
/// bare rethrow, or a single `as` narrowing. What teaches is the binding
|
|
1145
|
+
/// ESCAPING untyped: tsc types it `any` here (the subset checker is the
|
|
1146
|
+
/// authority), so a bare `e` handed to a call, stored, or returned would
|
|
1147
|
+
/// leave the type system silently.
|
|
1148
|
+
private checkCatchClause(cc: ts.CatchClause): void {
|
|
1149
|
+
const v = cc.variableDeclaration;
|
|
1150
|
+
if (!v) return;
|
|
1151
|
+
if (!ts.isIdentifier(v.name)) {
|
|
1152
|
+
this.report("NS1057", "a destructured catch binding — bind a name and narrow it once.", v);
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
const name = v.name.text;
|
|
1156
|
+
const visit = (n: ts.Node): void => {
|
|
1157
|
+
if (ts.isIdentifier(n) && n !== v.name && this.tast.declarationOf(n) === v) {
|
|
1158
|
+
let cur: ts.Node = n;
|
|
1159
|
+
let p: ts.Node = cur.parent;
|
|
1160
|
+
while (ts.isParenthesizedExpression(p)) {
|
|
1161
|
+
cur = p;
|
|
1162
|
+
p = p.parent;
|
|
1163
|
+
}
|
|
1164
|
+
const asserted = ts.isAsExpression(p) && p.expression === cur;
|
|
1165
|
+
const rethrown = ts.isThrowStatement(p) && p.expression === cur;
|
|
1166
|
+
const readInPlace = ts.isPropertyAccessExpression(p) && p.expression === cur;
|
|
1167
|
+
if (!asserted && !rethrown && !readInPlace) {
|
|
1168
|
+
this.report(
|
|
1169
|
+
"NS1057",
|
|
1170
|
+
`catch binding \`${name}\` escapes as an untyped value — read it in place (\`${name}.kind\` tests, the narrowed arm's fields), rethrow it (\`throw ${name};\`), or narrow it once (\`const err = ${name} as YourError;\`) and hand the narrowed value on.`,
|
|
1171
|
+
n,
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
ts.forEachChild(n, visit);
|
|
1176
|
+
};
|
|
1177
|
+
visit(cc.block);
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/// NS1057, module-wide: every throw carries the core's one error shape.
|
|
1181
|
+
private checkExceptions(): void {
|
|
1182
|
+
const res = thrownShapeOf(this.tast, this.table, this.files);
|
|
1183
|
+
for (const pr of res.problems) this.report("NS1057", pr.msg, pr.node);
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
// ------------------------------------------------------------------ walk
|
|
1187
|
+
|
|
1188
|
+
/// Whether the tsc type string names a mutable-or-readonly ARRAY. A bare
|
|
1189
|
+
/// `Uint8Array` is bytes (its own writable-until-escape discipline), but an
|
|
1190
|
+
/// array OF byte buffers (`Uint8Array[]`, `Array<Uint8Array>`) is an array
|
|
1191
|
+
/// like any other and follows array ownership.
|
|
1192
|
+
private isArrayTypeString(t: string): boolean {
|
|
1193
|
+
// tsc may print bytes with its buffer parameter (`Uint8Array<ArrayBuffer>`).
|
|
1194
|
+
const withoutBytes = t.replace(/Uint8Array(<[^<>]*>)?/g, "");
|
|
1195
|
+
return withoutBytes.includes("[]") || t.startsWith("readonly") || withoutBytes.includes("Array");
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/// The ownership teaching for one mutation site (a mutating method call or
|
|
1199
|
+
/// an indexed write). Legal on locally-owned arrays; NS1051 after an
|
|
1200
|
+
/// escape; NS1022 for in-place sort on shared data; NS1001 otherwise.
|
|
1201
|
+
private checkArrayMutation(base: ts.Expression, site: ts.Node, what: string, method: string | null): void {
|
|
1202
|
+
const verdict = arrayOwnership(this.tast, base, site);
|
|
1203
|
+
if (verdict.owned) {
|
|
1204
|
+
// The emitter enforces the exact lowering shapes (value-position
|
|
1205
|
+
// rules, spread arguments, iteration interleaving).
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
if (verdict.why === "escaped") {
|
|
1209
|
+
this.report("NS1051", `${what} mutates after the array escaped: ${verdict.detail}.`, site);
|
|
1210
|
+
} else if (method === "sort") {
|
|
1211
|
+
this.report("NS1022", `\`.sort()\` sorts, in place, an array this function does not own: ${verdict.detail}.`, site);
|
|
1212
|
+
} else {
|
|
1213
|
+
this.report("NS1001", `${what} mutates an array this function does not own: ${verdict.detail}.`, site);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/// The ownership teaching for one class-instance mutation site (a field
|
|
1218
|
+
/// write or a mutating-method call). Legal on locally-owned instances;
|
|
1219
|
+
/// NS1051 after an escape; NS1001 on shared data.
|
|
1220
|
+
private checkInstanceMutation(base: ts.Expression, site: ts.Node, what: string): void {
|
|
1221
|
+
const verdict = instanceOwnership(this.tast, base, site);
|
|
1222
|
+
if (verdict.owned) return;
|
|
1223
|
+
if (verdict.why === "escaped") {
|
|
1224
|
+
this.report("NS1051", `${what} mutates after the instance escaped: ${verdict.detail}.`, site);
|
|
1225
|
+
} else {
|
|
1226
|
+
this.report("NS1001", `${what} mutates an instance this function does not own: ${verdict.detail}.`, site);
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/// Whether a resolved type mentions a type parameter anywhere (such an
|
|
1231
|
+
/// argument resolves when the ENCLOSING generic instantiates).
|
|
1232
|
+
private containsTypeParameter(t: import("./typed_ast.ts").Type): boolean {
|
|
1233
|
+
if ((t.flags & ts.TypeFlags.TypeParameter) !== 0) return true;
|
|
1234
|
+
if (t.isUnion()) return t.types.some((m) => this.containsTypeParameter(m));
|
|
1235
|
+
return this.tast.typeArgumentsOf(t).some((a) => this.containsTypeParameter(a));
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
private isStringTyped(expr: ts.Expression): boolean {
|
|
1239
|
+
const t = this.tast.typeOf(expr);
|
|
1240
|
+
return (t.flags & (ts.TypeFlags.String | ts.TypeFlags.StringLiteral)) !== 0;
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/// String-typed, or a string-literal union value (emitted as an enum,
|
|
1244
|
+
/// where relational order would be declaration order, not code units).
|
|
1245
|
+
private isStringValued(expr: ts.Expression): boolean {
|
|
1246
|
+
if (this.isStringTyped(expr)) return true;
|
|
1247
|
+
const t = this.tast.typeOf(expr);
|
|
1248
|
+
return t.isUnion() && t.types.every((m) => m.isStringLiteral());
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
private walk(root: ts.Node): void {
|
|
1252
|
+
const visit = (node: ts.Node): void => {
|
|
1253
|
+
// NS1002 — synchronous updates.
|
|
1254
|
+
if (ts.isAwaitExpression(node)) {
|
|
1255
|
+
this.report("NS1002", "`await` cannot appear inside an app core.", node);
|
|
1256
|
+
} else if (
|
|
1257
|
+
(ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)) &&
|
|
1258
|
+
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword)
|
|
1259
|
+
) {
|
|
1260
|
+
this.report("NS1002", "`async` functions cannot appear inside an app core.", node);
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// NS1006 — classes are module-level declarations (expressions stay
|
|
1264
|
+
// taught); `this` is the receiver inside a data-class member and
|
|
1265
|
+
// reaches only fields and methods (`this.count`, `this.step()`).
|
|
1266
|
+
if (ts.isClassExpression(node)) {
|
|
1267
|
+
this.report("NS1006", "A class expression declares a class.", node);
|
|
1268
|
+
}
|
|
1269
|
+
if (node.kind === ts.SyntaxKind.ThisKeyword) {
|
|
1270
|
+
const member = this.enclosingClassMember(node);
|
|
1271
|
+
if (member === null) {
|
|
1272
|
+
this.report("NS1006", "`this` outside a class member body refers to no instance.", node);
|
|
1273
|
+
} else if (
|
|
1274
|
+
ts.canHaveModifiers(member) &&
|
|
1275
|
+
(ts.getModifiers(member) ?? []).some((x) => x.kind === ts.SyntaxKind.StaticKeyword)
|
|
1276
|
+
) {
|
|
1277
|
+
this.report(
|
|
1278
|
+
"NS1056",
|
|
1279
|
+
"`this` inside a static member is the class object, which is not a value — reach statics by the class name (`Task.LIMIT`, `Task.fromRow(...)`).",
|
|
1280
|
+
node,
|
|
1281
|
+
);
|
|
1282
|
+
} else if (!(ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
|
|
1283
|
+
this.report(
|
|
1284
|
+
"NS1056",
|
|
1285
|
+
"`this` is used as a value (returned, stored, or passed) — only `this.field` and `this.method()` reach the receiver.",
|
|
1286
|
+
node,
|
|
1287
|
+
);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
// NS1042 — generators (a resumable frame is hidden state).
|
|
1292
|
+
if (
|
|
1293
|
+
(ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)) &&
|
|
1294
|
+
node.asteriskToken
|
|
1295
|
+
) {
|
|
1296
|
+
this.report("NS1042", "`function*` declares a generator.", node);
|
|
1297
|
+
} else if (ts.isYieldExpression(node)) {
|
|
1298
|
+
this.report("NS1042", "`yield` suspends a generator frame.", node);
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// NS1046 — functions are module-level declarations (or const-bound
|
|
1302
|
+
// local helpers, which hoist); everything else that treats a function
|
|
1303
|
+
// as a runtime value stays taught.
|
|
1304
|
+
if (ts.isFunctionDeclaration(node) && !ts.isSourceFile(node.parent) && !node.asteriskToken) {
|
|
1305
|
+
this.report("NS1046", `\`function ${node.name?.text ?? "<anonymous>"}\` declares a nested function.`, node);
|
|
1306
|
+
} else if (
|
|
1307
|
+
(ts.isFunctionExpression(node) && !node.asteriskToken) ||
|
|
1308
|
+
(ts.isArrowFunction(node) && !isCallArgument(node))
|
|
1309
|
+
) {
|
|
1310
|
+
// NS1054 — the const-bound local-helper shape hoists to a module-
|
|
1311
|
+
// level declaration when it is capture-free, fully annotated, and
|
|
1312
|
+
// only called or passed as an array-method callback.
|
|
1313
|
+
const owner = owningConstDecl(node);
|
|
1314
|
+
const hoisted = owner ? constFunctionValue(owner) : null;
|
|
1315
|
+
if (owner && hoisted === node) {
|
|
1316
|
+
const verdict = functionValueLegality(owner, hoisted, this.tast);
|
|
1317
|
+
if (!verdict.ok) {
|
|
1318
|
+
this.report("NS1054", `This local function value cannot hoist: ${verdict.why}.`, node);
|
|
1319
|
+
}
|
|
1320
|
+
} else if (ts.isFunctionExpression(node)) {
|
|
1321
|
+
this.report("NS1046", "A `function` expression outside a `const` binding makes a function value.", node);
|
|
1322
|
+
} else {
|
|
1323
|
+
this.report("NS1046", "An arrow function outside a call-argument position or a `const` binding makes a stored function value.", node);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
if (ts.isCallExpression(node) && node.questionDotToken) {
|
|
1327
|
+
this.report("NS1046", "`?.()` calls a possibly-absent function value.", node);
|
|
1328
|
+
}
|
|
1329
|
+
// NS1054 — a call through a record FIELD reads a stored function.
|
|
1330
|
+
if (
|
|
1331
|
+
ts.isCallExpression(node) &&
|
|
1332
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
1333
|
+
!node.questionDotToken
|
|
1334
|
+
) {
|
|
1335
|
+
const d = this.tast.declarationOf(node.expression.name);
|
|
1336
|
+
if (
|
|
1337
|
+
d &&
|
|
1338
|
+
ts.isPropertySignature(d) &&
|
|
1339
|
+
d.type &&
|
|
1340
|
+
ts.isFunctionTypeNode(d.type) &&
|
|
1341
|
+
this.fileSet.has(d.getSourceFile())
|
|
1342
|
+
) {
|
|
1343
|
+
this.report("NS1054", `\`.${node.expression.name.text}()\` calls a function stored in a record field.`, node);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
// NS1040 — regular expressions.
|
|
1348
|
+
if (node.kind === ts.SyntaxKind.RegularExpressionLiteral) {
|
|
1349
|
+
this.report("NS1040", "A regex literal builds a RegExp value.", node);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
// NS1041 — no runtime type or shape tests.
|
|
1353
|
+
if (ts.isTypeOfExpression(node)) {
|
|
1354
|
+
this.report("NS1041", "`typeof` reads a runtime type tag.", node);
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// NS1044 — BigInt/Symbol value kinds.
|
|
1358
|
+
if (node.kind === ts.SyntaxKind.BigIntLiteral) {
|
|
1359
|
+
this.report("NS1044", "A BigInt literal makes an arbitrary-precision integer.", node);
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
// NS1043 — comma and void squeeze statements into expression position;
|
|
1363
|
+
// an assignment's value is read after the statement. The classic
|
|
1364
|
+
// for-loop's incrementor is the sanctioned home for both.
|
|
1365
|
+
if (ts.isVoidExpression(node)) {
|
|
1366
|
+
this.report("NS1043", "`void` manufactures a JS undefined.", node);
|
|
1367
|
+
}
|
|
1368
|
+
// `++`/`--` in value position: legal when the split statement is
|
|
1369
|
+
// provably order-exact (`arr[i++]`, `const n = ++count`); the
|
|
1370
|
+
// remainder teaches instead of stopping at the emitter.
|
|
1371
|
+
if (
|
|
1372
|
+
(ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
|
|
1373
|
+
(node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) &&
|
|
1374
|
+
!ts.isExpressionStatement(node.parent) &&
|
|
1375
|
+
!inForIncrementor(node) &&
|
|
1376
|
+
ts.isIdentifier(node.operand)
|
|
1377
|
+
) {
|
|
1378
|
+
const verdict = valuePositionStep(node, node.operand, this.tast);
|
|
1379
|
+
if (!verdict.ok) {
|
|
1380
|
+
this.report("NS1043", `\`++\`/\`--\` used as a value hides a statement (${verdict.why}).`, node);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
if (ts.isBinaryExpression(node)) {
|
|
1384
|
+
const op = node.operatorToken.kind;
|
|
1385
|
+
if (op === ts.SyntaxKind.CommaToken && !inForIncrementor(node)) {
|
|
1386
|
+
this.report("NS1043", "A comma expression sequences statements in expression position.", node);
|
|
1387
|
+
}
|
|
1388
|
+
if (
|
|
1389
|
+
compoundAndPlainAssignmentOps.has(op) &&
|
|
1390
|
+
!ts.isExpressionStatement(node.parent) &&
|
|
1391
|
+
!inForIncrementor(node)
|
|
1392
|
+
) {
|
|
1393
|
+
// A number assignment may ride a value position when the split
|
|
1394
|
+
// statement is provably order-exact (sole mention, unskippable).
|
|
1395
|
+
const verdict = valuePositionStep(node, node.left, this.tast);
|
|
1396
|
+
if (!verdict.ok) {
|
|
1397
|
+
this.report("NS1043", `An assignment used as a value hides a statement (${verdict.why}).`, node);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
// NS1048 — loose equality coerces.
|
|
1401
|
+
if (op === ts.SyntaxKind.EqualsEqualsToken) {
|
|
1402
|
+
this.report("NS1048", "`==` compares with coercion.", node);
|
|
1403
|
+
} else if (op === ts.SyntaxKind.ExclamationEqualsToken) {
|
|
1404
|
+
this.report("NS1048", "`!=` compares with coercion.", node);
|
|
1405
|
+
}
|
|
1406
|
+
// NS1041 — `in` / `instanceof` runtime tests.
|
|
1407
|
+
if (op === ts.SyntaxKind.InKeyword) {
|
|
1408
|
+
this.report("NS1041", "`in` queries an object's shape at runtime.", node);
|
|
1409
|
+
} else if (op === ts.SyntaxKind.InstanceOfKeyword) {
|
|
1410
|
+
this.report("NS1041", "`instanceof` tests a class identity at runtime.", node);
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
// NS1018 — a tagged template runs a function over strings at runtime.
|
|
1415
|
+
if (ts.isTaggedTemplateExpression(node)) {
|
|
1416
|
+
this.report("NS1018", "A tagged template runs a function over its strings at runtime.", node);
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// NS1045 — destructuring: record fields into const locals only.
|
|
1420
|
+
if (ts.isArrayBindingPattern(node)) {
|
|
1421
|
+
// `for (const [i, x] of xs.entries())` keeps its own tailored
|
|
1422
|
+
// teaching (the emitter names the classic-loop rewrite).
|
|
1423
|
+
if (!isEntriesLoopBinding(node)) {
|
|
1424
|
+
this.report("NS1045", "Array destructuring binds element positions.", node);
|
|
1425
|
+
}
|
|
1426
|
+
} else if (ts.isObjectBindingPattern(node)) {
|
|
1427
|
+
if (ts.isParameter(node.parent)) {
|
|
1428
|
+
this.report("NS1045", "A parameter destructures in the signature.", node);
|
|
1429
|
+
} else if (ts.isVariableDeclaration(node.parent) && ts.isVariableDeclarationList(node.parent.parent)) {
|
|
1430
|
+
const list = node.parent.parent;
|
|
1431
|
+
if (ts.isForOfStatement(list.parent) || ts.isForInStatement(list.parent)) {
|
|
1432
|
+
this.report("NS1045", "A loop binding destructures its element.", node);
|
|
1433
|
+
} else if ((list.flags & ts.NodeFlags.Const) === 0) {
|
|
1434
|
+
this.report("NS1045", "`let` destructuring makes reassignable aliases.", node);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
for (const el of node.elements) {
|
|
1438
|
+
if (el.dotDotDotToken) {
|
|
1439
|
+
this.report("NS1045", "`...rest` collects the remaining fields into a new object.", el);
|
|
1440
|
+
} else if (el.initializer) {
|
|
1441
|
+
this.report("NS1045", "A destructuring default expects an absent field.", el);
|
|
1442
|
+
} else if (!ts.isIdentifier(el.name)) {
|
|
1443
|
+
this.report("NS1045", "A nested destructuring pattern hides its reads.", el);
|
|
1444
|
+
} else if (el.propertyName && !ts.isIdentifier(el.propertyName)) {
|
|
1445
|
+
this.report("NS1045", "A computed destructuring key resolves at runtime.", el);
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
// NS1019 — dynamic argument lists (defaults are checked below).
|
|
1451
|
+
if (ts.isParameter(node) && node.dotDotDotToken) {
|
|
1452
|
+
this.report("NS1019", `\`...${node.name.getText()}\` collects a dynamic argument list.`, node);
|
|
1453
|
+
}
|
|
1454
|
+
if (ts.isSpreadElement(node) && ts.isCallExpression(node.parent) && !isMutatingAppendCall(node.parent)) {
|
|
1455
|
+
this.report("NS1019", "`...` spreads a dynamic argument list into a call.", node);
|
|
1456
|
+
}
|
|
1457
|
+
if (
|
|
1458
|
+
ts.isIdentifier(node) &&
|
|
1459
|
+
node.text === "arguments" &&
|
|
1460
|
+
!(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) &&
|
|
1461
|
+
!(ts.isPropertySignature(node.parent) || ts.isPropertyAssignment(node.parent)) &&
|
|
1462
|
+
this.isAmbientRef(node)
|
|
1463
|
+
) {
|
|
1464
|
+
this.report("NS1019", "`arguments` reads the dynamic argument list.", node);
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
// NS1039 — a namespace alias is dot-syntax, not a value.
|
|
1468
|
+
if (ts.isIdentifier(node) && this.nsAliasNames.has(node.text)) {
|
|
1469
|
+
const sym = this.tast.symbolOf(node);
|
|
1470
|
+
const d = sym?.declarations?.[0];
|
|
1471
|
+
if (d && ts.isNamespaceImport(d) && d.name !== node) {
|
|
1472
|
+
const p = node.parent;
|
|
1473
|
+
const legal =
|
|
1474
|
+
(ts.isPropertyAccessExpression(p) && p.expression === node) ||
|
|
1475
|
+
(ts.isQualifiedName(p) && p.left === node);
|
|
1476
|
+
if (!legal) {
|
|
1477
|
+
this.report("NS1039", `\`${node.text}\` uses a namespace alias as a value.`, node);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// R20 — exceptions are deterministic control flow: `throw` unwinds
|
|
1483
|
+
// to the nearest catch inside the core (an uncaught throw is a
|
|
1484
|
+
// defined panic at the boundary — node crashes there too). The
|
|
1485
|
+
// discipline rules teach: one error shape per core (NS1057) and no
|
|
1486
|
+
// control flow out of `finally` (NS1058).
|
|
1487
|
+
if (ts.isTryStatement(node)) {
|
|
1488
|
+
if (node.finallyBlock) this.checkFinallyBlock(node.finallyBlock);
|
|
1489
|
+
if (node.catchClause) this.checkCatchClause(node.catchClause);
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
// NS1008 — decorators.
|
|
1493
|
+
if (ts.isDecorator(node)) {
|
|
1494
|
+
this.report("NS1008", "Decorators are non-erasable syntax.", node);
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
// NS1009 — for/in.
|
|
1498
|
+
if (ts.isForInStatement(node)) {
|
|
1499
|
+
this.report("NS1009", "`for`/`in` walks prototype chains.", node);
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// NS1013 — `debugger` pauses a JS engine the binary does not carry.
|
|
1503
|
+
if (node.kind === ts.SyntaxKind.DebuggerStatement) {
|
|
1504
|
+
this.report("NS1013", "`debugger` pauses a JS engine.", node);
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
// NS1049 — `var` hoists; const/let map exactly. (Module-level `var`
|
|
1508
|
+
// additionally teaches NS1010, the module-state rule.)
|
|
1509
|
+
if (
|
|
1510
|
+
ts.isVariableDeclarationList(node) &&
|
|
1511
|
+
(node.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) === 0
|
|
1512
|
+
) {
|
|
1513
|
+
this.report("NS1049", "`var` declares a hoisted, function-scoped local.", node);
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
// NS1052 — an un-annotated local initialized from a spread array
|
|
1517
|
+
// literal has no slice target for the emitter to lower against
|
|
1518
|
+
// (the generic emit-time stop taught nothing; this names the fix).
|
|
1519
|
+
if (
|
|
1520
|
+
ts.isVariableDeclaration(node) &&
|
|
1521
|
+
!node.type &&
|
|
1522
|
+
node.initializer !== undefined
|
|
1523
|
+
) {
|
|
1524
|
+
let init: ts.Expression = node.initializer;
|
|
1525
|
+
while (ts.isParenthesizedExpression(init)) init = init.expression;
|
|
1526
|
+
if (ts.isArrayLiteralExpression(init) && init.elements.some((el) => ts.isSpreadElement(el))) {
|
|
1527
|
+
this.report(
|
|
1528
|
+
"NS1052",
|
|
1529
|
+
`\`${node.name.getText()}\` spreads into an array literal without declaring its array type.`,
|
|
1530
|
+
node,
|
|
1531
|
+
);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
// NS1050 — generics live on module-level declarations (functions,
|
|
1536
|
+
// interfaces, type aliases — monomorphized per call site). Function
|
|
1537
|
+
// VALUES and the entry points stay concrete.
|
|
1538
|
+
if (
|
|
1539
|
+
(ts.isArrowFunction(node) || ts.isFunctionExpression(node)) &&
|
|
1540
|
+
node.typeParameters &&
|
|
1541
|
+
node.typeParameters.length > 0
|
|
1542
|
+
) {
|
|
1543
|
+
this.report("NS1050", "A generic function value declares a type parameter.", node);
|
|
1544
|
+
} else if (
|
|
1545
|
+
ts.isFunctionDeclaration(node) &&
|
|
1546
|
+
node.typeParameters &&
|
|
1547
|
+
node.typeParameters.length > 0 &&
|
|
1548
|
+
node.name &&
|
|
1549
|
+
SubsetChecker.entryOnlyExports.has(node.name.text)
|
|
1550
|
+
) {
|
|
1551
|
+
this.report("NS1050", `Entry point \`${node.name.text}\` declares a type parameter.`, node);
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
// NS1053 — a generic call must resolve to concrete emitted types
|
|
1555
|
+
// (tsc's own signature resolution; type parameters of an enclosing
|
|
1556
|
+
// generic resolve at that generic's instantiation).
|
|
1557
|
+
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
|
|
1558
|
+
const gdecl = this.tast.declarationOf(node.expression);
|
|
1559
|
+
if (
|
|
1560
|
+
gdecl &&
|
|
1561
|
+
ts.isFunctionDeclaration(gdecl) &&
|
|
1562
|
+
gdecl.typeParameters &&
|
|
1563
|
+
gdecl.typeParameters.length > 0 &&
|
|
1564
|
+
this.fileSet.has(gdecl.getSourceFile())
|
|
1565
|
+
) {
|
|
1566
|
+
const targs = this.tast.resolvedCallTypeArguments(node);
|
|
1567
|
+
if (!targs || targs.length < gdecl.typeParameters.length) {
|
|
1568
|
+
this.report("NS1053", `\`${gdecl.name?.text}\` is called without resolvable type arguments.`, node);
|
|
1569
|
+
} else {
|
|
1570
|
+
targs.forEach((a, idx) => {
|
|
1571
|
+
if (this.containsTypeParameter(a)) return; // resolves at the enclosing instantiation
|
|
1572
|
+
const z = this.table.zTypeOfTsType(a);
|
|
1573
|
+
if (!z || z.k === "void") {
|
|
1574
|
+
this.report(
|
|
1575
|
+
"NS1053",
|
|
1576
|
+
`\`${gdecl.name?.text}\`'s type argument \`${gdecl.typeParameters![idx]?.name.text ?? idx + 1}\` resolves to \`${this.tast.typeToString(a)}\`, which has no concrete emitted type.`,
|
|
1577
|
+
node,
|
|
1578
|
+
);
|
|
1579
|
+
}
|
|
1580
|
+
});
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
// NS1012 — a computed property name builds a shape at runtime.
|
|
1586
|
+
if (ts.isComputedPropertyName(node)) {
|
|
1587
|
+
this.report("NS1012", "A computed property name builds a shape at runtime.", node);
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// NS1012 — shape stability.
|
|
1591
|
+
if (ts.isDeleteExpression(node)) {
|
|
1592
|
+
this.report("NS1012", "`delete` removes a field from a fixed shape.", node);
|
|
1593
|
+
} else if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) {
|
|
1594
|
+
this.report("NS1012", "Getters/setters make field reads run code.", node);
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
// NS1013 — closed world.
|
|
1598
|
+
if (ts.isCallExpression(node)) {
|
|
1599
|
+
if (ts.isIdentifier(node.expression)) {
|
|
1600
|
+
const callName = node.expression.text;
|
|
1601
|
+
if (callName === "eval") {
|
|
1602
|
+
this.report("NS1013", "`eval` executes dynamic code.", node);
|
|
1603
|
+
} else if (callName === "RegExp" && this.isAmbientRef(node.expression)) {
|
|
1604
|
+
this.report("NS1040", "`RegExp(...)` builds a RegExp value.", node);
|
|
1605
|
+
} else if ((callName === "Symbol" || callName === "BigInt") && this.isAmbientRef(node.expression)) {
|
|
1606
|
+
this.report("NS1044", `\`${callName}(...)\` makes a ${callName} value.`, node);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
if (node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
1610
|
+
this.report("NS1013", "Dynamic `import()` loads code at runtime.", node);
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
if (ts.isNewExpression(node)) {
|
|
1614
|
+
if (ts.isIdentifier(node.expression)) {
|
|
1615
|
+
const name = node.expression.text;
|
|
1616
|
+
if (name === "Error" && this.isAmbientRef(node.expression)) {
|
|
1617
|
+
this.report(
|
|
1618
|
+
"NS1057",
|
|
1619
|
+
"`new Error(...)` builds an engine error object (message string, stack trace) with no native shape.",
|
|
1620
|
+
node,
|
|
1621
|
+
);
|
|
1622
|
+
} else if (name === "Function") {
|
|
1623
|
+
this.report("NS1013", "`new Function` compiles source at runtime.", node);
|
|
1624
|
+
} else if (name === "Map" || name === "Set") {
|
|
1625
|
+
// NS1011 — no Map/Set in v1, with or without type arguments.
|
|
1626
|
+
this.report("NS1011", `\`new ${name}\` constructs a hashed container.`, node);
|
|
1627
|
+
} else if (name === "RegExp") {
|
|
1628
|
+
this.report("NS1040", "`new RegExp` builds a RegExp value.", node);
|
|
1629
|
+
} else if (name === "Promise") {
|
|
1630
|
+
this.report("NS1002", "`new Promise` starts asynchronous work.", node);
|
|
1631
|
+
} else if (name === "Date") {
|
|
1632
|
+
this.report("NS1005", "`new Date` reads ambient wall-clock state.", node);
|
|
1633
|
+
} else if (name !== "Uint8Array") {
|
|
1634
|
+
const decl = this.tast.declarationOf(node.expression);
|
|
1635
|
+
const cls = this.table.classes.get(name);
|
|
1636
|
+
const supported = decl !== null && ts.isClassDeclaration(decl) && cls !== undefined && cls.decl === decl;
|
|
1637
|
+
// `new` of a registered data class constructs a record-shaped
|
|
1638
|
+
// value; ill-shaped local classes teach at their declaration,
|
|
1639
|
+
// and everything ambient lands here.
|
|
1640
|
+
if (!supported && this.isAmbientRef(node.expression)) {
|
|
1641
|
+
this.report("NS1006", `\`new ${name}\` constructs a class instance.`, node);
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
} else {
|
|
1645
|
+
this.report("NS1006", "`new` constructs a class instance.", node);
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
// NS1005 — determinism (and the runtime-surface globals near it).
|
|
1650
|
+
if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {
|
|
1651
|
+
const base = node.expression.text;
|
|
1652
|
+
const member = node.name.text;
|
|
1653
|
+
if (base === "Math" && member === "random") {
|
|
1654
|
+
this.report("NS1005", "`Math.random()` draws ambient randomness.", node);
|
|
1655
|
+
} else if (ambientGlobals.has(base)) {
|
|
1656
|
+
this.report("NS1005", `\`${base}.${member}\` reaches ambient platform state.`, node);
|
|
1657
|
+
} else if (base === "Array" && (member === "from" || member === "of" || member === "fromAsync") && this.isAmbientRef(node.expression)) {
|
|
1658
|
+
// NS1059 — the Array constructors get their own accurate teaching
|
|
1659
|
+
// (they BUILD arrays; only `Array.isArray` tests a runtime shape).
|
|
1660
|
+
this.report("NS1059", `\`Array.${member}\` constructs an array through a runtime protocol.`, node);
|
|
1661
|
+
} else if ((base === "Object" || base === "Reflect" || base === "JSON" || base === "Array") && this.isAmbientRef(node.expression)) {
|
|
1662
|
+
this.report("NS1041", `\`${base}.${member}\` works on runtime shapes.`, node);
|
|
1663
|
+
} else if (base === "Symbol" && this.isAmbientRef(node.expression)) {
|
|
1664
|
+
this.report("NS1044", `\`Symbol.${member}\` names an engine symbol.`, node);
|
|
1665
|
+
} else if (base === "Promise" && this.isAmbientRef(node.expression)) {
|
|
1666
|
+
this.report("NS1002", `\`Promise.${member}\` starts asynchronous work.`, node);
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
// NS1060/NS1005/NS1040 — the byte-text stays-out tail: spellings the
|
|
1671
|
+
// ambient surface declares only so each one can teach its reason
|
|
1672
|
+
// (UTF-16, locale, regex) and the byte-honest alternative here.
|
|
1673
|
+
if (
|
|
1674
|
+
ts.isPropertyAccessExpression(node) &&
|
|
1675
|
+
bytesTextStaysOut.has(node.name.text) &&
|
|
1676
|
+
this.tast.isBytesTyped(node.expression)
|
|
1677
|
+
) {
|
|
1678
|
+
const teach = bytesTextStaysOut.get(node.name.text)!;
|
|
1679
|
+
this.report(teach.id, teach.site, node);
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
// NS1004 — string code-unit observation (UTF-16/UTF-8 seam).
|
|
1683
|
+
if (ts.isPropertyAccessExpression(node) && node.name.text === "length" && this.isStringTyped(node.expression)) {
|
|
1684
|
+
this.report("NS1004", "`.length` on a string counts code units.", node);
|
|
1685
|
+
} else if (
|
|
1686
|
+
ts.isPropertyAccessExpression(node) &&
|
|
1687
|
+
stringObservers.has(node.name.text) &&
|
|
1688
|
+
this.isStringTyped(node.expression)
|
|
1689
|
+
) {
|
|
1690
|
+
this.report("NS1004", `\`.${node.name.text}\` on a string reads code units.`, node);
|
|
1691
|
+
} else if (ts.isElementAccessExpression(node) && this.isStringTyped(node.expression)) {
|
|
1692
|
+
this.report("NS1004", "Indexing a string reads a code unit.", node);
|
|
1693
|
+
} else if (ts.isBinaryExpression(node)) {
|
|
1694
|
+
const op = node.operatorToken.kind;
|
|
1695
|
+
const relational =
|
|
1696
|
+
op === ts.SyntaxKind.LessThanToken ||
|
|
1697
|
+
op === ts.SyntaxKind.LessThanEqualsToken ||
|
|
1698
|
+
op === ts.SyntaxKind.GreaterThanToken ||
|
|
1699
|
+
op === ts.SyntaxKind.GreaterThanEqualsToken;
|
|
1700
|
+
if (relational && this.isStringValued(node.left) && this.isStringValued(node.right)) {
|
|
1701
|
+
this.report("NS1004", "Relational comparison on strings orders code units.", node);
|
|
1702
|
+
}
|
|
1703
|
+
// NS1018 — string concatenation (either operand string-valued makes
|
|
1704
|
+
// JS `+` concatenate; `+=` is the same operation through assignment).
|
|
1705
|
+
const concatOp = op === ts.SyntaxKind.PlusToken || op === ts.SyntaxKind.PlusEqualsToken;
|
|
1706
|
+
if (concatOp && (this.isStringValued(node.left) || this.isStringValued(node.right))) {
|
|
1707
|
+
this.report("NS1018", "`+` on a string concatenates at runtime.", node);
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
// NS1019 — parameter defaults are silently arity-changing; ban them.
|
|
1712
|
+
if (ts.isParameter(node) && node.initializer) {
|
|
1713
|
+
this.report("NS1019", `Parameter \`${node.name.getText()}\` declares a default value.`, node);
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
// NS1021 — a null/undefined test on an optional chain distinguishes JS
|
|
1717
|
+
// undefined (the chain short-circuited) from null (the field's value);
|
|
1718
|
+
// the native optional cannot.
|
|
1719
|
+
if (ts.isBinaryExpression(node)) {
|
|
1720
|
+
const op = node.operatorToken.kind;
|
|
1721
|
+
const equality =
|
|
1722
|
+
op === ts.SyntaxKind.EqualsEqualsEqualsToken || op === ts.SyntaxKind.ExclamationEqualsEqualsToken;
|
|
1723
|
+
if (equality) {
|
|
1724
|
+
const pairs: Array<[ts.Expression, ts.Expression]> = [
|
|
1725
|
+
[node.left, node.right],
|
|
1726
|
+
[node.right, node.left],
|
|
1727
|
+
];
|
|
1728
|
+
for (const [chainSide, nullSide] of pairs) {
|
|
1729
|
+
const isNullish =
|
|
1730
|
+
nullSide.kind === ts.SyntaxKind.NullKeyword ||
|
|
1731
|
+
(ts.isIdentifier(nullSide) && nullSide.text === "undefined");
|
|
1732
|
+
let unwrapped = chainSide;
|
|
1733
|
+
while (ts.isParenthesizedExpression(unwrapped)) unwrapped = unwrapped.expression;
|
|
1734
|
+
if (isNullish && ts.isOptionalChain(unwrapped)) {
|
|
1735
|
+
this.report("NS1021", "A `?.` chain flows into a null test.", node);
|
|
1736
|
+
break;
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
// NS1028 — persist compiles and stays on the wire, but no shipping
|
|
1743
|
+
// host performs it yet; teach the writeFile path without stopping
|
|
1744
|
+
// the build.
|
|
1745
|
+
if (
|
|
1746
|
+
ts.isCallExpression(node) &&
|
|
1747
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
1748
|
+
node.expression.name.text === "persist" &&
|
|
1749
|
+
ts.isIdentifier(node.expression.expression) &&
|
|
1750
|
+
this.cmdNames.has(node.expression.expression.text) &&
|
|
1751
|
+
this.isSdkReference(node.expression.expression)
|
|
1752
|
+
) {
|
|
1753
|
+
this.warn("NS1028", "`Cmd.persist()` asks for a host service no shipping host provides yet.", node);
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
// NS1001/NS1022/NS1051 — mutation stays inside local ownership:
|
|
1757
|
+
// mutating array methods are legal on arrays this function created and
|
|
1758
|
+
// still owns; shared data (parameters, model/msg trees, module tables)
|
|
1759
|
+
// and escaped locals keep the teaching rules. Bytes keep their legacy
|
|
1760
|
+
// treatment (a Uint8Array writes through `.set`/indexed stores).
|
|
1761
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
|
|
1762
|
+
const method = node.expression.name.text;
|
|
1763
|
+
if (mutatingArrayMethods.has(method)) {
|
|
1764
|
+
const t = this.tast.typeToString(this.tast.typeOf(node.expression.expression));
|
|
1765
|
+
if (this.isArrayTypeString(t)) {
|
|
1766
|
+
if (!ownedMutatingMethods.has(method)) {
|
|
1767
|
+
// `copyWithin` stays out of v1 even on owned arrays.
|
|
1768
|
+
this.report("NS1001", `\`.${method}()\` is not part of v1 (splice/fill cover its uses).`, node);
|
|
1769
|
+
} else {
|
|
1770
|
+
this.checkArrayMutation(node.expression.expression, node, `\`.${method}()\``, method);
|
|
1771
|
+
}
|
|
1772
|
+
} else if (t.includes("Uint8Array")) {
|
|
1773
|
+
// Legacy bytes treatment: whole-buffer mutators stay taught
|
|
1774
|
+
// (bytes write through `.set` and indexed stores instead).
|
|
1775
|
+
if (method === "sort") {
|
|
1776
|
+
this.report("NS1022", `\`.sort()\` sorts the array in place.`, node);
|
|
1777
|
+
} else {
|
|
1778
|
+
this.report("NS1001", `\`.${method}()\` mutates an existing array.`, node);
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
// NS1023 — a boolean comparator is a JS bug the types can catch
|
|
1783
|
+
// (in-place `.sort` keeps exactly the `.toSorted` comparator rules).
|
|
1784
|
+
if (method === "toSorted" || method === "sort") {
|
|
1785
|
+
const cmp = node.arguments[0];
|
|
1786
|
+
if (cmp && ts.isArrowFunction(cmp) && this.tast.arrowReturnsBoolean(cmp)) {
|
|
1787
|
+
this.report("NS1023", `This \`.${method}\` comparator returns a boolean.`, cmp);
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
// The same ownership rule for indexed writes: `xs[i] = v`, the
|
|
1793
|
+
// compound forms, and `xs[i]++` mutate the array exactly like the
|
|
1794
|
+
// methods do (bytes stay on their own writable-until-escape rule).
|
|
1795
|
+
{
|
|
1796
|
+
let writeTarget: ts.Expression | null = null;
|
|
1797
|
+
let what = "";
|
|
1798
|
+
if (
|
|
1799
|
+
ts.isBinaryExpression(node) &&
|
|
1800
|
+
compoundAndPlainAssignmentOps.has(node.operatorToken.kind) &&
|
|
1801
|
+
ts.isElementAccessExpression(node.left)
|
|
1802
|
+
) {
|
|
1803
|
+
writeTarget = node.left.expression;
|
|
1804
|
+
what = "An indexed write";
|
|
1805
|
+
} else if (
|
|
1806
|
+
(ts.isPostfixUnaryExpression(node) || ts.isPrefixUnaryExpression(node)) &&
|
|
1807
|
+
(node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) &&
|
|
1808
|
+
ts.isElementAccessExpression(node.operand)
|
|
1809
|
+
) {
|
|
1810
|
+
writeTarget = node.operand.expression;
|
|
1811
|
+
what = "`++`/`--` on an element";
|
|
1812
|
+
}
|
|
1813
|
+
if (writeTarget !== null) {
|
|
1814
|
+
const t = this.tast.typeToString(this.tast.typeOf(writeTarget));
|
|
1815
|
+
if (this.isArrayTypeString(t)) {
|
|
1816
|
+
this.checkArrayMutation(writeTarget, node, what, null);
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
// Class-instance mutation follows the same local-ownership rule as
|
|
1822
|
+
// arrays: your own `new` instance mutates freely until it escapes;
|
|
1823
|
+
// `this` writes inside members are the class's own business (the
|
|
1824
|
+
// CALL of a mutating method is where ownership gates).
|
|
1825
|
+
{
|
|
1826
|
+
let fieldWrite: ts.PropertyAccessExpression | null = null;
|
|
1827
|
+
let what = "";
|
|
1828
|
+
if (
|
|
1829
|
+
ts.isBinaryExpression(node) &&
|
|
1830
|
+
compoundAndPlainAssignmentOps.has(node.operatorToken.kind) &&
|
|
1831
|
+
ts.isPropertyAccessExpression(node.left)
|
|
1832
|
+
) {
|
|
1833
|
+
fieldWrite = node.left;
|
|
1834
|
+
what = `A write to field \`.${node.left.name.text}\``;
|
|
1835
|
+
} else if (
|
|
1836
|
+
(ts.isPostfixUnaryExpression(node) || ts.isPrefixUnaryExpression(node)) &&
|
|
1837
|
+
(node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) &&
|
|
1838
|
+
ts.isPropertyAccessExpression(node.operand)
|
|
1839
|
+
) {
|
|
1840
|
+
fieldWrite = node.operand;
|
|
1841
|
+
what = `\`++\`/\`--\` on field \`.${node.operand.name.text}\``;
|
|
1842
|
+
}
|
|
1843
|
+
if (fieldWrite !== null && fieldWrite.expression.kind !== ts.SyntaxKind.ThisKeyword) {
|
|
1844
|
+
const propDecl = this.tast.declarationOf(fieldWrite.name);
|
|
1845
|
+
if (propDecl && ts.isPropertyDeclaration(propDecl)) {
|
|
1846
|
+
this.checkInstanceMutation(fieldWrite.expression, node, what);
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {
|
|
1850
|
+
const recv = node.expression.expression;
|
|
1851
|
+
const methodDecl = this.tast.declarationOf(node.expression.name);
|
|
1852
|
+
if (
|
|
1853
|
+
recv.kind !== ts.SyntaxKind.ThisKeyword &&
|
|
1854
|
+
methodDecl &&
|
|
1855
|
+
ts.isMethodDeclaration(methodDecl) &&
|
|
1856
|
+
ts.isClassDeclaration(methodDecl.parent) &&
|
|
1857
|
+
methodDecl.parent.name &&
|
|
1858
|
+
this.table.classes.get(methodDecl.parent.name.text)?.mutating.has(node.expression.name.text)
|
|
1859
|
+
) {
|
|
1860
|
+
this.checkInstanceMutation(recv, node, `\`.${node.expression.name.text}()\` (a method that writes \`this\`)`);
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
ts.forEachChild(node, visit);
|
|
1866
|
+
};
|
|
1867
|
+
visit(root);
|
|
1868
|
+
}
|
|
1869
|
+
}
|