-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtransfun.js
2284 lines (1869 loc) · 74.4 KB
/
transfun.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
/*
transfun.js
Copyright Guillaume Lathoud 2016
Boost License: see the file ./LICENSE
Contact: glat@glat.info
--- DESCRIPTION ---
Merge loops for speed in JavaScript: transformation functions
generate code where:
(1) loops do as few function calls as possible,
(2) consecutive loops have been merged into a single loop, whenever
possible.
See also:
http://glat.info/transfun
https://github.com/glathoud/transfun
*/
/*global
tval tpub tfun fullexpr
map filter reduce redinit sum prod decl
console global exports
Map
JSON
*/
var global, exports; // NPM support [github#1]
(function (global) {
var L_LEFT = 'loopleftright'
, L_RIGHT = 'looprightleft'
, L_IN = 'loopin'
, R_LEFT = 'rangeleftright'
, R_RIGHT = 'rangerightleft'
, ARRAY = 'array'
, OBJECT = 'object'
, CURRENT = 'current'
, _emptyObj = {}
;
// ---------- Public API: global namespace access
//
// (1) through global variables: only `tfun`, `tpub` and `tval`.
//
// (2) through `tfun.*` methods: everything, including
// transformation function ("transfuns") published with `tpub`
// (examples below).
global.tfun = tfun;
global.tpub = tfun.tpub = tpub;
global.tval = tfun.tval = tval;
tfun.createMap = createMap;
tfun.fullexpr = fullexpr;
tfun.statement = statement;
// --- Publish a few common transfunctions, specifying an
// internally imperative implementation for a functional.
tpub( 'arg', { // To extract multiple arguments (instead of the standard single argument `current`)
arity : 1
, specgen : function ( /*...comma-separated string, e.g. "a,b,c"...*/cs ) {
var arr = cs.split( ',' )
, n = arr.length
, stepadd = new Array( n )
;
for (var i = 0; i < n; ++i)
{
var name = arr[ i ].replace( /^\s+|\s+$/i, '' );
(name || null).substring.call.a;
stepadd[ i ] = { decl : [ name, { get_at : [ 'arguments', ''+i ] } ] };
}
return { stepadd : stepadd, first_only : true };
}
});
tpub( 'map', {
arity : 1
, specgen : function ( /*string | externcall object*/transform ) {
return { loopleftright : {
morph : 'array' // --> means, among other, reducable + depending on conserve_array_length, init & bodyend (store)
, conserve_array_length : true
, bodyadd : { set : [ 'v', tfun.fullexpr( transform, 'v', 'k' ) ] }
}};
}
});
tpub( 'mapRight', {
arity : 1
, specgen : function ( /*string | externcall object*/transform ) {
return { looprightleft : {
morph : 'array' // --> means, among other, reducable + depending on conserve_array_length, init & bodyend (store)
, conserve_array_length : true
, bodyadd : { set : [ 'v', tfun.fullexpr( transform, 'v', 'k' ) ] }
}};
}
});
tpub( 'mapIn', {
arity : 1
, specgen : function ( /*string | externcall object*/transform ) {
return { loopin : {
morph : 'object' // --> means, among other, reducable, init & bodyend (store)
, bodyadd : { set : [ 'v', tfun.fullexpr( transform, 'v', 'k' ) ] }
}};
}
});
tpub( 'filter', {
arity : 1
, specgen : function ( /*string | externcall object*/test ) {
return { loopleftright : {
morph : 'array' // --> means, among other, reducable + depending on conserve_array_length (always false here), init & bodyend (store)
, bodyadd : { restwrap : { 'if' : tfun.fullexpr( test, 'v', 'k' ), 'then' : { rest : 1 } } }
}};
}
});
tpub( 'filterRight', {
arity : 1
, specgen : function ( /*string | externcall object*/test ) {
return { looprightleft : {
morph : 'array' // --> means, among other, reducable + depending on conserve_array_length (always false here), init & bodyend (store)
, bodyadd : { restwrap : { 'if' : tfun.fullexpr( test, 'v', 'k' ), 'then' : { rest : 1 } } }
}};
}
});
tpub( 'filterIn', {
arity : 1
, specgen : function ( /*string | externcall object*/test ) {
return { loopin : {
morph : 'object' // --> means, among other, reducable + depending on conserve_array_length (always false here), init & bodyend (store)
, bodyadd : { restwrap : { 'if' : tfun.fullexpr( test, 'v', 'k' ), 'then' : { rest : 1 } } }
}};
}
});
tpub( 'reduce', {
arity : 1
, specgen : function ( /*string | externcall object*/combine ) {
return { loopleftright : {
beforeloop : [ { decl : [ 'out', 'null' ] }
, { decl : [ 'redinit', 'false' ] }
]
, bodyadd : { 'if' : 'redinit'
, then : { set : [ 'out', tfun.fullexpr( combine, 'out', 'v', 'k' ) ] }
, 'else' : [ { set : [ 'out', 'v' ] }
, { set : [ 'redinit', 'true' ] }
]
}
, afterloop : { set : [ 'current', 'out' ] }
}};
}
});
tpub( 'reduceRight', {
arity : 1
, specgen : function ( /*string | externcall object*/combine ) {
return { looprightleft : {
beforeloop : [ { decl : [ 'out', 'null' ] }
, { decl : [ 'redinit', 'false' ] }
]
, bodyadd : { 'if' : 'redinit'
, then : { set : [ 'out', tfun.fullexpr( combine, 'out', 'v', 'k' ) ] }
, 'else' : [ { set : [ 'out', 'v' ] }
, { set : [ 'redinit', 'true' ] }
]
}
, afterloop : { set : [ 'current', 'out' ] }
}};
}
});
tpub( 'reduceIn', {
arity : 1
, specgen : function ( /*string | externcall object*/combine ) {
return { loopin : {
beforeloop : [ { decl : [ 'out', 'null' ] }
, { decl : [ 'redinit', 'false' ] }
]
, bodyadd : { 'if' : 'redinit'
, then : { set : [ 'out', tfun.fullexpr( combine, 'out', 'v', 'k' ) ] }
, 'else' : [ { set : [ 'out', 'v' ] }
, { set : [ 'redinit', 'true' ] }
]
}
, afterloop : { set : [ 'current', 'out' ] }
}};
}
});
tpub( 'redinit', {
arity : 2
, specgen : function ( /*string*/redinit, /*string | externcall object*/combine ) {
return { loopleftright : {
beforeloop : { decl : [ 'out', tfun.fullexpr( redinit, 'current' ) ] }
, bodyadd : { set : [ 'out', tfun.fullexpr( combine, 'out', 'v', 'k' ) ] }
, afterloop : { set : [ 'current', 'out' ] }
}};
}
});
tpub( 'redinitRight', {
arity : 2
, specgen : function ( /*string*/redinit, /*string | externcall object*/combine ) {
return { looprightleft : {
beforeloop : { decl : [ 'out', tfun.fullexpr( redinit, 'current' ) ] }
, bodyadd : { set : [ 'out', tfun.fullexpr( combine, 'out', 'v', 'k' ) ] }
, afterloop : { set : [ 'current', 'out' ] }
}};
}
});
tpub( 'redinitIn', {
arity : 2
, specgen : function ( /*string*/redinit, /*string | externcall object*/combine ) {
return { loopin : {
beforeloop : { decl : [ 'out', tfun.fullexpr( redinit, 'current' ) ] }
, bodyadd : { set : [ 'out', tfun.fullexpr( combine, 'out', 'v', 'k' ) ] }
, afterloop : { set : [ 'current', 'out' ] }
}};
}
});
tpub( 'each', {
arity : 1
, specgen : function ( /*string*/action ) {
return { loopleftright : {
morph : 'array'
, keep_current_instance : true
, bodyadd : tfun.statement( action, 'v', 'k', 'current' )
}};
}
});
tpub( 'eachRight', {
arity : 1
, specgen : function ( /*string*/action ) {
return { looprightleft : {
morph : 'array'
, keep_current_instance : true
, bodyadd : tfun.statement( action, 'v', 'k', 'current' )
}};
}
});
tpub( 'eachIn', {
arity : 1
, specgen : function ( /*string*/action ) {
return { loopin : {
morph : 'object'
, keep_current_instance : true
, bodyadd : tfun.statement( action, 'v', 'k', 'current' )
}};
}
});
tpub( 'breakWhen', {
arity : 1
, specgen : function ( /*string | externcall object*/test ) {
return { loopleftright : { bodyadd : { 'if' : tfun.fullexpr( test, 'v', 'k' ), 'then' : 'break' } }};
}
});
tpub( 'breakWhenRight', {
arity : 1
, specgen : function ( /*string | externcall object*/test ) {
return { looprightleft : { bodyadd : { 'if' : tfun.fullexpr( test, 'v', 'k' ), 'then' : 'break' } }};
}
});
tpub( 'takeWhile', {
arity : 1
, specgen : function ( /* string | externcall object*/test ) {
return { loopleftright : {
morph : 'array'
, bodyadd : { restwrap : { 'if' : tfun.fullexpr( test, 'v', 'k' ), then : { rest : 1 }, 'else' : 'break' } }
}};
}
});
tpub( 'takeWhileIn', {
arity : 1
, specgen : function ( /* string | externcall object*/test ) {
return { loopin : {
morph : 'object'
, bodyadd : { restwrap : { 'if' : tfun.fullexpr( test, 'v', 'k' ), then : { rest : 1 }, 'else' : 'break' } }
}};
}
});
// -- and
tpub( 'and', {
arity : 0
, spec : { loopleftright : {
beforeloop : { decl : [ 'out', 'true' ] }
, bodyadd : [
{ set : [ 'out', 'v' ] }
, { 'if' : { not : 'out' } , 'then' : 'break' }
]
, afterloop : { set : [ 'current', 'out' ] }
}}
});
tpub( 'andRight', {
arity : 0
, spec : { looprightleft : {
beforeloop : { decl : [ 'out', 'true' ] }
, bodyadd : [
{ set : [ 'out', 'v' ] }
, { 'if' : { not : 'out' } , 'then' : 'break' }
]
, afterloop : { set : [ 'current', 'out' ] }
}}
});
tpub( 'andIn', {
arity : 0
, spec : { loopin : {
beforeloop : { decl : [ 'out', 'true' ] }
, bodyadd : [
{ set : [ 'out', 'v' ] }
, { 'if' : { not : 'out' } , 'then' : 'break' }
]
, afterloop : { set : [ 'current', 'out' ] }
}}
});
// -- or
tpub( 'or', {
arity : 0
, spec : { loopleftright : {
beforeloop : { decl : [ 'out', 'false' ] }
, bodyadd : [
{ set : [ 'out', 'v' ] }
, { 'if' : 'out' , 'then' : 'break' }
]
, afterloop : { set : [ 'current', 'out' ] }
}}
});
tpub( 'orRight', {
arity : 0
, spec : { looprightleft : {
beforeloop : { decl : [ 'out', 'false' ] }
, bodyadd : [
{ set : [ 'out', 'v' ] }
, { 'if' : 'out' , 'then' : 'break' }
]
, afterloop : { set : [ 'current', 'out' ] }
}}
});
tpub( 'orIn', {
arity : 0
, spec : { loopin : {
beforeloop : { decl : [ 'out', 'false' ] }
, bodyadd : [
{ set : [ 'out', 'v' ] }
, { 'if' : 'out' , 'then' : 'break' }
]
, afterloop : { set : [ 'current', 'out' ] }
}}
});
// "Values" extraction:
tpub( 'o2values', {
arity : 0
, spec : { loopin : {
beforeloop : { decl : [ 'out', '[]' ] }
, bodyadd : { push : [ 'out', 'v' ] }
, afterloop : { set : [ 'current', 'out' ] }
}}
});
// "Key" conversions:
tpub( 'o2keys', {
arity : 0
, spec : { stepadd : { set : [ 'current', 'Object.keys(current)' ] } }
});
tpub( 'keys2o', {
arity : 0
, spec : { loopleftright : {
beforeloop : { decl : [ 'out', '{}' ] }
, bodyadd : { set_at : [ 'out', 'v', 'true' ] }
, afterloop : { set : [ 'current', 'out' ] }
}}
});
// "Key-values" conversions:
tpub( 'o2kv', {
arity : 0
, spec : { loopin : {
beforeloop : { decl : [ 'out', '[]' ] }
, bodyadd : { push : [ 'out', '[k, v]' ] }
, afterloop : { set : [ 'current', 'out' ] }
}}
});
tpub( 'kv2o', {
arity : 0
, spec : { loopleftright : {
beforeloop : { decl : [ 'out', '{}' ] }
, bodyadd : { set_at : [ 'out', 'v[0]', 'v[1]' ] }
, afterloop : { set : [ 'current', 'out' ] }
}}
});
tpub( 'decl', {
arity : 2
, specgen : function ( /*string*/name, /*string | externcall object*/expr ) {
return {
stepadd : { decl : [ name, tfun.fullexpr( expr, 'current' ) ] }
};
}
});
tpub( 'declIn', {
arity : 1
, specgen : function ( /*object: name -> value*/o ) {
var arr = [];
for (var k in o) { if (!(k in _emptyObj)) { // More flexible than hasOwnProperty
var v = o[ k ];
arr.push({
decl : [ k, tfun.fullexpr( v, 'current' ) ]
});
}}
return { stepadd : arr };
}
});
// Ranges
tpub( 'rangeOf', {
arity : +Infinity // xxx maybe restrict to {2:true or 3:true} (not supported yet). Maybe. Maybe leave it as is.
, specgen : function ( begin, end, maybe_step ) {
arguments.length in {2:true,3:true} || null.invalid_arity;
return { rangeleftright : {
morph : 'array'
, conserve_array_length : true
, begin : begin
, end : end
, step : maybe_step
, varname : 'v'
}};
}
});
tpub( 'range', tfun.arg( 'begin,end,maybe_step' ).rangeOf( 'begin', 'end', 'maybe_step' ) );
// Others
tpub( 'prod', tfun.redinit( '1', '*' ) );
tpub( 'sum', tfun.redinit( '0', '+' ) );
tpub( 'join', '#s', '.join(#s)' );
tpub( 'split', '#s', '.split(#s)' );
tpub( 'sorted', {
arity : 1
, specgen : function( /*string | externcall object*/transform ) {
return {
stepadd : {
set : [
CURRENT
, CURRENT + '.slice().sort((a,b)=>' + tfun.fullexpr( transform, 'a', 'b' ) + ')'
]
}
};
}
});
// ---------- Public API implementation
function tval( /*...args...*/ )
// Convenience sugar to reverse the syntax:
// value first, then function:
//
// instead of h(g(f( value ))))
//
// one can call:
//
// tval( value )( f, g, h )
//
// or:
//
// tval( value )( [f, g, h] )
//
// Note: the `this` object is also transmitted, as in:
//
// tval.call( thisObj, value )( f, g, h )
{
var thisObj = this
, args = arguments
;
return tvalfun;
function tvalfun( /* ...functions... | array of function*/f )
{
var arr = Array.apply(
null
, 'function' === typeof f ? arguments : f
)
, n = arr.length
, v = arr[ 0 ].apply( thisObj, args )
;
for (var i = 1; i < n; ++i)
v = arr[ i ].call( thisObj, v );
return v;
}
}
var _tpub_cache;
function tpub( name, spec_or_fun_or_str /*... more strings in the shortcut variant...*/ )
{
(name || null).substring.call.a;
_tpub_cache || (_tpub_cache = {});
if (name in _tpub_cache)
throw new Error( '"' + name + '" already published!' );
var tf = _tpub_cache[ name ] = tfun.apply(
null
, with_default_loopname( Array.prototype.slice.call( arguments, 1 ) )
);
// Also publish the function to the global namespace through
// `tfun.*` methods (2) through `tfun.*` properties ==
new Function( 'tf' , 'this.tfun["' + name + '"]=tf' )
.call( global, tf );
return tf;
function with_default_loopname( arg )
{
var x = arg[ 0 ];
if ('object' === typeof x)
{
if (x.spec)
{
x = Object.create( x );
x.spec = try_to_add_default_loopname( x.spec );
x._tf_tpub_name = name; // Not mandatory, only for better logging
arg[ 0 ] = x;
}
else if (x.specgen)
{
x = Object.create( x );
x.specgen = get_default_loopname_wrapper( x.specgen );
x._tf_tpub_name = name; // Not mandatory, only for better logging
arg[ 0 ] = x;
}
}
return arg;
function try_to_add_default_loopname( spec, opt )
{
var looptype = get_looptype( spec );
if (looptype)
{
var loop = spec[ looptype ];
if (!loop.loopname)
loop.loopname = '-- ' + name + '(' + (opt ? ' ' + Array.apply( null, opt )
.map( s2origcodestring )
.join( ', ' ) + ' ' : ''
) + ') --'
}
return spec;
function s2origcodestring( s )
{
var x = (s.externcall || s)
, codestr = 'string' === typeof x ? x : JSON.stringify( x )
;
return '`' + codestr + '`';
}
}
function get_default_loopname_wrapper( specgen )
{
return default_loopname_wrapper;
function default_loopname_wrapper( /*...*/ )
{
return try_to_add_default_loopname( specgen.apply( this, arguments ), arguments );
}
}
}
}
function statement( /* ... see _stmt_expr_common... */ )
{
return _stmt_expr_common.apply( { statement : true }, arguments );
}
function fullexpr( /* ... see _stmt_expr_common... */ )
// string|object->string|object: Complete a code expression of one or two variables.
//
// Examples:
// {{{
// 'v!=null' === tfun.fullexpr( '!=null', 'v' )
// 'v+k' === tfun.fullexpr( '+', 'v', 'k' )
// }}}
{
return _stmt_expr_common.apply( { statement : false }, arguments );
}
var _TF_GET_ARGNAME_ARR = '_tf_get_argname_arr'
, _TF_GET_BODYCODE = '_tf_get_bodycode'
, _TF_POUND_OUT_TMPL = '#__tf_out__#'
, _TF_TOP_LOOP = '__tf_top_loop__'
, _TF_TOP_LOOP_I = 0
;
function _stmt_expr_common( /* string | externcall object*/code, /*string*/leftvar, /*?string?*/rightvar /*...more variables (for [extern]call)...*/ )
{
var opt = this
, opt_statement = opt && opt.statement
;
if ('object' === typeof code)
{
// object: call to an extern function => replace with a
// code string implementing the function call.
if (code.externcall)
{
var externcall = code.externcall;
(externcall || null).substring.call.a;
var arg = Array.apply( 0, arguments ).slice( 1 );
// Optional API for inlining
var one = code.one;
'function' === typeof one || null.bug;
var tmp_has_0 = _TF_GET_ARGNAME_ARR in one
, tmp_has_1 = _TF_GET_BODYCODE in one
;
if (tmp_has_0 ^ tmp_has_1)
{
throw new Error( 'transfun: optional inlineable function: please provide either both or none of the'
+ ' function object method ' + _TF_GET_ARGNAME_ARR + ' and ' + _TF_GET_BODYCODE + '.'
+ ' See also: https://github.com/glathoud/transfun/issues/7'
);
}
else if (tmp_has_0 && tmp_has_1)
{
var top_loop = _TF_TOP_LOOP + (_TF_TOP_LOOP_I++);
var f_argname_arr = one[ _TF_GET_ARGNAME_ARR ]()
, f_bodycode = get_transformed_bodycode( one[ _TF_GET_BODYCODE ]() )
;
if ('string' === typeof f_argname_arr)
f_argname_arr = f_argname_arr.split( ',' );
var homonyms = f_argname_arr.map( function ( s, i ) {
return s === arg[ i ] && 'let ' + tmp_homonym( s ) + ' = ' + s + ';'
|| ''
;
}).join( '' )
, assigns = !f_argname_arr.length
? ''
: 'let ' +
f_argname_arr.map( function ( s, i ) {
return !arg[ i ]
? ''
: s + ' = ' + (s === arg[ i ] ? tmp_homonym( s ) : arg[ i ])
;
}).join( ', ') + ';';
;
return [
'{'
, homonyms
, '{'
, assigns
, top_loop + ': for(;;) {'
, f_bodycode
, exiter()
, '}'
, '}'
, '}'
].join( '\n' );
}
return { 'call' : { fun : externcall, arg : arg } };
}
// object: definition piece => as is.
return code;
}
function tmp_homonym( s ) { (s || null).substring.call.a; return '__tf_homonym_' + s + '__'; }
function get_transformed_bodycode( /*string*/bodycode )
{
bodycode.substring.call.a;
return bodycode.replace( /\breturn([^;]+);/, replace_exit );
function replace_exit( s0, s1 )
{
return exiter( s1 );
}
}
function exiter( expr ) { return _TF_POUND_OUT_TMPL + ' = ' + expr + '; break ' + top_loop + ';' }
// string: statement => as is (no completion).
if (opt_statement)
return code;
// string: expression => complete it if necessary.
code.substring.call.a; // the empty string '' is allowed, means the value itself, unchanged
(leftvar || null).substring.call.a;
rightvar && rightvar.substring.call.a;
var is_left_implicit = /^\s*(?:[+*\/%&|\^\.=<>\?]|!=|-=|$)/.test( code )
, is_right_implicit = /[+\-*\/%&|\^\.=<>!]\s*$/ .test( code ) && !/(\+\+|\-\-)$/.test( code )
;
if (is_left_implicit)
code = leftvar + code;
if (is_right_implicit)
code = code + (is_left_implicit ? (rightvar || '') : leftvar);
return '(' + code + ')';
}
var _transfun_id; // for caching [github#2], to speedup the code generation
function tfun( def_or_fun_or_str /*... more strings in the string shortcut variant...*/ )
{
var tof = typeof def_or_fun_or_str;
if ('string' === tof)
{
// Shortcut "string" variant
//
// Call syntax similar to that of `new Function`,
// except that the parameter names start with '#'
var arr = Array.apply( null, arguments );
for (var i = arr.length - 1; i--;)
{
var x = arr[ i ].split( ',' );
if (x.length > 1)
arr.splice.apply( arr, [ i, 1 ].concat( x ) );
}
var shortcut_par_rx = arr.slice( 0, -1 ).map( function ( hash_string ) {
var hashname = hash_string.match( /^#[a-zA-Z_][a-zA-Z_0-9]*$/ )[ 0 ]
return new RegExp( hashname, 'g' );
})
, shortcut_arity = shortcut_par_rx.length
, shortcut_body = arr.slice( -1 )[ 0 ]
;
return tfun( { arity : shortcut_arity
, specgen : shortcut_specgen
}
);
}
// General variant
if (1 !== arguments.length)
throw new Error( 'General variant requires a single specification (object or function).' );
var fun;
if ('function' === tof)
{
var f = def_or_fun_or_str;
if (f._is_transfun)
{
fun = f;
}
else
{
var appfun = f;
fun = appfun._tf_bound;
}
}
else
{
var def = def_or_fun_or_str;
fun = 'object' === typeof def ? tfun_from_objectdef( def ) : def;
}
if (!('function' === typeof fun && fun._is_transfun))
throw new Error( 'Invalid specification! Must be an object or a transfunction.' );
return fun;
// --- Details for the string shortcut variant
function shortcut_specgen( /*...arguments...*/ )
{
shortcut_arity === arguments.length || null.bug;
var ret = shortcut_body;
for (var i = shortcut_par_rx.length; i--;)
ret = ret.replace( shortcut_par_rx[ i ], arguments[ i ] );
return { stepadd : { set : [ CURRENT, fullexpr( ret, CURRENT ) ] } };
}
// --- Details for the object definition variant
function tfun_from_objectdef( definition )
{
var def_arity = definition.arity
, has_variable_arity = def_arity === +Infinity // xxx Maybe: more restrictive def_arity, e.g. set: {2:true,3:true}
;
var spec = def_arity === 0 && definition.spec
, specgen = def_arity !== 0 && definition.specgen
, tf_id = _transfun_id = 1 + ~~_transfun_id; // [github#2]
;
transfun._is_transfun = true;
transfun._tf_def_arity = def_arity;
transfun._tf_has_variable_arity = has_variable_arity
transfun._tf_id = tf_id;
var tpub_name = definition._tf_tpub_name;
if (tpub_name)
transfun._tf_tpub_name = tpub_name;
return transfun;
function transfun( /*...`arity` arguments: array of (code string | non-string extern) ... */ )
{
var arity = has_variable_arity ? arguments.length : def_arity;
if (arity !== arguments.length)
{
return missing_args_transfun.apply( { transfunThisObj : this, arg : [] }, arguments );
}
var prev_chainspec = (this instanceof _ChainSpec ? this : new _ChainSpec)
, chainspec = prev_chainspec
.add_step( arity, tf_id, spec || specgen, transfun, arguments )
, cached_appfun = chainspec.appfun // avoid duplicated work [github#2]
;
if (!cached_appfun)
{
var appfun; // function: `impl` or `extern_impl_wrapper`
// Do it now, so that we can have appfun==impl in
// most cases -> performance. This is okay
// because we have cache: do it only once.
// See also [github#2].
ensure_appimpl();
appfun._tf_actual_arity = arity;
// Necessary to support `next` (see `ChainSpec.concat_call_tf`)
appfun._tf_chainspec = chainspec;
// Necessary to support `tfun( <appfun> )`
var _tf_bound_arg = [].slice.call( arguments );
appfun._tf_bound = appfun__tf_bound;
appfun._tf_bound._is_transfun = true;
// For convenience: give access
appfun.getBodyCode = appfun_getBodyCode;
appfun.getFunSpec = appfun_getFunSpec;
appfun.getNExternal = appfun_getNExternal;
cached_appfun = chainspec.appfun = mix_published_tfun_methods_into_appfun( chainspec, appfun );
// API for inlining when appfun are used as externals
// https://github.com/glathoud/transfun/issues/12
appfun[ _TF_GET_BODYCODE ] = appfun_getBodyCode;
appfun[ _TF_GET_ARGNAME_ARR ] = function () { return code_par_arr.slice( extern_arr.length ); };
}
return cached_appfun;
function appfun__tf_bound()
{
// Fail early to help the user self-correcting
// misuses.
if (arguments.length !== 0)
throw new Error( arguments.length + ' unexpected arguments: ' + Array.prototype.slice.call( arguments ) );
return transfun.apply( this instanceof _ChainSpec
? this.concat_call( prev_chainspec )
: prev_chainspec
, _tf_bound_arg
);
}
// --- Details
// steps for code & function generation
var extern_arr // array of non-string values (if any, given by _ChainSpec)
, has_extern
, spec_arr_optim // after merging compatible `morph` loops + one extra loop
, spec_arr_optim_solved // after expliciting the last `store` step of `morph` loops
, spec_arr_optim_multiarg // after optimizing some multiple arguments use cases
, code_par_arr // actual implementation: parameters (array of string: parameter names, `n_extern` extern names, if any, + `current`)
, code_body // actual implementation: body (string)
, impl // actual implementation (function)
;
function appfun_getBodyCode()
{
ensure_appimpl();
return code_body;
}
function appfun_getFunSpec()
{
ensure_appimpl();
return { funSpec : {
varNameArr : code_par_arr.slice()
, specArr : chainspec.spec_arr
}};
}
function appfun_getNExternal()
{
ensure_appimpl();
return extern_arr.length;
}
function ensure_appimpl()
{
if (!impl)
{
extern_arr = chainspec.extern_arr;
has_extern = extern_arr.length > 0;
code_par_arr = chainspec.externname_arr.concat( [ CURRENT ] );
var first_only = is_first_only( chainspec.spec_arr );
spec_arr_optim = optimize_spec_arr_merging_morphs( chainspec.spec_arr );
spec_arr_optim_solved = explicit_and_optimize_morph_store( spec_arr_optim );
if (first_only)
mark_first_only( spec_arr_optim_solved );
var gcb_o = optimize_some_multiarg_cases( code_par_arr, spec_arr_optim_solved );
if (first_only)
mark_first_only( gcb_o.spec_arr );
code_body = ' "use strict";\n' // https://github.com/glathoud/transfun/issues/11
+ generate_code_body( gcb_o.spec_arr );
impl = new Function( gcb_o.code_par_arr, code_body );
// In most cases no wrapper because no
// externs. Performance in mind. Okay because
// of cache [github#2].
appfun = has_extern
? (gcb_o.code_par_arr.length - chainspec.externname_arr.length > 1 // optimization for that case
? extern_impl_wrapper_many_args