-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjexpr.js
2122 lines (1899 loc) · 71.7 KB
/
jexpr.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
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
// Copyright (c) 2012, Srikumar K. S. (srikumarks.github.com)
//
// Code licensed for use and redistribution with warranties
// (or the lack thereof) as described in the MIT licence.
// License URL: http://www.opensource.org/licenses/MIT
// This is an attempt at developing a language using JSON objects as containers
// for the AST, similar to how list expressions serve as a representation for
// ASTs in the lisp family of languages. The key idea exploited here is that
// browser based Javascript engines such as V8 always enumerate the keys of an
// object in the same order as they were inserted. Though this is not required
// by ECMAScript, it is considered standard behaviour in browser environments
// and in Node.js too (since it uses V8).
//
// The overall structure of a j-expression is like this -
//
// {operator: [args...],
// keyword1: value1,
// keyword2: value2,
// ...}
//
// .. and we'll call the language "J" here for brevity.
//
// #### Relevant posts
//
// 1. [J-expressions]
// 2. [DSLs using JSON expressions]
//
// [DSLs using JSON expressions]: http://srikumarks.github.com/gyan/2012/04/14/creating-dsls-in-javascript-using-j-expressions/
// [J-expressions]: http://srikumarks.github.com/gyan/2012/04/15/j-expressions/
var J = (function (enable_tests) {
// We single out the first key presented in a JSON object as the name of the
// operator.
function operatorName(obj) {
if (obj && obj.constructor === Object) {
for (var k in obj) {
return k;
}
} else {
return undefined;
}
};
// ## Compilation environments
// We need an environment structure to remember the scope of bindings
// established as we develop the compiler and as the compiler walks through the
// AST. We start with a simple environment definition with the ability to
// construct an environment with another one as its "parent scope".
var Env = function (base) {
if (base) {
this.base = base;
this.symbols = Object.create(base.symbols);
} else {
this.symbols = {};
}
}
// We now start with the basic compiler that supports simple object types -
// numbers and booleans. The compiled form of these is simply the JSON
// stringification so that we can insert them into the compiled code directly
// as literals.
function compile_lit(env, expr) {
if (expr === undefined || expr === null) {
return JSON.stringify(expr);
}
if (expr.constructor === Number || expr.constructor == Boolean) {
return JSON.stringify(expr);
}
return undefined;
}
// Strings are a bit special. We're going to need symbols in our
// language. Since JS doesn't have a separate symbol type, we'll
// just use plain strings as symbols and worry about strings later on.
// This means we're going to need a way to lookup the compile-value of a
// symbol in an environment first. Use a namespace prefix to avoid
// touching the builtin properties.
function lookupSymbol(env, sym) {
return env.symbols['J_' + sym];
}
// We now add a simple function to define new things into
// a given environment.
function define(env, name, value) {
return env.symbols['J_' + name] = value;
}
// We can now write our symbol compilation. This looks up
// the value in the environment and just returns it if found.
function compile_sym(env, sym) {
if (sym && sym.constructor === String) {
return lookupSymbol(env, sym);
}
return undefined;
}
// A new "variable" in our language will be mapped to a javascript
// variable by attaching a special prefix so that the language
// cannot escape its boundaries. We also use the environment's
// "id" number in the name so that the JS variables associated
// with different environments can be told apart.
var idRx = /^[a-zA-Z_\$][a-zA-Z0-9_\$]*$/;
function varname(env, sym) {
if (!idRx.test(sym)) {
throw "Bad identifier!";
}
return 'var$' + env.id + '$' + sym;
}
function varnames(env, syms) {
return syms.map(function (sym) {
return varname(env, sym);
});
}
function newvar(env, sym) {
return define(env, sym, varname(env, sym));
}
function newvars(env, syms) {
if (typeof syms === 'string') {
return [newvar(env, syms)];
} else {
return syms.map(function (sym) {
return newvar(env, sym);
});
}
};
// Oops. We haven't defined an environment's ID. Let's patch
// Env to add that.
function patch(oldEnv, change) {
function NewEnv(base) {
oldEnv.call(this, base);
change.call(this, base);
}
NewEnv.prototype = oldEnv.prototype;
return NewEnv;
}
var globallyUniqueEnvID = 1;
Env = patch(Env, function (base) {
this.id = (globallyUniqueEnvID++);
});
// Lets also add some options that we can store and
// inherit over the Env chain.
Env = patch(Env, function (base) {
this.options = (base ? Object.create(base.options) : {});
});
// We're now ready to process our first J-expression. We treat
// the first key as the symbol standing for an operator, fetch
// the function that implements the operator and just call it.
// Note that if the looked up value is a function, it is really
// a "macro" because we're writing a *compiler*. Actual value
// lookup will yield a string which we can use as a JS expression
// in the compiled result directly.
// {operator: [arguments...], keyword1: value1, ...}
function compile_jexpr(env, jexpr) {
if (jexpr && jexpr.constructor === Object) {
var op = lookupSymbol(env, operatorName(jexpr));
if (op && op.constructor === Function) {
return op(env, jexpr); /* We have a native implementation available.
* We pass the entire body of the expression
* to it without evaluating anything else.
*/
}
if (op && op.constructor === String) {
return compile_apply(env, op, jexpr); /* This is an already compiled value. So just
* treat it as a function and apply it.
*/
}
if (!op && env.options.unsafe) {
// Treat it as a globally available thingie.
return compile_apply(env, operatorName(jexpr), jexpr);
}
} else if (jexpr && jexpr.constructor === Array) {
// This is s-expression fallback case where the operator
// expression is not a string.
var kw = jexpr.keywords;
var jexpr2 = {};
jexpr2['sexpr'] = jexpr.slice(1);
if (kw) {
Object.keys(kw).forEach(function (k) {
jexpr2[k] = kw[k];
});
}
return compile_apply(env, compile(env, jexpr[0]), jexpr2);
}
return undefined;
}
// We now need to build our whole compilation function so
// that we can just call it to compile any j-expression
// or primitive type.
function compile(env, expr) {
return compile_jexpr(env, expr)
|| compile_sym(env, expr)
|| compile_lit(env, expr);
}
// To help ourselves a bit, let's define a mapping utility
// that applies a two-argument "macro-like" function to
// an array of expressions.
function map(env, fn, exprs) {
return exprs.map(function (expr) {
return fn(env, expr);
});
}
// The "arguments" of an operator are provided as an array value.
// Each element is compiled in turn and the result used as the
// argument-list of the compiled javascript function.
function compile_args(env, argv) {
if (argv && argv.constructor === Array) {
return map(env, compile_args, argv).join(',');
} else {
// Compile it as a single expression.
return compile(env, argv);
}
}
// Now we are ready to write the compile_apply, which will
// apply a compiled function by symbol reference to a given
// arguments list.
function compile_apply(env, op, jexpr) {
return op + '(' + compile_args(env, jexpr[operatorName(jexpr)]) + ')';
}
// ## Primitives
//
// Ok, so far we have not implemented any primitives. Our first one
// is going to be a mechanism for expressions to return literal JSON
// objects. This is the analog of "quote" in Scheme and we'll use
// the succinct "$" symbol as the key of a jexpr to represent quoted
// forms. We'll insert these primitives into a "primitives" environment.
var Prim = new Env;
define(Prim, '$', function (env, expr) {
return JSON.stringify(expr.$);
});
// And now for an ultra simple "display" implementation.
// After all, how are we going to write a "hello world" program
// without this one!
define(Prim, 'display', function (env, expr) {
return '(console.log(' + compile(env, expr.display) + '), null)';
});
// We're now ready to do a "hello world". But first some helper stuff.
// We're going to be making new environments. So let's make a helper
// method on Env to make a new derived environment.
function subenv(env) {
return new Env(env);
}
// HELLO WORLD!
if (enable_tests) {
eval(compile(subenv(Prim), {display: {$: "Hello world!"}}));
}
// Let's wrap that little piece of code into a "run" method
// and insert it into the environment so that programs can
// be run within environments.
// "run" will run the expressions in a new child environment
// without affecting the target environment.
Env.prototype.run = function () {
var env = subenv(this);
var result;
Array.prototype.forEach.call(arguments, function (expr) {
result = eval(compile(env, expr));
});
return result;
};
// Now lets implement some more primitives!
// We'll do the useful "list" macro which will take
// a bunch of arguments and produce an list (a JS array)
// out of them. This has to be a macro because we're
// constructing an array for use at *runtime*.
define(Prim, 'list', function (env, expr) {
if (expr.list.constructor === Array) {
return '['
+ expr.list.map(function (e) {
return compile(env, e);
}).join(',')
+ ']';
} else {
return '[' + compile(env, expr.list) + ']';
}
});
// ... and list length
define(Prim, 'length', '(function (x) { return x.length; })');
if (enable_tests) {
Prim.run({display: {length: [{list: [1,2,3]}]}});
}
// We'll also put in a macro for constructing tables.
// This has to be a macro because we're going to have
// to evaluate the value fields of the given object.
//
// {table: {x: 2, y: {$: "why?"}}}
//
// should produce what you think it should.
define(Prim, 'table', function (env, expr) {
var keys = Object.keys(expr.table);
return '{'
+ keys.map(function (k) {
return JSON.stringify(k) + ':' + compile(env, expr.table[k]);
}).join(',')
+ '}';
});
// ### Let there be lambda
//
// Now for the BIG BOY! The syntax we use for lambda is like this -
//
// {lambda: ["arg1", "arg2", ...],
// body: expr|[expr1, expr2, ..., exprN]}
//
// We turn that into a JS function like this -
//
// function (arg1, arg2, ...) {
// var keywords = this;
// return (expr1, expr2, ... exprN);
// }
//
// We also make "this" available as the special symbol 'keywords'
// with the intention of passing in optional arguments through 'this'.
define(Prim, 'lambda', function (env, expr) {
var env2 = subenv(env);
return '(function ('
+ newvars(env2, expr.lambda).join(',')
+ ') {'
+ 'var ' + newvar(env2, 'keywords') + ' = this;'
+ 'return (' + compile_args(env2, expr.body) + ');})';
});
// Alias 'lambda:body:' as 'fn:to:'.
define(Prim, 'fn', function (env, expr) {
var k = Object.keys(expr);
k.shift();
var expr2 = {lambda: expr.fn};
k.forEach(function (k) {
if (k === 'to') {
expr2['body'] = expr[k];
} else {
expr2[k] = expr[k];
}
});
return lookupSymbol(Prim, 'lambda')(env, expr2);
});
// ### Optional keyword arguments
// That was easy! ... but the lambda is unable to make
// use of optional keyword arguments yet and that would be a real waste.
// To support that, at call time, we'll pass the compiled version of
// the call expression body to the lambda as a table so that it can
// access the arguments other than the args array through the local
// "keywords" symbol.
// First, we need to compile the entire expression as a value.
function compile_exprval(env, expr, keys) {
return '{'
+ keys.map(function (k) {
return JSON.stringify(k)
+ ':'
+ (compile_array(env, expr[k]) || compile(env, expr[k]));
}).join(',')
+ '}';
}
// Now we need to patch compile_apply to check for the presence
// of keywords and if so pass it as the "this" part of a call.
var compile_apply = (function (prevCompileApply) {
return function (env, op, jexpr) {
var keys = Object.keys(jexpr);
if (keys.length === 1) {
return prevCompileApply(env, op, jexpr); // Avoid the overhead of a ".call"
} else {
var opname = operatorName(jexpr);
keys.shift(); // Drop the operator.
return op
+ '.call('
+ compile_exprval(env, jexpr, keys)
+ ','
+ compile_args(env, jexpr[opname])
+ ')';
}
};
}(compile_apply));
// This just compiles the parts of the array and wraps it with the
// array constructor.
function compile_array(env, arr) {
if (arr && arr.constructor === Array) {
return '[' + compile_args(env, arr) + ']';
}
return undefined;
}
// And to *use* lambda, we're going to need apply.
//
// {apply: funval, args: listval, keywords: tableval}
define(Prim, 'apply', function (env, expr) {
return compile(env, expr.apply)
+ '.apply('
+ (expr.keywords ? compile(env, expr.keywords) : 'null')
+ ','
+ compile(env, expr.args)
+ ')';
});
// call func arg1 arg2 ... kw1: val1 kw2: val2 ...
define(Prim, 'call', function (env, expr) {
var op, argv, keywords;
keywords = Object.keys(expr);
keywords.unshift(); // Drop 'call'.
var keyvals = {};
keyvals.call = expr.call.constructor === Array ? expr.call.slice(1) : [];
keywords.forEach(function (k) { keyvals[k] = expr[k]; });
var op = '(' + compile_args(env, expr.call.constructor === Array ? expr.call[0] : expr.call) + ')';
return compile_apply(env, op, keywords);
});
// Lets now try a lambda hello world.
if (enable_tests) {
Prim.run({apply: {lambda: ["msg"],
body: [
{display: {$: "Hello lambda world ..."}},
{display: "msg"},
{display: "keywords"}
]},
args: {list: [{$: "planet earth rocks!"}]},
keywords: {table: {global: {$: "cooling ftw!"}}}});
}
// ### "where" clauses
//
// Now let's add something "interesting" to lambda
// - a "where" clause. The idea is that whenever we have an extra
// "where: {key1: val1, key2: val2,..}" entry in a j-expression,
// we make those keys available like local variables within the
// scope of the expression. Let's generalize this feature first.
//
// What we do is to turn {...where: {x: val1, y: val2} ...}
// as a function wrapper like -
//
// (function (x, y) {
// ..expr..
// }(val1, val2))
function whereClause(env, expr, where, macro) {
if (!where) {
return macro(env, expr);
}
var whereEnv = subenv(env);
var whereVars = Object.keys(where);
return '(function (' + newvars(whereEnv, whereVars) + ') {'
+ 'return (' + macro(whereEnv, expr) + ');}'
+ '('
+ whereVars.map(function (v) {
return '('+compile_args(env, where[v])+')';
}).join(',')
+ '))';
}
// Now we can add where clause support to lambda.
define(Prim, 'lambda', (function (oldLambda) {
return function (env, expr) {
return whereClause(env, expr, expr.where, oldLambda);
};
}(lookupSymbol(Prim, 'lambda'))));
// ### Macros
//
// Now we up the game a bit and define the ability to
// write macros. We've already been writing macros,
// so we just need to expose that bit of functionality
// to the language itself. Macros are just lambdas that
// take the entire expression as a single argument
// and return an expression to be used instead.
//
// {macro: "name",
// lambda: ["expr"],
// body: ...,
// where: ...}
define(Prim, 'macro', function (env, expr) {
var macrodefn = eval(lookupSymbol(env, 'lambda')(env, expr));
define(env, expr.macro, function (env, expr) {
var expn = macrodefn(expr);
return compile(env, expn);
});
return 'undefined';
});
// Woot! We have macros! ... but we can't even write a hello world
// with macros now because we don't have a proper way to construct object
// literals in our language. We can use 'list' and 'table', but yuck!
// we need a quasiquoter!
//
// {$_: <quoted> {_$: <unquoted>} ...}
//
// We first write a "$_" macro that will quasi quote. We make the
// unquoting mechanism generic by putting a table of unquoters for
// the quasi quoter to look for, right into the environment.
function AddUnquoters(base) {
this.unquoters = base ? Object.create(base.unquoters) : {};
}
Env = patch(Env, AddUnquoters);
AddUnquoters.call(Prim, Prim.base);
function quasiQuote(env, expr) {
if (expr && expr.constructor === Array) { // Array literal.
return '['
+ map(env, quasiQuote, expr).join(',')
+ ']';
}
if (expr && expr.constructor === Object) { // Object literal ...
var unquoter = env.unquoters[operatorName(expr)];
if (unquoter) { // ... but maybe an unquoter here?
return unquoter(env, expr);
} else {
return '{'
+ Object.keys(expr).map(function (k) {
return JSON.stringify(k) + ':' + quasiQuote(env, expr[k]);
}).join(',')
+ '}';
}
}
return JSON.stringify(expr); // else literal.
}
// Quasiquote operator
define(Prim, '$_', function (env, expr) {
return quasiQuote(env, expr.$_);
});
// Now we add one unquoter '_$'.
Prim.unquoters['_$'] = function (env, expr) {
return compile(env, expr._$);
};
// Unquote splice is simple enough as well.
// Beware that it can only be used sensibly
// when expanding arrays.
Prim.unquoters['_$$'] = function (env, expr) {
return compile_args(env, expr._$$);
};
// Hooray! We can now do a macro hello world!
if (enable_tests) {
Prim.run({macro: "hello",
lambda: ["expr"],
body: [{$_: {display: {$: ["In macro!", {_$$: ["meow", "expr"]}]}}}],
where: {meow: {$: "bowow"}}
},
{hello: ["macro", "world!"]});
}
// ## Going to town!
//
// Now we go to town and add all sorts of bells and whistles.
// ### let:in:
// First up is a variant on the "where" clause - the "let:in:".
//
// {let: {x: blah, y: bling}, in: expr|[expr1, expr2, ...]}
define(Prim, 'let', function (env, expr) {
return whereClause(env, expr, expr.let, function (envw, expr) {
return compile_args(envw, expr.in);
});
});
if (enable_tests) {
Prim.run({let: {msg: {$: "hello"}},
in: [{display: {$_: [{_$: "msg"}, "let world"]}}]});
}
// ### if:then:else:
// {if: cond, then: expr1, else: expr2}
define(Prim, 'if', function (env, expr) {
return '(' + compile(env, expr.if)
+ '?' + compile(env, expr.then)
+ ':' + compile(env, expr.else)
+ ')';
});
// ### Generators
// Since JS doesn't support tail call elimination, we need some
// way to loop. For that, it is useful to have generators like
// in python - basically functions that you can call repeatedly
// to get a sequence of values. Our protocol will be that the
// generator is considered to end when the function returns
// 'undefined', and we can pass in a bool value of 'true' to
// reset the generator.
// {from: ix1, to: ix2, step: dix}
// Usual defaults apply.
define(Prim, 'from', function (env, body) {
function iterator(comp) {
return '(function (reset) {'
+ 'if (reset) {i = from + step; return from;}\n'
+ 'var result = i;'
+ 'return (i ' + comp + ' to ? ((i += step), result) : undefined);})';
}
return '((function (from, to, step) {var i = from; '
+ 'if (to === undefined) {'
+ 'to = from + step * 1e16;'
+ '}\n'
+ 'return (step > 0 ?' + iterator('<') + ':' + iterator('>') + ');})('
+ compile(env, body.from) + ','
+ (body.to ? compile(env, body.to) : 'undefined') + ','
+ (body.step ? compile(env, body.step) : '1')
+ '))';
});
// {in: list, from: ix1, to: ix2, step: dix}
// Similar to from: but steps through array.
define(Prim, 'in', function (env, body) {
function iterator(comp) {
return '(function (reset) {'
+ 'if (reset) {i = from + step; return arr[from];}\n'
+ 'var result = arr[i];'
+ 'return (i ' + comp + ' to ? ((i += step), result) : undefined);})';
}
return '((function (arr, from, to, step) {var i = from; '
+ 'if (to === undefined) {'
+ 'to = (step > 0 ? arr.length : -1);'
+ '}\n'
+ 'return (step > 0 ?' + iterator('<') + ':' + iterator('>') + ');})('
+ compile(env, body.in) + ','
+ compile(env, body.from) + ','
+ (body.to ? compile(env, body.to) : 'undefined') + ','
+ (body.step ? compile(env, body.step) : '1')
+ '))';
});
// ### Looping using for:
//
// {for: {x: gen1, y: gen2,...},
// when: cond,
// expr: value|[expr1, expr2, ...],
// where: {...}}
// {for: {x: gen1, y: gen2,...},
// when: cond,
// body: stmt|[stmt1, stmt2,...],
// where: {...}}
//
// The "expr" version produces an array with those values, whereas the "body"
// and "dosync" versions are for side effects only. An extra "sync: true|false"
// keyword can be specified to indicate whether only synchronous computations
// are being done within - i.e. whether any closures are being created within
// the body of the loop that warrants wrapping the body in a function. "sync:"
// defaults to "false" so it is always safe in the default case.
//
// TODO: Optimize away the use of generators for the simple integer iteration
// cases.
//
define(Prim, 'for', function (env, expr) {
var numForms = (expr.expr ? 1 : 0) + (expr.body ? 1 : 0) + (expr.dosync ? 1 : 0);
if (numForms !== 1) {
throw new Error('for: Only one of expr: body: or dosync: can be specified.');
}
return whereClause(env, expr, expr.where, function (env, expr) {
var env2 = subenv(env);
var envb = subenv(env2);
var iters = Object.keys(expr.for);
return '(function () {'
+ iters.map(function (ivar) {
var v = newvar(env2, ivar);
var gen_v = 'gen_' + v; /* Use an extra "gen_" prefix
* for variables that hold
* generators.
*/
return 'var ' + v + ', ' + gen_v + ' = (' + compile_args(env2, expr.for[ivar]) + ');';
}).join('')
+ (expr.expr ? 'var __result = [];' : '')
// No need to wrap into a function if calculating expression.
+ (expr.sync ? '' : ('\nfunction __body('
+ newvars(envb, iters).join(',')
+ ') {'
+ (expr.expr
? ('__result.push((' + compile_args(envb, expr.expr) + '))')
: ('(' + compile_args(envb, expr.body) + ')'))
+ '}\n'))
+ iters.map(function (ivar) {
var v = varname(env2, ivar);
var gen_v = 'gen_' + v;
return '\nfor(' + v + ' = ' + gen_v + '(true);'
+ v + ' !== undefined; '
+ v + ' = ' + gen_v + '()) {';
}).join('')
+ (expr.when
? ('if (' + compile_args(env2, expr.when) + ') {')
: '')
+ (expr.sync
? (expr.expr
? ('__result.push((' + compile_args(env2, expr.expr) + '))')
: ('(' + compile_args(env2, expr.body) + ')'))
: ('__body(' + varnames(env2, iters).join(',') + ');'))
+ (expr.when ? '}' : '')
+ iters.map(function (ivar) { return '\n}'; }).join('')
+ (expr.expr ? '\nreturn __result;' : '')
+ '}())';
});
});
if (enable_tests) {
Prim.run({for: {x: {from: 1, to: 4},
y: {from: 100, to: 104}},
body: [{display: {$_: [{_$: "x"}, {_$: "y"}]}}]});
}
// ### Let's support some math as well.
// {expr: "x + y", where: {x: val1, y: val2}}
// The expression can only see the variables in the where clause.
// UNSAFE!
define(Prim, 'expr', function (env, expr) {
if (!env.options.unsafe) {
throw "Unsafe expression! " + JSON.stringify(expr);
}
if (expr.where) {
var vars = Object.keys(expr.where);
return '(function (' + vars.join(',') + ') {'
+ 'return (' + expr.expr + ');}'
+ '('
+ vars.map(function (v) { return compile(env, expr.where[v]); }).join(',')
+ '))';
} else {
return '(' + expr.expr + ')';
}
});
// ### Some higher order functions?
// {map: fn, list: listval}
define(Prim, 'map', function (env, expr) {
return '(' + compile(env, expr.list) + '.map(' + compile(env, expr.map) + '))';
});
// {reduce: fn, list: listval, init: value}
define(Prim, 'reduce', function (env, expr) {
return '(' + compile(env, expr.list) + '.reduce('
+ compile(env, expr.reduce) + ', '
+ compile(env, expr.init)
+ '))';
});
// {filter: fn, list: listval}
define(Prim, 'filter', function (env, expr) {
return '(' + compile(env, expr.list) + '.filter(' + compile(env, expr.filter) + '))';
});
// ### Dot notation
// It is useful to refer to object parts directly using
// the dot notation. Just change lookupSymbol to directly
// support it.
lookupSymbol = (function (lookup) {
var forbiddenProperties = {};
return function (env, sym) {
var parts = sym.split('.');
if (parts.length === 1) {
return lookup(env, sym);
} else {
parts[0] = lookup(env, parts[0]);
parts.forEach(function (p,i) {
if (i > 0) {
if (forbiddenProperties[p]) {
throw "Forbidden javascript property '" + p + "' accessed!";
}
}
});
if (parts[0]) {
return parts.join('.');
} else {
return undefined;
}
}
};
}(lookupSymbol));
if (enable_tests) {
Prim.run({let: {x: {table: {cat: {$: "meow"}}}},
in: {display: "x.cat"}});
// Try the lambda example again with dot notation access.
// Lets now try a lambda hello world.
Prim.run({let: {greet: {lambda: ["msg"],
body: [
{display: {$: "Hello lambda world ..."}},
{display: "msg"},
{display: "keywords.lockword"}
]}},
in: [{greet: [{$: "Planet earth rocks!"}],
lockword: {$: "haha!"}}]});
}
// ## Defines and blocks
// It will certainly be convenient to be able to write do blocks
// for walking through steps and introduce definitions along the way,
// process them etc. A simple macro for that would work on --
//
// {do: [stmt1, stmt2, ...],
// where: {...}}
//
// and allow define statements in the mix, like this -
//
// {define: {name1: value1, name2, value2,...}}
//
// We translate such a "do" block into a
// (function () {...}())
// form.
define(Prim, 'do', function (env, expr) {
return whereClause(env, expr, expr.where, function (env, expr) {
var result = '(function () {';
var stmts = expr.do;
if (stmts.constructor !== Array) {
stmts = [stmts];
}
stmts.forEach(function (stmt, i) {
if (stmt && operatorName(stmt) === 'define') {
env = subenv(env); /* It is a define statement. Make a new environment.
* This is an important step to ensure that new
* definitions don't override older ones.
*/
Object.keys(stmt.define).forEach(function (varname) {
result += 'var ' + newvar(env, varname) + ' = ';
result += compile(env, stmt.define[varname]) + ';';
});
} else {
result += (i+1 < expr.do.length ? '' : 'return ')
+ compile(env, stmt) + ';';
}
});
return result + '}())';
});
});
if (enable_tests) {
Prim.run({do: [
{define: {x: 5}},
{define: {fn: {lambda: ["y"], body: [{table: {x: "x", y: "y"}}]}}},
{define: {x: 10}},
{display: {fn: [10]}},
{display: "x"}
]});
}
// ### Accessors
// We don't have any accessor functions for working with
// object and array properties yet. Let's add a general purpose
// "get" and "put".
// {get: [obj, key1, key2, ...]}
define(Prim, 'get', function (env, expr) {
return expr.get.map(function (e, i) {
var ce = compile(env, e);
return (i > 0 ? ('['+ce+']') : ce);
}).join('');
});
// {put: [obj, key1, key2, ...], value: val}
define(Prim, 'put', function (env, expr) {
if (expr.put.constructor === String) {
return '(' + compile(env, expr.put) + ' = ' + compile(env, expr.value) + ')';
} else if (expr.put.constructor === Array) {
return '('
+ lookupSymbol(env, 'get')(env, expr.put)
+ ' = '
+ compile(env, expr.value)
+ ')';
}
});
// ### Resolving power differences
//
// There is a asymmetry between lambda and macro that is uncomfortable.
// It is that using a lambda always requires its arguments to be
// wrapped into an array (other than keywords) whereas macros are able
// to work with free forms better. Ideally, they shouldn't have differences
// in form at usage time and should be able to work with all forms.
// One simple solution to this is to auto-promote single non-array
// arguments into one-element arrays at call time. We patch compile_apply
// to resolve this.
//
// With this patch, you can have the following lambda -
//
// {let: {ruler: {lambda: ["arg"],
// body: [{if: "keywords.double_rule",
// then: {display: {$: "================="}}
// else: {display: {$: "-----------------"}}},
// {display: "arg"}]}}
// ...}
//
// which can be called like this -
//
// {ruler: {$: "An important message"}, double_rule: true}
//
// and "applied" like this -
//
// {apply: "ruler",
// args: {list: [{$: "An important message"}]},
// keywords: {table: {double_rule: true}}}
//
var compile_apply = (function (prevCompileApply) {
return function (env, op, jexpr) {
var opname = operatorName(jexpr);
var head = jexpr[opname];
if (head && head.constructor === Array) {
return prevCompileApply(env, op, jexpr); // Safe. Old behaviour applies.
} else {
jexpr[opname] = [jexpr[opname]]; /* Transform the main argument into a
* one-element array.
* HACK: We hack this by destructively modifying
* jexpr since the next time around we won't then
* get into this branch.
*/
return prevCompileApply(env, op, jexpr);
}
};
}(compile_apply));
if (enable_tests) {
Prim.run({let: {ruler: {lambda: ["arg"],
body: [{if: "keywords.double_rule",
then: {display: {$: "======================="}},
else: {display: {$: "-----------------------"}}},
{display: "arg"}]}},
in: [{ruler: {$: "An important message!"}, double_rule: true}]});
}
// This uniformity lets us turn 'display' into a function much more simply!
define(Prim, 'display', 'console.log');
// Can we turn map/reduce/filter into functions as well?
// This looks possible, but I'm not sure about the resulting
// efficiency, so I'll leave them as macros for now and leave
// it to YOU to figure that out.
//
// define(Prim, 'map', '(function (fn) { return this.list.map(fn); })');
// define(Prim, 'reduce', '(function (fn) { return this.list.reduce(fn, this.init); })');
// define(Prim, 'filter', '(function (fn) { return this.list.filter(fn); })');
//
// Many others that we've written as macros should similarly be
// expressed as functions .. except for such runtime performance considerations.
// The disadvantage to how we've been doing this up to here, is
// that we cannot use the macros with "apply" in a program. That's
// a pretty BIG disadvantage, but I'm waving my hands and saying
// "you can always wrap a lambda around it" :)
//
// Have fun!
// ## A runtime environment?
// So far, we don't have the notion of a runtime and all "functions"
// are actually macros and all is not well in this world just yet.
// We need some way to provide an environment that exposes symbol
// bindings to some piece of compiled code that we then evaluate
// using eval().
//
// We use a very simple model of a language runtime - which is a
// function that takes in a piece of compiled code and evaluates
// it using eval! The function is free to introduce new bindings
// in its local environment which then become accessible to eval.
// In other words, we just treat "eval" itself as a runtime.
//
// Here is a sample runtime that redefines "map", "reduce"
// and "filter" as functions instead of the macros that we defined