This repository has been archived by the owner on Mar 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
example-parsejs.js
14626 lines (12234 loc) · 518 KB
/
example-parsejs.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
/** @license
* JavaScript analysis tools based on JSParsec
*
* http://code.google.com/p/jshaskell/
*
* Copyright (c) 2010 Balazs Endresz ([email protected])
* Dual licensed under the MIT and GPL licenses.
*
* This is a port of the WebBits library (BrownPLT.JavaScript):
* http://hackage.haskell.org/package/WebBits-2.0
* Copyright (c) 2007-2009 Arjun Guha, Claudiu Saftoiu, and Spiridon Eliopoulos
*
* ------------------------------------------------------------
*
*/
/** @license
* pretty - A JavaScript port of the Haskell pretty package
*
* http://code.google.com/p/jshaskell/
*
* Copyright (c) 2010 Balazs Endresz ([email protected])
* Dual licensed under the MIT and GPL licenses.
*
* Original implementation and license:
* http://hackage.haskell.org/package/pretty-1.0.1.1
*
* ------------------------------------------------------------
*
*/
/** @license
* JSParsec - A parser combinator library for JavaScript
*
* http://code.google.com/p/jshaskell/
*
* Copyright (c) 2010 Balazs Endresz ([email protected])
* Dual licensed under the MIT and GPL licenses.
*
*
* The initial implementation of some combinators,
* and the memoization technique is derived from:
* http://www.bluishcoder.co.nz/2007/10/javascript-parser-combinators.html
*
* Most functions should behave like their counterparts in Parsec 3:
* http://www.haskell.org/haskellwiki/Parsec
*
* ------------------------------------------------------------
*
*/
/** @license
* JSHaskell - Some Haskell language features for JavaScript
*
* http://code.google.com/p/jshaskell/
*
* Copyright (c) 2010 Balazs Endresz ([email protected])
* Dual licensed under the MIT and GPL licenses.
*
* ------------------------------------------------------------
*
*/;(function(){
;(function(){
// -------------------------------------------------
// Main
// -------------------------------------------------
function namespace(ns, obj){
return NS[ns] = obj || {};
}
//e.g. module("Text_JSParsec"); importSubmodules("Text_JSParsec", ["Prim", "Char", ..]);
//if not all should be exported with "Text_JSParsec" then use the local attribute,
//and add them to the "Text_JSParsec" module manually: module("Text_JSParsec", {parse:parse, many: many, ...})
function importSubmodules(ns, imp){
var to = NS[ns];
//var imp = [].slice.call(arguments, 1);
for(var i = 0, l = imp.length; i < l; ++i){
var obj = NS[ns + "_" + imp[i]];
for(var name in obj)
to[name] = obj[name];
}
}
var global = function(){ return this }() || window,
NS = global["NS"] || (global["NS"] = {}),
undef,
_toString = {}.toString,
_slice = [].slice,
_map = [].map,
_filter = [].filter,
_indexOf = [].indexOf,
_lastIndexOf = [].lastIndexOf,
isSupported = {
//for non browser environments
setTimeout : typeof setTimeout != "undefined",
//to spare an extra function call with type class methods
funDecomp : function(){ return this }.toString().indexOf("this") != -1,
//for using Array.prototype methods on strings
stringAsArray : !!"a"[0],
//determines if object properties are enumerated in order
seqEnum: function(){
var obj = {9:1, d:1, b:1, 0:1, a:1, c:1},
arr = [9, "d", "b", 0, "a", "c"],
i = 0;
for(var key in obj)
if(key != arr[i++])
return false;
return true;
}()
},
isAllowed = {
funDecomp : true,
stringAsArray : true,
//e.g. using TypeClass.Type.method instead of getInstance(TypeClass, Type).method
funNameRef : true,
//TODO: depth
stackTrace : true
},
jsenv = { //TODO: not used yet
isSupported: isSupported,
isAllowed: isAllowed
},
ignoreAsserts = true; //TODO
global.global = global;
global.namespace = namespace;
global.importSubmodules = importSubmodules;
//function isType(str, a){ return _toString.call(a) == "[object " + str + "]" }
function isArray(a){ return _toString.call(a) == "[object Array]" }
function isDefined(x){ return x !== undef }
function strictEq(a, b){ return a === b }
function strictNe(a, b){ return a !== b }
function unsafeAdd(a, b){ return a + b }
function unsafeSub(a, b){ return a - b }
function unsafeMul(a, b){ return a * b }
function unsafeDiv(a, b){ return a / b }
function lt(a, b){ return a < b }
function le(a, b){ return a <= b }
function gt(a, b){ return a > b }
function ge(a, b){ return a >= b }
function negate(a){
return -a;
}
//TODO: null ?
function typeOf(a){
var ctr = a.constructor;
if(ctr)
return ctr;
var type = typeof a;
return type == "string" ? String :
type == "number" ? Number :
type == "boolean" ? Boolean :
type == "function" ? Function :
undef;
}
function curry(fn){
function ret(){
var args = slice(arguments);
return args.length >= (fn._length === undef ? fn.length : fn._length) ? fn.apply(null, args) :
function(){
return ret.apply( null, args.concat(slice(arguments)) );
};
}
return ret;
}
//e.g. eta(error, "Type error") returns a function, which calls error
//with the rest of the arguments, throwing an exception
function eta(f){
var args = slice(arguments, 1)
return function(){
return f.apply(null, args)
}
}
function stackTrace(){
function st(f){
return !f ? [] : [[f.name || f._name || f, f.arguments]].concat(st(f.caller));
}
return st(arguments.callee.caller);
}
function error(a){
var fnName = (a instanceof Function) ? (a.name || a._name) : null,
msg = fnName || a || "Unspecified error from " + arguments.callee.caller.name +" <- "+ arguments.callee.caller.caller.name,
err = new Error(msg);
try{
err.stackTrace = stackTrace();
}catch(_){}
err.message = msg;
throw err;
}
function extend(a, b){
for(var key in b)
a[key] = b[key];
return a;
}
// -------------------------------------------------
// Basic List/String functions,
// use ONLY the ones in Prelude or Data_List !!!
// -------------------------------------------------
var stringAsArray = !!"a"[0]; //TODO
//TODO!!! use only in low level code,
//replace occurances with tail/toArray in jsparsec
var slice = stringAsArray ?
function(arr, i1){ return _slice.call(arr, i1 || 0) } :
function(arr, i1){
var isString = typeof arr == "string";
if(isString){
arr = arr.split("");
if(!i1)
return arr;
}
return _slice.call(arr, i1 || 0);
}
function indexOf(value, arr) {
if(arr.indexOf)
return arr.indexOf(value);
var length = arr.length;
if(!length)
return -1;
for(var from = 0; from < length; from++)
if(arr[from] === value)
return from;
return -1;
}
function lastIndexOf(value, arr) {
if(arr.lastIndexOf)
return arr.lastIndexOf(value);
var length = arr.length;
if (!length)
return -1;
for (var from = length - 1; from > -1; --from)
if (arr[from] === value)
return from;
return -1;
}
function isort(arr){
var isStr = arr.charAt,
r = toArray(arr);
r.sort();
return isStr ? r.join("") : r;
}
var imap = _map ?
function(f, arr){ return _map.call(arr, f) } :
function(f, arr){
var res = [], i = 0, l = arr.length;
for(; i < l; ++i)
res[i] = f(arr[i], i, arr);
return res;
}
var ifilter = _filter ?
function(f, arr){ return _filter.call(arr, f) } :
function (f, arr){
var res = [], i = 0, l = arr.length;
for(; i < l; ++i)
if(f(arr[i], i, arr))
res.push(arr[i]);
return res;
}
function toArray(a){
if(!a.charAt)
return _slice.call(a, 0);
for(var r = [], i = 0, l = a.length; i < l; ++i)
r.push(a.charAt(i));
return r;
}
function range(lower, upper){
return {
indexOf: function(ch){ return (ch >= lower && ch <= upper) ? true : -1 },
toString: function(){ return "range(" + lower + ", " + upper + ")" }
};
}
// * the last return value indicates that the thunk is fully evaluated (i.e. it's not a function),
// and the result is passed to the continuation/callback specified in the program
// * the second parameter is for making it asynchronous (unless it's Infinity)
// * if the thunks are not CPS-based then only the synchronous method returns the result,
// which must not be a function
// * the unrolled loops are not _entirely_ pointless: e.g. a complex parser (like the one in WebBits)
// can build up hundreds of thousands of thunks even for a smaller document
function _evalThunks(thunk, hundredTimes) {
if (!hundredTimes || hundredTimes == Infinity) {
try {
while ((thunk = thunk()()()()()()()()()()()()()()()()()()()()()()()()()
()()()()()()()()()()()()()()()()()()()()()()()()()
()()()()()()()()()()()()()()()()()()()()()()()()()
()()()()()()()()()()()()()()()()()()()()()()()()()
));
} catch (e) {
//if(!/thunk/.test(e.message))
//throw e;
}
return thunk;
}
function next() {
try {
var i = hundredTimes;
do {
thunk = thunk()()()()()()()()()()()()()()()()()()()()()()()()()
()()()()()()()()()()()()()()()()()()()()()()()()()
()()()()()()()()()()()()()()()()()()()()()()()()()
()()()()()()()()()()()()()()()()()()()()()()()()();
} while (--i);
setTimeout(next, 1);
} catch (_) { }
}
next();
}
//a bit slower version for debugging:
function evalThunks(thunk, hundredTimes) {
if (!hundredTimes || hundredTimes == Infinity) {
do thunk = thunk()
while(thunk && thunk.call)
return thunk;
}
function next() {
var i = 100*hundredTimes;
do thunk = thunk()
while (--i && thunk && thunk.call);
setTimeout(next, 1);
}
next();
}
var Bool = Boolean;
namespace("Haskell_Main", {
Bool : Bool,
isArray : isArray,
isDefined : isDefined,
slice : slice,
imap : imap,
ifilter : ifilter,
indexOf : indexOf,
lastIndexOf : lastIndexOf,
isort : isort,
range : range,
extend : extend,
namespace : namespace,
typeOf : typeOf,
strictEq : strictEq,
strictNe : strictNe,
unsafeAdd : unsafeAdd,
unsafeSub : unsafeSub,
unsafeMul : unsafeMul,
unsafeDiv : unsafeDiv,
lt : lt,
le : le,
gt : gt,
ge : ge,
negate : negate,
evalThunks : evalThunks,
toArray : toArray,
curry : curry,
error : error,
eta : eta
});
/// <reference path="Main.js" />
// -------------------------------------------------
// Algebraic Data Types
// -------------------------------------------------
var accessors = {};
function accessor(prop, obj){
return obj ? obj[prop] : function(obj){ return obj[prop] }
}
function Record(){}
var record = new Record();
function ADT(){}
function adtToString(type){
return function(){
var acc = [], rec = this._recordset;
if(rec && (rec.constructor != Array)){
for(var name in rec){
var item = (type ? (rec[name].name || rec[name]) : this[name]);
if(!type && (item instanceof Function))
item = (item.constructor != Function) ?
item.constructor.name :
"Function(" + item.name + ")";
acc.push(name + (type ? " :: " : " = ") + item );
}
var indent = replicate(this._dataConstructor.length + 2, " ").join("");
acc = "{" + acc.join("\n" + indent + ",") + "\n" + indent +"}";
}else{
for(var i = 0; i in this; i++)
acc.push(type ? (rec[i].name || rec[i]) : this[i]);
acc = acc.join(" ");
}
return "(" + this._dataConstructor + (acc ? " " : "") + acc + ")";
};
}
ADT.prototype.toString = adtToString();
ADT.prototype.dataConstructorToString = adtToString(true);
//defined later
ADT.prototype.update = eta(error);
function dataError(checkType, valueType, name, typeName, constr) {
error("Type error: expecting " + checkType.name +
" instead of " + valueType.name +
" in the argument '" + name + "' of " + typeName + "." + constr);
}
function data(type, constr){
var typeName = type.name;
if(type._constructors)
throw "Type constructor has been already defined: '" + typeName + "'";
type._constructors = constr;
type.prototype = new ADT();
for(var i = 0, l = constr.length; i < l; ++i){
var single = typeof constr[i] != "object",
name = single ? constr[i] : constr[i][0];
if(name in type)
throw "The name of the data constructor (" +
typeName + "." + name + ") is invalid!";
type[name] = single ? mkDataCtr(name)() : mkDataCtr(name, slice(constr[i], 1));
if(!single)
type[name]._length = constr[i].length - 1; //for currying
}
function mkDataCtr(constr, fields){
var recordDef = fields && typeof fields[0] == "object";
var recordSet = recordDef && fields[0];
if(recordDef){
//this is used for simulating the record syntax
//but it's not guaranteed to work in every javascript environment
//beacause it assumes that the keys of objects are iterated
//in the order they were defined,
//but that is not part of the ECMAScript standard
var i = 0, fieldName, propToIndex = {}, indexToProp = {};
for (fieldName in recordSet) {
var fstchr = fieldName.charAt(0);
if ((fstchr == "_") || (fstchr == fstchr.toUpperCase()))
throw typeName + "." + name + "." + fieldName +
": record names can't start with underscore or uppercase letters";
if (fieldName in ({ update: 1 }))
throw typeName + "." + name + "." + fieldName + ": record name is invalid";
propToIndex[fieldName] = i;
indexToProp[i] = fieldName;
i++;
}
}
function create(_isrecord, rec){
var isrecord = (_isrecord instanceof Record),
adt = new type(),
value, valueType, checkType;
adt.constructor = type;
adt._recordset = (recordDef && fields[0]) || fields;
adt._dataConstructor = constr;
adt[constr] = true;
if (isrecord) {
for (var name in rec) {
value = rec[name];
if (!recordDef)
error("Records are not defined for " + typeName + "." + constr);
if (!(name in recordSet))
error("The accessor '" + name + "' is not defined for " + typeName + "." + constr);
checkType = recordSet[name];
if (typeof checkType != "string") {
valueType = typeOf(value);
if (valueType != checkType)
dataError(checkType, valueType, name, typeName, constr);
}
adt[name] = value;
adt[propToIndex[name]] = value;
}
} else {
var args = arguments;
for (var i = 0, l = args.length; i < l; ++i) {
value = args[i];
checkType = fields[i];
if (typeof checkType != "string") {
valueType = typeOf(value);
if (valueType != checkType)
dataError(checkType, valueType, i, typeName, constr);
}
adt[i] = value;
if(recordDef)
adt[indexToProp[i]] = value;
}
}
//TODO: deifne as separate function
adt.update = function(newRecords){
var obj = {};
for(var n in recordSet)
obj[n] = (n in newRecords) ? newRecords[n] : this[n];
return create(record, obj);
};
return adt;
}
return create;
}
}
//showConstrOf :: a -> String
//showConstrOf = Data.Data.showConstr . Data.Data.toConstr
function showConstrOf(dataType){
return dataType._dataConstructor;
}
//#region comment
//currently type variables on the lhs cannot be declared, and they are not checked at all:
// function Maybe(){}
// data(Maybe, [["Just", "a"], "Nothing"]);
// var Just = Maybe.Just;
// var Nothing = Maybe.Nothing;
//Just("a") instanceof Maybe
//Just("a").constructor == Maybe
//
//Just("a").Just == true //can be used in place of pattern matching: if(maybeval.Just) ... if(maybeval.Nothing) ...
//Just("a")[0] == "a" //access arguments by index
//
//Nothing.Nothing == true
//Nothing == Nothing
// using record syntax:
/*
function Type(){}
data(Type, [["Constr1", Number, "a"]
,"Constr2"
,["Constr3", {acc: Number}]
,["Constr4", Number]
]);
//in Haskell:
data Number = ... -- javascript number type
data Type a = Constr1 Number a
| Constr2
| Constr3 {acc :: Number}
| Constr4 Number
*/
//Type.Constr3(record, {acc:1}).Constr3 == true
//Type.Constr3(record, {acc:1}).acc == 1
//Type.Constr3(record, {acc:1})[0] == 1
//Type.Constr3(1)[0] == 1
//Type.Constr3(1).a == 1
//Type.Constr2.Constr2 == true
//Type.Constr2 == Type.Constr2
//record update (creates a new object):
//function T(){}
//data(T, [["C", {a: String,b: String}]]);
//T.C("2","3").update({a:"4"}).a == "4"
//#endregion
namespace("Haskell_DataType", {
data : data,
ADT : ADT,
record : record,
accessor : accessor,
accessors : accessors,
showConstrOf : showConstrOf
});/// <reference path="Main.js" />
// -------------------------------------------------
// Type classes
// -------------------------------------------------
//this is used for mapping a type to an object,
//which contains the instance functions
function Map() {
this.keys = [];
this.values = [];
}
Map.prototype.put = function (key, val) {
this.keys.push(key);
this.values.push(val);
}
Map.prototype.get = function (key) {
var i = indexOf(key, this.keys);
if (i == -1) return;
return this.values[i];
}
//if this is used in a type signature then from then on the types are not checked
var VARARG = {};
//TODO: define aliases for operators
//TODO: handle non-function types (e.g. Bounded)
function typeclass(name, tvar) {
var tcls = {};
tcls._context = [];
//tcls._fnTypes = {};
tcls._name = name;
tcls._dict = new Map();
tcls.context = function () {
this._context = slice(arguments);
delete tcls.context;
return this;
};
tcls.types = function (obj) {
this._fnTypes = obj;
delete tcls.types;
return this;
};
tcls.impl = function (obj) {
this._default = obj;
for (var name in tcls._fnTypes) (function (name, type) {
//constants can be accessed only from the instances
//see: asTypeOf, getInstance, typeOf
//but defaults are allowed
if ((type !== undef) && (type.constructor != Array)) {
tcls[name] = ((typeof obj == "function") ? obj() : obj)[name];
return;
} else
tcls[name] = function () {
var args = arguments;
var tctr;
if((type === undef) || (type === VARARG))
error("There's no type signature for " + tcls._name + "." + name +
", it can be accessed only by: getInstance(" +
tcls._name + ", SomeType" + ")." + name);
var matched;
//TODO: optimize
var matches = ifilter(function(arg, i) {
var t = type[i];
if(matched || (t == VARARG))
return (matched = true);
var ctr = typeOf(arg);
if (t == tvar) {
tctr = tctr || ctr;
return tctr == ctr;
}
else
return ctr == t;
}, args);
if (!matched && (matches.length != type.length - 1))
error("Type error in " + tcls._name + "." + name);
var inst = tcls._dict.get(tctr); //TODO: tcls[tctr.name || tctr._name] ||
if (!inst)
error("No " + tcls._name + " instance for " + (tctr.name || tctr._name));
return inst[name].apply(null, args);
};
} (name, tcls._fnTypes[name]));
delete tcls.impl;
return this;
};
return tcls;
}
function instance(tcls, tctr, defs) {
//check if superclasses are defined
imap(function (cls) {
if (!cls._dict.get(tctr))
throw "No " + (cls._name || "") + " instance for " + (tctr.name || tctr._name);
}, tcls._context);
//create instance
var inst = {};
//create reference to the type constructor
inst._type = tctr;
//store the instance on the type class in a map :: Map Type (Instance Type)
tcls._dict.put(tctr, inst);
//create definitions by optionally passing the instance,
//so that methods can refernce each other directly
defs = (typeof defs == "function") ? defs(inst) : (defs || {});
//copy instance methods or defaults to the instance object
var defaults = tcls._default;
defaults = (typeof defaults == "function") ? defaults(inst) : defaults;
for(var name in tcls._fnTypes)
inst[name] = defs[name] || defaults[name];
return inst;
}
//Ord.compare(1,2) -> Ordering.LT
function getInstance(tcls, tctr) {
return tcls._dict.get(tctr);
}
//var OrdNum = getInstance(Ord, Number)
//OrdNum.compare(1,2) -> Ordering.LT
function asTypeOf(tcls, method, value) {
return tcls._dict.get(typeOf(value))[method];
//return getInstance(tcls, typeOf(value))[method];
}
//#region comment
/*
//in contrast with Haskell `asTypeOf` takes a type class, and a method name
//instead of a function as a first argument
//it's essential for getting a constant value (not a function) from a type class
//e.g. since Bounded.maxBound is not a function, but it has different values for each type,
//Bounded.maxBound is undefined, maxBound exists only on each instance
//there are two ways of getting the right value, both are identical:
function getLastIndex1(a){
var iBounded = getInstance(Bounded, typeOf(a));
return Enum.fromEnum( iBounded.maxBound )
}
function getLastIndex2(a){
return Enum.fromEnum( asTypeOf(Bounded, "maxBound", a) )
}
//the same as the second one:
var getLastIndex3 = compose1(Enum.fromEnum, curry(asTypeOf)(Bounded, "maxBound"))
//if more functions are used from the same type class (inside a loop for example)
//then getting the instance explicitly is more efficient, but not necessary:
function getRangeLength(a){
var type = typeOf(a),
iBounded = getInstance(Bounded, type),
iEnum = getInstance(Enum , type);
return iEnum.fromEnum(iBounded.maxBound) - iEnum.fromEnum(iBounded.minBound)
}
//there's no expicit Enum instance here, so it will be resolved twice:
function getRangeLength_slower(a){
var type = typeOf(a),
iBounded = getInstance(Bounded, type);
return Enum.fromEnum(iBounded.maxBound) - Enum.fromEnum(iBounded.minBound)
}
*/
//#endregion
namespace("Haskell_TypeClass", {
typeclass : typeclass
,VARARG : VARARG
,instance : instance
,getInstance : getInstance
,asTypeOf : asTypeOf
})/// <reference path="Main.js" />
// -------------------------------------------------
// Operators
// -------------------------------------------------
function infixl(strength){ return ["l", strength] }
function infixr(strength){ return ["r", strength] }
function infix (strength){ return ["x", strength] }
function getFixity(opstr){
if(!opstr)
return;
if(opstr._String)
return;
var op = operators[opstr];
if(opstr._Op && !op)
return ["l", 9];
return op && op.fixity;
}
function getFixityDir(opstr){
if(!opstr)
return;
if(opstr._String)
return;
var op = operators[opstr];
if(opstr._Op && !op)
return "l";
return op && (op.fixity[0] || "l" );
}
function getFixityStrn(opstr){
if(!opstr)
return;
if(opstr._String)
return;
var op = operators[opstr];
if(opstr._Op && !op)
return 9;
return op && (isDefined(op.fixity[1]) ? op.fixity[1] : 9);
}
var operators = {};
// -------------------------------------------------
// Array expressions
// -------------------------------------------------
function Recurse(){}
var recurse = new Recurse();
// -- see usage in Char
function splice_args(args, i, rec){
var op;
if(args[i]._Op){
delete args[i]._Op;
op = args[i];
}else
op = operators[args[i]].func;
var item = op(args[i-1], args[i+1]);
args.splice(i-1, 3 , item);
return resolve(args, rec);
}
//In array-expressions if the square brackets are not intended for groupping subexpressions
//but an actual array is needed the it should be wrapped in `no` (i.e. "not operator")
//just like if there's a chance that a string might be the same one as an operator.
//
//Conversely, functions can be used as operators by wrapping them in `op`.
//
//var p = ex(string, no("<|>"), op(parserPlus), return_, no([])).resolve();
//
//But usually this can be done by simply using the native javascript call operator:
//
//var p = ex(string("<|>"), "<|>", return_([])).resolve();
function no(a){
if(typeof a == "string"){
var string = new String(a);
string._String = true;
return string;
}else{
a._Array = true;
return a;
}
}
function op(fn){
fn._Op = true;
return fn;
}
//TODO: reject multiple infix operators in the same expression
function resolve(args, rec){
//recurse on nested array-expressions or callstreams
args = imap(function(e){
if(!e)
return e;
if(e._Array){
delete e._Array;
return e;
}
return (e.constructor == Array) ? resolve(e, rec) :
(e.CallStream) ? e.resolve(rec) : e;
}, args);
//inject recursive calls
if(rec)
args = imap(function(e){return e instanceof Recurse ? rec : e}, args);
//execute functions between operators
var fna = [], fn, newfna = [], i = 0, l = args.length;
for(; i < l; ++i){
var e = args[i], isOp = false;
if(operators[e])
isOp = true;
if(e && e._String){
isOp = false;
e = e.toString();
}
if(e && e._Op)
isOp = true;
if(!isOp && i != (l-1))
fna.push(e);
else{
if(i == (l-1))
fna.push(e);
if(fna.length> 1){
//if(!fna[0] || !fna[0].apply)
// throw ["Expecting function in array-expression instead of " + fna[0], args, fna];
var functionInArrayExpr = fna[0];
fn = functionInArrayExpr.apply(null, fna.slice(1));
}
else
fn = fna[0];
newfna.push(fn);
if(i != l-1)
newfna.push(e);
fna = [];
}
}
args = newfna;