-
Notifications
You must be signed in to change notification settings - Fork 1
/
tMatching.nim
3045 lines (2371 loc) · 71.3 KB
/
tMatching.nim
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
import
std/[
strutils,
sequtils,
strformat,
sugar,
pegs,
macros,
options,
tables,
json
]
import hmisc/macros/matching
{.experimental: "caseStmtMacros".}
{.push hint[XDeclaredButNotUsed]: off.}
{.push hint[ConvFromXtoItselfNotNeeded]: off.}
{.push hint[CondTrue]: off.}
import hmisc/preludes/unittest
template testFail(str: string = ""): untyped =
doAssert false #, "Fail on " & $instantiationInfo() & ": " & str
template t(body: untyped): untyped =
block:
parseMatchExpr(
n = (
quote do:
body
)
)
template assertEq(a, b: untyped): untyped = check(a == b)
suite "Issue tests":
test "Duplicated unpacking":
[all [@head < 10, _]] := @[[1, 2], [3, 4], [5, 6]]
doAssert head.len == 3
macro sumt(arg: untyped): untyped =
Asgn[@name is Ident(), Call[_, [all @typeFields]]] := arg[0]
[all Call[@names is Ident(), _]] := typeFields
doAssert names.len == 3
sumt:
Name = sumtype:
Kind1(string)
Kind2(float)
Kind3(char)
test "`matching` bug with `{orc,arc}` #76":
# Compilation failed with `--gc:orc` enabled
macro parseTests(): untyped =
let patt = t O2(o2:Some(@mystring))
doAssert patt.kind == kObject
doAssert patt.kindCall.get() == ident("O2")
parseTests()
type
OKind = enum O1 O2
O = object
case kind: OKind
of O1: o1: int
of O2: o2: Option[string]
var str = "default"
case O(kind:O2,o2:some[string]("hello world")):
of O2(o2:Some(@mystring)): str = mystring
doAssert str == "hello world"
test "Support qualified variant selectors with matching? #83":
type
ZKind = enum Z1
Z = object
case kind: ZKind
of Z1:
o1: int
case Z(kind: Z1, o1: 1):
of ZKind.Z1(o1: @i):
doAssert i == 1
test "Compiler crashes when else match NimNode #98":
# https://github.com/nim-lang/fusion/issues/98
#
# Compiler crash was caused by depleted case - single `else` branch for
# case generated `IfStmt[Else[StmtList[]]]` node that is not valid.
# This caused compiler crash due to lack of bound check somewhere in
# the compiler body, I'm not sure what exactly.
macro m() =
case newLit(0):
else:
discard
m()
suite "Matching":
test "Pattern parser tests":
macro main(): untyped =
doAssert (t true).kind == kItem
block:
let s = t [1, 2, all @b, @a]
doAssert s.seqElements[3].bindVar == some(ident("a"))
doAssert s.seqElements[2].bindVar == some(ident("b"))
doAssert s.seqElements[2].pattern.bindVar == none(NimNode)
discard t([1,2,3,4])
discard t((1,2))
discard t((@a | @b))
discard t((a: 12, b: 2))
# dumpTree: [(0 .. 3) @patt is JString()]
# dumpTree: [0..3 @patt is JString()]
discard t([(0 .. 3) @patt is JString()])
discard t([0..3 @patt is JString()])
let node = quote: (12 .. 33)
block:
case node:
of Par [_]:
discard
else:
raiseAssert("#[ IMPLEMENT ]#")
case node:
of Par[_]:
discard
else:
raiseAssert("#[ IMPLEMENT ]#")
block:
node.assertMatch(Par [_] | Par [_])
node.assertMatch(Par[Infix()])
node.assertMatch(Par [Infix()])
node.assertMatch(Par[Infix ()])
node.assertMatch(Par [Infix ()])
node.assertMatch(Par [Infix ()])
block:
[
Par [Infix [_, @lhs, @rhs]] |
Command [Infix [_, @lhs, @rhs]] |
Infix [@infixId, @lhs, @rhs]
] := node
doAssert lhs is NimNode
doAssert rhs is NimNode
doAssert infixId is Option[NimNode]
doAssert lhs == newLit(12)
doAssert rhs == newLit(33)
block:
discard node.matches(
Call[
BracketExpr[@ident, opt @outType],
@body
] |
Command[
@ident is Ident(),
Bracket[@outType],
@body
]
)
doAssert body is NimNode, $typeof(body)
doAssert ident is NimNode, $typeof(ident)
doAssert outType is Option[NimNode]
block:
case node:
of Call[BracketExpr[@ident, opt @outType], @body] |
Command[@ident is Ident(), Bracket [@outType], @body]
:
static:
doAssert ident is NimNode, $typeof(ident)
doAssert body is NimNode, $typeof(body)
doAssert outType is Option[NimNode], $typeof(outType)
of Call[@head is Ident(), @body]:
static:
doAssert head is NimNode
doAssert body is NimNode
main()
test "Pattern parser broken brackets":
block: JArray[@a, @b] := %*[1, 3]
block: (JArray [@a, @b]) := %*[1, 3]
block: (JArray [@a, @b is JString()]) := %[%1, %"hello"]
block: (JArray [@a, @b is JString ()]) := %[%1, %"hello"]
block: (JArray [
@a, @b is JString (getStr: "hello")]) := %[%1, %"hello"]
block:
let vals = @[
%*[["AA", "BB"], "CC"],
%*["AA", ["BB"], "CC"]
]
template testTypes() {.dirty.} =
doAssert aa is JsonNode
doAssert bb is Option[JsonNode]
doAssert cc is JsonNode
doAssert aa == %"AA"
if Some(@bb) ?= bb: doAssert bb == %"BB"
doAssert cc == %"CC"
for val in vals:
case val:
of JArray[JArray[@aa, opt @bb], @cc] |
JArray[@aa, JArray[@bb], @cc]
:
testTypes()
else:
testFail($val)
block:
val.assertMatch(
JArray[JArray[@aa, opt @bb], @cc] |
JArray[@aa, JArray[@bb], @cc]
)
testTypes()
block:
val.assertMatch:
JArray[JArray[@aa, opt @bb], @cc] |
JArray[@aa, JArray[@bb], @cc]
testTypes()
block:
val.assertMatch:
JArray [ JArray [@aa, opt @bb] , @cc] |
JArray [@aa, JArray [@bb], @cc]
testTypes()
block:
val.assertMatch:
JArray [
JArray [
@aa,
opt @bb
] ,
@cc
] |
JArray [@aa, JArray [
@bb], @cc]
testTypes()
test "Simple uses":
case (12, 24):
of (_, 24):
discard
else:
raiseAssert("#[ not possible ]#")
case [1]:
of [_]: discard
case [1,2,3,4]:
of [_]: testFail()
of [_, 2, 3, _]:
discard
case (1, 2):
of (3, 4), (1, 2):
discard
else:
testFail()
check "hehe" == (
case (true, false):
of (true, _): "hehe"
else: "2222"
)
doAssert (a: 12) ?= (a: 12)
check "hello world" == (
case (a: 12, b: 12):
of (a: 12, b: 22): "nice"
of (a: 12, b: _): "hello world"
else: "default value"
)
doAssert (a: 22, b: 90) ?= (a: 22, b: 90)
block:
var res: string
case (a: 22, b: 90):
of (b: 91):
res = "900999"
elif "some other" == "check":
res = "rly?"
elif true:
res = "default fallback"
else:
raiseAssert("#[ not possible ! ]#")
check res == "default fallback"
check "000" == (
case %{"hello" : %"world"}:
of {"999": _}: "nice"
of {"hello": _}: "000"
else: "discard"
)
check 1 == (
case [(1, 3), (3, 4)]:
of [(1, _), _]: 1
else: 999
)
check 2 == (
case (true, false):
of (true, true) | (false, false): 3
else: 2
)
test "Len test":
macro e(body: untyped): untyped =
case body:
of Bracket([Bracket(len: in {1 .. 3})]):
newLit("Nested bracket !")
of Bracket(len: in {3 .. 6}):
newLit(body.toStrLit().strVal() & " matched")
else:
newLit("not matched")
discard e([2,3,4])
discard e([[1, 3, 4]])
discard e([3, 4])
test "Regular objects":
type
A1 = object
f1: int
case A1(f1: 12):
of (f1: 12):
discard "> 10"
else:
testFail()
check 10 == (
case A1(f1: 90):
of (f1: 20): 80
else: 10
)
test "Private fields":
type
A2 = object
hidden: float
func public(a: A2): string = $a.hidden
case A2():
of (public: _):
discard
else:
testFail()
case A2(hidden: 8.0):
of (public: "8.0"): discard
else: testFail()
type
En2 = enum
enEE
enEE1
enZZ
Obj2 = object
case kind: En2
of enEE, enEE1:
eee: seq[Obj2]
of enZZ:
fl: int
test "Case objects":
case Obj2():
of EE():
discard
of ZZ():
testFail()
case Obj2():
of (kind: in {enEE, enZZ}): discard
else:
testFail()
when false: # FIXME
const eKinds = {enEE, enEE1}
case Obj2():
of (kind: in {enEE} + eKinds): discard
else:
testFail()
case (c: (a: 12)):
of (c: (a: _)): discard
else: testFail()
case [(a: 12, b: 3)]:
of [(a: 12, b: 22)]: testFail()
of [(a: _, b: _)]: discard
case (c: [3, 3, 4]):
of (c: [_, _, _]): discard
of (c: _): testFail()
case (c: [(a: [1, 3])]):
of (c: [(a: [_])]): testFail()
else: discard
case (c: [(a: [1, 3]), (a: [1, 4])]):
of (c: [(a: [_]), _]): testFail()
else:
discard
case Obj2(kind: enEE, eee: @[Obj2(kind: enZZ, fl: 12)]):
of enEE(eee: [(kind: enZZ, fl: 12)]):
discard
else:
testFail()
case Obj2():
of enEE():
discard
of enZZ():
testFail()
else:
testFail()
case Obj2():
of (kind: in {enEE, enEE1}):
discard
else:
testFail()
func len(o: Obj2): int = o.eee.len
iterator items(o: Obj2): Obj2 =
for item in o.eee:
yield item
test "Object items":
case Obj2(kind: enEE, eee: @[Obj2(), Obj2()]):
of [_, _]:
discard
else:
testFail()
case Obj2(kind: enEE, eee: @[Obj2(), Obj2()]):
of EE(eee: [_, _, _]): testFail()
of EE(eee: [_, _]): discard
else: testFail()
case Obj2(kind: enEE1, eee: @[Obj2(), Obj2()]):
of EE([_, _]):
testFail()
of EE1([_, _, _]):
testFail()
of EE1([_, _]):
discard
else:
testFail()
test "Variable binding":
when false: # NOTE compilation error test
case (1, 2):
of ($a, $a, $a, $a):
discard
else:
testFail()
check "122" == (
case (a: 12, b: 2):
of (a: @a, b: @b): $a & $b
else: "✠ ♰ ♱ ☩ ☦ ☨ ☧ ⁜ ☥"
)
check 12 == (
case (a: 2, b: 10):
of (a: @a, b: @b): a + b
else: 89
)
check 1 == (
case (1, (3, 4, ("e", (9, 2)))):
of (@a, _): a
of (_, (@a, @b, _)): a + b
of (_, (_, _, (_, (@c, @d)))): c * d
else: 12
)
proc tupleOpen(a: (bool, int)): int =
case a:
of (true, @capture): capture
else: -90
check 12 == tupleOpen((true, 12))
test "Infix":
macro a(): untyped =
case newPar(ident "1", ident "2"):
of Par([@ident1, @ident2]):
doAssert ident1.strVal == "1"
doAssert ident2.strVal == "2"
else:
doAssert false
a()
test "Iflet 2":
macro ifLet2(head: untyped, body: untyped): untyped =
case head[0]:
of Asgn([@lhs is Ident(), @rhs]):
result = quote do:
let expr = `rhs`
if expr.isSome():
let `lhs` = expr.get()
`body`
else:
head[0].expectKind({nnkAsgn})
head[0][0].expectKind({nnkIdent})
error("Expected assgn expression", head[0])
ifLet2 (nice = some(69)):
doAssert nice == 69
when (NimMajor, NimMinor, NimPatch) >= (1, 2, 0):
test "min":
macro min1(args: varargs[untyped]): untyped =
let tmp = genSym(nskVar, "minResult")
result = makeTree(NimNode):
StmtList:
VarSection:
IdentDefs:
== tmp
Empty()
== args[0]
IfStmt:
== (block:
collect(newSeq):
for arg in args[1 .. ^1]:
makeTree(NimNode):
ElifBranch:
Infix[== ident("<"), @arg, @tmp]
Asgn [@tmp, @arg]
)
== tmp
macro min2(args: varargs[untyped]): untyped =
let tmp = genSym(nskVar, "minResult")
result = makeTree(NimNode):
StmtList:
VarSection:
IdentDefs:
==tmp
Empty()
==args[0]
IfStmt:
all == (
block:
collect(newSeq):
for i in 1 ..< args.len:
makeTree(NimNode):
ElifBranch:
Infix[== ident("<"), ==args[i], ==tmp]
Asgn [== tmp, ==args[i]]
)
== tmp
doAssert min1("a", "b", "c", "d") == "a"
doAssert min2("a", "b", "c", "d") == "a"
test "Alternative":
check "matched" == (
case (a: 12, c: 90):
of (a: 12 | 90, c: _): "matched"
else: "not matched"
)
check 12 == (
case (a: 9):
of (a: 9 | 12): 12
else: 666
)
test "Set":
case [3]:
of [{2, 3}]: discard
else: testFail()
[{'a' .. 'z'}, {' ', '*'}] := "z "
"hello".assertMatch([all @ident in {'a' .. 'z'}])
"hello:".assertMatch([pref in {'a' .. 'z'}, opt {':', '-'}])
test "Match assertions":
[1,2,3].assertMatch([all @res])
check res == @[1,2,3]
[1,2,3].assertMatch([all @res2])
check res2 == @[1,2,3]
[1,2,3].assertMatch([@first, all @other])
check first == 1
check other == @[2, 3]
block: [@first, all @other] := [1,2,3]
block: [_, _, _] := @[1,2,3]
block: (@a, @b) := ("1", "2")
block: (_, (@a, @b)) := (1, (2, 3))
block:
let tmp = @[1,2,3,4,5,6,5,6]
block: [until @a == 6, .._] := tmp; assertEq a, @[1,2,3,4,5]
block: [@a, .._] := tmp; assertEq a, 1
block: [any @a(it < 100)] := tmp; assertEq a, tmp
block: [pref @a is (1|2|3)] := [1,2,3]; assertEq a, @[1,2,3]
block: [pref (1|2|3)] := [1,2,3]
block: [until 3, _] := [1,2,3]
block: [all 1] := [1,1,1]
block: doAssert [all 1] ?= [1,1,1]
block: doAssert not ([all 1] ?= [1,2,3])
block: [opt @a or 12] := `@`[int]([]); check a == 12
block: [opt(@a or 12)] := [1]; assertEq a, 1
block: [opt @a] := [1]; assertEq a, some(1)
block: [opt @a] := `@`[int]([]); assertEq a, none(int)
block: [opt(@a)] := [1]; assertEq a, some(1)
block:
{"k": opt @val1 or "12"} := {"k": "22"}.toTable()
static: doAssert val1 is string
{"k": opt(@val2 or "12")} := {"k": "22"}.toTable()
static: doAssert val2 is string
assertEq val1, val2
assertEq val1, "22"
assertEq val2, "22"
block:
{"h": Some(@x)} := {"h": some("22")}.toTable()
doAssert x is string
doAssert x == "22"
block:
{"k": opt @val, "z": opt @val2} := {"z" : "2"}.toTable()
doAssert val is Option[string]
doAssert val.isNone()
doAssert val2 is Option[string]
doAssert val2.isSome()
doAssert val2.get() == "2"
block: [all(@a)] := [1]; assertEq a, @[1]
block: (f: @hello is ("2" | "3")) := (f: "2"); assertEq hello, "2"
block: (f: @a(it mod 2 == 0)) := (f: 2); assertEq a, 2
block: doAssert not ([1,2] ?= [1,2,3])
block: doAssert [1, .._] ?= [1,2,3]
block: doAssert [1,2,_] ?= [1,2,3]
block:
## Explicitly use `_` to match whole sequence
[until @head is 'd', _] := "word"
## Can also use trailing `.._`
[until 'd', .._] := "word"
assertEq head, @['w', 'o', 'r']
block:
[
[@a, @b],
[@c, @d, all @e],
[@f, @g, all @h]
] := @[
@[1,2],
@[2,3,4,5,6,7],
@[5,6,7,2,3,4]
]
block: (@a, (@b, @c), @d) := (1, (2, 3), 4)
block: (Some(@x), @y) := (some(12), none(float))
block: @hello != nil := (var tmp: ref int; new(tmp); tmp)
block: [all @head] := [1,2,3]; assertEq head, @[1,2,3]
block: [all (1|2|3|4|5)] := [1,2,3,4,1,1,2]
block:
[until @head is 2, all @tail] := [1,2,3]
assertEq head, @[1]
assertEq tail, @[2,3]
block: (_, _, _) := (1, 2, "fa")
block: ([1,2,3]) := [1,2,3]
block: ({0: 1, 1: 2, 2: 3}) := {0: 1, 1: 2, 2: 3}.toTable()
block:
block: [0..3 is @head] := @[1,2,3,4]
case [%*"hello", %*"12"]:
of [any @elem is JString()]:
discard
else:
testFail()
case ("foo", 78)
of ("foo", 78):
discard
of ("bar", 88):
testFail()
block: Some(@x) := some("hello")
if (Some(@x) ?= some("hello")) and
(Some(@y) ?= some("world")):
assertEq x, "hello"
assertEq y, "world"
else:
discard
test "More examples":
func butLast(a: seq[int]): int =
case a:
of []: raiseAssert(
"Cannot take one but last from empty seq!")
of [_]: raiseAssert(
"Cannot take one but last from seq with only one element!")
of [@pre, _]:
return pre
of [_, all @tail]:
return butLast(tail)
else:
raiseAssert("Not possible")
assertEq butLast(@[1,2,3,4]), 3
func butLastGen[T](a: seq[T]): T =
expand case a:
of []: raiseAssert(
"Cannot take one but last from empty seq!")
of [_]: raiseAssert(
"Cannot take one but last from seq with only one element!")
of [@pre, _]: pre
of [_, all @tail]: butLastGen(tail)
else: raiseAssert("Not possible")
assertEq butLastGen(@["1", "2"]), "1"
test "Use in generics":
func hello[T](a: seq[T]): T =
[@head, .._] := a
return head
doAssert hello(@[1,2,3]) == 1
proc g1[T](a: seq[T]): T =
case a:
of [@a]: discard
else: testFail()
expand case a:
of [_]: discard
else: testFail()
expand case a:
of [_.startsWith("--")]: discard
else: testFail()
expand case a:
of [(len: < 12)]: discard
else: testFail()
discard g1(@["---===---=="])
test "Predicates":
case ["hello"]:
of [_.startsWith("--")]:
testFail()
of [_.startsWith("==")]:
testFail()
else:
discard
[all _(it < 10)] := [1,2,3,5,6]
[all < 10] := [1,2,3,4]
[all (len: < 10)] := [@[1,2,3,4], @[1,2,3,4]]
[all _.startsWith("--")] := @["--", "--", "--=="]
block:
[@a.startsWith("--")] := ["--12"]
doAssert a == "--12"
proc exception() =
# This should generate quite nice exception message:
# Match failure for pattern 'all _.startsWith("--")' expected
# all elements to match, but item at index 2 failed
[all _.startsWith("--")] := @["--", "--", "=="]
expect MatchError:
exception()
test "Box reimplementation":
type
TypeKind = enum tkString, tkInt, tkFloat
VNType = object
case kind: TypeKind
of tkString: stringVal*: string
of tkInt: intVal*: int
of tkFloat: floatVal*: float
proc `-` (a, b: VNType): VNType =
case (a, b):
of ((intVal: @val1(a.kind == tkInt)),
(intVal: @val2(b.kind == tkInt))):
return VNType(intVal: val1 - val2, kind: tkInt)
test "Decision matrix":
proc test1(str, arg: string): bool = str == arg
proc test2(str, arg: string): bool = str == arg
case ("1", "2"):
of (_.test1("1"), _.test2("1")):
testFail()
of (_.test1("1"), _.test2("2")):
discard
else:
testFail()
test "One-or-more":
case [1]:
of [@a]: assertEq a, 1
else: testFail()
case [1]:
of [all @a]: assertEq a, @[1]
else: testFail()
case [1,2,3,4]:
of [_, until @a is 4, 4]:
assertEq a, @[2,3]
else:
testFail()
case [1,2,3,4]:
of [@a, .._]:
doAssert a is int
doAssert a == 1
else:
testFail()
case [1,2,3,4]:
of [all @a]:
doAssert a is seq[int]
doAssert a == @[1,2,3,4]
else:
testFail()
test "Optional matches":
case [1,2,3,4]:
of [pref @a is (1 | 2), _, opt @a or 5]:
assertEq a, @[1,2,4]
case [1,2,3]:
of [pref @a is (1 | 2), _, opt @a or 5]:
assertEq a, @[1,2,5]
case [1,2,2,1,1,1]:
of [all (1 | @a)]:
doAssert a is seq[int]
assertEq a, @[2, 2]
test "Tree construction":
macro testImpl(): untyped =
let node = makeTree(NimNode):
IfStmt[
ElifBranch[== ident("true"),
Call[
== ident("echo"),
== newLit("12")]]]
IfStmt[ElifBranch[@head, Call[@call, @arg]]] := node
doAssert head == ident("true")
doAssert call == ident("echo")
doAssert arg == newLit("12")
block:
let input = "hello"
# expandMacros:
Ident(str: @output) := makeTree(NimNode, Ident(str: input))
doAssert output == input
testImpl()
type
HtmlNodeKind = enum
htmlBase = "base"
htmlHead = "head"
htmlLink = "link"
HtmlNode = object
kind*: HtmlNodeKind
text*: string
subn*: seq[HtmlNode]
func add(n: var HtmlNode, s: HtmlNode) = n.subn.add s
func len(n: HtmlNode): int = n.subn.len
iterator items(node: HtmlNode): HtmlNode =
for sn in node.subn:
yield sn
test "Match assertions custom type; treeRepr syntax":
HtmlNode(kind: htmlBase).assertMatch:
Base()
HtmlNode(
kind: htmlLink, text: "text-1", subn: @[
HtmlNode(kind: htmlHead, text: "text-2")]
).assertMatch:
Link(text: "text-1"):
Head(text: "text-2")
HtmlNode(
kind: htmlLink, subn: @[
HtmlNode(kind: htmlHead, text: "text-2"),
HtmlNode(kind: htmlHead, text: "text-3", subn: @[
HtmlNode(kind: htmlBase, text: "text-4"),
HtmlNode(kind: htmlBase, text: "text-5")
])
]
).assertMatch:
Link:
Head(text: "text-2")
Head(text: "text-3"):
Base(text: "text-4")
Base()
test "Tree builder custom type":
discard makeTree(HtmlNode, Base())
discard makeTree(HtmlNode, base())
discard makeTree(HtmlNode, base([link()]))
discard makeTree(HtmlNode):
base:
link(text: "hello")
template wrapper1(body: untyped): untyped =
makeTree(HtmlNode):
body
template wrapper2(body: untyped): untyped =
makeTree(HtmlNode, body)
let tmp1 = wrapper1:
base: link()
base: link()
doAssert tmp1 is seq[HtmlNode]