-
Notifications
You must be signed in to change notification settings - Fork 855
Expand file tree
/
Copy pathPatternMatchCompilation.fs
More file actions
1746 lines (1523 loc) · 85.7 KB
/
PatternMatchCompilation.fs
File metadata and controls
1746 lines (1523 loc) · 85.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
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
module internal FSharp.Compiler.PatternMatchCompilation
open System.Collections.Generic
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open FSharp.Compiler
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AbstractIL.Diagnostics
open FSharp.Compiler.AccessibilityLogic
open FSharp.Compiler.CompilerGlobalState
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.InfoReader
open FSharp.Compiler.MethodCalls
open FSharp.Compiler.Syntax
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeBasics
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.TypeRelations
open type System.MemoryExtensions
exception MatchIncomplete of bool * (string * bool) option * range
exception RuleNeverMatched of range
exception EnumMatchIncomplete of bool * (string * bool) option * range
type ActionOnFailure =
| ThrowIncompleteMatchException
| IgnoreWithWarning
| Throw
| Rethrow
| FailFilter
[<NoEquality; NoComparison>]
type Pattern =
| TPat_const of Const * range
| TPat_wild of range (* note = TPat_disjs([], m), but we haven't yet removed that duplication *)
| TPat_as of Pattern * PatternValBinding * range (* note: can be replaced by TPat_var, i.e. equals TPat_conjs([TPat_var; pat]) *)
| TPat_disjs of Pattern list * range
| TPat_conjs of Pattern list * range
| TPat_query of (Expr * TType list * ActivePatternReturnKind * (ValRef * TypeInst) option * int * ActivePatternInfo) * Pattern * range
| TPat_unioncase of UnionCaseRef * TypeInst * Pattern list * range
| TPat_exnconstr of TyconRef * Pattern list * range
| TPat_tuple of TupInfo * Pattern list * TType list * range
| TPat_array of Pattern list * TType * range
| TPat_recd of TyconRef * TypeInst * Pattern list * range
| TPat_null of range
| TPat_isinst of TType * TType * Pattern option * range
| TPat_error of range
member this.Range =
match this with
| TPat_const(_, m) -> m
| TPat_wild m -> m
| TPat_as(_, _, m) -> m
| TPat_disjs(_, m) -> m
| TPat_conjs(_, m) -> m
| TPat_query(_, _, m) -> m
| TPat_unioncase(_, _, _, m) -> m
| TPat_exnconstr(_, _, m) -> m
| TPat_tuple(_, _, _, m) -> m
| TPat_array(_, _, m) -> m
| TPat_recd(_, _, _, m) -> m
| TPat_null m -> m
| TPat_isinst(_, _, _, m) -> m
| TPat_error m -> m
and PatternValBinding = PatternValBinding of Val * GeneralizedType
and MatchClause =
| MatchClause of Pattern * Expr option * DecisionTreeTarget * range
member c.GuardExpr = let (MatchClause(_, whenOpt, _, _)) = c in whenOpt
member c.Pattern = let (MatchClause(p, _, _, _)) = c in p
member c.Range = let (MatchClause(_, _, _, m)) = c in m
member c.Target = let (MatchClause(_, _, tg, _)) = c in tg
member c.BoundVals = let (MatchClause(_p, _whenOpt, TTarget(vs, _, _), _m)) = c in vs
//---------------------------------------------------------------------------
// Nasty stuff to permit obscure generic bindings such as
// let x, y = [], []
//
// BindSubExprOfInput actually produces the binding
// e.g. let v2 = \Gamma ['a, 'b]. ([] : 'a, [] : 'b)
// let (x, y) = p.
// When v = x, gtvs = 'a, 'b. We must bind:
// x --> \Gamma A. fst (v2[A, <dummy>])
// y --> \Gamma A. snd (v2[<dummy>, A]).
//
// GetSubExprOfInput is just used to get a concrete value from a type
// function in the middle of the "test" part of pattern matching.
// For example, e.g. let [x; y] = [ (\x.x); (\x.x) ]
// Here the constructor test needs a real list, even though the
// r.h.s. is actually a polymorphic type function. To do the
// test, we apply the r.h.s. to a dummy type - it doesn't matter
// which (unless the r.h.s. actually looks at it's type argument...)
//---------------------------------------------------------------------------
type SubExprOfInput =
| SubExpr of (TyparInstantiation -> Expr -> Expr) * (Expr * Val)
let BindSubExprOfInput g amap gtps (PatternValBinding(v, tyscheme)) m (SubExpr(accessf, (ve2, v2))) =
let e' =
if isNil gtps then
accessf [] ve2
else
let tyargs =
let mutable someSolved = false
let freezeVar gtp =
if isBeingGeneralized gtp tyscheme then
mkTyparTy gtp
else
someSolved <- true
ChooseTyparSolution g amap gtp
let solutions = List.map freezeVar gtps
if someSolved then
IterativelySubstituteTyparSolutions g gtps solutions
else
solutions
let tinst = mkTyparInst gtps tyargs
accessf tinst (mkApps g ((ve2, v2.Type), [tyargs], [], v2.Range))
v, mkGenericBindRhs g m [] tyscheme e'
let GetSubExprOfInput g (gtps, tyargs, tinst) (SubExpr(accessf, (ve2, v2))) =
if isNil gtps then accessf [] ve2 else
accessf tinst (mkApps g ((ve2, v2.Type), [tyargs], [], v2.Range))
//---------------------------------------------------------------------------
// path, frontier
//---------------------------------------------------------------------------
// A path reaches into a pattern.
// The ints record which choices taken, e.g. tuple/record fields.
type Path =
| PathQuery of Path * Unique
| PathTuple of Path * TypeInst * int
| PathRecd of Path * TyconRef * TypeInst * int
| PathUnionConstr of Path * UnionCaseRef * TypeInst * int
| PathArray of Path * TType * int * int
| PathExnConstr of Path * TyconRef * int
| PathEmpty of TType
let rec pathEq p1 p2 =
match p1, p2 with
| PathQuery(p1, n1), PathQuery(p2, n2) -> (n1 = n2) && pathEq p1 p2
| PathTuple(p1, _, n1), PathTuple(p2, _, n2) -> (n1 = n2) && pathEq p1 p2
| PathRecd(p1, _, _, n1), PathRecd(p2, _, _, n2) -> (n1 = n2) && pathEq p1 p2
| PathUnionConstr(p1, _, _, n1), PathUnionConstr(p2, _, _, n2) -> (n1 = n2) && pathEq p1 p2
| PathArray(p1, _, _, n1), PathArray(p2, _, _, n2) -> (n1 = n2) && pathEq p1 p2
| PathExnConstr(p1, _, n1), PathExnConstr(p2, _, n2) -> (n1 = n2) && pathEq p1 p2
| PathEmpty _, PathEmpty _ -> true
| _ -> false
//---------------------------------------------------------------------------
// Counter example generation
//---------------------------------------------------------------------------
type RefutedSet =
/// A value RefutedInvestigation(path, discrim) indicates that the value at the given path is known
/// to NOT be matched by the given discriminator
| RefutedInvestigation of Path * DecisionTreeTest list
/// A value RefutedWhenClause indicates that a 'when' clause failed
| RefutedWhenClause
let notNullText = "some-non-null-value"
let otherSubtypeText = "some-other-subtype"
/// Create a TAST const value from an IL-initialized field read from .NET metadata
// (Originally moved from TcFieldInit in CheckExpressions.fs -- feel free to move this somewhere more appropriate)
let ilFieldToTastConst lit =
match lit with
| ILFieldInit.String s -> Const.String s
| ILFieldInit.Null -> Const.Zero
| ILFieldInit.Bool b -> Const.Bool b
| ILFieldInit.Char c -> Const.Char (char (int c))
| ILFieldInit.Int8 x -> Const.SByte x
| ILFieldInit.Int16 x -> Const.Int16 x
| ILFieldInit.Int32 x -> Const.Int32 x
| ILFieldInit.Int64 x -> Const.Int64 x
| ILFieldInit.UInt8 x -> Const.Byte x
| ILFieldInit.UInt16 x -> Const.UInt16 x
| ILFieldInit.UInt32 x -> Const.UInt32 x
| ILFieldInit.UInt64 x -> Const.UInt64 x
| ILFieldInit.Single f -> Const.Single f
| ILFieldInit.Double f -> Const.Double f
exception CannotRefute
[<Struct>]
[<RequireQualifiedAccess>]
type CounterExampleType =
/// Maps to EnumMatchIncomplete exn
| EnumCoversKnown
/// Maps to MatchIncomplete exn
| WithoutEnum
with member x.Combine(other) = match other with EnumCoversKnown -> other | _ -> x
let RefuteDiscrimSet g m path discrims : Expr * CounterExampleType =
let mkUnknown ty = snd(mkCompGenLocal m "_" ty)
let rec go path tm =
match path with
| PathQuery _ -> raise CannotRefute
| PathTuple (p, tys, j) ->
let k, eCoversVals = mkOneKnown tm j tys
go p (fun _ -> mkRefTupled g m k tys, eCoversVals)
| PathRecd (p, tcref, tinst, j) ->
let flds, eCoversVals = tcref |> actualTysOfInstanceRecdFields (mkTyconRefInst tcref tinst) |> mkOneKnown tm j
go p (fun _ -> Expr.Op (TOp.Recd (RecdExpr, tcref), tinst, flds, m), eCoversVals)
| PathUnionConstr (p, ucref, tinst, j) ->
let flds, eCoversVals = ucref |> actualTysOfUnionCaseFields (mkTyconRefInst ucref.TyconRef tinst)|> mkOneKnown tm j
go p (fun _ -> Expr.Op (TOp.UnionCase ucref, tinst, flds, m), eCoversVals)
| PathArray (p, ty, len, n) ->
let flds, eCoversVals = mkOneKnown tm n (List.replicate len ty)
go p (fun _ -> Expr.Op (TOp.Array, [ty], flds, m), eCoversVals)
| PathExnConstr (p, ecref, n) ->
let flds, eCoversVals = ecref |> recdFieldTysOfExnDefRef |> mkOneKnown tm n
go p (fun _ -> Expr.Op (TOp.ExnConstr ecref, [], flds, m), eCoversVals)
| PathEmpty ty -> tm ty
and mkOneKnown tm n tys =
let flds = List.mapi (fun i ty -> if i = n then tm ty else (mkUnknown ty, CounterExampleType.WithoutEnum)) tys
List.map fst flds, List.fold (fun acc (_, eCoversVals) -> acc.Combine(eCoversVals)) CounterExampleType.WithoutEnum flds
and mkUnknowns tys = List.map mkUnknown tys
let tm ty =
match discrims with
| [DecisionTreeTest.IsNull] ->
snd(mkCompGenLocal m notNullText ty), CounterExampleType.WithoutEnum
| DecisionTreeTest.IsInst _ :: _ ->
snd(mkCompGenLocal m otherSubtypeText ty), CounterExampleType.WithoutEnum
| DecisionTreeTest.Const c :: rest ->
let consts = Set.ofList (c :: List.choose (function DecisionTreeTest.Const c -> Some c | _ -> None) rest)
let c' =
Seq.tryFind (consts.Contains >> not)
(match c with
| Const.Bool _ -> [ true; false ] |> List.toSeq |> Seq.map Const.Bool
| Const.SByte _ -> Seq.append (seq { 0y .. System.SByte.MaxValue }) (seq { System.SByte.MinValue .. 0y })|> Seq.map Const.SByte
| Const.Int16 _ -> Seq.append (seq { 0s .. System.Int16.MaxValue }) (seq { System.Int16.MinValue .. 0s }) |> Seq.map Const.Int16
| Const.Int32 _ -> Seq.append (seq { 0 .. System.Int32.MaxValue }) (seq { System.Int32.MinValue .. 0 })|> Seq.map Const.Int32
| Const.Int64 _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map Const.Int64
| Const.IntPtr _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map Const.IntPtr
| Const.Byte _ -> seq { 0uy .. System.Byte.MaxValue } |> Seq.map Const.Byte
| Const.UInt16 _ -> seq { 0us .. System.UInt16.MaxValue } |> Seq.map Const.UInt16
| Const.UInt32 _ -> seq { 0u .. System.UInt32.MaxValue } |> Seq.map Const.UInt32
| Const.UInt64 _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map Const.UInt64
| Const.UIntPtr _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map Const.UIntPtr
| Const.Double _ -> seq { 0 .. System.Int32.MaxValue } |> Seq.map (float >> Const.Double)
| Const.Single _ -> seq { 0 .. System.Int32.MaxValue } |> Seq.map (float32 >> Const.Single)
| Const.Char _ -> seq { 32us .. System.UInt16.MaxValue } |> Seq.map (char >> Const.Char)
| Const.String _ -> seq { 1 .. System.Int32.MaxValue } |> Seq.map (fun v -> Const.String(System.String('a', v)))
| Const.Decimal _ -> seq { 1 .. System.Int32.MaxValue } |> Seq.map (decimal >> Const.Decimal)
| _ ->
raise CannotRefute)
match c' with
| None -> raise CannotRefute
| Some c ->
match tryTcrefOfAppTy g ty with
| ValueSome tcref when tcref.IsEnumTycon ->
// We must distinguish between F#-defined enums and other .NET enums, as they are represented differently in the TAST
let enumValues =
if tcref.IsILEnumTycon then
let (TILObjectReprData(_, _, tdef)) = tcref.ILTyconInfo
tdef.Fields.AsList()
|> Seq.choose (fun ilField ->
if ilField.IsStatic then
ilField.LiteralValue |> Option.map (fun ilValue ->
ilField.Name, ilFieldToTastConst ilValue)
else None)
else
tcref.AllFieldsArray |> Seq.choose (fun fsField ->
match fsField.rfield_const, fsField.rfield_static with
| Some fsFieldValue, true -> Some (fsField.rfield_id.idText, fsFieldValue)
| _ -> None)
let nonCoveredEnumValues = Seq.tryFind (fun (_, fldValue) -> not (consts.Contains fldValue)) enumValues
match nonCoveredEnumValues with
| None -> Expr.Const (c, m, ty), CounterExampleType.EnumCoversKnown
| Some (fldName, _) ->
let v = RecdFieldRef.RecdFieldRef(tcref, fldName)
Expr.Op (TOp.ValFieldGet v, [ty], [], m), CounterExampleType.WithoutEnum
| _ -> Expr.Const (c, m, ty), CounterExampleType.WithoutEnum
| DecisionTreeTest.UnionCase (ucref1, tinst) :: rest ->
let ucrefs = ucref1 :: List.choose (function DecisionTreeTest.UnionCase(ucref, _) -> Some ucref | _ -> None) rest
let tcref = ucref1.TyconRef
(* Choose the first ucref based on ordering of names *)
let others =
tcref.UnionCasesAsRefList
|> List.filter (fun ucref -> not (List.exists (g.unionCaseRefEq ucref) ucrefs))
|> List.sortBy (fun ucref -> ucref.CaseName)
match others with
| [] -> raise CannotRefute
| ucref2 :: _ ->
let flds = ucref2 |> actualTysOfUnionCaseFields (mkTyconRefInst tcref tinst) |> mkUnknowns
Expr.Op (TOp.UnionCase ucref2, tinst, flds, m), CounterExampleType.WithoutEnum
| [DecisionTreeTest.ArrayLength (n, ty)] ->
Expr.Op (TOp.Array, [ty], mkUnknowns (List.replicate (n+1) ty), m), CounterExampleType.WithoutEnum
| _ ->
raise CannotRefute
go path tm
let rec CombineRefutations g refutation1 refutation2 =
match refutation1, refutation2 with
| Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = "_" -> other
| Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = notNullText -> other
| Expr.Val (vref, _, _), other | other, Expr.Val (vref, _, _) when vref.LogicalName = otherSubtypeText -> other
| Expr.Op (TOp.ExnConstr ecref1 as op1, tinst1, flds1, m1), Expr.Op (TOp.ExnConstr ecref2, _, flds2, _) when tyconRefEq g ecref1 ecref2 ->
Expr.Op (op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1)
| Expr.Op (TOp.UnionCase ucref1 as op1, tinst1, flds1, m1), Expr.Op (TOp.UnionCase ucref2, _, flds2, _) ->
if g.unionCaseRefEq ucref1 ucref2 then
Expr.Op (op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1)
(* Choose the greater of the two ucrefs based on name ordering *)
elif ucref1.CaseName < ucref2.CaseName then
refutation2
else
refutation1
| Expr.Op (op1, tinst1, flds1, m1), Expr.Op (_, _, flds2, _) ->
Expr.Op (op1, tinst1, List.map2 (CombineRefutations g) flds1 flds2, m1)
| Expr.Const (c1, m1, ty1), Expr.Const (c2, _, _) ->
let c12 =
// Make sure longer strings are greater, not the case in the default ordinal comparison
// This is needed because the individual counter examples make longer strings
let MaxStrings s1 s2 =
let c = compare (String.length s1) (String.length s2)
if c < 0 then s2
elif c > 0 then s1
elif s1 < s2 then s2
else s1
match c1, c2 with
| Const.String s1, Const.String s2 -> Const.String(MaxStrings s1 s2)
| Const.Decimal s1, Const.Decimal s2 -> Const.Decimal(max s1 s2)
| _ -> max c1 c2
Expr.Const (c12, m1, ty1)
| _ -> refutation1
let ShowCounterExample g denv m refuted =
try
let refutations = refuted |> List.collect (function RefutedWhenClause -> [] | RefutedInvestigation(path, discrim) -> [RefuteDiscrimSet g m path discrim])
let counterExample, enumCoversKnown =
match refutations with
| [] -> raise CannotRefute
| (r, eck) :: t ->
((r, eck), t) ||> List.fold (fun (rAcc, eckAcc) (r, eck) ->
CombineRefutations g rAcc r, eckAcc.Combine(eck))
let text = LayoutRender.showL (NicePrint.dataExprL denv counterExample)
let failingWhenClause = refuted |> List.exists (function RefutedWhenClause -> true | _ -> false)
Some(text, failingWhenClause, enumCoversKnown)
with
| CannotRefute ->
None
| e ->
warning(InternalError(sprintf "<failure during counter example generation: %s>" (e.ToString()), m))
None
//---------------------------------------------------------------------------
// Basic problem specification
//---------------------------------------------------------------------------
type ClauseNumber = int
/// Represents an unresolved portion of pattern matching
type Active = Active of Path * SubExprOfInput * Pattern
type Actives = Active list
/// Represents an unresolved portion of pattern matching within a clause
type Frontier = Frontier of ClauseNumber * Actives * ValMap<Expr>
type InvestigationPoint = Investigation of ClauseNumber * DecisionTreeTest * Path
// Note: actives must be a SortedDictionary
let rec isMemOfActives p1 actives =
match actives with
| [] -> false
| Active(p2, _, _) :: rest -> pathEq p1 p2 || isMemOfActives p1 rest
// Find the information about the active investigation
let rec lookupActive x l =
match l with
| [] -> raise (KeyNotFoundException())
| Active(h, r1, r2) :: t -> if pathEq x h then (r1, r2) else lookupActive x t
let rec removeActive x l =
match l with
| [] -> []
| Active(h, _, _) as p :: t -> if pathEq x h then t else p :: removeActive x t
[<RequireQualifiedAccess>]
type Implication =
/// Indicates that, for any inputs where the first test succeeds, the second test will succeed
| Succeeds
/// Indicates that, for any inputs where the first test succeeded, the second test will fail
| Fails
/// Indicates nothing in particular
| Nothing
/// Work out what a successful type test (against tgtTy1) implies about a null test for the same input value.
///
/// Example:
/// match x with
/// | :? string when false -> ... // note: "when false" used so type test succeeds but proceed to next type test
/// | null -> ...
/// For any inputs where ':? string' succeeds, 'null' will fail
///
/// Example:
/// match x with
/// | :? (int option) when false -> ... // note: "when false" used so type test succeeds but proceed to next type test
/// | null -> ...
/// Nothing can be learned. If ':? (int option)' succeeds, 'null' may still have to be run.
let computeWhatSuccessfulTypeTestImpliesAboutNullTest g tgtTy1 =
if TypeNullIsTrueValue g tgtTy1 then
Implication.Nothing
else
Implication.Fails
/// Work out what a failing type test (against tgtTy1) implies about a null test for the same input value.
///
/// Example:
/// match x with
/// | :? (int option) -> ...
/// | null -> ...
/// If ':? (int option)' fails then 'null' will fail
let computeWhatFailingTypeTestImpliesAboutNullTest g tgtTy1 =
if TypeNullIsTrueValue g tgtTy1 then
Implication.Fails
else
Implication.Nothing
/// Work out what one successful null test implies about a type test (against tgtTy2) for the same input value.
///
/// Example:
/// match x with
/// | null when false -> ... // note: "when false" used so null test succeeds but proceed to next type test
/// | :? string -> ...
/// For any inputs where 'null' succeeds, ':? string' will fail
///
/// Example:
/// match x with
/// | null when false -> ... // note: "when false" used so null test succeeds but proceed to next type test
/// | :? (int option) -> ...
/// For any inputs where 'null' succeeds, ':? (int option)' will succeed
let computeWhatSuccessfulNullTestImpliesAboutTypeTest g tgtTy2 =
if TypeNullIsTrueValue g tgtTy2 then
Implication.Succeeds
else
Implication.Fails
/// Work out what a failing null test implies about a type test (against tgtTy2) for the same
/// input value. The answer is "nothing" but it's included for symmetry.
let computeWhatFailingNullTestImpliesAboutTypeTest _g _tgtTy2 =
Implication.Nothing
/// Work out what one successful type test (against tgtTy1) implies about another type test (against tgtTy2)
/// for the same input value.
let computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 =
let tgtTy1 = stripTyEqnsWrtErasure EraseAll g tgtTy1
let tgtTy2 = stripTyEqnsWrtErasure EraseAll g tgtTy2
// A successful type test of an input value against a type (tgtTy1)
// implies all type tests of the same input value on equivalent or
// supertypes (tgtTy2) always succeed.
//
// Example:
// match x with
// | :? string when false -> ... // note: "when false" used so type test succeeds but proceed to next type test
// | :? IComparable -> ...
//
// Example:
// match x with
// | :? string when false -> ... // note: "when false" used so type test succeeds but proceed to next type test
// | :? string -> ...
//
if TypeDefinitelySubsumesTypeNoCoercion 0 g amap m tgtTy2 tgtTy1 then
Implication.Succeeds
// A successful type test of an input value against a sealed target type (tgtTy1) implies all
// type tests of the same object against a unrelated target type (tgtTy2) fails.
//
// Example:
// match x with
// | :? int when false -> ... // note: "when false" used so type test succeeds but proceed to next type test
// | :? string -> ...
//
// For any inputs where ':? int' succeeds, ':? string' will fail
//
//
// This only applies if tgtTy2 is not potentially related to the sealed type tgtTy1:
// match x with
// | :? int when false -> ... // note: "when false" used so type test succeeds but proceed to next type test
// | :? IComparable -> ...
//
// Here IComparable is not known to fail (NOTE: indeed it is actually known to succeed,
// give ":? int" succeeded, however this is not utilised in the analysis, because it involves coercion).
//
//
// This rule also doesn't apply to unsealed types:
// match x with
// | :? SomeUnsealedClass when false -> ... // note: "when false" used so type test succeeds but proceed to next type test
// | :? SomeInterface -> ...
// because the input may be some subtype of SomeUnsealedClass and that type could implement SomeInterface even if
// SomeUnsealedClass doesnt.
//
//
// This rule also doesn't apply to types with null as true value:
// match x with
// | :? (int option) when false -> ... // "when false" means type test succeeds but proceed to next type test
// | :? (string option) -> ...
//
// Here on 'null' input the first pattern succeeds, and the second pattern will also succeed
elif isSealedTy g tgtTy1 &&
not (TypeNullIsTrueValue g tgtTy1) &&
not (TypeFeasiblySubsumesType 0 g amap m tgtTy2 CanCoerce tgtTy1) then
Implication.Fails
// A successful type test of an input value against an unsealed class type (tgtTy1) implies
// a type test of the same input value against an unrelated non-interface type (tgtTy2) always fails
//
// Example:
// match x with
// | :? SomeUnsealedClass when false -> ... // "when false" used so type test succeeds but proceed to next type test
// | :? SomeUnrelatedClass -> ...
//
// For any inputs where ':? SomeUnsealedClass' succeeds, ':? SomeUnrelatedClass' will fail
//
// This doesn't apply to interfaces or null-as-true-value
elif not (isSealedTy g tgtTy1) &&
isClassTy g tgtTy1 &&
not (TypeNullIsTrueValue g tgtTy1) &&
not (isInterfaceTy g tgtTy2) &&
not (TypeFeasiblySubsumesType 0 g amap m tgtTy1 CanCoerce tgtTy2) &&
not (TypeFeasiblySubsumesType 0 g amap m tgtTy2 CanCoerce tgtTy1) then
Implication.Fails
// A successful type test of an input value against an interface type (tgtTy1) implies
// a type test of the same object against a sealed types (tgtTy2) that does not support that interface
// always fails.
//
// Example:
// match x with
// | :? IComparable when false -> ... // "when false" used so type test succeeds but proceed to next type test
// | :? SomeOtherSealedClass -> ...
//
// For any inputs where ':? IComparable' succeeds, ':? SomeOtherSealedClass' will fail
//
// This doesn't apply to interfaces or null-as-true-value
elif isInterfaceTy g tgtTy1 &&
not (TypeNullIsTrueValue g tgtTy1) &&
isSealedTy g tgtTy2 &&
not (TypeFeasiblySubsumesType 0 g amap m tgtTy1 CanCoerce tgtTy2) then
Implication.Fails
else
Implication.Nothing
/// Work out what one failing type test (tgtTy1) implies about another type test (tgtTy2)
let computeWhatFailingTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 =
let tgtTy1 = stripTyEqnsWrtErasure EraseAll g tgtTy1
let tgtTy2 = stripTyEqnsWrtErasure EraseAll g tgtTy2
// If testing an input value against a target type (tgtTy1) fails then
// testing the same input value against an equivalent or subtype type (tgtTy2) always fails.
//
// Example:
// match x with
// | :? IComparable -> ...
// | :? string -> ...
//
// Example:
// match x with
// | :? string -> ...
// | :? string -> ...
if TypeDefinitelySubsumesTypeNoCoercion 0 g amap m tgtTy1 tgtTy2 then
Implication.Fails
else
Implication.Nothing
//---------------------------------------------------------------------------
// Utilities
//---------------------------------------------------------------------------
// tpinst is required because the pattern is specified w.r.t. generalized type variables.
let getDiscrimOfPattern (g: TcGlobals) tpinst t =
match t with
| TPat_null _m ->
Some(DecisionTreeTest.IsNull)
| TPat_isinst (srcTy, tgtTy, _, _m) ->
Some(DecisionTreeTest.IsInst (instType tpinst srcTy, instType tpinst tgtTy))
| TPat_exnconstr(tcref, _, _m) ->
Some(DecisionTreeTest.IsInst (g.exn_ty, mkWoNullAppTy tcref []))
| TPat_const (c, _m) ->
Some(DecisionTreeTest.Const c)
| TPat_unioncase (c, tyargs', _, _m) ->
Some(DecisionTreeTest.UnionCase (c, instTypes tpinst tyargs'))
| TPat_array (args, ty, _m) ->
Some(DecisionTreeTest.ArrayLength (args.Length, ty))
| TPat_query ((activePatExpr, resTys, retKind, apatVrefOpt, idx, apinfo), _, _m) ->
Some (DecisionTreeTest.ActivePatternCase (activePatExpr, instTypes tpinst resTys, retKind, apatVrefOpt, idx, apinfo))
| TPat_error range ->
Some (DecisionTreeTest.Error range)
| _ -> None
let constOfDiscrim discrim =
match discrim with
| DecisionTreeTest.Const x -> x
| _ -> failwith "not a const case"
let constOfCase (c: DecisionTreeCase) = constOfDiscrim c.Discriminator
/// Compute pattern identity
let discrimsEq (g: TcGlobals) d1 d2 =
match d1, d2 with
| DecisionTreeTest.UnionCase (c1, _), DecisionTreeTest.UnionCase(c2, _) -> g.unionCaseRefEq c1 c2
| DecisionTreeTest.ArrayLength (n1, _), DecisionTreeTest.ArrayLength(n2, _) -> (n1=n2)
| DecisionTreeTest.Const c1, DecisionTreeTest.Const c2 -> (c1=c2)
| DecisionTreeTest.IsNull, DecisionTreeTest.IsNull -> true
| DecisionTreeTest.IsInst (srcTy1, tgtTy1), DecisionTreeTest.IsInst (srcTy2, tgtTy2) -> typeEquiv g srcTy1 srcTy2 && typeEquiv g tgtTy1 tgtTy2
| DecisionTreeTest.ActivePatternCase (_, _, _, vrefOpt1, n1, _), DecisionTreeTest.ActivePatternCase (_, _, _, vrefOpt2, n2, _) ->
match vrefOpt1, vrefOpt2 with
| Some (vref1, tinst1), Some (vref2, tinst2) -> valRefEq g vref1 vref2 && n1 = n2 && not (doesActivePatternHaveFreeTypars g vref1) && List.lengthsEqAndForall2 (typeEquiv g) tinst1 tinst2
| _ -> false (* for equality purposes these are considered unequal! This is because adhoc computed patterns have no identity. *)
| _ -> false
/// Redundancy of 'isinst' patterns
let isDiscrimSubsumedBy g amap m discrim taken =
discrimsEq g discrim taken
||
match taken, discrim with
| DecisionTreeTest.IsInst (_, tgtTy1), DecisionTreeTest.IsInst (_, tgtTy2) ->
computeWhatFailingTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = Implication.Fails
| DecisionTreeTest.IsNull, DecisionTreeTest.IsInst (_, tgtTy2) ->
computeWhatFailingNullTestImpliesAboutTypeTest g tgtTy2 = Implication.Fails
| DecisionTreeTest.IsInst (_, tgtTy1), DecisionTreeTest.IsNull ->
computeWhatFailingTypeTestImpliesAboutNullTest g tgtTy1 = Implication.Fails
| _ ->
false
type EdgeDiscrim = EdgeDiscrim of int * DecisionTreeTest * range
/// Choose a set of investigations that can be performed simultaneously
let rec chooseSimultaneousEdgeSet prev f l =
match l with
| [] -> [], []
| h :: t ->
match f prev h with
| Some (EdgeDiscrim(_, discrim, _) as edge) ->
let l, r = chooseSimultaneousEdgeSet (discrim::prev) f t
edge :: l, r
| None ->
let l, r = chooseSimultaneousEdgeSet prev f t
l, h :: r
/// Can we represent a integer discrimination as a 'switch'
let canCompactConstantClass c =
match c with
| Const.SByte _ | Const.Int16 _ | Const.Int32 _
| Const.Byte _ | Const.UInt16 _ | Const.UInt32 _
| Const.Char _ -> true
| _ -> false
/// Can two discriminators in a 'column' be decided simultaneously?
let discrimWithinSimultaneousClass g amap m discrim prev =
match discrim, prev with
| _, [] -> true
| DecisionTreeTest.Const _, DecisionTreeTest.Const _ :: _
| DecisionTreeTest.ArrayLength _, DecisionTreeTest.ArrayLength _ :: _
| DecisionTreeTest.UnionCase _, DecisionTreeTest.UnionCase _ :: _ -> true
| DecisionTreeTest.IsNull, _ ->
// Check that each previous test in the set, if successful, gives some information about this test
prev |> List.forall (fun edge ->
match edge with
| DecisionTreeTest.IsNull -> true
| DecisionTreeTest.IsInst (_, tgtTy1) -> computeWhatSuccessfulTypeTestImpliesAboutNullTest g tgtTy1 <> Implication.Nothing
| _ -> false)
| DecisionTreeTest.IsInst (_, tgtTy2), _ ->
// Check that each previous test in the set, if successful, gives some information about this test
prev |> List.forall (fun edge ->
match edge with
| DecisionTreeTest.IsNull -> true
| DecisionTreeTest.IsInst (_, tgtTy1) -> computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 <> Implication.Nothing
| _ -> false)
| DecisionTreeTest.ActivePatternCase (_, _, _, apatVrefOpt1, _, _),
DecisionTreeTest.ActivePatternCase (_, _, _, apatVrefOpt2, _, _) :: _ ->
match apatVrefOpt1, apatVrefOpt2 with
| Some (vref1, tinst1), Some (vref2, tinst2) -> valRefEq g vref1 vref2 && not (doesActivePatternHaveFreeTypars g vref1) && List.lengthsEqAndForall2 (typeEquiv g) tinst1 tinst2
| _ -> false (* for equality purposes these are considered different classes of discriminators! This is because adhoc computed patterns have no identity! *)
| _ -> false
let canInvestigate (pat: Pattern) =
match pat with
| TPat_null _ | TPat_isinst _ | TPat_exnconstr _ | TPat_unioncase _
| TPat_array _ | TPat_const _ | TPat_query _ | TPat_error _ -> true
| _ -> false
/// Decide the next pattern to investigate
let ChooseInvestigationPointLeftToRight frontiers =
match frontiers with
| Frontier (_i, actives, _) :: _t ->
let rec choose l =
match l with
| [] -> failwith "ChooseInvestigationPointLeftToRight: no non-immediate patterns in first rule"
| Active (_, _, pat) as active :: _ when canInvestigate pat -> active
| _ :: t -> choose t
choose actives
| [] -> failwith "ChooseInvestigationPointLeftToRight: no frontiers!"
[<return: Struct>]
let (|ConstNeedsDefaultCase|_|) c =
match c with
| Const.Decimal _
| Const.String _
| Const.Single _
| Const.Double _
| Const.Int16 _
| Const.UInt16 _
| Const.Int32 _
| Const.UInt32 _
| Const.Int64 _
| Const.UInt64 _
| Const.IntPtr _
| Const.UIntPtr _
| Const.Char _ -> ValueSome ()
| _ -> ValueNone
/// Build a dtree, equivalent to: TDSwitch("expr", edges, default, m)
///
/// Once we've chosen a particular active to investigate, we compile the
/// set of edges affected by this investigation into a switch.
///
/// - For DecisionTreeTest.ActivePatternCase(..., None, ...) there is only one edge
///
/// - For DecisionTreeTest.IsInst there are multiple edges, which we can't deal with
/// one switch, so we make an iterated if-then-else to cover the cases. We
/// should probably adjust the code to only choose one edge in this case.
///
/// - Compact integer switches become a single switch. Non-compact integer
/// switches, string switches and floating point switches are treated in the
/// same way as DecisionTreeTest.IsInst.
let rec BuildSwitch inpExprOpt g isNullFiltered expr edges dflt m =
match edges, dflt with
| [], None -> failwith "internal error: no edges and no default"
| [], Some dflt -> dflt
// Optimize the case where the match always succeeds
| [TCase(_, tree)], None -> tree
// 'isinst' tests where we have stored the result of the 'isinst' in a variable
// In this case the 'expr' already holds the result of the 'isinst' test.
| TCase(DecisionTreeTest.IsInst _, success) :: edges, dflt when Option.isSome inpExprOpt ->
TDSwitch(expr, [TCase(DecisionTreeTest.IsNull, BuildSwitch None g false expr edges dflt m)], Some success, m)
// isnull and isinst tests
| TCase((DecisionTreeTest.IsNull | DecisionTreeTest.IsInst _), _) as edge :: edges, dflt ->
// After an IsNull test, in the fallthrough branch (Some), we know the value is not null
let nullFiltered = match edge with TCase(DecisionTreeTest.IsNull, _) -> true | _ -> isNullFiltered
TDSwitch(expr, [edge], Some (BuildSwitch None g nullFiltered expr edges dflt m), m)
// All these should also always have default cases
| TCase(DecisionTreeTest.Const ConstNeedsDefaultCase, _) :: _, None ->
error(InternalError("inexhaustive match - need a default case!", m))
// Split string, float, uint64, int64, unativeint, nativeint matches into serial equality tests
| TCase((DecisionTreeTest.ArrayLength _ | DecisionTreeTest.Const (Const.Single _ | Const.Double _ | Const.String _ | Const.Decimal _ | Const.Int64 _ | Const.UInt64 _ | Const.IntPtr _ | Const.UIntPtr _)), _) :: _, Some dflt ->
List.foldBack
(fun (TCase(discrim, tree)) sofar ->
let testexpr = expr
let testexpr =
match discrim with
| DecisionTreeTest.ArrayLength(n, _) ->
let _v, vExpr, bind = mkCompGenLocalAndInvisibleBind g "testExpr" m testexpr
// Skip null check if we're in a null-filtered context
let test = mkILAsmCeq g m (mkLdlen g m vExpr) (mkInt g m n)
let finalTest = if isNullFiltered then test else mkLazyAnd g m (mkNonNullTest g m vExpr) test
mkLetBind m bind finalTest
| DecisionTreeTest.Const (Const.String "") ->
// Optimize empty string check to use null-safe length check
let _v, vExpr, bind = mkCompGenLocalAndInvisibleBind g "testExpr" m testexpr
let test = mkILAsmCeq g m (mkGetStringLength g m vExpr) (mkInt g m 0)
// Skip null check if we're in a null-filtered context
let finalTest = if isNullFiltered then test else mkLazyAnd g m (mkNonNullTest g m vExpr) test
mkLetBind m bind finalTest
| DecisionTreeTest.Const (Const.String _ as c) ->
mkCallEqualsOperator g m g.string_ty testexpr (Expr.Const (c, m, g.string_ty))
| DecisionTreeTest.Const (Const.Decimal _ as c) ->
mkCallEqualsOperator g m g.decimal_ty testexpr (Expr.Const (c, m, g.decimal_ty))
| DecisionTreeTest.Const (Const.Double _ | Const.Single _ | Const.Int64 _ | Const.UInt64 _ | Const.IntPtr _ | Const.UIntPtr _ as c) ->
mkILAsmCeq g m testexpr (Expr.Const (c, m, tyOfExpr g testexpr))
| _ -> error(InternalError("strange switch", m))
mkBoolSwitch m testexpr tree sofar)
edges
dflt
// Split integer and char matches into compact fragments which will themselves become switch statements.
| TCase(DecisionTreeTest.Const c, _) :: _, Some dflt when canCompactConstantClass c ->
let edgeCompare c1 c2 =
match constOfCase c1, constOfCase c2 with
| Const.SByte i1, Const.SByte i2 -> compare i1 i2
| Const.Int16 i1, Const.Int16 i2 -> compare i1 i2
| Const.Int32 i1, Const.Int32 i2 -> compare i1 i2
| Const.Byte i1, Const.Byte i2 -> compare i1 i2
| Const.UInt16 i1, Const.UInt16 i2 -> compare i1 i2
| Const.UInt32 i1, Const.UInt32 i2 -> compare i1 i2
| Const.Char c1, Const.Char c2 -> compare c1 c2
| _ -> failwith "illtyped term during pattern compilation"
let edges' = List.sortWith edgeCompare edges
let rec compactify curr edges =
match curr, edges with
| None, [] -> []
| Some last, [] -> [List.rev last]
| None, h :: t -> compactify (Some [h]) t
| Some (prev :: moreprev), h :: t ->
match constOfCase prev, constOfCase h with
| Const.SByte iprev, Const.SByte inext when int32 iprev + 1 = int32 inext ->
compactify (Some (h :: prev :: moreprev)) t
| Const.Int16 iprev, Const.Int16 inext when int32 iprev + 1 = int32 inext ->
compactify (Some (h :: prev :: moreprev)) t
| Const.Int32 iprev, Const.Int32 inext when iprev+1 = inext ->
compactify (Some (h :: prev :: moreprev)) t
| Const.Byte iprev, Const.Byte inext when int32 iprev + 1 = int32 inext ->
compactify (Some (h :: prev :: moreprev)) t
| Const.UInt16 iprev, Const.UInt16 inext when int32 iprev+1 = int32 inext ->
compactify (Some (h :: prev :: moreprev)) t
| Const.UInt32 iprev, Const.UInt32 inext when int32 iprev+1 = int32 inext ->
compactify (Some (h :: prev :: moreprev)) t
| Const.Char cprev, Const.Char cnext when (int32 cprev + 1 = int32 cnext) ->
compactify (Some (h :: prev :: moreprev)) t
| _ -> (List.rev (prev :: moreprev)) :: compactify None edges
| _ -> failwith "internal error: compactify"
let edgeGroups = compactify None edges'
(edgeGroups, dflt) ||> List.foldBack (fun edgeGroup sofar -> TDSwitch(expr, edgeGroup, Some sofar, m))
// For a total pattern match, run the active pattern, bind the result and
// recursively build a switch in the choice type
| TCase(DecisionTreeTest.ActivePatternCase _, _) :: _, _ ->
error(InternalError("DecisionTreeTest.ActivePatternCase should have been eliminated", m))
// For a complete match, optimize one test to be the default
| TCase(_, tree) :: rest, None -> TDSwitch (expr, rest, Some tree, m)
// Otherwise let codegen make the choices
| _ -> TDSwitch (expr, edges, dflt, m)
#if DEBUG
let rec layoutPat pat =
match pat with
| TPat_query (_, pat, _) -> Layout.(--) (Layout.wordL (TaggedText.tagText "query")) (layoutPat pat)
| TPat_wild _ -> Layout.wordL (TaggedText.tagText "wild")
| TPat_as _ -> Layout.wordL (TaggedText.tagText "var")
| TPat_tuple (_, pats, _, _)
| TPat_array (pats, _, _) -> Layout.bracketL (Layout.tupleL (List.map layoutPat pats))
| _ -> Layout.wordL (TaggedText.tagText "?")
#endif
let mkFrontiers investigations clauseNumber =
investigations |> List.map (fun (actives, valMap) -> Frontier(clauseNumber, actives, valMap))
let singleFalseInvestigationPoint = [| false |]
// Search for pattern decision points that are decided "one at a time" - i.e. where there is no
// multi-way switching. For example partial active patterns
let rec investigationPoints inpPat =
match inpPat with
| TPat_query((_, _, _, _, _, apinfo), subPat, _) ->
Array.prepend (not apinfo.IsTotal) (investigationPoints subPat)
| TPat_isinst(_, _tgtTy, subPatOpt, _) ->
match subPatOpt with
| None -> singleFalseInvestigationPoint
| Some subPat -> Array.prepend false (investigationPoints subPat)
| TPat_as(subPat, _, _) -> investigationPoints subPat
| TPat_disjs(subPats, _)
| TPat_conjs(subPats, _)
| TPat_tuple(_, subPats, _, _)
| TPat_exnconstr(_, subPats, _)
| TPat_recd(_, _, subPats, _) ->
subPats
|> Seq.collect investigationPoints
|> Seq.toArray
| TPat_array (subPats, _, _)
| TPat_unioncase (_, _, subPats, _) ->
subPats
|> Seq.collect investigationPoints
|> Seq.toArray
|> Array.prepend false
| TPat_null _
| TPat_const _ -> singleFalseInvestigationPoint
| TPat_wild _
| TPat_error _ -> [||]
let rec erasePartialPatterns inpPat =
match inpPat with
| TPat_query ((expr, resTys, retKind, apatVrefOpt, idx, apinfo), p, m) ->
if apinfo.IsTotal then TPat_query ((expr, resTys, retKind, apatVrefOpt, idx, apinfo), erasePartialPatterns p, m)
else TPat_disjs ([], m) (* always fail *)
| TPat_as (p, x, m) -> TPat_as (erasePartialPatterns p, x, m)
| TPat_disjs (subPats, m) -> TPat_disjs(erasePartials subPats, m)
| TPat_conjs(subPats, m) -> TPat_conjs(erasePartials subPats, m)
| TPat_tuple (tupInfo, subPats, x, m) -> TPat_tuple(tupInfo, erasePartials subPats, x, m)
| TPat_exnconstr(x, subPats, m) -> TPat_exnconstr(x, erasePartials subPats, m)
| TPat_array (subPats, x, m) -> TPat_array (erasePartials subPats, x, m)
| TPat_unioncase (x, y, ps, m) -> TPat_unioncase (x, y, erasePartials ps, m)
| TPat_recd (x, y, ps, m) -> TPat_recd (x, y, List.map erasePartialPatterns ps, m)
| TPat_isinst (x, y, subPatOpt, m) -> TPat_isinst (x, y, Option.map erasePartialPatterns subPatOpt, m)
| TPat_const _
| TPat_wild _
| TPat_null _
| TPat_error _ -> inpPat
and erasePartials inps =
List.map erasePartialPatterns inps
let ReportUnusedTargets (clauses: MatchClause list) dtree =
match dtree, clauses with
| TDSuccess _, [ _ ] -> ()
| _ ->
let used = HashSet<_>(accTargetsOfDecisionTree dtree [], HashIdentity.Structural)
clauses |> List.iteri (fun i c ->
if not (used.Contains i) then
let m =
match c.BoundVals, c.GuardExpr with
| [], Some guard -> guard.Range
| [ bound ], None -> bound.Id.idRange
| [ _ ], Some guard -> guard.Range
| rest, None ->
match rest with
| [ head ] -> head.Id.idRange
| _ -> c.Pattern.Range
| _, Some guard -> guard.Range
withStartEnd c.Range.Start m.End m
|> RuleNeverMatched
|> warning)
let rec isPatternDisjunctive inpPat =
match inpPat with
| TPat_query (_, subPat, _) -> isPatternDisjunctive subPat
| TPat_as (subPat, _, _) -> isPatternDisjunctive subPat
| TPat_disjs (subPats, _) -> subPats.Length > 1 || List.exists isPatternDisjunctive subPats
| TPat_conjs(subPats, _)
| TPat_tuple (_, subPats, _, _)
| TPat_exnconstr(_, subPats, _)
| TPat_array (subPats, _, _)
| TPat_unioncase (_, _, subPats, _)
| TPat_recd (_, _, subPats, _) -> List.exists isPatternDisjunctive subPats
| TPat_isinst (_, _, subPatOpt, _) -> Option.exists isPatternDisjunctive subPatOpt
| TPat_const _ -> false
| TPat_wild _ -> false
| TPat_null _ -> false
| TPat_error _ -> false
//---------------------------------------------------------------------------
// The algorithm
//---------------------------------------------------------------------------
let CompilePatternBasic
(g: TcGlobals) denv amap tcVal infoReader mExpr mMatch
warnOnUnused
warnOnIncomplete
actionOnFailure
(origInputVal, origInputValTypars, _origInputExprOpt: Expr option)
(clauses: MatchClause list)
inputTy
resultTy =
// Add the targets to a match builder.
// Note the input expression has already been evaluated and saved into a variable,
// hence no need for a new sequence point.
let matchBuilder = MatchBuilder (DebugPointAtBinding.NoneAtInvisible, mExpr)
clauses |> List.iter (fun clause -> matchBuilder.AddTarget clause.Target |> ignore)