-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjlisp.js
468 lines (413 loc) · 10.7 KB
/
jlisp.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
(function(undefined) {
var isNodeJsEnvironment = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined');
var global = this;
var globalScope = {
'T': true,
'NIL': false
};
var structures = {};
var output = null;
var lib = {
'+': function(args) {
var res = 0;
for (var i = 0; i < args.length; i++) {
res += args[i];
}
return res;
},
'-': function(args) {
var res = args.length > 1 ? args[0] : 0;
for (var i = args.length > 1 ? 1 : 0; i < args.length; i++) {
res -= args[i];
}
return res; //ako je jedan onda 0-prvi, inace prvi-ostali
},
'*': function(args) {
var res = 1;
for (var i = 0; i < args.length; i++) {
res *= args[i];
}
return res;
},
'quote': function(args) {
return args[0];
},
'<': function(args) {
if (args.length > 2) {
return 'NIL';
} //kako ovo hendlati?//pa valjda se ocekuje da je evalano vec?!
if (eval(args[0]) < eval(args[1])) {
return true;
} else {
return false;
}
},
'>': function(args) {
if (args.length > 2) {
return 'NIL';
} //kako ovo hendlati? //isto tako valjda je evalano
if (eval(args[0]) > eval(args[1])) {
return true;
} else {
return false;
}
},
'lt': function(args) {
return this['<'](args);
}, //ovako sinonime pisati
'car': function(args) {
//checkiraj broj argsa
return args[0][0]; //args[0] je lista, 0i clan nje
},
'cdr': function(args) {
return args[0].slice(1);
},
'list': function(args) {
ret = [];
for (var i = 0; i < args.length; i++) {
ret.push(args[i]);
}
return ret;
},
'nth': function(args) {
return args[1][parseInt(args[0])];
},
'print': function(args) {
output(args[0]);
},
'eq': function(args) {
if (args[0] == args[1]) {
return true;
} else {
return false;
}
},
'cons': function(args, scope) { //only in case the eval, evaluates args before passing to function
if (args.length != 2) {
error('Illegal number of arguments to CONS function ' + args.length);
}
var res = [];
var fir = args[0];
var sec = args[1];
var fa = fir instanceof Array;
var sa = sec instanceof Array;
if (fa) {
if (sa) {
res.push(fir);
return res.concat(sec);
} else {
if (sec !== undefined)
return fir.concat(sec);
else {
res.push(fir);
return res;
}
}
} else {
if (sa) {
res.push(fir);
return res.concat(sec);
} else {
if (fir !== undefined)
res.push(fir);
if (sec !== undefined)
res.push(sec);
return res;
}
}
return res;
},
'load': function(args, scope) {
//var fs = require('fs');
//var contents = fs.readFileSync(args[0]).toString();
//contents = contents.replace(/\n+/g, '');
},
'rand': function(args, scope) {
return Math.round(Math.random());
}
};
var specials = {
'defun': function(args, definitionScope) { //ime fje (arg or multy) (body) (body2) (body3)
var funcName = args[0];
var params = args[1];
var funcBody = args.slice(2);
var fun = function(args, callingScope) {
var retVal = null;
//calling scope na atributima glavni, definition scope za lokalne varijable ne moze biti pregazen nikako, cak ni definiranjem ponovo u callingscopeu
for (var i = 0; i < funcBody.length; i++) {
retVal = eval(funcBody[i], bind(params, args, callingScope)); //izostavljen scope u kojem je fja definirana
}
return retVal;
};
lib[funcName] = fun;
return funcName;
},
'lambda': function(params, body, args, scope) {
for (var i = 0; i < args.length; i++) {
args[i] = eval(args[i], scope);
}
return eval(body, bind(params, args, scope));
},
'if': function(args, scope) {
if (args.length != 3) {
//raise error, wrong number of arguments
return false;
}
if (eval(args[0], scope)) {
return eval(args[1], scope);
} else {
return eval(args[2], scope);
}
},
'quote': function(args, scope) {
if (args.length != 1) {
//raise error, illegal number of arguments
throw 'hes dead jim! :/ too many damn arguments';
return;
}
return args[0]; //ne evaluatea nist, samo vrati
},
'let': function(args, scope) {
var bindings = args[0];
var bodies = args.slice(1);
var innerScope = {};
for (var i = 0; i < bindings.length; i++) {
var symbol = bindings[i][0];
var val = eval(bindings[i][1], scope);
innerScope[symbol] = val;
}
innerScope.__proto__ = scope;
var res = 0;
for (var i = 0; i < bodies.length; i++) {
res = eval(bodies[i], innerScope);
}
return res;
},
'setq': function(args, scope) {
var val;
var symbol;
for (var i = 0; i < args.length; i += 2) {
symbol = args[i];
val = eval(args[i + 1], scope);
globalScope[symbol] = val;
}
return val;
},
'defstruct': function(args, scope) {
//strukture su immutable
//generira strukturu
//u fje doda za svaki atribut structa imestructa-atribut fju
//(defstruct ime atr1 atr2 atr3...)
var name = args[0];
var attributes = args.slice(1);
var struct = {}; //definition
struct.attributes = {};
struct.name = name;
struct.accessors = [];
struct.setters = [];
attributes.forEach(function(attr) {
struct.attributes[attr] = null;
});
// output('defined: ' + name);
// output(struct);
var constructorName = 'make-' + name;
var constructor = function(consArgs, callingScope) { //argsi pocinju s :
var instance = {};
for (var definedAttr in struct.attributes) {
if (struct.attributes.hasOwnProperty(definedAttr)) {
instance[definedAttr] = null;
}
}
for (var i = 0; i < consArgs.length; i += 2) {
// console.log(consArgs[i] + ' ' + consArgs[i + 1]);
instance[consArgs[i]] = consArgs[i + 1];
}
// output('constructed: ');
// output(instance);
return instance;
}
attributes.forEach(function(attr) {
var accessorName = name + '-' + attr;
// output('creating accessor ' + accessorName);
var accessor = function(args) {
var instance = args[0];
return instance[attr];
}
struct.accessors.push(accessor);
lib[accessorName] = accessor;
});
specials[constructorName] = constructor; //konstruktori specialsi jer oni ne evalaju argumente, vratiti na fje kad se doda :arg
return name;
},
'do': function(args, scope) { // (do ((x 1 (+ x 1))) ((eq 2 1) 1) (print x)) //DO-WHILE!
debugger
var init = args[0][0]; //only one init and increment for now
var inc = init[2];
var cond = args[1][0];
var retValue = args[1][1];
//setting scope variables
scope[init[0]] = eval(init[1], scope);
var bodies = args.slice(2); //also one for now, multiplying trivial
do {
for (var i = 0; i < bodies.length; i++) {
eval(bodies[i], scope);
}
scope[init[0]] = eval(inc, scope);
} while (!eval(cond, scope));
return retValue;
}
};
var preSplit = function(line) {
line = line.replace(/[\n\r]/g, '');
line = line.replace(/ +/g, ' ');
return line.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ');
};
//lexer
var scan = function(str) {
var ret = [];
var read = false;
var curr = "";
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (c == " ") {
if (read) {
ret.push(curr);
}
curr = "";
read = false;
} else {
curr += c;
if (!read) read = true;
}
}
// console.log('Lexical stage: ');
// console.log(ret);
// console.log('======================================');
return ret;
};
//parser, syntax analysis
var parse = function(tokens) {
var ret = [];
if (tokens.length < 2) {
error('Invalid token number');
}
for (var i = 0; i < tokens.length; i++) {
if (tokens[i] == "(") {
ret.push(parse(tokens.slice(i + 1)));
i++;
var j = 0;
while (true) { //fastforward sramota
if (i >= tokens.length) {
error('Syntax error. Missing some closing brackets.');
}
if (j === 0 && tokens[i] === ')') {
break;
}
if (tokens[i] == "(") {
j++;
} else if (tokens[i] == ")") {
j--;
}
i++;
}
} else if (tokens[i] == ")") {
return ret;
} else {
ret.push(tokens[i]);
}
}
// console.log('Syntactical stage: ');
// console.log(ret);
// console.log('======================================');
return ret;
};
//binds formal to actual params creating new closure with the calling one as parent and still accessible if not hidden by the new binding
var bind = function(formal, actual, parentScope) {
var closure = {};
for (var i = 0; i < formal.length; i++) {
closure[formal[i]] = actual[i];
}
closure.__proto__ = parentScope;
return closure;
};
var eval = function(atom, scope) {
//ako je array, onda je s-izraz inace atom
if (atom instanceof Array) {
var fja = atom[0];
var args = atom.slice(1);
// Check if lambda
if (fja instanceof Array) {
if (fja[0].toLowerCase() == 'lambda') {
var lParams = fja[1];
var lBody = fja[2];
return specials.lambda(lParams, lBody, args, scope);
} else {
error('Invalid lambda expression');
}
}
//check if special
if (specials.hasOwnProperty(fja)) {
return specials[fja](args, scope); //specialsi vracaju function obj
};
//postoji li fja, evalaj redom argse, prosljedi ih fji
var evaluatedArgs = [];
for (var i = 0; i < args.length; i++) {
evaluatedArgs.push(eval(args[i], scope));
}
if (lib.hasOwnProperty(fja)) {
//fja treba raditi? optimizacija kod OR-a npr...
return lib[fja](evaluatedArgs, scope);
} else {
error('Undefined function');
}
} else if (atom instanceof Object) {
return atom;
} else {
var intTry = parseInt(atom, 10); // probaj i double
if (isNaN(intTry)) {
return scope[atom];
} else {
return intTry;
}
}
};
var evaluateLine = function(line) {
var results = [];
var structure = parse(scan(preSplit(line)));
for (var g = 0; g < structure.length; g++) {
results.push(eval(structure[g], globalScope));
}
for (var g = 0; g < results.length; g++) {
output(results[g]);
}
return results;
};
var error = function(errorText) {
output(errorText);
throw 'LISP Error: ' + errorText;
};
var defaultOutput = function(out) {
console.log(out);
};
var setOutput = function(newOutput) {
output = newOutput;
};
output = defaultOutput;
var exports = {
eval: evaluateLine,
onOutput: setOutput
};
if (isNodeJsEnvironment) {
require('fs').readFile('programs/nocomment.lisp', function(err, data) {
if (err) {
console.log(err);
output(err);
}
var data = data.toString().replace(/\n+/g, '');
evaluateLine(data.toString());
});
module.exports = exports;
} else {
this.LispJS = exports;
}
}).call(this);