@ball-lang/engine 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/src/index.ts ADDED
@@ -0,0 +1,853 @@
1
+ /**
2
+ * Ball TypeScript Engine — interprets Ball programs directly from JSON.
3
+ *
4
+ * Runs in Node.js and browsers. No protobuf dependency — works with
5
+ * proto3 JSON representation of Ball programs.
6
+ *
7
+ * Usage:
8
+ * import { BallEngine } from '@ball-lang/engine';
9
+ * const engine = new BallEngine(programJson, { stdout: console.log });
10
+ * engine.run();
11
+ */
12
+
13
+ // ── Types ───────────────────────────────────────────────────────────────────
14
+
15
+ type BallValue = any;
16
+ type BallFunction = (input: BallValue) => BallValue;
17
+
18
+ interface Program {
19
+ name?: string;
20
+ version?: string;
21
+ modules: Module[];
22
+ entryModule: string;
23
+ entryFunction: string;
24
+ }
25
+
26
+ interface Module {
27
+ name: string;
28
+ functions: FunctionDef[];
29
+ moduleImports?: ModuleImport[];
30
+ }
31
+
32
+ interface ModuleImport {
33
+ name: string;
34
+ }
35
+
36
+ interface FunctionDef {
37
+ name: string;
38
+ isBase?: boolean;
39
+ body?: Expression;
40
+ outputType?: string;
41
+ metadata?: Record<string, any>;
42
+ }
43
+
44
+ interface Expression {
45
+ call?: FunctionCall;
46
+ literal?: Literal;
47
+ reference?: { name: string };
48
+ fieldAccess?: { object: Expression; field: string };
49
+ messageCreation?: { fields: FieldValuePair[] };
50
+ block?: Block;
51
+ lambda?: Lambda;
52
+ }
53
+
54
+ interface FunctionCall {
55
+ module?: string;
56
+ function: string;
57
+ input?: Expression;
58
+ }
59
+
60
+ interface Literal {
61
+ intValue?: string | number;
62
+ doubleValue?: number;
63
+ stringValue?: string;
64
+ boolValue?: boolean;
65
+ listValue?: { elements: Expression[] };
66
+ }
67
+
68
+ interface FieldValuePair {
69
+ name: string;
70
+ value: Expression;
71
+ }
72
+
73
+ interface Block {
74
+ statements: Statement[];
75
+ result?: Expression;
76
+ }
77
+
78
+ interface Statement {
79
+ let?: { name: string; value: Expression; metadata?: Record<string, any> };
80
+ expression?: Expression;
81
+ }
82
+
83
+ interface Lambda {
84
+ body: Expression;
85
+ metadata?: Record<string, any>;
86
+ }
87
+
88
+ // ── Flow signals ────────────────────────────────────────────────────────────
89
+
90
+ class FlowSignal {
91
+ kind: string;
92
+ value?: BallValue;
93
+ label?: string;
94
+ constructor(kind: string, value?: BallValue, label?: string) {
95
+ this.kind = kind;
96
+ this.value = value;
97
+ this.label = label;
98
+ }
99
+ }
100
+
101
+ class BallException {
102
+ typeName: string;
103
+ value: BallValue;
104
+ constructor(typeName: string, value: BallValue) {
105
+ this.typeName = typeName;
106
+ this.value = value;
107
+ }
108
+ }
109
+
110
+ class BallRuntimeError extends Error {
111
+ constructor(message: string) {
112
+ super(message);
113
+ this.name = 'BallRuntimeError';
114
+ }
115
+ }
116
+
117
+ // ── Scope ───────────────────────────────────────────────────────────────────
118
+
119
+ class Scope {
120
+ private bindings = new Map<string, BallValue>();
121
+ private parent?: Scope;
122
+ constructor(parent?: Scope) {
123
+ this.parent = parent;
124
+ }
125
+
126
+ bind(name: string, value: BallValue): void {
127
+ this.bindings.set(name, value);
128
+ }
129
+
130
+ has(name: string): boolean {
131
+ return this.bindings.has(name) || (this.parent?.has(name) ?? false);
132
+ }
133
+
134
+ lookup(name: string): BallValue {
135
+ if (this.bindings.has(name)) return this.bindings.get(name);
136
+ if (this.parent) return this.parent.lookup(name);
137
+ throw new BallRuntimeError(`Undefined variable: "${name}"`);
138
+ }
139
+
140
+ assign(name: string, value: BallValue): void {
141
+ if (this.bindings.has(name)) {
142
+ this.bindings.set(name, value);
143
+ return;
144
+ }
145
+ if (this.parent) {
146
+ this.parent.assign(name, value);
147
+ return;
148
+ }
149
+ throw new BallRuntimeError(`Cannot assign to undefined variable: "${name}"`);
150
+ }
151
+
152
+ child(): Scope {
153
+ return new Scope(this);
154
+ }
155
+ }
156
+
157
+ // ── Engine ──────────────────────────────────────────────────────────────────
158
+
159
+ export interface BallEngineOptions {
160
+ stdout?: (msg: string) => void;
161
+ stderr?: (msg: string) => void;
162
+ }
163
+
164
+ export class BallEngine {
165
+ private program: Program;
166
+ private stdout: (msg: string) => void;
167
+ private stderr: (msg: string) => void;
168
+ private functions = new Map<string, FunctionDef>();
169
+ private currentModule = '';
170
+ private activeException: any = null;
171
+ private output: string[] = [];
172
+
173
+ constructor(program: Program | string, options: BallEngineOptions = {}) {
174
+ this.program = typeof program === 'string' ? JSON.parse(program) : program;
175
+ this.stdout = options.stdout ?? ((msg) => this.output.push(msg));
176
+ this.stderr = options.stderr ?? (() => {});
177
+ this.buildLookupTables();
178
+ }
179
+
180
+ private buildLookupTables(): void {
181
+ for (const mod of this.program.modules) {
182
+ for (const fn of mod.functions) {
183
+ this.functions.set(`${mod.name}.${fn.name}`, fn);
184
+ }
185
+ }
186
+ }
187
+
188
+ run(): string[] {
189
+ const key = `${this.program.entryModule}.${this.program.entryFunction}`;
190
+ const fn = this.functions.get(key);
191
+ if (!fn) throw new BallRuntimeError(`Entry function "${key}" not found`);
192
+
193
+ const scope = new Scope();
194
+ this.currentModule = this.program.entryModule;
195
+ const result = this.callFunction(this.program.entryModule, fn, null, scope);
196
+
197
+ if (result instanceof FlowSignal && result.kind === 'return') {
198
+ return this.output;
199
+ }
200
+ return this.output;
201
+ }
202
+
203
+ getOutput(): string[] {
204
+ return this.output;
205
+ }
206
+
207
+ // ── Expression evaluation ─────────────────────────────────────────────
208
+
209
+ private evalExpr(expr: Expression, scope: Scope): BallValue {
210
+ if (expr.call) return this.evalCall(expr.call, scope);
211
+ if (expr.literal) return this.evalLiteral(expr.literal, scope);
212
+ if (expr.reference) return this.evalReference(expr.reference, scope);
213
+ if (expr.fieldAccess) return this.evalFieldAccess(expr.fieldAccess, scope);
214
+ if (expr.messageCreation) return this.evalMessageCreation(expr.messageCreation, scope);
215
+ if (expr.block) return this.evalBlock(expr.block, scope);
216
+ if (expr.lambda) return this.evalLambda(expr.lambda, scope);
217
+ return null;
218
+ }
219
+
220
+ private evalCall(call: FunctionCall, scope: Scope): BallValue {
221
+ const moduleName = call.module || this.currentModule;
222
+
223
+ // Lazy control flow
224
+ if (moduleName === 'std' || moduleName === 'dart_std') {
225
+ switch (call.function) {
226
+ case 'if': return this.evalLazyIf(call, scope);
227
+ case 'for': return this.evalLazyFor(call, scope);
228
+ case 'for_in': return this.evalLazyForIn(call, scope);
229
+ case 'while': return this.evalLazyWhile(call, scope);
230
+ case 'do_while': return this.evalLazyDoWhile(call, scope);
231
+ case 'switch': return this.evalLazySwitch(call, scope);
232
+ case 'try': return this.evalLazyTry(call, scope);
233
+ case 'and': return this.evalShortCircuitAnd(call, scope);
234
+ case 'or': return this.evalShortCircuitOr(call, scope);
235
+ case 'return': return this.evalReturn(call, scope);
236
+ case 'break': return new FlowSignal('break', undefined, this.lazyStringField(call, 'label'));
237
+ case 'continue': return new FlowSignal('continue', undefined, this.lazyStringField(call, 'label'));
238
+ case 'assign': return this.evalAssign(call, scope);
239
+ case 'labeled': return this.evalLabeled(call, scope);
240
+ case 'pre_increment': case 'post_increment':
241
+ case 'pre_decrement': case 'post_decrement':
242
+ return this.evalIncDec(call, scope);
243
+ }
244
+ }
245
+
246
+ // Eager evaluation
247
+ const input = call.input ? this.evalExpr(call.input, scope) : null;
248
+
249
+ // Fast path for explicit std calls
250
+ if (call.module === 'std' || call.module === 'dart_std') {
251
+ return this.callBaseFunction(call.module, call.function, input);
252
+ }
253
+
254
+ const key = `${moduleName}.${call.function}`;
255
+ const fn = this.functions.get(key);
256
+ if (fn?.isBase) return this.callBaseFunction(moduleName, call.function, input);
257
+
258
+ // Scope closure lookup
259
+ if (!call.module && scope.has(call.function)) {
260
+ const bound = scope.lookup(call.function);
261
+ if (typeof bound === 'function') return bound(input);
262
+ }
263
+
264
+ // Module function lookup
265
+ if (fn) return this.callFunction(moduleName, fn, input, scope);
266
+
267
+ // Fallback: scan all modules
268
+ for (const mod of this.program.modules) {
269
+ for (const f of mod.functions) {
270
+ if (f.name === call.function) {
271
+ return this.callFunction(mod.name, f, input, scope);
272
+ }
273
+ }
274
+ }
275
+
276
+ throw new BallRuntimeError(`Function "${key}" not found`);
277
+ }
278
+
279
+ private callFunction(moduleName: string, fn: FunctionDef, input: BallValue, parentScope: Scope): BallValue {
280
+ if (fn.isBase) return this.callBaseFunction(moduleName, fn.name, input);
281
+ if (!fn.body) return null;
282
+
283
+ const prevModule = this.currentModule;
284
+ this.currentModule = moduleName;
285
+
286
+ const fnScope = parentScope.child();
287
+ fnScope.bind('input', input);
288
+
289
+ // Destructure input fields as named parameters
290
+ const params = fn.metadata?.params;
291
+ if (params && Array.isArray(params)) {
292
+ if (params.length === 1 && (input === null || input === undefined || typeof input !== 'object' || Array.isArray(input))) {
293
+ // Single-param function with non-object input: bind directly
294
+ const name = typeof params[0] === 'string' ? params[0] : params[0].name;
295
+ if (name) fnScope.bind(name, input);
296
+ } else if (input && typeof input === 'object' && !Array.isArray(input)) {
297
+ for (let i = 0; i < params.length; i++) {
298
+ const p = params[i];
299
+ const name = typeof p === 'string' ? p : p.name;
300
+ if (!name) continue;
301
+ if (name in input) {
302
+ fnScope.bind(name, input[name]);
303
+ } else if (`arg${i}` in input) {
304
+ fnScope.bind(name, input[`arg${i}`]);
305
+ }
306
+ }
307
+ }
308
+ }
309
+
310
+ let result = this.evalExpr(fn.body, fnScope);
311
+ this.currentModule = prevModule;
312
+
313
+ if (result instanceof FlowSignal && result.kind === 'return') {
314
+ return result.value;
315
+ }
316
+ return result;
317
+ }
318
+
319
+ // ── Literals ──────────────────────────────────────────────────────────
320
+
321
+ private evalLiteral(lit: Literal, scope: Scope): BallValue {
322
+ if (lit.intValue !== undefined) return typeof lit.intValue === 'string' ? parseInt(lit.intValue) : lit.intValue;
323
+ if (lit.doubleValue !== undefined) return lit.doubleValue;
324
+ if (lit.stringValue !== undefined) return lit.stringValue;
325
+ if (lit.boolValue !== undefined) return lit.boolValue;
326
+ if (lit.listValue) return lit.listValue.elements.map(e => this.evalExpr(e, scope));
327
+ return null;
328
+ }
329
+
330
+ private evalReference(ref: { name: string }, scope: Scope): BallValue {
331
+ return scope.lookup(ref.name);
332
+ }
333
+
334
+ private evalFieldAccess(fa: { object: Expression; field: string }, scope: Scope): BallValue {
335
+ const obj = this.evalExpr(fa.object, scope);
336
+ // Handle string properties
337
+ if (typeof obj === 'string') {
338
+ if (fa.field === 'length') return obj.length;
339
+ return null;
340
+ }
341
+ // Handle array properties
342
+ if (Array.isArray(obj)) {
343
+ if (fa.field === 'length') return obj.length;
344
+ return null;
345
+ }
346
+ if (obj && typeof obj === 'object' && fa.field in obj) return obj[fa.field];
347
+ return null;
348
+ }
349
+
350
+ private evalMessageCreation(mc: { fields: FieldValuePair[] }, scope: Scope): BallValue {
351
+ const result: Record<string, BallValue> = {};
352
+ for (const f of mc.fields) {
353
+ result[f.name] = this.evalExpr(f.value, scope);
354
+ }
355
+ return result;
356
+ }
357
+
358
+ private evalBlock(block: Block, scope: Scope): BallValue {
359
+ const blockScope = scope.child();
360
+ let lastResult: BallValue = null;
361
+
362
+ for (const stmt of block.statements) {
363
+ if (stmt.let) {
364
+ const val = this.evalExpr(stmt.let.value, blockScope);
365
+ if (val instanceof FlowSignal) return val;
366
+ blockScope.bind(stmt.let.name, val);
367
+ }
368
+ if (stmt.expression) {
369
+ lastResult = this.evalExpr(stmt.expression, blockScope);
370
+ if (lastResult instanceof FlowSignal) return lastResult;
371
+ }
372
+ }
373
+
374
+ if (block.result) {
375
+ lastResult = this.evalExpr(block.result, blockScope);
376
+ }
377
+ return lastResult;
378
+ }
379
+
380
+ private evalLambda(lambda: Lambda, scope: Scope): BallValue {
381
+ return (input: BallValue) => {
382
+ const lambdaScope = scope.child();
383
+ lambdaScope.bind('input', input);
384
+ const params = lambda.metadata?.params;
385
+ if (params && Array.isArray(params)) {
386
+ if (params.length === 1 && (input === null || input === undefined || typeof input !== 'object' || Array.isArray(input))) {
387
+ const name = typeof params[0] === 'string' ? params[0] : params[0].name;
388
+ if (name) lambdaScope.bind(name, input);
389
+ } else if (input && typeof input === 'object' && !Array.isArray(input)) {
390
+ for (let i = 0; i < params.length; i++) {
391
+ const p = params[i];
392
+ const name = typeof p === 'string' ? p : p.name;
393
+ if (!name) continue;
394
+ if (name in input) {
395
+ lambdaScope.bind(name, input[name]);
396
+ } else if (`arg${i}` in input) {
397
+ lambdaScope.bind(name, input[`arg${i}`]);
398
+ }
399
+ }
400
+ }
401
+ }
402
+ const result = this.evalExpr(lambda.body, lambdaScope);
403
+ if (result instanceof FlowSignal && result.kind === 'return') return result.value;
404
+ return result;
405
+ };
406
+ }
407
+
408
+ // ── Lazy control flow ─────────────────────────────────────────────────
409
+
410
+ private lazyFields(call: FunctionCall): Record<string, Expression> {
411
+ if (!call.input?.messageCreation) return {};
412
+ const result: Record<string, Expression> = {};
413
+ for (const f of call.input.messageCreation.fields) {
414
+ result[f.name] = f.value;
415
+ }
416
+ return result;
417
+ }
418
+
419
+ private lazyStringField(call: FunctionCall, name: string): string | undefined {
420
+ const fields = this.lazyFields(call);
421
+ const expr = fields[name];
422
+ if (!expr?.literal?.stringValue) return undefined;
423
+ return expr.literal.stringValue;
424
+ }
425
+
426
+ private evalLazyIf(call: FunctionCall, scope: Scope): BallValue {
427
+ const fields = this.lazyFields(call);
428
+ if (!fields.condition) return null;
429
+ const cond = this.evalExpr(fields.condition, scope);
430
+ if (this.toBool(cond)) {
431
+ return fields.then ? this.evalExpr(fields.then, scope) : null;
432
+ }
433
+ return fields.else ? this.evalExpr(fields.else, scope) : null;
434
+ }
435
+
436
+ private evalLazyWhile(call: FunctionCall, scope: Scope): BallValue {
437
+ const fields = this.lazyFields(call);
438
+ while (true) {
439
+ if (fields.condition) {
440
+ if (!this.toBool(this.evalExpr(fields.condition, scope))) break;
441
+ }
442
+ if (fields.body) {
443
+ const result = this.evalExpr(fields.body, scope);
444
+ if (result instanceof FlowSignal) {
445
+ if (result.kind === 'return') return result;
446
+ if (result.label) return result;
447
+ if (result.kind === 'break') break;
448
+ if (result.kind === 'continue') continue;
449
+ }
450
+ }
451
+ }
452
+ return null;
453
+ }
454
+
455
+ private evalLazyDoWhile(call: FunctionCall, scope: Scope): BallValue {
456
+ const fields = this.lazyFields(call);
457
+ do {
458
+ if (fields.body) {
459
+ const result = this.evalExpr(fields.body, scope);
460
+ if (result instanceof FlowSignal) {
461
+ if (result.kind === 'return') return result;
462
+ if (result.kind === 'break') break;
463
+ }
464
+ }
465
+ if (fields.condition) {
466
+ if (!this.toBool(this.evalExpr(fields.condition, scope))) break;
467
+ } else break;
468
+ } while (true);
469
+ return null;
470
+ }
471
+
472
+ private evalLazyFor(call: FunctionCall, scope: Scope): BallValue {
473
+ const fields = this.lazyFields(call);
474
+ const forScope = scope.child();
475
+ if (fields.init) {
476
+ // Handle init as string literal "var i = 0" (encoder format)
477
+ if (fields.init.literal?.stringValue) {
478
+ const match = fields.init.literal.stringValue.match(/^(?:var|final|int|double|String)\s+(\w+)\s*=\s*(.+)$/);
479
+ if (match) {
480
+ const varName = match[1];
481
+ const rawVal = match[2].trim();
482
+ const parsed = rawVal === 'true' ? true : rawVal === 'false' ? false : (isNaN(Number(rawVal)) ? rawVal : Number(rawVal));
483
+ forScope.bind(varName, parsed);
484
+ }
485
+ } else if (fields.init.block) {
486
+ this.evalBlock(fields.init.block, forScope);
487
+ } else {
488
+ this.evalExpr(fields.init, forScope);
489
+ }
490
+ }
491
+ while (true) {
492
+ if (fields.condition) {
493
+ if (!this.toBool(this.evalExpr(fields.condition, forScope))) break;
494
+ }
495
+ if (fields.body) {
496
+ const result = this.evalExpr(fields.body, forScope);
497
+ if (result instanceof FlowSignal) {
498
+ if (result.kind === 'return') return result;
499
+ if (result.label) return result;
500
+ if (result.kind === 'break') break;
501
+ if (result.kind === 'continue') { if (fields.update) this.evalExpr(fields.update, forScope); continue; }
502
+ }
503
+ }
504
+ if (fields.update) this.evalExpr(fields.update, forScope);
505
+ }
506
+ return null;
507
+ }
508
+
509
+ private evalLazyForIn(call: FunctionCall, scope: Scope): BallValue {
510
+ const fields = this.lazyFields(call);
511
+ const varName = fields.variable?.literal?.stringValue ?? 'item';
512
+ if (!fields.iterable || !fields.body) return null;
513
+ const iterable = this.evalExpr(fields.iterable, scope);
514
+ if (!Array.isArray(iterable)) throw new BallRuntimeError('for_in: iterable is not a List');
515
+ for (const item of iterable) {
516
+ const loopScope = scope.child();
517
+ loopScope.bind(varName, item);
518
+ const result = this.evalExpr(fields.body, loopScope);
519
+ if (result instanceof FlowSignal) {
520
+ if (result.kind === 'return') return result;
521
+ if (result.label) return result;
522
+ if (result.kind === 'break') break;
523
+ if (result.kind === 'continue') continue;
524
+ }
525
+ }
526
+ return null;
527
+ }
528
+
529
+ private evalLazySwitch(call: FunctionCall, scope: Scope): BallValue {
530
+ const fields = this.lazyFields(call);
531
+ if (!fields.subject || !fields.cases) return null;
532
+ const subject = this.evalExpr(fields.subject, scope);
533
+ const cases = fields.cases.literal?.listValue?.elements ?? [];
534
+ let defaultBody: Expression | undefined;
535
+ for (const c of cases) {
536
+ if (!c.messageCreation) continue;
537
+ const cf: Record<string, Expression> = {};
538
+ for (const f of c.messageCreation.fields) cf[f.name] = f.value;
539
+ if (cf.is_default?.literal?.boolValue) { defaultBody = cf.body; continue; }
540
+ if (cf.value) {
541
+ const caseVal = this.evalExpr(cf.value, scope);
542
+ if (caseVal === subject && cf.body) return this.evalExpr(cf.body, scope);
543
+ }
544
+ }
545
+ if (defaultBody) return this.evalExpr(defaultBody, scope);
546
+ return null;
547
+ }
548
+
549
+ private evalLazyTry(call: FunctionCall, scope: Scope): BallValue {
550
+ const fields = this.lazyFields(call);
551
+ let result: BallValue = null;
552
+ try {
553
+ result = fields.body ? this.evalExpr(fields.body, scope) : null;
554
+ } catch (e: any) {
555
+ result = null;
556
+ const catches = fields.catches?.literal?.listValue?.elements ?? [];
557
+ let caught = false;
558
+ for (const c of catches) {
559
+ if (!c.messageCreation) continue;
560
+ const cf: Record<string, Expression> = {};
561
+ for (const f of c.messageCreation.fields) cf[f.name] = f.value;
562
+ const catchType = cf.type?.literal?.stringValue;
563
+ if (catchType) {
564
+ const matches = e instanceof BallException ? e.typeName === catchType : e.constructor?.name === catchType;
565
+ if (!matches) continue;
566
+ }
567
+ const variable = cf.variable?.literal?.stringValue ?? 'e';
568
+ if (cf.body) {
569
+ const catchScope = scope.child();
570
+ catchScope.bind(variable, e instanceof BallException ? e.value : (e instanceof Error ? e.message : String(e)));
571
+ const prev = this.activeException;
572
+ this.activeException = e;
573
+ try { result = this.evalExpr(cf.body, catchScope); }
574
+ finally { this.activeException = prev; }
575
+ caught = true;
576
+ break;
577
+ }
578
+ }
579
+ if (!caught) throw e;
580
+ } finally {
581
+ if (fields.finally) this.evalExpr(fields.finally, scope);
582
+ }
583
+ return result;
584
+ }
585
+
586
+ private evalShortCircuitAnd(call: FunctionCall, scope: Scope): BallValue {
587
+ const fields = this.lazyFields(call);
588
+ if (!fields.left || !fields.right) return false;
589
+ if (!this.toBool(this.evalExpr(fields.left, scope))) return false;
590
+ return this.toBool(this.evalExpr(fields.right, scope));
591
+ }
592
+
593
+ private evalShortCircuitOr(call: FunctionCall, scope: Scope): BallValue {
594
+ const fields = this.lazyFields(call);
595
+ if (!fields.left || !fields.right) return false;
596
+ if (this.toBool(this.evalExpr(fields.left, scope))) return true;
597
+ return this.toBool(this.evalExpr(fields.right, scope));
598
+ }
599
+
600
+ private evalReturn(call: FunctionCall, scope: Scope): BallValue {
601
+ const fields = this.lazyFields(call);
602
+ const val = fields.value ? this.evalExpr(fields.value, scope) : null;
603
+ return new FlowSignal('return', val);
604
+ }
605
+
606
+ private evalAssign(call: FunctionCall, scope: Scope): BallValue {
607
+ const fields = this.lazyFields(call);
608
+ if (!fields.value) return null;
609
+ const val = this.evalExpr(fields.value, scope);
610
+
611
+ // Target can be a reference expression or a string literal name.
612
+ const target = fields.target ?? fields.name ?? fields.variable;
613
+ if (!target) return null;
614
+
615
+ let name: string | undefined;
616
+ if (target.reference) {
617
+ name = target.reference.name;
618
+ } else if (target.literal?.stringValue) {
619
+ name = target.literal.stringValue;
620
+ }
621
+ if (!name) return null;
622
+
623
+ const op = fields.op?.literal?.stringValue;
624
+ if (op && op !== '=') {
625
+ const current = scope.lookup(name);
626
+ const computed = this.applyCompoundOp(op, current, val);
627
+ try { scope.assign(name, computed); } catch { scope.bind(name, computed); }
628
+ return computed;
629
+ }
630
+ try { scope.assign(name, val); } catch { scope.bind(name, val); }
631
+ return val;
632
+ }
633
+
634
+ private applyCompoundOp(op: string, current: BallValue, val: BallValue): BallValue {
635
+ const a = this.toNum(current);
636
+ const b = this.toNum(val);
637
+ switch (op) {
638
+ case '+=': return a + b;
639
+ case '-=': return a - b;
640
+ case '*=': return a * b;
641
+ case '/=': return Math.trunc(a / b);
642
+ case '%=': return a % b;
643
+ case '&=': return (a | 0) & (b | 0);
644
+ case '|=': return (a | 0) | (b | 0);
645
+ case '^=': return (a | 0) ^ (b | 0);
646
+ case '<<=': return (a | 0) << (b | 0);
647
+ case '>>=': return (a | 0) >> (b | 0);
648
+ default: return val;
649
+ }
650
+ }
651
+
652
+ private evalIncDec(call: FunctionCall, scope: Scope): BallValue {
653
+ const fields = this.lazyFields(call);
654
+ const valueExpr = fields.value;
655
+ if (!valueExpr) return null;
656
+
657
+ if (valueExpr.reference) {
658
+ const name = valueExpr.reference.name;
659
+ const current = this.toNum(scope.lookup(name));
660
+ const isInc = call.function.includes('increment');
661
+ const isPre = call.function.startsWith('pre');
662
+ const updated = isInc ? current + 1 : current - 1;
663
+ scope.assign(name, updated);
664
+ return isPre ? updated : current;
665
+ }
666
+
667
+ // Fallback: just compute
668
+ const val = this.toNum(this.evalExpr(valueExpr, scope));
669
+ const isInc = call.function.includes('increment');
670
+ return isInc ? val + 1 : val - 1;
671
+ }
672
+
673
+ private evalLabeled(call: FunctionCall, scope: Scope): BallValue {
674
+ const fields = this.lazyFields(call);
675
+ const label = fields.label?.literal?.stringValue;
676
+ if (!fields.body) return null;
677
+ const result = this.evalExpr(fields.body, scope);
678
+ if (result instanceof FlowSignal && result.label === label) {
679
+ if (result.kind === 'break') return null;
680
+ }
681
+ return result;
682
+ }
683
+
684
+ // ── Base function dispatch ────────────────────────────────────────────
685
+
686
+ private callBaseFunction(module: string, fn: string, input: BallValue): BallValue {
687
+ const left = input?.left;
688
+ const right = input?.right;
689
+ const value = input?.value;
690
+
691
+ switch (fn) {
692
+ // I/O
693
+ case 'print': this.stdout(this.ballToString(value ?? input?.message ?? input)); return null;
694
+
695
+ // Arithmetic
696
+ case 'add': {
697
+ if (typeof left === 'string' || typeof right === 'string') return String(left ?? '') + String(right ?? '');
698
+ return this.numOp(left, right, (a, b) => a + b);
699
+ }
700
+ case 'subtract': return this.numOp(left, right, (a, b) => a - b);
701
+ case 'multiply': return this.numOp(left, right, (a, b) => a * b);
702
+ case 'divide': return Math.trunc(this.toNum(left) / this.toNum(right));
703
+ case 'divide_double': return this.toNum(left) / this.toNum(right);
704
+ case 'modulo': return this.numOp(left, right, (a, b) => a % b);
705
+ case 'negate': return -this.toNum(value ?? input);
706
+
707
+ // Comparison
708
+ case 'equals': return left === right;
709
+ case 'not_equals': return left !== right;
710
+ case 'less_than': return this.toNum(left) < this.toNum(right);
711
+ case 'greater_than': return this.toNum(left) > this.toNum(right);
712
+ case 'lte': return this.toNum(left) <= this.toNum(right);
713
+ case 'gte': return this.toNum(left) >= this.toNum(right);
714
+
715
+ // Logical
716
+ case 'not': return !this.toBool(value ?? input);
717
+
718
+ // String
719
+ case 'concat': return String(left ?? '') + String(right ?? '');
720
+ case 'to_string': return this.ballToString(value ?? input);
721
+ case 'string_length': return String(value ?? input).length;
722
+ case 'string_contains': return String(input?.string ?? '').includes(String(input?.substring ?? ''));
723
+ case 'string_substring': return String(input?.string ?? '').substring(input?.start ?? 0, input?.end);
724
+ case 'string_to_upper': return String(value ?? input).toUpperCase();
725
+ case 'string_to_lower': return String(value ?? input).toLowerCase();
726
+ case 'string_trim': return String(value ?? input).trim();
727
+ case 'string_split': return String(input?.string ?? '').split(String(input?.delimiter ?? ''));
728
+ case 'string_replace': return String(input?.string ?? '').replace(String(input?.from ?? ''), String(input?.to ?? ''));
729
+ case 'string_replace_all': return String(input?.string ?? '').replaceAll(String(input?.from ?? ''), String(input?.to ?? ''));
730
+ case 'string_starts_with': return String(input?.string ?? '').startsWith(String(input?.prefix ?? ''));
731
+ case 'string_ends_with': return String(input?.string ?? '').endsWith(String(input?.suffix ?? ''));
732
+ case 'string_index_of': return String(input?.string ?? '').indexOf(String(input?.substring ?? ''));
733
+
734
+ // Type ops
735
+ case 'is': return typeof input?.value === input?.type;
736
+ case 'as': return input?.value;
737
+
738
+ // Math
739
+ case 'math_abs': return Math.abs(this.toNum(value ?? input));
740
+ case 'math_floor': return Math.floor(this.toNum(value ?? input));
741
+ case 'math_ceil': return Math.ceil(this.toNum(value ?? input));
742
+ case 'math_round': return Math.round(this.toNum(value ?? input));
743
+ case 'math_sqrt': return Math.sqrt(this.toNum(value ?? input));
744
+ case 'math_pow': return Math.pow(this.toNum(input?.base ?? left), this.toNum(input?.exponent ?? right));
745
+ case 'math_min': return Math.min(this.toNum(left), this.toNum(right));
746
+ case 'math_max': return Math.max(this.toNum(left), this.toNum(right));
747
+ case 'math_pi': return Math.PI;
748
+
749
+ // Error handling
750
+ case 'throw': {
751
+ const rawVal = input?.value ?? input?.message ?? input;
752
+ const typeName = input?.type ?? rawVal?.__type ?? 'Exception';
753
+ throw new BallException(typeName, rawVal);
754
+ }
755
+ case 'rethrow': {
756
+ if (this.activeException) throw this.activeException;
757
+ throw new BallRuntimeError('rethrow outside of catch');
758
+ }
759
+ case 'assert': {
760
+ if (!this.toBool(input?.condition ?? input)) {
761
+ throw new BallRuntimeError(`Assertion failed: ${input?.message ?? ''}`);
762
+ }
763
+ return null;
764
+ }
765
+
766
+ // Collections
767
+ case 'list_push': { const l = [...(input?.list ?? [])]; l.push(input?.value); return l; }
768
+ case 'list_length': return (input?.list ?? input ?? []).length;
769
+ case 'list_get': return (input?.list ?? [])[input?.index ?? 0];
770
+ case 'list_map': {
771
+ const list = input?.list ?? [];
772
+ const fn = input?.function;
773
+ if (typeof fn === 'function') return list.map((item: any) => fn(item));
774
+ return list;
775
+ }
776
+ case 'list_filter': {
777
+ const list = input?.list ?? [];
778
+ const fn = input?.function;
779
+ if (typeof fn === 'function') return list.filter((item: any) => fn(item));
780
+ return list;
781
+ }
782
+ case 'map_get': return (input?.map ?? {})[input?.key];
783
+ case 'map_set': { const m = { ...(input?.map ?? {}) }; m[input?.key] = input?.value; return m; }
784
+ case 'map_keys': return Object.keys(input?.map ?? input ?? {});
785
+
786
+ // Increment/decrement (pure value ops)
787
+ case 'pre_increment': case 'post_increment': return this.toNum(value ?? input) + 1;
788
+ case 'pre_decrement': case 'post_decrement': return this.toNum(value ?? input) - 1;
789
+
790
+ // Index
791
+ case 'index': {
792
+ const target = input?.target ?? input?.list;
793
+ const idx = input?.index ?? input?.key;
794
+ if (Array.isArray(target)) return target[idx];
795
+ if (target && typeof target === 'object') return target[idx];
796
+ if (typeof target === 'string') return target[idx];
797
+ return null;
798
+ }
799
+
800
+ // Bitwise
801
+ case 'bitwise_and': return (this.toNum(left) | 0) & (this.toNum(right) | 0);
802
+ case 'bitwise_or': return (this.toNum(left) | 0) | (this.toNum(right) | 0);
803
+ case 'bitwise_xor': return (this.toNum(left) | 0) ^ (this.toNum(right) | 0);
804
+ case 'bitwise_not': return ~(this.toNum(value ?? input) | 0);
805
+ case 'left_shift': return (this.toNum(left) | 0) << (this.toNum(right) | 0);
806
+ case 'right_shift': return (this.toNum(left) | 0) >> (this.toNum(right) | 0);
807
+
808
+ // Null
809
+ case 'null_coalesce': return left ?? right;
810
+
811
+ // Misc
812
+ case 'paren': return value ?? input;
813
+ case 'string_interpolation': return String(value ?? input);
814
+ case 'int_to_string': return String(Math.trunc(this.toNum(value ?? input)));
815
+ case 'double_to_string': return String(this.toNum(value ?? input));
816
+ case 'string_to_int': return parseInt(String(value ?? input));
817
+ case 'string_to_double': return parseFloat(String(value ?? input));
818
+ case 'length': return (value ?? input)?.length ?? 0;
819
+
820
+ default:
821
+ throw new BallRuntimeError(`Unknown base function: ${module}.${fn}`);
822
+ }
823
+ }
824
+
825
+ // ── Helpers ───────────────────────────────────────────────────────────
826
+
827
+ private toBool(v: BallValue): boolean {
828
+ if (v === null || v === undefined || v === false || v === 0 || v === '') return false;
829
+ return true;
830
+ }
831
+
832
+ private toNum(v: BallValue): number {
833
+ if (typeof v === 'number') return v;
834
+ if (typeof v === 'string') return Number(v) || 0;
835
+ if (typeof v === 'boolean') return v ? 1 : 0;
836
+ return 0;
837
+ }
838
+
839
+ private numOp(left: BallValue, right: BallValue, op: (a: number, b: number) => number): number {
840
+ return op(this.toNum(left), this.toNum(right));
841
+ }
842
+
843
+ private ballToString(v: BallValue): string {
844
+ if (v === null || v === undefined) return 'null';
845
+ if (typeof v === 'number') {
846
+ return Number.isInteger(v) ? v.toString() : v.toString();
847
+ }
848
+ if (typeof v === 'boolean') return v.toString();
849
+ if (Array.isArray(v)) return `[${v.map(x => this.ballToString(x)).join(', ')}]`;
850
+ if (typeof v === 'object') return JSON.stringify(v);
851
+ return String(v);
852
+ }
853
+ }