-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathScorecode.js
More file actions
1102 lines (978 loc) · 41.9 KB
/
Copy pathScorecode.js
File metadata and controls
1102 lines (978 loc) · 41.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Scorecode Interpreter
* A primitive functional programming language parser and interpreter.
* Generated by Gemini 3 pro.
*/
/**
* Scorecode object && export
* * @param {string} formula - The code to execute.
* @param {Object} specials - Context object containing special variables (e.g., 'value').
* @returns {number|function} - The result of the execution.
*/
const Scorecode = (function() {
// --- Configuration & Constants ---
const OPS = {
TERNARY: '?', COLON: ':',
OR: '|', AND: '&',
EQ: '=', NEQ: '!=', GT: '>', LT: '<',
MAX: 'max', MIN: 'min',
ADD: '+', SUB: '-',
MUL: '*', DIV: '/', MOD: '%',
POW: '^',
NOT: '!',
LPAREN: '(', RPAREN: ')',
LBRACKET: '[', RBRACKET: ']',
LBRACE: '{', RBRACE: '}',
LAMBDA_DEF: '#', LAMBDA_CALL: '@',
COMMA: ','
};
const UNARY_OPS = ['sin', 'cos', 'tan', 'asin', 'acos', 'atan'];
// Sentinel for rest-args (...) splatting. When a lambda declares '...' as
// its last argument, the binding scope receives an object tagged with this
// symbol. When such a value is later passed to another lambda call, the
// call site splats the carried values back into the argument list.
const REST_ARGS = Symbol('rest_args');
const isRestArgs = v => v && typeof v === 'object' && v[REST_ARGS] === true;
// Precedence levels (Higher runs first)
const PRECEDENCE = {
[OPS.LAMBDA_CALL]: 11, // @
'ITERATION': 11, // {code}(sum)
'UNARY': 10, // !, -, trig
[OPS.POW]: 9,
[OPS.MUL]: 8, [OPS.DIV]: 8, [OPS.MOD]: 8,
[OPS.ADD]: 7, [OPS.SUB]: 7,
[OPS.MAX]: 6, [OPS.MIN]: 6,
[OPS.LT]: 5, [OPS.GT]: 5, [OPS.EQ]: 5,
[OPS.AND]: 4,
[OPS.OR]: 3,
[OPS.TERNARY]: 2,
[OPS.COLON]: 1
};
// --- Errors ---
class ScorecodeError extends Error {
constructor(message, token) {
super(message + (token ? ` at index ${token.index}` : ''));
this.name = "ScorecodeError";
}
}
// --- AST Nodes ---
// Using classes for V8 hidden class optimization
class Node {
evaluate(scope, specials) { throw new Error("Method not implemented"); }
static type = 'node';
}
class ConstantNode extends Node {
constructor(value) { super(); this.value = value; }
evaluate() { return this.value; }
static type = 'constant';
}
class SpecialVarNode extends Node {
constructor(name) { super(); this.name = name; }
evaluate(scope, specials) {
// Priority: Lambda Scope -> Specials Object
if (scope && scope.has(this.name)) return scope.get(this.name);
if (specials && Object.prototype.hasOwnProperty.call(specials, this.name)) {
return specials[this.name];
}
throw new ScorecodeError(`Unknown special/argument: '${this.name}'`);
}
static type = 'special';
}
class TrackerNode extends Node {
constructor(name) { super(); this.name = name; }
evaluate(scope, specials) {
const t = window.trackGet(this.name);
if (t instanceof LambdaDefNode) { return t.evaluate(scope, specials) } else { return t; }
}
static type = 'tracker';
}
class EnvNode extends Node {
constructor(name) { super(); this.name = name; }
evaluate() {
const val = window.get(this.name);
if (typeof val !== 'number' && typeof val !== 'boolean') {
throw new ScorecodeError(`Environment variable [[${this.name}]] must be number or boolean.`);
}
return Number(val);
}
static type = 'env';
}
class DynamicNode extends Node {
constructor(key, args) {
super();
this.key = key;
this.args = args; // Array of string or AST Node
}
evaluate(scope, specials) {
const evaluatedArgs = this.args.map(arg => {
if (arg instanceof Node) return arg.evaluate(scope, specials);
return arg;
});
const result = window.watchKey(this.key, ...evaluatedArgs);
/*if (typeof result === 'string') {
throw new ScorecodeError(`Dynamic variable [${this.key}] returned a string, which is forbidden.`);
}*/
return result;
}
static type = 'dynamic';
}
class UnaryNode extends Node {
constructor(operator, expression) {
super();
this.op = operator;
this.expression = expression;
}
evaluate(scope, specials) {
const val = this.expression.evaluate(scope, specials);
if (typeof val === 'string') {
throw new ScorecodeError('Illegal string operation: cannot apply "' + this.op + '" to a string');
}
// Handle Lambda passthrough if needed, but usually unary ops apply to numbers
switch (this.op) {
case '!': return val ? 0 : 1;
case '-': return -val;
case 'sin': return Math.sin(val);
case 'cos': return Math.cos(val);
case 'tan': return Math.tan(val);
case 'asin': return Math.asin(val);
case 'acos': return Math.acos(val);
case 'atan': return Math.atan(val);
default: throw new ScorecodeError(`Unknown unary operator ${this.operator}`);
}
}
static type = 'unary';
}
class BinaryNode extends Node {
constructor(operator, left, right) {
super();
this.op = operator;
this.left = left;
this.right = right;
}
evaluate(scope, specials) {
const l = this.left.evaluate(scope, specials);
const r = this.right.evaluate(scope, specials);
if ((typeof l === 'string' || typeof r === 'string') && this.op !== '=') {
throw new ScorecodeError('Illegal string operation: cannot apply "' + this.op + '" to strings');
}
switch (this.op) {
case '+': return l + r;
case '-': return l - r;
case '*': return l * r;
case '/': return r === 0 ? 0 : l / r;
case '%': return r === 0 ? 0 : l % r;
case '^': return Math.pow(l, r);
case 'max': return Math.max(l, r);
case 'min': return Math.min(l, r);
case '<': return (l < r) ? 1 : 0;
case '>': return (l > r) ? 1 : 0;
case '=': return (l === r) ? 1 : 0;
case '&': return (l && r) ? 1 : 0;
case '|': return (l || r) ? 1 : 0;
default: throw new ScorecodeError(`Unknown binary operator ${this.op}`);
}
}
static type = 'binary';
}
class TernaryNode extends Node {
constructor(cond, trueExpr, falseExpr) {
super();
this.cond = cond;
this.trueExpr = trueExpr;
this.falseExpr = falseExpr;
}
evaluate(scope, specials) {
const condition = this.cond.evaluate(scope, specials);
if (typeof condition === 'string') {
throw new ScorecodeError('Illegal string operation: cannot evaluate truthy-ness of a string');
}
if (condition) return this.trueExpr.evaluate(scope, specials);
return this.falseExpr.evaluate(scope, specials);
}
static type = 'ternary';
}
class LambdaDefNode extends Node {
constructor(args, bodyNode) {
super();
this.args = args; // Array of strings
this.body = bodyNode;
}
evaluate(scope, specials) {
// Return a wrapper that executes the body with a new scope
return {
type: 'lambda',
args: this.args,
body: this.body,
parentScope: scope // Closures not explicitly requested but good practice
};
}
static type = 'lambda';
}
class LambdaCallNode extends Node {
constructor(funcNode, argNodes) {
super();
this.funcNode = funcNode;
this.argNodes = argNodes;
}
evaluate(scope, specials) {
const lambda = this.funcNode.evaluate(scope, specials);
if (!lambda || lambda.type !== 'lambda') {
throw new ScorecodeError("Attempted to call a non-lambda value: " + lambda);
}
// Evaluate raw call args, then splat any rest-args placeholders so
// that '...' passed through another call expands to its carried values.
const rawArgValues = this.argNodes.map(n => n.evaluate(scope, specials));
const argValues = [];
for (const v of rawArgValues) {
if (isRestArgs(v)) {
for (const inner of v.values) argValues.push(inner);
} else {
argValues.push(v);
}
}
// Create new scope for execution
const newScope = new Map(lambda.parentScope); // Inherit (optional based on spec, but usually safe)
lambda.args.forEach((argName, index) => {
if (argName === '...') {
// Triple dot must be the last argument and captures the
// remaining call-site values. Inner lambdas that declare
// their own '...' naturally shadow the outer one, since
// their scope is built fresh from the call args.
newScope.set('...', { [REST_ARGS]: true, values: argValues.slice(index) });
return;
}
if (index < argValues.length) {
newScope.set(argName, argValues[index]);
}
});
return lambda.body.evaluate(newScope, specials);
}
static type = 'lambda_call';
}
class IterationNode extends Node {
constructor(maxNode, codeNode, sumNode) {
super();
this.maxNode = maxNode;
this.codeNode = codeNode;
this.sumNode = sumNode;
}
evaluate(scope, specials) {
const max = this.maxNode.evaluate(scope, specials);
const codeLambda = this.codeNode.evaluate(scope, specials);
const sumLambda = this.sumNode.evaluate(scope, specials);
if (codeLambda.type !== 'lambda' || sumLambda.type !== 'lambda') {
throw new ScorecodeError("Iteration requires lambda functions for code and summation");
}
if (typeof max === 'string') {
throw new ScorecodeError("Iteration count must be a number");
}
if (max < 1) { return 0; }
let codeScopeT = new Map(scope);
if (codeLambda.args[0]) codeScopeT.set(codeLambda.args[0], 0);
if (codeLambda.args[1]) codeScopeT.set(codeLambda.args[1], 0);
if (codeLambda.args[2]) codeScopeT.set(codeLambda.args[2], max);
let accumulator = codeLambda.body.evaluate(codeScopeT, specials);
for (let i = 1; i < max; i++) {
// Execute Code: (i, currentSum, max)
let codeScope = new Map(scope);
if (codeLambda.args[0]) codeScope.set(codeLambda.args[0], i);
if (codeLambda.args[1]) codeScope.set(codeLambda.args[1], accumulator);
if (codeLambda.args[2]) codeScope.set(codeLambda.args[2], max);
const codeResult = codeLambda.body.evaluate(codeScope, specials);
// Execute Summation: (accumulator, codeResult)
let sumScope = new Map(scope);
if (sumLambda.args[0]) sumScope.set(sumLambda.args[0], accumulator);
if (sumLambda.args[1]) sumScope.set(sumLambda.args[1], codeResult);
accumulator = sumLambda.body.evaluate(sumScope, specials);
}
return accumulator;
}
static type = 'iteration';
}
// --- Tokenizer ---
class Tokenizer {
constructor(input, pos) {
this.input = input;
this.pos = pos ?? 0;
this.length = input.length;
}
hasMore() { return this.pos < this.length; }
peek() { return this.input[this.pos]; }
tokenize() {
// Entry point
const tokens = this.process();
if (this.hasMore()) {
throw new ScorecodeError('Uncaught closing bracket (\']\') or semicolon at index ' + this.pos);
}
return tokens;
}
process() {
const tokens = [];
let inDynamic = false;
let pendingSemicolon = false;
while (this.hasMore()) {
const char = this.input[this.pos];
// 1. Whitespace (Ignored)
if (/\s/.test(char)) {
this.pos++;
continue;
}
// 1b. Single-line comments (// ... until newline, exclusive)
// A comment is defined as all characters following the '//' substring,
// including the substring itself, up to the next new line character.
if (char === '/' && this.input[this.pos + 1] === '/') {
while (this.hasMore() && this.input[this.pos] !== '\n') {
this.pos++;
}
continue;
}
// 2. Numbers
if (/[0-9]/.test(char) || (char === '.' && /[0-9]/.test(this.input[this.pos+1]))) {
let numStr = "";
while (this.hasMore() && (/[0-9.]/.test(this.input[this.pos]))) {
numStr += this.input[this.pos++];
}
tokens.push({ type: 'NUMBER', value: parseFloat(numStr), index: this.pos - numStr.length });
pendingSemicolon = false;
continue;
}
if (inDynamic) {
if (/[a-zA-Z_-\s0-9]+/.test(char)) {
// Numbers are already matched before
const begins = this.pos;
let content = this.readPureString();
tokens.push({ type: 'STR', value: content, index: begins });
pendingSemicolon = false;
continue;
}
if (char === ';') {
if (pendingSemicolon) {
throw new ScorecodeError('Empty watcher argument at index ' + this.pos);
}
this.pos++;
pendingSemicolon = true;
continue;
}
if (char === ']') {
if (pendingSemicolon) {
throw new ScorecodeError('Empty watcher argument at index ' + this.pos);
}
const begins = this.pos;
this.pos++;
inDynamic = false;
tokens.push({ type: 'DYNEND', index: begins });
continue;
}
if (char === '$') {
this.pos++;
const begins = this.pos;
let content = this.tokenizeSub(this.pos);
this.pos = content[content.length - 1].index;
content.pop();
tokens.push({ type: 'ARG', value: content, index: begins });
pendingSemicolon = false;
continue;
}
}
// Will catch something later on or it errors, so safe to set here
pendingSemicolon = false;
// 3. Operators (Multi-char first)
if (this.input.startsWith('max', this.pos)) { tokens.push({ type: 'OP', value: 'max', index: this.pos }); this.pos += 3; continue; }
if (this.input.startsWith('min', this.pos)) { tokens.push({ type: 'OP', value: 'min', index: this.pos }); this.pos += 3; continue; }
if (this.input.startsWith('true', this.pos)) { tokens.push({ type: 'NUMBER', value: 1, index: this.pos }); this.pos += 4; continue; }
if (this.input.startsWith('false', this.pos)) { tokens.push({ type: 'NUMBER', value: 0, index: this.pos }); this.pos += 5; continue; }
// Rest-args token '...': only meaningful in lambda-arg position,
// but emitted as a generic OP here so the parser can enforce rules.
if (this.input[this.pos] === '.' && this.input[this.pos + 1] === '.' && this.input[this.pos + 2] === '.') {
tokens.push({ type: 'OP', value: '...', index: this.pos });
this.pos += 3;
continue;
}
// Trig unary operators
let matchedTrig = false;
for (const trig of UNARY_OPS) {
if (this.input.startsWith(trig, this.pos)) {
// Ensure it's not part of a longer word? (unlikely given syntax rules, but good for safety)
tokens.push({ type: 'OP', value: trig, index: this.pos });
this.pos += trig.length;
matchedTrig = true;
break;
}
}
if (matchedTrig) continue;
// Single char operators
if ('+-*/%^<>=&|!?:()#@{},'.includes(char)) {
tokens.push({ type: 'OP', value: char, index: this.pos });
this.pos++;
continue;
}
// 4. Variables/Inputs
// Environment [[...]]
if (this.input.startsWith('[[', this.pos)) {
this.pos += 2;
let content = this.readUntil(']]');
tokens.push({ type: 'ENV', value: content, index: this.pos });
continue;
}
// Dynamic [...]
if (char === '[') {
const begins = this.pos;
this.pos++;
inDynamic = true;
let content = this.readUntilDynamic();
tokens.push({ type: 'DYN', value: content, index: begins });
continue;
}
if ((char === ']' || char === ';') && !inDynamic) {
tokens.push({ type: 'TERM', index: this.pos });
return tokens;
}
// Trackers "..."
if (char === '"') {
const begins = this.pos;
this.pos++;
let content = this.readUntil('"');
tokens.push({ type: 'TRACK', value: content, index: begins });
continue;
}
// Specials '...'
if (char === "'") {
const begins = this.pos;
this.pos++;
let content = this.readUntil("'");
tokens.push({ type: 'SPEC', value: content, index: begins });
continue;
}
throw new ScorecodeError(`Unexpected character: ${char}`, { index: this.pos });
}
if (inDynamic) {
throw new ScorecodeError(`Missing closing ']' at the end of formula (index ${this.pos})`);
}
return tokens;
}
tokenizeSub(pos) {
const tokens = (new Tokenizer(this.input, pos)).process();
if (!tokens.length) {
throw new ScorecodeError(`Empty argument specification`);
}
return tokens;
}
readUntil(endStr) {
let result = "";
while (this.hasMore()) {
if (this.input.startsWith(endStr, this.pos)) {
this.pos += endStr.length;
return result;
}
result += this.input[this.pos++];
}
throw new ScorecodeError(`Unclosed delimiter, expected '${endStr}'`);
}
readUntilDynamic() {
let result = "";
while (this.hasMore()) {
if (this.input.startsWith(']', this.pos) || this.input.startsWith(';', this.pos)) {
return result;
}
result += this.input[this.pos++];
}
throw new ScorecodeError(`Unclosed delimiter, expected '${endStr}'`);
}
readPureString() {
let result = "";
while (this.hasMore()) {
if (this.input.startsWith(']', this.pos) || this.input.startsWith(';', this.pos)) {
return result;
}
result += this.input[this.pos++];
}
throw new ScorecodeError(`Unbounded watcher argument string specification`);
}
}
// --- Parser ---
class Parser {
constructor(tokens) {
this.tokens = tokens;
this.pos = 0;
this.posOffset = 0;
}
setPosOffset(pos) {
this.posOffset = pos;
return this;
}
peek() { return this.tokens[this.pos]; }
consume() { return this.tokens[this.pos++]; }
match(val) {
if (this.pos < this.tokens.length && this.tokens[this.pos].value === val) {
this.consume();
return true;
}
return false;
}
parse() {
if (this.tokens.length === 0) {
return new ConstantNode(0);
}
const ast = this.parseExpression();
if (this.pos < this.tokens.length) {
throw new ScorecodeError("Unexpected token remaining after parsing", this.peek());
}
return ast;
}
parseExpression() {
let lhs = this.parseLogicalOr();
// Ternary ? :
if (this.match('?')) {
const trueExpr = this.parseExpression(); // Recurse
if (!this.match(':')) throw new ScorecodeError("Expected ':' in ternary operator", this.peek());
const falseExpr = this.parseExpression();
lhs = new TernaryNode(lhs, trueExpr, falseExpr);
}
return lhs;
}
parseLogicalOr() {
let lhs = this.parseLogicalAnd();
while (this.match('|')) {
const rhs = this.parseLogicalAnd();
lhs = new BinaryNode('|', lhs, rhs);
}
return lhs;
}
parseLogicalAnd() {
let lhs = this.parseComparison();
while (this.match('&')) {
const rhs = this.parseComparison();
lhs = new BinaryNode('&', lhs, rhs);
}
return lhs;
}
parseComparison() {
let lhs = this.parseMinMax();
while (true) {
const token = this.peek();
if (token && ['<', '>', '='].includes(token.value)) {
this.consume();
const rhs = this.parseMinMax();
lhs = new BinaryNode(token.value, lhs, rhs);
} else {
break;
}
}
return lhs;
}
parseMinMax() {
let lhs = this.parseSum();
while (true) {
const token = this.peek();
if (token && ['min', 'max'].includes(token.value)) {
this.consume();
const rhs = this.parseSum();
lhs = new BinaryNode(token.value, lhs, rhs);
} else {
break;
}
}
return lhs;
}
parseSum() {
let lhs = this.parseProduct();
while (true) {
const token = this.peek();
if (token && ['+', '-'].includes(token.value)) {
this.consume();
const rhs = this.parseProduct();
lhs = new BinaryNode(token.value, lhs, rhs);
} else {
break;
}
}
return lhs;
}
parseProduct() {
let lhs = this.parsePower();
while (true) {
const token = this.peek();
if (token && ['*', '/', '%'].includes(token.value)) {
this.consume();
const rhs = this.parsePower();
lhs = new BinaryNode(token.value, lhs, rhs);
} else {
break;
}
}
return lhs;
}
parsePower() {
let lhs = this.parseUnary();
if (this.match('^')) {
const rhs = this.parsePower(); // Right associative usually, or just parseUnary
lhs = new BinaryNode('^', lhs, rhs);
}
return lhs;
}
parseUnary() {
const token = this.peek();
// Negation, Not, Trig
if (token && (token.value === '!' || token.value === '-' || UNARY_OPS.includes(token.value))) {
this.consume();
const expr = this.parseUnary(); // Recursive for !!x or -sin(x)
return new UnaryNode(token.value, expr);
}
return this.parsePostfix();
}
// Handles Iteration and Lambda Calls as Postfix operations on a Primary
parsePostfix() {
let node = this.parsePrimary();
while (true) {
if (this.match('@')) {
// Lambda Call: (func)@(args)
if (!this.match('(')) throw new ScorecodeError("Expected '(' after '@'", this.peek());
const args = [];
if (!this.match(')')) {
do {
// '...' in arg position forwards the current scope's
// rest-args marker. Resolved as a SpecialVarNode so the
// call-site's LambdaCallNode.evaluate can splat it.
const argTok = this.peek();
if (argTok && argTok.type === 'OP' && argTok.value === '...') {
this.consume();
args.push(new SpecialVarNode('...'));
} else {
args.push(this.parseExpression());
}
} while (this.match(','));
if (!this.match(')')) throw new ScorecodeError("Expected ')' after arguments", this.peek());
}
node = new LambdaCallNode(node, args);
} else if (this.match('{')) {
// Iteration: (max){code}(summation)
// At this point 'node' is 'max'
// Parse Code Lambda
const code = this.parseExpression(); // This should result in a LambdaDefNode usually
if (!this.match('}')) throw new ScorecodeError("Expected '}' after iteration code", this.peek());
// Parse Summation Lambda
if (!this.match('(')) throw new ScorecodeError("Expected '(' for summation part of iteration", this.peek());
const summation = this.parseExpression();
if (!this.match(')')) throw new ScorecodeError("Expected ')' closing summation", this.peek());
node = new IterationNode(node, code, summation);
} else {
break;
}
}
return node;
}
parsePrimary() {
const token = this.peek();
if (!token) throw new ScorecodeError("Unexpected end of input");
if (token.type === 'NUMBER') {
this.consume();
return new ConstantNode(token.value);
}
if (token.type === 'SPEC') {
this.consume();
return new SpecialVarNode(token.value);
}
if (token.type === 'TRACK') {
this.consume();
return new TrackerNode(token.value);
}
if (token.type === 'ENV') {
this.consume();
return new EnvNode(token.value);
}
if (token.type === 'DYN') {
this.consume();
// Parse args inside [key;arg1;$expr]
const key = token.value;
const args = [];
while(true) {
const curToken = this.peek();
if (curToken.type === 'DYNEND') {
this.consume();
break;
}
if (curToken.type === 'STR' || curToken.type === 'NUMBER') {
args.push(curToken.value);
this.consume();
continue;
}
if (curToken.type === 'ARG') {
args.push((new Parser(curToken.value)).parse());
this.consume();
continue;
}
throw new ScorecodeError("Unclosed watcher call (missing ']') at index " + this.pos);
}
return new DynamicNode(key, args);
}
if (this.match('(')) {
// Could be grouped expression OR Lambda definition
// If we see args followed by )#, it is a lambda def.
// However, args are just identifiers enclosed in single quotes?
// "When using any argument the name should be wrapped in single quotes"
// This implies args in definition are also single quoted?
// Prompt: "define by (arg1, arg2, …)#(code)"
// "arg1" is an identifier. Given the whitespace rules, probably standard identifiers or quoted.
// Let's assume standard parsing. If we see comma or ')' followed by '#', it is a lambda.
// We need to look ahead or parse tentatively.
// Simpler: Parse a list of potential args. If we hit '#', convert to LambdaDef.
// If not, it must be a simple parenthesized expression (which cannot have commas).
// Lookahead check for lambda
let isLambda = false;
let scanPos = this.pos;
// Scan until matching paren
let depth = 1;
while(scanPos < this.tokens.length) {
const t = this.tokens[scanPos];
if(t.value === '(') depth++;
if(t.value === ')') {
depth--;
if(depth === 0) {
// Check next token
if (this.tokens[scanPos + 1] && this.tokens[scanPos+1].value === '#') {
isLambda = true;
}
break;
}
}
scanPos++;
}
if (isLambda) {
// Parse Lambda Def
const args = [];
if (this.peek().value !== ')') {
let sawRest = false;
do {
const argToken = this.peek();
if (argToken.type === 'OP' && argToken.value === '...') {
if (sawRest) {
throw new ScorecodeError("'...' may only appear once in a lambda argument list", argToken);
}
args.push('...');
sawRest = true;
this.consume();
// '...' must be the final argument.
if (this.peek().value !== ')') {
throw new ScorecodeError("'...' must be the last argument in a lambda definition", this.peek());
}
break;
}
if (sawRest) {
throw new ScorecodeError("'...' must be the last argument in a lambda definition", argToken);
}
if (argToken.type !== 'SPEC') throw new ScorecodeError("Lambda arguments must be enclosed in single quotes", argToken);
args.push(argToken.value);
this.consume();
} while (this.match(','));
}
if (!this.match(')')) throw new ScorecodeError("Expected ')' after lambda args");
if (!this.match('#')) throw new ScorecodeError("Expected '#' after lambda args");
if (!this.match('(')) throw new ScorecodeError("Expected '(' for lambda body");
const body = this.parseExpression();
if (!this.match(')')) throw new ScorecodeError("Expected ')' after lambda body");
return new LambdaDefNode(args, body);
} else {
// Standard grouping
const expr = this.parseExpression();
if (!this.match(')')) throw new ScorecodeError("Expected ')'");
return expr;
}
}
throw new ScorecodeError("Unexpected token", token);
}
}
/**
* Annotates Scorecode with HTML <span> tags for syntax highlighting.
* @param {string} code - The raw Scorecode string.
* @returns {string} - The HTML string with highlighted classes.
*/
function highlightScorecode(code) {
let i = 0;
let out = "";
// Helper to safely append HTML
const push = (className, text) => {
if (!text) return;
const escaped = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
if (className) {
out += `<span class="an ${className}">${escaped}</span>`;
} else {
out += escaped; // Raw push for whitespace
}
};
// Helper to read contiguous valid variable characters
const readVarChars = () => {
let start = i;
while (i < code.length && /[a-zA-Z0-9_\s]/.test(code[i])) i++;
return code.substring(start, i);
};
while (i < code.length) {
let char = code[i];
let remaining = code.substring(i);
// 1. Whitespace
if (/\s/.test(char)) {
push(null, char);
i++;
continue;
}
// 1b. Single-line comments (// ... until newline, exclusive)
if (char === '/' && code[i + 1] === '/') {
const begins = i;
while (i < code.length && code[i] !== '\n') i++;
push('comment', code.substring(begins, i));
continue;
}
// 2. Environment Variables: [[var_name]]
if (remaining.startsWith('[[')) {
push('orange', '[[');
i += 2;
let inner = "";
while (i < code.length && !code.substring(i).startsWith(']]')) {
inner += code[i++];
}
push(/^[a-zA-Z0-9_\s]+$/.test(inner) ? 'white' : 'warning', inner);
if (code.substring(i).startsWith(']]')) {
push('orange', ']]');
i += 2;
}
continue;
}
// 3. Dynamic Variables: [name;arg1;$code]
if (char === '[') {
push('orange', '[');
i++;
// Name
let varName = readVarChars();
if (varName) push('white', varName);
// Arguments
while (i < code.length && code[i] !== ']') {
if (code[i] === ';') {
push('yellow', ';');
i++;
if (code[i] === '$') {
// Enter recursive code mode
push('yellow', '$');
i++;
let depth = 0;
let codeStr = "";
while (i < code.length) {
if (code[i] === '[') depth++;
else if (code[i] === ']') {
if (depth === 0) break;
depth--;
} else if (code[i] === ';' && depth === 0) {
break;
}
codeStr += code[i++];
}
out += highlightScorecode(codeStr); // Highlight nested code
} else {
// Plain string argument
let argStr = "";
while (i < code.length && code[i] !== ';' && code[i] !== ']') {
argStr += code[i++];
}
// Only highlight valid characters in plain string args
for (let c of argStr) {
if (/[a-zA-Z0-9_\s]/.test(c)) push('white', c);
else if (/\s/.test(c)) push(null, c);
else push('warning', c);
}
}
} else {
push('warning', code[i]);
i++;
}
}
if (i < code.length && code[i] === ']') {
push('orange', ']');
i++;
}
continue;
}
// 4. Trackers: "name"