-
Notifications
You must be signed in to change notification settings - Fork 326
Expand file tree
/
Copy pathTestPatternMatch.fs
More file actions
522 lines (437 loc) · 15.7 KB
/
Copy pathTestPatternMatch.fs
File metadata and controls
522 lines (437 loc) · 15.7 KB
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
module Fable.Tests.PatternMatch
open Util.Testing
// ============================================================================
// Pattern Matching Tests for Python Match Statement Generation
// ============================================================================
// ----------------------------------------------------------------------------
// 1. Simple Integer Matching
// ----------------------------------------------------------------------------
let intMatch2Cases x =
match x with
| 1 -> "one"
| _ -> "other"
let intMatch3Cases x =
match x with
| 1 -> "one"
| 2 -> "two"
| _ -> "other"
let intMatch4Cases x =
match x with
| 1 -> "one"
| 2 -> "two"
| 3 -> "three"
| _ -> "other"
[<Fact>]
let ``test integer match with 2 cases`` () =
intMatch2Cases 1 |> equal "one"
intMatch2Cases 5 |> equal "other"
[<Fact>]
let ``test integer match with 3 cases`` () =
intMatch3Cases 1 |> equal "one"
intMatch3Cases 2 |> equal "two"
intMatch3Cases 5 |> equal "other"
[<Fact>]
let ``test integer match with 4 cases`` () =
intMatch4Cases 1 |> equal "one"
intMatch4Cases 2 |> equal "two"
intMatch4Cases 3 |> equal "three"
intMatch4Cases 5 |> equal "other"
// ----------------------------------------------------------------------------
// 2. String Matching
// ----------------------------------------------------------------------------
let stringMatch2Cases s =
match s with
| "hello" -> "greeting"
| _ -> "unknown"
let stringMatch3Cases s =
match s with
| "hello" -> "greeting"
| "bye" -> "farewell"
| _ -> "unknown"
[<Fact>]
let ``test string match with 2 cases`` () =
stringMatch2Cases "hello" |> equal "greeting"
stringMatch2Cases "foo" |> equal "unknown"
[<Fact>]
let ``test string match with 3 cases`` () =
stringMatch3Cases "hello" |> equal "greeting"
stringMatch3Cases "bye" |> equal "farewell"
stringMatch3Cases "foo" |> equal "unknown"
// ----------------------------------------------------------------------------
// 3. Or-Patterns
// ----------------------------------------------------------------------------
let orPattern2 x =
match x with
| 1 | 2 -> "one or two"
| _ -> "other"
let orPattern3 x =
match x with
| 1 | 2 -> "one or two"
| 3 | 4 | 5 -> "three to five"
| _ -> "other"
[<Fact>]
let ``test or-pattern with 2 alternatives`` () =
orPattern2 1 |> equal "one or two"
orPattern2 2 |> equal "one or two"
orPattern2 3 |> equal "other"
[<Fact>]
let ``test or-pattern with multiple groups`` () =
orPattern3 1 |> equal "one or two"
orPattern3 2 |> equal "one or two"
orPattern3 3 |> equal "three to five"
orPattern3 4 |> equal "three to five"
orPattern3 5 |> equal "three to five"
orPattern3 6 |> equal "other"
// ----------------------------------------------------------------------------
// 4. Union Types
// ----------------------------------------------------------------------------
type Shape =
| Circle of radius: float
| Rectangle of width: float * height: float
| Triangle of base': float * height: float
let unionMatch shape =
match shape with
| Circle r -> $"Circle {r}"
| Rectangle (w, h) -> $"Rectangle {w}x{h}"
| Triangle (b, h) -> $"Triangle {b}x{h}"
let unionWildcard shape =
match shape with
| Circle _ -> "circle"
| _ -> "not circle"
type Color = Red | Blue | Green
let colorMatch2 c =
match c with
| Red -> "red"
| _ -> "not red"
let colorMatch3 c =
match c with
| Red -> "red"
| Blue -> "blue"
| _ -> "other"
type Case =
| BestCase
| MidCase
| WorstCase
// Or-pattern over union cases where the grouped cases share the same target
// as the default branch. See https://github.com/fable-compiler/Fable/issues/4649
let atLeastMid c =
match c with
| BestCase | MidCase -> true
| WorstCase -> false
[<Fact>]
let ``test union match with field extraction`` () =
unionMatch (Circle 5.0) |> equal "Circle 5"
unionMatch (Rectangle (3.0, 4.0)) |> equal "Rectangle 3x4"
unionMatch (Triangle (6.0, 2.0)) |> equal "Triangle 6x2"
[<Fact>]
let ``test union match with wildcard`` () =
unionWildcard (Circle 1.0) |> equal "circle"
unionWildcard (Rectangle (1.0, 1.0)) |> equal "not circle"
unionWildcard (Triangle (1.0, 1.0)) |> equal "not circle"
[<Fact>]
let ``test simple union match with 2 cases`` () =
colorMatch2 Red |> equal "red"
colorMatch2 Blue |> equal "not red"
colorMatch2 Green |> equal "not red"
[<Fact>]
let ``test simple union match with 3 cases`` () =
colorMatch3 Red |> equal "red"
colorMatch3 Blue |> equal "blue"
colorMatch3 Green |> equal "other"
[<Fact>]
let ``test or-pattern over union cases sharing default target`` () =
atLeastMid BestCase |> equal true
atLeastMid MidCase |> equal true
atLeastMid WorstCase |> equal false
// ----------------------------------------------------------------------------
// 5. Guard Expressions (when clauses)
// ----------------------------------------------------------------------------
let guardSimple x =
match x with
| n when n > 10 -> "big"
| n when n > 0 -> "small"
| _ -> "zero or negative"
let guardCapture x =
match x with
| v when v % 2 = 0 -> $"even: {v}"
| v when v % 2 = 1 -> $"odd: {v}"
| _ -> "unexpected"
let guardMixed x =
match x with
| 0 -> "zero"
| 1 -> "one"
| n when n > 100 -> "big"
| _ -> "other"
// More guard cases to test match statement generation with 4+ guards
let guardMultiple x =
match x with
| n when n > 100 -> "huge"
| n when n > 50 -> "big"
| n when n > 10 -> "medium"
| n when n > 0 -> "small"
| _ -> "zero or negative"
// Guard with capture used in body (5 cases)
let guardCaptureMultiple x =
match x with
| n when n > 100 -> $"huge: {n}"
| n when n > 50 -> $"big: {n}"
| n when n > 10 -> $"medium: {n}"
| n when n > 0 -> $"small: {n}"
| _ -> "zero or negative"
[<Fact>]
let ``test guard expression simple`` () =
guardSimple 15 |> equal "big"
guardSimple 5 |> equal "small"
guardSimple 0 |> equal "zero or negative"
guardSimple -5 |> equal "zero or negative"
[<Fact>]
let ``test guard expression with capture`` () =
guardCapture 4 |> equal "even: 4"
guardCapture 7 |> equal "odd: 7"
guardCapture 0 |> equal "even: 0"
[<Fact>]
let ``test guard expression mixed with constants`` () =
guardMixed 0 |> equal "zero"
guardMixed 1 |> equal "one"
guardMixed 150 |> equal "big"
guardMixed 50 |> equal "other"
[<Fact>]
let ``test guard expression with 5 cases`` () =
guardMultiple 150 |> equal "huge"
guardMultiple 75 |> equal "big"
guardMultiple 25 |> equal "medium"
guardMultiple 5 |> equal "small"
guardMultiple 0 |> equal "zero or negative"
guardMultiple -10 |> equal "zero or negative"
[<Fact>]
let ``test guard expression capture with 5 cases`` () =
guardCaptureMultiple 150 |> equal "huge: 150"
guardCaptureMultiple 75 |> equal "big: 75"
guardCaptureMultiple 25 |> equal "medium: 25"
guardCaptureMultiple 5 |> equal "small: 5"
guardCaptureMultiple 0 |> equal "zero or negative"
// Guard that uses the bound value multiple times. The guard is hoisted into a
// helper function and must not capture the outer argument as a duplicate
// default parameter (see #4610).
let mkTag (tag: string option) =
match tag with
| None -> ""
| Some s when s.StartsWith("!") && not (s.StartsWith("!!")) -> s + " "
| Some s -> "!<" + s + "> "
[<Fact>]
let ``test guard reusing binding does not duplicate captured argument`` () =
mkTag None |> equal ""
mkTag (Some "!foo") |> equal "!foo "
mkTag (Some "!!foo") |> equal "!<!!foo> "
mkTag (Some "foo") |> equal "!<foo> "
// ----------------------------------------------------------------------------
// 6. Nested Matching
// ----------------------------------------------------------------------------
let nestedSimple x y =
match x with
| 1 ->
match y with
| 1 -> "both one"
| _ -> "x is one"
| _ -> "x is not one"
let nestedComplex x y =
match x with
| 1 ->
match y with
| 1 -> "x=1, y=1"
| 2 -> "x=1, y=2"
| _ -> "x=1, y=other"
| 2 ->
match y with
| 1 -> "x=2, y=1"
| _ -> "x=2, y=other"
| _ -> "x=other"
[<Fact>]
let ``test nested match simple`` () =
nestedSimple 1 1 |> equal "both one"
nestedSimple 1 2 |> equal "x is one"
nestedSimple 2 1 |> equal "x is not one"
[<Fact>]
let ``test nested match complex`` () =
nestedComplex 1 1 |> equal "x=1, y=1"
nestedComplex 1 2 |> equal "x=1, y=2"
nestedComplex 1 3 |> equal "x=1, y=other"
nestedComplex 2 1 |> equal "x=2, y=1"
nestedComplex 2 2 |> equal "x=2, y=other"
nestedComplex 3 1 |> equal "x=other"
// ----------------------------------------------------------------------------
// 7. Option Matching
// ----------------------------------------------------------------------------
let optionMatch opt =
match opt with
| Some x -> $"value: {x}"
| None -> "none"
[<Fact>]
let ``test option match`` () =
optionMatch (Some 42) |> equal "value: 42"
optionMatch None |> equal "none"
// ----------------------------------------------------------------------------
// 8. Result Matching
// ----------------------------------------------------------------------------
let resultMatch res =
match res with
| Ok v -> $"ok: {v}"
| Error e -> $"error: {e}"
[<Fact>]
let ``test result match`` () =
resultMatch (Ok 100) |> equal "ok: 100"
resultMatch (Error "fail") |> equal "error: fail"
// ----------------------------------------------------------------------------
// 9. List Matching
// ----------------------------------------------------------------------------
let listMatch lst =
match lst with
| [] -> "empty"
| [x] -> $"single: {x}"
| [x; y] -> $"pair: {x}, {y}"
| _ -> "many"
[<Fact>]
let ``test list match`` () =
listMatch [] |> equal "empty"
listMatch [1] |> equal "single: 1"
listMatch [1; 2] |> equal "pair: 1, 2"
listMatch [1; 2; 3] |> equal "many"
// ----------------------------------------------------------------------------
// 10. Char Matching
// ----------------------------------------------------------------------------
let charMatch c =
match c with
| 'a' -> "letter a"
| 'b' -> "letter b"
| _ -> "other"
[<Fact>]
let ``test char match`` () =
charMatch 'a' |> equal "letter a"
charMatch 'b' |> equal "letter b"
charMatch 'c' |> equal "other"
// ----------------------------------------------------------------------------
// 11. Tuple Patterns with Boolean and Guard
// ----------------------------------------------------------------------------
// These patterns generate Python match statements like:
// match tuple:
// case [True, _, i] if i > threshold:
// ...
// case _:
// ...
/// Helper that returns (found: bool, hash: int, index: int)
let tryFindIndex (key: string) (data: Map<string, int>) : bool * int * int =
match Map.tryFind key data with
| Some idx -> true, key.GetHashCode(), idx
| None -> false, key.GetHashCode(), -1
let tupleBoolGuardSimple (result: bool * int * int) =
match result with
| true, _, i when i > -1 -> "found"
| _, _, _ -> "not found"
let tupleBoolGuardWithValue (result: bool * int * int) =
match result with
| true, _, i when i >= 0 -> $"found at {i}"
| _, _, _ -> "not found"
let tupleBoolGuardMultiple (result: bool * int * int) =
match result with
| true, _, i when i > 10 -> "found high"
| true, _, i when i > 0 -> "found low"
| true, _, 0 -> "found at zero"
| _, _, _ -> "not found"
/// Simulates Dictionary.ContainsKey pattern
let containsKeyPattern (key: string) (data: Map<string, int>) =
match tryFindIndex key data with
| true, _, i when i > -1 -> true
| _, _, _ -> false
/// Simulates Dictionary.TryGetValue pattern
let tryGetValuePattern (key: string) (data: Map<string, int>) =
match tryFindIndex key data with
| true, _, i when i >= 0 -> Some i
| _, _, _ -> None
[<Fact>]
let ``test tuple bool guard simple`` () =
tupleBoolGuardSimple (true, 123, 5) |> equal "found"
tupleBoolGuardSimple (true, 123, -1) |> equal "not found"
tupleBoolGuardSimple (false, 0, -1) |> equal "not found"
[<Fact>]
let ``test tuple bool guard with value`` () =
tupleBoolGuardWithValue (true, 0, 42) |> equal "found at 42"
tupleBoolGuardWithValue (true, 0, 0) |> equal "found at 0"
tupleBoolGuardWithValue (true, 0, -1) |> equal "not found"
tupleBoolGuardWithValue (false, 0, -1) |> equal "not found"
[<Fact>]
let ``test tuple bool guard multiple conditions`` () =
tupleBoolGuardMultiple (true, 0, 15) |> equal "found high"
tupleBoolGuardMultiple (true, 0, 5) |> equal "found low"
tupleBoolGuardMultiple (true, 0, 0) |> equal "found at zero"
tupleBoolGuardMultiple (true, 0, -1) |> equal "not found"
tupleBoolGuardMultiple (false, 0, 10) |> equal "not found"
[<Fact>]
let ``test contains key pattern`` () =
let data = Map.ofList [("a", 0); ("b", 1); ("c", 2)]
containsKeyPattern "a" data |> equal true
containsKeyPattern "b" data |> equal true
containsKeyPattern "z" data |> equal false
[<Fact>]
let ``test try get value pattern`` () =
let data = Map.ofList [("x", 10); ("y", 20)]
tryGetValuePattern "x" data |> equal (Some 10)
tryGetValuePattern "y" data |> equal (Some 20)
tryGetValuePattern "z" data |> equal None
// ----------------------------------------------------------------------------
// 8. Nonlocal in match/case (regression test)
// Tests that mutable variables captured in closures work correctly when
// assigned inside union pattern match statements (nonlocal must be hoisted
// out of match/case blocks to avoid Python SyntaxError).
// ----------------------------------------------------------------------------
type Msg =
| OnNext of int
| OnError of exn
| OnCompleted
/// Simulates a take(n) operator: processes at most `count` OnNext messages.
let takeFn (count: int) (msgs: Msg list) : int list =
let mutable remaining = count
let results = System.Collections.Generic.List<int>()
let handle (msg: Msg) =
let remaining_snapshot = remaining
match msg with
| OnError _ -> ()
| OnCompleted -> ()
| OnNext value ->
if remaining_snapshot > 1 then
remaining <- remaining_snapshot - 1
results.Add(value)
elif remaining_snapshot = 1 then
remaining <- 0
results.Add(value)
msgs |> List.iter handle
results |> Seq.toList
[<Fact>]
let ``test nonlocal hoisted out of match case - take operator`` () =
let msgs = [ OnNext 1; OnNext 2; OnNext 3; OnNext 4; OnNext 5 ]
takeFn 3 msgs |> equal [ 1; 2; 3 ]
takeFn 1 msgs |> equal [ 1 ]
takeFn 5 msgs |> equal [ 1; 2; 3; 4; 5 ]
/// Simulates nested union pattern matching with mutable captures.
let nestedUnionMatch (msg: Msg) : string =
let mutable state = "initial"
let handle () =
let snapshot = state
match msg with
| OnError _ ->
state <- "error"
"error"
| _ ->
match msg with
| OnCompleted ->
state <- "completed"
"completed"
| _ ->
// OnNext case - uses snapshot (nonlocal must be hoisted)
state <- snapshot + "-processed"
"next:" + snapshot
handle ()
[<Fact>]
let ``test nonlocal hoisted out of nested match case`` () =
nestedUnionMatch (OnNext 42) |> equal "next:initial"
nestedUnionMatch OnCompleted |> equal "completed"
nestedUnionMatch (OnError(exn "err")) |> equal "error"