-
Notifications
You must be signed in to change notification settings - Fork 859
Expand file tree
/
Copy pathTypedTreeOps.FreeVars.fs
More file actions
1544 lines (1278 loc) · 61.7 KB
/
TypedTreeOps.FreeVars.fs
File metadata and controls
1544 lines (1278 loc) · 61.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.
/// Defines derived expression manipulation and construction functions.
namespace FSharp.Compiler.TypedTreeOps
open System
open System.CodeDom.Compiler
open System.Collections.Generic
open System.Collections.Immutable
open Internal.Utilities
open Internal.Utilities.Collections
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open Internal.Utilities.Rational
open FSharp.Compiler.IO
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.CompilerGlobalState
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.Features
open FSharp.Compiler.Syntax
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.SyntaxTreeOps
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Text.Layout
open FSharp.Compiler.Text.LayoutRender
open FSharp.Compiler.Text.TaggedText
open FSharp.Compiler.Xml
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeBasics
#if !NO_TYPEPROVIDERS
open FSharp.Compiler.TypeProviders
#endif
[<AutoOpen>]
module internal FreeTypeVars =
//---------------------------------------------------------------------------
// Find all type variables in a type, apart from those that have had
// an equation assigned by type inference.
//---------------------------------------------------------------------------
let emptyFreeLocals = Zset.empty valOrder
let unionFreeLocals s1 s2 =
if s1 === emptyFreeLocals then s2
elif s2 === emptyFreeLocals then s1
else Zset.union s1 s2
let emptyFreeRecdFields = Zset.empty recdFieldRefOrder
let unionFreeRecdFields s1 s2 =
if s1 === emptyFreeRecdFields then s2
elif s2 === emptyFreeRecdFields then s1
else Zset.union s1 s2
let emptyFreeUnionCases = Zset.empty unionCaseRefOrder
let unionFreeUnionCases s1 s2 =
if s1 === emptyFreeUnionCases then s2
elif s2 === emptyFreeUnionCases then s1
else Zset.union s1 s2
let emptyFreeTycons = Zset.empty tyconOrder
let unionFreeTycons s1 s2 =
if s1 === emptyFreeTycons then s2
elif s2 === emptyFreeTycons then s1
else Zset.union s1 s2
let typarOrder =
{ new IComparer<Typar> with
member x.Compare(v1: Typar, v2: Typar) = compareBy v1 v2 _.Stamp
}
let emptyFreeTypars = Zset.empty typarOrder
let unionFreeTypars s1 s2 =
if s1 === emptyFreeTypars then s2
elif s2 === emptyFreeTypars then s1
else Zset.union s1 s2
let emptyFreeTyvars =
{
FreeTycons = emptyFreeTycons
// The summary of values used as trait solutions
FreeTraitSolutions = emptyFreeLocals
FreeTypars = emptyFreeTypars
}
let isEmptyFreeTyvars ftyvs =
Zset.isEmpty ftyvs.FreeTypars && Zset.isEmpty ftyvs.FreeTycons
let unionFreeTyvars fvs1 fvs2 =
if fvs1 === emptyFreeTyvars then
fvs2
else if fvs2 === emptyFreeTyvars then
fvs1
else
{
FreeTycons = unionFreeTycons fvs1.FreeTycons fvs2.FreeTycons
FreeTraitSolutions = unionFreeLocals fvs1.FreeTraitSolutions fvs2.FreeTraitSolutions
FreeTypars = unionFreeTypars fvs1.FreeTypars fvs2.FreeTypars
}
type FreeVarOptions =
{
canCache: bool
collectInTypes: bool
includeLocalTycons: bool
includeTypars: bool
includeLocalTyconReprs: bool
includeRecdFields: bool
includeUnionCases: bool
includeLocals: bool
templateReplacement: ((TyconRef -> bool) * Typars) option
stackGuard: StackGuard option
}
member this.WithTemplateReplacement(f, typars) =
{ this with
templateReplacement = Some(f, typars)
}
let CollectAllNoCaching =
{
canCache = false
collectInTypes = true
includeLocalTycons = true
includeLocalTyconReprs = true
includeRecdFields = true
includeUnionCases = true
includeTypars = true
includeLocals = true
templateReplacement = None
stackGuard = None
}
let CollectTyparsNoCaching =
{
canCache = false
collectInTypes = true
includeLocalTycons = false
includeTypars = true
includeLocalTyconReprs = false
includeRecdFields = false
includeUnionCases = false
includeLocals = false
templateReplacement = None
stackGuard = None
}
let CollectLocalsNoCaching =
{
canCache = false
collectInTypes = false
includeLocalTycons = false
includeTypars = false
includeLocalTyconReprs = false
includeRecdFields = false
includeUnionCases = false
includeLocals = true
templateReplacement = None
stackGuard = None
}
let CollectTyparsAndLocalsNoCaching =
{
canCache = false
collectInTypes = true
includeLocalTycons = false
includeLocalTyconReprs = false
includeRecdFields = false
includeUnionCases = false
includeTypars = true
includeLocals = true
templateReplacement = None
stackGuard = None
}
let CollectAll =
{
canCache = false
collectInTypes = true
includeLocalTycons = true
includeLocalTyconReprs = true
includeRecdFields = true
includeUnionCases = true
includeTypars = true
includeLocals = true
templateReplacement = None
stackGuard = None
}
let CollectTyparsAndLocalsImpl stackGuardOpt = // CollectAll
{
canCache = true // only cache for this one
collectInTypes = true
includeTypars = true
includeLocals = true
includeLocalTycons = false
includeLocalTyconReprs = false
includeRecdFields = false
includeUnionCases = false
templateReplacement = None
stackGuard = stackGuardOpt
}
let CollectTyparsAndLocals = CollectTyparsAndLocalsImpl None
let CollectTypars = CollectTyparsAndLocals
let CollectLocals = CollectTyparsAndLocals
let CollectTyparsAndLocalsWithStackGuard () =
let stackGuard = StackGuard("AccFreeVarsStackGuardDepth")
CollectTyparsAndLocalsImpl(Some stackGuard)
let CollectLocalsWithStackGuard () = CollectTyparsAndLocalsWithStackGuard()
let accFreeLocalTycon opts x acc =
if not opts.includeLocalTycons then
acc
else if Zset.contains x acc.FreeTycons then
acc
else
{ acc with
FreeTycons = Zset.add x acc.FreeTycons
}
let rec accFreeTycon opts (tcref: TyconRef) acc =
let acc =
match opts.templateReplacement with
| Some(isTemplateTyconRef, cloFreeTyvars) when isTemplateTyconRef tcref ->
let cloInst = List.map mkTyparTy cloFreeTyvars
accFreeInTypes opts cloInst acc
| _ -> acc
if not opts.includeLocalTycons then
acc
elif tcref.IsLocalRef then
accFreeLocalTycon opts tcref.ResolvedTarget acc
else
acc
and boundTypars opts tps acc =
// Bound type vars form a recursively-referential set due to constraints, e.g. A: I<B>, B: I<A>
// So collect up free vars in all constraints first, then bind all variables
let acc =
List.foldBack (fun (tp: Typar) acc -> accFreeInTyparConstraints opts tp.Constraints acc) tps acc
List.foldBack
(fun tp acc ->
{ acc with
FreeTypars = Zset.remove tp acc.FreeTypars
})
tps
acc
and accFreeInTyparConstraints opts cxs acc =
List.foldBack (accFreeInTyparConstraint opts) cxs acc
and accFreeInTyparConstraint opts tpc acc =
match tpc with
| TyparConstraint.CoercesTo(ty, _) -> accFreeInType opts ty acc
| TyparConstraint.MayResolveMember(traitInfo, _) -> accFreeInTrait opts traitInfo acc
| TyparConstraint.DefaultsTo(_, defaultTy, _) -> accFreeInType opts defaultTy acc
| TyparConstraint.SimpleChoice(tys, _) -> accFreeInTypes opts tys acc
| TyparConstraint.IsEnum(underlyingTy, _) -> accFreeInType opts underlyingTy acc
| TyparConstraint.IsDelegate(argTys, retTy, _) -> accFreeInType opts argTys (accFreeInType opts retTy acc)
| TyparConstraint.SupportsComparison _
| TyparConstraint.SupportsEquality _
| TyparConstraint.SupportsNull _
| TyparConstraint.NotSupportsNull _
| TyparConstraint.IsNonNullableStruct _
| TyparConstraint.IsReferenceType _
| TyparConstraint.IsUnmanaged _
| TyparConstraint.AllowsRefStruct _
| TyparConstraint.RequiresDefaultConstructor _ -> acc
and accFreeInTrait opts (TTrait(tys, _, _, argTys, retTy, _, sln)) acc =
Option.foldBack
(accFreeInTraitSln opts)
sln.Value
(accFreeInTypes opts tys (accFreeInTypes opts argTys (Option.foldBack (accFreeInType opts) retTy acc)))
and accFreeInTraitSln opts sln acc =
match sln with
| ILMethSln(ty, _, _, minst, staticTyOpt) ->
Option.foldBack (accFreeInType opts) staticTyOpt (accFreeInType opts ty (accFreeInTypes opts minst acc))
| FSMethSln(ty, vref, minst, staticTyOpt) ->
Option.foldBack
(accFreeInType opts)
staticTyOpt
(accFreeInType opts ty (accFreeValRefInTraitSln opts vref (accFreeInTypes opts minst acc)))
| FSAnonRecdFieldSln(_anonInfo, tinst, _n) -> accFreeInTypes opts tinst acc
| FSRecdFieldSln(tinst, _rfref, _isSet) -> accFreeInTypes opts tinst acc
| BuiltInSln -> acc
| ClosedExprSln _ -> acc // nothing to accumulate because it's a closed expression referring only to erasure of provided method calls
and accFreeLocalValInTraitSln _opts v fvs =
if Zset.contains v fvs.FreeTraitSolutions then
fvs
else
{ fvs with
FreeTraitSolutions = Zset.add v fvs.FreeTraitSolutions
}
and accFreeValRefInTraitSln opts (vref: ValRef) fvs =
if vref.IsLocalRef then
accFreeLocalValInTraitSln opts vref.ResolvedTarget fvs
else
// non-local values do not contain free variables
fvs
and accFreeTyparRef opts (tp: Typar) acc =
if not opts.includeTypars then
acc
else if Zset.contains tp acc.FreeTypars then
acc
else
accFreeInTyparConstraints
opts
tp.Constraints
{ acc with
FreeTypars = Zset.add tp acc.FreeTypars
}
and accFreeInType opts ty acc =
match stripTyparEqns ty with
| TType_tuple(tupInfo, l) -> accFreeInTypes opts l (accFreeInTupInfo opts tupInfo acc)
| TType_anon(anonInfo, l) -> accFreeInTypes opts l (accFreeInTupInfo opts anonInfo.TupInfo acc)
| TType_app(tcref, tinst, _) ->
let acc = accFreeTycon opts tcref acc
match tinst with
| [] -> acc // optimization to avoid unneeded call
| [ h ] -> accFreeInType opts h acc // optimization to avoid unneeded call
| _ -> accFreeInTypes opts tinst acc
| TType_ucase(UnionCaseRef(tcref, _), tinst) -> accFreeInTypes opts tinst (accFreeTycon opts tcref acc)
| TType_fun(domainTy, rangeTy, _) -> accFreeInType opts domainTy (accFreeInType opts rangeTy acc)
| TType_var(r, _) -> accFreeTyparRef opts r acc
| TType_forall(tps, r) -> unionFreeTyvars (boundTypars opts tps (freeInType opts r)) acc
| TType_measure unt -> accFreeInMeasure opts unt acc
and accFreeInTupInfo _opts unt acc =
match unt with
| TupInfo.Const _ -> acc
and accFreeInMeasure opts unt acc =
List.foldBack (fun (tp, _) acc -> accFreeTyparRef opts tp acc) (ListMeasureVarOccsWithNonZeroExponents unt) acc
and accFreeInTypes opts tys acc =
match tys with
| [] -> acc
| h :: t -> accFreeInTypes opts t (accFreeInType opts h acc)
and freeInType opts ty = accFreeInType opts ty emptyFreeTyvars
and accFreeInVal opts (v: Val) acc = accFreeInType opts v.val_type acc
let freeInTypes opts tys = accFreeInTypes opts tys emptyFreeTyvars
let freeInVal opts v = accFreeInVal opts v emptyFreeTyvars
let freeInTyparConstraints opts v =
accFreeInTyparConstraints opts v emptyFreeTyvars
let accFreeInTypars opts tps acc =
List.foldBack (accFreeTyparRef opts) tps acc
let rec addFreeInModuleTy (mtyp: ModuleOrNamespaceType) acc =
QueueList.foldBack
(typeOfVal >> accFreeInType CollectAllNoCaching)
mtyp.AllValsAndMembers
(QueueList.foldBack
(fun (mspec: ModuleOrNamespace) acc -> addFreeInModuleTy mspec.ModuleOrNamespaceType acc)
mtyp.AllEntities
acc)
let freeInModuleTy mtyp = addFreeInModuleTy mtyp emptyFreeTyvars
//--------------------------------------------------------------------------
// Free in type, left-to-right order preserved. This is used to determine the
// order of type variables for top-level definitions based on their signature,
// so be careful not to change the order. We accumulate in reverse
// order.
//--------------------------------------------------------------------------
let emptyFreeTyparsLeftToRight = []
let unionFreeTyparsLeftToRight fvs1 fvs2 =
ListSet.unionFavourRight typarEq fvs1 fvs2
let rec boundTyparsLeftToRight g cxFlag thruFlag acc tps =
// Bound type vars form a recursively-referential set due to constraints, e.g. A: I<B>, B: I<A>
// So collect up free vars in all constraints first, then bind all variables
List.fold (fun acc (tp: Typar) -> accFreeInTyparConstraintsLeftToRight g cxFlag thruFlag acc tp.Constraints) tps acc
and accFreeInTyparConstraintsLeftToRight g cxFlag thruFlag acc cxs =
List.fold (accFreeInTyparConstraintLeftToRight g cxFlag thruFlag) acc cxs
and accFreeInTyparConstraintLeftToRight g cxFlag thruFlag acc tpc =
match tpc with
| TyparConstraint.CoercesTo(ty, _) -> accFreeInTypeLeftToRight g cxFlag thruFlag acc ty
| TyparConstraint.MayResolveMember(traitInfo, _) -> accFreeInTraitLeftToRight g cxFlag thruFlag acc traitInfo
| TyparConstraint.DefaultsTo(_, defaultTy, _) -> accFreeInTypeLeftToRight g cxFlag thruFlag acc defaultTy
| TyparConstraint.SimpleChoice(tys, _) -> accFreeInTypesLeftToRight g cxFlag thruFlag acc tys
| TyparConstraint.IsEnum(underlyingTy, _) -> accFreeInTypeLeftToRight g cxFlag thruFlag acc underlyingTy
| TyparConstraint.IsDelegate(argTys, retTy, _) ->
accFreeInTypeLeftToRight g cxFlag thruFlag (accFreeInTypeLeftToRight g cxFlag thruFlag acc argTys) retTy
| TyparConstraint.SupportsComparison _
| TyparConstraint.SupportsEquality _
| TyparConstraint.SupportsNull _
| TyparConstraint.NotSupportsNull _
| TyparConstraint.IsNonNullableStruct _
| TyparConstraint.IsUnmanaged _
| TyparConstraint.AllowsRefStruct _
| TyparConstraint.IsReferenceType _
| TyparConstraint.RequiresDefaultConstructor _ -> acc
and accFreeInTraitLeftToRight g cxFlag thruFlag acc (TTrait(tys, _, _, argTys, retTy, _, _)) =
let acc = accFreeInTypesLeftToRight g cxFlag thruFlag acc tys
let acc = accFreeInTypesLeftToRight g cxFlag thruFlag acc argTys
let acc = Option.fold (accFreeInTypeLeftToRight g cxFlag thruFlag) acc retTy
acc
and accFreeTyparRefLeftToRight g cxFlag thruFlag acc (tp: Typar) =
if ListSet.contains typarEq tp acc then
acc
else
let acc = ListSet.insert typarEq tp acc
if cxFlag then
accFreeInTyparConstraintsLeftToRight g cxFlag thruFlag acc tp.Constraints
else
acc
and accFreeInTypeLeftToRight g cxFlag thruFlag acc ty =
match (if thruFlag then stripTyEqns g ty else stripTyparEqns ty) with
| TType_anon(anonInfo, anonTys) ->
let acc = accFreeInTupInfoLeftToRight g cxFlag thruFlag acc anonInfo.TupInfo
accFreeInTypesLeftToRight g cxFlag thruFlag acc anonTys
| TType_tuple(tupInfo, tupTys) ->
let acc = accFreeInTupInfoLeftToRight g cxFlag thruFlag acc tupInfo
accFreeInTypesLeftToRight g cxFlag thruFlag acc tupTys
| TType_app(_, tinst, _) -> accFreeInTypesLeftToRight g cxFlag thruFlag acc tinst
| TType_ucase(_, tinst) -> accFreeInTypesLeftToRight g cxFlag thruFlag acc tinst
| TType_fun(domainTy, rangeTy, _) ->
let dacc = accFreeInTypeLeftToRight g cxFlag thruFlag acc domainTy
accFreeInTypeLeftToRight g cxFlag thruFlag dacc rangeTy
| TType_var(r, _) -> accFreeTyparRefLeftToRight g cxFlag thruFlag acc r
| TType_forall(tps, r) ->
let racc = accFreeInTypeLeftToRight g cxFlag thruFlag emptyFreeTyparsLeftToRight r
unionFreeTyparsLeftToRight (boundTyparsLeftToRight g cxFlag thruFlag tps racc) acc
| TType_measure unt ->
let mvars = ListMeasureVarOccsWithNonZeroExponents unt
List.foldBack (fun (tp, _) acc -> accFreeTyparRefLeftToRight g cxFlag thruFlag acc tp) mvars acc
and accFreeInTupInfoLeftToRight _g _cxFlag _thruFlag acc unt =
match unt with
| TupInfo.Const _ -> acc
and accFreeInTypesLeftToRight g cxFlag thruFlag acc tys =
match tys with
| [] -> acc
| h :: t -> accFreeInTypesLeftToRight g cxFlag thruFlag (accFreeInTypeLeftToRight g cxFlag thruFlag acc h) t
let freeInTypeLeftToRight g thruFlag ty =
accFreeInTypeLeftToRight g true thruFlag emptyFreeTyparsLeftToRight ty
|> List.rev
let freeInTypesLeftToRight g thruFlag ty =
accFreeInTypesLeftToRight g true thruFlag emptyFreeTyparsLeftToRight ty
|> List.rev
let freeInTypesLeftToRightSkippingConstraints g ty =
accFreeInTypesLeftToRight g false true emptyFreeTyparsLeftToRight ty |> List.rev
[<AutoOpen>]
module internal MemberRepresentation =
//--------------------------------------------------------------------------
// Values representing member functions on F# types
//--------------------------------------------------------------------------
// Pull apart the type for an F# value that represents an object model method. Do not strip off a 'unit' argument.
// Review: Should GetMemberTypeInFSharpForm have any other direct callers?
let GetMemberTypeInFSharpForm g (memberFlags: SynMemberFlags) arities ty m =
let tps, argInfos, retTy, retInfo = GetValReprTypeInFSharpForm g arities ty m
let argInfos =
if memberFlags.IsInstance then
match argInfos with
| [] ->
errorR (InternalError("value does not have a valid member type", m))
argInfos
| _ :: t -> t
else
argInfos
tps, argInfos, retTy, retInfo
// Check that an F# value represents an object model method.
// It will also always have an arity (inferred from syntax).
let checkMemberVal membInfo arity m =
match membInfo, arity with
| None, _ -> error (InternalError("checkMemberVal - no membInfo", m))
| _, None -> error (InternalError("checkMemberVal - no arity", m))
| Some membInfo, Some arity -> (membInfo, arity)
let checkMemberValRef (vref: ValRef) =
checkMemberVal vref.MemberInfo vref.ValReprInfo vref.Range
let GetFSharpViewOfReturnType (g: TcGlobals) retTy =
match retTy with
| None -> g.unit_ty
| Some retTy -> retTy
type TraitConstraintInfo with
member traitInfo.GetReturnType(g: TcGlobals) =
GetFSharpViewOfReturnType g traitInfo.CompiledReturnType
member traitInfo.GetObjectType() =
match traitInfo.MemberFlags.IsInstance, traitInfo.CompiledObjectAndArgumentTypes with
| true, objTy :: _ -> Some objTy
| _ -> None
// For static property traits:
// ^T: (static member Zero: ^T)
// The inner representation is
// TraitConstraintInfo([^T], get_Zero, Property, Static, [], ^T)
// and this returns
// []
//
// For the logically equivalent static get_property traits (i.e. the property as a get_ method)
// ^T: (static member get_Zero: unit -> ^T)
// The inner representation is
// TraitConstraintInfo([^T], get_Zero, Member, Static, [], ^T)
// and this returns
// []
//
// For instance property traits
// ^T: (member Length: int)
// The inner TraitConstraintInfo representation is
// TraitConstraintInfo([^T], get_Length, Property, Instance, [], int)
// and this returns
// []
//
// For the logically equivalent instance get_property traits (i.e. the property as a get_ method)
// ^T: (member get_Length: unit -> int)
// The inner TraitConstraintInfo representation is
// TraitConstraintInfo([^T], get_Length, Method, Instance, [^T], int)
// and this returns
// []
//
// For index property traits
// ^T: (member Item: int -> int with get)
// The inner TraitConstraintInfo representation is
// TraitConstraintInfo([^T], get_Item, Property, Instance, [^T; int], int)
// and this returns
// [int]
member traitInfo.GetCompiledArgumentTypes() =
match traitInfo.MemberFlags.IsInstance, traitInfo.CompiledObjectAndArgumentTypes with
| true, _ :: argTys -> argTys
| _, argTys -> argTys
// For static property traits:
// ^T: (static member Zero: ^T)
// The inner representation is
// TraitConstraintInfo([^T], get_Zero, PropertyGet, Static, [], ^T)
// and this returns
// []
//
// For the logically equivalent static get_property traits (i.e. the property as a get_ method)
// ^T: (static member get_Zero: unit -> ^T)
// The inner representation is
// TraitConstraintInfo([^T], get_Zero, Member, Static, [], ^T)
// and this returns
// [unit]
//
// For instance property traits
// ^T: (member Length: int)
// The inner TraitConstraintInfo representation is
// TraitConstraintInfo([^T], get_Length, PropertyGet, Instance, [^T], int)
// and this views the constraint as if it were
// []
//
// For the logically equivalent instance get_property traits (i.e. the property as a get_ method)
// ^T: (member get_Length: unit -> int)
// The inner TraitConstraintInfo representation is
// TraitConstraintInfo([^T], get_Length, Member, Instance, [^T], int)
// and this returns
// [unit]
//
// For index property traits
// (member Item: int -> int with get)
// The inner TraitConstraintInfo representation is
// TraitConstraintInfo([^T], get_Item, PropertyGet, [^T; int], int)
// and this returns
// [int]
member traitInfo.GetLogicalArgumentTypes(g: TcGlobals) =
match traitInfo.GetCompiledArgumentTypes(), traitInfo.MemberFlags.MemberKind with
| [], SynMemberKind.Member -> [ g.unit_ty ]
| argTys, _ -> argTys
member traitInfo.MemberDisplayNameCore =
let traitName0 = traitInfo.MemberLogicalName
match traitInfo.MemberFlags.MemberKind with
| SynMemberKind.PropertyGet
| SynMemberKind.PropertySet ->
match TryChopPropertyName traitName0 with
| Some nm -> nm
| None -> traitName0
| _ -> traitName0
/// Get the key associated with the member constraint.
member traitInfo.GetWitnessInfo() =
let (TTrait(tys, nm, memFlags, objAndArgTys, rty, _, _)) = traitInfo
TraitWitnessInfo(tys, nm, memFlags, objAndArgTys, rty)
/// Get information about the trait constraints for a set of typars.
/// Put these in canonical order.
let GetTraitConstraintInfosOfTypars g (tps: Typars) =
[
for tp in tps do
for cx in tp.Constraints do
match cx with
| TyparConstraint.MayResolveMember(traitInfo, _) -> traitInfo
| _ -> ()
]
|> ListSet.setify (traitsAEquiv g TypeEquivEnv.EmptyIgnoreNulls)
|> List.sortBy (fun traitInfo -> traitInfo.MemberLogicalName, traitInfo.GetCompiledArgumentTypes().Length)
/// Get information about the runtime witnesses needed for a set of generalized typars
let GetTraitWitnessInfosOfTypars g numParentTypars typars =
let typs = typars |> List.skip numParentTypars
let cxs = GetTraitConstraintInfosOfTypars g typs
cxs |> List.map (fun cx -> cx.GetWitnessInfo())
/// Count the number of type parameters on the enclosing type
let CountEnclosingTyparsOfActualParentOfVal (v: Val) =
match v.ValReprInfo with
| None -> 0
| Some _ ->
if v.IsExtensionMember then 0
elif not v.IsMember then 0
else v.MemberApparentEntity.TyparsNoRange.Length
let GetValReprTypeInCompiledForm g valReprInfo numEnclosingTypars ty m =
let tps, paramArgInfos, retTy, retInfo =
GetValReprTypeInFSharpForm g valReprInfo ty m
let witnessInfos = GetTraitWitnessInfosOfTypars g numEnclosingTypars tps
// Eliminate lone single unit arguments
let paramArgInfos =
match paramArgInfos, valReprInfo.ArgInfos with
// static member and module value unit argument elimination
| [ [ (_argType, _) ] ], [ [] ] ->
//assert isUnitTy g argType
[ [] ]
// instance member unit argument elimination
| [ objInfo; [ (_argType, _) ] ], [ [ _objArg ]; [] ] ->
//assert isUnitTy g argType
[ objInfo; [] ]
| _ -> paramArgInfos
let retTy = if isUnitTy g retTy then None else Some retTy
(tps, witnessInfos, paramArgInfos, retTy, retInfo)
// Pull apart the type for an F# value that represents an object model method
// and see the "member" form for the type, i.e.
// detect methods with no arguments by (effectively) looking for single argument type of 'unit'.
// The analysis is driven of the inferred arity information for the value.
//
// This is used not only for the compiled form - it's also used for all type checking and object model
// logic such as determining if abstract methods have been implemented or not, and how
// many arguments the method takes etc.
let GetMemberTypeInMemberForm g memberFlags valReprInfo numEnclosingTypars ty m =
let tps, paramArgInfos, retTy, retInfo =
GetMemberTypeInFSharpForm g memberFlags valReprInfo ty m
let witnessInfos = GetTraitWitnessInfosOfTypars g numEnclosingTypars tps
// Eliminate lone single unit arguments
let paramArgInfos =
match paramArgInfos, valReprInfo.ArgInfos with
// static member and module value unit argument elimination
| [ [ (argTy, _) ] ], [ [] ] ->
assert isUnitTy g argTy
[ [] ]
// instance member unit argument elimination
| [ [ (argTy, _) ] ], [ [ _objArg ]; [] ] ->
assert isUnitTy g argTy
[ [] ]
| _ -> paramArgInfos
let retTy = if isUnitTy g retTy then None else Some retTy
(tps, witnessInfos, paramArgInfos, retTy, retInfo)
let GetTypeOfMemberInMemberForm g (vref: ValRef) =
//assert (not vref.IsExtensionMember)
let membInfo, valReprInfo = checkMemberValRef vref
let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal vref.Deref
GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars vref.Type vref.Range
let GetTypeOfMemberInFSharpForm g (vref: ValRef) =
let membInfo, valReprInfo = checkMemberValRef vref
GetMemberTypeInFSharpForm g membInfo.MemberFlags valReprInfo vref.Type vref.Range
let PartitionValTyparsForApparentEnclosingType g (v: Val) =
match v.ValReprInfo with
| None -> error (InternalError("PartitionValTypars: not a top value", v.Range))
| Some arities ->
let fullTypars, _ = destTopForallTy g arities v.Type
let parent = v.MemberApparentEntity
let parentTypars = parent.TyparsNoRange
let nparentTypars = parentTypars.Length
if nparentTypars <= fullTypars.Length then
let memberParentTypars, memberMethodTypars = List.splitAt nparentTypars fullTypars
let memberToParentInst, tinst =
mkTyparToTyparRenaming memberParentTypars parentTypars
Some(parentTypars, memberParentTypars, memberMethodTypars, memberToParentInst, tinst)
else
None
/// Match up the type variables on an member value with the type
/// variables on the apparent enclosing type
let PartitionValTypars g (v: Val) =
match v.ValReprInfo with
| None -> error (InternalError("PartitionValTypars: not a top value", v.Range))
| Some arities ->
if v.IsExtensionMember then
let fullTypars, _ = destTopForallTy g arities v.Type
Some([], [], fullTypars, emptyTyparInst, [])
else
PartitionValTyparsForApparentEnclosingType g v
let PartitionValRefTypars g (vref: ValRef) = PartitionValTypars g vref.Deref
/// Get the arguments for an F# value that represents an object model method
let ArgInfosOfMemberVal g (v: Val) =
let membInfo, valReprInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range
let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal v
let _, _, arginfos, _, _ =
GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars v.Type v.Range
arginfos
let ArgInfosOfMember g (vref: ValRef) = ArgInfosOfMemberVal g vref.Deref
/// Get the property "type" (getter return type) for an F# value that represents a getter or setter
/// of an object model property.
let ReturnTypeOfPropertyVal g (v: Val) =
let membInfo, valReprInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range
match membInfo.MemberFlags.MemberKind with
| SynMemberKind.PropertySet ->
let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal v
let _, _, arginfos, _, _ =
GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars v.Type v.Range
if not arginfos.IsEmpty && not arginfos.Head.IsEmpty then
arginfos.Head |> List.last |> fst
else
error (Error(FSComp.SR.tastValueDoesNotHaveSetterType (), v.Range))
| SynMemberKind.PropertyGet ->
let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal v
let _, _, _, retTy, _ =
GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars v.Type v.Range
GetFSharpViewOfReturnType g retTy
| _ -> error (InternalError("ReturnTypeOfPropertyVal", v.Range))
/// Get the property arguments for an F# value that represents a getter or setter
/// of an object model property.
let ArgInfosOfPropertyVal g (v: Val) =
let membInfo, valReprInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range
match membInfo.MemberFlags.MemberKind with
| SynMemberKind.PropertyGet -> ArgInfosOfMemberVal g v |> List.concat
| SynMemberKind.PropertySet ->
let numEnclosingTypars = CountEnclosingTyparsOfActualParentOfVal v
let _, _, arginfos, _, _ =
GetMemberTypeInMemberForm g membInfo.MemberFlags valReprInfo numEnclosingTypars v.Type v.Range
if not arginfos.IsEmpty && not arginfos.Head.IsEmpty then
arginfos.Head |> List.frontAndBack |> fst
else
error (Error(FSComp.SR.tastValueDoesNotHaveSetterType (), v.Range))
| _ -> error (InternalError("ArgInfosOfPropertyVal", v.Range))
//---------------------------------------------------------------------------
// Generalize type constructors to types
//---------------------------------------------------------------------------
let generalTyconRefInst (tcref: TyconRef) = generalizeTypars tcref.TyparsNoRange
let generalizeTyconRef (g: TcGlobals) tcref =
let tinst = generalTyconRefInst tcref
tinst, TType_app(tcref, tinst, g.knownWithoutNull)
let generalizedTyconRef (g: TcGlobals) tcref =
let tinst = generalTyconRefInst tcref
TType_app(tcref, tinst, g.knownWithoutNull)
let isTTyparCoercesToType tpc =
match tpc with
| TyparConstraint.CoercesTo _ -> true
| _ -> false
//--------------------------------------------------------------------------
// Print Signatures/Types - prelude
//--------------------------------------------------------------------------
let prefixOfStaticReq s =
match s with
| TyparStaticReq.None -> "'"
| TyparStaticReq.HeadType -> "^"
let prefixOfInferenceTypar (typar: Typar) =
if typar.Rigidity <> TyparRigidity.Rigid then "_" else ""
let isTyparOrderMismatch (tps: Typars) (argInfos: CurriedArgInfos) =
let rec getTyparName (ty: TType) : string list =
match ty with
| TType_var(typar = tp) ->
if tp.Id.idText <> unassignedTyparName then
[ tp.Id.idText ]
else
match tp.Solution with
| None -> []
| Some solutionType -> getTyparName solutionType
| TType_fun(domainType, rangeType, _) -> [ yield! getTyparName domainType; yield! getTyparName rangeType ]
| TType_anon(tys = ti)
| TType_app(typeInstantiation = ti)
| TType_tuple(elementTypes = ti) -> List.collect getTyparName ti
| _ -> []
let typarNamesInArguments =
argInfos
|> List.collect (fun argInfos -> argInfos |> List.collect (fun (ty, _) -> getTyparName ty))
|> List.distinct
let typarNamesInDefinition =
tps |> List.map (fun (tp: Typar) -> tp.Id.idText) |> List.distinct
typarNamesInArguments.Length = typarNamesInDefinition.Length
&& typarNamesInArguments <> typarNamesInDefinition
//---------------------------------------------------------------------------
// Prettify: PrettyTyparNames/PrettifyTypes - make typar names human friendly
//---------------------------------------------------------------------------
type TyparConstraintsWithTypars = (Typar * TyparConstraint) list
module PrettyTypes =
let newPrettyTypar (tp: Typar) nm =
Construct.NewTypar(
tp.Kind,
tp.Rigidity,
SynTypar(ident (nm, tp.Range), tp.StaticReq, false),
false,
TyparDynamicReq.Yes,
[],
false,
false
)
let NewPrettyTypars renaming tps names =
let niceTypars = List.map2 newPrettyTypar tps names
let tl, _tt = mkTyparToTyparRenaming tps niceTypars in
let renaming = renaming @ tl
(tps, niceTypars)
||> List.iter2 (fun tp tpnice -> tpnice.SetConstraints(instTyparConstraints renaming tp.Constraints))
niceTypars, renaming
// We choose names for type parameters from 'a'..'t'
// We choose names for unit-of-measure from 'u'..'z'
// If we run off the end of these ranges, we use 'aX' for positive integer X or 'uX' for positive integer X
// Finally, we skip any names already in use
let NeedsPrettyTyparName (tp: Typar) =
tp.IsCompilerGenerated
&& tp.ILName.IsNone
&& (tp.typar_id.idText = unassignedTyparName)
let PrettyTyparNames pred alreadyInUse tps =
let rec choose (tps: Typar list) (typeIndex, measureIndex) acc =
match tps with
| [] -> List.rev acc
| tp :: tps ->
// Use a particular name, possibly after incrementing indexes
let useThisName (nm, typeIndex, measureIndex) =
choose tps (typeIndex, measureIndex) (nm :: acc)
// Give up, try again with incremented indexes
let tryAgain (typeIndex, measureIndex) =
choose (tp :: tps) (typeIndex, measureIndex) acc
let tryName (nm, typeIndex, measureIndex) f =
if List.contains nm alreadyInUse then
f ()
else
useThisName (nm, typeIndex, measureIndex)
if pred tp then
if NeedsPrettyTyparName tp then
let typeIndex, measureIndex, baseName, letters, i =
match tp.Kind with
| TyparKind.Type -> (typeIndex + 1, measureIndex, 'a', 20, typeIndex)
| TyparKind.Measure -> (typeIndex, measureIndex + 1, 'u', 6, measureIndex)
let nm =
if i < letters then
String.make 1 (char (int baseName + i))
else
String.make 1 baseName + string (i - letters + 1)
tryName (nm, typeIndex, measureIndex) (fun () -> tryAgain (typeIndex, measureIndex))
else
tryName (tp.Name, typeIndex, measureIndex) (fun () ->
// Use the next index and append it to the natural name
let typeIndex, measureIndex, nm =
match tp.Kind with
| TyparKind.Type -> (typeIndex + 1, measureIndex, tp.Name + string typeIndex)
| TyparKind.Measure -> (typeIndex, measureIndex + 1, tp.Name + string measureIndex)
tryName (nm, typeIndex, measureIndex) (fun () -> tryAgain (typeIndex, measureIndex)))
else
useThisName (tp.Name, typeIndex, measureIndex)
choose tps (0, 0) []
let AssignPrettyTyparNames typars prettyNames =
(typars, prettyNames)
||> List.iter2 (fun tp nm ->
if NeedsPrettyTyparName tp then
tp.typar_id <- ident (nm, tp.Range))
let PrettifyThings g foldTys mapTys things =
let ftps =
foldTys (accFreeInTypeLeftToRight g true false) emptyFreeTyparsLeftToRight things
let ftps = List.rev ftps
let rec computeKeep (keep: Typars) change (tps: Typars) =
match tps with
| [] -> List.rev keep, List.rev change
| tp :: rest ->
if
not (NeedsPrettyTyparName tp)
&& (not (keep |> List.exists (fun tp2 -> tp.Name = tp2.Name)))
then
computeKeep (tp :: keep) change rest
else
computeKeep keep (tp :: change) rest
let keep, change = computeKeep [] [] ftps
let alreadyInUse = keep |> List.map (fun x -> x.Name)
let names = PrettyTyparNames (fun x -> List.memq x change) alreadyInUse ftps
let niceTypars, renaming = NewPrettyTypars [] ftps names
// strip universal types for printing
let getTauStayTau ty =
match ty with
| TType_forall(_, tau) -> tau
| _ -> ty
let tauThings = mapTys getTauStayTau things
let prettyThings = mapTys (instType renaming) tauThings