-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
index.js
2487 lines (2312 loc) · 78.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
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
/* ___ ______
/ /\ / ___/\
______/ / / _______ __/ /___\/
/ ___ / / / ___ \ /_ __/\
/ /\_/ / / / /__/ /\ \/ /\_\/
/ / // / / / ______/ / / / /
/ /_// / / / /______\/ / / /
\_______/ / \_______/\ /__/ /
\______\/ \______\/ \__*/
//. # sanctuary-def
//.
//. sanctuary-def is a run-time type system for JavaScript. It facilitates
//. the definition of curried JavaScript functions which are explicit about
//. the number of arguments to which they may be applied and the types of
//. those arguments.
//.
//. It is conventional to import the package as `$`:
//.
//. ```javascript
//. const $ = require('sanctuary-def');
//. ```
//.
//. The next step is to define an environment. An environment is an array
//. of [types][]. [`env`][] is an environment containing all the built-in
//. JavaScript types. It may be used as the basis for environments which
//. include custom types in addition to the built-in types:
//.
//. ```javascript
//. // Integer :: Type
//. const Integer = ...;
//.
//. // NonZeroInteger :: Type
//. const NonZeroInteger = ...;
//.
//. // env :: Array Type
//. const env = $.env.concat([Integer, NonZeroInteger]);
//. ```
//.
//. The next step is to define a `def` function for the environment:
//.
//. ```javascript
//. const def = $.create({checkTypes: true, env: env});
//. ```
//.
//. The `checkTypes` option determines whether type checking is enabled.
//. This allows one to only pay the performance cost of run-time type checking
//. during development. For example:
//.
//. ```javascript
//. const def = $.create({
//. checkTypes: process.env.NODE_ENV === 'development',
//. env: env,
//. });
//. ```
//.
//. `def` is a function for defining functions. For example:
//.
//. ```javascript
//. // add :: Number -> Number -> Number
//. const add =
//. def('add', {}, [$.Number, $.Number, $.Number], (x, y) => x + y);
//. ```
//.
//. `[$.Number, $.Number, $.Number]` specifies that `add` takes two arguments
//. of type `Number` and returns a value of type `Number`.
//.
//. Applying `add` to two arguments gives the expected result:
//.
//. ```javascript
//. add(2, 2);
//. // => 4
//. ```
//.
//. Applying `add` to greater than two arguments results in an exception being
//. thrown:
//.
//. ```javascript
//. add(2, 2, 2);
//. // ! TypeError: ‘add’ requires two arguments; received three arguments
//. ```
//.
//. Applying `add` to fewer than two arguments results in a function
//. awaiting the remaining arguments. This is known as partial application.
//. Partial application is convenient as it allows more specific functions
//. to be defined in terms of more general ones:
//.
//. ```javascript
//. // inc :: Number -> Number
//. const inc = add(1);
//.
//. inc(7);
//. // => 8
//. ```
//.
//. JavaScript's implicit type coercion often obfuscates the source of type
//. errors. Consider the following function:
//.
//. ```javascript
//. // _add :: (Number, Number) -> Number
//. const _add = (x, y) => x + y;
//. ```
//.
//. The type signature indicates that `_add` takes two arguments of type
//. `Number`, but this is not enforced. This allows type errors to be silently
//. ignored:
//.
//. ```javascript
//. _add('2', '2');
//. // => '22'
//. ```
//.
//. `add`, on the other hand, throws if applied to arguments of the wrong
//. types:
//.
//. ```javascript
//. add('2', '2');
//. // ! TypeError: Invalid value
//. //
//. // add :: Number -> Number -> Number
//. // ^^^^^^
//. // 1
//. //
//. // 1) "2" :: String
//. //
//. // The value at position 1 is not a member of ‘Number’.
//. ```
//.
//. Type checking is performed as arguments are provided (rather than once all
//. arguments have been provided), so type errors are reported early:
//.
//. ```javascript
//. add('X');
//. // ! TypeError: Invalid value
//. //
//. // add :: Number -> Number -> Number
//. // ^^^^^^
//. // 1
//. //
//. // 1) "X" :: String
//. //
//. // The value at position 1 is not a member of ‘Number’.
//. ```
(function(f) {
'use strict';
/* istanbul ignore else */
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = f(require('sanctuary-type-classes'),
require('sanctuary-type-identifiers'));
} else if (typeof define === 'function' && define.amd != null) {
define(['sanctuary-type-classes', 'sanctuary-type-identifiers'], f);
} else {
self.sanctuaryDef = f(self.sanctuaryTypeClasses,
self.sanctuaryTypeIdentifiers);
}
}(function(Z, type) {
'use strict';
//# __ :: Placeholder
//.
//. The special placeholder value.
//.
//. One may wish to partially apply a function whose parameters are in the
//. "wrong" order. Functions defined via sanctuary-def accommodate this by
//. accepting placeholders for arguments yet to be provided. For example:
//.
//. ```javascript
//. // concatS :: String -> String -> String
//. const concatS =
//. def('concatS', {}, [$.String, $.String, $.String], (x, y) => x + y);
//.
//. // exclaim :: String -> String
//. const exclaim = concatS($.__, '!');
//.
//. exclaim('ahoy');
//. // => 'ahoy!'
//. ```
var __ = {'@@functional/placeholder': true};
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var MIN_SAFE_INTEGER = -MAX_SAFE_INTEGER;
var slice = Array.prototype.slice;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function Either(tag, value) {
this.isLeft = tag === 'Left';
this.isRight = tag === 'Right';
this.value = value;
}
Either['@@type'] = 'sanctuary-def/Either';
Either.prototype['fantasy-land/map'] = function(f) {
return this.isLeft ? this : Right(f(this.value));
};
Either.prototype['fantasy-land/chain'] = function(f) {
return this.isLeft ? this : f(this.value);
};
// Left :: a -> Either a b
function Left(x) { return new Either('Left', x); }
// Right :: b -> Either a b
function Right(x) { return new Either('Right', x); }
// K :: a -> b -> a
function K(x) { return function(y) { return x; }; }
// always :: a -> (-> a)
function always(x) { return function() { return x; }; }
// always2 :: a -> (b, c) -> a
function always2(x) { return function(y, z) { return x; }; }
// id :: a -> a
function id(x) { return x; }
// init :: Array a -> Array a
function init(xs) { return xs.slice(0, -1); }
// isEmpty :: Array a -> Boolean
function isEmpty(xs) { return xs.length === 0; }
// isPrefix :: Array a -> Array a -> Boolean
function isPrefix(candidate) {
return function(xs) {
if (candidate.length > xs.length) return false;
for (var idx = 0; idx < candidate.length; idx += 1) {
if (candidate[idx] !== xs[idx]) return false;
}
return true;
};
}
// last :: Array a -> a
function last(xs) { return xs[xs.length - 1]; }
// memberOf :: Array a -> a -> Boolean
function memberOf(xs) {
return function(y) {
return xs.some(function(x) { return Z.equals(x, y); });
};
}
// or :: (Array a, Array a) -> Array a
function or(xs, ys) { return isEmpty(xs) ? ys : xs; }
// range :: (Number, Number) -> Array Number
function range(start, stop) {
var result = [];
for (var n = start; n < stop; n += 1) result.push(n);
return result;
}
// strRepeat :: (String, Integer) -> String
function strRepeat(s, times) {
return Array(times + 1).join(s);
}
// r :: Char -> String -> String
function r(c) {
return function(s) {
return strRepeat(c, s.length);
};
}
// _ :: String -> String
var _ = r(' ');
// stripOutermostParens :: String -> String
function stripOutermostParens(s) {
return s.slice('('.length, -')'.length);
}
// trimTrailingSpaces :: String -> String
function trimTrailingSpaces(s) {
return s.replace(/[ ]+$/gm, '');
}
// unless :: (Boolean, (a -> a), a) -> a
function unless(bool, f, x) {
return bool ? x : f(x);
}
// when :: (Boolean, (a -> a), a) -> a
function when(bool, f, x) {
return bool ? f(x) : x;
}
// wrap :: String -> String -> String -> String
function wrap(prefix) {
return function(suffix) {
return function(s) {
return prefix + s + suffix;
};
};
}
// q :: String -> String
var q = wrap('\u2018')('\u2019');
// stripNamespace :: String -> String
function stripNamespace(s) { return s.slice(s.indexOf('/') + 1); }
// _Type :: ... -> Type
function _Type(
type, // :: String
name, // :: String
url, // :: String
format, // :: (String -> String, String -> String -> String) -> String
test, // :: Any -> Boolean
keys, // :: Array String
types // :: StrMap { extractor :: a -> Array b, type :: Type }
) {
this._test = test;
this.format = format;
this.keys = keys;
this.name = name;
this.type = type;
this.types = types;
this.url = url;
}
_Type['@@type'] = 'sanctuary-def/Type';
_Type.prototype.validate = function(x) {
if (!this._test(x)) return Left({value: x, propPath: []});
for (var idx = 0; idx < this.keys.length; idx += 1) {
var k = this.keys[idx];
var t = this.types[k];
for (var idx2 = 0, ys = t.extractor(x); idx2 < ys.length; idx2 += 1) {
var result = t.type.validate(ys[idx2]);
if (result.isLeft) {
var value = result.value.value;
var propPath = Z.concat([k], result.value.propPath);
return Left({value: value, propPath: propPath});
}
}
}
return Right(x);
};
_Type.prototype.toString = function() {
return this.format(id, K(id));
};
var BINARY = 'BINARY';
var FUNCTION = 'FUNCTION';
var INCONSISTENT = 'INCONSISTENT';
var NULLARY = 'NULLARY';
var RECORD = 'RECORD';
var UNARY = 'UNARY';
var UNKNOWN = 'UNKNOWN';
var VARIABLE = 'VARIABLE';
// Inconsistent :: Type
var Inconsistent =
new _Type(INCONSISTENT, '', '', always2('???'), K(false), [], {});
// typeEq :: String -> a -> Boolean
function typeEq(name) {
return function(x) {
return type(x) === name;
};
}
// typeofEq :: String -> a -> Boolean
function typeofEq(typeof_) {
return function(x) {
return typeof x === typeof_;
};
}
// functionUrl :: String -> String
function functionUrl(name) {
var version = '0.9.0'; // updated programmatically
return 'https://github.com/sanctuary-js/sanctuary-def/tree/v' + version +
'#' + stripNamespace(name);
}
// NullaryTypeWithUrl :: (String, Any -> Boolean) -> Type
function NullaryTypeWithUrl(name, test) {
return NullaryType(name, functionUrl(name), test);
}
// EnumTypeWithUrl :: (String, Array Any) -> Type
function EnumTypeWithUrl(name, members) {
return EnumType(name, functionUrl(name), members);
}
// UnaryTypeWithUrl ::
// (String, Any -> Boolean, t a -> Array a) -> (Type -> Type)
function UnaryTypeWithUrl(name, test, _1) {
return UnaryType(name, functionUrl(name), test, _1);
}
// BinaryTypeWithUrl ::
// (String, Any -> Boolean, t a b -> Array a, t a b -> Array b) ->
// ((Type, Type) -> Type)
function BinaryTypeWithUrl(name, test, _1, _2) {
return BinaryType(name, functionUrl(name), test, _1, _2);
}
// applyParameterizedTypes :: Array Type -> Array Type
function applyParameterizedTypes(types) {
return Z.map(function(x) {
return typeof x === 'function' ?
x.apply(null, Z.map(K(Unknown), range(0, x.length))) :
x;
}, types);
}
//. ### Types
//.
//. Conceptually, a type is a set of values. One can think of a value of
//. type `Type` as a function of type `Any -> Boolean` which tests values
//. for membership in the set (though this is an oversimplification).
//# Any :: Type
//.
//. Type comprising every JavaScript value.
var Any = NullaryTypeWithUrl('sanctuary-def/Any', K(true));
//# AnyFunction :: Type
//.
//. Type comprising every Function value.
var AnyFunction = NullaryTypeWithUrl('Function', typeEq('Function'));
//# Arguments :: Type
//.
//. Type comprising every [`arguments`][arguments] object.
var Arguments = NullaryTypeWithUrl('Arguments', typeEq('Arguments'));
//# Array :: Type -> Type
//.
//. Constructor for homogeneous Array types.
var Array_ = UnaryTypeWithUrl('Array', typeEq('Array'), id);
//# Boolean :: Type
//.
//. Type comprising `true` and `false`.
var Boolean_ = NullaryTypeWithUrl('Boolean', typeofEq('boolean'));
//# Date :: Type
//.
//. Type comprising every Date value.
var Date_ = NullaryTypeWithUrl('Date', typeEq('Date'));
//# Error :: Type
//.
//. Type comprising every Error value, including values of more specific
//. constructors such as [`SyntaxError`][] and [`TypeError`][].
var Error_ = NullaryTypeWithUrl('Error', typeEq('Error'));
//# FiniteNumber :: Type
//.
//. Type comprising every [`ValidNumber`][] value except `Infinity` and
//. `-Infinity`.
var FiniteNumber = NullaryTypeWithUrl(
'sanctuary-def/FiniteNumber',
function(x) { return ValidNumber._test(x) && isFinite(x); }
);
//# Function :: Array Type -> Type
//.
//. Constructor for Function types.
//.
//. Examples:
//.
//. - `$.Function([$.Date, $.String])` represents the `Date -> String`
//. type; and
//. - `$.Function([a, b, a])` represents the `(a, b) -> a` type.
function Function_(types) {
function format(outer, inner) {
var xs = types.map(function(t, idx) {
return unless(t.type === RECORD || isEmpty(t.keys),
stripOutermostParens,
inner('$' + String(idx + 1))(String(t)));
});
var parenthesize = wrap(outer('('))(outer(')'));
return parenthesize(unless(types.length === 2,
parenthesize,
init(xs).join(outer(', '))) +
outer(' -> ') +
last(xs));
}
var test = AnyFunction._test;
var $keys = [];
var $types = {};
types.forEach(function(t, idx) {
var k = '$' + String(idx + 1);
$keys.push(k);
$types[k] = {extractor: K([]), type: t};
});
return new _Type(FUNCTION, '', '', format, test, $keys, $types);
}
//# GlobalRegExp :: Type
//.
//. Type comprising every [`RegExp`][] value whose `global` flag is `true`.
//.
//. See also [`NonGlobalRegExp`][].
var GlobalRegExp = NullaryTypeWithUrl(
'sanctuary-def/GlobalRegExp',
function(x) { return RegExp_._test(x) && x.global; }
);
//# Integer :: Type
//.
//. Type comprising every integer in the range
//. [[`Number.MIN_SAFE_INTEGER`][min] .. [`Number.MAX_SAFE_INTEGER`][max]].
var Integer = NullaryTypeWithUrl(
'sanctuary-def/Integer',
function(x) {
return ValidNumber._test(x) &&
Math.floor(x) === x &&
x >= MIN_SAFE_INTEGER &&
x <= MAX_SAFE_INTEGER;
}
);
//# NegativeFiniteNumber :: Type
//.
//. Type comprising every [`FiniteNumber`][] value less than zero.
var NegativeFiniteNumber = NullaryTypeWithUrl(
'sanctuary-def/NegativeFiniteNumber',
function(x) { return FiniteNumber._test(x) && x < 0; }
);
//# NegativeInteger :: Type
//.
//. Type comprising every [`Integer`][] value less than zero.
var NegativeInteger = NullaryTypeWithUrl(
'sanctuary-def/NegativeInteger',
function(x) { return Integer._test(x) && x < 0; }
);
//# NegativeNumber :: Type
//.
//. Type comprising every [`Number`][] value less than zero.
var NegativeNumber = NullaryTypeWithUrl(
'sanctuary-def/NegativeNumber',
function(x) { return Number_._test(x) && x < 0; }
);
//# NonGlobalRegExp :: Type
//.
//. Type comprising every [`RegExp`][] value whose `global` flag is `false`.
//.
//. See also [`GlobalRegExp`][].
var NonGlobalRegExp = NullaryTypeWithUrl(
'sanctuary-def/NonGlobalRegExp',
function(x) { return RegExp_._test(x) && !x.global; }
);
//# NonZeroFiniteNumber :: Type
//.
//. Type comprising every [`FiniteNumber`][] value except `0` and `-0`.
var NonZeroFiniteNumber = NullaryTypeWithUrl(
'sanctuary-def/NonZeroFiniteNumber',
function(x) { return FiniteNumber._test(x) && x !== 0; }
);
//# NonZeroInteger :: Type
//.
//. Type comprising every [`Integer`][] value except `0` and `-0`.
var NonZeroInteger = NullaryTypeWithUrl(
'sanctuary-def/NonZeroInteger',
function(x) { return Integer._test(x) && x !== 0; }
);
//# NonZeroValidNumber :: Type
//.
//. Type comprising every [`ValidNumber`][] value except `0` and `-0`.
var NonZeroValidNumber = NullaryTypeWithUrl(
'sanctuary-def/NonZeroValidNumber',
function(x) { return ValidNumber._test(x) && x !== 0; }
);
//# Null :: Type
//.
//. Type whose sole member is `null`.
var Null = NullaryTypeWithUrl('Null', typeEq('Null'));
//# Nullable :: Type -> Type
//.
//. Constructor for types which include `null` as a member.
var Nullable = UnaryTypeWithUrl(
'sanctuary-def/Nullable',
K(true),
function(nullable) { return nullable === null ? [] : [nullable]; }
);
//# Number :: Type
//.
//. Type comprising every primitive Number value (including `NaN`).
var Number_ = NullaryTypeWithUrl('Number', typeofEq('number'));
//# Object :: Type
//.
//. Type comprising every "plain" Object value. Specifically, values
//. created via:
//.
//. - object literal syntax;
//. - [`Object.create`][]; or
//. - the `new` operator in conjunction with `Object` or a custom
//. constructor function.
var Object_ = NullaryTypeWithUrl('Object', typeEq('Object'));
//# Pair :: Type -> Type -> Type
//.
//. Constructor for tuple types of length 2. Arrays are said to represent
//. tuples. `['foo', 42]` is a member of `Pair String Number`.
var Pair = BinaryTypeWithUrl(
'sanctuary-def/Pair',
function(x) { return typeEq('Array')(x) && x.length === 2; },
function(pair) { return [pair[0]]; },
function(pair) { return [pair[1]]; }
);
//# PositiveFiniteNumber :: Type
//.
//. Type comprising every [`FiniteNumber`][] value greater than zero.
var PositiveFiniteNumber = NullaryTypeWithUrl(
'sanctuary-def/PositiveFiniteNumber',
function(x) { return FiniteNumber._test(x) && x > 0; }
);
//# PositiveInteger :: Type
//.
//. Type comprising every [`Integer`][] value greater than zero.
var PositiveInteger = NullaryTypeWithUrl(
'sanctuary-def/PositiveInteger',
function(x) { return Integer._test(x) && x > 0; }
);
//# PositiveNumber :: Type
//.
//. Type comprising every [`Number`][] value greater than zero.
var PositiveNumber = NullaryTypeWithUrl(
'sanctuary-def/PositiveNumber',
function(x) { return Number_._test(x) && x > 0; }
);
//# RegExp :: Type
//.
//. Type comprising every RegExp value.
var RegExp_ = NullaryTypeWithUrl('RegExp', typeEq('RegExp'));
//# RegexFlags :: Type
//.
//. Type comprising the canonical RegExp flags:
//.
//. - `''`
//. - `'g'`
//. - `'i'`
//. - `'m'`
//. - `'gi'`
//. - `'gm'`
//. - `'im'`
//. - `'gim'`
var RegexFlags = EnumTypeWithUrl(
'sanctuary-def/RegexFlags',
['', 'g', 'i', 'm', 'gi', 'gm', 'im', 'gim']
);
//# StrMap :: Type -> Type
//.
//. Constructor for homogeneous Object types.
//.
//. `{foo: 1, bar: 2, baz: 3}`, for example, is a member of `StrMap Number`;
//. `{foo: 1, bar: 2, baz: 'XXX'}` is not.
var StrMap = UnaryTypeWithUrl(
'sanctuary-def/StrMap',
Object_._test,
function(strMap) {
return Z.map(function(k) { return strMap[k]; },
Object.keys(strMap).sort());
}
);
//# String :: Type
//.
//. Type comprising every primitive String value.
var String_ = NullaryTypeWithUrl('String', typeofEq('string'));
//# Undefined :: Type
//.
//. Type whose sole member is `undefined`.
var Undefined = NullaryTypeWithUrl('Undefined', typeEq('Undefined'));
//# Unknown :: Type
//.
//. Type used internally to represent missing type information. The type of
//. `[]`, for example, is `Array ???`. This type is exported solely for use
//. by other Sanctuary packages.
var Unknown = new _Type(UNKNOWN, '', '', always2('???'), K(true), [], {});
//# ValidDate :: Type
//.
//. Type comprising every [`Date`][] value except `new Date(NaN)`.
var ValidDate = NullaryTypeWithUrl(
'sanctuary-def/ValidDate',
function(x) { return Date_._test(x) && !isNaN(x.valueOf()); }
);
//# ValidNumber :: Type
//.
//. Type comprising every [`Number`][] value except `NaN`.
var ValidNumber = NullaryTypeWithUrl(
'sanctuary-def/ValidNumber',
function(x) { return Number_._test(x) && !isNaN(x); }
);
//# env :: Array Type
//.
//. An array of [types][]:
//.
//. - [`AnyFunction`][]
//. - [`Arguments`][]
//. - [`Array`][]
//. - [`Boolean`][]
//. - [`Date`][]
//. - [`Error`][]
//. - [`Null`][]
//. - [`Number`][]
//. - [`Object`][]
//. - [`RegExp`][]
//. - [`StrMap`][]
//. - [`String`][]
//. - [`Undefined`][]
var env = applyParameterizedTypes([
AnyFunction,
Arguments,
Array_,
Boolean_,
Date_,
Error_,
Null,
Number_,
Object_,
RegExp_,
StrMap,
String_,
Undefined
]);
// Type :: Type
var Type = NullaryType(
'sanctuary-def/Type',
'',
typeEq('sanctuary-def/Type')
);
// TypeClass :: Type
var TypeClass = NullaryType(
'sanctuary-type-classes/TypeClass',
'',
typeEq('sanctuary-type-classes/TypeClass')
);
// Unchecked :: String -> Type
function Unchecked(s) { return NullaryType(s, '', K(true)); }
var def = _create({checkTypes: true, env: env});
// arity :: (Number, Function) -> Function
function arity(n, f) {
return (
n === 0 ?
function() {
return f.apply(this, arguments);
} :
n === 1 ?
function($1) {
return f.apply(this, arguments);
} :
n === 2 ?
function($1, $2) {
return f.apply(this, arguments);
} :
n === 3 ?
function($1, $2, $3) {
return f.apply(this, arguments);
} :
n === 4 ?
function($1, $2, $3, $4) {
return f.apply(this, arguments);
} :
n === 5 ?
function($1, $2, $3, $4, $5) {
return f.apply(this, arguments);
} :
n === 6 ?
function($1, $2, $3, $4, $5, $6) {
return f.apply(this, arguments);
} :
n === 7 ?
function($1, $2, $3, $4, $5, $6, $7) {
return f.apply(this, arguments);
} :
n === 8 ?
function($1, $2, $3, $4, $5, $6, $7, $8) {
return f.apply(this, arguments);
} :
// else
function($1, $2, $3, $4, $5, $6, $7, $8, $9) {
return f.apply(this, arguments);
}
);
}
// numArgs :: Number -> String
function numArgs(n) {
switch (n) {
case 0: return 'zero arguments';
case 1: return 'one argument';
case 2: return 'two arguments';
case 3: return 'three arguments';
case 4: return 'four arguments';
case 5: return 'five arguments';
case 6: return 'six arguments';
case 7: return 'seven arguments';
case 8: return 'eight arguments';
case 9: return 'nine arguments';
default: return n + ' arguments';
}
}
// _determineActualTypes :: ... -> Array Type
function _determineActualTypes(
loose, // :: Boolean
env, // :: Array Type
types, // :: Array Type
seen, // :: Array Object
values // :: Array Any
) {
var recur = _determineActualTypes;
function refine(types, value) {
var seen$;
if (typeof value === 'object' && value != null ||
typeof value === 'function') {
// Abort if a circular reference is encountered; add the current
// object to the array of seen objects otherwise.
if (seen.indexOf(value) >= 0) return [];
seen$ = Z.concat(seen, [value]);
} else {
seen$ = seen;
}
return Z.chain(function(t) {
return (
t.name === 'sanctuary-def/Nullable' || t.validate(value).isLeft ?
[] :
t.type === UNARY ?
Z.map(fromUnaryType(t),
recur(loose, env, env, seen$, t.types.$1.extractor(value))) :
t.type === BINARY ?
xprod(
t,
t.types.$1.type.type === UNKNOWN ?
recur(loose, env, env, seen$, t.types.$1.extractor(value)) :
[t.types.$1.type],
t.types.$2.type.type === UNKNOWN ?
recur(loose, env, env, seen$, t.types.$2.extractor(value)) :
[t.types.$2.type]
) :
// else
[t]
);
}, types);
}
return isEmpty(values) ?
[Unknown] :
or(Z.reduce(refine, types, values), loose ? [Inconsistent] : []);
}
// rejectInconsistent :: Array Type -> Array Type
function rejectInconsistent(types) {
return types.filter(function(t) {
return t.type !== INCONSISTENT && t.type !== UNKNOWN;
});
}
// determineActualTypesStrict ::
// (Array Type, Array Type, Array Any) -> Array Type
function determineActualTypesStrict(env, types, values) {
var types$ = _determineActualTypes(false, env, types, [], values);
return rejectInconsistent(types$);
}
// determineActualTypesLoose ::
// (Array Type, Array Type, Array Any) -> Array Type
function determineActualTypesLoose(env, types, values) {
var types$ = _determineActualTypes(true, env, types, [], values);
return rejectInconsistent(types$);
}
// TypeInfo = { name :: String
// , constraints :: StrMap (Array TypeClass)
// , types :: Array Type }
//
// TypeVarMap = StrMap { types :: Array Type
// , valuesByPath :: StrMap (Array Any) }
//
// PropPath = Array (Number | String)
// updateTypeVarMap :: ... -> TypeVarMap
function updateTypeVarMap(
env, // :: Array Type
typeVarMap, // :: TypeVarMap
typeVar, // :: Type
index, // :: Integer
propPath, // :: PropPath
values // :: Array Any
) {
var $typeVarMap = {};
for (var typeVarName in typeVarMap) {
var entry = typeVarMap[typeVarName];
var $entry = {types: entry.types.slice(), valuesByPath: {}};
for (var k in entry.valuesByPath) {
$entry.valuesByPath[k] = entry.valuesByPath[k].slice();
}
$typeVarMap[typeVarName] = $entry;
}
if (!hasOwnProperty.call($typeVarMap, typeVar.name)) {
$typeVarMap[typeVar.name] = {types: env.slice(), valuesByPath: {}};
}
var key = JSON.stringify(Z.concat([index], propPath));
if (!hasOwnProperty.call($typeVarMap[typeVar.name].valuesByPath, key)) {
$typeVarMap[typeVar.name].valuesByPath[key] = [];
}
values.forEach(function(value) {
$typeVarMap[typeVar.name].valuesByPath[key].push(value);
$typeVarMap[typeVar.name].types = Z.chain(
function(t) {
var xs;
var invalid = !test(env, t, value);
return (
invalid ?
[] :
typeVar.keys.length > 0 ?
[t].filter(function(t) {
return (
t.type !== RECORD &&
t.keys.length >= typeVar.keys.length &&
t.keys.slice(-typeVar.keys.length).every(function(k) {
var xs = t.types[k].extractor(value);
return isEmpty(xs) ||
!isEmpty(determineActualTypesStrict(env, env, xs));
})
);
}) :
t.type === UNARY ?
t.types.$1.type.type === UNKNOWN &&
!isEmpty(xs = t.types.$1.extractor(value)) ?
Z.map(fromUnaryType(t),
determineActualTypesStrict(env, env, xs)) :
[t] :
t.type === BINARY ?
xprod(t,
t.types.$1.type.type === UNKNOWN &&
!isEmpty(xs = t.types.$1.extractor(value)) ?
determineActualTypesStrict(env, env, xs) :
[t.types.$1.type],
t.types.$2.type.type === UNKNOWN &&
!isEmpty(xs = t.types.$2.extractor(value)) ?
determineActualTypesStrict(env, env, xs) :
[t.types.$2.type]) :
// else
[t]
);
},
$typeVarMap[typeVar.name].types
);
});
return $typeVarMap;
}
// underlineTypeVars :: (TypeInfo, StrMap (Array Any)) -> String
function underlineTypeVars(typeInfo, valuesByPath) {
// Note: Sorting these keys lexicographically is not "correct", but it
// does the right thing for indexes less than 10.
var paths = Z.map(JSON.parse, Object.keys(valuesByPath).sort());
return underline(
typeInfo,