@invinite-org/chartlang-compiler 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +246 -0
- package/dist/analysis/extractMaxLookback.d.ts +2 -1
- package/dist/analysis/extractMaxLookback.d.ts.map +1 -1
- package/dist/analysis/extractMaxLookback.js +90 -6
- package/dist/analysis/extractMaxLookback.js.map +1 -1
- package/dist/analysis/extractRequestedIntervals.d.ts +43 -1
- package/dist/analysis/extractRequestedIntervals.d.ts.map +1 -1
- package/dist/analysis/extractRequestedIntervals.js +95 -10
- package/dist/analysis/extractRequestedIntervals.js.map +1 -1
- package/dist/analysis/forbiddenConstructs.d.ts.map +1 -1
- package/dist/analysis/forbiddenConstructs.js +2 -41
- package/dist/analysis/forbiddenConstructs.js.map +1 -1
- package/dist/analysis/index.d.ts +3 -1
- package/dist/analysis/index.d.ts.map +1 -1
- package/dist/analysis/index.js +2 -1
- package/dist/analysis/index.js.map +1 -1
- package/dist/analysis/loopBounds.d.ts +91 -0
- package/dist/analysis/loopBounds.d.ts.map +1 -0
- package/dist/analysis/loopBounds.js +132 -0
- package/dist/analysis/loopBounds.js.map +1 -0
- package/dist/analysis/resolveIndexBound.d.ts +73 -0
- package/dist/analysis/resolveIndexBound.d.ts.map +1 -0
- package/dist/analysis/resolveIndexBound.js +336 -0
- package/dist/analysis/resolveIndexBound.js.map +1 -0
- package/dist/analysis/validateSecurityExpr.d.ts +25 -0
- package/dist/analysis/validateSecurityExpr.d.ts.map +1 -0
- package/dist/analysis/validateSecurityExpr.js +154 -0
- package/dist/analysis/validateSecurityExpr.js.map +1 -0
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +13 -3
- package/dist/api.js.map +1 -1
- package/dist/diagnostics.d.ts +4 -2
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/diagnostics.js.map +1 -1
- package/dist/manifest.d.ts +2 -1
- package/dist/manifest.d.ts.map +1 -1
- package/dist/manifest.js +7 -0
- package/dist/manifest.js.map +1 -1
- package/dist/program.d.ts.map +1 -1
- package/dist/program.js +91 -14
- package/dist/program.js.map +1 -1
- package/dist/transformers/callsiteIdInjection.d.ts +21 -0
- package/dist/transformers/callsiteIdInjection.d.ts.map +1 -1
- package/dist/transformers/callsiteIdInjection.js +26 -3
- package/dist/transformers/callsiteIdInjection.js.map +1 -1
- package/dist/transformers/resolveCallee.d.ts +21 -0
- package/dist/transformers/resolveCallee.d.ts.map +1 -1
- package/dist/transformers/resolveCallee.js +14 -1
- package/dist/transformers/resolveCallee.js.map +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
/**
|
|
3
|
+
* Compile-time context for resolving a series index's upper bound.
|
|
4
|
+
*
|
|
5
|
+
* @since 0.1
|
|
6
|
+
* @stable
|
|
7
|
+
* @example
|
|
8
|
+
* const ctx: IndexBoundContext = {
|
|
9
|
+
* constEnv: new Map([["k", 3]]),
|
|
10
|
+
* checker, // ts.TypeChecker
|
|
11
|
+
* };
|
|
12
|
+
* void ctx;
|
|
13
|
+
*/
|
|
14
|
+
export type IndexBoundContext = Readonly<{
|
|
15
|
+
/** `const <id> = <numeric literal>` bindings visible at the index use site. */
|
|
16
|
+
constEnv: ReadonlyMap<string, number>;
|
|
17
|
+
/** Checker used to avoid resolving loop variables through a shadowed name. */
|
|
18
|
+
checker: ts.TypeChecker;
|
|
19
|
+
}>;
|
|
20
|
+
/**
|
|
21
|
+
* The provable maximum non-negative integer a series-index expression
|
|
22
|
+
* can reach at runtime, or `null` when no sound upper bound exists.
|
|
23
|
+
* Over-approximates: a result is always `>=` the true max index, so the
|
|
24
|
+
* runtime buffer (sized `maxLookback + 1`) never under-sizes. `null`
|
|
25
|
+
* signals the caller to fall back to the 5000-slot dynamic buffer.
|
|
26
|
+
*
|
|
27
|
+
* Resolves any expression built from numeric literals, `const`
|
|
28
|
+
* numeric-literal bindings (`ctx.constEnv`), bounded-loop induction
|
|
29
|
+
* variables (resolved to their full range), the binary operators `+`,
|
|
30
|
+
* `−`, `*`, unary `±`, and parentheses, by computing its integer
|
|
31
|
+
* interval and returning the **upper** endpoint. Any other node (another
|
|
32
|
+
* identifier, a call, `/`, `%`, `**`, a bitwise op, a non-numeric
|
|
33
|
+
* literal) collapses the containing interval — and thus the whole
|
|
34
|
+
* index — to `null`.
|
|
35
|
+
*
|
|
36
|
+
* @since 0.1
|
|
37
|
+
* @stable
|
|
38
|
+
* @example
|
|
39
|
+
* // for (let i = 0; i < 5; i++) { series[i + 1]; }
|
|
40
|
+
* // resolveIndexUpperBound(<the `i + 1` arg>, <access node>, ctx) → 5
|
|
41
|
+
* const fn: typeof resolveIndexUpperBound = resolveIndexUpperBound;
|
|
42
|
+
* void fn;
|
|
43
|
+
*/
|
|
44
|
+
export declare function resolveIndexUpperBound(argument: ts.Expression, node: ts.Node, ctx: IndexBoundContext): number | null;
|
|
45
|
+
/**
|
|
46
|
+
* The `const <id> = <numeric literal>` bindings lexically visible at a
|
|
47
|
+
* specific series-index expression. Only `const` initialised with a
|
|
48
|
+
* numeric literal — or a unary `+`/`-` on one — is included (mirroring
|
|
49
|
+
* `extractInputs.readLiteral`'s numeric handling); a binary initialiser
|
|
50
|
+
* is left for Task 2's interval evaluator and is simply omitted. The walk
|
|
51
|
+
* runs from `useSite` outward through its lexical containers up to
|
|
52
|
+
* `scopeRoot`, collecting only declarations that occur before
|
|
53
|
+
* `useSite.pos` within each container, so it never sees a declaration
|
|
54
|
+
* after the read, inside a sibling block, or in a nested function/class
|
|
55
|
+
* that does not contain `useSite`. The innermost visible binding for a
|
|
56
|
+
* name wins (normal shadowing) — including binders that are not
|
|
57
|
+
* `var`/`let`/`const` statements: a `for`-init induction variable and a
|
|
58
|
+
* function parameter shadow an outer numeric `const` of the same name
|
|
59
|
+
* (`markContainerBinders`), so a reassigned `for (let i …)` index or a
|
|
60
|
+
* `request.security((k) => series[k])` callback parameter can never leak
|
|
61
|
+
* an unrelated outer `const k`'s value into the bound (which would
|
|
62
|
+
* under-size the buffer).
|
|
63
|
+
*
|
|
64
|
+
* @since 0.1
|
|
65
|
+
* @stable
|
|
66
|
+
* @example
|
|
67
|
+
* // const k = 3; series[k];
|
|
68
|
+
* // collectConstNumberEnv(<the `k` arg>, scope).get("k") → 3
|
|
69
|
+
* const fn: typeof collectConstNumberEnv = collectConstNumberEnv;
|
|
70
|
+
* void fn;
|
|
71
|
+
*/
|
|
72
|
+
export declare function collectConstNumberEnv(useSite: ts.Node, scopeRoot: ts.Node): ReadonlyMap<string, number>;
|
|
73
|
+
//# sourceMappingURL=resolveIndexBound.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolveIndexBound.d.ts","sourceRoot":"","sources":["../../src/analysis/resolveIndexBound.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,YAAY,CAAC;AAS5B;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC;IACrC,+EAA+E;IAC/E,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,8EAA8E;IAC9E,OAAO,EAAE,EAAE,CAAC,WAAW,CAAC;CAC3B,CAAC,CAAC;AAUH;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,sBAAsB,CAClC,QAAQ,EAAE,EAAE,CAAC,UAAU,EACvB,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,GAAG,EAAE,iBAAiB,GACvB,MAAM,GAAG,IAAI,CAGf;AAqLD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,qBAAqB,CACjC,OAAO,EAAE,EAAE,CAAC,IAAI,EAChB,SAAS,EAAE,EAAE,CAAC,IAAI,GACnB,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CA+B7B"}
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
// Copyright (c) 2026 Invinite. Licensed under the MIT License.
|
|
2
|
+
// See the LICENSE file in the repo root for full license text.
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import { boundedLoopVarId, parseBoundedForLoop, unwrapParens, } from "./loopBounds.js";
|
|
5
|
+
/**
|
|
6
|
+
* The provable maximum non-negative integer a series-index expression
|
|
7
|
+
* can reach at runtime, or `null` when no sound upper bound exists.
|
|
8
|
+
* Over-approximates: a result is always `>=` the true max index, so the
|
|
9
|
+
* runtime buffer (sized `maxLookback + 1`) never under-sizes. `null`
|
|
10
|
+
* signals the caller to fall back to the 5000-slot dynamic buffer.
|
|
11
|
+
*
|
|
12
|
+
* Resolves any expression built from numeric literals, `const`
|
|
13
|
+
* numeric-literal bindings (`ctx.constEnv`), bounded-loop induction
|
|
14
|
+
* variables (resolved to their full range), the binary operators `+`,
|
|
15
|
+
* `−`, `*`, unary `±`, and parentheses, by computing its integer
|
|
16
|
+
* interval and returning the **upper** endpoint. Any other node (another
|
|
17
|
+
* identifier, a call, `/`, `%`, `**`, a bitwise op, a non-numeric
|
|
18
|
+
* literal) collapses the containing interval — and thus the whole
|
|
19
|
+
* index — to `null`.
|
|
20
|
+
*
|
|
21
|
+
* @since 0.1
|
|
22
|
+
* @stable
|
|
23
|
+
* @example
|
|
24
|
+
* // for (let i = 0; i < 5; i++) { series[i + 1]; }
|
|
25
|
+
* // resolveIndexUpperBound(<the `i + 1` arg>, <access node>, ctx) → 5
|
|
26
|
+
* const fn: typeof resolveIndexUpperBound = resolveIndexUpperBound;
|
|
27
|
+
* void fn;
|
|
28
|
+
*/
|
|
29
|
+
export function resolveIndexUpperBound(argument, node, ctx) {
|
|
30
|
+
const interval = evalInterval(argument, node, ctx);
|
|
31
|
+
return interval === null ? null : interval.hi;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The integer interval an index sub-expression spans, or `null` when any
|
|
35
|
+
* leaf or operator cannot be soundly bounded. The single evaluator that
|
|
36
|
+
* subsumes the leaf cases (literal / bounded-loop var / `const` number)
|
|
37
|
+
* and their affine combinations (`+`, `−`, `*`, unary `±`, parens).
|
|
38
|
+
*/
|
|
39
|
+
function evalInterval(expr, node, ctx) {
|
|
40
|
+
const inner = unwrapParens(expr);
|
|
41
|
+
if (ts.isNumericLiteral(inner)) {
|
|
42
|
+
const value = Number(inner.text);
|
|
43
|
+
return finiteInterval(value, value);
|
|
44
|
+
}
|
|
45
|
+
if (ts.isIdentifier(inner)) {
|
|
46
|
+
const loopInterval = resolveLoopVarInterval(inner, node, ctx.checker);
|
|
47
|
+
if (loopInterval !== null)
|
|
48
|
+
return loopInterval;
|
|
49
|
+
const constValue = ctx.constEnv.get(inner.text);
|
|
50
|
+
return constValue === undefined ? null : finiteInterval(constValue, constValue);
|
|
51
|
+
}
|
|
52
|
+
if (ts.isPrefixUnaryExpression(inner)) {
|
|
53
|
+
if (inner.operator === ts.SyntaxKind.PlusToken) {
|
|
54
|
+
return evalInterval(inner.operand, node, ctx);
|
|
55
|
+
}
|
|
56
|
+
if (inner.operator === ts.SyntaxKind.MinusToken) {
|
|
57
|
+
const operand = evalInterval(inner.operand, node, ctx);
|
|
58
|
+
return operand === null ? null : finiteInterval(-operand.hi, -operand.lo);
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
if (ts.isBinaryExpression(inner)) {
|
|
63
|
+
return evalBinaryInterval(inner, node, ctx);
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The interval of a `+`/`−`/`*` over two sub-intervals, or `null` when
|
|
69
|
+
* either operand is unbounded or the operator is unsupported (`/`, `%`,
|
|
70
|
+
* `**`, bitwise, …). Multiplication takes the min/max of the four
|
|
71
|
+
* endpoint products so the bound is correct for any sign combination.
|
|
72
|
+
*/
|
|
73
|
+
function evalBinaryInterval(expr, node, ctx) {
|
|
74
|
+
const left = evalInterval(expr.left, node, ctx);
|
|
75
|
+
if (left === null)
|
|
76
|
+
return null;
|
|
77
|
+
const right = evalInterval(expr.right, node, ctx);
|
|
78
|
+
if (right === null)
|
|
79
|
+
return null;
|
|
80
|
+
switch (expr.operatorToken.kind) {
|
|
81
|
+
case ts.SyntaxKind.PlusToken:
|
|
82
|
+
return finiteInterval(left.lo + right.lo, left.hi + right.hi);
|
|
83
|
+
case ts.SyntaxKind.MinusToken:
|
|
84
|
+
return finiteInterval(left.lo - right.hi, left.hi - right.lo);
|
|
85
|
+
case ts.SyntaxKind.AsteriskToken: {
|
|
86
|
+
const products = [
|
|
87
|
+
left.lo * right.lo,
|
|
88
|
+
left.lo * right.hi,
|
|
89
|
+
left.hi * right.lo,
|
|
90
|
+
left.hi * right.hi,
|
|
91
|
+
];
|
|
92
|
+
return finiteInterval(Math.min(...products), Math.max(...products));
|
|
93
|
+
}
|
|
94
|
+
default:
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* An interval with finite endpoints, or `null` when either endpoint is
|
|
100
|
+
* non-finite. A defensive guard against a pathological literal
|
|
101
|
+
* (`1e400` → `Infinity`) or an overflow product feeding a non-finite
|
|
102
|
+
* `hi` into `maxLookback`; integer-ness needs no check (see `Interval`).
|
|
103
|
+
*/
|
|
104
|
+
function finiteInterval(lo, hi) {
|
|
105
|
+
if (!Number.isFinite(lo) || !Number.isFinite(hi))
|
|
106
|
+
return null;
|
|
107
|
+
// Normalise `-0` (e.g. `-2 * 0`) to `0` so a resolved bound is never the
|
|
108
|
+
// negative zero a downstream `Object.is`/strict consumer would distinguish.
|
|
109
|
+
return { lo: lo + 0, hi: hi + 0 };
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The index range a bare bounded-loop induction variable can span, or
|
|
113
|
+
* `null` when the identifier is not the induction variable of an
|
|
114
|
+
* enclosing legal `for`, is reassigned in the body, runs a
|
|
115
|
+
* non-terminating `>`/`>=` loop, or is a shadowed name that does not
|
|
116
|
+
* resolve to the loop's own declaration. Affine forms need the full
|
|
117
|
+
* range (`K - i` is largest when `i` is smallest); a bare loop-var read
|
|
118
|
+
* still takes `interval.hi`, identical to the leaf max.
|
|
119
|
+
*/
|
|
120
|
+
function resolveLoopVarInterval(id, node, checker) {
|
|
121
|
+
const idSymbol = checker.getSymbolAtLocation(id);
|
|
122
|
+
let current = node;
|
|
123
|
+
while (current) {
|
|
124
|
+
if (ts.isForStatement(current)) {
|
|
125
|
+
const loopVarId = boundedLoopVarId(current);
|
|
126
|
+
if (loopVarId && loopVarId.text === id.text) {
|
|
127
|
+
// Confirm the use refers to THIS loop's induction variable
|
|
128
|
+
// and not a nested binding that shadows the same text.
|
|
129
|
+
const loopSymbol = checker.getSymbolAtLocation(loopVarId);
|
|
130
|
+
if (!idSymbol || !loopSymbol || idSymbol !== loopSymbol)
|
|
131
|
+
return null;
|
|
132
|
+
const loop = parseBoundedForLoop(current);
|
|
133
|
+
if (loop === null)
|
|
134
|
+
return null;
|
|
135
|
+
if (isLoopVarReassigned(current, loop.varName))
|
|
136
|
+
return null;
|
|
137
|
+
return loopVarInterval(loop);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
current = current.parent;
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* The full index range a terminating `for` reaches (`[start, max]`), or
|
|
146
|
+
* `null` for a non-terminating (`>`/`>=` with `i++`) header the resolver
|
|
147
|
+
* cannot bound. `<` reaches `limit - 1`; `<=` reaches `limit`.
|
|
148
|
+
*/
|
|
149
|
+
function loopVarInterval(loop) {
|
|
150
|
+
if (loop.op === ts.SyntaxKind.LessThanToken) {
|
|
151
|
+
return finiteInterval(loop.start, loop.limit - 1);
|
|
152
|
+
}
|
|
153
|
+
if (loop.op === ts.SyntaxKind.LessThanEqualsToken) {
|
|
154
|
+
return finiteInterval(loop.start, loop.limit);
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Whether the loop body reassigns `varName` beyond the header `i++`
|
|
160
|
+
* incrementor (a plain `=`, a compound assignment, or an extra `++`/`--`
|
|
161
|
+
* whose target is the induction variable). Such a body breaks the
|
|
162
|
+
* `limit`-based bound, so the resolver refuses to size the read.
|
|
163
|
+
*/
|
|
164
|
+
function isLoopVarReassigned(loop, varName) {
|
|
165
|
+
const body = loop.statement;
|
|
166
|
+
let reassigned = false;
|
|
167
|
+
const visit = (node) => {
|
|
168
|
+
if (reassigned)
|
|
169
|
+
return;
|
|
170
|
+
if (ts.isBinaryExpression(node) &&
|
|
171
|
+
isAssignmentOperator(node.operatorToken.kind) &&
|
|
172
|
+
ts.isIdentifier(node.left) &&
|
|
173
|
+
node.left.text === varName) {
|
|
174
|
+
reassigned = true;
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if ((ts.isPostfixUnaryExpression(node) || ts.isPrefixUnaryExpression(node)) &&
|
|
178
|
+
(node.operator === ts.SyntaxKind.PlusPlusToken ||
|
|
179
|
+
node.operator === ts.SyntaxKind.MinusMinusToken) &&
|
|
180
|
+
ts.isIdentifier(node.operand) &&
|
|
181
|
+
node.operand.text === varName) {
|
|
182
|
+
reassigned = true;
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
ts.forEachChild(node, visit);
|
|
186
|
+
};
|
|
187
|
+
visit(body);
|
|
188
|
+
return reassigned;
|
|
189
|
+
}
|
|
190
|
+
/** Whether a binary operator token writes to its left operand. */
|
|
191
|
+
function isAssignmentOperator(kind) {
|
|
192
|
+
return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The `const <id> = <numeric literal>` bindings lexically visible at a
|
|
196
|
+
* specific series-index expression. Only `const` initialised with a
|
|
197
|
+
* numeric literal — or a unary `+`/`-` on one — is included (mirroring
|
|
198
|
+
* `extractInputs.readLiteral`'s numeric handling); a binary initialiser
|
|
199
|
+
* is left for Task 2's interval evaluator and is simply omitted. The walk
|
|
200
|
+
* runs from `useSite` outward through its lexical containers up to
|
|
201
|
+
* `scopeRoot`, collecting only declarations that occur before
|
|
202
|
+
* `useSite.pos` within each container, so it never sees a declaration
|
|
203
|
+
* after the read, inside a sibling block, or in a nested function/class
|
|
204
|
+
* that does not contain `useSite`. The innermost visible binding for a
|
|
205
|
+
* name wins (normal shadowing) — including binders that are not
|
|
206
|
+
* `var`/`let`/`const` statements: a `for`-init induction variable and a
|
|
207
|
+
* function parameter shadow an outer numeric `const` of the same name
|
|
208
|
+
* (`markContainerBinders`), so a reassigned `for (let i …)` index or a
|
|
209
|
+
* `request.security((k) => series[k])` callback parameter can never leak
|
|
210
|
+
* an unrelated outer `const k`'s value into the bound (which would
|
|
211
|
+
* under-size the buffer).
|
|
212
|
+
*
|
|
213
|
+
* @since 0.1
|
|
214
|
+
* @stable
|
|
215
|
+
* @example
|
|
216
|
+
* // const k = 3; series[k];
|
|
217
|
+
* // collectConstNumberEnv(<the `k` arg>, scope).get("k") → 3
|
|
218
|
+
* const fn: typeof collectConstNumberEnv = collectConstNumberEnv;
|
|
219
|
+
* void fn;
|
|
220
|
+
*/
|
|
221
|
+
export function collectConstNumberEnv(useSite, scopeRoot) {
|
|
222
|
+
const env = new Map();
|
|
223
|
+
// Every `var`/`let`/`const` name bound at or inside a nearer container,
|
|
224
|
+
// numeric or not. A nearer binding shadows an outer one even when it is
|
|
225
|
+
// a `let` or a non-numeric `const`, so an outer `const k = 5` must not
|
|
226
|
+
// leak through it — once a name is `seen`, no outer container can set it.
|
|
227
|
+
const seen = new Set();
|
|
228
|
+
let container = useSite.parent;
|
|
229
|
+
while (container) {
|
|
230
|
+
// A `for`-init variable / function parameter introduced by this
|
|
231
|
+
// container shadows any same-named outer `const`, even though it is
|
|
232
|
+
// not a `var`/`let`/`const` statement `variableDeclarationsIn` scans.
|
|
233
|
+
markContainerBinders(container, seen);
|
|
234
|
+
for (const declaration of variableDeclarationsIn(container)) {
|
|
235
|
+
if (declaration.pos >= useSite.pos)
|
|
236
|
+
continue;
|
|
237
|
+
if (!ts.isIdentifier(declaration.name))
|
|
238
|
+
continue;
|
|
239
|
+
const name = declaration.name.text;
|
|
240
|
+
if (seen.has(name))
|
|
241
|
+
continue;
|
|
242
|
+
seen.add(name);
|
|
243
|
+
const list = declaration.parent;
|
|
244
|
+
if (ts.isVariableDeclarationList(list) && (list.flags & ts.NodeFlags.Const) !== 0) {
|
|
245
|
+
const value = readNumericLiteralInit(declaration);
|
|
246
|
+
if (value !== null)
|
|
247
|
+
env.set(name, value);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
if (container === scopeRoot)
|
|
251
|
+
break;
|
|
252
|
+
container = container.parent;
|
|
253
|
+
}
|
|
254
|
+
return env;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Mark every binding name a container introduces at its OWN level — a
|
|
258
|
+
* `for` initializer's induction variable and a function-like's parameters
|
|
259
|
+
* — as `seen`, so an outer numeric `const` of the same name cannot leak
|
|
260
|
+
* past it. These binders are never numeric `const`s the resolver trusts,
|
|
261
|
+
* so marking them only blocks unsound shadow leaks: a reassigned
|
|
262
|
+
* `for (let i …)` index or a callback parameter (`(k) => series[k]`) that
|
|
263
|
+
* collides with an outer `const i`/`const k`. Only identifier binders
|
|
264
|
+
* matter here (a numeric series index is an identifier); destructured
|
|
265
|
+
* parameter/loop patterns bind no numeric index and are skipped.
|
|
266
|
+
*/
|
|
267
|
+
function markContainerBinders(container, seen) {
|
|
268
|
+
if (ts.isForStatement(container)) {
|
|
269
|
+
const init = container.initializer;
|
|
270
|
+
if (init && ts.isVariableDeclarationList(init)) {
|
|
271
|
+
for (const declaration of init.declarations) {
|
|
272
|
+
if (ts.isIdentifier(declaration.name))
|
|
273
|
+
seen.add(declaration.name.text);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (ts.isFunctionLike(container)) {
|
|
279
|
+
for (const parameter of container.parameters) {
|
|
280
|
+
if (ts.isIdentifier(parameter.name))
|
|
281
|
+
seen.add(parameter.name.text);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* The direct `var`/`let`/`const` `VariableDeclaration`s of a container —
|
|
287
|
+
* of every declaration kind, so the caller can detect a nearer binding
|
|
288
|
+
* that shadows an outer numeric `const` — without descending into nested
|
|
289
|
+
* functions, classes, or blocks (those are handled by their own
|
|
290
|
+
* enclosing-container pass when they actually contain the use site).
|
|
291
|
+
* `Block`, `SourceFile`, function bodies, and case clauses hold their
|
|
292
|
+
* declarations as `statements`/`clauses` we scan directly.
|
|
293
|
+
*/
|
|
294
|
+
function variableDeclarationsIn(container) {
|
|
295
|
+
const declarations = [];
|
|
296
|
+
const statements = statementsOf(container);
|
|
297
|
+
for (const statement of statements) {
|
|
298
|
+
if (!ts.isVariableStatement(statement))
|
|
299
|
+
continue;
|
|
300
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
301
|
+
declarations.push(declaration);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return declarations;
|
|
305
|
+
}
|
|
306
|
+
/** The lexical statement list a container exposes, or `[]` when it holds none. */
|
|
307
|
+
function statementsOf(container) {
|
|
308
|
+
if (ts.isSourceFile(container) || ts.isBlock(container) || ts.isModuleBlock(container)) {
|
|
309
|
+
return container.statements;
|
|
310
|
+
}
|
|
311
|
+
if (ts.isCaseClause(container) || ts.isDefaultClause(container)) {
|
|
312
|
+
return container.statements;
|
|
313
|
+
}
|
|
314
|
+
return [];
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* The numeric value of a `const k = <numeric literal>` /
|
|
318
|
+
* `const k = <unary ± numeric literal>` initialiser, or `null` for any
|
|
319
|
+
* other initialiser (no binary folding here — that is Task 2).
|
|
320
|
+
*/
|
|
321
|
+
function readNumericLiteralInit(declaration) {
|
|
322
|
+
const initializer = declaration.initializer;
|
|
323
|
+
if (!initializer)
|
|
324
|
+
return null;
|
|
325
|
+
const expr = unwrapParens(initializer);
|
|
326
|
+
if (ts.isNumericLiteral(expr))
|
|
327
|
+
return Number(expr.text);
|
|
328
|
+
if (ts.isPrefixUnaryExpression(expr) &&
|
|
329
|
+
(expr.operator === ts.SyntaxKind.MinusToken || expr.operator === ts.SyntaxKind.PlusToken) &&
|
|
330
|
+
ts.isNumericLiteral(expr.operand)) {
|
|
331
|
+
const value = Number(expr.operand.text);
|
|
332
|
+
return expr.operator === ts.SyntaxKind.MinusToken ? -value : value;
|
|
333
|
+
}
|
|
334
|
+
return null;
|
|
335
|
+
}
|
|
336
|
+
//# sourceMappingURL=resolveIndexBound.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolveIndexBound.js","sourceRoot":"","sources":["../../src/analysis/resolveIndexBound.ts"],"names":[],"mappings":"AAAA,+DAA+D;AAC/D,+DAA+D;AAE/D,OAAO,EAAE,MAAM,YAAY,CAAC;AAE5B,OAAO,EAEH,gBAAgB,EAChB,mBAAmB,EACnB,YAAY,GACf,MAAM,iBAAiB,CAAC;AA6BzB;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,sBAAsB,CAClC,QAAuB,EACvB,IAAa,EACb,GAAsB;IAEtB,MAAM,QAAQ,GAAG,YAAY,CAAC,QAAQ,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;IACnD,OAAO,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;AAClD,CAAC;AAED;;;;;GAKG;AACH,SAAS,YAAY,CAAC,IAAmB,EAAE,IAAa,EAAE,GAAsB;IAC5E,MAAM,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;IAEjC,IAAI,EAAE,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC7B,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAA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W,CAAC,CAAC;IACvC,IAAI,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxD,IACI,EAAE,CAAC,uBAAuB,CAAC,IAAI,CAAC;QAChC,CAAC,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,UAAU,CAAC,UAAU,IAAI,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC;QACzF,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EACnC,CAAC;QACC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACxC,OAAO,IAAI,CAAC,QAAQ,KAAK,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC;IACvE,CAAC;IACD,OAAO,IAAI,CAAC;AAChB,CAAC","sourcesContent":["// Copyright (c) 2026 Invinite. Licensed under the MIT License.\n// See the LICENSE file in the repo root for full license text.\n\nimport ts from \"typescript\";\n\nimport {\n type BoundedForLoop,\n boundedLoopVarId,\n parseBoundedForLoop,\n unwrapParens,\n} from \"./loopBounds.js\";\n\n/**\n * Compile-time context for resolving a series index's upper bound.\n *\n * @since 0.1\n * @stable\n * @example\n * const ctx: IndexBoundContext = {\n * constEnv: new Map([[\"k\", 3]]),\n * checker, // ts.TypeChecker\n * };\n * void ctx;\n */\nexport type IndexBoundContext = Readonly<{\n /** `const <id> = <numeric literal>` bindings visible at the index use site. */\n constEnv: ReadonlyMap<string, number>;\n /** Checker used to avoid resolving loop variables through a shadowed name. */\n checker: ts.TypeChecker;\n}>;\n\n/**\n * The compile-time integer range an index sub-expression can span. Every\n * input is an integer and `+`/`−`/`*`/unary-`±` preserve integers, so the\n * endpoints are exact integers — no rounding and no `Number.isInteger`\n * guard is needed.\n */\ntype Interval = Readonly<{ lo: number; hi: number }>;\n\n/**\n * The provable maximum non-negative integer a series-index expression\n * can reach at runtime, or `null` when no sound upper bound exists.\n * Over-approximates: a result is always `>=` the true max index, so the\n * runtime buffer (sized `maxLookback + 1`) never under-sizes. `null`\n * signals the caller to fall back to the 5000-slot dynamic buffer.\n *\n * Resolves any expression built from numeric literals, `const`\n * numeric-literal bindings (`ctx.constEnv`), bounded-loop induction\n * variables (resolved to their full range), the binary operators `+`,\n * `−`, `*`, unary `±`, and parentheses, by computing its integer\n * interval and returning the **upper** endpoint. Any other node (another\n * identifier, a call, `/`, `%`, `**`, a bitwise op, a non-numeric\n * literal) collapses the containing interval — and thus the whole\n * index — to `null`.\n *\n * @since 0.1\n * @stable\n * @example\n * // for (let i = 0; i < 5; i++) { series[i + 1]; }\n * // resolveIndexUpperBound(<the `i + 1` arg>, <access node>, ctx) → 5\n * const fn: typeof resolveIndexUpperBound = resolveIndexUpperBound;\n * void fn;\n */\nexport function resolveIndexUpperBound(\n argument: ts.Expression,\n node: ts.Node,\n ctx: IndexBoundContext,\n): number | null {\n const interval = evalInterval(argument, node, ctx);\n return interval === null ? null : interval.hi;\n}\n\n/**\n * The integer interval an index sub-expression spans, or `null` when any\n * leaf or operator cannot be soundly bounded. The single evaluator that\n * subsumes the leaf cases (literal / bounded-loop var / `const` number)\n * and their affine combinations (`+`, `−`, `*`, unary `±`, parens).\n */\nfunction evalInterval(expr: ts.Expression, node: ts.Node, ctx: IndexBoundContext): Interval | null {\n const inner = unwrapParens(expr);\n\n if (ts.isNumericLiteral(inner)) {\n const value = Number(inner.text);\n return finiteInterval(value, value);\n }\n\n if (ts.isIdentifier(inner)) {\n const loopInterval = resolveLoopVarInterval(inner, node, ctx.checker);\n if (loopInterval !== null) return loopInterval;\n const constValue = ctx.constEnv.get(inner.text);\n return constValue === undefined ? null : finiteInterval(constValue, constValue);\n }\n\n if (ts.isPrefixUnaryExpression(inner)) {\n if (inner.operator === ts.SyntaxKind.PlusToken) {\n return evalInterval(inner.operand, node, ctx);\n }\n if (inner.operator === ts.SyntaxKind.MinusToken) {\n const operand = evalInterval(inner.operand, node, ctx);\n return operand === null ? null : finiteInterval(-operand.hi, -operand.lo);\n }\n return null;\n }\n\n if (ts.isBinaryExpression(inner)) {\n return evalBinaryInterval(inner, node, ctx);\n }\n\n return null;\n}\n\n/**\n * The interval of a `+`/`−`/`*` over two sub-intervals, or `null` when\n * either operand is unbounded or the operator is unsupported (`/`, `%`,\n * `**`, bitwise, …). Multiplication takes the min/max of the four\n * endpoint products so the bound is correct for any sign combination.\n */\nfunction evalBinaryInterval(\n expr: ts.BinaryExpression,\n node: ts.Node,\n ctx: IndexBoundContext,\n): Interval | null {\n const left = evalInterval(expr.left, node, ctx);\n if (left === null) return null;\n const right = evalInterval(expr.right, node, ctx);\n if (right === null) return null;\n\n switch (expr.operatorToken.kind) {\n case ts.SyntaxKind.PlusToken:\n return finiteInterval(left.lo + right.lo, left.hi + right.hi);\n case ts.SyntaxKind.MinusToken:\n return finiteInterval(left.lo - right.hi, left.hi - right.lo);\n case ts.SyntaxKind.AsteriskToken: {\n const products = [\n left.lo * right.lo,\n left.lo * right.hi,\n left.hi * right.lo,\n left.hi * right.hi,\n ];\n return finiteInterval(Math.min(...products), Math.max(...products));\n }\n default:\n return null;\n }\n}\n\n/**\n * An interval with finite endpoints, or `null` when either endpoint is\n * non-finite. A defensive guard against a pathological literal\n * (`1e400` → `Infinity`) or an overflow product feeding a non-finite\n * `hi` into `maxLookback`; integer-ness needs no check (see `Interval`).\n */\nfunction finiteInterval(lo: number, hi: number): Interval | null {\n if (!Number.isFinite(lo) || !Number.isFinite(hi)) return null;\n // Normalise `-0` (e.g. `-2 * 0`) to `0` so a resolved bound is never the\n // negative zero a downstream `Object.is`/strict consumer would distinguish.\n return { lo: lo + 0, hi: hi + 0 };\n}\n\n/**\n * The index range a bare bounded-loop induction variable can span, or\n * `null` when the identifier is not the induction variable of an\n * enclosing legal `for`, is reassigned in the body, runs a\n * non-terminating `>`/`>=` loop, or is a shadowed name that does not\n * resolve to the loop's own declaration. Affine forms need the full\n * range (`K - i` is largest when `i` is smallest); a bare loop-var read\n * still takes `interval.hi`, identical to the leaf max.\n */\nfunction resolveLoopVarInterval(\n id: ts.Identifier,\n node: ts.Node,\n checker: ts.TypeChecker,\n): Interval | null {\n const idSymbol = checker.getSymbolAtLocation(id);\n\n let current: ts.Node | undefined = node;\n while (current) {\n if (ts.isForStatement(current)) {\n const loopVarId = boundedLoopVarId(current);\n if (loopVarId && loopVarId.text === id.text) {\n // Confirm the use refers to THIS loop's induction variable\n // and not a nested binding that shadows the same text.\n const loopSymbol = checker.getSymbolAtLocation(loopVarId);\n if (!idSymbol || !loopSymbol || idSymbol !== loopSymbol) return null;\n const loop = parseBoundedForLoop(current);\n if (loop === null) return null;\n if (isLoopVarReassigned(current, loop.varName)) return null;\n return loopVarInterval(loop);\n }\n }\n current = current.parent;\n }\n return null;\n}\n\n/**\n * The full index range a terminating `for` reaches (`[start, max]`), or\n * `null` for a non-terminating (`>`/`>=` with `i++`) header the resolver\n * cannot bound. `<` reaches `limit - 1`; `<=` reaches `limit`.\n */\nfunction loopVarInterval(loop: BoundedForLoop): Interval | null {\n if (loop.op === ts.SyntaxKind.LessThanToken) {\n return finiteInterval(loop.start, loop.limit - 1);\n }\n if (loop.op === ts.SyntaxKind.LessThanEqualsToken) {\n return finiteInterval(loop.start, loop.limit);\n }\n return null;\n}\n\n/**\n * Whether the loop body reassigns `varName` beyond the header `i++`\n * incrementor (a plain `=`, a compound assignment, or an extra `++`/`--`\n * whose target is the induction variable). Such a body breaks the\n * `limit`-based bound, so the resolver refuses to size the read.\n */\nfunction isLoopVarReassigned(loop: ts.ForStatement, varName: string): boolean {\n const body = loop.statement;\n let reassigned = false;\n const visit = (node: ts.Node): void => {\n if (reassigned) return;\n if (\n ts.isBinaryExpression(node) &&\n isAssignmentOperator(node.operatorToken.kind) &&\n ts.isIdentifier(node.left) &&\n node.left.text === varName\n ) {\n reassigned = true;\n return;\n }\n if (\n (ts.isPostfixUnaryExpression(node) || ts.isPrefixUnaryExpression(node)) &&\n (node.operator === ts.SyntaxKind.PlusPlusToken ||\n node.operator === ts.SyntaxKind.MinusMinusToken) &&\n ts.isIdentifier(node.operand) &&\n node.operand.text === varName\n ) {\n reassigned = true;\n return;\n }\n ts.forEachChild(node, visit);\n };\n visit(body);\n return reassigned;\n}\n\n/** Whether a binary operator token writes to its left operand. */\nfunction isAssignmentOperator(kind: ts.SyntaxKind): boolean {\n return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;\n}\n\n/**\n * The `const <id> = <numeric literal>` bindings lexically visible at a\n * specific series-index expression. Only `const` initialised with a\n * numeric literal — or a unary `+`/`-` on one — is included (mirroring\n * `extractInputs.readLiteral`'s numeric handling); a binary initialiser\n * is left for Task 2's interval evaluator and is simply omitted. The walk\n * runs from `useSite` outward through its lexical containers up to\n * `scopeRoot`, collecting only declarations that occur before\n * `useSite.pos` within each container, so it never sees a declaration\n * after the read, inside a sibling block, or in a nested function/class\n * that does not contain `useSite`. The innermost visible binding for a\n * name wins (normal shadowing) — including binders that are not\n * `var`/`let`/`const` statements: a `for`-init induction variable and a\n * function parameter shadow an outer numeric `const` of the same name\n * (`markContainerBinders`), so a reassigned `for (let i …)` index or a\n * `request.security((k) => series[k])` callback parameter can never leak\n * an unrelated outer `const k`'s value into the bound (which would\n * under-size the buffer).\n *\n * @since 0.1\n * @stable\n * @example\n * // const k = 3; series[k];\n * // collectConstNumberEnv(<the `k` arg>, scope).get(\"k\") → 3\n * const fn: typeof collectConstNumberEnv = collectConstNumberEnv;\n * void fn;\n */\nexport function collectConstNumberEnv(\n useSite: ts.Node,\n scopeRoot: ts.Node,\n): ReadonlyMap<string, number> {\n const env = new Map<string, number>();\n // Every `var`/`let`/`const` name bound at or inside a nearer container,\n // numeric or not. A nearer binding shadows an outer one even when it is\n // a `let` or a non-numeric `const`, so an outer `const k = 5` must not\n // leak through it — once a name is `seen`, no outer container can set it.\n const seen = new Set<string>();\n\n let container: ts.Node | undefined = useSite.parent;\n while (container) {\n // A `for`-init variable / function parameter introduced by this\n // container shadows any same-named outer `const`, even though it is\n // not a `var`/`let`/`const` statement `variableDeclarationsIn` scans.\n markContainerBinders(container, seen);\n for (const declaration of variableDeclarationsIn(container)) {\n if (declaration.pos >= useSite.pos) continue;\n if (!ts.isIdentifier(declaration.name)) continue;\n const name = declaration.name.text;\n if (seen.has(name)) continue;\n seen.add(name);\n const list = declaration.parent;\n if (ts.isVariableDeclarationList(list) && (list.flags & ts.NodeFlags.Const) !== 0) {\n const value = readNumericLiteralInit(declaration);\n if (value !== null) env.set(name, value);\n }\n }\n if (container === scopeRoot) break;\n container = container.parent;\n }\n\n return env;\n}\n\n/**\n * Mark every binding name a container introduces at its OWN level — a\n * `for` initializer's induction variable and a function-like's parameters\n * — as `seen`, so an outer numeric `const` of the same name cannot leak\n * past it. These binders are never numeric `const`s the resolver trusts,\n * so marking them only blocks unsound shadow leaks: a reassigned\n * `for (let i …)` index or a callback parameter (`(k) => series[k]`) that\n * collides with an outer `const i`/`const k`. Only identifier binders\n * matter here (a numeric series index is an identifier); destructured\n * parameter/loop patterns bind no numeric index and are skipped.\n */\nfunction markContainerBinders(container: ts.Node, seen: Set<string>): void {\n if (ts.isForStatement(container)) {\n const init = container.initializer;\n if (init && ts.isVariableDeclarationList(init)) {\n for (const declaration of init.declarations) {\n if (ts.isIdentifier(declaration.name)) seen.add(declaration.name.text);\n }\n }\n return;\n }\n if (ts.isFunctionLike(container)) {\n for (const parameter of container.parameters) {\n if (ts.isIdentifier(parameter.name)) seen.add(parameter.name.text);\n }\n }\n}\n\n/**\n * The direct `var`/`let`/`const` `VariableDeclaration`s of a container —\n * of every declaration kind, so the caller can detect a nearer binding\n * that shadows an outer numeric `const` — without descending into nested\n * functions, classes, or blocks (those are handled by their own\n * enclosing-container pass when they actually contain the use site).\n * `Block`, `SourceFile`, function bodies, and case clauses hold their\n * declarations as `statements`/`clauses` we scan directly.\n */\nfunction variableDeclarationsIn(container: ts.Node): ReadonlyArray<ts.VariableDeclaration> {\n const declarations: ts.VariableDeclaration[] = [];\n const statements = statementsOf(container);\n for (const statement of statements) {\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n declarations.push(declaration);\n }\n }\n return declarations;\n}\n\n/** The lexical statement list a container exposes, or `[]` when it holds none. */\nfunction statementsOf(container: ts.Node): ReadonlyArray<ts.Statement> {\n if (ts.isSourceFile(container) || ts.isBlock(container) || ts.isModuleBlock(container)) {\n return container.statements;\n }\n if (ts.isCaseClause(container) || ts.isDefaultClause(container)) {\n return container.statements;\n }\n return [];\n}\n\n/**\n * The numeric value of a `const k = <numeric literal>` /\n * `const k = <unary ± numeric literal>` initialiser, or `null` for any\n * other initialiser (no binary folding here — that is Task 2).\n */\nfunction readNumericLiteralInit(declaration: ts.VariableDeclaration): number | null {\n const initializer = declaration.initializer;\n if (!initializer) return null;\n const expr = unwrapParens(initializer);\n if (ts.isNumericLiteral(expr)) return Number(expr.text);\n if (\n ts.isPrefixUnaryExpression(expr) &&\n (expr.operator === ts.SyntaxKind.MinusToken || expr.operator === ts.SyntaxKind.PlusToken) &&\n ts.isNumericLiteral(expr.operand)\n ) {\n const value = Number(expr.operand.text);\n return expr.operator === ts.SyntaxKind.MinusToken ? -value : value;\n }\n return null;\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { type CompileDiagnostic } from "../diagnostics.js";
|
|
3
|
+
/**
|
|
4
|
+
* Validate that a `request.security({ interval }, (bar) => …)` expression
|
|
5
|
+
* callback references only its `bar` parameter (and locals derived from it),
|
|
6
|
+
* the ambient `ta` namespace, `inputs`, safe `Math.*` globals, and literal
|
|
7
|
+
* constants. Any other free identifier is a captured outer binding — it would
|
|
8
|
+
* smuggle the main-timeline clock into the higher-timeframe expression — and
|
|
9
|
+
* is rejected with `request-security-expr-captures-local`.
|
|
10
|
+
*
|
|
11
|
+
* Function / arrow expressions nested deeper inside the callback are out of
|
|
12
|
+
* the v1 subset and rejected too (keeps the expression unit flat), as is a
|
|
13
|
+
* `this` reference. Parameter default initialisers are walked alongside the
|
|
14
|
+
* body so a default that captures an outer binding is flagged too.
|
|
15
|
+
*
|
|
16
|
+
* @since 0.7
|
|
17
|
+
* @stable
|
|
18
|
+
* @example
|
|
19
|
+
* // Inside extractRequestAnalysis, once per expression callsite:
|
|
20
|
+
* // validateSecurityExpr(callback, checker, diagnostics, sourcePath);
|
|
21
|
+
* const fn: typeof validateSecurityExpr = validateSecurityExpr;
|
|
22
|
+
* void fn;
|
|
23
|
+
*/
|
|
24
|
+
export declare function validateSecurityExpr(callback: ts.ArrowFunction | ts.FunctionExpression, checker: ts.TypeChecker, diagnostics: CompileDiagnostic[], sourcePath: string): void;
|
|
25
|
+
//# sourceMappingURL=validateSecurityExpr.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validateSecurityExpr.d.ts","sourceRoot":"","sources":["../../src/analysis/validateSecurityExpr.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,YAAY,CAAC;AAE5B,OAAO,EAAE,KAAK,iBAAiB,EAAoB,MAAM,mBAAmB,CAAC;AAG7E;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,oBAAoB,CAChC,QAAQ,EAAE,EAAE,CAAC,aAAa,GAAG,EAAE,CAAC,kBAAkB,EAClD,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,WAAW,EAAE,iBAAiB,EAAE,EAChC,UAAU,EAAE,MAAM,GACnB,IAAI,CA2DN"}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Copyright (c) 2026 Invinite. Licensed under the MIT License.
|
|
2
|
+
// See the LICENSE file in the repo root for full license text.
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import { createDiagnostic } from "../diagnostics.js";
|
|
5
|
+
import { resolveCoreSymbolName } from "../transformers/resolveCallee.js";
|
|
6
|
+
/**
|
|
7
|
+
* Validate that a `request.security({ interval }, (bar) => …)` expression
|
|
8
|
+
* callback references only its `bar` parameter (and locals derived from it),
|
|
9
|
+
* the ambient `ta` namespace, `inputs`, safe `Math.*` globals, and literal
|
|
10
|
+
* constants. Any other free identifier is a captured outer binding — it would
|
|
11
|
+
* smuggle the main-timeline clock into the higher-timeframe expression — and
|
|
12
|
+
* is rejected with `request-security-expr-captures-local`.
|
|
13
|
+
*
|
|
14
|
+
* Function / arrow expressions nested deeper inside the callback are out of
|
|
15
|
+
* the v1 subset and rejected too (keeps the expression unit flat), as is a
|
|
16
|
+
* `this` reference. Parameter default initialisers are walked alongside the
|
|
17
|
+
* body so a default that captures an outer binding is flagged too.
|
|
18
|
+
*
|
|
19
|
+
* @since 0.7
|
|
20
|
+
* @stable
|
|
21
|
+
* @example
|
|
22
|
+
* // Inside extractRequestAnalysis, once per expression callsite:
|
|
23
|
+
* // validateSecurityExpr(callback, checker, diagnostics, sourcePath);
|
|
24
|
+
* const fn: typeof validateSecurityExpr = validateSecurityExpr;
|
|
25
|
+
* void fn;
|
|
26
|
+
*/
|
|
27
|
+
export function validateSecurityExpr(callback, checker, diagnostics, sourcePath) {
|
|
28
|
+
const sourceFile = callback.getSourceFile();
|
|
29
|
+
const bound = collectBoundNames(callback);
|
|
30
|
+
const visit = (node) => {
|
|
31
|
+
// Nested functions/arrows are out of the flat v1 subset.
|
|
32
|
+
if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
|
|
33
|
+
diagnostics.push(createDiagnostic({
|
|
34
|
+
severity: "error",
|
|
35
|
+
code: "request-security-expr-captures-local",
|
|
36
|
+
message: "A request.security expression callback may not contain a nested function. Keep the expression flat.",
|
|
37
|
+
file: sourcePath,
|
|
38
|
+
node,
|
|
39
|
+
sourceFile,
|
|
40
|
+
}));
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
// `this` is not a value the flat expression subset may read — in a
|
|
44
|
+
// function-expression callback it would be `undefined` under the
|
|
45
|
+
// module's strict mode and throw at runtime.
|
|
46
|
+
if (node.kind === ts.SyntaxKind.ThisKeyword) {
|
|
47
|
+
diagnostics.push(createDiagnostic({
|
|
48
|
+
severity: "error",
|
|
49
|
+
code: "request-security-expr-captures-local",
|
|
50
|
+
message: "A request.security expression callback may not use `this`.",
|
|
51
|
+
file: sourcePath,
|
|
52
|
+
node,
|
|
53
|
+
sourceFile,
|
|
54
|
+
}));
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (ts.isIdentifier(node) && isFreeReference(node)) {
|
|
58
|
+
if (!isAllowedReference(node, bound, checker)) {
|
|
59
|
+
diagnostics.push(createDiagnostic({
|
|
60
|
+
severity: "error",
|
|
61
|
+
code: "request-security-expr-captures-local",
|
|
62
|
+
message: `A request.security expression callback may not capture the outer binding \`${node.text}\`. Inline it as a literal or read it from \`inputs\`.`,
|
|
63
|
+
file: sourcePath,
|
|
64
|
+
node,
|
|
65
|
+
sourceFile,
|
|
66
|
+
}));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
ts.forEachChild(node, visit);
|
|
70
|
+
};
|
|
71
|
+
// A parameter default (`(bar = outer) => …`) is a value read of whatever it
|
|
72
|
+
// initialises to, so it must be checked for captures alongside the body.
|
|
73
|
+
for (const parameter of callback.parameters) {
|
|
74
|
+
if (parameter.initializer !== undefined)
|
|
75
|
+
visit(parameter.initializer);
|
|
76
|
+
}
|
|
77
|
+
visit(callback.body);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Collect every name bound *inside* the callback: the parameter identifiers
|
|
81
|
+
* plus any `const` / `let` / `var` declared in the body. A binding's
|
|
82
|
+
* initialiser is still walked by the caller, so an initialiser that captures
|
|
83
|
+
* an outer name is still flagged.
|
|
84
|
+
*/
|
|
85
|
+
function collectBoundNames(callback) {
|
|
86
|
+
const names = new Set();
|
|
87
|
+
for (const parameter of callback.parameters) {
|
|
88
|
+
addBindingNames(parameter.name, names);
|
|
89
|
+
}
|
|
90
|
+
const visit = (node) => {
|
|
91
|
+
if (ts.isVariableDeclaration(node)) {
|
|
92
|
+
addBindingNames(node.name, names);
|
|
93
|
+
}
|
|
94
|
+
ts.forEachChild(node, visit);
|
|
95
|
+
};
|
|
96
|
+
visit(callback.body);
|
|
97
|
+
return names;
|
|
98
|
+
}
|
|
99
|
+
function addBindingNames(name, into) {
|
|
100
|
+
if (ts.isIdentifier(name)) {
|
|
101
|
+
into.add(name.text);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
for (const element of name.elements) {
|
|
105
|
+
if (ts.isBindingElement(element))
|
|
106
|
+
addBindingNames(element.name, into);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Whether an identifier is a *free reference* — an actual value read, not a
|
|
111
|
+
* property name (`bar.close` → `close`), a property-assignment key, or a
|
|
112
|
+
* binding/declaration name (handled by `collectBoundNames`).
|
|
113
|
+
*
|
|
114
|
+
* A shorthand property (`{ offset }`) is deliberately NOT excluded: the
|
|
115
|
+
* identifier there is both the key and the value read, so `{ outerLength }`
|
|
116
|
+
* inside an opts object must still be checked against the allowed subset.
|
|
117
|
+
*/
|
|
118
|
+
function isFreeReference(node) {
|
|
119
|
+
const parent = node.parent;
|
|
120
|
+
if (ts.isPropertyAccessExpression(parent) && parent.name === node)
|
|
121
|
+
return false;
|
|
122
|
+
if (ts.isPropertyAssignment(parent) && parent.name === node)
|
|
123
|
+
return false;
|
|
124
|
+
if (ts.isBindingElement(parent) && parent.propertyName === node)
|
|
125
|
+
return false;
|
|
126
|
+
if (ts.isVariableDeclaration(parent) && parent.name === node)
|
|
127
|
+
return false;
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Pure value globals that carry no main-timeline data and are morally literals.
|
|
132
|
+
* They cannot smuggle the outer clock in, so they are allowed alongside `Math`.
|
|
133
|
+
* Genuinely hostile globals (`Date`, `fetch`, …) are rejected separately by the
|
|
134
|
+
* file-level `forbiddenConstructs` pass, which also covers the inline callback.
|
|
135
|
+
*/
|
|
136
|
+
const SAFE_VALUE_GLOBALS = new Set(["undefined", "NaN", "Infinity"]);
|
|
137
|
+
/**
|
|
138
|
+
* Whether a free identifier is in the allowed subset: a name bound inside the
|
|
139
|
+
* callback (`bar` + locals), a {@link SAFE_VALUE_GLOBALS} constant, the ambient
|
|
140
|
+
* `ta` / `inputs` namespaces, or the `Math` global (individual hostile members
|
|
141
|
+
* such as `Math.random` are rejected by the separate hostile-global pass, not
|
|
142
|
+
* here).
|
|
143
|
+
*/
|
|
144
|
+
function isAllowedReference(node, bound, checker) {
|
|
145
|
+
if (bound.has(node.text))
|
|
146
|
+
return true;
|
|
147
|
+
if (node.text === "Math")
|
|
148
|
+
return true;
|
|
149
|
+
if (SAFE_VALUE_GLOBALS.has(node.text))
|
|
150
|
+
return true;
|
|
151
|
+
const canonical = resolveCoreSymbolName(checker, node);
|
|
152
|
+
return canonical === "ta" || canonical === "inputs";
|
|
153
|
+
}
|
|
154
|
+
//# sourceMappingURL=validateSecurityExpr.js.map
|