-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathScorecode.js
More file actions
736 lines (642 loc) · 27.7 KB
/
Copy pathScorecode.js
File metadata and controls
736 lines (642 loc) · 27.7 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
/*
* 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: '/',
POW: '^',
NOT: '!',
LPAREN: '(', RPAREN: ')',
LBRACKET: '[', RBRACKET: ']',
LBRACE: '{', RBRACE: '}',
LAMBDA_DEF: '#', LAMBDA_CALL: '@',
COMMA: ','
};
const UNARY_OPS = ['sin', 'cos', 'tan', 'asin', 'acos', 'atan'];
// 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.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"); }
}
class ConstantNode extends Node {
constructor(value) { super(); this.value = value; }
evaluate() { return this.value; }
}
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}'`);
}
}
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; }}
}
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);
}
}
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;
}
}
class UnaryNode extends Node {
constructor(operator, expression) {
super();
this.operator = operator;
this.expression = expression;
}
evaluate(scope, specials) {
const val = this.expression.evaluate(scope, specials);
// Handle Lambda passthrough if needed, but usually unary ops apply to numbers
switch (this.operator) {
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}`);
}
}
}
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);
switch (this.op) {
case '+': return l + r;
case '-': return l - r;
case '*': return 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}`);
}
}
}
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 (condition) return this.trueExpr.evaluate(scope, specials);
return this.falseExpr.evaluate(scope, specials);
}
}
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
};
}
}
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");
}
const argValues = this.argNodes.map(n => n.evaluate(scope, specials));
// 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 (index < argValues.length) {
newScope.set(argName, argValues[index]);
}
});
return lambda.body.evaluate(newScope, specials);
}
}
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 (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], accumulator);
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;
}
}
// --- Tokenizer ---
class Tokenizer {
constructor(input) {
this.input = input;
this.pos = 0;
this.length = input.length;
}
hasMore() { return this.pos < this.length; }
peek() { return this.input[this.pos]; }
tokenize() {
const tokens = [];
while (this.hasMore()) {
const char = this.input[this.pos];
// 1. Whitespace (Ignored)
if (/\s/.test(char)) {
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 });
continue;
}
// 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; }
// 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 === '[') {
this.pos++;
let content = this.readBracketUntil(']', '[');
tokens.push({ type: 'DYN', value: content, index: this.pos });
continue;
}
// Trackers "..."
if (char === '"') {
this.pos++;
let content = this.readUntil('"');
tokens.push({ type: 'TRACK', value: content, index: this.pos });
continue;
}
// Specials '...'
if (char === "'") {
this.pos++;
let content = this.readUntil("'");
tokens.push({ type: 'SPEC', value: content, index: this.pos });
continue;
}
throw new ScorecodeError(`Unexpected character: ${char}`, { index: this.pos });
}
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}'`);
}
readBracketUntil(endStr, skipStr) {
// Not failproof, careful when using.
// Human patched.
let result = "";
let layer = 1;
while (this.hasMore()) {
if (this.input.startsWith(skipStr, this.pos)) {
layer++;
this.pos += skipStr.length;
result += skipStr;
continue;
}
if (this.input.startsWith(endStr, this.pos)) {
this.pos += endStr.length;
layer--;
if (layer == 0) {
return result;
}
result += endStr;
continue;
}
result += this.input[this.pos++];
}
throw new ScorecodeError(`Unclosed delimiter, expected '${endStr}'`);
}
}
// --- Parser ---
class Parser {
constructor(tokens) {
this.tokens = tokens;
this.pos = 0;
}
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() {
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 {
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 parts = token.value.split(';');
const key = parts[0];
const args = [];
for (let i = 1; i < parts.length; i++) {
const argStr = parts[i];
if (argStr.startsWith('$')) {
// It is a dynamic expression, parse it separately
// Create a temporary parser for this substring
const subTokenizer = new Tokenizer(argStr.substring(1));
const subParser = new Parser(subTokenizer.tokenize());
args.push(subParser.parse());
} else {
args.push(argStr);
}
}
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 !== ')') {
do {
// The parser tokenized 'arg' as SPEC (if quoted) or...
// The prompt says "When using any argument the name should be wrapped in single quotes".
// This likely applies to usage. For definition: "(arg1, arg2)".
// These tokens would likely be parsed as 'identifiers' but our tokenizer doesn't have identifiers,
// it has SPEC (quoted) or error.
// BUT: "Whitespace is ignored, except for names in variables."
// If I write (a,b), 'a' is unknown char.
// Interpretation: Args in definition must be valid tokens.
// If they are unquoted text, our tokenizer throws "Unexpected character".
// Assumption: Arguments in definition MUST be single quoted: "('a', 'b')#( ... )"
// OR: We update tokenizer to allow bare words, but treat them as errors unless in specific context?
// Safest bet based on "primitive": Arguments must be defined as quoted strings too, or the tokenizer needs to support identifiers.
// Let's support Quoted strings (SPEC) as arguments.
const argToken = this.peek();
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);
}
}
// --- Main Export Functions ---
function tokenize(formula) {
return new Tokenizer(formula).tokenize();
}
function parse(formulaOrTokens) {
const tokens = Array.isArray(formulaOrTokens) ? formulaOrTokens : tokenize(formulaOrTokens);
return new Parser(tokens).parse();
}
function execute(formula, specials) {
const ast = parse(formula);
return ast.evaluate(null, specials);
}
// Expose API
execute.tokenize = tokenize;
execute.parse = parse;
return execute;
})();