/
stdlib.ngs
4120 lines (3410 loc) · 121 KB
/
stdlib.ngs
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
STDLIB_EOL = "\n"
STDLIB_PATH_SEP = '/'
STDLIB_CHILD_TO_PARENT_PIPE_DIR = 1
STDLIB_PARENT_TO_CHILD_PIPE_DIR = 2
STDLIB_MAX_RAND_REAL = Real(RAND_MAX)
STDLIB_RAND_SAFETY_MAX = 100
# === Trivial init() helper ===
doc Trivial initialization helper for init(o, ...)
doc Sets object fields from the supplied parameters
doc %EX - # sets t.a and t.b
doc %EX - F init(t:MyType, a, b) init(args())
F init(h:Hash) {
args = Arr(h)
dst = args.shift()[1]
args.each(F(field_name_value) dst.(field_name_value[0]) = field_name_value[1])
dst
}
# === Exceptions ===
{
doc Represents failed asserttion, thrown by assert(). Should be used to catch programming errors.
doc %EXSYN - commands
doc %EX - F box_area(x:Int, y:Int) {
doc %EX - assert(x > 0)
doc %EX - assert(y > 0)
doc %EX - x * y
doc %EX - }
doc %EX - echo(box_area(5, 10))
doc %EX - # Output: 50
doc %EX - echo(box_area(-5, 10))
doc %EX - # ... Exception of type AssertFail ...
type AssertFail
AssertFail.inherit(Exception)
}
doc IndexNotFound exception constructor
doc %RET - IndexNotFound type instance with the given message, container and key attributes
F init(e:IndexNotFound, message:Str, container, key) init(args())
doc Throws AssertFail with givens message if condition is false
doc %RET - Unspecified, do not count on this value
F assert(condition:Bool, msg:Str) not(condition) throws AssertFail(msg)
doc Throws AssertFail if condition is false
doc %RET - Unspecified, do not count on this value
F assert(condition:Bool) assert(condition, "Assertion failed")
F assert(condition, *args) {
guard condition is not Bool
super(Bool(condition), *args)
}
# === Namespaces =================================
F '::'(nti:NormalTypeInstance, k) nti.(k)
F '::'(h:Hash, k) h[k]
F '::='(nti:NormalTypeInstance, k, v) nti.(k) = v
F '::='(h:Hash, k, v) h[k] = v
# === Return =====================================
doc Implements calling of Return type instances
doc like the finish(i) call in the example below
doc %EX - F first(r:Range, predicate:Fun) {
doc %EX - finish = Return()
doc %EX - r.each(F(i) {
doc %EX - predicate(i) throws finish(i)
doc %EX - })
doc %EX - null
doc %EX - }
F call(r:Return, v=null) {
r.val = v
r
}
# === Misc functional ============================
{
doc Parent type of all types that have each() method
type Eachable
doc Eachable which each() calls the callback with one argument
type Eachable1
Eachable1.inherit(Eachable)
doc Eachable which each() calls the callback with two arguments
type Eachable2
Eachable2.inherit(Eachable)
Int.inherit(Eachable1)
Arr.inherit(Eachable1)
Str.inherit(Eachable1)
# TODO: Consider Eachable2 subtype for Hash (as callback has 2 arguments)
Hash.inherit(Eachable2)
}
doc %RET - The given argument
F identity(x) x
TEST identity(10) == 10
# TODO: Add more info about the newly created function - useful for debugging
# See https://docs.python.org/2/library/functools.html#partial-objects
doc Returns partially-applied function
doc f - The base function
doc Xunderscore_unsupportedXbind_args - The arguments to partiall apply (bind the function to)
F partial(f:Fun, *bind_args)
F(*args) f(*bind_args, *args)
TEST p = partial((-), 10); p(7) == 3
doc Same as partial() but the bound arguments are last ones
F partial_tail(f:Fun, *bind_args)
F(*args) f(*args, *bind_args)
TEST p = partial_tail((-), 10); p(7) == -3
doc Sets the given attribute to the given value
doc %RET - The modified obj
doc %EX - s.len() != 1 throws InvalidArgument("ord() argument must be of length 1 exactly").set('given', s)
doc %EX - # Would else be written as
doc %EX - if s.len() != 1 {
doc %EX - e = InvalidArgument("ord() argument must be of length 1 exactly")
doc %EX - e.given = s
doc %EX - throw e
doc %EX - }
F set(obj, attr:Str, val) {
obj.(attr) = val
obj
}
doc Convert anything to a predicate.
doc anything - The value to compare to
doc %RET - A function that compares the only argument to the given value
F Pred(anything) F eq_pred(x) x == anything
doc Convert a function to predicate.
doc %RET - The given function, without any transformation
F Pred(f:Fun) f
doc Convert a type to a predicate.
doc t - A type
doc %RET - A function that checks whether the only argument is of type t
F Pred(t:Type) F is_pred(x) x is t
doc Map something to an Arr (array) of values using mapper.
doc something - Instance of any type that has each(something, callback) implemented
doc %RET - Arr
doc %EX - [1,2,3].map(X*4) # [4,8,12]
F map(something:Eachable, mapper:Fun)
collector
something.each(collect + mapper)
doc Transform mapper to handle only items matching predicate. Non-matching items will be returned as is.
doc %EX - ["abc", 1, "def", 2].map(only(Int, X*2)) # ["abc", 2, "def", 4]
F only(predicate, mapper:Fun) {
p = Pred(predicate)
F wrapped_in_only(elt) {
if p(elt) {
mapper(elt)
} else {
elt
}
}
}
TEST ["abc", 1, "def", 2].map(only(Int, X*2)) == ["abc", 2, "def", 4]
doc Filter something to an Arr (array) of values using predicate.
doc something - Instance of any type that has each(something, callback) implemented.
doc predicate - Decision function to be called with each item as first argument.
doc predicate - When predicate(item) returns true, the item will appear in the resulting array.
doc %EX - (1...10).filter(F(num) num % 2 == 0) # Gives [2,4,6,8,10]
doc %EX - (1...10).filter(X<5) # Gives [1,2,3,4], predicate called as predicate(item, 5)
doc %RET - Arr
F filter(something:Eachable1, predicate) {
p = Pred(predicate)
collector
something.each() do F(elt) {
if p(elt)
collect(elt)
}
}
{
type TheOneFail
TheOneFail.inherit(InvalidArgument)
}
doc Find the only element that satisfies the predicate.
doc Throws TheOneFail exception if there are no elements that satisfy the predicate or if there is more than one element that satisfies the predicate.
doc %RET - The only element that satisfies the predicate.
F the_one(something:Eachable1, predicate) {
p = Pred(predicate)
ret = EmptyBox()
something.each() do F(elt) {
if p(elt) {
ret throws TheOneFail("the_one() had more than one match")
ret = FullBox(elt)
}
}
not(ret) throws TheOneFail("the_one() had no matches")
ret.val
}
TEST [1,2,11,3,4].the_one(X>10) == 11
TEST try [1,2,11,12,4].the_one(X>10) catch(e:TheOneFail) true
TEST try [1,2,3,4].the_one(X>10) catch(e:TheOneFail) true
doc Find the only element that satisfies the predicate and execute given code with the value
doc body - The code to execute when exactly one element that satisfies the predicate was found. Executed with the found value. It's value will be returned as result of the_one().
doc found_more - The code to execute when more than one element satisfies the predicate. It's value will be returned as result of the_one(). Defaults to function returning null.
doc found_none - The code to execute when none of the elements satisfy the predicate. It's value will be returned as result of the_one(). Defaults to function returning null.
doc %RET - Result of running on of the following: body, found_more, found_none
doc %EX - F name(dn:MethodDocNode) {
doc %EX - dn.children.the_one(MethodNameDocNode).text[0]
doc %EX - }
F the_one(something:Eachable1, predicate, body:Fun, found_more:Fun={null}, found_none:Fun={null}) {
p = Pred(predicate)
ret = EmptyBox()
r = Return()
something.each(F(elt) {
if p(elt) {
if ret {
throw r(found_more())
}
ret = FullBox(elt)
}
})
if ret {
body(ret.get())
} else {
found_none()
}
}
TEST ok = false; [1,2,11,3,4].the_one(X>10, F(the_value) { if(the_value == 11) ok = true });
TEST ok = false; [1,2,11,3,4].the_one(X>20, { does_not_matter }, found_none = { ok = true }); ok
TEST ok = false; [1,2,11,3,4].the_one(Int, { does_not_matter }, found_more = { ok = true }); ok
doc Extract the only element.
doc Throws TheOneFail exception if there are no elements or if there is more than one element.
doc %RET - The only element.
doc %EX - ``aws ec2 describe-security-groups --group-ids $sg_id``.the_one() # {OwnerId=..., VpcId=..., GroupId=..., ...}
F the_one(something:Eachable1) something.the_one({true})
doc Filter nulls out.
doc DEPRECATED, USE something.without(null) INSTEAD.
doc something - Instance of any type that has each(something, callback) implemented
doc %RET - Arr (array) of original items without nulls
F filter(something:Eachable1) {
error("USING DEPRECATED filter(something)")
filter(something, X is not Null)
}
TEST [1,2,null,3].filter() == [1,2,3]
doc Filter something to an Arr (array) of values using predicate
doc predicate - Decision function to be called with each item as first argument.
doc predicate - When predicate(item) returns true, the item will not appear in the resulting array
doc something - Instance of any type that has each(something, callback) implemented
doc %EX - (1...10).reject(F(num) num % 2 == 0) # Gives [1,3,5,7,9]
doc %EX - (1...10).reject(X<5) # Gives [5,6,7,8,9,10], predicate called as predicate(item, 5)
doc %RET - Arr
F reject(something:Eachable, predicate) {
p = Pred(predicate)
something.filter(not + p)
}
doc EXPERIMENTAL! Do not use!
F take_while(something:Eachable1, predicate)
collector {
p = Pred(predicate)
r = Return()
something.each(F(elt) {
if p(elt)
collect(elt)
else
throw r()
})
}
TEST [1,2,3,1,2].take_while(X<3) == [1,2]
# Would look much better with an iterator of "something"
doc EXPERIMENTAL! Do not use!
F drop_while(something:Eachable1, predicate)
collector {
p = Pred(predicate)
found = false
something.each(F(elt) {
if found { collect(elt); return null; }
if not(p(elt)) {
collect(elt)
found = true
}
})
}
TEST [1,2,3,1,2].drop_while(X<3) == [3,1,2]
doc Replace all occurrences of src with dst
doc something - Instance of any type that has each(something, callback) implemented
doc %RET - Arr
doc %EX - ["ssh", "IP", "w"].replace("IP", "10.0.0.100") # ['ssh','10.0.0.100','w']
F replace(something:Eachable1, src, dst) map(something, only(X == src, {dst}))
TEST ["ssh", "IP", "w"].replace("IP", "10.0.0.100") == ['ssh','10.0.0.100','w']
doc Combine items to a single value using the supplied binary function
doc First f is applied to start and the first element of something
doc then on each step f is applied to previous result and next element
doc of something.
doc start - First argument of f, for the first call of f
doc something - Instance of any type that has each(something, callback) implemented
doc f - The combining function
doc %EX - F sum(something) something.reduce(0, (+))
F reduce(something:Eachable1, start, f:Fun) {
ret = start
something.each(F(elt) ret = f(ret, elt))
ret
}
TEST [1,2,3].reduce(0, (+)) == 6
doc EXPERIMENTAL!
doc Map when there is more than one element. If there is exactly one element, it's left as is
doc mapper - Will be called with zero based index and successive elements from arr
doc %RET - Arr
F map_base_idx(base, n:Int, mapper:Fun) {
n == 1 returns [base]
n.map(mapper(base, X))
}
doc EXPERIMENTAL! Do not use!
doc Map val only when val is true in boolean context. Otherwise return the original val.
F map_true(val, mapper:Fun) only(identity, mapper)(val)
TEST [].map_true(["--filters"] + X) == []
TEST ["something"].map_true(["--filters"] + X) == ["--filters", "something"]
doc EXPERIMENTAL! Do not use!
doc Map val only when val is false in boolean context. Otherwise return the original val.
F map_false(val, mapper:Fun) only(not + identity, mapper)(val)
TEST [].map_false({ ["default"] }) == ["default"]
TEST ["something"].map_false({ ["default"] }) == ["something"]
doc Call cb with val
doc %RET - val
doc %EX - h.mapv(only(Pfx, { "${A.val}*" })).map("Name=$X,Values=$Y").tap(F(x) echo("DEBUG: $x")).map_true(['--filters'] + X)
F tap(val, cb:Fun) {
cb(val)
val
}
TEST ok=false; (7.tap({ if A == 7 ok = true}) == 7) and ok
doc Filter operator.
doc Same as calling x.filter(predicate)
doc %EX - [1,2,3,4] ? F(x) x > 2 # [3,4]
F ?(x, predicate:Fun) x.filter(predicate)
doc Map operator.
doc Same as calling x.map(mapper)
doc %EX - [1,2,3,4] / F(x) x * 10
F /(x, mapper:Fun) x.map(mapper)
doc Each operator.
doc Same as calling x.each(cb)
doc %EX - [1,2,3,4] % echo
F %(x, cb:Fun) x.each(cb)
doc Call operator.
doc Same as calling f(x)
doc %EX - [1,2,3,4] \ echo
F \(x, f:Fun) f(x)
# === ArrLike ====================================
{
doc Parent type for user-defined types with array-like behaviour. Use in cases when you would like to inherit from built-in Arr. Inheriting from built-ins is not possible for now.
doc arr_like_attr - name of the attribute that holds the underlying array, defaults to "items"
doc items - default attribute for the underlying array
doc %EX - type T(ArrLike)
doc %EX - F Str(t:T) "<My array has ${len(t)} items totalling ${sum(t)}>" # Override one of the Arr methods
doc %EX - a = T()
doc %EX - a.push(10)
doc %EX - a.push(20)
doc %EX - echo(a) # <My array has 2 items totalling 30>
doc %EX -
doc %EX - # If you need init() you should have something like the following to allow ArrLike initialization:
doc %EX - init(t:T) {
doc %EX - super(t)
doc %EX - ...
doc %EX - }
type ArrLike
ArrLike.inherit(Eachable1)
}
doc ArrLike constructor
doc attr - name of the attribute that holds the underlying array
F init(al:ArrLike, attr:Str='items') {
al.arr_like_attr = attr
al.(al.arr_like_attr) = []
}
doc Get length of the underlying array.
F len(al:ArrLike) al.(al.arr_like_attr).len()
doc Set element in the underlying array.
F '[]'(al:ArrLike, idx:Int) al.(al.arr_like_attr)[idx]
doc Get element from the underlying array.
F '[]='(al:ArrLike, idx:Int, x) al.(al.arr_like_attr)[idx] = x
doc Call cb for each element in the underlying array.
F each(al:ArrLike, cb:Fun) al.(al.arr_like_attr).each(cb)
doc Call Bool() on the underlying array.
F Bool(al:ArrLike) al.(al.arr_like_attr).Bool()
doc Push an element to the underlying array.
F push(al:ArrLike, val) al.(al.arr_like_attr).push(val)
# === HashLike ===================================
{
type HashLike
HashLike.inherit(Eachable2)
}
F in(name:Str, hl:HashLike) name in hl.attrs().HashLike
F len(hl:HashLike) hl.attrs().HashLike.len()
F '[]' (hl:HashLike, k) hl.attrs().HashLike[k]
F '[]='(hl:HashLike, k, v) hl.attrs().HashLike[k] = v
F .(hl:HashLike, k) hl.attrs().HashLike[k]
F .=(hl:HashLike, k, v) hl.attrs().HashLike[k] = v
F get(hl:HashLike, k, dflt) hl.attrs().HashLike.get(k, dflt)
F get(hl:HashLike, k) hl.get(k, null)
F each(hl:HashLike, cb:Fun) hl.attrs().HashLike.each(cb)
F keys(hl:HashLike) hl.attrs().HashLike.keys()
F values(hl:HashLike) hl.attrs().HashLike.values()
F Bool(hl:HashLike) hl.attrs().HashLike.Bool()
# TODO: mapk, mapv and friends
# TOOD: Hash() - copy or hash attribute?
F filter(hl:HashLike, cb:Fun) {
ret = HashLike()
ret.attrs().HashLike = hl.attrs().HashLike.filter(cb)
ret
}
F init(hl:HashLike, h:Hash=null) {
if hl.attrs() is not Hash {
hl.attrs({})
}
hl.attrs().HashLike = h or {}
}
doc Get the underlying Hash with all the keys/values of the HashLike.
doc Note: the returned value is not a copy.
doc %RET - Hash
F Hash(hl:HashLike) hl.attrs().HashLike
# === Hook =======================================
{
doc Hook is a simple pub-sub
type Hook
Hook.inherit(HashLike)
}
doc Hook constructor.
doc %RET - Hook
F init(hook:Hook) {
super(hook)
hook.attrs().idx = 0
}
doc Add unnamed handler.
doc The hook is automatically named "pushed-N" where N is sequential integer.
doc %RET - New hook name
F push(hook:Hook, handler:Closure) {
name = "pushed-${hook.attrs().idx}"
hook.attrs().idx += 1
hook[name] = handler
name
}
# TODO: consider optional? try/catch isolation
doc Runs all handlers passing all args.
doc args - Arguments to pass to handlers
doc %RET - Output of the combiner function applied to all handlers' results
F call(hook:Hook, *args) hook.attrs().HashLike.mapv(X(*args))
# === Real =======================================
# TODO: something more efficient
doc Convert a string to real (floating) number, inefficiently
doc %RET - Real
doc %EX - Real("1.1") # 1.1
F Real(s:Str) {
parts = s.split('.')
parts.len() == 1 returns Real(Int(parts[0]))
parts.len() != 2 throws InvalidArgument("Invalid argument ${s}")
l = parts[1].len()
frac = Real(Int(parts[1]))
for(i;l) frac = frac / 10.0
Real(Int(parts[0])) + frac
}
TEST Real('1.1') == 1.1
# === Fun helpers ================================
doc TODO: Defaut values
F StrParams(f:Fun) {
guard f is Closure or f is NativeMethod
f.params().map(F(p) {
"${p.name}:${p.type.name}"
}).join(', ') \ "($X)"
}
# === NativeMethod ===============================
doc String representation of native method.
doc %RET - "<Native method NAME>"
doc %EX - (%)[0].Str().echo() # Outputs: <Native method %>
F Str(c:NativeMethod) "<Native method ${c.attrs().name}${StrParams(c)}>"
# === Closure ====================================
# TODO: show arguments:
# "<Closure ${c.attrs().name tor "<anonymous>"}(HERE) at ${location}>"
doc String representation of a closure
doc %RET - Str
doc %EX - Real.constructors[-1].Str().echo() # Outputs: <Closure Real at /usr/share/ngs/stdlib.ngs:350>
F Str(c:Closure) {
info = c.ip().resolve_instruction_pointer()
location = "${info.file}:${info.first_line}" tor "<unknown location>"
"<Closure ${c.attrs().name tor "<anonymous>"}${StrParams(c)} at ${location}>"
}
# === Type =======================================
doc Type constructor
doc %EX - type MyType1
doc %EX - type MyType2(MyType1)
F Type(t:Str, doc, parent:Type) Type(t, doc, [parent])
doc Type constructor
doc %EX - type MyType1
doc %EX - type MyType2
doc %EX - type MyType3([MyType1, MyType2])
F Type(t:Str, doc, parents:Arr) {
ret = Type(t, doc)
parents % ret.inherit(X)
ret
}
TEST type T1; type T2(T1); T2() is T1
doc Match a type. Same as "something is t".
doc %EX - 1 ~ Int # true
doc %EX - "a" ~ Int # false
F ~(something, t:Type) something is t
doc String representation of a type
doc %RET - "<Type NAME>"
doc %EX - Real.Str().echo() # Outputs: <Type Real>
F Str(t:Type) "<Type ${t.name}>"
# === NormalType =================================
doc String representation of normal type instance i
doc Normal type is a user defined type. In addition some types defined by NGS are also normal types.
doc %EX - {
doc %EX - type T
doc %EX - # nti - Normal type instance
doc %EX - nti = T()
doc %EX - nti.a = 1
doc %EX - nti.b = 2
doc %EX - echo(Str(nti)) # <T a=1 b=2>
doc %EX - }
doc %RET - "<TYPE_NAME attr1=val1 attr2=val2 ...>"
F Str(i:NormalTypeInstance) {
h = Hash(i)
truncated = len(h) > 10
if truncated {
h .= limit(10)
}
# TODO limit key and value lengths
h .= Strs()
attrs = h.join(' ').map_true(' ' + X)
"<${i.typeof().name}${attrs}${if truncated ' ...' else ''}>"
}
doc Set an attribute in an instance if it's not already set
doc %EX - mysomething.dflt(k, []).push(elt)
doc %RET - Attribute value, the already-existed or new.
F dflt(i:NormalTypeInstance, k, v) {
if k not in i {
i.(k) = v
}
i.(k)
}
TEST type T; t=T(); t.dflt("a", 1); t.a == 1
TEST type T; t=T(); t.a = 2; t.dflt("a", 1); t.a == 2
doc Set an attribute on instances if it's not already set
doc %RET - v
F dflt(arr:Arr, k, v) {
guard arr.all({A is NormalTypeInstance or A is Hash})
arr.each(X.dflt(k, v))
v
}
doc Equaity test for normal type instances: must be of same type and have same attributes and their values
doc %RET - Bool
doc %EX - type T
doc %EX - t1 = T()
doc %EX - t1.a = 1
doc %EX - t2 = T()
doc %EX - t2.a = 1
doc %EX - echo(t1 == t2) # Outputs: true
F ==(a:NormalTypeInstance, b:NormalTypeInstance) {
typeof(a) != typeof(b) returns false
Hash(a) == Hash(b)
}
# TODO: move to somewhere more appropriate, keep in mind - must be after dflt(NormalTypeInstance, ...)
F dflt(hl:HashLike, k, v) hl.attrs().HashLike.dflt(k, v)
# === Exceptions =================================
{
# TODO: Investigate why type CException(Error) does not work at this point
doc Base type for exceptions arising from errors returned by calling C functions
type CException
CException.inherit(Error)
doc CException constructor. In addition to storing message attribute, adds errno and errno_name attributes.
F init(e:CException, message:Str) {
errno = get_c_errno()
super(e, message)
e.errno = errno
e.errno_name = c_strerror(e.errno)
}
doc Exception representing a failure to kill() a process
type KillFail
KillFail.inherit(CException)
}
# === auto-load ==================================
doc Called when reading undefined global.
doc Implements autoloading.
doc Searches in $NGS_DIR/autoload/NAME.ngs
doc WARNING: May have security implications when looking up a name from untrusted source.
doc %EX - test("My web server runs") do { .... } # $NGS_DIR/autoload/test.ngs is automatically loaded.
F global_not_found_handler(name:Str) {
val = require("${NGS_DIR}/autoload/${name}.ngs")
idx = resolve_global_variable(name)
if not(is_global_variable_defined(idx)) {
# echo("IDX $name $idx")
set_global_variable(idx, val)
}
}
# === Range ======================================
{ Range.inherit(Eachable1) }
doc Range constructor
F init(r:Range, start, end, step=1) init(args())
doc ExclusiveRange constructor
F ..(start, end) ExclusiveRange(start, end)
doc InclusiveRange constructor
F ...(start, end) InclusiveRange(start, end)
doc Iterates over the elements of r, passing each in turn to cb.
doc cb - Function to be called with values from r
doc args - Additional arguments for calling cb
doc %RET - r
doc %EX - s=0
doc %EX - (1...10).each(F(i) { global s; s+=i })
doc %EX - echo(s) # Outputs: 55
F each(r:Range, cb:Fun) {
# TODO: support Real step
econd {
(r.end is Null) or (r.step == 0) {
cmp = F(a,b) true
}
r.step > 0 {
cmp = if r is ExclusiveRange (<) (<=)
}
r.step < 0 {
cmp = if r is ExclusiveRange (>) (>=)
}
}
for(i=r.start; cmp(i, r.end); i=i+r.step)
cb(i)
r
}
TEST (1..3).map(X*2) == [2, 4]
TEST (1...3).map(X*2) == [2, 4, 6]
doc Find first element in r that satisfies the predicate.
doc args - Additional arguments for calling the predicate.
doc The predicate is called with each one of the elements plus the args: predicate(i)
doc %RET - Either the element or null if element was not found.
doc %EX - (10..20).first(F(x) x % 3 == 0) # 12 - first item divisible by 3
F first(r:Range, predicate:Fun) {
finish = Return()
r.each(F(i) {
predicate(i) throws finish(i)
})
null
}
TEST (10..20).first(F(x) x % 3 == 0) == 12
doc TODO
F Str(r:ExclusiveRange) "<ExclusiveRange ${r.start}..${r.end} step ${r.step}>"
doc TODO
F Str(r:InclusiveRange) "<InclusiveRange ${r.start}...${r.end} step ${r.step}>"
# === Syntactic sugar ============================
doc Boolean negation for non-boolean values. Converts to boolean first.
doc %RET - Bool
F not(x) { guard (x is Bool) == false; x.Bool().not() }
doc Inequality operator
doc %EX - 1 !=2 # true, same as not(1==2)
F !=(a,b) not(a==b)
doc Non-sameness operator
doc %EX - h1 = {"a": 1}
doc %EX - h2 = {"a": 1}
doc %EX - h1 !== h2 # true, same as not(h1===h2)
doc %EX - h1 == h2 # true
F !==(a,b) not(a===b)
TEST 1 != 2
TEST (1 != 1) == false
TEST 1 !== 2
TEST (1 !== 1) == false
doc "not in" operator. Exactly same as "not(a in b)"
doc %EX - 10 not in [1,2] # true
doc %EX - 1 not in [1,2] # false
F 'not in'(a,b) not(a in b)
TEST (1 not in [1,2,3]) == false
TEST 10 not in [1,2,3]
doc "is not" operator. Exactly same as "not(a is b)".
doc %EX - 1 is not Null # true
doc %EX - null is not Null # false
F 'is not'(a,b) not(a is b)
TEST 1 is not Null
TEST (null is not Null) == false
doc Exactly same as "element in container". It's just more convenient in specific cases.
doc %EX - [1,2,3].has(2) # true
doc %EX - [[1,2,3], [1,20,30], [100,200,300]].filter(X.has(1)) # [ [1,2,3], [1,20,30] ]
doc %RET - Bool
F has(container, element) element in container
TEST [1,2,3].has(1)
TEST [1,2,3].has(10).not()
doc Defines collector { ... collect(...) ... } behaviour for arrays
doc a - Initial array
doc body - The body after collector keyword and possible initial value, wrapped in a function
doc body - "collector THIS_CODE" or "collector/my_init THIS_CODE"
doc %RET - Constructed array
doc %EX - items = collector {
doc %EX - collect(10)
doc %EX - for(i;2) collect(i)
doc %EX - collect(20)
doc %EX - }
doc %EX - echo(items) # Outputs: [10,0,1,20]
doc %EX -
doc %EX - # Or start with few items:
doc %EX - items = collector/[100,200] {
doc %EX - collect(10)
doc %EX - for(i;2) collect(i)
doc %EX - collect(20)
doc %EX - }
doc %EX - echo(items) # Outputs: [100,200,10,0,1,20]
F collector(a:Arr, body:Fun) {
body(F(elt) a.push(elt))
a
}
doc Defines collector { ... collect(...) ... } behaviour for hashes
doc h - Initial hash
doc body - The body after collector keyword and initial value, wrapped in a function
doc body - "collector/{'my': 'hash'} THIS_CODE"
doc %RET - Constructed array
doc %EX - arr = [{"Name": "n1", "Value": "v1"},{"Name": "n2", "Value": "v2"}]
doc %EX - my_hash = collector/{}
doc %EX - arr.each(F(elt) collect(elt.Name, elt.Value))
doc %EX - echo(my_hash) # Outputs: {n1=v1, n2=v2}
F collector(h:Hash, body:Fun) {
body(F(k, v) h[k] = v)
h
}
doc Defines collector { ... collect(...) ... } behaviour for integers (summarizes collected items).
doc n - Initial number
doc body - The body after collector keyword and initial value, wrapped in a function
doc body - "collector/100 THIS_CODE"
doc %RET - Constructed array
doc %EX - collector/0 { (1...10).each(collect) } # 55
F collector(n:Int, body:Fun) {
body(F(incr) n=n+incr)
n
}
doc Comparison to null
doc %RET - false
F ==(a:Null, b) false
doc Comparison to null
doc %RET - false
F ==(a, b:Null) false
doc Comparison to null
doc %RET - true
F ==(a:Null, b:Null) true
doc Run cleanup after successful execution of body or exception in body
doc body - Main code to execute
doc cleanup - Cleanup code to execute
doc TODO: make sure cleanup() is not run twice in case of exception in cleanup() itself
doc %EX - finally(
doc %EX - { while entry = c_readdir(d) { ... } },
doc %EX - { ... c_closedir(d) ...}
doc %EX - )
doc %RET - Whatever body call returns
F finally(body:Fun, cleanup:Fun) {
try {
ret = body()
cleanup()
ret
} catch(e) {
cleanup()
throw e
}
}
TEST a=0; {1/1}.finally({a=10}) == 1 and a == 10
TEST a=0; (try finally() with {1/0} with {a=10} catch(e:DivisionByZero) "OK") == "OK" and a == 10
# --- Hash ---
doc Get hash key.
doc %EX - h = {"a": 1}
doc %EX - h.a # 1, Same as h["a"]
F .(h:Hash, attr:Str) h[attr]
doc Set hash key.
doc %EX - h = {"a": 1}
doc %EX - h.a = 2 # 2, Same as h["a"] = 2
doc %RET - v
F .=(h:Hash, attr:Str, v) h[attr] = v
doc Get hash value by key or null if it does not exist
doc %EX - h = {"a": 1}
doc %EX - h.get("a") # 1
doc %EX - h.get("b") # null
F get(h:Hash, k) get(h, k, null)
doc Convert hash values to integers where possible
doc %RET - New Hash
doc %EX - %{k 7 kk "a"}["k"] is Str # true
doc %EX - %{k 7 kk "a"}.n() # {'k': 7, 'kk': 'a'}
doc %EX - %{k 7 kk "a"}.n()["k"] is Int # true
F n(h:Hash) h.mapv({Int(A) tor A})
TEST %{k 7 kk "a"}.n() == {'k': 7, 'kk': 'a'}
# --- Arr ---
doc Return array made of given attribute of each element of given array
doc %EX - [{"x": 1}, {"x": 2}].x # [1, 2]
doc %RET - Arr
F .(a:Arr, attr:Str) a.map(X.(attr))
TEST [{"x": 1}, {"x": 2}].x == [1, 2]
doc Return array made of given attribute of each element of given Eachable1 where present
doc %EX - [{"x": 1}, {"y": 2}].get("x") # [1]
doc %EX - ``aws ec2 describe-instances``.Tags.get("role").uniq()
doc %EX - # Returns Arr of Str with roles. Does not crash if some machines do not have "role" tag.
doc %RET - Arr
F get(e:Eachable1, attr:Str)
collector
e.each(F(item) {
try collect(item.(attr))
})
doc Return array made of given attribute of each element of given Eachable1 where present or default value where the attribute is not present
doc Return array (? depends on map() ?) made of given attribute of each element of given Eachable1
doc %EX - [{"x": 1}, {"y": 2}].get("x", null) # [1, null]
doc %RET - Arr
F get(e:Eachable1, attr:Str, dflt) e.map(X.get(attr, dflt))
doc Concatenate strings
doc %EX - "ab" + "cd" # "abcd"
doc %RET - New Str
F +(s1:Str, s2:Str) "${s1}${s2}"
TEST "ab" + "cd" == "abcd"
# === Array ======================================
doc Checks whether element x is in array arr
doc x - Needle
doc arr - Haystack
doc %EX - 1 in [1,2,3] # true
doc %EX - 10 in [1,2,3] # false
doc %RET - Bool
F in(x, arr:Arr) {
l = arr.len()
for(i;l) arr[i] == x returns true
false
}
# Tested by has() tests
doc Arrays equality test.
doc True if arrays are of the same length and all elements are equal (==)
doc %RET - Bool
F ==(a:Arr, b:Arr) {
l = a.len()
l != b.len() returns false
for(i;l) a[i] != b[i] returns false
true
}
TEST [1, 2] == [1, 2]
TEST [1, 3] != [1, 2]
TEST [1] != [1, 2]
doc Check whether there is any element in arr that satisfies the given predicate.
doc TODO: Make it work on anything with Eachable2 too.
doc e - The items to check
doc predicate - Test function
doc args - Additional arguments for calling the predicate.
doc %EX - [1,2,10].any(F(elt) elt > 5) # true
doc %EX - [1,2,10].any(F(elt) elt > 15) # false
doc %RET - Bool
F any(e:Eachable1, predicate) {
p = Pred(predicate)
r = Return()
e.each(F(x) {
p(x) throws r(true)
})
false
}
TEST [1,2,10].any(F(elt) elt > 5)
TEST [1,2,3].any(F(elt) elt > 5).not()
doc Check whether all elements in arr satisfy the given predicate.
doc e - The items to check
doc predicate - Test function
doc args - Additional arguments for calling the predicate.
doc %RET - Bool
doc %EX - [1,2,3].all(X<10) # true