-
Notifications
You must be signed in to change notification settings - Fork 797
/
Copy pathCheckDeclarations.fs
5934 lines (4933 loc) · 341 KB
/
CheckDeclarations.fs
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.CheckDeclarations
open System
open System.Collections.Generic
open System.Threading
open FSharp.Compiler.Diagnostics
open Internal.Utilities.Collections
open Internal.Utilities.Library
open Internal.Utilities.Library.Extras
open Internal.Utilities.Library.ResultOrException
open FSharp.Compiler
open FSharp.Compiler.AbstractIL.IL
open FSharp.Compiler.AccessibilityLogic
open FSharp.Compiler.AttributeChecking
open FSharp.Compiler.CheckComputationExpressions
open FSharp.Compiler.CheckExpressions
open FSharp.Compiler.CheckSequenceExpressions
open FSharp.Compiler.CheckArrayOrListComputedExpressions
open FSharp.Compiler.CheckBasics
open FSharp.Compiler.CheckExpressionsOps
open FSharp.Compiler.CheckIncrementalClasses
open FSharp.Compiler.CheckPatterns
open FSharp.Compiler.ConstraintSolver
open FSharp.Compiler.DiagnosticsLogger
open FSharp.Compiler.Features
open FSharp.Compiler.Infos
open FSharp.Compiler.InfoReader
open FSharp.Compiler.MethodOverrides
open FSharp.Compiler.NameResolution
open FSharp.Compiler.Syntax
open FSharp.Compiler.SyntaxTrivia
open FSharp.Compiler.Syntax.PrettyNaming
open FSharp.Compiler.SyntaxTreeOps
open FSharp.Compiler.Text
open FSharp.Compiler.Text.Range
open FSharp.Compiler.Xml
open FSharp.Compiler.TcGlobals
open FSharp.Compiler.TypedTree
open FSharp.Compiler.TypedTreeBasics
open FSharp.Compiler.TypedTreeOps
open FSharp.Compiler.TypeHierarchy
open FSharp.Compiler.TypeRelations
#if !NO_TYPEPROVIDERS
open FSharp.Compiler.TypeProviders
#endif
type cenv = TcFileState
//-------------------------------------------------------------------------
// Mutually recursive shapes
//-------------------------------------------------------------------------
type MutRecDataForOpen = MutRecDataForOpen of SynOpenDeclTarget * range * appliedScope: range * OpenDeclaration list ref
type MutRecDataForModuleAbbrev = MutRecDataForModuleAbbrev of Ident * LongIdent * range
/// Represents the shape of a mutually recursive group of declarations including nested modules
[<RequireQualifiedAccess>]
type MutRecShape<'TypeData, 'LetsData, 'ModuleData> =
| Tycon of 'TypeData
| Lets of 'LetsData
| Module of 'ModuleData * MutRecShapes<'TypeData, 'LetsData, 'ModuleData>
| ModuleAbbrev of MutRecDataForModuleAbbrev
| Open of MutRecDataForOpen
and MutRecShapes<'TypeData, 'LetsData, 'ModuleData> = MutRecShape<'TypeData, 'LetsData, 'ModuleData> list
//-------------------------------------------------------------------------
// Mutually recursive shapes
//-------------------------------------------------------------------------
module MutRecShapes =
let rec map f1 f2 f3 x =
x |> List.map (function
| MutRecShape.Open a -> MutRecShape.Open a
| MutRecShape.ModuleAbbrev b -> MutRecShape.ModuleAbbrev b
| MutRecShape.Tycon a -> MutRecShape.Tycon (f1 a)
| MutRecShape.Lets b -> MutRecShape.Lets (f2 b)
| MutRecShape.Module (c, d) -> MutRecShape.Module (f3 c, map f1 f2 f3 d))
let mapTycons f1 xs = map f1 id id xs
let mapTyconsAndLets f1 f2 xs = map f1 f2 id xs
let mapLets f2 xs = map id f2 id xs
let mapModules f1 xs = map id id f1 xs
let rec mapWithEnv fTycon fLets (env: 'Env) x =
x |> List.map (function
| MutRecShape.Open a -> MutRecShape.Open a
| MutRecShape.ModuleAbbrev a -> MutRecShape.ModuleAbbrev a
| MutRecShape.Tycon a -> MutRecShape.Tycon (fTycon env a)
| MutRecShape.Lets b -> MutRecShape.Lets (fLets env b)
| MutRecShape.Module ((c, env2), d) -> MutRecShape.Module ((c, env2), mapWithEnv fTycon fLets env2 d))
let mapTyconsWithEnv f1 env xs = mapWithEnv f1 (fun _env x -> x) env xs
let rec mapWithParent parent f1 f2 f3 xs =
xs |> List.map (function
| MutRecShape.Open a -> MutRecShape.Open a
| MutRecShape.ModuleAbbrev a -> MutRecShape.ModuleAbbrev a
| MutRecShape.Tycon a -> MutRecShape.Tycon (f2 parent a)
| MutRecShape.Lets b -> MutRecShape.Lets (f3 parent b)
| MutRecShape.Module (c, d) ->
let c2, parent2 = f1 parent c d
MutRecShape.Module (c2, mapWithParent parent2 f1 f2 f3 d))
let rec computeEnvs f1 f2 (env: 'Env) xs =
let env = f2 env xs
env,
xs |> List.map (function
| MutRecShape.Open a -> MutRecShape.Open a
| MutRecShape.ModuleAbbrev a -> MutRecShape.ModuleAbbrev a
| MutRecShape.Tycon a -> MutRecShape.Tycon a
| MutRecShape.Lets b -> MutRecShape.Lets b
| MutRecShape.Module (c, ds) ->
let env2 = f1 env c
let env3, ds2 = computeEnvs f1 f2 env2 ds
MutRecShape.Module ((c, env3), ds2))
let rec extendEnvs f1 (env: 'Env) xs =
let env = f1 env xs
env,
xs |> List.map (function
| MutRecShape.Module ((c, env), ds) ->
let env2, ds2 = extendEnvs f1 env ds
MutRecShape.Module ((c, env2), ds2)
| x -> x)
let dropEnvs xs = xs |> mapModules fst
let rec expandTyconsWithEnv f1 env xs =
let preBinds, postBinds =
xs |> List.map (fun elem ->
match elem with
| MutRecShape.Tycon a -> f1 env a
| _ -> [], [])
|> List.unzip
[MutRecShape.Lets (List.concat preBinds)] @
(xs |> List.map (fun elem ->
match elem with
| MutRecShape.Module ((c, env2), d) -> MutRecShape.Module ((c, env2), expandTyconsWithEnv f1 env2 d)
| _ -> elem)) @
[MutRecShape.Lets (List.concat postBinds)]
let rec mapFoldWithEnv f1 z env xs =
(z, xs) ||> List.mapFold (fun z x ->
match x with
| MutRecShape.Module ((c, env2), ds) -> let ds2, z = mapFoldWithEnv f1 z env2 ds in MutRecShape.Module ((c, env2), ds2), z
| _ -> let x2, z = f1 z env x in x2, z)
let rec collectTycons x =
x |> List.collect (function
| MutRecShape.Tycon a -> [a]
| MutRecShape.Module (_, d) -> collectTycons d
| _ -> [])
let topTycons x =
x |> List.choose (function MutRecShape.Tycon a -> Some a | _ -> None)
let rec iter f1 f2 f3 f4 f5 x =
x |> List.iter (function
| MutRecShape.Tycon a -> f1 a
| MutRecShape.Lets b -> f2 b
| MutRecShape.Module (c, d) -> f3 c; iter f1 f2 f3 f4 f5 d
| MutRecShape.Open a -> f4 a
| MutRecShape.ModuleAbbrev a -> f5 a)
let iterTycons f1 x = iter f1 ignore ignore ignore ignore x
let iterTyconsAndLets f1 f2 x = iter f1 f2 ignore ignore ignore x
let iterModules f1 x = iter ignore ignore f1 ignore ignore x
let rec iterWithEnv f1 f2 f3 f4 env x =
x |> List.iter (function
| MutRecShape.Tycon a -> f1 env a
| MutRecShape.Lets b -> f2 env b
| MutRecShape.Module ((_, env), d) -> iterWithEnv f1 f2 f3 f4 env d
| MutRecShape.Open a -> f3 env a
| MutRecShape.ModuleAbbrev a -> f4 env a)
let iterTyconsWithEnv f1 env xs = iterWithEnv f1 (fun _env _x -> ()) (fun _env _x -> ()) (fun _env _x -> ()) env xs
/// Indicates a declaration is contained in the given module
let ModuleOrNamespaceContainerInfo modref =
ContainerInfo(Parent modref, Some(MemberOrValContainerInfo(modref, None, None, NoSafeInitInfo, [])))
/// Indicates a declaration is contained in the given type definition in the given module
let TyconContainerInfo (parent, tcref, declaredTyconTypars, safeInitInfo) =
ContainerInfo(parent, Some(MemberOrValContainerInfo(tcref, None, None, safeInitInfo, declaredTyconTypars)))
type TyconBindingDefn = TyconBindingDefn of ContainerInfo * NewSlotsOK * DeclKind * SynMemberDefn option * range
type MutRecSigsInitialData = MutRecShape<SynTypeDefnSig, SynValSig, SynComponentInfo> list
type MutRecDefnsInitialData = MutRecShape<SynTypeDefn, SynBinding list, SynComponentInfo> list
type MutRecDefnsPhase1DataForTycon = MutRecDefnsPhase1DataForTycon of SynComponentInfo * SynTypeDefnSimpleRepr * (SynType * range) list * preEstablishedHasDefaultCtor: bool * hasSelfReferentialCtor: bool * isAtOriginalTyconDefn: bool
type MutRecDefnsPhase1Data = MutRecShape<MutRecDefnsPhase1DataForTycon * SynMemberDefn list, RecDefnBindingInfo list, SynComponentInfo> list
type MutRecDefnsPhase2DataForTycon = MutRecDefnsPhase2DataForTycon of Tycon option * ParentRef * DeclKind * TyconRef * Val option * SafeInitData * Typars * SynMemberDefn list * range * NewSlotsOK * fixupFinalAttribs: (unit -> unit)
type MutRecDefnsPhase2DataForModule = MutRecDefnsPhase2DataForModule of ModuleOrNamespaceType ref * ModuleOrNamespace
type MutRecDefnsPhase2Data = MutRecShape<MutRecDefnsPhase2DataForTycon, RecDefnBindingInfo list, MutRecDefnsPhase2DataForModule * TcEnv> list
type MutRecDefnsPhase2InfoForTycon = MutRecDefnsPhase2InfoForTycon of Tycon option * TyconRef * Typars * DeclKind * TyconBindingDefn list * fixupFinalAttrs: (unit -> unit)
type MutRecDefnsPhase2Info = MutRecShape<MutRecDefnsPhase2InfoForTycon, RecDefnBindingInfo list, MutRecDefnsPhase2DataForModule * TcEnv> list
//-------------------------------------------------------------------------
// Helpers for TcEnv
//-------------------------------------------------------------------------
/// Add an exception definition to TcEnv and report it to the sink
let AddLocalExnDefnAndReport tcSink scopem env (exnc: Tycon) =
let env = { env with eNameResEnv = AddExceptionDeclsToNameEnv BulkAdd.No env.eNameResEnv (mkLocalEntityRef exnc) }
// Also make VisualStudio think there is an identifier in scope at the range of the identifier text of its binding location
CallEnvSink tcSink (exnc.Range, env.NameEnv, env.AccessRights)
CallEnvSink tcSink (scopem, env.NameEnv, env.AccessRights)
env
/// Add a list of type definitions to TcEnv
let AddLocalTyconRefs ownDefinition g amap m tcrefs env =
if isNil tcrefs then env else
{ env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.No ownDefinition g amap env.eAccessRights m false env.eNameResEnv tcrefs }
/// Add a list of type definitions to TcEnv
let AddLocalTycons g amap m (tycons: Tycon list) env =
if isNil tycons then env else
env |> AddLocalTyconRefs false g amap m (List.map mkLocalTyconRef tycons)
/// Add a list of type definitions to TcEnv and report them to the sink
let AddLocalTyconsAndReport tcSink scopem g amap m tycons env =
let env = AddLocalTycons g amap m tycons env
CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights)
env
/// Add a "module X = ..." definition to the TcEnv
let AddLocalSubModule g amap m env (moduleEntity: ModuleOrNamespace) =
let env = { env with
eNameResEnv = AddModuleOrNamespaceRefToNameEnv g amap m false env.eAccessRights env.eNameResEnv (mkLocalModuleRef moduleEntity)
eUngeneralizableItems = addFreeItemOfModuleTy moduleEntity.ModuleOrNamespaceType env.eUngeneralizableItems }
env
/// Add a "module X = ..." definition to the TcEnv and report it to the sink
let AddLocalSubModuleAndReport tcSink scopem g amap m env (moduleEntity: ModuleOrNamespace) =
let env = AddLocalSubModule g amap m env moduleEntity
if not (equals scopem m) then
// Don't report another environment for top-level module at its own range,
// so it doesn't overwrite inner environment used by features like code completion.
CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights)
env
/// Given an inferred module type, place that inside a namespace path implied by a "namespace X.Y.Z" definition
let BuildRootModuleType enclosingNamespacePath (cpath: CompilationPath) moduleTy =
(enclosingNamespacePath, (cpath, (moduleTy, [])))
||> List.foldBack (fun id (cpath, (moduleTy, moduls)) ->
let a, b = wrapModuleOrNamespaceTypeInNamespace id cpath.ParentCompPath moduleTy
cpath.ParentCompPath, (a, b :: moduls))
|> fun (_, (moduleTy, moduls)) -> moduleTy, List.rev moduls
/// Given a resulting module expression, place that inside a namespace path implied by a "namespace X.Y.Z" definition
let BuildRootModuleContents (isModule: bool) enclosingNamespacePath (cpath: CompilationPath) moduleContents =
(enclosingNamespacePath, (cpath, moduleContents))
||> List.foldBack (fun id (cpath, moduleContents) -> (cpath.ParentCompPath, wrapModuleOrNamespaceContentsInNamespace isModule id cpath.ParentCompPath moduleContents))
|> snd
/// Try to take the "FSI_NNN" prefix off a namespace path
let TryStripPrefixPath (g: TcGlobals) (enclosingNamespacePath: Ident list) =
match enclosingNamespacePath with
| p :: rest when
g.isInteractive &&
not (isNil rest) &&
p.idText.StartsWithOrdinal FsiDynamicModulePrefix &&
p.idText[FsiDynamicModulePrefix.Length..] |> String.forall Char.IsDigit
-> Some(p, rest)
| _ -> None
/// Add a "module X = Y" local module abbreviation to the TcEnv
let AddModuleAbbreviationAndReport tcSink scopem id modrefs env =
let env =
if isNil modrefs then env else
{ env with eNameResEnv = AddModuleAbbrevToNameEnv id env.eNameResEnv modrefs }
CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights)
let item = Item.ModuleOrNamespaces modrefs
CallNameResolutionSink tcSink (id.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurrence.Use, env.AccessRights)
env
/// Adjust the TcEnv to account for opening the set of modules or namespaces implied by an `open` declaration
let OpenModuleOrNamespaceRefs tcSink g amap scopem root env mvvs openDeclaration =
let env =
if isNil mvvs then env else
{ env with eNameResEnv = AddModuleOrNamespaceRefsContentsToNameEnv g amap env.eAccessRights scopem root env.eNameResEnv mvvs }
CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights)
CallOpenDeclarationSink tcSink openDeclaration
env
/// Adjust the TcEnv to account for opening a type implied by an `open type` declaration
let OpenTypeContent tcSink g amap scopem env (ty: TType) openDeclaration =
let env =
{ env with eNameResEnv = AddTypeContentsToNameEnv g amap env.eAccessRights scopem env.eNameResEnv ty }
CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights)
CallOpenDeclarationSink tcSink openDeclaration
env
/// Adjust the TcEnv to account for a new root Ccu being available, e.g. a referenced assembly
let AddRootModuleOrNamespaceRefs g amap m env modrefs =
if isNil modrefs then env else
{ env with eNameResEnv = AddModuleOrNamespaceRefsToNameEnv g amap m true env.eAccessRights env.eNameResEnv modrefs }
/// Adjust the TcEnv to make more things 'InternalsVisibleTo'
let addInternalsAccessibility env (ccu: CcuThunk) =
let compPath = CompPath (ccu.ILScopeRef, TypedTree.SyntaxAccess.Unknown, [])
let eInternalsVisibleCompPaths = compPath :: env.eInternalsVisibleCompPaths
{ env with
eAccessRights = ComputeAccessRights env.eAccessPath eInternalsVisibleCompPaths env.eFamilyType // update this computed field
eInternalsVisibleCompPaths = compPath :: env.eInternalsVisibleCompPaths }
/// Adjust the TcEnv to account for a new referenced assembly
let AddNonLocalCcu g amap scopem env assemblyName (ccu: CcuThunk, internalsVisibleToAttributes) =
let internalsVisible =
internalsVisibleToAttributes
|> List.exists (fun visibleTo ->
try
System.Reflection.AssemblyName(visibleTo).Name = assemblyName
with _ ->
warning(InvalidInternalsVisibleToAssemblyName(visibleTo, ccu.FileName))
false)
let env = if internalsVisible then addInternalsAccessibility env ccu else env
// Compute the top-rooted module or namespace references
let modrefs = ccu.RootModulesAndNamespaces |> List.map (mkNonLocalCcuRootEntityRef ccu)
// Compute the top-rooted type definitions
let tcrefs = ccu.RootTypeAndExceptionDefinitions |> List.map (mkNonLocalCcuRootEntityRef ccu)
let env = AddRootModuleOrNamespaceRefs g amap scopem env modrefs
let env =
if isNil tcrefs then env else
{ env with eNameResEnv = AddTyconRefsToNameEnv BulkAdd.Yes false g amap env.eAccessRights scopem true env.eNameResEnv tcrefs }
env
/// Adjust the TcEnv to account for a fully processed "namespace" declaration in this file
let AddLocalRootModuleOrNamespace tcSink g amap scopem env (moduleTy: ModuleOrNamespaceType) =
// Compute the top-rooted module or namespace references
let modrefs = moduleTy.ModuleAndNamespaceDefinitions |> List.map mkLocalModuleRef
// Compute the top-rooted type definitions
let tcrefs = moduleTy.TypeAndExceptionDefinitions |> List.map mkLocalTyconRef
let env = AddRootModuleOrNamespaceRefs g amap scopem env modrefs
let env = { env with
eNameResEnv = if isNil tcrefs then env.eNameResEnv else AddTyconRefsToNameEnv BulkAdd.No false g amap env.eAccessRights scopem true env.eNameResEnv tcrefs
eUngeneralizableItems = addFreeItemOfModuleTy moduleTy env.eUngeneralizableItems }
CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights)
env
/// Inside "namespace X.Y.Z" there is an implicit open of "X.Y.Z"
let ImplicitlyOpenOwnNamespace tcSink g amap scopem enclosingNamespacePath (env: TcEnv) =
if isNil enclosingNamespacePath then
env
else
// For F# interactive, skip "FSI_0002" prefixes when determining the path to open implicitly
let enclosingNamespacePathToOpen =
match TryStripPrefixPath g enclosingNamespacePath with
| Some(_, rest) -> rest
| None -> enclosingNamespacePath
match enclosingNamespacePathToOpen with
| id :: rest ->
let ad = env.AccessRights
match ResolveLongIdentAsModuleOrNamespace tcSink amap scopem true OpenQualified env.eNameResEnv ad id rest true ShouldNotifySink.Yes with
| Result modrefs ->
let modrefs = List.map p23 modrefs
let lid = SynLongIdent(enclosingNamespacePathToOpen, [] , [])
let openTarget = SynOpenDeclTarget.ModuleOrNamespace(lid, scopem)
let openDecl = OpenDeclaration.Create (openTarget, modrefs, [], scopem, true)
OpenModuleOrNamespaceRefs tcSink g amap scopem false env modrefs openDecl
| Exception _ -> env
| _ -> env
//-------------------------------------------------------------------------
// Bind elements of data definitions for exceptions and types (fields, etc.)
//-------------------------------------------------------------------------
exception NotUpperCaseConstructor of range: range
exception NotUpperCaseConstructorWithoutRQA of range: range
let CheckNamespaceModuleOrTypeName (g: TcGlobals) (id: Ident) =
// type names '[]' etc. are used in fslib
if not g.compilingFSharpCore && id.idText.IndexOfAny IllegalCharactersInTypeAndNamespaceNames <> -1 then
errorR(Error(FSComp.SR.tcInvalidNamespaceModuleTypeUnionName(), id.idRange))
let CheckDuplicates (idf: _ -> Ident) k elems =
elems |> List.iteri (fun i uc1 ->
elems |> List.iteri (fun j uc2 ->
let id1 = (idf uc1)
let id2 = (idf uc2)
if j > i && id1.idText = id2.idText then
errorR (Duplicate(k, id1.idText, id1.idRange))))
elems
let private CheckDuplicatesArgNames (synVal: SynValSig) m =
let argNames = synVal.SynInfo.ArgNames |> List.duplicates
for name in argNames do
errorR(Error((FSComp.SR.chkDuplicatedMethodParameter(name), m)))
let private CheckDuplicatesAbstractMethodParamsSig (typeSpecs: SynTypeDefnSig list) =
for SynTypeDefnSig(typeRepr= trepr) in typeSpecs do
match trepr with
| SynTypeDefnSigRepr.ObjectModel(_, synMemberSigs, _) ->
for sms in synMemberSigs do
match sms with
| SynMemberSig.Member(memberSig = synValSig; range = m) ->
CheckDuplicatesArgNames synValSig m
| _ -> ()
| _ -> ()
module TcRecdUnionAndEnumDeclarations =
open CheckExpressionsOps
let CombineReprAccess parent vis =
match parent with
| ParentNone -> vis
| Parent tcref -> combineAccess vis tcref.TypeReprAccessibility
let MakeRecdFieldSpec g env parent (isStatic, konst, tyR, attrsForProperty, attrsForField, id, nameGenerated, isMutable, vol, xmldoc, vis, m) =
let vis, _ = ComputeAccessAndCompPath g env None m vis None parent
let vis = CombineReprAccess parent vis
Construct.NewRecdField isStatic konst id nameGenerated tyR isMutable vol attrsForProperty attrsForField xmldoc vis false
let TcFieldDecl (cenv: cenv) env parent isIncrClass tpenv (isStatic, synAttrs, id: Ident, nameGenerated, ty, isMutable, xmldoc, vis) =
let g = cenv.g
let m = id.idRange
let attrs, _ = TcAttributesWithPossibleTargets TcCanFail.ReportAllErrors cenv env AttributeTargets.FieldDecl synAttrs
let attrsForProperty, attrsForField = attrs |> List.partition (fun (attrTargets, _) -> (attrTargets &&& AttributeTargets.Property) <> enum 0)
let attrsForProperty = (List.map snd attrsForProperty)
let attrsForField = (List.map snd attrsForField)
let tyR, _ = TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurrence.UseInType WarnOnIWSAM.Yes env tpenv ty
let zeroInit = HasFSharpAttribute g g.attrib_DefaultValueAttribute attrsForField
let isVolatile = HasFSharpAttribute g g.attrib_VolatileFieldAttribute attrsForField
let isThreadStatic = isThreadOrContextStatic g attrsForField
if isThreadStatic && (not zeroInit || not isStatic) then
error(Error(FSComp.SR.tcThreadStaticAndContextStaticMustBeStatic(), m))
if isVolatile then
error(Error(FSComp.SR.tcVolatileOnlyOnClassLetBindings(), m))
if isIncrClass && (not zeroInit || not isMutable) then errorR(Error(FSComp.SR.tcUninitializedValFieldsMustBeMutable(), m))
let isPrivate = match vis with | Some (SynAccess.Private _) -> true | _ -> false
if isStatic && (not zeroInit || not isMutable || not isPrivate) then errorR(Error(FSComp.SR.tcStaticValFieldsMustBeMutableAndPrivate(), m))
let konst = if zeroInit then Some Const.Zero else None
let rfspec = MakeRecdFieldSpec g env parent (isStatic, konst, tyR, attrsForProperty, attrsForField, id, nameGenerated, isMutable, isVolatile, xmldoc, vis, m)
match parent with
| Parent tcref when useGenuineField tcref.Deref rfspec ->
// Recheck the attributes for errors if the definition only generates a field
TcAttributesWithPossibleTargets TcCanFail.ReportAllErrors cenv env AttributeTargets.FieldDeclRestricted synAttrs |> ignore
| _ -> ()
rfspec
let TcAnonFieldDecl cenv env parent tpenv nm (SynField(Attributes attribs, isStatic, idOpt, ty, isMutable, xmldoc, vis, m, _)) =
let mName = m.MakeSynthetic()
let id = match idOpt with None -> mkSynId mName nm | Some id -> id
let checkXmlDocs = cenv.diagnosticOptions.CheckXmlDocs
let xmlDoc = xmldoc.ToXmlDoc(checkXmlDocs, Some [])
TcFieldDecl cenv env parent false tpenv (isStatic, attribs, id, idOpt.IsNone, ty, isMutable, xmlDoc, vis)
let TcNamedFieldDecl cenv env parent isIncrClass tpenv (SynField(Attributes attribs, isStatic, id, ty, isMutable, xmldoc, vis, m, _)) =
match id with
| None ->
errorR (Error(FSComp.SR.tcFieldRequiresName(), m))
None
| Some id ->
let checkXmlDocs = cenv.diagnosticOptions.CheckXmlDocs
let xmlDoc = xmldoc.ToXmlDoc(checkXmlDocs, Some [])
Some(TcFieldDecl cenv env parent isIncrClass tpenv (isStatic, attribs, id, false, ty, isMutable, xmlDoc, vis))
let TcNamedFieldDecls cenv env parent isIncrClass tpenv fields =
fields |> List.choose (TcNamedFieldDecl cenv env parent isIncrClass tpenv)
//-------------------------------------------------------------------------
// Bind other elements of type definitions (constructors etc.)
//-------------------------------------------------------------------------
let CheckUnionCaseName (cenv: cenv) (id: Ident) hasRQAAttribute =
let g = cenv.g
let name = id.idText
if name = "Tags" then
errorR(Error(FSComp.SR.tcUnionCaseNameConflictsWithGeneratedType(name, "Tags"), id.idRange))
CheckNamespaceModuleOrTypeName g id
if g.langVersion.SupportsFeature(LanguageFeature.LowercaseDUWhenRequireQualifiedAccess) then
if not (String.isLeadingIdentifierCharacterUpperCase name) && not hasRQAAttribute && name <> opNameCons && name <> opNameNil then
errorR(NotUpperCaseConstructorWithoutRQA(id.idRange))
else
if not (String.isLeadingIdentifierCharacterUpperCase name) && name <> opNameCons && name <> opNameNil then
errorR(NotUpperCaseConstructor(id.idRange))
let private CheckUnionDuplicateFields (elems: Ident list) =
elems |> List.iteri (fun i (uc1: Ident) ->
elems |> List.iteri (fun j (uc2: Ident) ->
if j > i && uc1.idText = uc2.idText then
errorR(Error(FSComp.SR.tcFieldNameIsUsedModeThanOnce(uc1.idText), uc1.idRange))))
let ValidateFieldNames (synFields: SynField list, tastFields: RecdField list) =
let fields = synFields |> List.choose (function SynField(idOpt = Some ident) -> Some ident | _ -> None)
if fields.Length > 1 then
CheckUnionDuplicateFields fields
let seen = Dictionary()
(synFields, tastFields) ||> List.iter2 (fun sf f ->
match seen.TryGetValue f.LogicalName with
| true, synField ->
match sf, synField with
| SynField(idOpt = Some id), SynField(idOpt = None)
| SynField(idOpt = None), SynField(idOpt = Some id) ->
errorR(Error(FSComp.SR.tcFieldNameConflictsWithGeneratedNameForAnonymousField(id.idText), id.idRange))
| _ -> ()
| _ ->
seen.Add(f.LogicalName, sf))
let TcUnionCaseDecl (cenv: cenv) env parent thisTy thisTyInst tpenv hasRQAAttribute (SynUnionCase(Attributes synAttrs, SynIdent(id, _), args, xmldoc, vis, m, _)) =
let g = cenv.g
let vis, _ = ComputeAccessAndCompPath g env None m vis None parent
let vis = CombineReprAccess parent vis
CheckUnionCaseName cenv id hasRQAAttribute
let rfields, recordTy =
match args with
| SynUnionCaseKind.Fields flds ->
let nFields = flds.Length
let rfields =
flds
|> List.mapi (fun i (SynField (idOpt = idOpt) as fld) ->
match idOpt, parent with
| Some fieldId, Parent tcref ->
let item = Item.UnionCaseField (UnionCaseInfo (thisTyInst, UnionCaseRef (tcref, id.idText)), i)
CallNameResolutionSink cenv.tcSink (fieldId.idRange, env.NameEnv, item, emptyTyparInst, ItemOccurrence.Binding, env.AccessRights)
TcNamedFieldDecl cenv env parent false tpenv fld
| _ ->
Some(TcAnonFieldDecl cenv env parent tpenv (mkUnionCaseFieldName nFields i) fld)
)
|> List.choose (fun x -> x)
ValidateFieldNames(flds, rfields)
rfields, thisTy
| SynUnionCaseKind.FullType (ty, arity) ->
let tyR, _ = TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurrence.UseInType WarnOnIWSAM.Yes env tpenv ty
let curriedArgTys, recordTy = GetTopTauTypeInFSharpForm g (arity |> TranslateSynValInfo cenv m (TcAttributes cenv env) |> TranslatePartialValReprInfo []).ArgInfos tyR m
if curriedArgTys.Length > 1 then
errorR(Error(FSComp.SR.tcIllegalFormForExplicitTypeDeclaration(), m))
let argTys = curriedArgTys |> List.concat
let nFields = argTys.Length
let rfields =
argTys |> List.mapi (fun i (argTy, argInfo) ->
let id = (match argInfo.Name with Some id -> id | None -> mkSynId m (mkUnionCaseFieldName nFields i))
MakeRecdFieldSpec g env parent (false, None, argTy, [], [], id, argInfo.Name.IsNone, false, false, XmlDoc.Empty, None, m))
if not (typeEquiv g recordTy thisTy) then
error(Error(FSComp.SR.tcReturnTypesForUnionMustBeSameAsType(), m))
rfields, recordTy
let names = rfields
|> Seq.filter (fun f -> not f.rfield_name_generated)
|> Seq.map (fun f -> f.DisplayNameCore)
|> Seq.toList
let checkXmlDocs = cenv.diagnosticOptions.CheckXmlDocs
let xmlDoc = xmldoc.ToXmlDoc(checkXmlDocs, Some names)
let attrs =
(*
The attributes of a union case decl get attached to the generated "static factory" method.
Enforce union-cases AttributeTargets:
- AttributeTargets.Method
type SomeUnion =
| Case1 of int // Compiles down to a static method
- AttributeTargets.Property
type SomeUnion =
| Case1 // Compiles down to a static property
*)
if g.langVersion.SupportsFeature(LanguageFeature.EnforceAttributeTargets) then
let target = if rfields.IsEmpty then AttributeTargets.Property else AttributeTargets.Method
TcAttributes cenv env target synAttrs
else
TcAttributes cenv env AttributeTargets.UnionCaseDecl synAttrs
Construct.NewUnionCase id rfields recordTy attrs xmlDoc vis
let TcUnionCaseDecls (cenv: cenv) env (parent: ParentRef) (thisTy: TType) (thisTyInst: TypeInst) hasRQAAttribute tpenv unionCases =
let unionCasesR =
unionCases
|> List.filter (fun (SynUnionCase(_, SynIdent(id, _), _, _, _, _, _)) -> id.idText <> "")
|> List.map (TcUnionCaseDecl cenv env parent thisTy thisTyInst tpenv hasRQAAttribute)
unionCasesR |> CheckDuplicates (fun uc -> uc.Id) "union case"
let MakeEnumCaseSpec g cenv env parent attrs thisTy caseRange (caseIdent: Ident) (xmldoc: PreXmlDoc) value =
let vis, _ = ComputeAccessAndCompPath g env None caseRange None None parent
let vis = CombineReprAccess parent vis
if caseIdent.idText = "value__" then errorR(Error(FSComp.SR.tcNotValidEnumCaseName(), caseIdent.idRange))
let checkXmlDocs = cenv.diagnosticOptions.CheckXmlDocs
let xmlDoc = xmldoc.ToXmlDoc(checkXmlDocs, Some [])
Construct.NewRecdField true (Some value) caseIdent false thisTy false false [] attrs xmlDoc vis false
let TcEnumDecl g cenv env tpenv parent thisTy fieldTy (SynEnumCase (attributes = Attributes synAttrs; ident = SynIdent (id, _); valueExpr = valueExpr; xmlDoc = xmldoc; range = caseRange)) =
let attrs = TcAttributes cenv env AttributeTargets.Field synAttrs
let valueRange = valueExpr.Range
match valueExpr with
| SynExpr.Const (constant = SynConst.Bytes _ | SynConst.UInt16s _ | SynConst.UserNum _) ->
error(Error(FSComp.SR.tcInvalidEnumerationLiteral(), valueRange))
| SynExpr.Const (synConst, _) ->
let konst = TcConst cenv fieldTy valueRange env synConst
MakeEnumCaseSpec g cenv env parent attrs thisTy caseRange id xmldoc konst
| _ ->
let expr, actualTy, _ = TcExprOfUnknownType cenv env tpenv valueExpr
UnifyTypes cenv env valueRange fieldTy actualTy
match EvalLiteralExprOrAttribArg cenv.g expr with
| Expr.Const (konst, _, _) -> MakeEnumCaseSpec g cenv env parent attrs thisTy caseRange id xmldoc konst
| _ -> error(Error(FSComp.SR.tcInvalidEnumerationLiteral(), valueRange))
let TcEnumDecls (cenv: cenv) env tpenv parent thisTy enumCases =
let g = cenv.g
let fieldTy = NewInferenceType g
let enumCases' = enumCases |> List.map (TcEnumDecl g cenv env tpenv parent thisTy fieldTy) |> CheckDuplicates (fun f -> f.Id) "enum element"
fieldTy, enumCases'
//-------------------------------------------------------------------------
// Bind elements of classes
//-------------------------------------------------------------------------
let PublishInterface (cenv: cenv) denv (tcref: TyconRef) m isCompGen interfaceTy =
let g = cenv.g
if not (isInterfaceTy g interfaceTy) then
errorR(Error(FSComp.SR.tcTypeIsNotInterfaceType1(NicePrint.minimalStringOfType denv interfaceTy), m))
if tcref.HasInterface g interfaceTy then
errorR(Error(FSComp.SR.tcDuplicateSpecOfInterface(), m))
let tcaug = tcref.TypeContents
tcaug.tcaug_interfaces <- (interfaceTy, isCompGen, m) :: tcaug.tcaug_interfaces
let TcAndPublishMemberSpec cenv env containerInfo declKind tpenv memb =
match memb with
| SynMemberSig.ValField(_, m) -> error(Error(FSComp.SR.tcFieldValIllegalHere(), m))
| SynMemberSig.Inherit(_, m) -> error(Error(FSComp.SR.tcInheritIllegalHere(), m))
| SynMemberSig.NestedType(_, m) -> error(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), m))
| SynMemberSig.Member(memberSig = synValSig; flags = memberFlags) ->
TcAndPublishValSpec (cenv, env, containerInfo, declKind, Some memberFlags, tpenv, synValSig)
| SynMemberSig.Interface _ ->
// These are done in TcMutRecDefns_Phase1
[], tpenv
let TcTyconMemberSpecs cenv env containerInfo declKind tpenv augSpfn =
let members, tpenv = List.mapFold (TcAndPublishMemberSpec cenv env containerInfo declKind) tpenv augSpfn
List.concat members, tpenv
//-------------------------------------------------------------------------
// Bind 'open' declarations
//-------------------------------------------------------------------------
let TcOpenLidAndPermitAutoResolve tcSink (env: TcEnv) amap (longId : Ident list) =
let ad = env.AccessRights
match longId with
| [] -> []
| id :: rest ->
let m = longId |> List.map (fun id -> id.idRange) |> List.reduce unionRanges
match ResolveLongIdentAsModuleOrNamespace tcSink amap m true OpenQualified env.NameEnv ad id rest true ShouldNotifySink.Yes with
| Result res -> res
| Exception err ->
errorR(err); []
let TcOpenModuleOrNamespaceDecl tcSink g amap scopem env (longId, m) =
match TcOpenLidAndPermitAutoResolve tcSink env amap longId with
| [] -> env, []
| modrefs ->
// validate opened namespace names
for id in longId do
if id.idText <> MangledGlobalName then
CheckNamespaceModuleOrTypeName g id
let IsPartiallyQualifiedNamespace (modref: ModuleOrNamespaceRef) =
let (CompPath(_, _, p)) = modref.CompilationPath
// Bug FSharp 1.0 3274: FSI paths don't count when determining this warning
let p =
match p with
| [] -> []
| (h, _) :: t -> if h.StartsWithOrdinal FsiDynamicModulePrefix then t else p
// See https://fslang.uservoice.com/forums/245727-f-language/suggestions/6107641-make-microsoft-prefix-optional-when-using-core-f
let isFSharpCoreSpecialCase =
match ccuOfTyconRef modref with
| None -> false
| Some ccu ->
ccuEq ccu g.fslibCcu &&
// Check if we're using a reference one string shorter than what we expect.
//
// "p" is the fully qualified path _containing_ the thing we're opening, e.g. "Microsoft.FSharp" when opening "Microsoft.FSharp.Data"
// "longId" is the text being used, e.g. "FSharp.Data"
// Length of thing being opened = p.Length + 1
// Length of reference = longId.Length
// So the reference is a "shortened" reference if (p.Length + 1) - 1 = longId.Length
(p.Length + 1) - 1 = longId.Length &&
fst p[0] = "Microsoft"
modref.IsNamespace &&
p.Length >= longId.Length &&
not isFSharpCoreSpecialCase
// Allow "open Foo" for "Microsoft.Foo" from FSharp.Core
modrefs |> List.iter (fun (_, modref, _) ->
if modref.IsModule && HasFSharpAttribute g g.attrib_RequireQualifiedAccessAttribute modref.Attribs then
errorR(Error(FSComp.SR.tcModuleRequiresQualifiedAccess(fullDisplayTextOfModRef modref), m)))
// Bug FSharp 1.0 3133: 'open Lexing'. Skip this warning if we successfully resolved to at least a module name
if not (modrefs |> List.exists (fun (_, modref, _) -> modref.IsModule && not (HasFSharpAttribute g g.attrib_RequireQualifiedAccessAttribute modref.Attribs))) then
modrefs |> List.iter (fun (_, modref, _) ->
if IsPartiallyQualifiedNamespace modref then
errorR(Error(FSComp.SR.tcOpenUsedWithPartiallyQualifiedPath(fullDisplayTextOfModRef modref), m)))
let modrefs = List.map p23 modrefs
modrefs |> List.iter (fun modref -> CheckEntityAttributes g modref m |> CommitOperationResult)
let openDecl = OpenDeclaration.Create (SynOpenDeclTarget.ModuleOrNamespace (SynLongIdent(longId, [], []), m), modrefs, [], scopem, false)
let env = OpenModuleOrNamespaceRefs tcSink g amap scopem false env modrefs openDecl
env, [openDecl]
let TcOpenTypeDecl (cenv: cenv) mOpenDecl scopem env (synType: SynType, m) =
let g = cenv.g
checkLanguageFeatureError g.langVersion LanguageFeature.OpenTypeDeclaration mOpenDecl
let ty, _tpenv = TcType cenv NoNewTypars CheckCxs ItemOccurrence.Open WarnOnIWSAM.Yes env emptyUnscopedTyparEnv synType
if not (isAppTy g ty) then
error(Error(FSComp.SR.tcNamedTypeRequired("open type"), m))
if isByrefTy g ty then
error(Error(FSComp.SR.tcIllegalByrefsInOpenTypeDeclaration(), m))
let openDecl = OpenDeclaration.Create (SynOpenDeclTarget.Type (synType, m), [], [ty], scopem, false)
let env = OpenTypeContent cenv.tcSink g cenv.amap scopem env ty openDecl
env, [openDecl]
let TcOpenDecl (cenv: cenv) mOpenDecl scopem env target =
let g = cenv.g
match target with
| SynOpenDeclTarget.ModuleOrNamespace (longId, m) ->
TcOpenModuleOrNamespaceDecl cenv.tcSink g cenv.amap scopem env (longId.LongIdent, m)
| SynOpenDeclTarget.Type (synType, m) ->
TcOpenTypeDecl cenv mOpenDecl scopem env (synType, m)
let MakeSafeInitField (cenv: cenv) env m isStatic =
let id =
// Ensure that we have an g.CompilerGlobalState
ident(cenv.niceNameGen.FreshCompilerGeneratedName("init", m), m)
let taccess = TAccess [env.eAccessPath]
Construct.NewRecdField isStatic None id false cenv.g.int_ty true true [] [] XmlDoc.Empty taccess true
//-------------------------------------------------------------------------
// Build augmentation declarations
//-------------------------------------------------------------------------
module AddAugmentationDeclarations =
let tcaugHasNominalInterface g (tcaug: TyconAugmentation) tcref =
tcaug.tcaug_interfaces |> List.exists (fun (x, _, _) ->
match tryTcrefOfAppTy g x with
| ValueSome tcref2 when tyconRefEq g tcref2 tcref -> true
| _ -> false)
let AddGenericCompareDeclarations (cenv: cenv) (env: TcEnv) (scSet: Set<Stamp>) (tycon: Tycon) =
let g = cenv.g
if AugmentTypeDefinitions.TyconIsCandidateForAugmentationWithCompare g tycon && scSet.Contains tycon.Stamp then
let tcref = mkLocalTyconRef tycon
let tcaug = tycon.TypeContents
let ty = if tcref.Deref.IsFSharpException then g.exn_ty else generalizedTyconRef g tcref
let m = tycon.Range
let genericIComparableTy = mkWoNullAppTy g.system_GenericIComparable_tcref [ty]
let hasExplicitIComparable = tycon.HasInterface g g.mk_IComparable_ty
let hasExplicitGenericIComparable = tcaugHasNominalInterface g tcaug g.system_GenericIComparable_tcref
let hasExplicitIStructuralComparable = tycon.HasInterface g g.mk_IStructuralComparable_ty
if hasExplicitIComparable then
errorR(Error(FSComp.SR.tcImplementsIComparableExplicitly(tycon.DisplayName), m))
elif hasExplicitGenericIComparable then
errorR(Error(FSComp.SR.tcImplementsGenericIComparableExplicitly(tycon.DisplayName), m))
elif hasExplicitIStructuralComparable then
errorR(Error(FSComp.SR.tcImplementsIStructuralComparableExplicitly(tycon.DisplayName), m))
else
let hasExplicitGenericIComparable = tycon.HasInterface g genericIComparableTy
let cvspec1, cvspec2 = AugmentTypeDefinitions.MakeValsForCompareAugmentation g tcref
let cvspec3 = AugmentTypeDefinitions.MakeValsForCompareWithComparerAugmentation g tcref
PublishInterface cenv env.DisplayEnv tcref m true g.mk_IStructuralComparable_ty
PublishInterface cenv env.DisplayEnv tcref m true g.mk_IComparable_ty
if not tycon.IsFSharpException && not hasExplicitGenericIComparable then
PublishInterface cenv env.DisplayEnv tcref m true genericIComparableTy
tcaug.SetCompare (mkLocalValRef cvspec1, mkLocalValRef cvspec2)
tcaug.SetCompareWith (mkLocalValRef cvspec3)
PublishValueDefn cenv env ModuleOrMemberBinding cvspec1
PublishValueDefn cenv env ModuleOrMemberBinding cvspec2
PublishValueDefn cenv env ModuleOrMemberBinding cvspec3
let AddGenericEqualityWithComparerDeclarations (cenv: cenv) (env: TcEnv) (seSet: Set<Stamp>) (tycon: Tycon) =
let g = cenv.g
if AugmentTypeDefinitions.TyconIsCandidateForAugmentationWithEquals g tycon && seSet.Contains tycon.Stamp then
let tcref = mkLocalTyconRef tycon
let tcaug = tycon.TypeContents
let m = tycon.Range
let hasExplicitIStructuralEquatable = tycon.HasInterface g g.mk_IStructuralEquatable_ty
if hasExplicitIStructuralEquatable then
errorR(Error(FSComp.SR.tcImplementsIStructuralEquatableExplicitly(tycon.DisplayName), m))
else
let augmentation = AugmentTypeDefinitions.MakeValsForEqualityWithComparerAugmentation g tcref
PublishInterface cenv env.DisplayEnv tcref m true g.mk_IStructuralEquatable_ty
tcaug.SetHashAndEqualsWith (
mkLocalValRef augmentation.GetHashCode,
mkLocalValRef augmentation.GetHashCodeWithComparer,
mkLocalValRef augmentation.EqualsWithComparer,
Some (mkLocalValRef augmentation.EqualsExactWithComparer))
PublishValueDefn cenv env ModuleOrMemberBinding augmentation.GetHashCode
PublishValueDefn cenv env ModuleOrMemberBinding augmentation.GetHashCodeWithComparer
PublishValueDefn cenv env ModuleOrMemberBinding augmentation.EqualsWithComparer
PublishValueDefnMaybeInclCompilerGenerated cenv env true ModuleOrMemberBinding augmentation.EqualsExactWithComparer
let AddGenericCompareBindings (cenv: cenv) (tycon: Tycon) =
if (* AugmentTypeDefinitions.TyconIsCandidateForAugmentationWithCompare cenv.g tycon && *) Option.isSome tycon.GeneratedCompareToValues then
AugmentTypeDefinitions.MakeBindingsForCompareAugmentation cenv.g tycon
else
[]
let AddGenericCompareWithComparerBindings (cenv: cenv) (tycon: Tycon) =
if (* AugmentTypeDefinitions.TyconIsCandidateForAugmentationWithCompare cenv.g tycon && *) Option.isSome tycon.GeneratedCompareToWithComparerValues then
(AugmentTypeDefinitions.MakeBindingsForCompareWithComparerAugmentation cenv.g tycon)
else
[]
let AddGenericEqualityWithComparerBindings (cenv: cenv) (tycon: Tycon) =
if AugmentTypeDefinitions.TyconIsCandidateForAugmentationWithEquals cenv.g tycon && Option.isSome tycon.GeneratedHashAndEqualsWithComparerValues then
(AugmentTypeDefinitions.MakeBindingsForEqualityWithComparerAugmentation cenv.g tycon)
else
[]
let AddGenericHashAndComparisonDeclarations (cenv: cenv) (env: TcEnv) scSet seSet tycon =
AddGenericCompareDeclarations cenv env scSet tycon
AddGenericEqualityWithComparerDeclarations cenv env seSet tycon
let AddGenericHashAndComparisonBindings cenv tycon =
AddGenericCompareBindings cenv tycon @ AddGenericCompareWithComparerBindings cenv tycon @ AddGenericEqualityWithComparerBindings cenv tycon
// We can only add the Equals override after we've done the augmentation because we have to wait until
// tycon.HasOverride can give correct results
let AddGenericEqualityBindings (cenv: cenv) (env: TcEnv) tycon =
let g = cenv.g
if AugmentTypeDefinitions.TyconIsCandidateForAugmentationWithEquals g tycon then
let tcref = mkLocalTyconRef tycon
let tcaug = tycon.TypeContents
let ty = if tcref.Deref.IsFSharpException then g.exn_ty else generalizedTyconRef g tcref
let m = tycon.Range
// Note: tycon.HasOverride only gives correct results after we've done the type augmentation
let hasExplicitObjectEqualsOverride = tycon.HasOverride g "Equals" [g.obj_ty_ambivalent]
let hasExplicitGenericIEquatable = tcaugHasNominalInterface g tcaug g.system_GenericIEquatable_tcref
if hasExplicitGenericIEquatable then
errorR(Error(FSComp.SR.tcImplementsIEquatableExplicitly(tycon.DisplayName), m))
// Note: only provide the equals method if Equals is not implemented explicitly, and
// we're actually generating Hash/Equals for this type
if not hasExplicitObjectEqualsOverride &&
Option.isSome tycon.GeneratedHashAndEqualsWithComparerValues then
let vspec1, vspec2 = AugmentTypeDefinitions.MakeValsForEqualsAugmentation g tcref
tcaug.SetEquals (mkLocalValRef vspec1, mkLocalValRef vspec2)
if not tycon.IsFSharpException then
PublishInterface cenv env.DisplayEnv tcref m true (mkWoNullAppTy g.system_GenericIEquatable_tcref [ty])
PublishValueDefn cenv env ModuleOrMemberBinding vspec1
PublishValueDefn cenv env ModuleOrMemberBinding vspec2
AugmentTypeDefinitions.MakeBindingsForEqualsAugmentation g tycon
else []
else []
let ShouldAugmentUnion (g: TcGlobals) (tycon: Tycon) =
g.langVersion.SupportsFeature LanguageFeature.UnionIsPropertiesVisible &&
HasDefaultAugmentationAttribute g (mkLocalTyconRef tycon) &&
tycon.UnionCasesArray.Length > 1
let AddUnionAugmentationValues (cenv: cenv) (env: TcEnv) tycon =
let tcref = mkLocalTyconRef tycon
let vals = AugmentTypeDefinitions.MakeValsForUnionAugmentation cenv.g tcref
for v in vals do
PublishValueDefnMaybeInclCompilerGenerated cenv env true ModuleOrMemberBinding v
vals
// Checking of mutually recursive types, members and 'let' bindings in classes
//
// Technique: multiple passes.
// Phase1: create and establish type definitions and core representation information
// Phase2A: create Vals for recursive items given names and args
// Phase2B-D: type check AST to TAST collecting (sufficient) type constraints,
// generalize definitions, fix up recursive instances, build ctor binding
module MutRecBindingChecking =
/// Represents one element in a type definition, after the first phase
type TyconBindingPhase2A =
/// An entry corresponding to the definition of the static constructor of a class and optional of the incremental constructor (if one exists)
| Phase2AIncrClassCtor of StaticCtorInfo * IncrClassCtorInfo option
/// An 'inherit' declaration in an incremental class
///
/// Phase2AInherit (ty, arg, baseValOpt, m)
| Phase2AInherit of SynType * SynExpr * Val option * range
/// A set of value or function definitions in an incremental class
///
/// Phase2AIncrClassBindings (tcref, letBinds, isStatic, isRec, m)
| Phase2AIncrClassBindings of TyconRef * SynBinding list * bool * bool * range
/// A 'member' definition in a class
| Phase2AMember of PreCheckingRecursiveBinding
/// Indicates the super init has just been called, 'this' may now be published
| Phase2AIncrClassCtorJustAfterSuperInit
/// Indicates the last 'field' has been initialized, only 'do' comes after
| Phase2AIncrClassCtorJustAfterLastLet
/// The collected syntactic input definitions for a single type or type-extension definition
type TyconBindingsPhase2A =
| TyconBindingsPhase2A of Tycon option * DeclKind * Val list * TyconRef * Typar list * TType * TyconBindingPhase2A list
/// The collected syntactic input definitions for a recursive group of type or type-extension definitions
type MutRecDefnsPhase2AData = MutRecShape<TyconBindingsPhase2A, PreCheckingRecursiveBinding list, MutRecDefnsPhase2DataForModule * TcEnv> list
/// Represents one element in a type definition, after the second phase
type TyconBindingPhase2B =
| Phase2BIncrClassCtor of staticCtorInfo: StaticCtorInfo * incrCtorInfoOpt: IncrClassCtorInfo option * safeThisValBindOpt: Binding option
| Phase2BInherit of inheritsExpr: Expr
/// A set of value of function definitions in a class definition with an implicit constructor.
| Phase2BIncrClassBindings of IncrClassBindingGroup list
/// A member, by index
| Phase2BMember of int
/// An intermediate definition that represent the point in an implicit class definition where
/// the super type has been initialized.
| Phase2BIncrClassCtorJustAfterSuperInit
/// An intermediate definition that represent the point in an implicit class definition where
/// the last 'field' has been initialized, i.e. only 'do' and 'member' definitions come after
/// this point.
| Phase2BIncrClassCtorJustAfterLastLet
type TyconBindingsPhase2B = TyconBindingsPhase2B of Tycon option * TyconRef * TyconBindingPhase2B list
type MutRecDefnsPhase2BData = MutRecShape<TyconBindingsPhase2B, int list, MutRecDefnsPhase2DataForModule * TcEnv> list
/// Represents one element in a type definition, after the third phase
type TyconBindingPhase2C =
| Phase2CIncrClassCtor of StaticCtorInfo * IncrClassCtorInfo option * Binding option
| Phase2CInherit of Expr
| Phase2CIncrClassBindings of IncrClassBindingGroup list
| Phase2CMember of PreInitializationGraphEliminationBinding
// Indicates the last 'field' has been initialized, only 'do' comes after
| Phase2CIncrClassCtorJustAfterSuperInit
| Phase2CIncrClassCtorJustAfterLastLet
type TyconBindingsPhase2C = TyconBindingsPhase2C of Tycon option * TyconRef * TyconBindingPhase2C list
type MutRecDefnsPhase2CData = MutRecShape<TyconBindingsPhase2C, PreInitializationGraphEliminationBinding list, MutRecDefnsPhase2DataForModule * TcEnv> list
// Phase2A: create member prelimRecValues for "recursive" items, i.e. ctor val and member vals
// Phase2A: also processes their arg patterns - collecting type assertions