-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy pathCheckDeclarations.fs
5350 lines (4417 loc) · 308 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 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.CheckBasics
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
let TcClassRewriteStackGuardDepth = StackGuard.GetDepthOption "TcClassRewrite"
//-------------------------------------------------------------------------
// 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 * 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 "FSINNN" 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, ItemOccurence.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, [])
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 ResultCollectionSettings.AllResults amap scopem true OpenQualified env.eNameResEnv ad id rest true 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 CheckDuplicatesAbstractMethodParmsSig (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(synValSig, _, m) ->
CheckDuplicatesArgNames synValSig m
| _ -> ()
| _ -> ()
module TcRecdUnionAndEnumDeclarations =
let CombineReprAccess parent vis =
match parent with
| ParentNone -> vis
| Parent tcref -> combineAccess vis tcref.TypeReprAccessibility
let MakeRecdFieldSpec _cenv env parent (isStatic, konst, tyR, attrsForProperty, attrsForField, id, nameGenerated, isMutable, vol, xmldoc, vis, m) =
let vis, _ = ComputeAccessAndCompPath 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, nameGenerated, ty, isMutable, xmldoc, vis, m) =
let g = cenv.g
let attrs, _ = TcAttributesWithPossibleTargets false 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 ItemOccurence.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 cenv 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 false 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 xmlDoc = xmldoc.ToXmlDoc(true, Some [])
TcFieldDecl cenv env parent false tpenv (isStatic, attribs, id, idOpt.IsNone, ty, isMutable, xmlDoc, vis, m)
let TcNamedFieldDecl cenv env parent isIncrClass tpenv (SynField(Attributes attribs, isStatic, id, ty, isMutable, xmldoc, vis, m, _)) =
match id with
| None -> error (Error(FSComp.SR.tcFieldRequiresName(), m))
| Some id ->
let xmlDoc = xmldoc.ToXmlDoc(true, Some [])
TcFieldDecl cenv env parent isIncrClass tpenv (isStatic, attribs, id, false, ty, isMutable, xmlDoc, vis, m)
let TcNamedFieldDecls cenv env parent isIncrClass tpenv fields =
fields |> List.map (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 ValidateFieldNames (synFields: SynField list, tastFields: RecdField list) =
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 = Some _) ->
error(Error(FSComp.SR.tcFieldNameIsUsedModeThanOnce(id.idText), id.idRange))
| SynField(idOpt = Some id), SynField(idOpt = None)
| SynField(idOpt = None), SynField(idOpt = Some id) ->
error(Error(FSComp.SR.tcFieldNameConflictsWithGeneratedNameForAnonymousField(id.idText), id.idRange))
| _ -> assert false
| _ ->
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 attrs = TcAttributes cenv env AttributeTargets.UnionCaseDecl synAttrs // the attributes of a union case decl get attached to the generated "static factory" method
let vis, _ = ComputeAccessAndCompPath 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, ItemOccurence.Binding, env.AccessRights)
TcNamedFieldDecl cenv env parent false tpenv fld
| _ ->
TcAnonFieldDecl cenv env parent tpenv (mkUnionCaseFieldName nFields i) fld)
ValidateFieldNames(flds, rfields)
rfields, thisTy
| SynUnionCaseKind.FullType (ty, arity) ->
let tyR, _ = TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInType WarnOnIWSAM.Yes env tpenv ty
let curriedArgTys, recordTy = GetTopTauTypeInFSharpForm g (arity |> TranslateSynValInfo 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 cenv 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 xmlDoc = xmldoc.ToXmlDoc(true, Some names)
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.map (TcUnionCaseDecl cenv env parent thisTy thisTyInst tpenv hasRQAAttribute)
unionCasesR |> CheckDuplicates (fun uc -> uc.Id) "union case"
let TcEnumDecl cenv env parent thisTy fieldTy (SynEnumCase(attributes=Attributes synAttrs; ident= SynIdent(id,_); value=v; xmlDoc=xmldoc; range=m)) =
let attrs = TcAttributes cenv env AttributeTargets.Field synAttrs
match v with
| SynConst.Bytes _
| SynConst.UInt16s _
| SynConst.UserNum _ -> error(Error(FSComp.SR.tcInvalidEnumerationLiteral(), m))
| _ ->
let v = TcConst cenv fieldTy m env v
let vis, _ = ComputeAccessAndCompPath env None m None None parent
let vis = CombineReprAccess parent vis
if id.idText = "value__" then errorR(Error(FSComp.SR.tcNotValidEnumCaseName(), id.idRange))
let xmlDoc = xmldoc.ToXmlDoc(true, Some [])
Construct.NewRecdField true (Some v) id false thisTy false false [] attrs xmlDoc vis false
let TcEnumDecls (cenv: cenv) env parent thisTy enumCases =
let g = cenv.g
let fieldTy = NewInferenceType g
let enumCases' = enumCases |> List.map (TcEnumDecl cenv env 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(synValSig, 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 ResultCollectionSettings.AllResults amap m true OpenQualified env.NameEnv ad id rest true 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 ItemOccurence.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
// 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 implicit constructor for a class
| Phase2AIncrClassCtor of IncrClassCtorLhs
/// 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
#if OPEN_IN_TYPE_DECLARATIONS
/// A dummy declaration, should we ever support 'open' in type definitions
| Phase2AOpen of SynOpenDeclTarget * range
#endif
/// 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 IncrClassCtorLhs * Binding option
| Phase2BInherit of Expr * Val option
/// A set of value of function definitions in a class definition with an implicit constructor.
| Phase2BIncrClassBindings of IncrClassBindingGroup list
| 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 IncrClassCtorLhs * Binding option
| Phase2CInherit of Expr * Val option
| 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
let TcMutRecBindings_Phase2A_CreateRecursiveValuesAndCheckArgumentPatterns (cenv: cenv) tpenv (envMutRec, mutRecDefns: MutRecDefnsPhase2Info) =
let g = cenv.g
// The basic iteration over the declarations in a single type definition
// State:
// tpenv: floating type parameter environment
// recBindIdx: index of the recursive binding
// prelimRecValuesRev: accumulation of prelim value entries
// uncheckedBindsRev: accumulation of unchecked bindings
let (defnsAs: MutRecDefnsPhase2AData), (tpenv, _, uncheckedBindsRev) =
let initialOuterState = (tpenv, 0, ([]: PreCheckingRecursiveBinding list))
(initialOuterState, envMutRec, mutRecDefns) |||> MutRecShapes.mapFoldWithEnv (fun outerState envForDecls defn ->
let tpenv, recBindIdx, uncheckedBindsRev = outerState
match defn with
| MutRecShape.Module _ -> failwith "unreachable"
| MutRecShape.Open x -> MutRecShape.Open x, outerState
| MutRecShape.ModuleAbbrev x -> MutRecShape.ModuleAbbrev x, outerState
| MutRecShape.Lets recBinds ->
let normRecDefns =
[ for RecDefnBindingInfo(a, b, c, bind) in recBinds do
yield NormalizedRecBindingDefn(a, b, c, BindingNormalization.NormalizeBinding ValOrMemberBinding cenv envForDecls bind) ]
let bindsAndValues, (tpenv, recBindIdx) = ((tpenv, recBindIdx), normRecDefns) ||> List.mapFold (AnalyzeAndMakeAndPublishRecursiveValue ErrorOnOverrides false cenv envForDecls)
let binds = bindsAndValues |> List.collect fst
let defnAs = MutRecShape.Lets binds
defnAs, (tpenv, recBindIdx, List.rev binds @ uncheckedBindsRev)
| MutRecShape.Tycon (MutRecDefnsPhase2InfoForTycon(tyconOpt, tcref, declaredTyconTypars, declKind, binds, _)) ->
// Class members can access protected members of the implemented type
// Class members can access private members in the ty
let isExtrinsic = (declKind = ExtrinsicExtensionBinding)
let initialEnvForTycon = MakeInnerEnvForTyconRef envForDecls tcref isExtrinsic
// Re-add the type constructor to make it take precedence for record label field resolutions
// This does not apply to extension members: in those cases the relationship between the record labels
// and the type is too extruded
let envForTycon =
if isExtrinsic then
initialEnvForTycon
else
AddLocalTyconRefs true g cenv.amap tcref.Range [tcref] initialEnvForTycon
// Make fresh version of the class type for type checking the members and lets *
let _, copyOfTyconTypars, _, objTy, thisTy = FreshenObjectArgType cenv envForTycon.TraitContext tcref.Range TyparRigidity.WillBeRigid tcref isExtrinsic declaredTyconTypars
// The basic iteration over the declarations in a single type definition
let initialInnerState = (None, envForTycon, tpenv, recBindIdx, uncheckedBindsRev)
let defnAs, (_, _envForTycon, tpenv, recBindIdx, uncheckedBindsRev) =
(initialInnerState, binds) ||> List.collectFold (fun innerState defn ->
let (TyconBindingDefn(containerInfo, newslotsOK, declKind, classMemberDef, m)) = defn
let incrClassCtorLhsOpt, envForTycon, tpenv, recBindIdx, uncheckedBindsRev = innerState
if tcref.IsTypeAbbrev then
// ideally we'd have the 'm' of the type declaration stored here, to avoid needing to trim to line to approx
error(Error(FSComp.SR.tcTypeAbbreviationsMayNotHaveMembers(), (trimRangeToLine m)))
if tcref.IsEnumTycon && (declKind <> ExtrinsicExtensionBinding) then
// ideally we'd have the 'm' of the type declaration stored here, to avoid needing to trim to line to approx
error(Error(FSComp.SR.tcEnumerationsMayNotHaveMembers(), (trimRangeToLine m)))
match classMemberDef, containerInfo with
| SynMemberDefn.ImplicitCtor (vis, Attributes attrs, SynSimplePats.SimplePats(spats, _), thisIdOpt, xmlDoc, m), ContainerInfo(_, Some(MemberOrValContainerInfo(tcref, _, baseValOpt, safeInitInfo, _))) ->
if tcref.TypeOrMeasureKind = TyparKind.Measure then
error(Error(FSComp.SR.tcMeasureDeclarationsRequireStaticMembers(), m))
// Phase2A: make incrClassCtorLhs - ctorv, thisVal etc, type depends on argty(s)
let incrClassCtorLhs = TcImplicitCtorLhs_Phase2A(cenv, envForTycon, tpenv, tcref, vis, attrs, spats, thisIdOpt, baseValOpt, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy, xmlDoc)
// Phase2A: Add copyOfTyconTypars from incrClassCtorLhs - or from tcref
let envForTycon = AddDeclaredTypars CheckForDuplicateTypars incrClassCtorLhs.InstanceCtorDeclaredTypars envForTycon
let innerState = (Some incrClassCtorLhs, envForTycon, tpenv, recBindIdx, uncheckedBindsRev)
[Phase2AIncrClassCtor incrClassCtorLhs], innerState
| SynMemberDefn.ImplicitInherit (ty, arg, _baseIdOpt, m), _ ->
if tcref.TypeOrMeasureKind = TyparKind.Measure then
error(Error(FSComp.SR.tcMeasureDeclarationsRequireStaticMembers(), m))
// Phase2A: inherit ty(arg) as base - pass through
// Phase2A: pick up baseValOpt!
let baseValOpt = incrClassCtorLhsOpt |> Option.bind (fun x -> x.InstanceCtorBaseValOpt)
let innerState = (incrClassCtorLhsOpt, envForTycon, tpenv, recBindIdx, uncheckedBindsRev)
[Phase2AInherit (ty, arg, baseValOpt, m); Phase2AIncrClassCtorJustAfterSuperInit], innerState
| SynMemberDefn.LetBindings (letBinds, isStatic, isRec, m), _ ->
match tcref.TypeOrMeasureKind, isStatic with
| TyparKind.Measure, false -> error(Error(FSComp.SR.tcMeasureDeclarationsRequireStaticMembers(), m))
| _ -> ()
if not isStatic && tcref.IsStructOrEnumTycon then
let allDo = letBinds |> List.forall (function SynBinding(kind=SynBindingKind.Do) -> true | _ -> false)
// Code for potential future design change to allow functions-compiled-as-members in structs
if allDo then
errorR(Deprecated(FSComp.SR.tcStructsMayNotContainDoBindings(), (trimRangeToLine m)))
else
// Code for potential future design change to allow functions-compiled-as-members in structs
errorR(Error(FSComp.SR.tcStructsMayNotContainLetBindings(), (trimRangeToLine m)))
if isStatic && Option.isNone incrClassCtorLhsOpt then
errorR(Error(FSComp.SR.tcStaticLetBindingsRequireClassesWithImplicitConstructors(), m))
// Phase2A: let-bindings - pass through
let innerState = (incrClassCtorLhsOpt, envForTycon, tpenv, recBindIdx, uncheckedBindsRev)
[Phase2AIncrClassBindings (tcref, letBinds, isStatic, isRec, m)], innerState
| SynMemberDefn.Member (bind, m), _ ->
// Phase2A: member binding - create prelim valspec (for recursive reference) and RecursiveBindingInfo
let NormalizedBinding(_, _, _, _, _, _, _, valSynData, _, _, _, _) as bind = BindingNormalization.NormalizeBinding ValOrMemberBinding cenv envForTycon bind
let (SynValData(memberFlagsOpt, _, _)) = valSynData
match tcref.TypeOrMeasureKind with
| TyparKind.Type -> ()
| TyparKind.Measure ->
match memberFlagsOpt with
| None -> ()
| Some memberFlags ->
if memberFlags.IsInstance then error(Error(FSComp.SR.tcMeasureDeclarationsRequireStaticMembers(), m))
match memberFlags.MemberKind with
| SynMemberKind.Constructor -> error(Error(FSComp.SR.tcMeasureDeclarationsRequireStaticMembersNotConstructors(), m))
| _ -> ()
let envForMember =
match incrClassCtorLhsOpt with
| None -> AddDeclaredTypars CheckForDuplicateTypars copyOfTyconTypars envForTycon
| Some _ -> envForTycon
let rbind = NormalizedRecBindingDefn(containerInfo, newslotsOK, declKind, bind)
let overridesOK = declKind.CanOverrideOrImplement
let (binds, _values), (tpenv, recBindIdx) = AnalyzeAndMakeAndPublishRecursiveValue overridesOK false cenv envForMember (tpenv, recBindIdx) rbind
let cbinds = [ for rbind in binds -> Phase2AMember rbind ]
let innerState = (incrClassCtorLhsOpt, envForTycon, tpenv, recBindIdx, List.rev binds @ uncheckedBindsRev)
cbinds, innerState
#if OPEN_IN_TYPE_DECLARATIONS
| SynMemberDefn.Open (target, m), _ ->
let innerState = (incrClassCtorLhsOpt, env, tpenv, recBindIdx, prelimRecValuesRev, uncheckedBindsRev)
[ Phase2AOpen (target, m) ], innerState
#endif
| definition ->
error(InternalError(sprintf "Unexpected definition %A" definition, m)))
// If no constructor call, insert Phase2AIncrClassCtorJustAfterSuperInit at start
let defnAs =
match defnAs with
| Phase2AIncrClassCtor _ as b1 :: rest ->
let rest =
if rest |> List.exists (function Phase2AIncrClassCtorJustAfterSuperInit -> true | _ -> false) then
rest
else
Phase2AIncrClassCtorJustAfterSuperInit :: rest
// Insert Phase2AIncrClassCtorJustAfterLastLet at the point where local construction is known to have been finished
let rest =
let isAfter b =
match b with
#if OPEN_IN_TYPE_DECLARATIONS
| Phase2AOpen _
#endif
| Phase2AIncrClassCtor _ | Phase2AInherit _ | Phase2AIncrClassCtorJustAfterSuperInit -> false
| Phase2AIncrClassBindings (_, binds, _, _, _) -> binds |> List.exists (function SynBinding (kind=SynBindingKind.Do) -> true | _ -> false)
| Phase2AIncrClassCtorJustAfterLastLet
| Phase2AMember _ -> true
let restRev = List.rev rest
let afterRev = restRev |> List.takeWhile isAfter
let beforeRev = restRev |> List.skipWhile isAfter
[ yield! List.rev beforeRev
yield Phase2AIncrClassCtorJustAfterLastLet
yield! List.rev afterRev ]
b1 :: rest
// Cover the case where this is not a type with an implicit constructor.
| rest -> rest
let prelimRecValues = [ for x in defnAs do match x with Phase2AMember bind -> yield bind.RecBindingInfo.Val | _ -> () ]
let defnAs = MutRecShape.Tycon(TyconBindingsPhase2A(tyconOpt, declKind, prelimRecValues, tcref, copyOfTyconTypars, thisTy, defnAs))
defnAs, (tpenv, recBindIdx, uncheckedBindsRev))
let uncheckedRecBinds = List.rev uncheckedBindsRev
(defnsAs, uncheckedRecBinds, tpenv)
/// Phase2B: check each of the bindings, convert from ast to tast and collects type assertions.
/// Also generalize incrementally.
let TcMutRecBindings_Phase2B_TypeCheckAndIncrementalGeneralization (cenv: cenv) tpenv envInitial (envMutRec, defnsAs: MutRecDefnsPhase2AData, uncheckedRecBinds: PreCheckingRecursiveBinding list, scopem) : MutRecDefnsPhase2BData * _ * _ =
let g = cenv.g
let (defnsBs: MutRecDefnsPhase2BData), (tpenv, generalizedRecBinds, preGeneralizationRecBinds, _, _) =
let uncheckedRecBindsTable = uncheckedRecBinds |> List.map (fun rbind -> rbind.RecBindingInfo.Val.Stamp, rbind) |> Map.ofList
// Loop through the types being defined...
//
// The envNonRec is the environment used to limit generalization to prevent leakage of type
// variables into the types of 'let' bindings. It gets accumulated across type definitions, e.g.
// consider
//
// type A<'T>() =
// let someFuncValue: 'A = A<'T>.Meth2()
// static member Meth2() = A<'T>.Meth2()
// and B<'T>() =
// static member Meth1() = A<'T>.Meth2()
//
// Here 'A can't be generalized, even at 'Meth1'.
//