@ball-lang/engine 0.2.1 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,962 +1,99 @@
1
1
  /**
2
2
  * Ball TypeScript Engine — interprets Ball programs directly from JSON.
3
3
  *
4
- * Runs in Node.js and browsers. No protobuf dependency — works with
5
- * proto3 JSON representation of Ball programs.
4
+ * This is a compatibility wrapper around the compiled (self-hosted)
5
+ * Ball engine. The compiled engine is generated by compiling
6
+ * `dart/self_host/engine.ball.json` through `@ball-lang/compiler`.
6
7
  *
7
8
  * Usage:
8
9
  * import { BallEngine } from '@ball-lang/engine';
9
- * const engine = new BallEngine(programJson, { stdout: console.log });
10
- * engine.run();
10
+ * const engine = new BallEngine(programJson);
11
+ * await engine.run();
12
+ * console.log(engine.getOutput());
11
13
  */
12
- // ── Flow signals ────────────────────────────────────────────────────────────
13
- class FlowSignal {
14
- kind;
15
- value;
16
- label;
17
- constructor(kind, value, label) {
18
- this.kind = kind;
19
- this.value = value;
20
- this.label = label;
21
- }
22
- }
23
- class BallException {
24
- typeName;
25
- value;
26
- constructor(typeName, value) {
27
- this.typeName = typeName;
28
- this.value = value;
29
- }
30
- }
31
- class BallRuntimeError extends Error {
32
- constructor(message) {
33
- super(message);
34
- this.name = 'BallRuntimeError';
35
- }
36
- }
37
- // ── Scope ───────────────────────────────────────────────────────────────────
38
- class Scope {
39
- bindings = new Map();
40
- parent;
41
- constructor(parent) {
42
- this.parent = parent;
43
- }
44
- bind(name, value) {
45
- this.bindings.set(name, value);
46
- }
47
- has(name) {
48
- return this.bindings.has(name) || (this.parent?.has(name) ?? false);
49
- }
50
- lookup(name) {
51
- if (this.bindings.has(name))
52
- return this.bindings.get(name);
53
- if (this.parent)
54
- return this.parent.lookup(name);
55
- throw new BallRuntimeError(`Undefined variable: "${name}"`);
56
- }
57
- assign(name, value) {
58
- if (this.bindings.has(name)) {
59
- this.bindings.set(name, value);
60
- return;
61
- }
62
- if (this.parent) {
63
- this.parent.assign(name, value);
64
- return;
65
- }
66
- throw new BallRuntimeError(`Cannot assign to undefined variable: "${name}"`);
67
- }
68
- child() {
69
- return new Scope(this);
70
- }
71
- }
14
+ import { BallEngine as CompiledEngine, } from "./compiled_engine.js";
15
+ import * as _compiled from "./compiled_engine.js";
16
+ import { createEngineSetup } from "./engine_setup.js";
17
+ import { unwrapBallFile } from "./ball_file.js";
18
+ // All proto3-JSON normalization, the method-dispatch handler, the extra
19
+ // std-function registrations, and the compiled-engine patches live in the
20
+ // shared `engine_setup` module so the Phase 2.7b conformance harness (which
21
+ // runs against a freshly compiled engine) can reuse the exact same setup.
22
+ const _setup = createEngineSetup(_compiled);
23
+ const protoWrap = _setup.protoWrap;
24
+ const MethodDispatchHandler = _setup.MethodDispatchHandler;
25
+ const StdModuleHandler = _compiled.StdModuleHandler;
26
+ const registerExtraStdFunctions = _setup.registerExtraStdFunctions;
27
+ const seedGlobalScope = _setup.seedGlobalScope;
28
+ const patchCompiledEngine = _setup.patchCompiledEngine;
29
+ const patchScopeBindings = _setup.patchScopeBindings;
72
30
  export class BallEngine {
73
- program;
74
- stdout;
75
- stderr;
76
- functions = new Map();
77
- constructors = new Map();
78
- enumValues = new Map();
79
- currentModule = '';
80
- activeException = null;
81
- output = [];
31
+ _compiledEngine;
32
+ _output = [];
82
33
  constructor(program, options = {}) {
83
- this.program = typeof program === 'string' ? JSON.parse(program) : program;
84
- this.stdout = options.stdout ?? ((msg) => this.output.push(msg));
85
- this.stderr = options.stderr ?? (() => { });
86
- this.buildLookupTables();
87
- }
88
- buildLookupTables() {
89
- for (const mod of this.program.modules) {
90
- // Index enum types from module (if present).
91
- const enums = mod.enums;
92
- if (Array.isArray(enums)) {
93
- for (const enumDesc of enums) {
94
- const enumName = enumDesc.name; // e.g. "main:Color"
95
- const values = {};
96
- for (const v of (enumDesc.value ?? enumDesc.values ?? [])) {
97
- values[v.name] = { __type__: enumName, name: v.name, index: v.number ?? v.index ?? 0 };
98
- }
99
- this.enumValues.set(enumName, values);
100
- const ec = enumName.indexOf(':');
101
- if (ec >= 0)
102
- this.enumValues.set(enumName.substring(ec + 1), values);
103
- }
104
- }
105
- for (const fn of mod.functions) {
106
- this.functions.set(`${mod.name}.${fn.name}`, fn);
107
- // Register constructors (metadata.kind === "constructor").
108
- const kind = fn.metadata?.kind;
109
- if (kind === 'constructor') {
110
- const entry = { module: mod.name, fn };
111
- // fn.name is "ClassName.new" or "ClassName.named".
112
- const dotIdx = fn.name.indexOf('.');
113
- if (dotIdx >= 0) {
114
- const className = fn.name.substring(0, dotIdx);
115
- const ctorSuffix = fn.name.substring(dotIdx + 1);
116
- if (ctorSuffix === 'new') {
117
- this.constructors.set(className, entry);
118
- this.constructors.set(`${mod.name}:${className}`, entry);
119
- }
120
- this.constructors.set(fn.name, entry);
121
- }
122
- }
123
- }
124
- }
125
- }
126
- run() {
127
- const key = `${this.program.entryModule}.${this.program.entryFunction}`;
128
- const fn = this.functions.get(key);
129
- if (!fn)
130
- throw new BallRuntimeError(`Entry function "${key}" not found`);
131
- const scope = new Scope();
132
- this.currentModule = this.program.entryModule;
133
- const result = this.callFunction(this.program.entryModule, fn, null, scope);
134
- if (result instanceof FlowSignal && result.kind === 'return') {
135
- return this.output;
136
- }
137
- return this.output;
138
- }
34
+ // Ball files are self-describing `google.protobuf.Any` envelopes. Unwrap
35
+ // the `@type` envelope (if present) before normalizing; callers passing an
36
+ // already-unwrapped Program object are still supported.
37
+ const parsed = typeof program === 'string' ? JSON.parse(program) : program;
38
+ const normalized = protoWrap(unwrapBallFile(parsed));
39
+ const stdHandler = new StdModuleHandler();
40
+ const methodHandler = new MethodDispatchHandler();
41
+ const outputCapture = this._output;
42
+ const stdoutFn = options.stdout ?? ((msg) => {
43
+ outputCapture.push(msg);
44
+ });
45
+ const stderrFn = options.stderr ?? (() => { });
46
+ // The self-hosted engine constructor takes 16 positional parameters:
47
+ // program, stdout, stderr, stdinReader, envGet, args, enableProfiling,
48
+ // maxRecursionDepth, timeoutMs, maxMemoryBytes, maxModules,
49
+ // maxExpressionDepth, maxProgramSizeBytes, sandbox, moduleHandlers,
50
+ // resolver
51
+ // (older IR revisions only had 9). Options default to permissive values
52
+ // unless the caller explicitly sets them.
53
+ this._compiledEngine = new CompiledEngine(normalized, stdoutFn, stderrFn, null, // stdinReader
54
+ null, // envGet
55
+ [], // args
56
+ false, // enableProfiling
57
+ options.maxRecursionDepth ?? 100000, // maxRecursionDepth
58
+ options.timeoutMs ?? null, // timeoutMs (null = unbounded)
59
+ options.maxMemoryBytes ?? null, // maxMemoryBytes (null = unbounded)
60
+ options.maxModules ?? 1000000, // maxModules
61
+ options.maxExpressionDepth ?? 1000000, // maxExpressionDepth
62
+ options.maxProgramSizeBytes ?? null, // maxProgramSizeBytes (null = skip)
63
+ options.sandbox ?? false, // sandbox
64
+ [methodHandler, stdHandler], // moduleHandlers
65
+ null);
66
+ // Patch scope bindings to use null-prototype objects (avoids
67
+ // Object.prototype.values/entries/keys getters polluting `in` checks).
68
+ if (typeof globalThis._patchScopeBindings === 'function') {
69
+ globalThis._patchScopeBindings(this._compiledEngine._globalScope);
70
+ }
71
+ else {
72
+ patchScopeBindings(this._compiledEngine._globalScope);
73
+ }
74
+ registerExtraStdFunctions(stdHandler);
75
+ seedGlobalScope(this._compiledEngine);
76
+ patchCompiledEngine(this._compiledEngine);
77
+ // Note: double formatting (12 vs 12.0) handled by BallDouble in preamble.
78
+ // The compiled engine returns raw numbers for literals; BallDouble wrapping
79
+ // happens in arithmetic operations (_stdAdd, _stdBinary, etc.).
80
+ }
81
+ /**
82
+ * Run the program. Returns a promise that resolves to the captured
83
+ * output lines (same content as `getOutput()`).
84
+ *
85
+ * NOTE: The compiled engine is async internally. If you were relying
86
+ * on synchronous `run()`, wrap your call in `await`.
87
+ */
88
+ async run() {
89
+ await this._compiledEngine.run();
90
+ return this._output;
91
+ }
92
+ /** Retrieve lines printed via `std.print` (when no custom stdout was given). */
139
93
  getOutput() {
140
- return this.output;
141
- }
142
- // ── Expression evaluation ─────────────────────────────────────────────
143
- evalExpr(expr, scope) {
144
- if (expr.call)
145
- return this.evalCall(expr.call, scope);
146
- if (expr.literal)
147
- return this.evalLiteral(expr.literal, scope);
148
- if (expr.reference)
149
- return this.evalReference(expr.reference, scope);
150
- if (expr.fieldAccess)
151
- return this.evalFieldAccess(expr.fieldAccess, scope);
152
- if (expr.messageCreation)
153
- return this.evalMessageCreation(expr.messageCreation, scope);
154
- if (expr.block)
155
- return this.evalBlock(expr.block, scope);
156
- if (expr.lambda)
157
- return this.evalLambda(expr.lambda, scope);
158
- return null;
159
- }
160
- evalCall(call, scope) {
161
- const moduleName = call.module || this.currentModule;
162
- // Lazy control flow
163
- if (moduleName === 'std' || moduleName === 'dart_std') {
164
- switch (call.function) {
165
- case 'if': return this.evalLazyIf(call, scope);
166
- case 'for': return this.evalLazyFor(call, scope);
167
- case 'for_in': return this.evalLazyForIn(call, scope);
168
- case 'while': return this.evalLazyWhile(call, scope);
169
- case 'do_while': return this.evalLazyDoWhile(call, scope);
170
- case 'switch': return this.evalLazySwitch(call, scope);
171
- case 'try': return this.evalLazyTry(call, scope);
172
- case 'and': return this.evalShortCircuitAnd(call, scope);
173
- case 'or': return this.evalShortCircuitOr(call, scope);
174
- case 'return': return this.evalReturn(call, scope);
175
- case 'break': return new FlowSignal('break', undefined, this.lazyStringField(call, 'label'));
176
- case 'continue': return new FlowSignal('continue', undefined, this.lazyStringField(call, 'label'));
177
- case 'assign': return this.evalAssign(call, scope);
178
- case 'labeled': return this.evalLabeled(call, scope);
179
- case 'pre_increment':
180
- case 'post_increment':
181
- case 'pre_decrement':
182
- case 'post_decrement':
183
- return this.evalIncDec(call, scope);
184
- }
185
- }
186
- // Eager evaluation
187
- const input = call.input ? this.evalExpr(call.input, scope) : null;
188
- // Fast path for explicit std calls
189
- if (call.module === 'std' || call.module === 'dart_std') {
190
- return this.callBaseFunction(call.module, call.function, input);
191
- }
192
- // Method call on object (has 'self' field) — instance method dispatch.
193
- if (input && typeof input === 'object' && !Array.isArray(input) && 'self' in input) {
194
- const self = input.self;
195
- if (self && typeof self === 'object' && !Array.isArray(self)) {
196
- const typeName = self.__type__;
197
- if (typeName) {
198
- const colonIdx = typeName.indexOf(':');
199
- const modPart = colonIdx >= 0 ? typeName.substring(0, colonIdx) : this.currentModule;
200
- // Try ClassName.methodName
201
- const methodKey = `${modPart}.${typeName}.${call.function}`;
202
- const method = this.functions.get(methodKey);
203
- if (method)
204
- return this.callFunction(modPart, method, input, scope);
205
- // Walk __super__ chain for inherited methods.
206
- let superObj = self.__super__;
207
- while (superObj && typeof superObj === 'object' && !Array.isArray(superObj)) {
208
- const superType = superObj.__type__;
209
- if (superType) {
210
- const sColonIdx = superType.indexOf(':');
211
- const sModPart = sColonIdx >= 0 ? superType.substring(0, sColonIdx) : modPart;
212
- const sTypeName = sColonIdx >= 0 ? superType : `${sModPart}:${superType}`;
213
- const superMethodKey = `${sModPart}.${sTypeName}.${call.function}`;
214
- const superMethod = this.functions.get(superMethodKey);
215
- if (superMethod)
216
- return this.callFunction(sModPart, superMethod, input, scope);
217
- }
218
- superObj = superObj.__super__;
219
- }
220
- }
221
- }
222
- // Fall through to normal resolution if no method found on the type.
223
- }
224
- const key = `${moduleName}.${call.function}`;
225
- const fn = this.functions.get(key);
226
- if (fn?.isBase)
227
- return this.callBaseFunction(moduleName, call.function, input);
228
- // Scope closure lookup
229
- if (!call.module && scope.has(call.function)) {
230
- const bound = scope.lookup(call.function);
231
- if (typeof bound === 'function')
232
- return bound(input);
233
- }
234
- // Module function lookup
235
- if (fn)
236
- return this.callFunction(moduleName, fn, input, scope);
237
- // Fallback: scan all modules
238
- for (const mod of this.program.modules) {
239
- for (const f of mod.functions) {
240
- if (f.name === call.function) {
241
- return this.callFunction(mod.name, f, input, scope);
242
- }
243
- }
244
- }
245
- throw new BallRuntimeError(`Function "${key}" not found`);
246
- }
247
- callFunction(moduleName, fn, input, parentScope) {
248
- if (fn.isBase)
249
- return this.callBaseFunction(moduleName, fn.name, input);
250
- if (!fn.body)
251
- return null;
252
- const prevModule = this.currentModule;
253
- this.currentModule = moduleName;
254
- const fnScope = parentScope.child();
255
- fnScope.bind('input', input);
256
- // Bind 'self' for instance method calls so `this` references resolve.
257
- if (input && typeof input === 'object' && !Array.isArray(input) && 'self' in input) {
258
- fnScope.bind('self', input.self);
259
- }
260
- // Destructure input fields as named parameters
261
- const params = fn.metadata?.params;
262
- if (params && Array.isArray(params)) {
263
- if (params.length === 1 && (input === null || input === undefined || typeof input !== 'object' || Array.isArray(input))) {
264
- // Single-param function with non-object input: bind directly
265
- const name = typeof params[0] === 'string' ? params[0] : params[0].name;
266
- if (name)
267
- fnScope.bind(name, input);
268
- }
269
- else if (input && typeof input === 'object' && !Array.isArray(input)) {
270
- for (let i = 0; i < params.length; i++) {
271
- const p = params[i];
272
- const name = typeof p === 'string' ? p : p.name;
273
- if (!name)
274
- continue;
275
- if (name in input) {
276
- fnScope.bind(name, input[name]);
277
- }
278
- else if (`arg${i}` in input) {
279
- fnScope.bind(name, input[`arg${i}`]);
280
- }
281
- }
282
- }
283
- }
284
- let result = this.evalExpr(fn.body, fnScope);
285
- this.currentModule = prevModule;
286
- if (result instanceof FlowSignal && result.kind === 'return') {
287
- return result.value;
288
- }
289
- return result;
290
- }
291
- // ── Literals ──────────────────────────────────────────────────────────
292
- evalLiteral(lit, scope) {
293
- if (lit.intValue !== undefined)
294
- return typeof lit.intValue === 'string' ? parseInt(lit.intValue) : lit.intValue;
295
- if (lit.doubleValue !== undefined)
296
- return lit.doubleValue;
297
- if (lit.stringValue !== undefined)
298
- return lit.stringValue;
299
- if (lit.boolValue !== undefined)
300
- return lit.boolValue;
301
- if (lit.listValue)
302
- return lit.listValue.elements.map(e => this.evalExpr(e, scope));
303
- return null;
304
- }
305
- evalReference(ref, scope) {
306
- const name = ref.name;
307
- if (scope.has(name))
308
- return scope.lookup(name);
309
- // Constructor tear-off: resolve class names to callable closures.
310
- const ctorEntry = this.constructors.get(name);
311
- if (ctorEntry) {
312
- return (input) => this.callFunction(ctorEntry.module, ctorEntry.fn, input, scope);
313
- }
314
- // Try stripping module prefix (e.g. "main:Foo" -> "Foo").
315
- const colonIdx = name.indexOf(':');
316
- if (colonIdx >= 0) {
317
- const bare = name.substring(colonIdx + 1);
318
- const bareEntry = this.constructors.get(bare);
319
- if (bareEntry) {
320
- return (input) => this.callFunction(bareEntry.module, bareEntry.fn, input, scope);
321
- }
322
- }
323
- // Enum type reference: resolve to a map of enum values.
324
- const enumVals = this.enumValues.get(name);
325
- if (enumVals)
326
- return enumVals;
327
- return scope.lookup(name);
328
- }
329
- evalFieldAccess(fa, scope) {
330
- const obj = this.evalExpr(fa.object, scope);
331
- // Handle string properties
332
- if (typeof obj === 'string') {
333
- if (fa.field === 'length')
334
- return obj.length;
335
- return null;
336
- }
337
- // Handle array properties
338
- if (Array.isArray(obj)) {
339
- if (fa.field === 'length')
340
- return obj.length;
341
- return null;
342
- }
343
- if (obj && typeof obj === 'object' && !Array.isArray(obj)) {
344
- if (fa.field in obj)
345
- return obj[fa.field];
346
- // Walk __super__ chain for inherited fields.
347
- let superObj = obj.__super__;
348
- while (superObj && typeof superObj === 'object' && !Array.isArray(superObj)) {
349
- if (fa.field in superObj)
350
- return superObj[fa.field];
351
- superObj = superObj.__super__;
352
- }
353
- }
354
- return null;
355
- }
356
- evalMessageCreation(mc, scope) {
357
- const result = {};
358
- for (const f of mc.fields) {
359
- result[f.name] = this.evalExpr(f.value, scope);
360
- }
361
- return result;
362
- }
363
- evalBlock(block, scope) {
364
- const blockScope = scope.child();
365
- let lastResult = null;
366
- for (const stmt of block.statements) {
367
- if (stmt.let) {
368
- const val = this.evalExpr(stmt.let.value, blockScope);
369
- if (val instanceof FlowSignal)
370
- return val;
371
- blockScope.bind(stmt.let.name, val);
372
- }
373
- if (stmt.expression) {
374
- lastResult = this.evalExpr(stmt.expression, blockScope);
375
- if (lastResult instanceof FlowSignal)
376
- return lastResult;
377
- }
378
- }
379
- if (block.result) {
380
- lastResult = this.evalExpr(block.result, blockScope);
381
- }
382
- return lastResult;
383
- }
384
- evalLambda(lambda, scope) {
385
- return (input) => {
386
- const lambdaScope = scope.child();
387
- lambdaScope.bind('input', input);
388
- const params = lambda.metadata?.params;
389
- if (params && Array.isArray(params)) {
390
- if (params.length === 1 && (input === null || input === undefined || typeof input !== 'object' || Array.isArray(input))) {
391
- const name = typeof params[0] === 'string' ? params[0] : params[0].name;
392
- if (name)
393
- lambdaScope.bind(name, input);
394
- }
395
- else if (input && typeof input === 'object' && !Array.isArray(input)) {
396
- for (let i = 0; i < params.length; i++) {
397
- const p = params[i];
398
- const name = typeof p === 'string' ? p : p.name;
399
- if (!name)
400
- continue;
401
- if (name in input) {
402
- lambdaScope.bind(name, input[name]);
403
- }
404
- else if (`arg${i}` in input) {
405
- lambdaScope.bind(name, input[`arg${i}`]);
406
- }
407
- }
408
- }
409
- }
410
- const result = this.evalExpr(lambda.body, lambdaScope);
411
- if (result instanceof FlowSignal && result.kind === 'return')
412
- return result.value;
413
- return result;
414
- };
415
- }
416
- // ── Lazy control flow ─────────────────────────────────────────────────
417
- lazyFields(call) {
418
- if (!call.input?.messageCreation)
419
- return {};
420
- const result = {};
421
- for (const f of call.input.messageCreation.fields) {
422
- result[f.name] = f.value;
423
- }
424
- return result;
425
- }
426
- lazyStringField(call, name) {
427
- const fields = this.lazyFields(call);
428
- const expr = fields[name];
429
- if (!expr?.literal?.stringValue)
430
- return undefined;
431
- return expr.literal.stringValue;
432
- }
433
- evalLazyIf(call, scope) {
434
- const fields = this.lazyFields(call);
435
- if (!fields.condition)
436
- return null;
437
- const cond = this.evalExpr(fields.condition, scope);
438
- if (this.toBool(cond)) {
439
- return fields.then ? this.evalExpr(fields.then, scope) : null;
440
- }
441
- return fields.else ? this.evalExpr(fields.else, scope) : null;
442
- }
443
- evalLazyWhile(call, scope) {
444
- const fields = this.lazyFields(call);
445
- while (true) {
446
- if (fields.condition) {
447
- if (!this.toBool(this.evalExpr(fields.condition, scope)))
448
- break;
449
- }
450
- if (fields.body) {
451
- const result = this.evalExpr(fields.body, scope);
452
- if (result instanceof FlowSignal) {
453
- if (result.kind === 'return')
454
- return result;
455
- if (result.label)
456
- return result;
457
- if (result.kind === 'break')
458
- break;
459
- if (result.kind === 'continue')
460
- continue;
461
- }
462
- }
463
- }
464
- return null;
465
- }
466
- evalLazyDoWhile(call, scope) {
467
- const fields = this.lazyFields(call);
468
- do {
469
- if (fields.body) {
470
- const result = this.evalExpr(fields.body, scope);
471
- if (result instanceof FlowSignal) {
472
- if (result.kind === 'return')
473
- return result;
474
- if (result.kind === 'break')
475
- break;
476
- }
477
- }
478
- if (fields.condition) {
479
- if (!this.toBool(this.evalExpr(fields.condition, scope)))
480
- break;
481
- }
482
- else
483
- break;
484
- } while (true);
485
- return null;
486
- }
487
- evalLazyFor(call, scope) {
488
- const fields = this.lazyFields(call);
489
- const forScope = scope.child();
490
- if (fields.init) {
491
- // Handle init as string literal "var i = 0" (encoder format)
492
- if (fields.init.literal?.stringValue) {
493
- const match = fields.init.literal.stringValue.match(/^(?:var|final|int|double|String)\s+(\w+)\s*=\s*(.+)$/);
494
- if (match) {
495
- const varName = match[1];
496
- const rawVal = match[2].trim();
497
- const parsed = rawVal === 'true' ? true : rawVal === 'false' ? false : (isNaN(Number(rawVal)) ? rawVal : Number(rawVal));
498
- forScope.bind(varName, parsed);
499
- }
500
- }
501
- else if (fields.init.block) {
502
- this.evalBlock(fields.init.block, forScope);
503
- }
504
- else {
505
- this.evalExpr(fields.init, forScope);
506
- }
507
- }
508
- while (true) {
509
- if (fields.condition) {
510
- if (!this.toBool(this.evalExpr(fields.condition, forScope)))
511
- break;
512
- }
513
- if (fields.body) {
514
- const result = this.evalExpr(fields.body, forScope);
515
- if (result instanceof FlowSignal) {
516
- if (result.kind === 'return')
517
- return result;
518
- if (result.label)
519
- return result;
520
- if (result.kind === 'break')
521
- break;
522
- if (result.kind === 'continue') {
523
- if (fields.update)
524
- this.evalExpr(fields.update, forScope);
525
- continue;
526
- }
527
- }
528
- }
529
- if (fields.update)
530
- this.evalExpr(fields.update, forScope);
531
- }
532
- return null;
533
- }
534
- evalLazyForIn(call, scope) {
535
- const fields = this.lazyFields(call);
536
- const varName = fields.variable?.literal?.stringValue ?? 'item';
537
- if (!fields.iterable || !fields.body)
538
- return null;
539
- const iterable = this.evalExpr(fields.iterable, scope);
540
- if (!Array.isArray(iterable))
541
- throw new BallRuntimeError('for_in: iterable is not a List');
542
- for (const item of iterable) {
543
- const loopScope = scope.child();
544
- loopScope.bind(varName, item);
545
- const result = this.evalExpr(fields.body, loopScope);
546
- if (result instanceof FlowSignal) {
547
- if (result.kind === 'return')
548
- return result;
549
- if (result.label)
550
- return result;
551
- if (result.kind === 'break')
552
- break;
553
- if (result.kind === 'continue')
554
- continue;
555
- }
556
- }
557
- return null;
558
- }
559
- evalLazySwitch(call, scope) {
560
- const fields = this.lazyFields(call);
561
- if (!fields.subject || !fields.cases)
562
- return null;
563
- const subject = this.evalExpr(fields.subject, scope);
564
- const cases = fields.cases.literal?.listValue?.elements ?? [];
565
- let defaultBody;
566
- for (const c of cases) {
567
- if (!c.messageCreation)
568
- continue;
569
- const cf = {};
570
- for (const f of c.messageCreation.fields)
571
- cf[f.name] = f.value;
572
- if (cf.is_default?.literal?.boolValue) {
573
- defaultBody = cf.body;
574
- continue;
575
- }
576
- if (cf.value) {
577
- const caseVal = this.evalExpr(cf.value, scope);
578
- if (caseVal === subject && cf.body)
579
- return this.evalExpr(cf.body, scope);
580
- }
581
- }
582
- if (defaultBody)
583
- return this.evalExpr(defaultBody, scope);
584
- return null;
585
- }
586
- evalLazyTry(call, scope) {
587
- const fields = this.lazyFields(call);
588
- let result = null;
589
- try {
590
- result = fields.body ? this.evalExpr(fields.body, scope) : null;
591
- }
592
- catch (e) {
593
- result = null;
594
- const catches = fields.catches?.literal?.listValue?.elements ?? [];
595
- let caught = false;
596
- for (const c of catches) {
597
- if (!c.messageCreation)
598
- continue;
599
- const cf = {};
600
- for (const f of c.messageCreation.fields)
601
- cf[f.name] = f.value;
602
- const catchType = cf.type?.literal?.stringValue;
603
- if (catchType) {
604
- const matches = e instanceof BallException ? e.typeName === catchType : e.constructor?.name === catchType;
605
- if (!matches)
606
- continue;
607
- }
608
- const variable = cf.variable?.literal?.stringValue ?? 'e';
609
- if (cf.body) {
610
- const catchScope = scope.child();
611
- catchScope.bind(variable, e instanceof BallException ? e.value : (e instanceof Error ? e.message : String(e)));
612
- const prev = this.activeException;
613
- this.activeException = e;
614
- try {
615
- result = this.evalExpr(cf.body, catchScope);
616
- }
617
- finally {
618
- this.activeException = prev;
619
- }
620
- caught = true;
621
- break;
622
- }
623
- }
624
- if (!caught)
625
- throw e;
626
- }
627
- finally {
628
- if (fields.finally)
629
- this.evalExpr(fields.finally, scope);
630
- }
631
- return result;
632
- }
633
- evalShortCircuitAnd(call, scope) {
634
- const fields = this.lazyFields(call);
635
- if (!fields.left || !fields.right)
636
- return false;
637
- if (!this.toBool(this.evalExpr(fields.left, scope)))
638
- return false;
639
- return this.toBool(this.evalExpr(fields.right, scope));
640
- }
641
- evalShortCircuitOr(call, scope) {
642
- const fields = this.lazyFields(call);
643
- if (!fields.left || !fields.right)
644
- return false;
645
- if (this.toBool(this.evalExpr(fields.left, scope)))
646
- return true;
647
- return this.toBool(this.evalExpr(fields.right, scope));
648
- }
649
- evalReturn(call, scope) {
650
- const fields = this.lazyFields(call);
651
- const val = fields.value ? this.evalExpr(fields.value, scope) : null;
652
- return new FlowSignal('return', val);
653
- }
654
- evalAssign(call, scope) {
655
- const fields = this.lazyFields(call);
656
- if (!fields.value)
657
- return null;
658
- const val = this.evalExpr(fields.value, scope);
659
- // Target can be a reference expression or a string literal name.
660
- const target = fields.target ?? fields.name ?? fields.variable;
661
- if (!target)
662
- return null;
663
- let name;
664
- if (target.reference) {
665
- name = target.reference.name;
666
- }
667
- else if (target.literal?.stringValue) {
668
- name = target.literal.stringValue;
669
- }
670
- if (!name)
671
- return null;
672
- const op = fields.op?.literal?.stringValue;
673
- if (op && op !== '=') {
674
- const current = scope.lookup(name);
675
- const computed = this.applyCompoundOp(op, current, val);
676
- try {
677
- scope.assign(name, computed);
678
- }
679
- catch {
680
- scope.bind(name, computed);
681
- }
682
- return computed;
683
- }
684
- try {
685
- scope.assign(name, val);
686
- }
687
- catch {
688
- scope.bind(name, val);
689
- }
690
- return val;
691
- }
692
- applyCompoundOp(op, current, val) {
693
- const a = this.toNum(current);
694
- const b = this.toNum(val);
695
- switch (op) {
696
- case '+=': return a + b;
697
- case '-=': return a - b;
698
- case '*=': return a * b;
699
- case '/=': return Math.trunc(a / b);
700
- case '%=': return a % b;
701
- case '&=': return (a | 0) & (b | 0);
702
- case '|=': return (a | 0) | (b | 0);
703
- case '^=': return (a | 0) ^ (b | 0);
704
- case '<<=': return (a | 0) << (b | 0);
705
- case '>>=': return (a | 0) >> (b | 0);
706
- default: return val;
707
- }
708
- }
709
- evalIncDec(call, scope) {
710
- const fields = this.lazyFields(call);
711
- const valueExpr = fields.value;
712
- if (!valueExpr)
713
- return null;
714
- if (valueExpr.reference) {
715
- const name = valueExpr.reference.name;
716
- const current = this.toNum(scope.lookup(name));
717
- const isInc = call.function.includes('increment');
718
- const isPre = call.function.startsWith('pre');
719
- const updated = isInc ? current + 1 : current - 1;
720
- scope.assign(name, updated);
721
- return isPre ? updated : current;
722
- }
723
- // Fallback: just compute
724
- const val = this.toNum(this.evalExpr(valueExpr, scope));
725
- const isInc = call.function.includes('increment');
726
- return isInc ? val + 1 : val - 1;
727
- }
728
- evalLabeled(call, scope) {
729
- const fields = this.lazyFields(call);
730
- const label = fields.label?.literal?.stringValue;
731
- if (!fields.body)
732
- return null;
733
- const result = this.evalExpr(fields.body, scope);
734
- if (result instanceof FlowSignal && result.label === label) {
735
- if (result.kind === 'break')
736
- return null;
737
- }
738
- return result;
739
- }
740
- // ── Base function dispatch ────────────────────────────────────────────
741
- callBaseFunction(module, fn, input) {
742
- const left = input?.left;
743
- const right = input?.right;
744
- const value = input?.value;
745
- switch (fn) {
746
- // I/O
747
- case 'print':
748
- this.stdout(this.ballToString(value ?? input?.message ?? input));
749
- return null;
750
- // Arithmetic
751
- case 'add': {
752
- if (typeof left === 'string' || typeof right === 'string')
753
- return String(left ?? '') + String(right ?? '');
754
- return this.numOp(left, right, (a, b) => a + b);
755
- }
756
- case 'subtract': return this.numOp(left, right, (a, b) => a - b);
757
- case 'multiply': return this.numOp(left, right, (a, b) => a * b);
758
- case 'divide': return Math.trunc(this.toNum(left) / this.toNum(right));
759
- case 'divide_double': return this.toNum(left) / this.toNum(right);
760
- case 'modulo': return this.numOp(left, right, (a, b) => a % b);
761
- case 'negate': return -this.toNum(value ?? input);
762
- // Comparison
763
- case 'equals': return left === right;
764
- case 'not_equals': return left !== right;
765
- case 'less_than': return this.toNum(left) < this.toNum(right);
766
- case 'greater_than': return this.toNum(left) > this.toNum(right);
767
- case 'lte': return this.toNum(left) <= this.toNum(right);
768
- case 'gte': return this.toNum(left) >= this.toNum(right);
769
- // Logical
770
- case 'not': return !this.toBool(value ?? input);
771
- // String
772
- case 'concat': return String(left ?? '') + String(right ?? '');
773
- case 'to_string': return this.ballToString(value ?? input);
774
- case 'string_length': return String(value ?? input).length;
775
- case 'string_contains': return String(input?.string ?? '').includes(String(input?.substring ?? ''));
776
- case 'string_substring': return String(input?.string ?? '').substring(input?.start ?? 0, input?.end);
777
- case 'string_to_upper': return String(value ?? input).toUpperCase();
778
- case 'string_to_lower': return String(value ?? input).toLowerCase();
779
- case 'string_trim': return String(value ?? input).trim();
780
- case 'string_split': return String(input?.string ?? '').split(String(input?.delimiter ?? ''));
781
- case 'string_replace': return String(input?.string ?? '').replace(String(input?.from ?? ''), String(input?.to ?? ''));
782
- case 'string_replace_all': return String(input?.string ?? '').replaceAll(String(input?.from ?? ''), String(input?.to ?? ''));
783
- case 'string_starts_with': return String(input?.string ?? '').startsWith(String(input?.prefix ?? ''));
784
- case 'string_ends_with': return String(input?.string ?? '').endsWith(String(input?.suffix ?? ''));
785
- case 'string_index_of': return String(input?.string ?? '').indexOf(String(input?.substring ?? ''));
786
- // Type ops
787
- case 'is': return this.typeMatches(input?.value, input?.type);
788
- case 'is_not': return !this.typeMatches(input?.value, input?.type);
789
- case 'as': return input?.value;
790
- // Math
791
- case 'math_abs': return Math.abs(this.toNum(value ?? input));
792
- case 'math_floor': return Math.floor(this.toNum(value ?? input));
793
- case 'math_ceil': return Math.ceil(this.toNum(value ?? input));
794
- case 'math_round': return Math.round(this.toNum(value ?? input));
795
- case 'math_sqrt': return Math.sqrt(this.toNum(value ?? input));
796
- case 'math_pow': return Math.pow(this.toNum(input?.base ?? left), this.toNum(input?.exponent ?? right));
797
- case 'math_min': return Math.min(this.toNum(left), this.toNum(right));
798
- case 'math_max': return Math.max(this.toNum(left), this.toNum(right));
799
- case 'math_pi': return Math.PI;
800
- // Error handling
801
- case 'throw': {
802
- const rawVal = input?.value ?? input?.message ?? input;
803
- const typeName = input?.type ?? rawVal?.__type ?? 'Exception';
804
- throw new BallException(typeName, rawVal);
805
- }
806
- case 'rethrow': {
807
- if (this.activeException)
808
- throw this.activeException;
809
- throw new BallRuntimeError('rethrow outside of catch');
810
- }
811
- case 'assert': {
812
- if (!this.toBool(input?.condition ?? input)) {
813
- throw new BallRuntimeError(`Assertion failed: ${input?.message ?? ''}`);
814
- }
815
- return null;
816
- }
817
- // Collections
818
- case 'list_push': {
819
- const l = [...(input?.list ?? [])];
820
- l.push(input?.value);
821
- return l;
822
- }
823
- case 'list_length': return (input?.list ?? input ?? []).length;
824
- case 'list_get': return (input?.list ?? [])[input?.index ?? 0];
825
- case 'list_map': {
826
- const list = input?.list ?? [];
827
- const fn = input?.function;
828
- if (typeof fn === 'function')
829
- return list.map((item) => fn(item));
830
- return list;
831
- }
832
- case 'list_filter': {
833
- const list = input?.list ?? [];
834
- const fn = input?.function;
835
- if (typeof fn === 'function')
836
- return list.filter((item) => fn(item));
837
- return list;
838
- }
839
- case 'map_get': return (input?.map ?? {})[input?.key];
840
- case 'map_set': {
841
- const m = { ...(input?.map ?? {}) };
842
- m[input?.key] = input?.value;
843
- return m;
844
- }
845
- case 'map_keys': return Object.keys(input?.map ?? input ?? {});
846
- // Increment/decrement (pure value ops)
847
- case 'pre_increment':
848
- case 'post_increment': return this.toNum(value ?? input) + 1;
849
- case 'pre_decrement':
850
- case 'post_decrement': return this.toNum(value ?? input) - 1;
851
- // Index
852
- case 'index': {
853
- const target = input?.target ?? input?.list;
854
- const idx = input?.index ?? input?.key;
855
- if (Array.isArray(target))
856
- return target[idx];
857
- if (target && typeof target === 'object')
858
- return target[idx];
859
- if (typeof target === 'string')
860
- return target[idx];
861
- return null;
862
- }
863
- // Bitwise
864
- case 'bitwise_and': return (this.toNum(left) | 0) & (this.toNum(right) | 0);
865
- case 'bitwise_or': return (this.toNum(left) | 0) | (this.toNum(right) | 0);
866
- case 'bitwise_xor': return (this.toNum(left) | 0) ^ (this.toNum(right) | 0);
867
- case 'bitwise_not': return ~(this.toNum(value ?? input) | 0);
868
- case 'left_shift': return (this.toNum(left) | 0) << (this.toNum(right) | 0);
869
- case 'right_shift': return (this.toNum(left) | 0) >> (this.toNum(right) | 0);
870
- // Null
871
- case 'null_coalesce': return left ?? right;
872
- // Misc
873
- case 'paren': return value ?? input;
874
- case 'string_interpolation': return String(value ?? input);
875
- case 'int_to_string': return String(Math.trunc(this.toNum(value ?? input)));
876
- case 'double_to_string': return String(this.toNum(value ?? input));
877
- case 'string_to_int': return parseInt(String(value ?? input));
878
- case 'string_to_double': return parseFloat(String(value ?? input));
879
- case 'length': return (value ?? input)?.length ?? 0;
880
- default:
881
- throw new BallRuntimeError(`Unknown base function: ${module}.${fn}`);
882
- }
883
- }
884
- // ── Helpers ───────────────────────────────────────────────────────────
885
- typeMatches(value, type) {
886
- if (type === undefined || type === null)
887
- return false;
888
- // Primitive type checks
889
- switch (type) {
890
- case 'int': return typeof value === 'number' && Number.isInteger(value);
891
- case 'double': return typeof value === 'number';
892
- case 'num': return typeof value === 'number';
893
- case 'String': return typeof value === 'string';
894
- case 'bool': return typeof value === 'boolean';
895
- case 'List': return Array.isArray(value);
896
- case 'Map': return value !== null && typeof value === 'object' && !Array.isArray(value);
897
- case 'Null':
898
- case 'void': return value === null || value === undefined;
899
- case 'Object':
900
- case 'dynamic': return true;
901
- case 'Function': return typeof value === 'function';
902
- }
903
- // Check BallObject __type__ and walk __super__ chain
904
- if (value && typeof value === 'object' && !Array.isArray(value)) {
905
- if (this.typeNameMatches(value.__type__, type))
906
- return true;
907
- let superObj = value.__super__;
908
- while (superObj && typeof superObj === 'object' && !Array.isArray(superObj)) {
909
- if (this.typeNameMatches(superObj.__type__, type))
910
- return true;
911
- superObj = superObj.__super__;
912
- }
913
- }
914
- // Fallback: JS typeof check
915
- return typeof value === type;
916
- }
917
- typeNameMatches(objType, checkType) {
918
- if (!objType)
919
- return false;
920
- if (objType === checkType)
921
- return true;
922
- // objType is "module:Foo", checkType is "Foo"
923
- if (objType.endsWith(':' + checkType))
924
- return true;
925
- // objType is "Foo", checkType is "module:Foo"
926
- if (checkType.endsWith(':' + objType))
927
- return true;
928
- return false;
929
- }
930
- toBool(v) {
931
- if (v === null || v === undefined || v === false || v === 0 || v === '')
932
- return false;
933
- return true;
934
- }
935
- toNum(v) {
936
- if (typeof v === 'number')
937
- return v;
938
- if (typeof v === 'string')
939
- return Number(v) || 0;
940
- if (typeof v === 'boolean')
941
- return v ? 1 : 0;
942
- return 0;
943
- }
944
- numOp(left, right, op) {
945
- return op(this.toNum(left), this.toNum(right));
946
- }
947
- ballToString(v) {
948
- if (v === null || v === undefined)
949
- return 'null';
950
- if (typeof v === 'number') {
951
- return Number.isInteger(v) ? v.toString() : v.toString();
952
- }
953
- if (typeof v === 'boolean')
954
- return v.toString();
955
- if (Array.isArray(v))
956
- return `[${v.map(x => this.ballToString(x)).join(', ')}]`;
957
- if (typeof v === 'object')
958
- return JSON.stringify(v);
959
- return String(v);
94
+ return this._output;
960
95
  }
961
96
  }
97
+ // Re-export useful compiled-engine types for advanced consumers.
98
+ export { StdModuleHandler } from "./compiled_engine.js";
962
99
  //# sourceMappingURL=index.js.map