-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
505 lines (446 loc) · 14.2 KB
/
index.js
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
/**
* Token class represents a lexical token with a type and value.
* The type is one of: EOF, LAMBDA, LPAREN, RPAREN, LCID, DOT.
* The value is the actual string content of the token.
*
* @example
* new Token(Token.LAMBDA, 'λ') // Represents a lambda symbol
* new Token(Token.LCID, 'x') // Represents a variable name
* new Token(Token.DOT, '.') // Represents the dot separator
* new Token(Token.EOF, '') // Represents end of input
*/
class Token {
constructor(type, value) {
this.type = type;
this.value = value;
}
};
const tokenStrings = [
'EOF', // we augment the tokens with EOF, to indicate the end of the input.
'LAMBDA',
'LPAREN',
'RPAREN',
'LCID',
'DOT',
]
tokenStrings.forEach(token => {
Token[token] = token;
});
/**
* Lexer class handles tokenization of the input string into a sequence of tokens.
* It maintains state about the current position in the input and provides methods
* to advance through the input character by character, converting them into tokens
* according to the lambda calculus syntax rules.
*
* @example
* const lexer = new Lexer('λx.x'); // Create lexer for λx.x
* lexer.token(); // Returns Token{type: 'LAMBDA', value: 'λ'}
* lexer.nextToken(); // Advances to next token
* lexer.token(); // Returns Token{type: 'LCID', value: 'x'}
* lexer.nextToken(); // Advances to next token
* lexer.token(); // Returns Token{type: 'DOT', value: '.'}
* lexer.nextToken(); // Advances to next token
* lexer.token(); // Returns Token{type: 'LCID', value: 'x'}
* lexer.nextToken(); // Advances to next token
* lexer.token(); // Returns Token{type: 'EOF', value: ''}
*/
class Lexer {
constructor(input) {
this._input = input;
this._index = 0;
this._token = undefined;
this._nextToken()
}
/**
* Return the next char of the input or '\0' if we've reached the end
*/
_nextChar() {
if (this._index >= this._input.length) {
return '\0';
}
return this._input[this._index++];
}
/**
* Set this._token based on the remaining of the input
*
* This method is meant to be private, it doesn't return a token, just sets
* up the state for the helper functions.
*/
_nextToken() {
let char = this._nextChar();
if (char === '\0') {
this._token = new Token(Token.EOF, '');
return;
}
if (char === '(') {
this._token = new Token(Token.LPAREN, char);
return;
}
if (char === ')') {
this._token = new Token(Token.RPAREN, char);
return;
}
if (char === '.') {
this._token = new Token(Token.DOT, char);
return;
}
if (char === '\\' || char === 'λ') {
this._token = new Token(Token.LAMBDA, char);
return;
}
if (char === ' ') {
this._nextToken();
return;
}
// Handle LCID - lowercase identifiers
if (/[a-z]/.test(char)) {
this._token = new Token(Token.LCID, char);
return;
}
throw new Error(`Unexpected character: ${char}`);
}
/**
* Return true if the next token is of type t
*/
next(t) {
return this._token.type === t;
}
/**
* Returns the current token value without consuming it
*/
peek() {
return this._token.value;
}
/**
* Skip the next token if it matches t
*/
skip(t) {
if (this.next(t)) {
const value = this._token.value;
this._nextToken();
return value;
}
return false;
}
/**
* Assert that the next token is of type t, and skip it
*/
match(t) {
if (!this.next(t)) {
throw new Error(`Expected token: ${t}`);
}
const value = this._token.value;
this._nextToken();
return value;
}
/**
* Assert that the next token is of type t, and return its value
*/
token(t) {
if (!this.next(t)) {
throw new Error(`Expected token: ${t}`);
}
const value = this._token.value;
this._nextToken();
return value;
}
}
class Abstraction {
/**
* Represents a lambda abstraction (λx. body) in the lambda calculus.
*
* Why this exists:
* - In lambda calculus, abstractions define functions with a single parameter
* - They are one of the core building blocks, alongside applications and variables
*
* Structure:
* - param: The bound variable name (the 'x' in λx. body)
* - body: The expression that forms the function body
*
* Implementation notes:
* - We don't need a separate node for the λ symbol since:
* 1. It's implicit in the Abstraction node type
* 2. λ always appears with a parameter and body together
* 3. The symbol itself carries no additional semantic meaning
*
* Example:
* For λx. x y
* - param would be "x"
* - body would be an Application node of (x y)
*/
constructor(param, body) {
this.param = param;
this.body = body;
}
toString(ctx = []) {
// Add parentheses around applications in the body
const bodyStr = this.body instanceof Application
? `(${this.body.toString([this.param].concat(ctx))})`
: this.body.toString([this.param].concat(ctx));
return `(λ${this.param}. ${bodyStr})`;
}
}
class Application {
/**
* (lhs rhs) - left-hand side and right-hand side of an application.
*/
constructor(lhs, rhs) {
this.lhs = lhs;
this.rhs = rhs;
}
toString(ctx = []) {
// Add parentheses around nested applications in lhs
const lhsStr = this.lhs instanceof Application
? `(${this.lhs.toString(ctx)})`
: this.lhs.toString(ctx);
// Add parentheses around rhs only if it's an application
// (not for abstractions - they already have their own parentheses)
const rhsStr = this.rhs instanceof Application
? `(${this.rhs.toString(ctx)})`
: this.rhs.toString(ctx);
return `${lhsStr} ${rhsStr}`;
}
}
class Identifier {
/**
* name is the string matched for this identifier.
*/
constructor(value) {
this.value = value;
}
toString(ctx = []) {
return this.value;
}
}
/**
* Parser class handles the conversion of a string input into a tree structure
* representing the lambda calculus expression.
*
* It uses the Lexer class to tokenize the input and then builds the tree structure
* based on the grammar rules defined in the lambda calculus.
*
* Example:
* Input: "λx. x y"
* Output:
* new Abstraction(
* "x",
* new Application(
* new Identifier("x"),
* new Identifier("y")
* )
* )
*
*/
class Parser {
/**
* Grammar rules being implemented:
* term ::= application
* | LAMBDA LCID DOT term
*
* atom ::= LPAREN term RPAREN
* | LCID
*/
constructor(input) {
this.lexer = new Lexer(input);
}
/**
* Parse a term according to the grammar rule:
* term ::= application
* | LAMBDA LCID DOT term [this is an abstraction]
*
* example:
* λx. x y
*/
parseTerm() {
// Check if it starts with a lambda
if (this.lexer.skip(Token.LAMBDA)) { // VERIFY and CONSUME lambda if present. Skip to next token.
// If yes, this is an abstraction.
const param = this.lexer.token(Token.LCID); // GET and CONSUME parameter name
this.lexer.match(Token.DOT); // CONSUME dot
const body = this.parseTerm(); // Recursively parse the body
return new Abstraction(param, body);
}
// If not a lambda, it must be an application
return this.parseApplication();
}
/**
* Parse an atom according to the grammar rule:
* atom ::= LPAREN term RPAREN
* | LCID
*/
parseAtom() {
if (this.lexer.skip(Token.LPAREN)) { // Check and consume left parenthesis if present
const term = this.parseTerm(); // Parse the term inside
this.lexer.match(Token.RPAREN); // Consume right parenthesis
return term;
}
// If not parenthesized, must be an identifier
if (this.lexer.next(Token.LCID)) {
const name = this.lexer.token(Token.LCID);
return new Identifier(name);
}
throw new Error('Expected atom');
}
/**
* Parse an application according to the grammar rule:
* application ::= atom application'
* application' ::= atom application'
* | ε
*
* This handles left-associative application like:
* f x y z => ((f x) y) z
*/
parseApplication() {
let lhs = this.parseAtom();
// Keep consuming atoms as right-hand sides while we have them
while (!this.lexer.next(Token.EOF) &&
!this.lexer.next(Token.RPAREN) &&
!this.lexer.next(Token.DOT)) {
const rhs = this.parseAtom();
lhs = new Application(lhs, rhs);
}
return lhs;
}
/**
* Main entry point for parsing
*/
parse() {
const term = this.parseTerm();
this.lexer.match(Token.EOF); // Make sure we've reached the end of input
return term;
}
}
class Interpreter {
constructor(input, options = {}) {
this.parser = new Parser(input);
this.AST = { Application, Abstraction, Identifier };
this.debug = options.debug || false;
this.steps = [];
this.stepCount = 0;
this.MAX_STEPS = options.maxSteps || 10000;
this._usedVariables = new Set();
}
evaluate() {
const ast = this.parser.parse();
this.stepCount = 0;
this.steps = [];
try {
const result = this._evaluate(ast);
if (this.debug) {
this.steps.push({ step: this.stepCount, term: result.toString() });
}
return result;
} catch (e) {
if (this.debug) {
console.error(`Evaluation error: ${e.message}`);
}
throw e;
}
}
_isValue(node) {
return node instanceof this.AST.Abstraction ||
node instanceof this.AST.Identifier;
}
_evaluate(ast) {
let current = ast;
while (this.stepCount < this.MAX_STEPS) {
if (this.debug) {
this.steps.push({ step: this.stepCount, term: current.toString() });
console.log(`Step ${this.stepCount}: ${current.toString()}`);
}
let next = null;
if (current instanceof this.AST.Application) {
// Normal order: reduce leftmost outermost
if (!this._isValue(current.lhs)) {
current.lhs = this._evaluate(current.lhs);
this.stepCount++;
continue;
}
if (current.lhs instanceof this.AST.Abstraction) {
next = this._substitute(current.lhs.param, current.rhs, current.lhs.body);
} else if (!this._isValue(current.rhs)) {
current.rhs = this._evaluate(current.rhs);
this.stepCount++;
continue;
}
} else if (current instanceof this.AST.Abstraction) {
const newBody = this._evaluate(current.body);
if (newBody !== current.body) {
next = new this.AST.Abstraction(current.param, newBody);
}
}
if (next !== null) {
current = next;
this.stepCount++;
} else {
break;
}
}
if (this.stepCount >= this.MAX_STEPS) {
throw new Error(`Evaluation exceeded ${this.MAX_STEPS} steps`);
}
return current;
}
_substitute(param, arg, node) {
if (node instanceof this.AST.Identifier) {
return node.value === param ? arg : node;
}
if (node instanceof this.AST.Application) {
return new this.AST.Application(
this._substitute(param, arg, node.lhs),
this._substitute(param, arg, node.rhs)
);
}
if (node instanceof this.AST.Abstraction) {
if (node.param === param) {
return node;
}
const freeVars = this._getFreeVariables(arg);
if (freeVars.has(node.param)) {
const newParam = this._freshVariable(node.param);
const newBody = this._substitute(node.param, new this.AST.Identifier(newParam), node.body);
return new this.AST.Abstraction(
newParam,
this._substitute(param, arg, newBody)
);
}
return new this.AST.Abstraction(
node.param,
this._substitute(param, arg, node.body)
);
}
}
_getFreeVariables(node) {
const freeVars = new Set();
if (node instanceof this.AST.Identifier) {
freeVars.add(node.value);
} else if (node instanceof this.AST.Application) {
this._getFreeVariables(node.lhs).forEach(v => freeVars.add(v));
this._getFreeVariables(node.rhs).forEach(v => freeVars.add(v));
} else if (node instanceof this.AST.Abstraction) {
this._getFreeVariables(node.body).forEach(v => {
if (v !== node.param) freeVars.add(v);
});
}
return freeVars;
}
_freshVariable(base) {
let counter = 1;
let newName = `${base}'`;
while (this._usedVariables.has(newName)) {
newName = `${base}'${counter++}`;
}
this._usedVariables.add(newName);
return newName;
}
getSteps() {
return this.steps;
}
}
module.exports = {
Parser,
Abstraction,
Application,
Identifier,
Interpreter
};