@chrischall/warapp-mcp 0.0.0 → 0.1.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/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +199 -8
- package/dist/analysis/award.js +159 -0
- package/dist/analysis/bonuses.js +98 -0
- package/dist/analysis/breach.js +62 -0
- package/dist/analysis/card-support.js +329 -0
- package/dist/analysis/card-threats.js +234 -0
- package/dist/analysis/cards-in-effect.js +130 -0
- package/dist/analysis/chains.js +59 -0
- package/dist/analysis/chokepoints.js +140 -0
- package/dist/analysis/combat.js +231 -0
- package/dist/analysis/commander-safety.js +149 -0
- package/dist/analysis/commitments.js +338 -0
- package/dist/analysis/exchange.js +155 -0
- package/dist/analysis/graph.js +82 -0
- package/dist/analysis/guard-off.js +54 -0
- package/dist/analysis/guess.js +351 -0
- package/dist/analysis/headroom.js +241 -0
- package/dist/analysis/hold-diff.js +64 -0
- package/dist/analysis/how-lost.js +130 -0
- package/dist/analysis/index.js +14 -0
- package/dist/analysis/local-deploy.js +159 -0
- package/dist/analysis/lookahead.js +108 -0
- package/dist/analysis/opponent-profile.js +551 -0
- package/dist/analysis/opponents.js +1245 -0
- package/dist/analysis/outlook.js +633 -0
- package/dist/analysis/overrides.js +60 -0
- package/dist/analysis/picks.js +1879 -0
- package/dist/analysis/plan/after-leftover.js +140 -0
- package/dist/analysis/plan/cap-spend.js +242 -0
- package/dist/analysis/plan/captures.js +1195 -0
- package/dist/analysis/plan/commander.js +236 -0
- package/dist/analysis/plan/completed.js +29 -0
- package/dist/analysis/plan/conceded-out.js +131 -0
- package/dist/analysis/plan/estimates.js +715 -0
- package/dist/analysis/plan/guard-off.js +232 -0
- package/dist/analysis/plan/holds.js +1631 -0
- package/dist/analysis/plan/leftover.js +760 -0
- package/dist/analysis/plan/move-order.js +319 -0
- package/dist/analysis/plan/orders.js +317 -0
- package/dist/analysis/plan/relations.js +702 -0
- package/dist/analysis/plan/report.js +672 -0
- package/dist/analysis/plan/shared.js +1218 -0
- package/dist/analysis/plan/stand-still.js +823 -0
- package/dist/analysis/plan/state.js +44 -0
- package/dist/analysis/plan/strike.js +1416 -0
- package/dist/analysis/plan/targets.js +651 -0
- package/dist/analysis/plan/team.js +299 -0
- package/dist/analysis/plan/threats.js +927 -0
- package/dist/analysis/plan/transfers.js +328 -0
- package/dist/analysis/plan/util.js +5 -0
- package/dist/analysis/plan/vacated.js +285 -0
- package/dist/analysis/planner.js +2922 -0
- package/dist/analysis/player-record.js +144 -0
- package/dist/analysis/player.js +268 -0
- package/dist/analysis/profile.js +347 -0
- package/dist/analysis/relations.js +1030 -0
- package/dist/analysis/schedule.js +88 -0
- package/dist/analysis/since-last.js +50 -0
- package/dist/analysis/static-seats.js +71 -0
- package/dist/analysis/stress.js +577 -0
- package/dist/analysis/team-brief.js +151 -0
- package/dist/analysis/tripwire.js +644 -0
- package/dist/analysis/turn-sim.js +259 -0
- package/dist/analysis/whereabouts.js +1109 -0
- package/dist/board.js +105 -0
- package/dist/bundle.js +117959 -36172
- package/dist/cards.js +435 -0
- package/dist/chat-cursor.js +135 -0
- package/dist/chat.js +192 -0
- package/dist/client.js +361 -0
- package/dist/config.js +62 -0
- package/dist/direct/link.js +102 -0
- package/dist/direct/session.js +267 -0
- package/dist/direct/transport.js +424 -0
- package/dist/guess-salt.js +65 -0
- package/dist/hosted.js +24 -0
- package/dist/index.js +33 -0
- package/dist/join-color.js +140 -0
- package/dist/live.js +278 -0
- package/dist/map-stats.js +152 -0
- package/dist/map-store.js +204 -0
- package/dist/move-order.js +141 -0
- package/dist/my-games.js +180 -0
- package/dist/normalize.js +411 -0
- package/dist/open-games.js +537 -0
- package/dist/outlook-log.js +138 -0
- package/dist/path-lock.js +22 -0
- package/dist/pick-list.js +193 -0
- package/dist/player-record-store.js +229 -0
- package/dist/player-states.js +31 -0
- package/dist/profile-store.js +677 -0
- package/dist/protocol/bundle.js +375 -0
- package/dist/protocol/codec.js +556 -0
- package/dist/protocol/decoded.js +12 -0
- package/dist/protocol/interp.js +1904 -0
- package/dist/protocol/methods.js +531 -0
- package/dist/protocol/rpc.js +202 -0
- package/dist/push/listener.js +393 -0
- package/dist/push/packets.js +66 -0
- package/dist/push/socketio.js +333 -0
- package/dist/push/websocket.js +179 -0
- package/dist/redact.js +62 -0
- package/dist/relations-store.js +242 -0
- package/dist/replay.js +215 -0
- package/dist/scalars.js +28 -0
- package/dist/scout.js +346 -0
- package/dist/stats.js +269 -0
- package/dist/strategy/card-clock.js +185 -0
- package/dist/strategy/map-notes.js +128 -0
- package/dist/strategy/notes.js +2168 -0
- package/dist/team-cards.js +84 -0
- package/dist/team-orders.js +150 -0
- package/dist/teams.js +19 -0
- package/dist/tools/award.js +206 -0
- package/dist/tools/begin-turn.js +162 -0
- package/dist/tools/board.js +77 -0
- package/dist/tools/card-advice.js +256 -0
- package/dist/tools/card-effects.js +49 -0
- package/dist/tools/card-plays.js +434 -0
- package/dist/tools/card-support-advice.js +140 -0
- package/dist/tools/chat-inbox.js +146 -0
- package/dist/tools/chat.js +483 -0
- package/dist/tools/check-plan.js +688 -0
- package/dist/tools/commander-check.js +102 -0
- package/dist/tools/commitments.js +216 -0
- package/dist/tools/common.js +143 -0
- package/dist/tools/diplomacy.js +342 -0
- package/dist/tools/game.js +126 -0
- package/dist/tools/guess-view.js +56 -0
- package/dist/tools/healthcheck.js +90 -0
- package/dist/tools/hints.js +34 -0
- package/dist/tools/how-lost.js +154 -0
- package/dist/tools/index.js +142 -0
- package/dist/tools/join-game.js +327 -0
- package/dist/tools/leave-game.js +181 -0
- package/dist/tools/live-context.js +339 -0
- package/dist/tools/live.js +404 -0
- package/dist/tools/map-stats.js +117 -0
- package/dist/tools/map.js +133 -0
- package/dist/tools/my-games.js +123 -0
- package/dist/tools/open-games.js +104 -0
- package/dist/tools/opponents.js +151 -0
- package/dist/tools/order-options.js +135 -0
- package/dist/tools/picks.js +292 -0
- package/dist/tools/profile-hook.js +156 -0
- package/dist/tools/profile-opponents.js +121 -0
- package/dist/tools/profile-reads.js +99 -0
- package/dist/tools/push.js +385 -0
- package/dist/tools/relations.js +611 -0
- package/dist/tools/resolve.js +45 -0
- package/dist/tools/route.js +36 -0
- package/dist/tools/scout.js +87 -0
- package/dist/tools/session.js +163 -0
- package/dist/tools/strategy.js +200 -0
- package/dist/tools/stress-opponents.js +83 -0
- package/dist/tools/surrender.js +240 -0
- package/dist/tools/survival.js +189 -0
- package/dist/tools/team-brief.js +266 -0
- package/dist/tools/team-source.js +222 -0
- package/dist/tools/team.js +182 -0
- package/dist/tools/turn.js +2761 -0
- package/dist/tools/uncommit.js +160 -0
- package/dist/tools/where.js +275 -0
- package/dist/tools/write-kit.js +158 -0
- package/dist/transport-bridge.js +33 -0
- package/dist/trend.js +452 -0
- package/dist/version.js +4 -0
- package/manifest.json +174 -4
- package/mint.yaml +101 -14
- package/package.json +11 -6
- package/server.json +40 -3
- package/skills/warapp-api/SKILL.md +95 -4
- package/skills/warapp-api/references/scout.mjs +348 -0
- package/skills/warapp-api/scripts/warapp.sh +69 -8
- package/skills/warapp-mcp/SKILL.md +969 -21
|
@@ -0,0 +1,1904 @@
|
|
|
1
|
+
// An evaluator for war.app's own generated reader functions.
|
|
2
|
+
//
|
|
3
|
+
// The client bundle (`ujs.js`, fetched from War.app's CDN at runtime — never vendored)
|
|
4
|
+
// contains, for every wire class, a reader `<Var>.Ha=function(a,b,d){…}` that reads the
|
|
5
|
+
// class's fields from a binary reader `a`. Rather than transcribe each layout (which
|
|
6
|
+
// changes between client releases), this module parses those functions with acorn and
|
|
7
|
+
// evaluates them against a codec `Reader`. Only the small JS subset the readers use is
|
|
8
|
+
// supported: primitive reads, present-flag ternaries, lists/dicts of nested classes via
|
|
9
|
+
// closures, version checks, `switch` on a type tag, the client's runtime type checks (`instanceof`
|
|
10
|
+
// through the superclass chain the bundle declares, a class's static data such as its interface
|
|
11
|
+
// list, a decoded object's class through its prototype's class field) and constructors that
|
|
12
|
+
// assign `this.*`. Anything else raises an {@link InterpError} naming the function and the
|
|
13
|
+
// bundle offset of the construct.
|
|
14
|
+
//
|
|
15
|
+
// The primitive helpers (`P.Ya`, the dialect) are built in and shadow the bundle's own
|
|
16
|
+
// definitions; `verifyDialect` checks them against those definitions when a bundle loads.
|
|
17
|
+
//
|
|
18
|
+
// Classes are registered in the bundle as `W["warlight.shared.Foo"]=Xy;` — the type name
|
|
19
|
+
// is stable, the var is minified. Decoded objects carry the type name as `$type`.
|
|
20
|
+
//
|
|
21
|
+
// Containment. The bundle is downloaded at run time, so it is treated as hostile: interpreted
|
|
22
|
+
// code must not reach anything of the host process (which holds the user's credentials), even
|
|
23
|
+
// though a browser would have sandboxed it. The design keeps the objects the interpreter makes
|
|
24
|
+
// ordinary (decoded objects stay plain `{ $type, … }` for every consumer) and enforces the rules
|
|
25
|
+
// at the only places interpreted code touches host values:
|
|
26
|
+
// - a member read returns an own property, or `length` / an index of an array, a string or the
|
|
27
|
+
// raw-bytes reader's Uint8Array (the only inherited members the readers use); any other inherited member reads as `undefined`, and the
|
|
28
|
+
// keys `constructor`, `__proto__` and `prototype` raise. Interpreter internals (closures, the
|
|
29
|
+
// reader, class refs) are not readable at all.
|
|
30
|
+
// - a write goes only to an array or a plain object the interpreter made, never with one of those
|
|
31
|
+
// three keys, so it can only create or replace an own data property. An array takes only an index
|
|
32
|
+
// at most its length (never `length`), so it stays dense; an object never takes one of
|
|
33
|
+
// Object.prototype's member names (or `toJSON`), which would shadow the host method with a non-callable value.
|
|
34
|
+
// - no operator converts an object operand (that would run host code such as an array's join):
|
|
35
|
+
// arithmetic, relational, bitwise and `++`/`--` refuse one (and a BigInt), and loose equality (`==`, `!=` and a
|
|
36
|
+
// `switch` case) compares an object by identity, so `x == null` still works.
|
|
37
|
+
// - only string, number, boolean and null literals evaluate: a BigInt would make one step cost the
|
|
38
|
+
// host work proportional to its size, and a RegExp is a host object.
|
|
39
|
+
// - a string built by `+` is capped at MAX_STRING characters and its length is charged to the step
|
|
40
|
+
// budget, as is comparing two strings, so string work cannot outrun the budget or the heap.
|
|
41
|
+
// - statics and reader methods are looked up as own entries of the dialect tables only.
|
|
42
|
+
// - a class's static data comes only from the bundle's source text: a static reads as a value only when
|
|
43
|
+
// every assignment to it is the same literal, null, class or list of classes (never a host object, a
|
|
44
|
+
// function or an expression's result), a list afresh on each read; statics are never written. A
|
|
45
|
+
// class is one value per name (`ClassRef`), so classes compare by identity as in JS; nothing reads
|
|
46
|
+
// through it to a prototype or constructor. A host global's own members (Math.PI) are not answered.
|
|
47
|
+
// The class structure (static sites, superclass links, the class field) is indexed in one pass over
|
|
48
|
+
// the source, once per interpreter, and walking a superclass chain costs a step per link and ends on a cycle.
|
|
49
|
+
// - natives call back only into interpreter closures (`toNative` brands the functions it makes and
|
|
50
|
+
// `callback` checks the brand), and no call or read hands a host function back to the bundle.
|
|
51
|
+
// - every `readClass` has one budget: a step count and a call depth (options with defaults), so
|
|
52
|
+
// nested loops and recursion end in an InterpError; native element work (an array handed to a
|
|
53
|
+
// native, a range's count) is charged to the same step count, and an allocating helper caps its count.
|
|
54
|
+
// A reply decoded by several `readClass` calls (the open-games list, one call per record) passes one
|
|
55
|
+
// `ReadBudget` to all of them, so the step count bounds the whole reply rather than each record.
|
|
56
|
+
// - converting a string operand to a number (arithmetic, relational, bitwise, unary minus, `++`/`--`,
|
|
57
|
+
// and `==` against a number or boolean) costs the string's length: the host scans it to convert it.
|
|
58
|
+
// - host work that grows with something the bundle controls is charged too, or done once: a computed
|
|
59
|
+
// member key costs its length, parsing a function costs the characters parsed, a constructor failure
|
|
60
|
+
// kept as `$ctorError` costs CTOR_FAILURE_STEPS, and definitions are indexed in one pass over the
|
|
61
|
+
// source, with failed lookups cached, so no lookup rescans the bundle. A thrown value's message is
|
|
62
|
+
// built once per throw site, capped at MAX_THROW_MESSAGE and charged; a key longer than ten
|
|
63
|
+
// characters is never an array index (no pattern test over a long key); a name lookup costs the
|
|
64
|
+
// scopes it walks, and functions nest at most MAX_NESTING deep.
|
|
65
|
+
// - a wall-clock deadline backs the step count up: each `readClass` (or shared `ReadBudget`) has
|
|
66
|
+
// `maxMillis` (default DEFAULT_MAX_MILLIS), checked every CLOCK_EVERY steps and raising the same
|
|
67
|
+
// budget error. It can only end a read between steps, so it bounds uncounted work only because every
|
|
68
|
+
// single host operation is itself size-bounded: a string is at most MAX_STRING characters when `+`
|
|
69
|
+
// builds it, else a literal (bounded by the bundle, whose parsing is charged) or a wire string
|
|
70
|
+
// (bounded by the frame); an array handed to a native is at most MAX_RANGE long, `E.Range` allocates at
|
|
71
|
+
// most MAX_RANGE, a wire list's count is capped by the codec, and every other array grows by one
|
|
72
|
+
// element per charged step (dense writes, `push` of the source's own arguments); a parse and the
|
|
73
|
+
// definition index are bounded by the bundle's size and done once per function or per interpreter.
|
|
74
|
+
// - the per-function AST walks (hoisting, `fieldsReadAs`, a throw's literals) are iterative, linear in
|
|
75
|
+
// the nodes they visit (duplicates removed with a Set, whether an expression calls a reader worked
|
|
76
|
+
// out once per node) and charge each node to the step count; a call also pays for the parameters
|
|
77
|
+
// and hoisted names it declares.
|
|
78
|
+
import { parseExpressionAt, } from 'acorn';
|
|
79
|
+
import { PROTOCOL_VERSION, ProtocolError, Reader } from './codec.js';
|
|
80
|
+
/** A reader the interpreter cannot evaluate, or one that failed on the bytes. */
|
|
81
|
+
export class InterpError extends Error {
|
|
82
|
+
kind;
|
|
83
|
+
where;
|
|
84
|
+
offset;
|
|
85
|
+
constructor(kind, message,
|
|
86
|
+
/** The bundle function being evaluated, e.g. `Xy.Ha`. */
|
|
87
|
+
where,
|
|
88
|
+
/** Character offset of the offending construct in the bundle source. */
|
|
89
|
+
offset) {
|
|
90
|
+
super(where === undefined ? message : `${message} in ${where}${offset === undefined ? '' : ` at bundle offset ${offset}`}`);
|
|
91
|
+
this.kind = kind;
|
|
92
|
+
this.where = where;
|
|
93
|
+
this.offset = offset;
|
|
94
|
+
this.name = 'InterpError';
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* A `W["<type name>"]=<var>;` registration. The minifier wraps long lines, and a wrap can fall right
|
|
99
|
+
* after the `=` (the real bundle has CRLF there, e.g. for `GameMessage`), so whitespace is allowed
|
|
100
|
+
* around it.
|
|
101
|
+
*/
|
|
102
|
+
const REGISTRATION = /W\["([\w.$]+)"\]\s*=\s*([\w$]+)\s*;/g;
|
|
103
|
+
/** Index the `W["<type name>"]=<var>;` registrations of a bundle. */
|
|
104
|
+
export function parseBundle(src) {
|
|
105
|
+
const typeNameOf = new Map();
|
|
106
|
+
const varOf = new Map();
|
|
107
|
+
for (const m of src.matchAll(REGISTRATION)) {
|
|
108
|
+
if (!typeNameOf.has(m[2]))
|
|
109
|
+
typeNameOf.set(m[2], m[1]);
|
|
110
|
+
if (!varOf.has(m[1]))
|
|
111
|
+
varOf.set(m[1], m[2]);
|
|
112
|
+
}
|
|
113
|
+
return { src, typeNameOf, varOf };
|
|
114
|
+
}
|
|
115
|
+
function readBytes(r) {
|
|
116
|
+
const at = r.position;
|
|
117
|
+
const n = r.int32();
|
|
118
|
+
if (n === -1)
|
|
119
|
+
return null;
|
|
120
|
+
if (n < 0)
|
|
121
|
+
throw new ProtocolError('bad-length', `negative byte-array length ${n} at offset ${at}`);
|
|
122
|
+
return r.raw(n);
|
|
123
|
+
}
|
|
124
|
+
function strBody(r) {
|
|
125
|
+
const n = r.varint();
|
|
126
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(r.raw(n));
|
|
127
|
+
}
|
|
128
|
+
/** A helper's reader argument: the codec reader, else an InterpError (never a host TypeError). */
|
|
129
|
+
function asReader(x) {
|
|
130
|
+
if (!(x instanceof Reader))
|
|
131
|
+
throw new InterpError('bad-value', `expected the reader, got ${describe(x)}`);
|
|
132
|
+
return x;
|
|
133
|
+
}
|
|
134
|
+
/** Functions `toNative` made from interpreter closures: the only callables a native may call. */
|
|
135
|
+
const CALLBACKS = new WeakSet();
|
|
136
|
+
/** A native's callback argument, refused unless it is an interpreter closure made callable by `toNative`. */
|
|
137
|
+
function callback(f) {
|
|
138
|
+
if (typeof f !== 'function' || !CALLBACKS.has(f)) {
|
|
139
|
+
throw new InterpError('forbidden', 'a native was handed a callback that is not an interpreter function');
|
|
140
|
+
}
|
|
141
|
+
return f;
|
|
142
|
+
}
|
|
143
|
+
/** The largest count `E.Range` will allocate, and the longest array a native takes (special-unit counts are a byte). */
|
|
144
|
+
const MAX_RANGE = 1_000_000;
|
|
145
|
+
function asArray(xs) {
|
|
146
|
+
if (!Array.isArray(xs))
|
|
147
|
+
throw new InterpError('bad-value', `expected an array, got ${describe(xs)}`);
|
|
148
|
+
// A backstop: interpreted writes keep arrays dense, so only a host-made array could be this long.
|
|
149
|
+
if (xs.length > MAX_RANGE)
|
|
150
|
+
throw new InterpError('bad-value', `array of ${xs.length} elements (at most ${MAX_RANGE})`);
|
|
151
|
+
return xs;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Charges native element work to the step budget of the `readClass` that called the native (set by
|
|
155
|
+
* `callStatic` for the duration of the call; a no-op when a native is called from host code).
|
|
156
|
+
*/
|
|
157
|
+
let chargeNative = () => { };
|
|
158
|
+
function range(start, count) {
|
|
159
|
+
if (typeof start !== 'number' || !Number.isFinite(start))
|
|
160
|
+
throw new InterpError('bad-value', `bad range start ${String(start)}`);
|
|
161
|
+
if (typeof count !== 'number' || !Number.isInteger(count) || count < 0 || count > MAX_RANGE) {
|
|
162
|
+
throw new InterpError('bad-value', `bad range count ${String(count)} (an integer 0..${MAX_RANGE})`);
|
|
163
|
+
}
|
|
164
|
+
chargeNative(count);
|
|
165
|
+
return Array.from({ length: count }, (_, i) => start + i);
|
|
166
|
+
}
|
|
167
|
+
function list(r, item) {
|
|
168
|
+
const f = callback(item);
|
|
169
|
+
return asReader(r).list(() => f());
|
|
170
|
+
}
|
|
171
|
+
/** The names used by client v6.07 (protocol 242). */
|
|
172
|
+
export const DEFAULT_DIALECT = {
|
|
173
|
+
readerMethods: {
|
|
174
|
+
Ua: (r) => r.bool(),
|
|
175
|
+
Og: (r) => r.int32(),
|
|
176
|
+
bc: (r) => r.u8(),
|
|
177
|
+
FJ: (r) => strBody(r),
|
|
178
|
+
// The client's 8-byte read is a float64 (its two int32 halves reassembled as a double), not an
|
|
179
|
+
// int64: kill rates, luck and TimeSpans (milliseconds) all arrive through it.
|
|
180
|
+
E3a: (r) => r.float64(),
|
|
181
|
+
Om: (r) => r.float32(),
|
|
182
|
+
NGb: (r) => r.uint16(),
|
|
183
|
+
S3c: (r) => r.int16(),
|
|
184
|
+
MGb: (r) => r.u8(),
|
|
185
|
+
JS: (r, n) => {
|
|
186
|
+
if (typeof n !== 'number' || !Number.isInteger(n) || n < 0)
|
|
187
|
+
throw new InterpError('bad-value', `bad byte count ${String(n)}`);
|
|
188
|
+
return r.raw(n);
|
|
189
|
+
},
|
|
190
|
+
I3c: (r) => r.varint(),
|
|
191
|
+
},
|
|
192
|
+
statics: {
|
|
193
|
+
P: {
|
|
194
|
+
Ya: (r) => asReader(r).int32(),
|
|
195
|
+
wc: (r) => asReader(r).string(),
|
|
196
|
+
Yc: (r) => asReader(r).bool(),
|
|
197
|
+
uq: (r) => asReader(r).u8(),
|
|
198
|
+
Ao: (r) => asReader(r).float32(),
|
|
199
|
+
ak: (r) => asReader(r).float64(),
|
|
200
|
+
uy: (r) => asReader(r).float64(),
|
|
201
|
+
Td: (r) => asReader(r).date(),
|
|
202
|
+
tL: (r) => asReader(r).guid(),
|
|
203
|
+
Z5: (r) => asReader(r).uint16(),
|
|
204
|
+
sL: (r) => readBytes(asReader(r)),
|
|
205
|
+
Sd: list,
|
|
206
|
+
ms: list,
|
|
207
|
+
uL: list,
|
|
208
|
+
ef: (r, k, v) => {
|
|
209
|
+
const fk = callback(k);
|
|
210
|
+
const fv = callback(v);
|
|
211
|
+
return asReader(r).list(() => [fk(), fv()]);
|
|
212
|
+
},
|
|
213
|
+
},
|
|
214
|
+
O: { fA: (x) => x, Fy: (x) => x, rc: (x) => x },
|
|
215
|
+
za: { rc: (x) => x },
|
|
216
|
+
// Enumerable helpers (special-unit lists): Range → Select → ToArray.
|
|
217
|
+
E: {
|
|
218
|
+
Range: range,
|
|
219
|
+
Za: (xs, f) => {
|
|
220
|
+
const fn = callback(f);
|
|
221
|
+
return asArray(xs).map((x) => fn(x));
|
|
222
|
+
},
|
|
223
|
+
Sa: (xs) => [...asArray(xs)],
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
wrappers: ['Z', 'Yb', 'uc', 'dc', 'oc', 'ec', 'fc'],
|
|
227
|
+
};
|
|
228
|
+
/** The class whose statics are the reader helpers (`P.Ya(a)`), checked by `verifyDialect`. */
|
|
229
|
+
export const READER_HELPERS = 'P';
|
|
230
|
+
/**
|
|
231
|
+
* The helpers every board count, flag and unit count is read through (int32, bool, byte). A bundle
|
|
232
|
+
* whose own definition of one of these cannot be verified is refused at load: an unverified one could
|
|
233
|
+
* be a swapped same-width read, which decodes a wrong board without an error (#148).
|
|
234
|
+
*/
|
|
235
|
+
export const REQUIRED_HELPERS = ['Ya', 'Yc', 'uq'];
|
|
236
|
+
/**
|
|
237
|
+
* The most object literals assigned to {@link READER_HELPERS} that `verifyDialect` parses (the live
|
|
238
|
+
* bundle has two `P={…}` sites, neither the helpers). Each parse is host work acorn does before any
|
|
239
|
+
* step is counted, so the scan is bounded in sites as well as in text; past either bound it stops and
|
|
240
|
+
* fails closed (#148, the #152 bounds).
|
|
241
|
+
*/
|
|
242
|
+
export const MAX_LITERAL_SITES = 16;
|
|
243
|
+
/** Byte strings each helper is run on: small counts, a -1 count, ascending bytes, zeros. */
|
|
244
|
+
const DIALECT_PROBES = [
|
|
245
|
+
Uint8Array.from([2, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),
|
|
246
|
+
Uint8Array.from([1, 1, 0, 0, 0, 1, 7, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]),
|
|
247
|
+
Uint8Array.from([255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
|
|
248
|
+
Uint8Array.from({ length: 32 }, (_, i) => i),
|
|
249
|
+
new Uint8Array(32),
|
|
250
|
+
];
|
|
251
|
+
/** Run a helper on a probe: the reader, then one item reader (a byte) per extra parameter. */
|
|
252
|
+
function runProbe(probe, arity, call) {
|
|
253
|
+
const r = new Reader(probe);
|
|
254
|
+
const args = [r];
|
|
255
|
+
const trace = [];
|
|
256
|
+
for (let i = 1; i < arity; i++) {
|
|
257
|
+
// An item reader the host made: registered as a callback, so a native list helper (and the
|
|
258
|
+
// bundle's own definition, through `call`) may call it like an interpreter closure. Each call
|
|
259
|
+
// is recorded, so the order of key and value reads is compared, not just the bytes consumed.
|
|
260
|
+
const item = () => {
|
|
261
|
+
trace.push([i, r.position]);
|
|
262
|
+
return r.u8();
|
|
263
|
+
};
|
|
264
|
+
CALLBACKS.add(item);
|
|
265
|
+
args.push(item);
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
const value = call(args);
|
|
269
|
+
return { kind: 'value', value, position: r.position, trace };
|
|
270
|
+
}
|
|
271
|
+
catch (e) {
|
|
272
|
+
return e instanceof InterpError && e.kind !== 'reader-threw' ? { kind: 'unevaluable', trace } : { kind: 'read-error', trace };
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const isClientObject = (v) => isObject(v) && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof Uint8Array) && typeof v.$type === 'string';
|
|
276
|
+
const sameTrace = (a, b) => a.length === b.length && a.every(([i, p], k) => i === b[k][0] && p === b[k][1]);
|
|
277
|
+
const tracePrefix = (a, of) => a.length <= of.length && a.every(([i, p], k) => i === of[k][0] && p === of[k][1]);
|
|
278
|
+
/**
|
|
279
|
+
* How the bundle's run of a helper on one probe compares with the built-in's: `agree` (with
|
|
280
|
+
* `informative` when it showed the helper's reads, not just a null for a -1 count), `differ`, or
|
|
281
|
+
* `unknown` when the run says nothing either way.
|
|
282
|
+
*/
|
|
283
|
+
function compareProbe(mine, theirs, arity) {
|
|
284
|
+
if (theirs.kind === 'unevaluable') {
|
|
285
|
+
// It stopped where the interpreter could not follow; the item reads it made before that still
|
|
286
|
+
// count: a dictionary that reads the value before the key differs on its first read.
|
|
287
|
+
// (Only against a built-in that read the probe through: one that refused the count up front made no reads to compare.)
|
|
288
|
+
return mine.kind !== 'value' || tracePrefix(theirs.trace, mine.trace) ? 'unknown' : 'differ';
|
|
289
|
+
}
|
|
290
|
+
if (mine.kind !== theirs.kind)
|
|
291
|
+
return 'differ';
|
|
292
|
+
// Both failed on the bytes: the codec refuses a count past the bytes left before reading an item,
|
|
293
|
+
// a hand-written loop after reading some, so where they stopped says nothing.
|
|
294
|
+
if (mine.kind === 'read-error')
|
|
295
|
+
return 'agree';
|
|
296
|
+
if (!sameTrace(mine.trace, theirs.trace))
|
|
297
|
+
return 'differ';
|
|
298
|
+
if (mine.kind === 'value' && theirs.kind === 'value') {
|
|
299
|
+
if (mine.position !== theirs.position)
|
|
300
|
+
return 'differ';
|
|
301
|
+
// A client collection (`new Je`, a dictionary) is not comparable with the built-in's JS array:
|
|
302
|
+
// the item reads (trace) and the bytes consumed say whether the two read alike.
|
|
303
|
+
if (!isClientObject(theirs.value) && !sameValue(mine.value, theirs.value))
|
|
304
|
+
return 'differ';
|
|
305
|
+
}
|
|
306
|
+
// A helper that takes item readers is shown to read alike only by a probe on which it read items.
|
|
307
|
+
return arity <= 1 || theirs.trace.length > 0 ? 'informative' : 'agree';
|
|
308
|
+
}
|
|
309
|
+
function sameValue(a, b) {
|
|
310
|
+
if (Object.is(a, b))
|
|
311
|
+
return true;
|
|
312
|
+
if (a instanceof Date && b instanceof Date)
|
|
313
|
+
return Object.is(a.getTime(), b.getTime());
|
|
314
|
+
// The client's date is a wrapper class (unwrapped, see `wrappers`) around Unix milliseconds, built by
|
|
315
|
+
// adding a static epoch: the same instant as the built-in's Date when the two read alike.
|
|
316
|
+
if (a instanceof Date && typeof b === 'number')
|
|
317
|
+
return Object.is(a.getTime(), b);
|
|
318
|
+
if (a instanceof Uint8Array && b instanceof Uint8Array)
|
|
319
|
+
return a.length === b.length && a.every((x, i) => x === b[i]);
|
|
320
|
+
if (Array.isArray(a) && Array.isArray(b))
|
|
321
|
+
return a.length === b.length && a.every((x, i) => sameValue(x, b[i]));
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Steps per `readClass`. Native element work counts too: an array handed to a native costs its
|
|
326
|
+
* length, and `E.Range` its count. A synthetic 3,000-territory board with 40 players' hands and
|
|
327
|
+
* special units (the test mini-bundle) takes about 0.49M steps (about 25 ms); this is about 60 times that.
|
|
328
|
+
* Measured, it ends a runaway read in well under a second: a nested-loop bomb in about 0.4 s, and
|
|
329
|
+
* one that repeats `E.Sa(E.Range(0,1e6))` in about 0.3 s.
|
|
330
|
+
*/
|
|
331
|
+
export const DEFAULT_MAX_STEPS = 30_000_000;
|
|
332
|
+
/**
|
|
333
|
+
* Wall-clock milliseconds per `readClass` (or per shared {@link ReadBudget}): the backstop for host
|
|
334
|
+
* work the step count does not see. A legitimate read of the large synthetic board takes about 25 ms.
|
|
335
|
+
*/
|
|
336
|
+
export const DEFAULT_MAX_MILLIS = 5_000;
|
|
337
|
+
/** The clock is read once every this many steps. */
|
|
338
|
+
const CLOCK_EVERY = 1024;
|
|
339
|
+
/**
|
|
340
|
+
* Lexical function nesting allowed (a function inside a function inside …). A name lookup walks every
|
|
341
|
+
* enclosing scope, so without a cap one step could cost hundreds of lookups; real readers nest a few deep.
|
|
342
|
+
*/
|
|
343
|
+
export const MAX_NESTING = 32;
|
|
344
|
+
/** The longest message kept for a thrown value (`reader threw: …`). */
|
|
345
|
+
export const MAX_THROW_MESSAGE = 200;
|
|
346
|
+
/** Interpreted call depth per `readClass`; real readers nest a few dozen deep at most. */
|
|
347
|
+
const DEFAULT_MAX_DEPTH = 256;
|
|
348
|
+
/** Steps charged when a constructor's failure is kept on the object (`$ctorError`) rather than thrown. */
|
|
349
|
+
const CTOR_FAILURE_STEPS = 20;
|
|
350
|
+
/** Keys that lead from any value to its prototype or constructor: never read or written. */
|
|
351
|
+
const FORBIDDEN_KEYS = new Set(['constructor', '__proto__', 'prototype']);
|
|
352
|
+
/**
|
|
353
|
+
* Object.prototype's member names (the legacy `__defineGetter__` family included) plus `toJSON`.
|
|
354
|
+
* Written onto a decoded object they would shadow the host member with a value that is not
|
|
355
|
+
* callable, so `String(obj)`, `obj.hasOwnProperty(…)`, `JSON.stringify` or loose equality in a
|
|
356
|
+
* consumer (or the interpreter) would throw. Never written.
|
|
357
|
+
*/
|
|
358
|
+
const SHADOWING_KEYS = new Set(['toJSON', ...Object.getOwnPropertyNames(Object.prototype)].filter((k) => !FORBIDDEN_KEYS.has(k)));
|
|
359
|
+
/** Operators that compare without converting an object operand (`==` / `!=` go through `looseEquals`). */
|
|
360
|
+
const EQUALITY_OPS = new Set(['===', '!==', '==', '!=']);
|
|
361
|
+
/** Operators that compare two string operands as strings (`==` / `!=` are charged in `looseEquals`). */
|
|
362
|
+
const STRING_COMPARE_OPS = new Set(['===', '!==', '<', '<=', '>', '>=']);
|
|
363
|
+
/**
|
|
364
|
+
* The longest string `+` may build. Real readers build only short strings (names, messages); without
|
|
365
|
+
* a cap, repeated doubling reaches the host's string limit (a RangeError) or exhausts the heap.
|
|
366
|
+
*/
|
|
367
|
+
const MAX_STRING = 1_000_000;
|
|
368
|
+
/**
|
|
369
|
+
* A canonical array index (`"0"`, `"12"`, not `"01"` or `"1.0"`). No index has more than ten digits, so a
|
|
370
|
+
* longer key is refused before the pattern test, which would otherwise scan the whole key.
|
|
371
|
+
*/
|
|
372
|
+
const isIndex = (k) => k.length <= 10 && /^(?:0|[1-9]\d*)$/.test(k);
|
|
373
|
+
// ---------------------------------------------------------------------------
|
|
374
|
+
// Runtime values
|
|
375
|
+
class ClassRef {
|
|
376
|
+
name;
|
|
377
|
+
constructor(name) {
|
|
378
|
+
this.name = name;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
class Closure {
|
|
382
|
+
node;
|
|
383
|
+
scope;
|
|
384
|
+
where;
|
|
385
|
+
constructor(node, scope, where) {
|
|
386
|
+
this.node = node;
|
|
387
|
+
this.scope = scope;
|
|
388
|
+
this.where = where;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
/** What `Scope.lookup` returns for a name no enclosing scope declares. */
|
|
392
|
+
const UNDECLARED = Symbol('undeclared');
|
|
393
|
+
class Scope {
|
|
394
|
+
parent;
|
|
395
|
+
vars = new Map();
|
|
396
|
+
/** Enclosing scopes: a function's scope is one deeper than the scope its closure was made in. */
|
|
397
|
+
depth;
|
|
398
|
+
constructor(parent = null) {
|
|
399
|
+
this.parent = parent;
|
|
400
|
+
this.depth = parent ? parent.depth + 1 : 0;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* The value of the nearest declaration of `name`, or UNDECLARED; `walked` is called with the number
|
|
404
|
+
* of scopes visited, so the caller can charge the lookup. Iterative: no host recursion per scope.
|
|
405
|
+
*/
|
|
406
|
+
lookup(name, walked) {
|
|
407
|
+
let n = 0;
|
|
408
|
+
for (let s = this; s; s = s.parent) {
|
|
409
|
+
n++;
|
|
410
|
+
if (s.vars.has(name)) {
|
|
411
|
+
walked(n);
|
|
412
|
+
return s.vars.get(name);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
walked(n);
|
|
416
|
+
return UNDECLARED;
|
|
417
|
+
}
|
|
418
|
+
hasOwn(name) {
|
|
419
|
+
return this.vars.has(name);
|
|
420
|
+
}
|
|
421
|
+
declare(name, value) {
|
|
422
|
+
this.vars.set(name, value);
|
|
423
|
+
}
|
|
424
|
+
/** Assign to the nearest scope that declares `name` (else this one); returns the scopes visited. */
|
|
425
|
+
assign(name, value) {
|
|
426
|
+
let n = 1;
|
|
427
|
+
let s = this;
|
|
428
|
+
while (s && !s.vars.has(name)) {
|
|
429
|
+
s = s.parent;
|
|
430
|
+
n++;
|
|
431
|
+
}
|
|
432
|
+
(s ?? this).vars.set(name, value);
|
|
433
|
+
return n;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const isObject = (v) => typeof v === 'object' && v !== null;
|
|
437
|
+
/** Descend from a parsed expression to the function expression that starts it. */
|
|
438
|
+
function leadingFunction(node) {
|
|
439
|
+
let n = node;
|
|
440
|
+
while (n) {
|
|
441
|
+
switch (n.type) {
|
|
442
|
+
case 'FunctionExpression':
|
|
443
|
+
return n;
|
|
444
|
+
case 'SequenceExpression':
|
|
445
|
+
n = n.expressions[0];
|
|
446
|
+
break;
|
|
447
|
+
case 'CallExpression':
|
|
448
|
+
n = n.callee;
|
|
449
|
+
break;
|
|
450
|
+
case 'MemberExpression':
|
|
451
|
+
n = n.object;
|
|
452
|
+
break;
|
|
453
|
+
case 'BinaryExpression':
|
|
454
|
+
case 'LogicalExpression':
|
|
455
|
+
case 'AssignmentExpression':
|
|
456
|
+
n = n.left;
|
|
457
|
+
break;
|
|
458
|
+
case 'ConditionalExpression':
|
|
459
|
+
n = n.test;
|
|
460
|
+
break;
|
|
461
|
+
default:
|
|
462
|
+
return null;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
/** Evaluates a bundle's reader functions against codec readers. */
|
|
468
|
+
export class BundleInterpreter {
|
|
469
|
+
bundle;
|
|
470
|
+
opts;
|
|
471
|
+
version;
|
|
472
|
+
dialect;
|
|
473
|
+
wrappers;
|
|
474
|
+
/** Resolved functions by `Cls.fn` / `new Cls`: a hit, `null` (no constructor) or the cached failure. */
|
|
475
|
+
fnCache = new Map();
|
|
476
|
+
defs = null;
|
|
477
|
+
typeIndex = null;
|
|
478
|
+
maxIterations;
|
|
479
|
+
maxSteps;
|
|
480
|
+
maxDepth;
|
|
481
|
+
maxMillis;
|
|
482
|
+
now;
|
|
483
|
+
steps = 0;
|
|
484
|
+
depth = 0;
|
|
485
|
+
/** When this read must end (the interpreter's clock), and the step count at which the clock is next read. */
|
|
486
|
+
deadline = Infinity;
|
|
487
|
+
nextClock = 0;
|
|
488
|
+
/** One class value per name (see `classRef`). */
|
|
489
|
+
classRefs = new Map();
|
|
490
|
+
/** Statics read as data, classified once each (see `staticData`). */
|
|
491
|
+
staticCache = new Map();
|
|
492
|
+
/** `reader threw: …` per throw site, built once (see `throwMessage`). */
|
|
493
|
+
throwMessages = new WeakMap();
|
|
494
|
+
constructor(bundle, opts = {}) {
|
|
495
|
+
this.bundle = bundle;
|
|
496
|
+
this.opts = opts;
|
|
497
|
+
this.version = opts.version ?? PROTOCOL_VERSION;
|
|
498
|
+
this.maxIterations = opts.maxIterations ?? 1e6;
|
|
499
|
+
this.maxSteps = opts.maxSteps ?? DEFAULT_MAX_STEPS;
|
|
500
|
+
this.maxDepth = opts.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
501
|
+
this.maxMillis = opts.maxMillis ?? DEFAULT_MAX_MILLIS;
|
|
502
|
+
this.now = opts.now ?? (() => performance.now());
|
|
503
|
+
const d = opts.dialect ?? {};
|
|
504
|
+
this.dialect = {
|
|
505
|
+
readerMethods: { ...DEFAULT_DIALECT.readerMethods, ...d.readerMethods },
|
|
506
|
+
statics: { ...DEFAULT_DIALECT.statics, ...d.statics },
|
|
507
|
+
wrappers: d.wrappers ?? DEFAULT_DIALECT.wrappers,
|
|
508
|
+
};
|
|
509
|
+
this.wrappers = new Set(this.dialect.wrappers);
|
|
510
|
+
}
|
|
511
|
+
/** The class var for a registered type name, or the argument itself if it is a var. */
|
|
512
|
+
resolveVar(typeNameOrVar) {
|
|
513
|
+
const v = this.bundle.varOf.get(typeNameOrVar);
|
|
514
|
+
if (v)
|
|
515
|
+
return v;
|
|
516
|
+
if (this.bundle.typeNameOf.has(typeNameOrVar) || !typeNameOrVar.includes('.'))
|
|
517
|
+
return typeNameOrVar;
|
|
518
|
+
throw new InterpError('unknown-class', `no class registered as ${typeNameOrVar}`);
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Read one instance of a class (`<Var>.Ha(reader, null, version)`). With `budget`, the read draws on
|
|
522
|
+
* that shared step count (and records what it spent there) instead of a fresh one.
|
|
523
|
+
*/
|
|
524
|
+
readClass(typeNameOrVar, reader, budget) {
|
|
525
|
+
const cls = this.resolveVar(typeNameOrVar);
|
|
526
|
+
return this.budgeted(budget, () => this.callStatic(cls, 'Ha', [reader, null, this.version]));
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Run interpreted code under one step and depth budget: a fresh one, or `budget`'s count continued
|
|
530
|
+
* (and what was spent recorded there). Every entry into interpreted code goes through here.
|
|
531
|
+
*/
|
|
532
|
+
budgeted(budget, run) {
|
|
533
|
+
this.steps = budget && Number.isFinite(budget.spent) && budget.spent > 0 ? budget.spent : 0;
|
|
534
|
+
this.depth = 0;
|
|
535
|
+
// One deadline per read, or per shared budget: its first read records when it started.
|
|
536
|
+
let started = this.now();
|
|
537
|
+
if (budget) {
|
|
538
|
+
if (typeof budget.startedAt === 'number' && Number.isFinite(budget.startedAt))
|
|
539
|
+
started = budget.startedAt;
|
|
540
|
+
else
|
|
541
|
+
budget.startedAt = started;
|
|
542
|
+
}
|
|
543
|
+
this.deadline = started + this.maxMillis;
|
|
544
|
+
this.nextClock = this.steps + CLOCK_EVERY;
|
|
545
|
+
try {
|
|
546
|
+
return run();
|
|
547
|
+
}
|
|
548
|
+
catch (e) {
|
|
549
|
+
// The depth limit should always fire first; this keeps a native stack overflow an InterpError too.
|
|
550
|
+
// Any other host RangeError (an invalid string or array length) is a runaway read too.
|
|
551
|
+
if (e instanceof RangeError) {
|
|
552
|
+
throw new InterpError('budget', /call stack/i.test(e.message) ? 'reader recursed past the host stack' : `read ran past a host limit: ${e.message}`);
|
|
553
|
+
}
|
|
554
|
+
throw e;
|
|
555
|
+
}
|
|
556
|
+
finally {
|
|
557
|
+
if (budget)
|
|
558
|
+
budget.spent = this.steps;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Check the built-in reader helpers (the dialect's statics on {@link READER_HELPERS}) against
|
|
563
|
+
* the bundle's own definitions of the same names: each definition is evaluated on a few probe
|
|
564
|
+
* byte strings and must read the same value, call its item readers in the same order and read
|
|
565
|
+
* the same number of bytes as the built-in. The built-ins shadow the bundle's definitions, so a
|
|
566
|
+
* new client that gives a name to another helper would otherwise decode every field through the
|
|
567
|
+
* wrong read without an error (#131). Every definition counts: `P.x=function`, an alias
|
|
568
|
+
* (`P.x=Q.y`, followed to Q.y's definition) and a property of an object literal assigned to P
|
|
569
|
+
* (`P={x:function…}`); a definition the interpreter cannot evaluate, or in a form it cannot
|
|
570
|
+
* follow, is unverified, not a mismatch, and so is a helper that takes item readers but was never
|
|
571
|
+
* seen reading an item (#148).
|
|
572
|
+
*/
|
|
573
|
+
verifyDialect() {
|
|
574
|
+
const out = { verified: [], unverified: [], mismatched: [] };
|
|
575
|
+
const reasons = {};
|
|
576
|
+
const natives = Object.hasOwn(this.dialect.statics, READER_HELPERS) ? this.dialect.statics[READER_HELPERS] : {};
|
|
577
|
+
// The bundle's definitions run like any interpreted code: contained, and under one step budget
|
|
578
|
+
// shared by the whole check, so a hostile bundle cannot spend more than one read's worth here.
|
|
579
|
+
// Past the budget, a probe is unevaluable (the helper unverified), never a mismatch.
|
|
580
|
+
const budget = { spent: 0 };
|
|
581
|
+
const forms = this.helperForms(READER_HELPERS, Object.keys(natives), budget);
|
|
582
|
+
// The required helpers are probed first: a runaway definition of another cannot spend the budget
|
|
583
|
+
// they need. Object literals assigned to P are parsed under a bound of their own (see helperForms).
|
|
584
|
+
const order = [...forms.keys()].sort((a, b) => Number(REQUIRED_HELPERS.includes(b)) - Number(REQUIRED_HELPERS.includes(a)) || (a < b ? -1 : 1));
|
|
585
|
+
for (const name of order) {
|
|
586
|
+
const native = natives[name];
|
|
587
|
+
const key = `${READER_HELPERS}.${name}`;
|
|
588
|
+
let mismatch = false;
|
|
589
|
+
let why;
|
|
590
|
+
for (const form of forms.get(name)) {
|
|
591
|
+
if ('unseen' in form) {
|
|
592
|
+
why ??= form.unseen;
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
let informative = 0;
|
|
596
|
+
let ran = false;
|
|
597
|
+
for (const probe of DIALECT_PROBES) {
|
|
598
|
+
const mine = runProbe(probe, native.length, (args) => native(...args));
|
|
599
|
+
const theirs = runProbe(probe, native.length, (args) => this.budgeted(budget, () => this.invoke(form.node, args, new Scope(), form.where)));
|
|
600
|
+
if (theirs.kind !== 'unevaluable')
|
|
601
|
+
ran = true;
|
|
602
|
+
const verdict = compareProbe(mine, theirs, native.length);
|
|
603
|
+
if (verdict === 'differ')
|
|
604
|
+
mismatch = true;
|
|
605
|
+
else if (verdict === 'informative')
|
|
606
|
+
informative++;
|
|
607
|
+
}
|
|
608
|
+
if (!informative) {
|
|
609
|
+
why ??= !ran
|
|
610
|
+
? 'its definition cannot be evaluated here'
|
|
611
|
+
: native.length > 1
|
|
612
|
+
? 'its definition was never seen reading an item (it builds a client collection this check cannot evaluate)'
|
|
613
|
+
: 'no probe showed it reading alike';
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (mismatch)
|
|
617
|
+
out.mismatched.push(key);
|
|
618
|
+
else if (why === undefined)
|
|
619
|
+
out.verified.push(key);
|
|
620
|
+
else {
|
|
621
|
+
out.unverified.push(key);
|
|
622
|
+
reasons[key] = why;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
// A required helper the scan found no definition of, though the bundle references it (`P.Ya`,
|
|
626
|
+
// `P["Ya"]`): it is defined in a form the scan does not know (`P["Ya"]=…`, `Object.assign(P,…)`),
|
|
627
|
+
// and the built-in would decode every read through it unchecked. Absent from the check is not
|
|
628
|
+
// verified (#148).
|
|
629
|
+
const src = this.bundle.src;
|
|
630
|
+
const esc = READER_HELPERS.replace(/\$/g, '\\$');
|
|
631
|
+
for (const name of REQUIRED_HELPERS) {
|
|
632
|
+
if (forms.has(name) || !Object.hasOwn(natives, name))
|
|
633
|
+
continue;
|
|
634
|
+
const ref = new RegExp(`(?<![\\w$.])${esc}\\s*(?:\\.\\s*${name}(?![\\w$])|\\[\\s*(["'\`])${name}\\1\\s*\\])`);
|
|
635
|
+
if (!ref.test(src))
|
|
636
|
+
continue;
|
|
637
|
+
const key = `${READER_HELPERS}.${name}`;
|
|
638
|
+
out.unverified.push(key);
|
|
639
|
+
reasons[key] = 'the bundle reads through it, but no definition was found in a form this check can follow';
|
|
640
|
+
}
|
|
641
|
+
for (const list of [out.verified, out.unverified, out.mismatched])
|
|
642
|
+
list.sort();
|
|
643
|
+
if (Object.keys(reasons).length)
|
|
644
|
+
out.reasons = reasons;
|
|
645
|
+
return out;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Every definition of each of `names` on `cls` in the bundle, found in one pass over the source:
|
|
649
|
+
* `cls.name=function` sites (parsed, the parsing charged to `budget`), aliases `cls.name=X.y`
|
|
650
|
+
* (followed to X.y's definition) and properties of object literals assigned to `cls`
|
|
651
|
+
* (`cls={name:function…}`). Anything else assigned to one of the names (a variable, an
|
|
652
|
+
* expression, a getter) is a form the check cannot follow. A name with no definition is absent.
|
|
653
|
+
*/
|
|
654
|
+
helperForms(cls, names, budget) {
|
|
655
|
+
const wanted = new Set(names);
|
|
656
|
+
const out = new Map();
|
|
657
|
+
const add = (name, form) => {
|
|
658
|
+
const list = out.get(name);
|
|
659
|
+
if (list)
|
|
660
|
+
list.push(form);
|
|
661
|
+
else
|
|
662
|
+
out.set(name, [form]);
|
|
663
|
+
};
|
|
664
|
+
const parseFn = (at, where) => {
|
|
665
|
+
try {
|
|
666
|
+
return { node: this.budgeted(budget, () => this.parseFunctionAt(at, where)), where };
|
|
667
|
+
}
|
|
668
|
+
catch {
|
|
669
|
+
return { unseen: 'its definition does not parse within the budget' };
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
const src = this.bundle.src;
|
|
673
|
+
const esc = cls.replace(/\$/g, '\\$');
|
|
674
|
+
// `P.name = <rhs>`: not `==`, not a member of something else (`x.P.name`).
|
|
675
|
+
for (const m of src.matchAll(new RegExp(`(?<![\\w$.])${esc}\\.([\\w$]+)\\s*=(?!=)\\s*`, 'g'))) {
|
|
676
|
+
const name = m[1];
|
|
677
|
+
if (!wanted.has(name))
|
|
678
|
+
continue;
|
|
679
|
+
const at = m.index + m[0].length;
|
|
680
|
+
const where = `${cls}.${name}`;
|
|
681
|
+
if (/^function\b/.test(src.slice(at, at + 9))) {
|
|
682
|
+
add(name, parseFn(at, where));
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
// An alias to another class's static: verified as that definition.
|
|
686
|
+
const alias = /^([\w$]+)\.([\w$]+)\s*(?=[;,})\n]|$)/.exec(src.slice(at, at + 200));
|
|
687
|
+
const sites = alias ? this.definitions().statics.get(`${alias[1]}.${alias[2]}`) : undefined;
|
|
688
|
+
if (alias && sites?.length) {
|
|
689
|
+
add(name, parseFn(sites[0], `${alias[1]}.${alias[2]}`));
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
// The assigned text is never quoted: it is the bundle's, not ours.
|
|
693
|
+
add(name, { unseen: 'it is assigned in a form this check cannot follow (not a function or an alias of one)' });
|
|
694
|
+
}
|
|
695
|
+
// `P = { name: function… }` (with `var`, or in a sequence). Each parse is host work acorn finishes
|
|
696
|
+
// before it can be charged, so the scan has its own bound, one read's worth of text over at most
|
|
697
|
+
// MAX_LITERAL_SITES sites: each parse is handed only the text left in that bound, every attempt
|
|
698
|
+
// (a failed one up to where it failed) is charged, and the scan stops when either runs out. It
|
|
699
|
+
// never charges the budget the definitions are parsed and probed with, so a large literal cannot
|
|
700
|
+
// starve the count helpers. A scan cut short could have missed a definition: every helper is then
|
|
701
|
+
// unverified, never verified on the definitions seen before it.
|
|
702
|
+
let litText = 0;
|
|
703
|
+
let litSites = 0;
|
|
704
|
+
let cutShort = false;
|
|
705
|
+
for (const m of src.matchAll(new RegExp(`(?<![\\w$.])${esc}\\s*=\\s*(?=\\{)`, 'g'))) {
|
|
706
|
+
const room = this.maxSteps - litText;
|
|
707
|
+
if (litSites >= MAX_LITERAL_SITES || room <= 0) {
|
|
708
|
+
cutShort = true;
|
|
709
|
+
break;
|
|
710
|
+
}
|
|
711
|
+
litSites++;
|
|
712
|
+
const at = m.index + m[0].length;
|
|
713
|
+
// The same offsets as the source (a prefix of it), so the nodes found point into the bundle.
|
|
714
|
+
const end = Math.min(src.length, at + room);
|
|
715
|
+
let obj;
|
|
716
|
+
try {
|
|
717
|
+
obj = parseExpressionAt(src.slice(0, end), at, { ecmaVersion: 'latest' });
|
|
718
|
+
}
|
|
719
|
+
catch (e) {
|
|
720
|
+
const raised = e.raisedAt;
|
|
721
|
+
// A failure with no position (a host stack overflow) is charged the whole of its room.
|
|
722
|
+
const stop = typeof raised === 'number' && raised > at ? Math.min(raised, end) : end;
|
|
723
|
+
litText += Math.max(1, stop - at);
|
|
724
|
+
// It ran into the end of its room (a literal this check cannot read), or spent the scan's bound.
|
|
725
|
+
if ((stop >= end && end < src.length) || litText >= this.maxSteps) {
|
|
726
|
+
cutShort = true;
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
litText += Math.max(1, obj.end - at);
|
|
732
|
+
if (obj.end >= end && end < src.length) {
|
|
733
|
+
cutShort = true;
|
|
734
|
+
break;
|
|
735
|
+
}
|
|
736
|
+
if (obj.type !== 'ObjectExpression')
|
|
737
|
+
continue;
|
|
738
|
+
for (const prop of obj.properties) {
|
|
739
|
+
if (prop.type !== 'Property' || prop.computed)
|
|
740
|
+
continue;
|
|
741
|
+
const name = prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' ? String(prop.key.value) : undefined;
|
|
742
|
+
if (name === undefined || !wanted.has(name))
|
|
743
|
+
continue;
|
|
744
|
+
const where = `${cls}.${name}`;
|
|
745
|
+
if (prop.kind === 'init' && !prop.method && prop.value.type === 'FunctionExpression')
|
|
746
|
+
add(name, { node: prop.value, where });
|
|
747
|
+
else if (prop.kind === 'init' && prop.value.type === 'MemberExpression' && !prop.value.computed &&
|
|
748
|
+
prop.value.object.type === 'Identifier' && prop.value.property.type === 'Identifier') {
|
|
749
|
+
const sites = this.definitions().statics.get(`${prop.value.object.name}.${prop.value.property.name}`);
|
|
750
|
+
add(name, sites?.length
|
|
751
|
+
? parseFn(sites[0], `${prop.value.object.name}.${prop.value.property.name}`)
|
|
752
|
+
: { unseen: 'it is an object-literal property this check cannot follow' });
|
|
753
|
+
}
|
|
754
|
+
else
|
|
755
|
+
add(name, { unseen: 'it is an object-literal property this check cannot follow' });
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
if (cutShort) {
|
|
759
|
+
for (const name of names) {
|
|
760
|
+
add(name, { unseen: `the bundle assigns ${cls} more object literals than this check reads, so a definition could go unseen` });
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
return out;
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* The fields a class's reader fills from another class's reader, in read order — found by
|
|
767
|
+
* reading the reader's source, not by running it, so a field the reply leaves absent (null)
|
|
768
|
+
* is still named. Follows the reader into its own class's statics (`Lg.Ha` → `Lg.R`). Empty
|
|
769
|
+
* when either class is unknown or no field is read from it.
|
|
770
|
+
*/
|
|
771
|
+
fieldsReadAs(ownerTypeOrVar, fieldType) {
|
|
772
|
+
const fieldVar = this.bundle.varOf.get(fieldType);
|
|
773
|
+
let ownerVar;
|
|
774
|
+
try {
|
|
775
|
+
ownerVar = this.resolveVar(ownerTypeOrVar);
|
|
776
|
+
}
|
|
777
|
+
catch {
|
|
778
|
+
return [];
|
|
779
|
+
}
|
|
780
|
+
if (!fieldVar)
|
|
781
|
+
return [];
|
|
782
|
+
const out = new Set();
|
|
783
|
+
const seen = new Set();
|
|
784
|
+
const where = `${ownerVar}.Ha`;
|
|
785
|
+
const visit = (fn, depth) => {
|
|
786
|
+
if (seen.has(fn) || depth > 3)
|
|
787
|
+
return;
|
|
788
|
+
seen.add(fn);
|
|
789
|
+
let node;
|
|
790
|
+
try {
|
|
791
|
+
node = this.resolveStatic(ownerVar, fn).node;
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const charge = (n) => this.spend(n, where, node.start);
|
|
797
|
+
const found = fieldAssignments(node, fieldVar, charge);
|
|
798
|
+
for (const f of found)
|
|
799
|
+
out.add(f);
|
|
800
|
+
if (!found.length)
|
|
801
|
+
for (const next of ownStaticCalls(node, ownerVar, charge))
|
|
802
|
+
visit(next, depth + 1);
|
|
803
|
+
};
|
|
804
|
+
// Parsing a reader, and walking it, is charged to a step budget like any other entry into the bundle.
|
|
805
|
+
this.budgeted(undefined, () => visit('Ha', 0));
|
|
806
|
+
return [...out];
|
|
807
|
+
}
|
|
808
|
+
// -------------------------------------------------------------------------
|
|
809
|
+
// Resolution
|
|
810
|
+
/**
|
|
811
|
+
* Parse the function expression at `pos`. The characters acorn consumed are charged to the step
|
|
812
|
+
* budget: each definition is parsed once per interpreter (see {@link fnCache}), but a hostile
|
|
813
|
+
* bundle could otherwise make one step parse megabytes.
|
|
814
|
+
*/
|
|
815
|
+
parseFunctionAt(pos, where) {
|
|
816
|
+
let node;
|
|
817
|
+
let failure;
|
|
818
|
+
let cost;
|
|
819
|
+
try {
|
|
820
|
+
node = parseExpressionAt(this.bundle.src, pos, { ecmaVersion: 'latest' });
|
|
821
|
+
cost = Math.max(1, node.end - pos);
|
|
822
|
+
}
|
|
823
|
+
catch (e) {
|
|
824
|
+
const at = e.raisedAt;
|
|
825
|
+
cost = typeof at === 'number' && at > pos ? at - pos : 1;
|
|
826
|
+
failure = new InterpError('parse', `cannot parse function: ${e.message}`, where, pos);
|
|
827
|
+
}
|
|
828
|
+
// A parse is host work that can only be charged once it is over. One that costs more than a
|
|
829
|
+
// whole read's budget would end every read in a budget error, which is never cached, and be
|
|
830
|
+
// parsed again each time: it is a parse failure instead, which the callers cache.
|
|
831
|
+
if (cost > this.maxSteps) {
|
|
832
|
+
throw new InterpError('parse', `function too large to interpret within one read (${cost} characters)`, where, pos);
|
|
833
|
+
}
|
|
834
|
+
this.spend(cost, where, pos);
|
|
835
|
+
if (failure || !node)
|
|
836
|
+
throw failure ?? new InterpError('parse', 'no function expression', where, pos);
|
|
837
|
+
const fn = leadingFunction(node);
|
|
838
|
+
if (!fn || fn.start !== pos)
|
|
839
|
+
throw new InterpError('parse', 'no function expression', where, pos);
|
|
840
|
+
return fn;
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* The bundle's definition sites, found in one pass the first time any function is resolved, so a
|
|
844
|
+
* lookup never rescans the source: a scan is host work in the bundle's length that the step budget
|
|
845
|
+
* cannot see, and before this a loop of failing lookups (a constructor swallows the error) rescanned
|
|
846
|
+
* the whole bundle on every iteration. Names are the minifier's ASCII identifiers (`[\w$]+`).
|
|
847
|
+
*/
|
|
848
|
+
definitions() {
|
|
849
|
+
if (this.defs)
|
|
850
|
+
return this.defs;
|
|
851
|
+
const { src, typeNameOf } = this.bundle;
|
|
852
|
+
const statics = new Map();
|
|
853
|
+
// `Cls.fn = function`: the lookahead leaves `function` unconsumed, so no definition hides another.
|
|
854
|
+
for (const m of src.matchAll(/(?<![\w$.])([\w$]+)\.([\w$]+)\s*=\s*(?=function\b)/g)) {
|
|
855
|
+
const key = `${m[1]}.${m[2]}`;
|
|
856
|
+
const at = m.index + m[0].length;
|
|
857
|
+
const list = statics.get(key);
|
|
858
|
+
if (list)
|
|
859
|
+
list.push(at);
|
|
860
|
+
else
|
|
861
|
+
statics.set(key, [at]);
|
|
862
|
+
}
|
|
863
|
+
const ctors = new Map();
|
|
864
|
+
for (const m of src.matchAll(/function ([\w$]+)\(/g))
|
|
865
|
+
if (!ctors.has(m[1]))
|
|
866
|
+
ctors.set(m[1], m.index);
|
|
867
|
+
// Where each class's first registration (`W["<type name>"]=<var>;`) sits.
|
|
868
|
+
const registrations = new Map();
|
|
869
|
+
for (const m of src.matchAll(REGISTRATION)) {
|
|
870
|
+
if (!registrations.has(m[2]) && typeNameOf.get(m[2]) === m[1])
|
|
871
|
+
registrations.set(m[2], m.index);
|
|
872
|
+
}
|
|
873
|
+
this.defs = { statics, ctors, registrations };
|
|
874
|
+
return this.defs;
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* The bundle's class structure — static data sites, superclass links, the class-link prototype
|
|
878
|
+
* field — indexed in one pass the first time a read needs it (a static read, `instanceof`, a member
|
|
879
|
+
* a decoded object lacks), so a bundle whose readers never check a type does not pay for it.
|
|
880
|
+
*/
|
|
881
|
+
types() {
|
|
882
|
+
if (this.typeIndex)
|
|
883
|
+
return this.typeIndex;
|
|
884
|
+
const { src, typeNameOf } = this.bundle;
|
|
885
|
+
const { ctors, registrations } = this.definitions();
|
|
886
|
+
// Every other `Cls.key = …` (not `==`, `=>` or a function): the candidates for a static's data. A
|
|
887
|
+
// site inside a function body is indexed too, so a static assigned more than one way is never a constant.
|
|
888
|
+
const assigns = new Map();
|
|
889
|
+
for (const m of src.matchAll(/(?<![\w$.])([\w$]+)\.([\w$]+)\s*=(?![=>])\s*(?!function\b)/g)) {
|
|
890
|
+
const key = `${m[1]}.${m[2]}`;
|
|
891
|
+
const list = assigns.get(key);
|
|
892
|
+
const at = m.index + m[0].length;
|
|
893
|
+
if (list)
|
|
894
|
+
list.push(at);
|
|
895
|
+
else
|
|
896
|
+
assigns.set(key, [at]);
|
|
897
|
+
}
|
|
898
|
+
const updated = new Set();
|
|
899
|
+
for (const m of src.matchAll(/(?<![\w$.])([\w$]+)\.([\w$]+)\s*(?:\+\+|--|(?:\*\*|<<|>>>?|\|\||&&|\?\?|[-+*/%&|^])=)/g))
|
|
900
|
+
updated.add(`${m[1]}.${m[2]}`);
|
|
901
|
+
for (const m of src.matchAll(/(?:\+\+|--)\s*([\w$]+)\.([\w$]+)/g))
|
|
902
|
+
updated.add(`${m[1]}.${m[2]}`);
|
|
903
|
+
// Prototypes: who has one, and who builds theirs from another class's. The builder (the compiler's
|
|
904
|
+
// `extend`, minified) is whichever function most prototypes are built with, so a stray call cannot
|
|
905
|
+
// pose as a superclass link.
|
|
906
|
+
const protoOwners = new Set();
|
|
907
|
+
const built = [];
|
|
908
|
+
const builders = new Map();
|
|
909
|
+
for (const m of src.matchAll(/(?<![\w$.])([\w$]+)\.prototype\s*=(?!=)\s*(?:([\w$]+)\(\s*([\w$]+)\.prototype\s*,)?/g)) {
|
|
910
|
+
protoOwners.add(m[1]);
|
|
911
|
+
if (m[2] && m[3]) {
|
|
912
|
+
built.push([m[2], m[1], m[3]]);
|
|
913
|
+
builders.set(m[2], (builders.get(m[2]) ?? 0) + 1);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
let builder;
|
|
917
|
+
for (const [fn, n] of builders)
|
|
918
|
+
if (builder === undefined || n > builders.get(builder))
|
|
919
|
+
builder = fn;
|
|
920
|
+
const superOf = new Map();
|
|
921
|
+
for (const [fn, cls, sup] of built)
|
|
922
|
+
if (fn === builder && !superOf.has(cls))
|
|
923
|
+
superOf.set(cls, sup);
|
|
924
|
+
const classes = new Set([...ctors.keys(), ...registrations.keys(), ...typeNameOf.keys(), ...protoOwners]);
|
|
925
|
+
// The class-link field: the object-literal key whose value is a class with a prototype, for by far
|
|
926
|
+
// the most classes (each class's prototype names itself under it).
|
|
927
|
+
const linked = new Map();
|
|
928
|
+
for (const m of src.matchAll(/[{,]([\w$]+):([\w$]+)(?=\s*[,}])/g)) {
|
|
929
|
+
if (!protoOwners.has(m[2]))
|
|
930
|
+
continue;
|
|
931
|
+
const set = linked.get(m[1]);
|
|
932
|
+
if (set)
|
|
933
|
+
set.add(m[2]);
|
|
934
|
+
else
|
|
935
|
+
linked.set(m[1], new Set([m[2]]));
|
|
936
|
+
}
|
|
937
|
+
const ranked = [...linked].sort((a, b) => b[1].size - a[1].size);
|
|
938
|
+
const top = ranked[0];
|
|
939
|
+
const classLink = top && top[1].size >= 2 * (ranked[1]?.[1].size ?? 0) ? { key: top[0], classes: top[1] } : null;
|
|
940
|
+
this.typeIndex = { assigns, updated, classes, superOf, classLink };
|
|
941
|
+
return this.typeIndex;
|
|
942
|
+
}
|
|
943
|
+
/** The one class value per name, so `==`, `===` and `switch` compare classes as JS compares constructors. */
|
|
944
|
+
classRef(name) {
|
|
945
|
+
let ref = this.classRefs.get(name);
|
|
946
|
+
if (!ref)
|
|
947
|
+
this.classRefs.set(name, (ref = new ClassRef(name)));
|
|
948
|
+
return ref;
|
|
949
|
+
}
|
|
950
|
+
/**
|
|
951
|
+
* `Cls.key` read as data. A static whose every assignment is the same simple value — a number,
|
|
952
|
+
* string, boolean (`!0` / `!1`), null, a class, or an array of classes — reads as that value (an
|
|
953
|
+
* array afresh on each read, so no read can change another). A key a bundle class never assigns
|
|
954
|
+
* reads undefined, as in JS. Anything else (a static function, an expression, two different
|
|
955
|
+
* values, a key changed in place, a host global's member) is unsupported.
|
|
956
|
+
*/
|
|
957
|
+
staticData(cls, key, n, where) {
|
|
958
|
+
const id = `${cls}.${key}`;
|
|
959
|
+
let data = this.staticCache.get(id);
|
|
960
|
+
if (!data) {
|
|
961
|
+
data = this.classifyStatic(cls, key, id, where, n);
|
|
962
|
+
// Only a key the source names is kept: a computed key (`Cls["k" + i]`) can invent a new one per
|
|
963
|
+
// step, and keeping each would grow the cache without bound. Its answer is cheap to recompute.
|
|
964
|
+
if (this.namedStatic(id))
|
|
965
|
+
this.staticCache.set(id, data);
|
|
966
|
+
}
|
|
967
|
+
if ('unsupported' in data)
|
|
968
|
+
throw this.unsupported(`static read ${id}`, n, where);
|
|
969
|
+
if ('absent' in data)
|
|
970
|
+
return undefined;
|
|
971
|
+
if (Array.isArray(data.value)) {
|
|
972
|
+
this.spend(data.value.length, where, n.start);
|
|
973
|
+
return [...data.value];
|
|
974
|
+
}
|
|
975
|
+
return data.value;
|
|
976
|
+
}
|
|
977
|
+
/** Whether the source names `Cls.key` (an assignment, a static function or an update): a bounded set. */
|
|
978
|
+
namedStatic(id) {
|
|
979
|
+
const defs = this.types();
|
|
980
|
+
return defs.assigns.has(id) || defs.updated.has(id) || this.definitions().statics.has(id);
|
|
981
|
+
}
|
|
982
|
+
classifyStatic(cls, key, id, where, n) {
|
|
983
|
+
const defs = this.types();
|
|
984
|
+
const sites = defs.assigns.get(id);
|
|
985
|
+
if (this.definitions().statics.has(id) || defs.updated.has(id))
|
|
986
|
+
return { unsupported: true };
|
|
987
|
+
if (!sites) {
|
|
988
|
+
// A host global (Math, Array, …) has members of its own the bundle never assigns: not the
|
|
989
|
+
// bundle's to answer, so only a key the host object lacks too reads undefined. Accepted: `key in
|
|
990
|
+
// host` lets a bundle learn whether a host global has a member of that name (names only, no values).
|
|
991
|
+
const host = hostGlobal(cls);
|
|
992
|
+
if (host === undefined)
|
|
993
|
+
return defs.classes.has(cls) ? { absent: true } : { unsupported: true };
|
|
994
|
+
return host !== null && !(key in host) ? { absent: true } : { unsupported: true };
|
|
995
|
+
}
|
|
996
|
+
let value;
|
|
997
|
+
let source;
|
|
998
|
+
for (const at of sites) {
|
|
999
|
+
SIMPLE_STATIC.lastIndex = at;
|
|
1000
|
+
const m = SIMPLE_STATIC.exec(this.bundle.src);
|
|
1001
|
+
this.spend(1 + (m ? m[0].length : 0), where, n.start);
|
|
1002
|
+
if (!m)
|
|
1003
|
+
return { unsupported: true };
|
|
1004
|
+
const text = m[1];
|
|
1005
|
+
if (source === undefined) {
|
|
1006
|
+
const v = this.staticValue(text, defs);
|
|
1007
|
+
if (v === UNDECLARED)
|
|
1008
|
+
return { unsupported: true };
|
|
1009
|
+
value = v;
|
|
1010
|
+
source = text;
|
|
1011
|
+
}
|
|
1012
|
+
else if (text !== source) {
|
|
1013
|
+
return { unsupported: true };
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
return { value };
|
|
1017
|
+
}
|
|
1018
|
+
/** The value of a simple static's source text, or UNDECLARED when it names something other than a class. */
|
|
1019
|
+
staticValue(text, defs) {
|
|
1020
|
+
if (text === '!0' || text === 'true')
|
|
1021
|
+
return true;
|
|
1022
|
+
if (text === '!1' || text === 'false')
|
|
1023
|
+
return false;
|
|
1024
|
+
if (text === 'null')
|
|
1025
|
+
return null;
|
|
1026
|
+
if (text === 'undefined')
|
|
1027
|
+
return undefined;
|
|
1028
|
+
if (text[0] === '"' || text[0] === "'") {
|
|
1029
|
+
try {
|
|
1030
|
+
const lit = parseExpressionAt(text, 0, { ecmaVersion: 'latest' });
|
|
1031
|
+
return lit.type === 'Literal' && typeof lit.value === 'string' && lit.end === text.length ? lit.value : UNDECLARED;
|
|
1032
|
+
}
|
|
1033
|
+
catch {
|
|
1034
|
+
return UNDECLARED;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
if (/^-?(?:\d|\.\d)/.test(text)) {
|
|
1038
|
+
const v = Number(text);
|
|
1039
|
+
return Number.isNaN(v) ? UNDECLARED : v;
|
|
1040
|
+
}
|
|
1041
|
+
const isClass = (name) => defs.classes.has(name) && hostGlobal(name) === undefined;
|
|
1042
|
+
if (text[0] === '[') {
|
|
1043
|
+
const inner = text.slice(1, -1).trim();
|
|
1044
|
+
const names = inner ? inner.split(',').map((x) => x.trim()) : [];
|
|
1045
|
+
return names.every((x) => /^[A-Za-z_$][\w$]*$/.test(x) && isClass(x)) ? names.map((x) => this.classRef(x)) : UNDECLARED;
|
|
1046
|
+
}
|
|
1047
|
+
return isClass(text) ? this.classRef(text) : UNDECLARED;
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* `o instanceof cls`: true for an object the interpreter decoded as `cls` or as any subclass of it,
|
|
1051
|
+
* following the superclass links the bundle builds its prototypes with (exact type only when it
|
|
1052
|
+
* builds none); `Array` matches arrays. Each link walked is a step, and a cycle ends the walk.
|
|
1053
|
+
*/
|
|
1054
|
+
instanceOf(o, cls, n, where) {
|
|
1055
|
+
if (!(cls instanceof ClassRef))
|
|
1056
|
+
throw this.unsupported('instanceof of a non-class', n, where);
|
|
1057
|
+
if (Array.isArray(o))
|
|
1058
|
+
return cls.name === 'Array';
|
|
1059
|
+
// A decoded object is a plain object, so `o instanceof Object` is false for it (unlike JS).
|
|
1060
|
+
if (!isDecoded(o))
|
|
1061
|
+
return false;
|
|
1062
|
+
// The exact registered type first: two class vars registered under one type name both match an
|
|
1063
|
+
// object built as either (`classOf` gives back only the first var). The cached client bundle
|
|
1064
|
+
// registered each of its 2310 type names once when checked (2026-11): a guard, not a known case.
|
|
1065
|
+
if (o.$type === (this.bundle.typeNameOf.get(cls.name) ?? cls.name))
|
|
1066
|
+
return true;
|
|
1067
|
+
const { superOf } = this.types();
|
|
1068
|
+
const seen = new Set();
|
|
1069
|
+
for (let v = this.classOf(o); v !== undefined && !seen.has(v); v = superOf.get(v)) {
|
|
1070
|
+
this.spend(1, where, n.start);
|
|
1071
|
+
if (v === cls.name)
|
|
1072
|
+
return true;
|
|
1073
|
+
seen.add(v);
|
|
1074
|
+
}
|
|
1075
|
+
return false;
|
|
1076
|
+
}
|
|
1077
|
+
/** The class var a decoded object was constructed as. */
|
|
1078
|
+
classOf(o) {
|
|
1079
|
+
return this.bundle.varOf.get(o.$type) ?? o.$type;
|
|
1080
|
+
}
|
|
1081
|
+
/** `o[k]` for a decoded object: an own field, else its class when `k` is the class-link field, else undefined. */
|
|
1082
|
+
decodedMember(o, k) {
|
|
1083
|
+
const v = readMember(o, k);
|
|
1084
|
+
if (v !== undefined || Object.hasOwn(o, k))
|
|
1085
|
+
return v;
|
|
1086
|
+
const link = this.types().classLink;
|
|
1087
|
+
if (link && k === link.key) {
|
|
1088
|
+
const cls = this.classOf(o);
|
|
1089
|
+
if (link.classes.has(cls))
|
|
1090
|
+
return this.classRef(cls);
|
|
1091
|
+
}
|
|
1092
|
+
return undefined;
|
|
1093
|
+
}
|
|
1094
|
+
resolveStatic(cls, fn) {
|
|
1095
|
+
const where = `${cls}.${fn}`;
|
|
1096
|
+
const cached = this.fnCache.get(where);
|
|
1097
|
+
// An unparsable function's failure is cached, so it is parsed once per interpreter. A missing one is
|
|
1098
|
+
// not: its name can be computed (`Cls["f" + i]()`), so caching each would grow without bound, and the
|
|
1099
|
+
// lookup is one map read.
|
|
1100
|
+
if (cached instanceof InterpError)
|
|
1101
|
+
throw cached;
|
|
1102
|
+
if (cached)
|
|
1103
|
+
return cached;
|
|
1104
|
+
try {
|
|
1105
|
+
const sites = this.definitions().statics.get(where);
|
|
1106
|
+
if (!sites)
|
|
1107
|
+
throw new InterpError('no-definition', `no definition for ${where}`);
|
|
1108
|
+
// Prefer the definition that follows the class's registration.
|
|
1109
|
+
const from = this.definitions().registrations.get(cls) ?? 0;
|
|
1110
|
+
const at = sites.find((p) => p >= from) ?? sites[0];
|
|
1111
|
+
const resolved = { node: this.parseFunctionAt(at, where), where };
|
|
1112
|
+
this.fnCache.set(where, resolved);
|
|
1113
|
+
return resolved;
|
|
1114
|
+
}
|
|
1115
|
+
catch (e) {
|
|
1116
|
+
if (e instanceof InterpError && e.kind === 'parse')
|
|
1117
|
+
this.fnCache.set(where, e);
|
|
1118
|
+
throw e;
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
resolveCtor(cls) {
|
|
1122
|
+
const key = `new ${cls}`;
|
|
1123
|
+
const cached = this.fnCache.get(key);
|
|
1124
|
+
if (cached instanceof InterpError)
|
|
1125
|
+
throw cached;
|
|
1126
|
+
if (cached !== undefined)
|
|
1127
|
+
return cached;
|
|
1128
|
+
const at = this.definitions().ctors.get(cls);
|
|
1129
|
+
let resolved = null;
|
|
1130
|
+
try {
|
|
1131
|
+
if (at !== undefined)
|
|
1132
|
+
resolved = { node: this.parseFunctionAt(at, key), where: key };
|
|
1133
|
+
}
|
|
1134
|
+
catch (e) {
|
|
1135
|
+
if (e instanceof InterpError && e.kind === 'parse')
|
|
1136
|
+
this.fnCache.set(key, e);
|
|
1137
|
+
throw e;
|
|
1138
|
+
}
|
|
1139
|
+
this.fnCache.set(key, resolved);
|
|
1140
|
+
return resolved;
|
|
1141
|
+
}
|
|
1142
|
+
// -------------------------------------------------------------------------
|
|
1143
|
+
// Calls
|
|
1144
|
+
callStatic(cls, fn, args) {
|
|
1145
|
+
// Own entries only: an inherited `constructor` would hand over Object and, through it, Function.
|
|
1146
|
+
const table = Object.hasOwn(this.dialect.statics, cls) ? this.dialect.statics[cls] : undefined;
|
|
1147
|
+
const native = table && Object.hasOwn(table, fn) ? table[fn] : undefined;
|
|
1148
|
+
if (native) {
|
|
1149
|
+
const where = `${cls}.${fn}`;
|
|
1150
|
+
const nargs = args.map((a) => this.toNative(a));
|
|
1151
|
+
// Element work a native does over an array argument is charged before it runs.
|
|
1152
|
+
for (const a of nargs)
|
|
1153
|
+
if (Array.isArray(a))
|
|
1154
|
+
this.spend(a.length, where);
|
|
1155
|
+
const outer = chargeNative;
|
|
1156
|
+
chargeNative = (n) => this.spend(n, where);
|
|
1157
|
+
try {
|
|
1158
|
+
return fromNative(native(...nargs));
|
|
1159
|
+
}
|
|
1160
|
+
finally {
|
|
1161
|
+
chargeNative = outer;
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
const { node, where } = this.resolveStatic(cls, fn);
|
|
1165
|
+
this.opts.trace?.(where);
|
|
1166
|
+
return this.invoke(node, args, new Scope(), where);
|
|
1167
|
+
}
|
|
1168
|
+
toNative(v) {
|
|
1169
|
+
if (v instanceof Closure) {
|
|
1170
|
+
const f = (...args) => this.invoke(v.node, args, v.scope, v.where);
|
|
1171
|
+
CALLBACKS.add(f);
|
|
1172
|
+
return f;
|
|
1173
|
+
}
|
|
1174
|
+
return fromNative(v);
|
|
1175
|
+
}
|
|
1176
|
+
/** Count one evaluation step against this read's budget. */
|
|
1177
|
+
tick(where, node) {
|
|
1178
|
+
this.spend(1, where, node.start);
|
|
1179
|
+
}
|
|
1180
|
+
/** Count `n` steps (native element work, or one evaluation) against this read's budget. */
|
|
1181
|
+
spend(n, where, offset) {
|
|
1182
|
+
this.steps += n;
|
|
1183
|
+
if (this.steps > this.maxSteps) {
|
|
1184
|
+
throw new InterpError('budget', `read ran past ${this.maxSteps} steps`, where, offset);
|
|
1185
|
+
}
|
|
1186
|
+
if (this.steps >= this.nextClock) {
|
|
1187
|
+
this.nextClock = this.steps + CLOCK_EVERY;
|
|
1188
|
+
if (this.now() > this.deadline)
|
|
1189
|
+
throw new InterpError('budget', `read ran past ${this.maxMillis} ms`, where, offset);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
/** Charge a name lookup that visited `walked` scopes: the first is the step's own, each further one a step. */
|
|
1193
|
+
chargeLookup(walked, where, node) {
|
|
1194
|
+
if (walked > 1)
|
|
1195
|
+
this.spend(walked - 1, where, node.start);
|
|
1196
|
+
}
|
|
1197
|
+
/** The value of `name` in `scope`, or UNDECLARED, its walk charged. */
|
|
1198
|
+
lookup(scope, name, where, node) {
|
|
1199
|
+
return scope.lookup(name, (walked) => this.chargeLookup(walked, where, node));
|
|
1200
|
+
}
|
|
1201
|
+
invoke(node, args, outer, where, self) {
|
|
1202
|
+
this.tick(where, node);
|
|
1203
|
+
if (this.depth >= this.maxDepth) {
|
|
1204
|
+
throw new InterpError('budget', `call depth ran past ${this.maxDepth}`, where, node.start);
|
|
1205
|
+
}
|
|
1206
|
+
this.depth++;
|
|
1207
|
+
try {
|
|
1208
|
+
return this.invokeBody(node, args, outer, where, self);
|
|
1209
|
+
}
|
|
1210
|
+
finally {
|
|
1211
|
+
this.depth--;
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
invokeBody(node, args, outer, where, self) {
|
|
1215
|
+
const scope = new Scope(outer);
|
|
1216
|
+
if (scope.depth > MAX_NESTING) {
|
|
1217
|
+
throw new InterpError('budget', `functions nested past ${MAX_NESTING}`, where, node.start);
|
|
1218
|
+
}
|
|
1219
|
+
if (self !== undefined)
|
|
1220
|
+
scope.declare('this', self);
|
|
1221
|
+
// `var` is function-scoped and hoisted: a var declared only in an untaken branch is undefined,
|
|
1222
|
+
// not an unknown name (which would read as a class reference). The walk that finds them is
|
|
1223
|
+
// charged once per function; declaring them, and the parameters, is charged on every call.
|
|
1224
|
+
const hoisted = hoistedVars(node, (n) => this.spend(n, where, node.start));
|
|
1225
|
+
this.spend(node.params.length + hoisted.length, where, node.start);
|
|
1226
|
+
node.params.forEach((p, i) => scope.declare(this.paramName(p, where), args[i]));
|
|
1227
|
+
for (const name of hoisted)
|
|
1228
|
+
if (!scope.hasOwn(name))
|
|
1229
|
+
scope.declare(name, undefined);
|
|
1230
|
+
const c = this.execBlock(node.body.body, scope, where);
|
|
1231
|
+
return c?.type === 'return' ? c.value : undefined;
|
|
1232
|
+
}
|
|
1233
|
+
paramName(p, where) {
|
|
1234
|
+
if (p.type !== 'Identifier')
|
|
1235
|
+
throw this.unsupported(`parameter ${p.type}`, p, where);
|
|
1236
|
+
return p.name;
|
|
1237
|
+
}
|
|
1238
|
+
unsupported(what, node, where) {
|
|
1239
|
+
return new InterpError('unsupported', `unsupported ${what}`, where, node.start);
|
|
1240
|
+
}
|
|
1241
|
+
// -------------------------------------------------------------------------
|
|
1242
|
+
// Statements
|
|
1243
|
+
execBlock(body, scope, where) {
|
|
1244
|
+
for (const st of body) {
|
|
1245
|
+
const c = this.exec(st, scope, where);
|
|
1246
|
+
if (c)
|
|
1247
|
+
return c;
|
|
1248
|
+
}
|
|
1249
|
+
return undefined;
|
|
1250
|
+
}
|
|
1251
|
+
exec(st, scope, where) {
|
|
1252
|
+
this.tick(where, st);
|
|
1253
|
+
switch (st.type) {
|
|
1254
|
+
case 'VariableDeclaration':
|
|
1255
|
+
for (const d of st.declarations) {
|
|
1256
|
+
const name = this.paramName(d.id, where);
|
|
1257
|
+
// `var x;` re-run (in a loop) keeps x's value; hoisting already declared it.
|
|
1258
|
+
if (d.init)
|
|
1259
|
+
scope.declare(name, this.eval(d.init, scope, where));
|
|
1260
|
+
else if (!scope.hasOwn(name))
|
|
1261
|
+
scope.declare(name, undefined);
|
|
1262
|
+
}
|
|
1263
|
+
return undefined;
|
|
1264
|
+
case 'ExpressionStatement':
|
|
1265
|
+
this.eval(st.expression, scope, where);
|
|
1266
|
+
return undefined;
|
|
1267
|
+
case 'ReturnStatement':
|
|
1268
|
+
return { type: 'return', value: st.argument ? this.eval(st.argument, scope, where) : undefined };
|
|
1269
|
+
case 'IfStatement':
|
|
1270
|
+
if (this.eval(st.test, scope, where))
|
|
1271
|
+
return this.exec(st.consequent, scope, where);
|
|
1272
|
+
return st.alternate ? this.exec(st.alternate, scope, where) : undefined;
|
|
1273
|
+
case 'BlockStatement':
|
|
1274
|
+
return this.execBlock(st.body, scope, where);
|
|
1275
|
+
case 'ForStatement': {
|
|
1276
|
+
if (st.init) {
|
|
1277
|
+
if (st.init.type === 'VariableDeclaration')
|
|
1278
|
+
this.exec(st.init, scope, where);
|
|
1279
|
+
else
|
|
1280
|
+
this.eval(st.init, scope, where);
|
|
1281
|
+
}
|
|
1282
|
+
for (let n = 0; !st.test || this.eval(st.test, scope, where); n++) {
|
|
1283
|
+
if (n >= this.maxIterations)
|
|
1284
|
+
throw new InterpError('loop-guard', `loop ran past ${this.maxIterations} iterations`, where, st.start);
|
|
1285
|
+
const c = this.exec(st.body, scope, where);
|
|
1286
|
+
if (c?.type === 'break')
|
|
1287
|
+
break;
|
|
1288
|
+
if (c)
|
|
1289
|
+
return c;
|
|
1290
|
+
if (st.update)
|
|
1291
|
+
this.eval(st.update, scope, where);
|
|
1292
|
+
}
|
|
1293
|
+
return undefined;
|
|
1294
|
+
}
|
|
1295
|
+
case 'SwitchStatement': {
|
|
1296
|
+
const v = this.eval(st.discriminant, scope, where);
|
|
1297
|
+
let i = st.cases.findIndex((c) => c.test && this.looseEquals(this.eval(c.test, scope, where), v, where, c));
|
|
1298
|
+
if (i < 0)
|
|
1299
|
+
i = st.cases.findIndex((c) => !c.test);
|
|
1300
|
+
if (i < 0)
|
|
1301
|
+
return undefined;
|
|
1302
|
+
for (; i < st.cases.length; i++) {
|
|
1303
|
+
const c = this.execBlock(st.cases[i].consequent, scope, where);
|
|
1304
|
+
if (c?.type === 'break')
|
|
1305
|
+
return undefined;
|
|
1306
|
+
if (c)
|
|
1307
|
+
return c;
|
|
1308
|
+
}
|
|
1309
|
+
return undefined;
|
|
1310
|
+
}
|
|
1311
|
+
case 'BreakStatement':
|
|
1312
|
+
if (st.label)
|
|
1313
|
+
throw this.unsupported('labelled break', st, where);
|
|
1314
|
+
return { type: 'break' };
|
|
1315
|
+
case 'EmptyStatement':
|
|
1316
|
+
return undefined;
|
|
1317
|
+
case 'ThrowStatement':
|
|
1318
|
+
// The argument is not evaluated (it may read bytes or build exception objects);
|
|
1319
|
+
// its string literals are the message, built once per throw site and capped.
|
|
1320
|
+
throw new InterpError('reader-threw', this.throwMessage(st, where), where, st.start);
|
|
1321
|
+
default:
|
|
1322
|
+
throw this.unsupported(`statement ${st.type}`, st, where);
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* `reader threw: <the argument's string literals>`, capped at MAX_THROW_MESSAGE characters. Walking the
|
|
1327
|
+
* argument is host work in its size, so it is done once per throw site (and charged by the nodes
|
|
1328
|
+
* walked); every throw is then charged the message's length, as building the error copies it.
|
|
1329
|
+
*/
|
|
1330
|
+
throwMessage(st, where) {
|
|
1331
|
+
let msg = this.throwMessages.get(st);
|
|
1332
|
+
if (msg === undefined) {
|
|
1333
|
+
const { literals, nodes } = stringLiterals(st.argument, MAX_THROW_MESSAGE);
|
|
1334
|
+
this.spend(nodes, where, st.start);
|
|
1335
|
+
const text = literals.join(' ');
|
|
1336
|
+
msg = `reader threw: ${text.length > MAX_THROW_MESSAGE ? `${text.slice(0, MAX_THROW_MESSAGE)}…` : text || '(no message)'}`;
|
|
1337
|
+
this.throwMessages.set(st, msg);
|
|
1338
|
+
}
|
|
1339
|
+
this.spend(msg.length, where, st.start);
|
|
1340
|
+
return msg;
|
|
1341
|
+
}
|
|
1342
|
+
// -------------------------------------------------------------------------
|
|
1343
|
+
// Expressions
|
|
1344
|
+
eval(n, scope, where) {
|
|
1345
|
+
this.tick(where, n);
|
|
1346
|
+
switch (n.type) {
|
|
1347
|
+
case 'Literal':
|
|
1348
|
+
// Only string, number, boolean and null literals. A BigInt costs the host O(size) per
|
|
1349
|
+
// operator while the budget charges one step, and a RegExp is a host object; no reader uses either.
|
|
1350
|
+
if (n.value !== null && typeof n.value === 'object')
|
|
1351
|
+
throw new InterpError('bad-value', 'regexp literal', where, n.start);
|
|
1352
|
+
if (typeof n.value === 'bigint')
|
|
1353
|
+
throw new InterpError('bad-value', 'bigint literal', where, n.start);
|
|
1354
|
+
return n.value;
|
|
1355
|
+
case 'Identifier': {
|
|
1356
|
+
const v = this.lookup(scope, n.name, where, n);
|
|
1357
|
+
if (v !== UNDECLARED)
|
|
1358
|
+
return v;
|
|
1359
|
+
if (n.name === 'undefined')
|
|
1360
|
+
return undefined;
|
|
1361
|
+
return this.classRef(n.name);
|
|
1362
|
+
}
|
|
1363
|
+
case 'ThisExpression': {
|
|
1364
|
+
const v = this.lookup(scope, 'this', where, n);
|
|
1365
|
+
return v === UNDECLARED ? undefined : v;
|
|
1366
|
+
}
|
|
1367
|
+
case 'SequenceExpression': {
|
|
1368
|
+
let v;
|
|
1369
|
+
for (const e of n.expressions)
|
|
1370
|
+
v = this.eval(e, scope, where);
|
|
1371
|
+
return v;
|
|
1372
|
+
}
|
|
1373
|
+
case 'ConditionalExpression':
|
|
1374
|
+
return this.eval(n.test, scope, where) ? this.eval(n.consequent, scope, where) : this.eval(n.alternate, scope, where);
|
|
1375
|
+
case 'LogicalExpression': {
|
|
1376
|
+
const l = this.eval(n.left, scope, where);
|
|
1377
|
+
if (n.operator === '&&')
|
|
1378
|
+
return l ? this.eval(n.right, scope, where) : l;
|
|
1379
|
+
if (n.operator === '||')
|
|
1380
|
+
return l ? l : this.eval(n.right, scope, where);
|
|
1381
|
+
throw this.unsupported(`operator ${n.operator}`, n, where);
|
|
1382
|
+
}
|
|
1383
|
+
case 'UnaryExpression': {
|
|
1384
|
+
const v = this.eval(n.argument, scope, where);
|
|
1385
|
+
if (n.operator === '!')
|
|
1386
|
+
return !v;
|
|
1387
|
+
if (n.operator === '-')
|
|
1388
|
+
return -this.numeric(v, n, where);
|
|
1389
|
+
if (n.operator === 'void')
|
|
1390
|
+
return undefined;
|
|
1391
|
+
// The client's runtime type checks (`"number"==typeof a`, `"function"==typeof b` for a
|
|
1392
|
+
// class) reach this on some boards; the interpreter's own values map onto JS's answers.
|
|
1393
|
+
if (n.operator === 'typeof')
|
|
1394
|
+
return typeOf(v);
|
|
1395
|
+
throw this.unsupported(`operator ${n.operator}`, n, where);
|
|
1396
|
+
}
|
|
1397
|
+
case 'BinaryExpression':
|
|
1398
|
+
return this.binary(n.operator, n.left, n.right, scope, where, n);
|
|
1399
|
+
case 'AssignmentExpression': {
|
|
1400
|
+
if (n.operator !== '=')
|
|
1401
|
+
throw this.unsupported(`assignment ${n.operator}`, n, where);
|
|
1402
|
+
const v = this.eval(n.right, scope, where);
|
|
1403
|
+
const t = n.left;
|
|
1404
|
+
if (t.type === 'Identifier') {
|
|
1405
|
+
this.chargeLookup(scope.assign(t.name, v), where, t);
|
|
1406
|
+
return v;
|
|
1407
|
+
}
|
|
1408
|
+
if (t.type === 'MemberExpression') {
|
|
1409
|
+
const o = this.eval(t.object, scope, where);
|
|
1410
|
+
const k = this.memberKey(t, scope, where);
|
|
1411
|
+
if (!isObject(o) || o instanceof ClassRef)
|
|
1412
|
+
throw new InterpError('bad-value', `cannot set ${k} on ${describe(o)}`, where, t.start);
|
|
1413
|
+
// Only arrays and plain objects (the ones the interpreter makes) take writes, and only as
|
|
1414
|
+
// own data properties: never onto the reader, a closure or a host object, never a prototype.
|
|
1415
|
+
const proto = Object.getPrototypeOf(o);
|
|
1416
|
+
if (Array.isArray(o)) {
|
|
1417
|
+
// An array stays dense: an index at most its length (overwrite or append), never `length`
|
|
1418
|
+
// itself or a far index, which would make a huge sparse array for free.
|
|
1419
|
+
if (!isIndex(k) || Number(k) > o.length)
|
|
1420
|
+
throw new InterpError('forbidden', `cannot set ${k} on an array of ${o.length}`, where, t.start);
|
|
1421
|
+
}
|
|
1422
|
+
else if (proto !== Object.prototype && proto !== null) {
|
|
1423
|
+
throw new InterpError('forbidden', `cannot set ${k} on ${describe(o)}`, where, t.start);
|
|
1424
|
+
}
|
|
1425
|
+
else if (SHADOWING_KEYS.has(k)) {
|
|
1426
|
+
throw new InterpError('forbidden', `cannot set ${k}: it would shadow a built-in method`, where, t.start);
|
|
1427
|
+
}
|
|
1428
|
+
o[k] = v;
|
|
1429
|
+
return v;
|
|
1430
|
+
}
|
|
1431
|
+
throw this.unsupported(`assignment target ${t.type}`, t, where);
|
|
1432
|
+
}
|
|
1433
|
+
case 'UpdateExpression': {
|
|
1434
|
+
if (n.argument.type !== 'Identifier')
|
|
1435
|
+
throw this.unsupported(`update of ${n.argument.type}`, n, where);
|
|
1436
|
+
const name = n.argument.name;
|
|
1437
|
+
// ToNumeric, as the language does (`"3"++` is 4), with a string's conversion charged.
|
|
1438
|
+
const cur = this.lookup(scope, name, where, n);
|
|
1439
|
+
const old = Number(this.numeric(cur === UNDECLARED ? undefined : cur, n, where));
|
|
1440
|
+
const next = n.operator === '++' ? old + 1 : old - 1;
|
|
1441
|
+
this.chargeLookup(scope.assign(name, next), where, n);
|
|
1442
|
+
return n.prefix ? next : old;
|
|
1443
|
+
}
|
|
1444
|
+
case 'FunctionExpression':
|
|
1445
|
+
return new Closure(n, scope, where);
|
|
1446
|
+
case 'NewExpression':
|
|
1447
|
+
return this.construct(n.callee, n.arguments, scope, where, n);
|
|
1448
|
+
case 'ArrayExpression':
|
|
1449
|
+
return n.elements.map((e) => {
|
|
1450
|
+
if (!e || e.type === 'SpreadElement')
|
|
1451
|
+
throw this.unsupported('array element', n, where);
|
|
1452
|
+
return this.eval(e, scope, where);
|
|
1453
|
+
});
|
|
1454
|
+
case 'MemberExpression': {
|
|
1455
|
+
const o = this.eval(n.object, scope, where);
|
|
1456
|
+
const k = this.memberKey(n, scope, where);
|
|
1457
|
+
if (o instanceof ClassRef)
|
|
1458
|
+
return this.staticData(o.name, k, n, where);
|
|
1459
|
+
if (o instanceof Reader)
|
|
1460
|
+
throw this.unsupported(`reader member ${k}`, n, where);
|
|
1461
|
+
if (o === null || o === undefined)
|
|
1462
|
+
throw new InterpError('bad-value', `read of ${k} of ${String(o)}`, where, n.start);
|
|
1463
|
+
if (o instanceof Closure || o instanceof Scope)
|
|
1464
|
+
throw new InterpError('forbidden', `read of ${k} of an interpreter value`, where, n.start);
|
|
1465
|
+
return isDecoded(o) ? this.decodedMember(o, k) : readMember(o, k);
|
|
1466
|
+
}
|
|
1467
|
+
case 'CallExpression':
|
|
1468
|
+
return this.call(n.callee, n.arguments, scope, where, n);
|
|
1469
|
+
default:
|
|
1470
|
+
throw this.unsupported(`expression ${n.type}`, n, where);
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
memberKey(n, scope, where) {
|
|
1474
|
+
const p = n.property;
|
|
1475
|
+
let k;
|
|
1476
|
+
if (n.computed) {
|
|
1477
|
+
const v = this.eval(p, scope, where);
|
|
1478
|
+
// A string or number key only: converting an object would run its (host) toString.
|
|
1479
|
+
if (typeof v !== 'string' && typeof v !== 'number')
|
|
1480
|
+
throw new InterpError('bad-value', `member key ${describe(v)}`, where, n.start);
|
|
1481
|
+
k = String(v);
|
|
1482
|
+
// Using a key is host work in its length (the index test, hashing, a static's lookup), so a long
|
|
1483
|
+
// computed key is charged: built once, it could otherwise be used over and over at one step a time.
|
|
1484
|
+
this.spend(k.length, where, n.start);
|
|
1485
|
+
}
|
|
1486
|
+
else {
|
|
1487
|
+
k = p.name;
|
|
1488
|
+
}
|
|
1489
|
+
if (FORBIDDEN_KEYS.has(k))
|
|
1490
|
+
throw new InterpError('forbidden', `access to ${k}`, where, n.start);
|
|
1491
|
+
return k;
|
|
1492
|
+
}
|
|
1493
|
+
binary(op, left, right, scope, where, n) {
|
|
1494
|
+
const l = this.eval(left, scope, where);
|
|
1495
|
+
const r = this.eval(right, scope, where);
|
|
1496
|
+
// Arithmetic, relational and bitwise operators convert an object through the host's
|
|
1497
|
+
// ToPrimitive: refused, so an odd operand is an InterpError rather than a host TypeError.
|
|
1498
|
+
if (op !== 'instanceof' && !EQUALITY_OPS.has(op)) {
|
|
1499
|
+
this.primitive(l, n, where);
|
|
1500
|
+
this.primitive(r, n, where);
|
|
1501
|
+
}
|
|
1502
|
+
if (typeof l === 'string' && typeof r === 'string' && STRING_COMPARE_OPS.has(op)) {
|
|
1503
|
+
// Comparing two strings is host work in their length: charged so long strings cannot outrun the budget
|
|
1504
|
+
// (`looseEquals` charges `==` / `!=`).
|
|
1505
|
+
this.spend(Math.min(l.length, r.length), where, n.start);
|
|
1506
|
+
}
|
|
1507
|
+
else if (op !== '+' && op !== 'instanceof' && !EQUALITY_OPS.has(op)) {
|
|
1508
|
+
// Every other string operand of a numeric operator is converted to a number, host work in its length.
|
|
1509
|
+
this.chargeConversion(l, where, n);
|
|
1510
|
+
this.chargeConversion(r, where, n);
|
|
1511
|
+
}
|
|
1512
|
+
switch (op) {
|
|
1513
|
+
case '==':
|
|
1514
|
+
return this.looseEquals(l, r, where, n);
|
|
1515
|
+
case '!=':
|
|
1516
|
+
return !this.looseEquals(l, r, where, n);
|
|
1517
|
+
case '===':
|
|
1518
|
+
return l === r;
|
|
1519
|
+
case '!==':
|
|
1520
|
+
return l !== r;
|
|
1521
|
+
case '<':
|
|
1522
|
+
return l < r;
|
|
1523
|
+
case '<=':
|
|
1524
|
+
return l <= r;
|
|
1525
|
+
case '>':
|
|
1526
|
+
return l > r;
|
|
1527
|
+
case '>=':
|
|
1528
|
+
return l >= r;
|
|
1529
|
+
case '+': {
|
|
1530
|
+
const v = l + r;
|
|
1531
|
+
if (typeof v === 'string') {
|
|
1532
|
+
if (v.length > MAX_STRING) {
|
|
1533
|
+
throw new InterpError('budget', `string of ${v.length} characters (at most ${MAX_STRING})`, where, n.start);
|
|
1534
|
+
}
|
|
1535
|
+
this.spend(v.length, where, n.start);
|
|
1536
|
+
}
|
|
1537
|
+
return v;
|
|
1538
|
+
}
|
|
1539
|
+
case '-':
|
|
1540
|
+
return l - r;
|
|
1541
|
+
case '*':
|
|
1542
|
+
return l * r;
|
|
1543
|
+
case '|':
|
|
1544
|
+
return l | r;
|
|
1545
|
+
case '&':
|
|
1546
|
+
return l & r;
|
|
1547
|
+
case 'instanceof':
|
|
1548
|
+
return this.instanceOf(l, r, n, where);
|
|
1549
|
+
default:
|
|
1550
|
+
throw this.unsupported(`operator ${op}`, n, where);
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* `l == r` without converting an object: an object (or function) loosely equals only itself, so
|
|
1555
|
+
* `x == null` keeps working and an object never equals a primitive (the host would convert it
|
|
1556
|
+
* through ToPrimitive, an array's join for instance, outside the step budget).
|
|
1557
|
+
*/
|
|
1558
|
+
looseEquals(l, r, where, n) {
|
|
1559
|
+
const ref = (v) => isObject(v) || typeof v === 'function';
|
|
1560
|
+
if (ref(l) || ref(r))
|
|
1561
|
+
return l === r;
|
|
1562
|
+
if (typeof l === 'string' && typeof r === 'string')
|
|
1563
|
+
this.spend(Math.min(l.length, r.length), where, n.start);
|
|
1564
|
+
// A string against a number or boolean is converted to a number: host work in its length.
|
|
1565
|
+
else if (typeof l === 'string' && (typeof r === 'number' || typeof r === 'boolean'))
|
|
1566
|
+
this.chargeConversion(l, where, n);
|
|
1567
|
+
else if (typeof r === 'string' && (typeof l === 'number' || typeof l === 'boolean'))
|
|
1568
|
+
this.chargeConversion(r, where, n);
|
|
1569
|
+
// biome-ignore lint/suspicious/noDoubleEquals: this is the interpreted bundle's own `==`, coercion and all.
|
|
1570
|
+
return l == r;
|
|
1571
|
+
}
|
|
1572
|
+
/** `v` for a numeric operator: refused when it is an object, its conversion charged when it is a string. */
|
|
1573
|
+
numeric(v, n, where) {
|
|
1574
|
+
this.primitive(v, n, where);
|
|
1575
|
+
this.chargeConversion(v, where, n);
|
|
1576
|
+
return v;
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* Charges the conversion of a string operand to a number. ToNumber scans the whole string, so one
|
|
1580
|
+
* step per conversion would let a long string in a loop do far more host work than the budget allows.
|
|
1581
|
+
*/
|
|
1582
|
+
chargeConversion(v, where, n) {
|
|
1583
|
+
if (typeof v === 'string')
|
|
1584
|
+
this.spend(v.length, where, n.start);
|
|
1585
|
+
}
|
|
1586
|
+
/** `v`, refused when it is an object (whose conversion to a primitive would run host code). */
|
|
1587
|
+
primitive(v, n, where) {
|
|
1588
|
+
if (isObject(v) || typeof v === 'function' || typeof v === 'bigint')
|
|
1589
|
+
throw new InterpError('bad-value', `operand ${describe(v)}`, where, n.start);
|
|
1590
|
+
return v;
|
|
1591
|
+
}
|
|
1592
|
+
construct(callee, argNodes, scope, where, n) {
|
|
1593
|
+
if (callee.type !== 'Identifier')
|
|
1594
|
+
throw this.unsupported(`new of ${callee.type}`, n, where);
|
|
1595
|
+
const args = argNodes.map((a) => this.eval(a, scope, where));
|
|
1596
|
+
const name = callee.name;
|
|
1597
|
+
if (this.wrappers.has(name))
|
|
1598
|
+
return args.length ? args[0] : null;
|
|
1599
|
+
if (name === 'Array')
|
|
1600
|
+
return [];
|
|
1601
|
+
const obj = { $type: this.bundle.typeNameOf.get(name) ?? name };
|
|
1602
|
+
if (args.length) {
|
|
1603
|
+
// Constructors only normalise what the reader passes in; a failure there (they can
|
|
1604
|
+
// validate or build helper objects) is kept on the object rather than losing the read.
|
|
1605
|
+
const ctor = this.resolveCtor(name);
|
|
1606
|
+
if (ctor) {
|
|
1607
|
+
try {
|
|
1608
|
+
this.invoke(ctor.node, args, new Scope(), ctor.where, obj);
|
|
1609
|
+
}
|
|
1610
|
+
catch (e) {
|
|
1611
|
+
// A budget or containment failure is never swallowed into the object.
|
|
1612
|
+
if (e instanceof InterpError && (e.kind === 'budget' || e.kind === 'forbidden'))
|
|
1613
|
+
throw e;
|
|
1614
|
+
// A host RangeError (stack, string or array length) is a runaway read: readClass turns it into a budget error.
|
|
1615
|
+
if (e instanceof RangeError)
|
|
1616
|
+
throw e;
|
|
1617
|
+
// A host throw and catch costs far more than a step: charged, so a loop of failing
|
|
1618
|
+
// constructors ends at the budget about as fast as any other loop.
|
|
1619
|
+
this.spend(CTOR_FAILURE_STEPS, where, n.start);
|
|
1620
|
+
obj.$ctorError = e.message;
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
return obj;
|
|
1625
|
+
}
|
|
1626
|
+
call(callee, argNodes, scope, where, n) {
|
|
1627
|
+
if (callee.type === 'MemberExpression') {
|
|
1628
|
+
const o = this.eval(callee.object, scope, where);
|
|
1629
|
+
const k = this.memberKey(callee, scope, where);
|
|
1630
|
+
const args = argNodes.map((a) => this.eval(a, scope, where));
|
|
1631
|
+
if (o instanceof Reader) {
|
|
1632
|
+
const f = Object.hasOwn(this.dialect.readerMethods, k) ? this.dialect.readerMethods[k] : undefined;
|
|
1633
|
+
if (!f)
|
|
1634
|
+
throw this.unsupported(`reader method ${k}`, n, where);
|
|
1635
|
+
return fromNative(f(o, ...args));
|
|
1636
|
+
}
|
|
1637
|
+
if (o instanceof ClassRef)
|
|
1638
|
+
return this.callStatic(o.name, k, args);
|
|
1639
|
+
if (Array.isArray(o) && k === 'push')
|
|
1640
|
+
return o.push(...args);
|
|
1641
|
+
throw this.unsupported(`call ${k} on ${describe(o)}`, n, where);
|
|
1642
|
+
}
|
|
1643
|
+
const f = this.eval(callee, scope, where);
|
|
1644
|
+
const args = argNodes.map((a) => this.eval(a, scope, where));
|
|
1645
|
+
if (f instanceof Closure)
|
|
1646
|
+
return this.invoke(f.node, args, f.scope, f.where);
|
|
1647
|
+
// A host function handed in as an argument (the dialect check's item readers): only one
|
|
1648
|
+
// registered as a callback, and its result is checked like any native's.
|
|
1649
|
+
if (typeof f === 'function' && CALLBACKS.has(f))
|
|
1650
|
+
return fromNative(f(...args));
|
|
1651
|
+
throw this.unsupported('call of a non-function', n, where);
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
const hoistCache = new WeakMap();
|
|
1655
|
+
/**
|
|
1656
|
+
* Walk the AST under `root` iteratively (a deeply nested bundle cannot overflow the host stack),
|
|
1657
|
+
* charging one step per node visited: `enter` on the way down (returning false skips the node's
|
|
1658
|
+
* children), `leave` on the way up, children from `kids` (default: all, in source order).
|
|
1659
|
+
*/
|
|
1660
|
+
function walkAst(root, charge, visit) {
|
|
1661
|
+
const kids = visit.kids ?? childrenOf;
|
|
1662
|
+
const stack = [];
|
|
1663
|
+
const push = (n) => {
|
|
1664
|
+
charge(1);
|
|
1665
|
+
const descend = visit.enter?.(n) !== false;
|
|
1666
|
+
stack.push({ n, c: descend ? kids(n) : [], i: 0 });
|
|
1667
|
+
};
|
|
1668
|
+
push(root);
|
|
1669
|
+
while (stack.length) {
|
|
1670
|
+
const top = stack[stack.length - 1];
|
|
1671
|
+
if (top.i < top.c.length)
|
|
1672
|
+
push(top.c[top.i++]);
|
|
1673
|
+
else {
|
|
1674
|
+
stack.pop();
|
|
1675
|
+
visit.leave?.(top.n);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
const isFunctionNode = (n) => n.type === 'FunctionExpression' || n.type === 'FunctionDeclaration' || n.type === 'ArrowFunctionExpression';
|
|
1680
|
+
/**
|
|
1681
|
+
* The names a function declares with `var` anywhere in its body (not in nested functions), in first
|
|
1682
|
+
* declaration order. Walked once per function (cached), each node charged.
|
|
1683
|
+
*/
|
|
1684
|
+
function hoistedVars(fn, charge) {
|
|
1685
|
+
let out = hoistCache.get(fn);
|
|
1686
|
+
if (out)
|
|
1687
|
+
return out;
|
|
1688
|
+
const names = new Set();
|
|
1689
|
+
walkAst(fn.body, charge, {
|
|
1690
|
+
enter: (n) => {
|
|
1691
|
+
if (isFunctionNode(n))
|
|
1692
|
+
return false;
|
|
1693
|
+
if (n.type === 'VariableDeclarator') {
|
|
1694
|
+
const id = n.id;
|
|
1695
|
+
if (id.type === 'Identifier')
|
|
1696
|
+
names.add(id.name);
|
|
1697
|
+
}
|
|
1698
|
+
return true;
|
|
1699
|
+
},
|
|
1700
|
+
});
|
|
1701
|
+
out = [...names];
|
|
1702
|
+
hoistCache.set(fn, out);
|
|
1703
|
+
return out;
|
|
1704
|
+
}
|
|
1705
|
+
const isNode = (v) => isObject(v) && typeof v.type === 'string' && typeof v.start === 'number';
|
|
1706
|
+
/** A node's child nodes, in source order. */
|
|
1707
|
+
function childrenOf(n) {
|
|
1708
|
+
const out = [];
|
|
1709
|
+
for (const [k, v] of Object.entries(n)) {
|
|
1710
|
+
if (k === 'type')
|
|
1711
|
+
continue;
|
|
1712
|
+
if (Array.isArray(v))
|
|
1713
|
+
for (const c of v)
|
|
1714
|
+
if (isNode(c))
|
|
1715
|
+
out.push(c);
|
|
1716
|
+
if (isNode(v))
|
|
1717
|
+
out.push(v);
|
|
1718
|
+
}
|
|
1719
|
+
return out.sort((a, b) => a.start - b.start);
|
|
1720
|
+
}
|
|
1721
|
+
/** Whether a node is itself a call `<cls>.Ha(…)`. */
|
|
1722
|
+
function isReaderCall(n, cls) {
|
|
1723
|
+
if (n.type !== 'CallExpression')
|
|
1724
|
+
return false;
|
|
1725
|
+
const c = n.callee;
|
|
1726
|
+
const o = c.object;
|
|
1727
|
+
const p = c.property;
|
|
1728
|
+
return c.type === 'MemberExpression' && o?.type === 'Identifier' && o.name === cls && p?.name === 'Ha';
|
|
1729
|
+
}
|
|
1730
|
+
/**
|
|
1731
|
+
* The `this`-free member assignments (`d.f = …`) of a reader whose value comes from `<cls>.Ha`,
|
|
1732
|
+
* directly or through a local (`e = a.Ua() ? Cls.Ha(a, d, b) : null; d.f = e`), in source order.
|
|
1733
|
+
* Whether an expression calls the reader (not counting nested functions) is worked out once per
|
|
1734
|
+
* node, bottom-up, so a long assignment chain is not re-walked for each of its assignments.
|
|
1735
|
+
*/
|
|
1736
|
+
function fieldAssignments(fn, cls, charge) {
|
|
1737
|
+
const root = fn;
|
|
1738
|
+
const calls = new Set();
|
|
1739
|
+
walkAst(root, charge, {
|
|
1740
|
+
enter: (n) => n === root || n.type !== 'FunctionExpression',
|
|
1741
|
+
leave: (n) => {
|
|
1742
|
+
if (n !== root && n.type === 'FunctionExpression')
|
|
1743
|
+
return;
|
|
1744
|
+
if (isReaderCall(n, cls) || childrenOf(n).some((c) => calls.has(c)))
|
|
1745
|
+
calls.add(n);
|
|
1746
|
+
},
|
|
1747
|
+
});
|
|
1748
|
+
const holds = new Set();
|
|
1749
|
+
const out = [];
|
|
1750
|
+
const assign = (target, value) => {
|
|
1751
|
+
const yes = calls.has(value) || (value.type === 'Identifier' && holds.has(value.name));
|
|
1752
|
+
if (target.type === 'Identifier') {
|
|
1753
|
+
if (yes)
|
|
1754
|
+
holds.add(target.name);
|
|
1755
|
+
else
|
|
1756
|
+
holds.delete(target.name);
|
|
1757
|
+
}
|
|
1758
|
+
else if (target.type === 'MemberExpression' && !target.computed && yes) {
|
|
1759
|
+
out.push(target.property.name);
|
|
1760
|
+
}
|
|
1761
|
+
};
|
|
1762
|
+
walkAst(root, charge, {
|
|
1763
|
+
kids: (n) => {
|
|
1764
|
+
if (n.type === 'FunctionExpression' && n !== root)
|
|
1765
|
+
return [];
|
|
1766
|
+
if (n.type === 'VariableDeclarator')
|
|
1767
|
+
return n.init ? [n.init] : [];
|
|
1768
|
+
if (n.type === 'AssignmentExpression' && n.operator === '=')
|
|
1769
|
+
return [n.right];
|
|
1770
|
+
return childrenOf(n);
|
|
1771
|
+
},
|
|
1772
|
+
leave: (n) => {
|
|
1773
|
+
if (n.type === 'VariableDeclarator' && n.init)
|
|
1774
|
+
assign(n.id, n.init);
|
|
1775
|
+
else if (n.type === 'AssignmentExpression' && n.operator === '=')
|
|
1776
|
+
assign(n.left, n.right);
|
|
1777
|
+
},
|
|
1778
|
+
});
|
|
1779
|
+
return out;
|
|
1780
|
+
}
|
|
1781
|
+
/** The statics of `cls` a function calls (`Cls.R(…)`), in source order, each once. */
|
|
1782
|
+
function ownStaticCalls(fn, cls, charge) {
|
|
1783
|
+
const root = fn;
|
|
1784
|
+
const out = new Set();
|
|
1785
|
+
walkAst(root, charge, {
|
|
1786
|
+
enter: (n) => {
|
|
1787
|
+
if (n.type === 'FunctionExpression' && n !== root)
|
|
1788
|
+
return false;
|
|
1789
|
+
if (n.type === 'CallExpression') {
|
|
1790
|
+
const c = n.callee;
|
|
1791
|
+
const o = c.object;
|
|
1792
|
+
const p = c.property;
|
|
1793
|
+
if (c.type === 'MemberExpression' && !c.computed && o?.type === 'Identifier' && o.name === cls && p?.name) {
|
|
1794
|
+
out.add(p.name);
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
return true;
|
|
1798
|
+
},
|
|
1799
|
+
});
|
|
1800
|
+
return [...out];
|
|
1801
|
+
}
|
|
1802
|
+
/** A native's result, refused if it would hand a host function to the bundle. */
|
|
1803
|
+
function fromNative(v) {
|
|
1804
|
+
if (typeof v === 'function')
|
|
1805
|
+
throw new InterpError('forbidden', 'a host function cannot enter interpreted code');
|
|
1806
|
+
return v;
|
|
1807
|
+
}
|
|
1808
|
+
/**
|
|
1809
|
+
* Interpreted `o[k]`: an own property, or `length` / an index of an array, a string or a typed array
|
|
1810
|
+
* (the raw-bytes reader returns a Uint8Array, whose `length` is an inherited accessor). Every other
|
|
1811
|
+
* inherited member (methods, accessors, the prototype chain) reads as `undefined`.
|
|
1812
|
+
*/
|
|
1813
|
+
function readMember(o, k) {
|
|
1814
|
+
let v;
|
|
1815
|
+
if (typeof o === 'string')
|
|
1816
|
+
v = k === 'length' || isIndex(k) ? o[k] : undefined;
|
|
1817
|
+
else if (o instanceof Uint8Array && k === 'length')
|
|
1818
|
+
v = o.length;
|
|
1819
|
+
else if (isObject(o) && Object.hasOwn(o, k))
|
|
1820
|
+
v = o[k];
|
|
1821
|
+
else
|
|
1822
|
+
v = undefined;
|
|
1823
|
+
return fromNative(v);
|
|
1824
|
+
}
|
|
1825
|
+
/**
|
|
1826
|
+
* The host's global of that name: its object or function when it is a plain data property, null when
|
|
1827
|
+
* it is anything else (an accessor, a primitive), undefined when there is none. Read through the
|
|
1828
|
+
* property descriptor, so no getter runs; the value is only ever tested with `in`, never handed out.
|
|
1829
|
+
*/
|
|
1830
|
+
function hostGlobal(name) {
|
|
1831
|
+
const d = Object.getOwnPropertyDescriptor(globalThis, name);
|
|
1832
|
+
if (!d)
|
|
1833
|
+
return undefined;
|
|
1834
|
+
return 'value' in d && (typeof d.value === 'function' || (typeof d.value === 'object' && d.value !== null)) ? d.value : null;
|
|
1835
|
+
}
|
|
1836
|
+
/** An object the interpreter constructed (`{ $type, … }`, a plain object), not an array, date, bytes or interpreter value. */
|
|
1837
|
+
function isDecoded(v) {
|
|
1838
|
+
if (!isObject(v) || Array.isArray(v) || !Object.hasOwn(v, '$type') || typeof v.$type !== 'string')
|
|
1839
|
+
return false;
|
|
1840
|
+
const proto = Object.getPrototypeOf(v);
|
|
1841
|
+
return proto === Object.prototype || proto === null;
|
|
1842
|
+
}
|
|
1843
|
+
/** The longest string literal, class list or whitespace run a simple static's source may have. */
|
|
1844
|
+
const MAX_STATIC_SOURCE = 4000;
|
|
1845
|
+
/**
|
|
1846
|
+
* A static's value when it is simple: `!0`/`!1`, true/false/null, a number, a string literal, a name
|
|
1847
|
+
* or an array of names, and nothing after it but the end of the expression: `;`, `,`, `}` or `)`, the
|
|
1848
|
+
* end of the source, or a line break before a name (where a new statement starts). Sticky: matched at
|
|
1849
|
+
* the value's offset in the whole source. Every repeat is bounded and the number has one way to match
|
|
1850
|
+
* (no leading-zero integer, which JS reads as octal), so one match is linear in a bounded length: a
|
|
1851
|
+
* longer string, class list, number or whitespace run does not match, and the static is unsupported.
|
|
1852
|
+
*/
|
|
1853
|
+
const SIMPLE_STATIC = new RegExp(String.raw `(!0|!1|-?(?:0x[\da-fA-F]{1,16}|(?:(?:0|[1-9]\d{0,399})(?:\.\d{0,400})?|\.\d{1,400})(?:[eE][-+]?\d{1,4})?)` +
|
|
1854
|
+
String.raw `|"(?:[^"\\\r\n]|\\.){0,${MAX_STATIC_SOURCE}}"|'(?:[^'\\\r\n]|\\.){0,${MAX_STATIC_SOURCE}}'` +
|
|
1855
|
+
String.raw `|[A-Za-z_$][\w$]{0,255}(?![\w$])|\[[\s\w$,]{0,${MAX_STATIC_SOURCE}}\])` +
|
|
1856
|
+
String.raw `(?=\s{0,${MAX_STATIC_SOURCE}}(?:[;,})]|$)|[ \t]{0,${MAX_STATIC_SOURCE}}\r?\n\s{0,${MAX_STATIC_SOURCE}}(?!in(?:stanceof)?\b)[A-Za-z_$])`, 'y');
|
|
1857
|
+
/** `typeof` over interpreter values: a class, a closure or a callback is a function. */
|
|
1858
|
+
function typeOf(v) {
|
|
1859
|
+
if (v instanceof ClassRef || v instanceof Closure || (typeof v === 'function' && CALLBACKS.has(v)))
|
|
1860
|
+
return 'function';
|
|
1861
|
+
if (v === null || typeof v === 'object' || typeof v === 'function')
|
|
1862
|
+
return 'object';
|
|
1863
|
+
return typeof v;
|
|
1864
|
+
}
|
|
1865
|
+
function describe(v) {
|
|
1866
|
+
if (v === null || v === undefined)
|
|
1867
|
+
return String(v);
|
|
1868
|
+
if (Array.isArray(v))
|
|
1869
|
+
return 'an array';
|
|
1870
|
+
if (isObject(v) && typeof v.$type === 'string')
|
|
1871
|
+
return `a ${v.$type}`;
|
|
1872
|
+
if (v instanceof ClassRef)
|
|
1873
|
+
return `class ${v.name}`;
|
|
1874
|
+
return typeof v;
|
|
1875
|
+
}
|
|
1876
|
+
/**
|
|
1877
|
+
* The string literals of an expression in source order, until they add up to more than `maxChars`
|
|
1878
|
+
* characters, and the number of nodes walked. Iterative: a deeply nested argument cannot overflow the stack.
|
|
1879
|
+
*/
|
|
1880
|
+
function stringLiterals(node, maxChars) {
|
|
1881
|
+
const literals = [];
|
|
1882
|
+
let chars = 0;
|
|
1883
|
+
let nodes = 0;
|
|
1884
|
+
const stack = [node];
|
|
1885
|
+
while (stack.length && chars <= maxChars) {
|
|
1886
|
+
const v = stack.pop();
|
|
1887
|
+
if (Array.isArray(v)) {
|
|
1888
|
+
for (let i = v.length - 1; i >= 0; i--)
|
|
1889
|
+
stack.push(v[i]);
|
|
1890
|
+
continue;
|
|
1891
|
+
}
|
|
1892
|
+
if (!isObject(v) || typeof v.type !== 'string')
|
|
1893
|
+
continue;
|
|
1894
|
+
nodes++;
|
|
1895
|
+
if (v.type === 'Literal' && typeof v.value === 'string') {
|
|
1896
|
+
literals.push(v.value);
|
|
1897
|
+
chars += v.value.length + 1;
|
|
1898
|
+
}
|
|
1899
|
+
const children = Object.entries(v).filter(([k]) => k !== 'type');
|
|
1900
|
+
for (let i = children.length - 1; i >= 0; i--)
|
|
1901
|
+
stack.push(children[i][1]);
|
|
1902
|
+
}
|
|
1903
|
+
return { literals, nodes };
|
|
1904
|
+
}
|