diff --git a/FSharpBuild.Directory.Build.props b/FSharpBuild.Directory.Build.props index 733d843fefc..12288215da0 100644 --- a/FSharpBuild.Directory.Build.props +++ b/FSharpBuild.Directory.Build.props @@ -9,10 +9,6 @@ - - true - - false @@ -110,6 +106,29 @@ $(ProtoOutputPath)\fsc\Microsoft.FSharp.Overrides.NetSdk.targets + + + true + + + <_FSharpRepoDotNetHost Condition="Exists('$(RepoRoot).dotnet/dotnet.exe')">$(RepoRoot).dotnet/dotnet.exe + <_FSharpRepoDotNetHost Condition="'$(_FSharpRepoDotNetHost)' == '' and Exists('$(RepoRoot).dotnet/dotnet')">$(RepoRoot).dotnet/dotnet + <_FSharpRepoDotNetHost Condition="'$(_FSharpRepoDotNetHost)' == '' and '$(DOTNET_HOST_PATH)' != ''">$(DOTNET_HOST_PATH) + + $([System.IO.Path]::GetDirectoryName('$(_FSharpRepoDotNetHost)')) + $([System.IO.Path]::GetFileName('$(_FSharpRepoDotNetHost)')) + "$(ProtoOutputPath)/fsc/fsc.dll" + + $([System.IO.Path]::GetDirectoryName('$(_FSharpRepoDotNetHost)')) + $([System.IO.Path]::GetFileName('$(_FSharpRepoDotNetHost)')) + "$(ProtoOutputPath)/fsc/fsi.dll" + + Tycon + /// Type, mapping mangled name to Tycon, e.g. + //// "Dictionary`2" --> Tycon //// "ListModule" --> Tycon with module info //// "FooException" --> Tycon with exception info member _.AllEntities = entities @@ -2135,127 +2141,127 @@ type ModuleOrNamespaceType(kind: ModuleOrNamespaceKind, vals: QueueList, en let entity = create () mtyp.AddModuleOrNamespaceByMutation entity entity) -#endif - +#endif + /// Return a new module or namespace type with an entity added. - member _.AddEntity(tycon: Tycon) = + member _.AddEntity(tycon: Tycon) = ModuleOrNamespaceType(kind, vals, entities.AppendOne tycon) - + /// Return a new module or namespace type with a value added. - member _.AddVal(vspec: Val) = + member _.AddVal(vspec: Val) = ModuleOrNamespaceType(kind, vals.AppendOne vspec, entities) - + /// Get a table of the active patterns defined in this module. member _.ActivePatternElemRefLookupTable = activePatternElemRefCache - - /// Get a list of types defined within this module, namespace or type. + + /// Get a list of types defined within this module, namespace or type. member _.TypeDefinitions = entities |> Seq.filter (fun x -> not x.IsFSharpException && not x.IsModuleOrNamespace) |> Seq.toList - /// Get a list of F# exception definitions defined within this module, namespace or type. + /// Get a list of F# exception definitions defined within this module, namespace or type. member _.ExceptionDefinitions = entities |> Seq.filter (fun x -> x.IsFSharpException) |> Seq.toList - /// Get a list of module and namespace definitions defined within this module, namespace or type. + /// Get a list of module and namespace definitions defined within this module, namespace or type. member _.ModuleAndNamespaceDefinitions = entities |> Seq.filter (fun x -> x.IsModuleOrNamespace) |> Seq.toList - /// Get a list of type and exception definitions defined within this module, namespace or type. + /// Get a list of type and exception definitions defined within this module, namespace or type. member _.TypeAndExceptionDefinitions = entities |> Seq.filter (fun x -> not x.IsModuleOrNamespace) |> Seq.toList - /// Get a table of types defined within this module, namespace or type. The - /// table is indexed by both name and generic arity. This means that for generic + /// Get a table of types defined within this module, namespace or type. The + /// table is indexed by both name and generic arity. This means that for generic /// types "List`1", the entry (List, 1) will be present. - member mtyp.TypesByDemangledNameAndArity = + member mtyp.TypesByDemangledNameAndArity = let version = System.Threading.Volatile.Read(&entitiesVersion) - cacheOptByrefByVersion version &tyconsByDemangledNameAndArityCache (fun () -> + cacheOptByrefByVersion version &tyconsByDemangledNameAndArityCache (fun () -> LayeredMap.Empty.AddMany( mtyp.TypeAndExceptionDefinitions |> List.map (fun (tc: Tycon) -> Construct.KeyTyconByDecodedName tc.LogicalName tc) |> List.toArray)) - /// Get a table of types defined within this module, namespace or type. The + /// Get a table of types defined within this module, namespace or type. The /// table is indexed by both name and, for generic types, also by mangled name. - member mtyp.TypesByAccessNames = + member mtyp.TypesByAccessNames = let version = System.Threading.Volatile.Read(&entitiesVersion) - cacheOptByrefByVersion version &tyconsByAccessNamesCache (fun () -> + cacheOptByrefByVersion version &tyconsByAccessNamesCache (fun () -> LayeredMultiMap.Empty.AddMany (mtyp.TypeAndExceptionDefinitions |> List.toArray |> Array.collect (fun (tc: Tycon) -> Construct.KeyTyconByAccessNames tc.LogicalName tc))) // REVIEW: we can remove this lookup and use AllEntitiesByMangledName instead? - member mtyp.TypesByMangledName = - let addTyconByMangledName (x: Tycon) tab = NameMap.add x.LogicalName x tab + member mtyp.TypesByMangledName = + let addTyconByMangledName (x: Tycon) tab = NameMap.add x.LogicalName x tab let version = System.Threading.Volatile.Read(&entitiesVersion) - cacheOptByrefByVersion version &tyconsByMangledNameCache (fun () -> + cacheOptByrefByVersion version &tyconsByMangledNameCache (fun () -> List.foldBack addTyconByMangledName mtyp.TypeAndExceptionDefinitions Map.empty) /// Get a table of entities indexed by both logical and compiled names - member mtyp.AllEntitiesByCompiledAndLogicalMangledNames: NameMap = - let addEntityByMangledName (x: Entity) tab = + member mtyp.AllEntitiesByCompiledAndLogicalMangledNames: NameMap = + let addEntityByMangledName (x: Entity) tab = let name1 = x.LogicalName let name2 = x.CompiledName - let tab = NameMap.add name1 x tab + let tab = NameMap.add name1 x tab if name1 = name2 then tab - else NameMap.add name2 x tab - + else NameMap.add name2 x tab + let version = System.Threading.Volatile.Read(&entitiesVersion) - cacheOptByrefByVersion version &allEntitiesByMangledNameCache (fun () -> + cacheOptByrefByVersion version &allEntitiesByMangledNameCache (fun () -> QueueList.foldBack addEntityByMangledName entities Map.empty) /// Get a table of entities indexed by both logical name - member _.AllEntitiesByLogicalMangledName: NameMap = - let addEntityByMangledName (x: Entity) tab = NameMap.add x.LogicalName x tab + member _.AllEntitiesByLogicalMangledName: NameMap = + let addEntityByMangledName (x: Entity) tab = NameMap.add x.LogicalName x tab QueueList.foldBack addEntityByMangledName entities Map.empty /// Get a table of values and members indexed by partial linkage key, which includes name, the mangled name of the parent type (if any), /// and the method argument count (if any). - member _.AllValsAndMembersByPartialLinkageKey = - let addValByMangledName (x: Val) tab = + member _.AllValsAndMembersByPartialLinkageKey = + let addValByMangledName (x: Val) tab = if x.IsCompiledAsTopLevel then let key = x.GetLinkagePartialKey() - MultiMap.add key x tab + MultiMap.add key x tab else tab - cacheOptByref &allValsAndMembersByPartialLinkageKeyCache (fun () -> + cacheOptByref &allValsAndMembersByPartialLinkageKeyCache (fun () -> QueueList.foldBack addValByMangledName vals MultiMap.empty) /// Try to find the member with the given linkage key in the given module. - member mtyp.TryLinkVal(ccu: CcuThunk, key: ValLinkageFullKey) = + member mtyp.TryLinkVal(ccu: CcuThunk, key: ValLinkageFullKey) = mtyp.AllValsAndMembersByPartialLinkageKey |> MultiMap.find key.PartialKey - |> List.tryFind (fun v -> match key.TypeForLinkage with + |> List.tryFind (fun v -> match key.TypeForLinkage with | None -> true | Some keyTy -> ccu.MemberSignatureEquality(keyTy, v.Type)) |> ValueOption.ofOption /// Get a table of values indexed by logical name - member _.AllValsByLogicalName = - let addValByName (x: Val) tab = + member _.AllValsByLogicalName = + let addValByName (x: Val) tab = // Note: names may occur twice prior to raising errors about this in PostTypeCheckSemanticChecks // Earlier ones take precedence since we report errors about the later ones - if not x.IsMember && not x.IsCompilerGenerated then - NameMap.add x.LogicalName x tab + if not x.IsMember && not x.IsCompilerGenerated then + NameMap.add x.LogicalName x tab else tab - cacheOptByref &allValsByLogicalNameCache (fun () -> + cacheOptByref &allValsByLogicalNameCache (fun () -> QueueList.foldBack addValByName vals Map.empty) /// Compute a table of values and members indexed by logical name. - member _.AllValsAndMembersByLogicalNameUncached = - let addValByName (x: Val) tab = - if not x.IsCompilerGenerated then - MultiMap.add x.LogicalName x tab + member _.AllValsAndMembersByLogicalNameUncached = + let addValByName (x: Val) tab = + if not x.IsCompilerGenerated then + MultiMap.add x.LogicalName x tab else tab QueueList.foldBack addValByName vals MultiMap.empty /// Get a table of F# exception definitions indexed by demangled name, so 'FailureException' is indexed by 'Failure' - member mtyp.ExceptionDefinitionsByDemangledName = + member mtyp.ExceptionDefinitionsByDemangledName = let add (tycon: Tycon) acc = NameMap.add tycon.LogicalName tycon acc - cacheOptByref &exconsByDemangledNameCache (fun () -> + cacheOptByref &exconsByDemangledNameCache (fun () -> List.foldBack add mtyp.ExceptionDefinitions Map.empty) /// Get a table of nested module and namespace fragments indexed by demangled name (so 'ListModule' becomes 'List') - member _.ModulesAndNamespacesByDemangledName = - let add (entity: Entity) acc = - if entity.IsModuleOrNamespace then + member _.ModulesAndNamespacesByDemangledName = + let add (entity: Entity) acc = + if entity.IsModuleOrNamespace then NameMap.add entity.DemangledModuleOrNamespaceName entity acc else acc let version = System.Threading.Volatile.Read(&entitiesVersion) - cacheOptByrefByVersion version &modulesByDemangledNameCache (fun () -> + cacheOptByrefByVersion version &modulesByDemangledNameCache (fun () -> QueueList.foldBack add entities Map.empty) [] @@ -2264,13 +2270,13 @@ type ModuleOrNamespaceType(kind: ModuleOrNamespaceKind, vals: QueueList, en override _.ToString() = "ModuleOrNamespaceType(...)" /// Represents a module or namespace definition in the typed AST -type ModuleOrNamespace = Entity +type ModuleOrNamespace = Entity /// Represents a type or exception definition in the typed AST type Tycon = Entity -let getNameOfScopeRef sref = - match sref with +let getNameOfScopeRef sref = + match sref with | ILScopeRef.Local -> "" | ILScopeRef.Module mref -> mref.Name | ILScopeRef.Assembly aref -> aref.Name @@ -2284,7 +2290,7 @@ let private isInternalCompPath x = let private (|Public|Internal|Private|) (TAccess p) = match p with | [] -> Public - | _ when List.forall isInternalCompPath p -> Internal + | _ when List.forall isInternalCompPath p -> Internal | _ -> Private let getSyntaxAccessForCompPath (TAccess a) = match a with | CompPath(_, sa, _) :: _ -> sa | _ -> SyntaxAccess.Unknown @@ -2297,7 +2303,7 @@ let updateSyntaxAccessForCompPath access syntaxAccess = /// Represents the constraint on access for a construct [] type Accessibility = - /// Indicates the construct can only be accessed from any code in the given type constructor, module or assembly. [] indicates global scope. + /// Indicates the construct can only be accessed from any code in the given type constructor, module or assembly. [] indicates global scope. | TAccess of compilationPaths: CompilationPath list member public x.IsPublic = match x with Public -> true | _ -> false @@ -2328,7 +2334,7 @@ type Accessibility = override x.ToString() = match x with | TAccess paths -> - let mangledTextOfCompPath (CompPath(scoref, _, path)) = getNameOfScopeRef scoref + "/" + textOfPath (List.map fst path) + let mangledTextOfCompPath (CompPath(scoref, _, path)) = getNameOfScopeRef scoref + "/" + textOfPath (List.map fst path) let scopename = if x.IsPublic then "public" elif x.IsInternal then "internal" @@ -2344,18 +2350,18 @@ type Accessibility = [] type TyparOptionalData = { - /// MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation + /// MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation /// The storage for the IL name for the type parameter. - mutable typar_il_name: string option + mutable typar_il_name: string option /// The documentation for the type parameter. Empty for inference variables. /// MUTABILITY: for linking when unpickling mutable typar_xmldoc: XmlDoc /// The inferred constraints for the type parameter or inference variable. - mutable typar_constraints: TyparConstraint list + mutable typar_constraints: TyparConstraint list - /// The declared attributes of the type parameter. Empty for type inference variables. + /// The declared attributes of the type parameter. Empty for type inference variables. mutable typar_attribs: Attribs /// Set to true if the typar is contravariant, i.e. declared as in C# @@ -2374,30 +2380,30 @@ type TyparData = Typar /// A declared generic type/measure parameter, or a type/measure inference variable. [] -type Typar = +type Typar = { - /// MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation + /// MUTABILITY: we set the names of generalized inference type parameters to make the look nice for IL code generation /// The identifier for the type parameter - mutable typar_id: Ident - + mutable typar_id: Ident + /// The flag data for the type parameter mutable typar_flags: TyparFlags - + /// The unique stamp of the type parameter /// MUTABILITY: for linking when unpickling - mutable typar_stamp: Stamp - - /// An inferred equivalence for a type inference variable. + mutable typar_stamp: Stamp + + /// An inferred equivalence for a type inference variable. mutable typar_solution: TType option /// A cached TAST type used when this type variable is used as type. mutable typar_astype: TType - + /// The optional data for the type parameter mutable typar_opt_data: TyparOptionalData option } - /// The name of the type parameter + /// The name of the type parameter member x.Name = x.typar_id.idText /// The range of the identifier for the type parameter definition @@ -2413,16 +2419,16 @@ type Typar = member x.Solution = x.typar_solution /// The inferred constraints for the type inference variable, if any - member x.Constraints = + member x.Constraints = match x.typar_opt_data with | Some optData -> optData.typar_constraints | _ -> [] - /// Indicates if the type variable is compiler generated, i.e. is an implicit type inference variable + /// Indicates if the type variable is compiler generated, i.e. is an implicit type inference variable member x.IsCompilerGenerated = x.typar_flags.IsCompilerGenerated /// Indicates if the type variable can be solved or given new constraints. The status of a type variable - /// generally always evolves towards being either rigid or solved. + /// generally always evolves towards being either rigid or solved. member x.Rigidity = x.typar_flags.Rigidity /// Indicates if a type parameter is needed at runtime and may not be eliminated @@ -2455,13 +2461,13 @@ type Typar = member x.IsErased = match x.Kind with TyparKind.Type -> false | _ -> true /// The declared attributes of the type parameter. Empty for type inference variables and parameters from .NET. - member x.Attribs = + member x.Attribs = match x.typar_opt_data with | Some optData -> optData.typar_attribs | _ -> [] /// Set the attributes on the type parameter - member x.SetAttribs attribs = + member x.SetAttribs attribs = match attribs, x.typar_opt_data with | [], None -> () | [], Some { typar_il_name = None; typar_xmldoc = doc; typar_constraints = []; typar_is_contravariant = false; typar_declared_name = None } when doc.IsEmpty -> @@ -2513,14 +2519,14 @@ type Typar = | _ -> x.typar_opt_data <- Some { typar_il_name = None; typar_xmldoc = XmlDoc.Empty; typar_constraints = cs; typar_attribs = []; typar_is_contravariant = false; typar_declared_name = None } /// Marks the typar as being contravariant - member x.MarkAsContravariant() = + member x.MarkAsContravariant() = match x.typar_opt_data with | Some optData -> optData.typar_is_contravariant <- true | _ -> x.typar_opt_data <- Some { typar_il_name = None; typar_xmldoc = XmlDoc.Empty; typar_constraints = []; typar_attribs = []; typar_is_contravariant = true; typar_declared_name = None } /// Creates a type variable that contains empty data, and is not yet linked. Only used during unpickling of F# metadata. - static member NewUnlinked() : Typar = + static member NewUnlinked() : Typar = { typar_id = Unchecked.defaultof<_> typar_flags = Unchecked.defaultof<_> typar_stamp = -1L @@ -2532,37 +2538,37 @@ type Typar = static member New (data: TyparData) : Typar = data /// Links a previously unlinked type variable to the given data. Only used during unpickling of F# metadata. - member x.Link (tg: TyparData) = + member x.Link (tg: TyparData) = x.typar_id <- tg.typar_id x.typar_flags <- tg.typar_flags x.typar_stamp <- tg.typar_stamp x.typar_solution <- tg.typar_solution match tg.typar_opt_data with - | Some tg -> + | Some tg -> let optData = { typar_il_name = tg.typar_il_name; typar_xmldoc = tg.typar_xmldoc; typar_constraints = tg.typar_constraints; typar_attribs = tg.typar_attribs; typar_is_contravariant = tg.typar_is_contravariant; typar_declared_name = tg.typar_declared_name } x.typar_opt_data <- Some optData | None -> () /// Links a previously unlinked type variable to the given data. Only used during unpickling of F# metadata. - member x.AsType nullness = - match nullness with - | Nullness.Known NullnessInfo.AmbivalentToNull -> + member x.AsType nullness = + match nullness with + | Nullness.Known NullnessInfo.AmbivalentToNull -> let ty = x.typar_astype - match box ty with - | null -> + match box ty with + | null -> let ty2 = TType_var (x, Nullness.Known NullnessInfo.AmbivalentToNull) x.typar_astype <- ty2 ty2 | _ -> ty - | _ -> + | _ -> TType_var (x, nullness) /// Indicates if a type variable has been linked. Only used during unpickling of F# metadata. member x.IsLinked = x.typar_stamp <> -1L /// Indicates if a type variable has been solved. - member x.IsSolved = - match x.Solution with + member x.IsSolved = + match x.Solution with | None -> false | _ -> true @@ -2572,12 +2578,12 @@ type Typar = /// Sets the rigidity of a type variable member x.SetRigidity b = let flags = x.typar_flags - x.typar_flags <- TyparFlags(flags.Kind, b, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn, flags.IsSupportsNullFlex) + x.typar_flags <- TyparFlags(flags.Kind, b, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn, flags.IsSupportsNullFlex) /// Sets whether a type variable is compiler generated member x.SetCompilerGenerated b = let flags = x.typar_flags - x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, b, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn, flags.IsSupportsNullFlex) + x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, b, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn, flags.IsSupportsNullFlex) /// Sets whether a type variable has a static requirement member x.SetStaticReq b = @@ -2586,17 +2592,17 @@ type Typar = /// Sets whether a type variable is required at runtime member x.SetDynamicReq b = let flags = x.typar_flags - x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, b, flags.EqualityConditionalOn, flags.ComparisonConditionalOn, flags.IsSupportsNullFlex) + x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, b, flags.EqualityConditionalOn, flags.ComparisonConditionalOn, flags.IsSupportsNullFlex) - /// Sets whether the equality constraint of a type definition depends on this type variable + /// Sets whether the equality constraint of a type definition depends on this type variable member x.SetEqualityDependsOn b = let flags = x.typar_flags - x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, b, flags.ComparisonConditionalOn, flags.IsSupportsNullFlex) + x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, b, flags.ComparisonConditionalOn, flags.IsSupportsNullFlex) - /// Sets whether the comparison constraint of a type definition depends on this type variable + /// Sets whether the comparison constraint of a type definition depends on this type variable member x.SetComparisonDependsOn b = let flags = x.typar_flags - x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, b, flags.IsSupportsNullFlex) + x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, b, flags.IsSupportsNullFlex) [] member x.DebugText = x.ToString() @@ -2605,65 +2611,65 @@ type Typar = /// Represents a constraint on a type parameter or type [] -type TyparConstraint = +type TyparConstraint = - /// A constraint that a type is a subtype of the given type + /// A constraint that a type is a subtype of the given type | CoercesTo of ty: TType * range: range - /// A constraint for a default value for an inference type variable should it be neither generalized nor solved - | DefaultsTo of priority: int * ty: TType * range: range - - /// A constraint that a type has a 'null' value - | SupportsNull of range: range - + /// A constraint for a default value for an inference type variable should it be neither generalized nor solved + | DefaultsTo of priority: int * ty: TType * range: range + + /// A constraint that a type has a 'null' value + | SupportsNull of range: range + /// A constraint that a type doesn't support nullness - | NotSupportsNull of range - - /// A constraint that a type has a member with the given signature + | NotSupportsNull of range + + /// A constraint that a type has a member with the given signature | MayResolveMember of constraintInfo: TraitConstraintInfo * range: range - - /// A constraint that a type is a non-Nullable value type - /// These are part of .NET's model of generic constraints, and in order to - /// generate verifiable code we must attach them to F# generalized type variables as well. - | IsNonNullableStruct of range: range - - /// A constraint that a type is a reference type - | IsReferenceType of range: range - - /// A constraint that a type is a simple choice between one of the given ground types. Only arises from 'printf' format strings. See format.fs - | SimpleChoice of tys: TTypes * range: range - - /// A constraint that a type has a parameterless constructor - | RequiresDefaultConstructor of range: range - - /// A constraint that a type is an enum with the given underlying - | IsEnum of ty: TType * range: range - + + /// A constraint that a type is a non-Nullable value type + /// These are part of .NET's model of generic constraints, and in order to + /// generate verifiable code we must attach them to F# generalized type variables as well. + | IsNonNullableStruct of range: range + + /// A constraint that a type is a reference type + | IsReferenceType of range: range + + /// A constraint that a type is a simple choice between one of the given ground types. Only arises from 'printf' format strings. See format.fs + | SimpleChoice of tys: TTypes * range: range + + /// A constraint that a type has a parameterless constructor + | RequiresDefaultConstructor of range: range + + /// A constraint that a type is an enum with the given underlying + | IsEnum of ty: TType * range: range + /// A constraint that a type implements IComparable, with special rules for some known structural container types - | SupportsComparison of range: range - + | SupportsComparison of range: range + /// A constraint that a type does not have the Equality(false) attribute, or is not a structural type with this attribute, with special rules for some known structural container types - | SupportsEquality of range: range - + | SupportsEquality of range: range + /// A constraint that a type is a delegate from the given tuple of args to the given return type - | IsDelegate of aty: TType * bty: TType * range: range - + | IsDelegate of aty: TType * bty: TType * range: range + /// A constraint that a type is .NET unmanaged type | IsUnmanaged of range: range - + /// An anti-constraint indicating that ref structs (e.g. Span<>) are allowed here | AllowsRefStruct of range:range // %+A formatting is used, so this is not needed //[] //member x.DebugText = x.ToString() - - override x.ToString() = sprintf "%+A" x - + + override x.ToString() = sprintf "%+A" x + [] -type TraitWitnessInfo = +type TraitWitnessInfo = | TraitWitnessInfo of tys: TTypes * memberName: string * memberFlags: SynMemberFlags * objAndArgTys: TTypes * returnTy: TType option - + /// Get the member name associated with the member constraint. member x.MemberName = (let (TraitWitnessInfo(_, b, _, _, _)) = x in b) @@ -2674,22 +2680,22 @@ type TraitWitnessInfo = member x.DebugText = x.ToString() override x.ToString() = "TraitWitnessInfo(" + x.MemberName + ")" - -/// The specification of a member constraint that must be solved + +/// The specification of a member constraint that must be solved [] -type TraitConstraintInfo = +type TraitConstraintInfo = /// Indicates the signature of a member constraint. Contains a mutable solution cell /// to store the inferred solution of the constraint. And a mutable source cell to store /// the name of the type or member that defined the constraint. | TTrait of - tys: TTypes * - memberName: string * - memberFlags: SynMemberFlags * - objAndArgTys: TTypes * - returnTyOpt: TType option * - source: string option ref * - solution: TraitConstraintSln option ref + tys: TTypes * + memberName: string * + memberFlags: SynMemberFlags * + objAndArgTys: TTypes * + returnTyOpt: TType option * + source: string option ref * + solution: TraitConstraintSln option ref /// Get the types that may provide solutions for the traits member x.SupportTypes = (let (TTrait(tys = tys)) = x in tys) @@ -2701,12 +2707,12 @@ type TraitConstraintInfo = member x.MemberFlags = (let (TTrait(memberFlags = flags)) = x in flags) member x.CompiledObjectAndArgumentTypes = (let (TTrait(objAndArgTys = objAndArgTys)) = x in objAndArgTys) - + /// Get the optional return type recorded in the member constraint. member x.CompiledReturnType = (let (TTrait(returnTyOpt = retTy)) = x in retTy) - + /// Get or set the solution of the member constraint during inference - member x.Solution + member x.Solution with get() = (let (TTrait(solution = sln)) = x in sln.Value) and set v = (let (TTrait(solution = sln)) = x in sln.Value <- v) @@ -2724,17 +2730,17 @@ type TraitConstraintInfo = member x.DebugText = x.ToString() override x.ToString() = "TTrait(" + x.MemberLogicalName + ")" - + /// Represents the solution of a member constraint during inference. [] -type TraitConstraintSln = +type TraitConstraintSln = /// FSMethSln(ty, vref, minst) /// /// Indicates a trait is solved by an F# method. /// ty -- the type and its instantiation /// vref -- the method that solves the trait constraint - /// minst -- the generic method instantiation + /// minst -- the generic method instantiation /// staticTyOpt -- the static type governing a static virtual call, if any | FSMethSln of ty: TType * vref: ValRef * minst: TypeInst * staticTyOpt: TType option @@ -2755,14 +2761,14 @@ type TraitConstraintSln = /// ty -- the type and its instantiation /// extOpt -- information about an extension member, if any /// ilMethodRef -- the method that solves the trait constraint - /// minst -- the generic method instantiation + /// minst -- the generic method instantiation /// staticTyOpt -- the static type governing a static virtual call, if any | ILMethSln of ty: TType * extOpt: ILTypeRef option * ilMethodRef: ILMethodRef * minst: TypeInst * staticTyOpt: TType option /// ClosedExprSln expr /// /// Indicates a trait is solved by an erased provided expression - | ClosedExprSln of expr: Expr + | ClosedExprSln of expr: Expr /// Indicates a trait is solved by a 'fake' instance of an operator, like '+' on integers | BuiltInSln @@ -2771,24 +2777,24 @@ type TraitConstraintSln = //[] //member x.DebugText = x.ToString() - override x.ToString() = sprintf "%+A" x + override x.ToString() = sprintf "%+A" x /// The partial information used to index the methods of all those in a ModuleOrNamespace. [] -type ValLinkagePartialKey = +type ValLinkagePartialKey = { /// The name of the type with which the member is associated. None for non-member values. - MemberParentMangledName: string option + MemberParentMangledName: string option - /// Indicates if the member is an override. - MemberIsOverride: bool + /// Indicates if the member is an override. + MemberIsOverride: bool - /// Indicates the logical name of the member. - LogicalName: string + /// Indicates the logical name of the member. + LogicalName: string /// Indicates the total argument count of the member. TotalArgCount: int - } + } [] member x.DebugText = x.ToString() @@ -2817,26 +2823,26 @@ type ValOptionalData = /// MUTABILITY: for unpickle linkage mutable val_compiled_name: string option - /// If this field is populated, this is the implementation range for an item in a signature, otherwise it is + /// If this field is populated, this is the implementation range for an item in a signature, otherwise it is /// the signature range for an item in an implementation - mutable val_other_range: (range * bool) option + mutable val_other_range: (range * bool) option mutable val_const: Const option - - /// What is the original, unoptimized, closed-term definition, if any? + + /// What is the original, unoptimized, closed-term definition, if any? /// Used to implement [] - mutable val_defn: Expr option + mutable val_defn: Expr option /// Records the "extra information" for a value compiled as a method (rather /// than a closure or a local), including argument names, attributes etc. // - // MUTABILITY CLEANUP: mutability of this field is used by - // -- adjustAllUsesOfRecValue + // MUTABILITY CLEANUP: mutability of this field is used by + // -- adjustAllUsesOfRecValue // -- TLR optimizations // -- LinearizeTopMatch // - // For example, we use mutability to replace the empty arity initially assumed with an arity garnered from the - // type-checked expression. + // For example, we use mutability to replace the empty arity initially assumed with an arity garnered from the + // type-checked expression. mutable val_repr_info: ValReprInfo option /// Records the "extra information" for display purposes for expression-level function definitions @@ -2847,23 +2853,23 @@ type ValOptionalData = /// them with lambda arguments. mutable arg_repr_info_for_display: ArgReprInfo option - /// How visible is this? + /// How visible is this? /// MUTABILITY: for unpickle linkage - mutable val_access: Accessibility + mutable val_access: Accessibility /// XML documentation attached to a value. /// MUTABILITY: for unpickle linkage mutable val_xmldoc: XmlDoc - + /// the signature xml doc for an item in an implementation file. mutable val_other_xmldoc : XmlDoc option - /// Is the value actually an instance method/property/event that augments + /// Is the value actually an instance method/property/event that augments /// a type, and if so what name does it take in the IL? /// MUTABILITY: for unpickle linkage mutable val_member_info: ValMemberInfo option - // MUTABILITY CLEANUP: mutability of this field is used by + // MUTABILITY CLEANUP: mutability of this field is used by // -- LinearizeTopMatch // // The fresh temporary should just be created with the right parent @@ -2872,8 +2878,8 @@ type ValOptionalData = /// XML documentation signature for the value mutable val_xmldocsig: string - /// Custom attributes attached to the value. These contain references to other values (i.e. constructors in types). Mutable to fixup - /// these value references after copying a collection of values. + /// Custom attributes attached to the value. These contain references to other values (i.e. constructors in types). Mutable to fixup + /// these value references after copying a collection of values. mutable val_attribs: WellKnownValAttribs } @@ -2885,7 +2891,7 @@ type ValOptionalData = type ValData = Val [] -type Val = +type Val = { /// Mutable for unpickle linkage mutable val_logical_name: string @@ -2896,7 +2902,7 @@ type Val = mutable val_type: TType /// Mutable for unpickle linkage - mutable val_stamp: Stamp + mutable val_stamp: Stamp /// See vflags section further below for encoding/decodings here mutable val_flags: ValFlags @@ -2919,59 +2925,59 @@ type Val = val_xmldocsig = String.Empty val_attribs = WellKnownValAttribs.Empty } - /// Range of the definition (implementation) of the value, used by Visual Studio - member x.DefinitionRange = + /// Range of the definition (implementation) of the value, used by Visual Studio + member x.DefinitionRange = match x.val_opt_data with | Some { val_other_range = Some(m, true) } -> m | _ -> x.val_range - /// Range of the definition (signature) of the value, used by Visual Studio + /// Range of the definition (signature) of the value, used by Visual Studio member x.SigRange = match x.val_opt_data with | Some { arg_repr_info_for_display = Some { OtherRange = Some m } } -> m | Some { val_other_range = Some(m, false) } -> m | _ -> x.val_range - /// The place where the value was defined. + /// The place where the value was defined. member x.Range = x.val_range - /// A unique stamp within the context of this invocation of the compiler process + /// A unique stamp within the context of this invocation of the compiler process member x.Stamp = x.val_stamp - /// The type of the value. - /// May be a TType_forall for a generic value. - /// May be a type variable or type containing type variables during type inference. + /// The type of the value. + /// May be a TType_forall for a generic value. + /// May be a type variable or type containing type variables during type inference. // - // Note: this data is mutated during inference by adjustAllUsesOfRecValue when we replace the inferred type with a schema. + // Note: this data is mutated during inference by adjustAllUsesOfRecValue when we replace the inferred type with a schema. member x.Type = x.val_type /// How visible is this value, function or member? - member x.Accessibility = + member x.Accessibility = match x.val_opt_data with | Some optData -> optData.val_access | _ -> TAccess [] - /// The value of a value or member marked with [] - member x.LiteralValue = + /// The value of a value or member marked with [] + member x.LiteralValue = match x.val_opt_data with | Some optData -> optData.val_const | _ -> None /// Records the "extra information" for a value compiled as a method. /// - /// This indicates the number of arguments in each position for a curried + /// This indicates the number of arguments in each position for a curried /// functions, and relates to the F# spec for arity analysis. - /// For module-defined values, the currying is based - /// on the number of lambdas, and in each position the elements are - /// based on attempting to deconstruct the type of the argument as a - /// tuple-type. + /// For module-defined values, the currying is based + /// on the number of lambdas, and in each position the elements are + /// based on attempting to deconstruct the type of the argument as a + /// tuple-type. /// - /// The field is mutable because arities for recursive - /// values are only inferred after the r.h.s. is analyzed, but the - /// value itself is created before the r.h.s. is analyzed. + /// The field is mutable because arities for recursive + /// values are only inferred after the r.h.s. is analyzed, but the + /// value itself is created before the r.h.s. is analyzed. /// - /// TLR also sets this for inner bindings that it wants to - /// represent as "top level" bindings. + /// TLR also sets this for inner bindings that it wants to + /// represent as "top level" bindings. member x.ValReprInfo: ValReprInfo option = match x.val_opt_data with | Some optData -> optData.val_repr_info @@ -2993,22 +2999,22 @@ type Val = /// instance member), rather than an "inner" binding that may result in a closure. /// /// This is implied by IsMemberOrModuleBinding, however not vice versa, for two reasons. - /// Some optimizations mutate this value when they decide to change the representation of a + /// Some optimizations mutate this value when they decide to change the representation of a /// binding to be IsCompiledAsTopLevel. Second, even immediately after type checking we expect - /// some non-module, non-member bindings to be marked IsCompiledAsTopLevel, e.g. 'y' in + /// some non-module, non-member bindings to be marked IsCompiledAsTopLevel, e.g. 'y' in /// 'let x = let y = 1 in y + y' (NOTE: check this, don't take it as gospel) - member x.IsCompiledAsTopLevel = x.ValReprInfo.IsSome + member x.IsCompiledAsTopLevel = x.ValReprInfo.IsSome /// The partial information used to index the methods of all those in a ModuleOrNamespace. - member x.GetLinkagePartialKey() : ValLinkagePartialKey = + member x.GetLinkagePartialKey() : ValLinkagePartialKey = assert x.IsCompiledAsTopLevel - { LogicalName = x.LogicalName + { LogicalName = x.LogicalName MemberParentMangledName = (if x.IsMember then Some x.MemberApparentEntity.LogicalName else None) MemberIsOverride = x.IsOverrideOrExplicitImpl TotalArgCount = if x.IsMember then x.ValReprInfo.Value.TotalArgCount else 0 } /// The full information used to identify a specific overloaded method amongst all those in a ModuleOrNamespace. - member x.GetLinkageFullKey() : ValLinkageFullKey = + member x.GetLinkageFullKey() : ValLinkageFullKey = assert x.IsCompiledAsTopLevel let key = x.GetLinkagePartialKey() ValLinkageFullKey(key, (if x.IsMember then Some x.Type else None)) @@ -3029,7 +3035,7 @@ type Val = /// /// Note, the value may still be (a) an extension member or (b) and abstract slot without /// a true body. These cases are often causes of bugs in the compiler. - member x.MemberInfo = + member x.MemberInfo = match x.val_opt_data with | Some optData -> optData.val_member_info | _ -> None @@ -3041,12 +3047,12 @@ type Val = member x.IsIntrinsicMember = x.IsMember && not x.IsExtensionMember /// Indicates if this is an F#-defined value in a module, or an extension member, but excluding compiler generated bindings from optimizations - member x.IsModuleBinding = x.IsMemberOrModuleBinding && not x.IsMember + member x.IsModuleBinding = x.IsMemberOrModuleBinding && not x.IsMember /// Indicates if this is something compiled into a module, i.e. a user-defined value, an extension member or a compiler-generated value member x.IsCompiledIntoModule = x.IsExtensionMember || x.IsModuleBinding - /// Indicates if this is an F#-defined instance member. + /// Indicates if this is an F#-defined instance member. /// /// Note, the value may still be (a) an extension member or (b) and abstract slot without /// a true body. These cases are often causes of bugs in the compiler. @@ -3054,34 +3060,34 @@ type Val = /// Indicates if this is an F#-defined 'new' constructor member member x.IsConstructor = - match x.MemberInfo with + match x.MemberInfo with | Some memberInfo when not x.IsExtensionMember && (memberInfo.MemberFlags.MemberKind = SynMemberKind.Constructor) -> true | _ -> false /// Indicates if this is a compiler-generated class constructor member member x.IsClassConstructor = - match x.MemberInfo with + match x.MemberInfo with | Some memberInfo when not x.IsExtensionMember && (memberInfo.MemberFlags.MemberKind = SynMemberKind.ClassConstructor) -> true | _ -> false /// Indicates if this value was a member declared 'override' or an implementation of an interface slot member x.IsOverrideOrExplicitImpl = - match x.MemberInfo with + match x.MemberInfo with | Some memberInfo when memberInfo.MemberFlags.IsOverrideOrExplicitImpl -> true | _ -> false - + /// Gets the dispatch slots implemented by this method member x.ImplementedSlotSigs = - match x.MemberInfo with + match x.MemberInfo with | Some memberInfo -> memberInfo.ImplementedSlotSigs | _ -> [] - + /// Indicates if this is declared 'mutable' member x.IsMutable = (match x.val_flags.MutabilityInfo with Immutable -> false | Mutable -> true) /// Indicates if this is inferred to be a method or function that definitely makes no critical tailcalls? member x.MakesNoCriticalTailcalls = x.val_flags.MakesNoCriticalTailcalls - + /// Indicates if this is ever referenced? member x.HasBeenReferenced = x.val_flags.HasBeenReferenced @@ -3127,7 +3133,7 @@ type Val = member x.HasSignatureFile = x.SigRange <> x.DefinitionRange - + /// Get the inline declaration on the value member x.InlineInfo = x.val_flags.InlineInfo @@ -3154,7 +3160,7 @@ type Val = x.MemberInfo |> Option.exists (fun m -> m.MemberFlags.GetterOrSetterIsCompilerGenerated) /// Get the declared attributes for the value - member x.Attribs = + member x.Attribs = match x.val_opt_data with | Some optData -> optData.val_attribs.AsList() | _ -> [] @@ -3176,20 +3182,20 @@ type Val = | Some xmlDoc -> xmlDoc | None -> XmlDoc.Empty | _ -> XmlDoc.Empty - + ///Get the signature for the value's XML documentation - member x.XmlDocSig - with get() = - match x.val_opt_data with - | Some optData -> optData.val_xmldocsig + member x.XmlDocSig + with get() = + match x.val_opt_data with + | Some optData -> optData.val_xmldocsig | _ -> String.Empty - and set v = - match x.val_opt_data with - | Some optData -> optData.val_xmldocsig <- v + and set v = + match x.val_opt_data with + | Some optData -> optData.val_xmldocsig <- v | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_xmldocsig = v } /// The parent type or module, if any (None for expression bindings and parameters) - member x.TryDeclaringEntity = + member x.TryDeclaringEntity = match x.val_opt_data with | Some optData -> optData.val_declaring_entity | _ -> ParentNone @@ -3197,33 +3203,33 @@ type Val = /// Get the actual parent entity for the value (a module or a type), i.e. the entity under which the /// value will appear in compiled code. For extension members this is the module where the extension member /// is declared. - member x.DeclaringEntity = - match x.TryDeclaringEntity with + member x.DeclaringEntity = + match x.TryDeclaringEntity with | Parent tcref -> tcref | ParentNone -> error(InternalError("DeclaringEntity: does not have a parent", x.Range)) - member x.HasDeclaringEntity = - match x.TryDeclaringEntity with + member x.HasDeclaringEntity = + match x.TryDeclaringEntity with | Parent _ -> true | ParentNone -> false - + /// Get the apparent parent entity for a member - member x.MemberApparentEntity: TyconRef = - match x.MemberInfo with + member x.MemberApparentEntity: TyconRef = + match x.MemberInfo with | Some membInfo -> membInfo.ApparentEnclosingEntity | None -> error(InternalError("MemberApparentEntity", x.Range)) /// Get the number of 'this'/'self' object arguments for the member. Instance extension members return '1'. member v.NumObjArgs = - match v.MemberInfo with + match v.MemberInfo with | Some membInfo -> if membInfo.MemberFlags.IsInstance then 1 else 0 | None -> 0 /// Get the apparent parent entity for the value, i.e. the entity under with which the /// value is associated. For extension members this is the nominal type the member extends. /// For other values it is just the actual parent. - member x.ApparentEnclosingEntity = - match x.MemberInfo with + member x.ApparentEnclosingEntity = + match x.MemberInfo with | Some membInfo -> Parent(membInfo.ApparentEnclosingEntity) | None -> x.TryDeclaringEntity @@ -3235,56 +3241,56 @@ type Val = // - in ilxgen.fs: when compiling fslib, we bind an entry for the value in a global table (see bind_escaping_local_vspec) // - in opt.fs: (fullDebugTextOfValRef) for error reporting of non-inlinable values // - in service.fs (output_item_description): to display the full text of a value's binding location - // - in check.fs: as a boolean to detect public values for saving quotations - // - in ilxgen.fs: as a boolean to detect public values for saving quotations + // - in check.fs: as a boolean to detect public values for saving quotations + // - in ilxgen.fs: as a boolean to detect public values for saving quotations // - in MakeExportRemapping, to build non-local references for values - member x.PublicPath = - match x.TryDeclaringEntity with - | Parent eref -> - match eref.PublicPath with + member x.PublicPath = + match x.TryDeclaringEntity with + | Parent eref -> + match eref.PublicPath with | None -> None | Some p -> Some(ValPubPath(p, x.GetLinkageFullKey())) - | ParentNone -> + | ParentNone -> None /// Indicates if this member is an F#-defined dispatch slot. - member x.IsDispatchSlot = - match x.MemberInfo with - | Some membInfo -> membInfo.MemberFlags.IsDispatchSlot + member x.IsDispatchSlot = + match x.MemberInfo with + | Some membInfo -> membInfo.MemberFlags.IsDispatchSlot | _ -> false /// Get the type of the value including any generic type parameters - member x.GeneralizedType = - match x.Type with + member x.GeneralizedType = + match x.Type with | TType_forall(tps, tau) -> tps, tau | ty -> [], ty /// Get the type of the value after removing any generic type parameters - member x.TauType = - match x.Type with + member x.TauType = + match x.Type with | TType_forall(_, tau) -> tau | ty -> ty /// Get the generic type parameters for the value - member x.Typars = - match x.Type with + member x.Typars = + match x.Type with | TType_forall(tps, _) -> tps | _ -> [] - /// The name of the method. + /// The name of the method. /// - If this is a property then this is 'get_Foo' or 'set_Foo' /// - If this is an implementation of an abstract slot then this is the name of the method implemented by the abstract slot /// - If this is an extension member then this will be the simple name - member x.LogicalName = - match x.MemberInfo with + member x.LogicalName = + match x.MemberInfo with | None -> x.val_logical_name - | Some membInfo -> - match membInfo.ImplementedSlotSigs with + | Some membInfo -> + match membInfo.ImplementedSlotSigs with | slotsig :: _ -> slotsig.Name | _ -> x.val_logical_name // Set the logical name of the value - member x.SetLogicalName(nm) = + member x.SetLogicalName(nm) = x.val_logical_name <- nm member x.ValCompiledName = @@ -3298,12 +3304,12 @@ type Val = /// - If this is an extension member then this will be a mangled name /// - If this is an operator then this is 'op_Addition' member x.CompiledName (compilerGlobalState:CompilerGlobalState option) = - let givenName = - match x.val_opt_data with + let givenName = + match x.val_opt_data with | Some { val_compiled_name = Some n } -> n - | _ -> x.LogicalName + | _ -> x.LogicalName // These cases must get stable unique names for their static field & static property. This name - // must be stable across quotation generation and IL code generation (quotations can refer to the + // must be stable across quotation generation and IL code generation (quotations can refer to the // properties implicit in these) // // Variable 'x' here, which is compiled as a top level static: @@ -3311,19 +3317,19 @@ type Val = // // The implicit 'patternInput' variable here: // let [x] = expr in ... // IsMemberOrModuleBinding = true, IsCompiledAsTopLevel = true, IsMember = false, CompilerGenerated=true - // + // // The implicit 'copyOfStruct' variables here: // let dt = System.DateTime.Now - System.DateTime.Now // IsMemberOrModuleBinding = false, IsCompiledAsTopLevel = true, IsMember = false, CompilerGenerated=true - // + // // However we don't need this for CompilerGenerated members such as the implementations of IComparable match compilerGlobalState with | Some state when x.IsCompiledAsTopLevel && not x.IsMember && (x.IsCompilerGenerated || not x.IsMemberOrModuleBinding) -> - state.StableNameGenerator.GetUniqueCompilerGeneratedName(givenName, x.Range, x.Stamp) + state.StableNameGenerator.GetUniqueCompilerGeneratedName(givenName, x.Range, x.Stamp) | _ -> givenName /// The name of the property. - /// - If this is a property then this is 'Foo' - member x.PropertyName = + /// - If this is a property then this is 'Foo' + member x.PropertyName = let logicalName = x.LogicalName ChopPropertyName logicalName @@ -3338,14 +3344,14 @@ type Val = /// - If this is an active pattern --> |A|_| /// - If this is an operator --> op_Addition /// - If this is an identifier needing backticks --> A-B - member x.DisplayNameCoreMangled = - match x.MemberInfo with - | Some membInfo -> - match membInfo.MemberFlags.MemberKind with - | SynMemberKind.ClassConstructor - | SynMemberKind.Constructor + member x.DisplayNameCoreMangled = + match x.MemberInfo with + | Some membInfo -> + match membInfo.MemberFlags.MemberKind with + | SynMemberKind.ClassConstructor + | SynMemberKind.Constructor | SynMemberKind.Member -> x.LogicalName - | SynMemberKind.PropertyGetSet + | SynMemberKind.PropertyGetSet | SynMemberKind.PropertySet | SynMemberKind.PropertyGet -> x.PropertyName | None -> x.LogicalName @@ -3353,7 +3359,7 @@ type Val = /// The display name of the value or method with operator names decompiled but without backticks etc. /// /// Note: here "Core" means "without added backticks or parens" - member x.DisplayNameCore = + member x.DisplayNameCore = x.DisplayNameCoreMangled |> ConvertValLogicalNameToDisplayNameCore /// The full text for the value to show in error messages and to use in code. @@ -3366,14 +3372,14 @@ type Val = /// - If this is an identifier needing backticks --> ``A-B`` /// - If this is a base value --> base /// - If this is a value named ``base`` --> ``base`` - member x.DisplayName = + member x.DisplayName = ConvertValLogicalNameToDisplayName x.IsBaseVal x.DisplayNameCoreMangled - member x.SetValRec b = x.val_flags <- x.val_flags.WithRecursiveValInfo b + member x.SetValRec b = x.val_flags <- x.val_flags.WithRecursiveValInfo b - member x.SetIsCompilerGenerated(v) = x.val_flags <- x.val_flags.WithIsCompilerGenerated(v) + member x.SetIsCompilerGenerated(v) = x.val_flags <- x.val_flags.WithIsCompilerGenerated(v) - member x.SetIsMemberOrModuleBinding() = x.val_flags <- x.val_flags.WithIsMemberOrModuleBinding + member x.SetIsMemberOrModuleBinding() = x.val_flags <- x.val_flags.WithIsMemberOrModuleBinding member x.SetMakesNoCriticalTailcalls() = x.val_flags <- x.val_flags.WithMakesNoCriticalTailcalls @@ -3393,12 +3399,12 @@ type Val = member x.SetIsParameter() = x.val_flags <- x.val_flags.WithIsParameter - member x.SetValReprInfo info = + member x.SetValReprInfo info = match x.val_opt_data with | Some optData -> optData.val_repr_info <- info | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_repr_info = info } - member x.SetValReprInfoForDisplay info = + member x.SetValReprInfoForDisplay info = match x.val_opt_data with | Some optData -> optData.val_repr_info_for_display <- info | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_repr_info_for_display = info } @@ -3419,13 +3425,13 @@ type Val = match x.val_opt_data with | Some optData -> optData.val_other_xmldoc <- Some xmlDoc | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_other_xmldoc = Some xmlDoc } - - member x.SetDeclaringEntity parent = + + member x.SetDeclaringEntity parent = match x.val_opt_data with | Some optData -> optData.val_declaring_entity <- parent | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_declaring_entity = parent } - member x.SetAttribs (attribs: Attribs) = + member x.SetAttribs (attribs: Attribs) = let wa = WellKnownValAttribs.Create(attribs) match x.val_opt_data with | Some optData -> optData.val_attribs <- wa @@ -3442,18 +3448,18 @@ type Val = if changed then x.SetValAttribs(waNew) result - member x.SetMemberInfo member_info = + member x.SetMemberInfo member_info = match x.val_opt_data with | Some optData -> optData.val_member_info <- Some member_info | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_member_info = Some member_info } - member x.SetValDefn val_defn = + member x.SetValDefn val_defn = match x.val_opt_data with | Some optData -> optData.val_defn <- Some val_defn | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_defn = Some val_defn } /// Create a new value with empty, unlinked data. Only used during unpickling of F# metadata. - static member NewUnlinked() : Val = + static member NewUnlinked() : Val = { val_logical_name = Unchecked.defaultof<_> val_range = Unchecked.defaultof<_> val_type = Unchecked.defaultof<_> @@ -3469,15 +3475,15 @@ type Val = member x.Link (tg: ValData) = x.SetData tg /// Set all the data on a value - member x.SetData (tg: ValData) = - x.val_logical_name <- tg.val_logical_name - x.val_range <- tg.val_range - x.val_type <- tg.val_type - x.val_stamp <- tg.val_stamp - x.val_flags <- tg.val_flags + member x.SetData (tg: ValData) = + x.val_logical_name <- tg.val_logical_name + x.val_range <- tg.val_range + x.val_type <- tg.val_type + x.val_stamp <- tg.val_stamp + x.val_flags <- tg.val_flags match tg.val_opt_data with - | Some tg -> - x.val_opt_data <- + | Some tg -> + x.val_opt_data <- Some { val_compiled_name = tg.val_compiled_name val_other_range = tg.val_other_range val_const = tg.val_const @@ -3495,26 +3501,26 @@ type Val = | None -> () /// Indicates if a value is linked to backing data yet. Only used during unpickling of F# metadata. - member x.IsLinked = match box x.val_logical_name with null -> false | _ -> true + member x.IsLinked = match box x.val_logical_name with null -> false | _ -> true [] member x.DebugText = x.ToString() override x.ToString() = x.LogicalName - - + + /// Represents the extra information stored for a member [] -type ValMemberInfo = +type ValMemberInfo = { - /// The parent type. For an extension member this is the type being extended - ApparentEnclosingEntity: TyconRef + /// The parent type. For an extension member this is the type being extended + ApparentEnclosingEntity: TyconRef - /// Updated with the full implemented slotsig after interface implementation relation is checked - mutable ImplementedSlotSigs: SlotSig list + /// Updated with the full implemented slotsig after interface implementation relation is checked + mutable ImplementedSlotSigs: SlotSig list - /// Gets updated with 'true' if an abstract slot is implemented in the file being typechecked. Internal only. - mutable IsImplemented: bool + /// Gets updated with 'true' if an abstract slot is implemented in the file being typechecked. Internal only. + mutable IsImplemented: bool MemberFlags: SynMemberFlags } @@ -3525,10 +3531,10 @@ type ValMemberInfo = override x.ToString() = "ValMemberInfo(...)" [] -type NonLocalValOrMemberRef = +type NonLocalValOrMemberRef = { /// A reference to the entity containing the value or member. This will always be a non-local reference - EnclosingEntity: EntityRef + EnclosingEntity: EntityRef /// The name of the value, or the full signature of the member ItemKey: ValLinkageFullKey @@ -3546,11 +3552,11 @@ type NonLocalValOrMemberRef = /// For debugging override x.ToString() = !! x.EnclosingEntity.nlr.ToString() + "::" + x.ItemKey.PartialKey.LogicalName - + /// Represents the path information for a reference to a value or member in another assembly, disassociated /// from any particular reference. [] -type ValPublicPath = +type ValPublicPath = | ValPubPath of PublicPath * ValLinkageFullKey [] @@ -3560,14 +3566,14 @@ type ValPublicPath = /// Represents an index into the namespace/module structure of an assembly [] -type NonLocalEntityRef = +type NonLocalEntityRef = | NonLocalEntityRef of CcuThunk * string[] /// Try to find the entity corresponding to the given path in the given CCU - static member TryDerefEntityPath(ccu: CcuThunk, path: string[], i: int, entity: Entity) = + static member TryDerefEntityPath(ccu: CcuThunk, path: string[], i: int, entity: Entity) = if i >= path.Length then ValueSome entity - else - match entity.ModuleOrNamespaceType.AllEntitiesByCompiledAndLogicalMangledNames.TryGetValue path[i] with + else + match entity.ModuleOrNamespaceType.AllEntitiesByCompiledAndLogicalMangledNames.TryGetValue path[i] with | true, res -> NonLocalEntityRef.TryDerefEntityPath(ccu, path, (i+1), res) #if !NO_TYPEPROVIDERS | _ -> NonLocalEntityRef.TryDerefEntityPathViaProvidedType(ccu, path, i, entity) @@ -3577,21 +3583,21 @@ type NonLocalEntityRef = #if !NO_TYPEPROVIDERS /// Try to find the entity corresponding to the given path, using type-providers to link the data - static member TryDerefEntityPathViaProvidedType(ccu: CcuThunk, path: string[], i: int, entity: Entity) = + static member TryDerefEntityPathViaProvidedType(ccu: CcuThunk, path: string[], i: int, entity: Entity) = // Errors during linking are not necessarily given good ranges. This has always been the case in F# 2.0, but also applies to // type provider type linking errors in F# 3.0. let m = range0 match entity.TypeReprInfo with - | TProvidedTypeRepr info -> + | TProvidedTypeRepr info -> let resolutionEnvironment = info.ResolutionEnvironment let st = info.ProvidedType - + // In this case, we're safely in the realm of types. Just iterate through the nested // types until i = path.Length-1. Create the Tycon's as needed - let rec tryResolveNestedTypeOf(parentEntity: Entity, resolutionEnvironment, st: Tainted, i) = + let rec tryResolveNestedTypeOf(parentEntity: Entity, resolutionEnvironment, st: Tainted, i) = match st.PApply((fun st -> st.GetNestedType path[i]), m) with | Tainted.Null -> ValueNone - | Tainted.NonNull st -> + | Tainted.NonNull st -> let canonicalEntity = parentEntity.ModuleOrNamespaceType.GetOrInternProvidedEntity( path[i], @@ -3601,9 +3607,9 @@ type NonLocalEntityRef = tryResolveNestedTypeOf(entity, resolutionEnvironment, st, i) - | TProvidedNamespaceRepr(resolutionEnvironment, resolvers) -> + | TProvidedNamespaceRepr(resolutionEnvironment, resolvers) -> - // In this case, we're still in the realm of extensible namespaces. + // In this case, we're still in the realm of extensible namespaces. // <----entity--> // 0 .........i-1..i .......... j ..... path.Length-1 // @@ -3613,16 +3619,16 @@ type NonLocalEntityRef = // <----entity--> <---resolver----> <--loop---> // 0 .........i-1..i ............. j ..... path.Length-1 // - // We now query the resolvers with - // moduleOrNamespace = path.[0..j-1] - // typeName = path.[j] + // We now query the resolvers with + // moduleOrNamespace = path.[0..j-1] + // typeName = path.[j] // starting with j = i and then progressively increasing j - + // This function queries at 'j' - let tryResolvePrefix j = + let tryResolvePrefix j = assert (j >= 0) assert (j <= path.Length - 1) - let matched = + let matched = [ for resolver in resolvers do let moduleOrNamespace = if j = 0 then [| |] else path[0..j-1] let typename = path[j] @@ -3638,8 +3644,8 @@ type NonLocalEntityRef = // 'entity' is at position i in the dereference chain. We resolved to position 'j'. // Inject namespaces until we're an position j, and then inject the type. // Note: this is similar to code in CompileOps.fs - let rec injectNamespacesFromIToJ (entity: Entity) k = - if k = j then + let rec injectNamespacesFromIToJ (entity: Entity) k = + if k = j then entity.ModuleOrNamespaceType.GetOrInternProvidedEntity( path[j], (fun () -> Construct.NewProvidedTycon(resolutionEnvironment, st, ccu.ImportProvidedType, false, m))) @@ -3649,22 +3655,22 @@ type NonLocalEntityRef = path[k], (fun () -> let cpath = entity.CompilationPath.NestedCompPath entity.LogicalName (ModuleOrNamespaceKind.Namespace false) - Construct.NewModuleOrNamespace - (Some cpath) - (TAccess []) (ident(path[k], m)) XmlDoc.Empty [] + Construct.NewModuleOrNamespace + (Some cpath) + (TAccess []) (ident(path[k], m)) XmlDoc.Empty [] (MaybeLazy.Strict (Construct.NewEmptyModuleOrNamespaceType (Namespace true))))) injectNamespacesFromIToJ newEntity (k+1) let newEntity = injectNamespacesFromIToJ entity i - + // newEntity is at 'j' - NonLocalEntityRef.TryDerefEntityPath(ccu, path, (j+1), newEntity) + NonLocalEntityRef.TryDerefEntityPath(ccu, path, (j+1), newEntity) - | [] -> ValueNone + | [] -> ValueNone | _ -> failwith "Unexpected" - let rec tryResolvePrefixes j = + let rec tryResolvePrefixes j = if j >= path.Length then ValueNone - else match tryResolvePrefix j with + else match tryResolvePrefix j with | ValueNone -> tryResolvePrefixes (j+1) | ValueSome res -> ValueSome res @@ -3672,11 +3678,11 @@ type NonLocalEntityRef = | _ -> ValueNone #endif - + /// Try to link a non-local entity reference to an actual entity - member nleref.TryDeref canError = - let (NonLocalEntityRef(ccu, path)) = nleref - if canError then + member nleref.TryDeref canError = + let (NonLocalEntityRef(ccu, path)) = nleref + if canError then ccu.EnsureDerefable path if ccu.IsUnresolvedReference then ValueNone else @@ -3686,62 +3692,62 @@ type NonLocalEntityRef = | ValueNone -> // OK, the lookup failed. Check if we can redirect through a type forwarder on this assembly. // Look for a forwarder for each prefix-path - let rec tryForwardPrefixPath i = - if i < path.Length then + let rec tryForwardPrefixPath i = + if i < path.Length then match ccu.TryForward(path[0..i-1], path[i]) with // OK, found a forwarder, now continue with the lookup to find the nested type - | Some tcref -> NonLocalEntityRef.TryDerefEntityPath(ccu, path, (i+1), tcref.Deref) + | Some tcref -> NonLocalEntityRef.TryDerefEntityPath(ccu, path, (i+1), tcref.Deref) | None -> tryForwardPrefixPath (i+1) else ValueNone tryForwardPrefixPath 0 - + /// Get the CCU referenced by the nonlocal reference. member nleref.Ccu = - let (NonLocalEntityRef(ccu, _)) = nleref + let (NonLocalEntityRef(ccu, _)) = nleref ccu /// Get the path into the CCU referenced by the nonlocal reference. member nleref.Path = - let (NonLocalEntityRef(_, p)) = nleref + let (NonLocalEntityRef(_, p)) = nleref p member nleref.DisplayName = String.concat "." nleref.Path /// Get the mangled name of the last item in the path of the nonlocal reference. - member nleref.LastItemMangledName = + member nleref.LastItemMangledName = let p = nleref.Path p[p.Length-1] /// Get the all-but-last names of the path of the nonlocal reference. - member nleref.EnclosingMangledPath = + member nleref.EnclosingMangledPath = let p = nleref.Path p[0..p.Length-2] - + /// Get the name of the assembly referenced by the nonlocal reference. member nleref.AssemblyName = nleref.Ccu.AssemblyName /// Dereference the nonlocal reference, and raise an error if this fails. - member nleref.Deref = - match nleref.TryDeref(canError=true) with + member nleref.Deref = + match nleref.TryDeref(canError=true) with | ValueSome res -> res - | ValueNone -> - errorR (InternalUndefinedItemRef (FSComp.SR.tastUndefinedItemRefModuleNamespace, nleref.DisplayName, nleref.AssemblyName, "")) + | ValueNone -> + errorR (InternalUndefinedItemRef (FSComp.SR.tastUndefinedItemRefModuleNamespace, nleref.DisplayName, nleref.AssemblyName, "")) raise (KeyNotFoundException()) [] member x.DebugText = x.ToString() override x.ToString() = x.DisplayName - + [] -type EntityRef = +type EntityRef = { - /// Indicates a reference to something bound in this CCU + /// Indicates a reference to something bound in this CCU mutable binding: NonNullSlot - /// Indicates a reference to something bound in another CCU + /// Indicates a reference to something bound in another CCU nlr: NonLocalEntityRef } @@ -3755,36 +3761,36 @@ type EntityRef = member x.ResolvedTarget = x.binding /// Resolve the reference - member private tcr.Resolve canError = + member private tcr.Resolve canError = let res = tcr.nlr.TryDeref canError - match res with - | ValueSome r -> - tcr.binding <- nullableSlotFull r - | ValueNone -> + match res with + | ValueSome r -> + tcr.binding <- nullableSlotFull r + | ValueNone -> () /// Dereference the TyconRef to a Tycon. Amortize the cost of doing this. /// This path should not allocate in the amortized case - member tcr.Deref = - match box tcr.binding with + member tcr.Deref = + match box tcr.binding with | null -> tcr.Resolve(canError=true) - match box tcr.binding with + match box tcr.binding with | null -> error (InternalUndefinedItemRef (FSComp.SR.tastUndefinedItemRefModuleNamespaceType, String.concat "." tcr.nlr.EnclosingMangledPath, tcr.nlr.AssemblyName, tcr.nlr.LastItemMangledName)) | _ -> tcr.binding - | _ -> + | _ -> tcr.binding /// Dereference the TyconRef to a Tycon option. - member tcr.TryDeref = - match box tcr.binding with - | null -> + member tcr.TryDeref = + match box tcr.binding with + | null -> tcr.Resolve(canError=false) - match box tcr.binding with + match box tcr.binding with | null -> ValueNone | _ -> ValueSome tcr.binding - | _ -> + | _ -> ValueSome tcr.binding /// Is the destination assembly available? @@ -3802,10 +3808,10 @@ type EntityRef = /// The signature definition location of the namespace, module or type member x.SigRange = x.Deref.SigRange - /// The name of the namespace, module or type, possibly with mangling, e.g. List`1, List or FailureException + /// The name of the namespace, module or type, possibly with mangling, e.g. List`1, List or FailureException member x.LogicalName = x.Deref.LogicalName - /// The compiled name of the namespace, module or type, e.g. FSharpList`1, ListModule or FailureException + /// The compiled name of the namespace, module or type, e.g. FSharpList`1, ListModule or FailureException member x.CompiledName = x.Deref.CompiledName /// The display name of the namespace, module or type, e.g. List instead of List`1, not including static parameters @@ -3831,8 +3837,8 @@ type EntityRef = /// The code location where the module, namespace or type is defined. member x.Range = x.Deref.Range - /// A unique stamp for this module, namespace or type definition within the context of this compilation. - /// Note that because of signatures, there are situations where in a single compilation the "same" + /// A unique stamp for this module, namespace or type definition within the context of this compilation. + /// Note that because of signatures, there are situations where in a single compilation the "same" /// module, namespace or type may have two distinct Entity objects that have distinct stamps. member x.Stamp = x.Deref.Stamp @@ -3842,7 +3848,7 @@ type EntityRef = /// The XML documentation of the entity, if any. If the entity is backed by provided metadata /// then this _does_ include this documentation. If the entity is backed by Abstract IL metadata - /// or comes from another F# assembly then it does not (because the documentation will get read from + /// or comes from another F# assembly then it does not (because the documentation will get read from /// an XML file). member x.XmlDoc = if not x.Deref.XmlDoc.IsEmpty then @@ -3851,7 +3857,7 @@ type EntityRef = x.Deref.entity_opt_data |> Option.bind (fun d -> d.entity_other_xmldoc) |> Option.defaultValue XmlDoc.Empty - + member x.SetOtherXmlDoc (xmlDoc: XmlDoc) = x.Deref.SetOtherXmlDoc(xmlDoc) /// The XML documentation sig-string of the entity, if any, to use to lookup an .xml doc file. This also acts @@ -3860,7 +3866,7 @@ type EntityRef = /// The logical contents of the entity when it is a module or namespace fragment. member x.ModuleOrNamespaceType = x.Deref.ModuleOrNamespaceType - + /// Demangle the module name, if FSharpModuleWithSuffix is used member x.DemangledModuleOrNamespaceName = x.Deref.DemangledModuleOrNamespaceName @@ -3876,12 +3882,12 @@ type EntityRef = /// The information about the r.h.s. of a type definition, if any. For example, the r.h.s. of a union or record type. member x.TypeReprInfo = x.Deref.TypeReprInfo - /// The information about the r.h.s. of an F# exception definition, if any. + /// The information about the r.h.s. of an F# exception definition, if any. member x.ExceptionInfo = x.Deref.ExceptionInfo /// Indicates if the entity represents an F# exception declaration. member x.IsFSharpException = x.Deref.IsFSharpException - + /// Get the type parameters for an entity that is a type declaration, otherwise return the empty list. /// /// Lazy because it may read metadata. Uses the entity's own range for error context. @@ -3905,10 +3911,10 @@ type EntityRef = /// Get the value representing the accessibility of an F# type definition or module. member x.Accessibility = x.Deref.Accessibility - /// Indicates the type prefers the "tycon" syntax for display etc. + /// Indicates the type prefers the "tycon" syntax for display etc. member x.IsPrefixDisplay = x.Deref.IsPrefixDisplay - /// Indicates the "tycon blob" is actually a module + /// Indicates the "tycon blob" is actually a module member x.IsModuleOrNamespace = x.Deref.IsModuleOrNamespace /// Indicates if the entity is a namespace @@ -4002,7 +4008,7 @@ type EntityRef = /// Indicates if this is a struct or enum type definition, i.e. a value type definition, including struct records and unions member x.IsStructOrEnumTycon = x.Deref.IsStructOrEnumTycon - /// Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll which uses + /// Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll which uses /// an assembly-code representation for the type, e.g. the primitive array type constructor. member x.IsAsmReprTycon = x.Deref.IsAsmReprTycon @@ -4012,7 +4018,7 @@ type EntityRef = /// Indicates if the entity is erased, either a measure definition, or an erased provided type definition member x.IsErased = x.Deref.IsErased - + /// Gets any implicit hash/equals (with comparer argument) methods added to an F# record, union or struct type definition. member x.GeneratedHashAndEqualsWithComparerValues = x.Deref.GeneratedHashAndEqualsWithComparerValues @@ -4024,11 +4030,11 @@ type EntityRef = /// Gets any implicit hash/equals methods added to an F# record, union or struct type definition. member x.GeneratedHashAndEqualsValues = x.Deref.GeneratedHashAndEqualsValues - + /// Indicate if this is a type definition backed by Abstract IL metadata. member x.IsILTycon = x.Deref.IsILTycon - /// Get the Abstract IL scope, nesting and metadata for this + /// Get the Abstract IL scope, nesting and metadata for this /// type definition, assuming it is backed by Abstract IL metadata. member x.ILTyconInfo = x.Deref.ILTyconInfo @@ -4068,19 +4074,19 @@ type EntityRef = /// which in F# is called a 'unknown representation' type). member x.IsHiddenReprTycon = x.Deref.IsHiddenReprTycon - /// Indicates if this is an F#-defined interface type definition + /// Indicates if this is an F#-defined interface type definition member x.IsFSharpInterfaceTycon = x.Deref.IsFSharpInterfaceTycon - /// Indicates if this is an F#-defined delegate type definition + /// Indicates if this is an F#-defined delegate type definition member x.IsFSharpDelegateTycon = x.Deref.IsFSharpDelegateTycon - /// Indicates if this is an F#-defined enum type definition + /// Indicates if this is an F#-defined enum type definition member x.IsFSharpEnumTycon = x.Deref.IsFSharpEnumTycon - /// Indicates if this is a .NET-defined enum type definition + /// Indicates if this is a .NET-defined enum type definition member x.IsILEnumTycon = x.Deref.IsILEnumTycon - /// Indicates if this is an enum type definition + /// Indicates if this is an enum type definition member x.IsEnumTycon = x.Deref.IsEnumTycon /// Indicates if this is an F#-defined value type definition, including struct records and unions @@ -4108,11 +4114,11 @@ type EntityRef = [] member x.DebugText = x.ToString() - override x.ToString() = - if x.IsLocalRef then - x.ResolvedTarget.DisplayName - else - x.nlr.DisplayName + override x.ToString() = + if x.IsLocalRef then + x.ResolvedTarget.DisplayName + else + x.nlr.DisplayName /// Represents a module-or-namespace reference in the typed abstract syntax. type ModuleOrNamespaceRef = EntityRef @@ -4122,12 +4128,12 @@ type TyconRef = EntityRef /// References are either local or nonlocal [] -type ValRef = +type ValRef = { - /// Indicates a reference to something bound in this CCU + /// Indicates a reference to something bound in this CCU mutable binding: NonNullSlot - /// Indicates a reference to something bound in another CCU + /// Indicates a reference to something bound in another CCU nlr: NonLocalValOrMemberRef } @@ -4138,35 +4144,35 @@ type ValRef = member x.ResolvedTarget = x.binding /// Dereference the ValRef to a Val. - member x.Deref = + member x.Deref = if obj.ReferenceEquals(x.binding, null) then - let res = - let nlr = x.nlr - let e = nlr.EnclosingEntity.Deref + let res = + let nlr = x.nlr + let e = nlr.EnclosingEntity.Deref let possible = e.ModuleOrNamespaceType.TryLinkVal(nlr.EnclosingEntity.nlr.Ccu, nlr.ItemKey) - match possible with + match possible with | ValueNone -> error (InternalUndefinedItemRef (FSComp.SR.tastUndefinedItemRefVal, e.DisplayNameWithStaticParameters, nlr.AssemblyName, sprintf "%+A" nlr.ItemKey.PartialKey)) | ValueSome h -> h - x.binding <- nullableSlotFull res - res + x.binding <- nullableSlotFull res + res else x.binding /// Dereference the ValRef to a Val option. - member x.TryDeref = + member x.TryDeref = if obj.ReferenceEquals(x.binding, null) then - let resOpt = - match x.nlr.EnclosingEntity.TryDeref with + let resOpt = + match x.nlr.EnclosingEntity.TryDeref with | ValueNone -> ValueNone | ValueSome e -> e.ModuleOrNamespaceType.TryLinkVal(x.nlr.EnclosingEntity.nlr.Ccu, x.nlr.ItemKey) - match resOpt with + match resOpt with | ValueNone -> () - | ValueSome res -> - x.binding <- nullableSlotFull res + | ValueSome res -> + x.binding <- nullableSlotFull res resOpt else ValueSome x.binding - /// The type of the value. May be a TType_forall for a generic value. - /// May be a type variable or type containing type variables during type inference. + /// The type of the value. May be a TType_forall for a generic value. + /// May be a type variable or type containing type variables during type inference. member x.Type = x.Deref.Type /// Get the type of the value including any generic type parameters @@ -4202,29 +4208,29 @@ type ValRef = member x.SigRange = x.Deref.SigRange - /// The value of a value or member marked with [] + /// The value of a value or member marked with [] member x.LiteralValue = x.Deref.LiteralValue member x.Id = x.Deref.Id /// Get the name of the value, assuming it is compiled as a property. - /// - If this is a property then this is 'Foo' + /// - If this is a property then this is 'Foo' /// - If this is an implementation of an abstract slot then this is the name of the property implemented by the abstract slot member x.PropertyName = x.Deref.PropertyName /// Indicates whether this value represents a property getter. - member x.IsPropertyGetterMethod = + member x.IsPropertyGetterMethod = match x.MemberInfo with | None -> false | Some (memInfo: ValMemberInfo) -> memInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGet || memInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGetSet /// Indicates whether this value represents a property setter. - member x.IsPropertySetterMethod = + member x.IsPropertySetterMethod = match x.MemberInfo with | None -> false | Some (memInfo: ValMemberInfo) -> memInfo.MemberFlags.MemberKind = SynMemberKind.PropertySet || memInfo.MemberFlags.MemberKind = SynMemberKind.PropertyGetSet - /// A unique stamp within the context of this invocation of the compiler process + /// A unique stamp within the context of this invocation of the compiler process member x.Stamp = x.Deref.Stamp /// Is this represented as a "top level" static binding (i.e. a static field, static member, @@ -4262,7 +4268,7 @@ type ValRef = /// Indicates if this is an F#-defined value in a module, or an extension member, but excluding compiler generated bindings from optimizations member x.IsModuleBinding = x.Deref.IsModuleBinding - /// Indicates if this is an F#-defined instance member. + /// Indicates if this is an F#-defined instance member. /// /// Note, the value may still be (a) an extension member or (b) and abstract slot without /// a true body. These cases are often causes of bugs in the compiler. @@ -4356,13 +4362,13 @@ type ValRef = [] member x.DebugText = x.ToString() - override x.ToString() = - if x.IsLocalRef then x.ResolvedTarget.DisplayName + override x.ToString() = + if x.IsLocalRef then x.ResolvedTarget.DisplayName else x.nlr.ToString() /// Represents a reference to a case of a union type [] -type UnionCaseRef = +type UnionCaseRef = | UnionCaseRef of tyconRef: TyconRef * caseName: string /// Get a reference to the type containing this union case @@ -4375,14 +4381,14 @@ type UnionCaseRef = member x.Tycon = x.TyconRef.Deref /// Dereference the reference to the union case - member x.UnionCase = - match x.TyconRef.GetUnionCaseByName x.CaseName with + member x.UnionCase = + match x.TyconRef.GetUnionCaseByName x.CaseName with | Some res -> res | None -> error(InternalError(sprintf "union case %s not found in type %s" x.CaseName x.TyconRef.LogicalName, x.TyconRef.Range)) - /// Try to dereference the reference + /// Try to dereference the reference member x.TryUnionCase = - x.TyconRef.TryDeref + x.TyconRef.TryDeref |> ValueOption.bind (fun tcref -> tcref.GetUnionCaseByName x.CaseName |> ValueOption.ofOption) /// Get the attributes associated with the union case @@ -4398,11 +4404,11 @@ type UnionCaseRef = member x.SigRange = x.UnionCase.SigRange /// Get the index of the union case amongst the cases - member x.Index = - try - // REVIEW: this could be faster, e.g. by storing the index in the NameMap - x.TyconRef.UnionCasesArray |> Array.findIndex (fun uc -> uc.LogicalName = x.CaseName) - with :? KeyNotFoundException -> + member x.Index = + try + // REVIEW: this could be faster, e.g. by storing the index in the NameMap + x.TyconRef.UnionCasesArray |> Array.findIndex (fun uc -> uc.LogicalName = x.CaseName) + with :? KeyNotFoundException -> error(InternalError(sprintf "union case %s not found in type %s" x.CaseName x.TyconRef.LogicalName, x.TyconRef.Range)) /// Get the fields of the union case @@ -4434,7 +4440,7 @@ let findLogicalFieldIndexOfRecordField (tcref:TyconRef) (id:string) = /// Represents a reference to a field in a record, class or struct [] -type RecdFieldRef = +type RecdFieldRef = | RecdFieldRef of tyconRef: TyconRef * fieldName: string /// Get a reference to the type containing this record field @@ -4449,34 +4455,34 @@ type RecdFieldRef = /// Get the Entity for the type containing this record field member x.Tycon = x.TyconRef.Deref - /// Dereference the reference - member x.RecdField = + /// Dereference the reference + member x.RecdField = let (RecdFieldRef(tcref, id)) = x - match tcref.GetFieldByName id with + match tcref.GetFieldByName id with | Some res -> res | None -> error(InternalError(sprintf "field %s not found in type %s" id tcref.LogicalName, tcref.Range)) - /// Try to dereference the reference - member x.TryRecdField = - x.TyconRef.TryDeref + /// Try to dereference the reference + member x.TryRecdField = + x.TyconRef.TryDeref |> ValueOption.bind (fun tcref -> tcref.GetFieldByName x.FieldName |> ValueOption.ofOption) - /// Get the attributes associated with the compiled property of the record field + /// Get the attributes associated with the compiled property of the record field member x.PropertyAttribs = x.RecdField.PropertyAttribs - /// Get the declaration range of the record field + /// Get the declaration range of the record field member x.Range = x.RecdField.Range - /// Get the definition range of the record field + /// Get the definition range of the record field member x.DefinitionRange = x.RecdField.DefinitionRange - /// Get the signature range of the record field + /// Get the signature range of the record field member x.SigRange = x.RecdField.SigRange member x.Index = let (RecdFieldRef(tcref, id)) = x findLogicalFieldIndexOfRecordField tcref id - + [] member x.DebugText = x.ToString() @@ -4484,7 +4490,7 @@ type RecdFieldRef = override x.ToString() = x.FieldName [] -type Nullness = +type Nullness = | Known of NullnessInfo | Variable of NullnessVar /// The value is known to be non-null because it was produced by a constructor call. @@ -4497,14 +4503,14 @@ type Nullness = | KnownFromConstructor -> Known NullnessInfo.WithoutNull | n -> n - member n.Evaluate() = - match n with + member n.Evaluate() = + match n with | Known info -> info | Variable v -> v.Evaluate() | KnownFromConstructor -> NullnessInfo.WithoutNull - member n.TryEvaluate() = - match n with + member n.TryEvaluate() = + match n with | Known info -> ValueSome info | Variable v -> v.TryEvaluate() | KnownFromConstructor -> NullnessInfo.WithoutNull |> ValueSome @@ -4515,42 +4521,42 @@ type Nullness = // Note, nullness variables are only created if the nullness checking feature is on [] -type NullnessVar() = +type NullnessVar() = let mutable solution: Nullness option = None - member nv.Evaluate() = - match solution with + member nv.Evaluate() = + match solution with | None -> NullnessInfo.WithoutNull | Some soln -> soln.Evaluate() - member nv.TryEvaluate() = - match solution with + member nv.TryEvaluate() = + match solution with | None -> ValueNone | Some soln -> soln.TryEvaluate() member nv.IsSolved = solution.IsSome - member nv.IsFullySolved = + member nv.IsFullySolved = match solution with | None -> false | Some (Nullness.Known _) -> true | Some (Nullness.KnownFromConstructor) -> true | Some (Nullness.Variable v) -> v.IsFullySolved - member nv.Set(nullness) = - assert (not nv.IsSolved) + member nv.Set(nullness) = + assert (not nv.IsSolved) solution <- Some nullness - member nv.Unset() = + member nv.Unset() = assert nv.IsSolved solution <- None - member nv.Solution = + member nv.Solution = assert nv.IsSolved solution.Value [] -type NullnessInfo = +type NullnessInfo = /// we know that there is an extra null value in the type | WithNull @@ -4565,7 +4571,7 @@ type NullnessInfo = [] type TType = - /// Indicates the type is a universal type, only used for types of values and members + /// Indicates the type is a universal type, only used for types of values and members | TType_forall of typars: Typars * bodyTy: TType /// TType_app(tyconRef, typeInstantiation, nullness). @@ -4581,7 +4587,7 @@ type TType = /// TType_fun(domainType, rangeType, nullness). /// - /// Indicates the type is a function type + /// Indicates the type is a function type | TType_fun of domainType: TType * rangeType: TType * nullness: Nullness /// Indicates the type is a non-F#-visible type representing a "proof" that a union value belongs to a particular union case @@ -4589,7 +4595,7 @@ type TType = /// the temporaries arising out of pattern matching on union values. | TType_ucase of unionCaseRef: UnionCaseRef * typeInstantiation: TypeInst - /// Indicates the type is a variable type, whether declared, generalized or an inference type parameter + /// Indicates the type is a variable type, whether declared, generalized or an inference type parameter | TType_var of typar: Typar * nullness: Nullness /// Indicates the type is a unit-of-measure expression being used as an argument to a type or member @@ -4613,24 +4619,24 @@ type TType = [] member x.DebugText = x.LimitedToString(4) - member x.LimitedToString(maxDepth:int) = - match x with + member x.LimitedToString(maxDepth:int) = + match x with | TType_forall (_tps, ty) -> "forall ... " + ty.ToString() - | TType_app (tcref, tinst, nullness) -> tcref.DisplayName + (match tinst with [] -> "" | tys -> "<" + String.concat "," (List.map string tys) + ">") + nullness.ToString() - | TType_tuple (tupInfo, tinst) -> - (match tupInfo with + | TType_app (tcref, tinst, nullness) -> tcref.DisplayName + (match tinst with [] -> "" | tys -> "<" + String.concat "," (List.map string tys) + ">") + nullness.ToString() + | TType_tuple (tupInfo, tinst) -> + (match tupInfo with | TupInfo.Const false -> "" | TupInfo.Const true -> "struct ") + String.concat "," (List.map string tinst) + ")" - | TType_anon (anonInfo, tinst) -> - (match anonInfo.TupInfo with + | TType_anon (anonInfo, tinst) -> + (match anonInfo.TupInfo with | TupInfo.Const false -> "" | TupInfo.Const true -> "struct ") + "{|" + String.concat "," (Seq.map2 (fun nm ty -> nm + " " + string ty + ";") anonInfo.SortedNames tinst) + "|}" | TType_fun (domainTy, retTy, nullness) -> "(" + string domainTy + " -> " + string retTy + ")" + nullness.ToString() | TType_ucase (uc, tinst) -> "ucase " + uc.CaseName + (match tinst with [] -> "" | tys -> "<" + String.concat "," (List.map string tys) + ">") - | TType_var (tp, _) -> - match tp.Solution with + | TType_var (tp, _) -> + match tp.Solution with | None -> tp.DisplayName | Some t -> tp.DisplayName + $" (solved: {if maxDepth < 0 then Boolean.TrueString else t.LimitedToString(maxDepth-1)})" | TType_measure ms -> ms.ToString() @@ -4638,16 +4644,16 @@ type TType = override x.ToString() = x.LimitedToString(4) -type TypeInst = TType list +type TypeInst = TType list -type TTypes = TType list +type TTypes = TType list -/// Represents the information identifying an anonymous record -[] -type AnonRecdTypeInfo = +/// Represents the information identifying an anonymous record +[] +type AnonRecdTypeInfo = { // Mutability for pickling/unpickling only - mutable Assembly: CcuThunk + mutable Assembly: CcuThunk mutable TupInfo: TupInfo @@ -4661,7 +4667,7 @@ type AnonRecdTypeInfo = } /// Create an AnonRecdTypeInfo from the basic data - static member Create(ccu: CcuThunk, tupInfo, ids: Ident[]) = + static member Create(ccu: CcuThunk, tupInfo, ids: Ident[]) = let sortedIds = ids |> Array.sortBy (fun id -> id.idText) // Hash all the data to form a unique stamp. @@ -4670,9 +4676,9 @@ type AnonRecdTypeInfo = let stamp = sha1HashInt64 [| for c in ccu.AssemblyName do yield byte c; yield byte (int32 c >>> 8) - match tupInfo with + match tupInfo with | TupInfo.Const b -> yield (if b then 0uy else 1uy) - for id in sortedIds do + for id in sortedIds do for c in id.idText do yield byte c; yield byte (int32 c >>> 8) yield 0uy |] @@ -4690,11 +4696,11 @@ type AnonRecdTypeInfo = { Assembly = ccu; TupInfo = tupInfo; SortedIds = sortedIds; Stamp = stamp; SortedNames = sortedNames; IlTypeName = ilName } /// Get the ILTypeRef for the generated type implied by the anonymous type - member x.ILTypeRef = + member x.ILTypeRef = let ilTypeName = sprintf "<>f__AnonymousType%s%u`%d" (match x.TupInfo with TupInfo.Const b -> if b then "1000" else "") (uint32 x.IlTypeName) x.SortedIds.Length mkILTyRef(x.Assembly.ILScopeRef, ilTypeName) - static member NewUnlinked() : AnonRecdTypeInfo = + static member NewUnlinked() : AnonRecdTypeInfo = { Assembly = Unchecked.defaultof<_> TupInfo = Unchecked.defaultof<_> SortedIds = Unchecked.defaultof<_> @@ -4702,7 +4708,7 @@ type AnonRecdTypeInfo = SortedNames = Unchecked.defaultof<_> IlTypeName = Unchecked.defaultof<_> } - member x.Link d = + member x.Link d = let sortedNames = Array.map textOfId d.SortedIds x.Assembly <- d.Assembly x.TupInfo <- d.TupInfo @@ -4712,19 +4718,19 @@ type AnonRecdTypeInfo = x.IlTypeName <- d.IlTypeName member x.IsLinked = (match box x.SortedIds with null -> true | _ -> false) - + member x.DisplayNameCoreByIdx idx = x.SortedNames[idx] member x.DisplayNameByIdx idx = x.SortedNames[idx] |> ConvertLogicalNameToDisplayName -[] -type TupInfo = +[] +type TupInfo = /// Some constant, e.g. true or false for tupInfo | Const of bool /// Represents a unit of measure in the typed AST [] -type Measure = +type Measure = /// A variable unit-of-measure | Var of typar: Typar @@ -4741,17 +4747,17 @@ type Measure = /// The unit of measure '1', e.g. float = float<1> | One of range: range - /// Raising a measure to a rational power + /// Raising a measure to a rational power | RationalPower of measure: Measure * power: Rational // %+A formatting is used, so this is not needed //[] //member x.DebugText = x.ToString() - + override x.ToString() = sprintf "%+A" x - - member x.Range = - match x with + + member x.Range = + match x with | Var(typar) -> typar.Range | Const(range= m) -> m | Prod(range= m) -> m @@ -4795,26 +4801,26 @@ module WellKnownValAttribs = let CreateWithFlags(attribs: Attrib list, flags: WellKnownValAttributes) = WellKnownAttribs(attribs, flags) -type Attribs = Attrib list +type Attribs = Attrib list [] -type AttribKind = +type AttribKind = - /// Indicates an attribute refers to a type defined in an imported .NET assembly - | ILAttrib of ilMethodRef: ILMethodRef + /// Indicates an attribute refers to a type defined in an imported .NET assembly + | ILAttrib of ilMethodRef: ILMethodRef - /// Indicates an attribute refers to a type defined in an imported F# assembly + /// Indicates an attribute refers to a type defined in an imported F# assembly | FSAttrib of valRef: ValRef // %+A formatting is used, so this is not needed //[] //member x.DebugText = x.ToString() - override x.ToString() = sprintf "%+A" x + override x.ToString() = sprintf "%+A" x /// Attrib(tyconRef, kind, unnamedArgs, propVal, appliedToAGetterOrSetter, targetsOpt, range) [] -type Attrib = +type Attrib = | Attrib of tyconRef: TyconRef * @@ -4836,10 +4842,10 @@ type Attrib = /// We keep both source expression and evaluated expression around to help intellisense and signature printing [] -type AttribExpr = +type AttribExpr = /// AttribExpr(source, evaluated) - | AttribExpr of source: Expr * evaluated: Expr + | AttribExpr of source: Expr * evaluated: Expr [] member x.DebugText = x.ToString() @@ -4848,7 +4854,7 @@ type AttribExpr = /// AttribNamedArg(name, type, isField, value) [] -type AttribNamedArg = +type AttribNamedArg = | AttribNamedArg of (string*TType*bool*AttribExpr) [] @@ -4858,7 +4864,7 @@ type AttribNamedArg = /// Constants in expressions [] -type Const = +type Const = | Bool of bool | SByte of sbyte | Byte of byte @@ -4874,9 +4880,9 @@ type Const = | Double of double | Char of char | String of string - | Decimal of Decimal + | Decimal of Decimal | Unit - | Zero // null/zero-bit-pattern + | Zero // null/zero-bit-pattern [] member x.DebugText = x.ToString() @@ -4908,12 +4914,12 @@ type Const = /// the decision tree are labelled by integers that are unique for that /// particular tree. [] -type DecisionTree = +type DecisionTree = /// TDSwitch(input, cases, default, range) /// - /// Indicates a decision point in a decision tree. - /// input -- The expression being tested. If switching over a struct union this + /// Indicates a decision point in a decision tree. + /// input -- The expression being tested. If switching over a struct union this /// must be the address of the expression being tested. /// cases -- The list of tests and their subsequent decision trees /// default -- The default decision tree, if any @@ -4925,11 +4931,11 @@ type DecisionTree = /// Indicates the decision tree has terminated with success, transferring control to the given target with the given parameters. /// results -- the expressions to be bound to the variables at the target /// target -- the target number for the continuation - | TDSuccess of results: Exprs * targetNum: int + | TDSuccess of results: Exprs * targetNum: int /// TDBind(binding, body) /// - /// Bind the given value through the remaining cases of the dtree. + /// Bind the given value through the remaining cases of the dtree. /// These arise from active patterns and some optimizations to prevent /// repeated computations in decision trees. /// binding -- the value and the expression it is bound to @@ -4940,11 +4946,11 @@ type DecisionTree = //[] //member x.DebugText = x.ToString() - override x.ToString() = sprintf "%+A" x + override x.ToString() = sprintf "%+A" x /// Represents a test and a subsequent decision tree [] -type DecisionTreeCase = +type DecisionTreeCase = | TCase of discriminator: DecisionTreeTest * caseTree: DecisionTree /// Get the discriminator associated with the case @@ -4957,49 +4963,49 @@ type DecisionTreeCase = member x.DebugText = x.ToString() override x.ToString() = sprintf "DecisionTreeCase(...)" - + [] type ActivePatternReturnKind = | RefTypeWrapper | StructTypeWrapper | Boolean - member this.IsStruct with get () = + member this.IsStruct with get () = match this with | RefTypeWrapper -> false | StructTypeWrapper | Boolean -> true [] -type DecisionTreeTest = +type DecisionTreeTest = /// Test if the input to a decision tree matches the given union case | UnionCase of caseRef: UnionCaseRef * tinst: TypeInst - /// Test if the input to a decision tree is an array of the given length - | ArrayLength of length: int * ty: TType + /// Test if the input to a decision tree is an array of the given length + | ArrayLength of length: int * ty: TType - /// Test if the input to a decision tree is the given constant value + /// Test if the input to a decision tree is the given constant value | Const of value: Const - /// Test if the input to a decision tree is null - | IsNull + /// Test if the input to a decision tree is null + | IsNull /// IsInst(source, target) /// - /// Test if the input to a decision tree is an instance of the given type + /// Test if the input to a decision tree is an instance of the given type | IsInst of source: TType * target: TType /// Test.ActivePatternCase(activePatExpr, activePatResTys, activePatRetKind, activePatIdentity, idx, activePatInfo) /// - /// Run the active pattern and bind a successful result to a - /// variable in the remaining tree. + /// Run the active pattern and bind a successful result to a + /// variable in the remaining tree. /// activePatExpr -- The active pattern function being called, perhaps applied to some active pattern parameters. /// activePatResTys -- The result types (case types) of the active pattern. /// activePatRetKind -- Indicating what is returning from the active pattern - /// activePatIdentity -- The value and the types it is applied to. If there are any active pattern parameters then this is empty. + /// activePatIdentity -- The value and the types it is applied to. If there are any active pattern parameters then this is empty. /// idx -- The case number of the active pattern which the test relates to. /// activePatternInfo -- The extracted info for the active pattern. | ActivePatternCase of - activePatExpr: Expr * + activePatExpr: Expr * activePatResTys: TTypes * activePatRetKind: ActivePatternReturnKind * activePatIdentity: (ValRef * TypeInst) option * @@ -5013,16 +5019,16 @@ type DecisionTreeTest = //[] //member x.DebugText = x.ToString() - override x.ToString() = sprintf "%+A" x + override x.ToString() = sprintf "%+A" x -/// A target of a decision tree. Can be thought of as a little function, though is compiled as a local block. +/// A target of a decision tree. Can be thought of as a little function, though is compiled as a local block. /// -- boundVals - The values bound at the target, matching the valuesin the TDSuccess /// -- targetExpr - The expression to evaluate if we branch to the target /// -- debugPoint - The debug point for the target /// -- isStateVarFlags - Indicates which, if any, of the values are represents as state machine variables [] -type DecisionTreeTarget = - | TTarget of +type DecisionTreeTarget = + | TTarget of boundVals: Val list * targetExpr: Expr * isStateVarFlags: bool list option @@ -5042,7 +5048,7 @@ type Bindings = Binding list /// -- expr: The expression to execute to get the value /// -- debugPoint: The debug point for the binding [] -type Binding = +type Binding = | TBind of var: Val * expr: Expr * @@ -5062,10 +5068,10 @@ type Binding = override x.ToString() = sprintf "TBind(%s, ...)" (x.Var.CompiledName None) -/// Represents a reference to an active pattern element. The -/// integer indicates which choice in the target set is being selected by this item. +/// Represents a reference to an active pattern element. The +/// integer indicates which choice in the target set is being selected by this item. [] -type ActivePatternElemRef = +type ActivePatternElemRef = | APElemRef of activePatternInfo: ActivePatternInfo * activePatternVal: ValRef * @@ -5081,7 +5087,7 @@ type ActivePatternElemRef = /// Get a reference to the value for the active pattern being referred to member x.ActivePatternRetKind = (let (APElemRef(_, _, _, activePatRetKind)) = x in activePatRetKind) - /// Get the index of the active pattern element within the overall active pattern + /// Get the index of the active pattern element within the overall active pattern member x.CaseIndex = (let (APElemRef(_, _, n, _)) = x in n) [] @@ -5092,12 +5098,12 @@ type ActivePatternElemRef = /// Records the "extra information" for a value compiled as a method (rather /// than a closure or a local), including argument names, attributes etc. [] -type ValReprInfo = +type ValReprInfo = /// ValReprInfo (typars, args, result) | ValReprInfo of typars: TyparReprInfo list * args: ArgReprInfo list list * - result: ArgReprInfo + result: ArgReprInfo /// Get the extra information about the arguments for the value member x.ArgInfos = (let (ValReprInfo(_, args, _)) = x in args) @@ -5117,17 +5123,17 @@ type ValReprInfo = /// Get the kind of each type parameter member x.KindsOfTypars = (let (ValReprInfo(n, _, _)) = x in n |> List.map (fun (TyparReprInfo(_, k)) -> k)) - /// Get the total number of arguments - member x.TotalArgCount = + /// Get the total number of arguments + member x.TotalArgCount = let (ValReprInfo(_, args, _)) = x // This is List.sumBy List.length args // We write this by hand as it can be a performance bottleneck in LinkagePartialKey - let rec loop (args: ArgReprInfo list list) acc = - match args with - | [] -> acc - | [] :: t -> loop t acc - | [_] :: t -> loop t (acc+1) - | (_ :: _ :: h) :: t -> loop t (acc + h.Length + 2) + let rec loop (args: ArgReprInfo list list) acc = + match args with + | [] -> acc + | [] :: t -> loop t acc + | [_] :: t -> loop t (acc+1) + | (_ :: _ :: h) :: t -> loop t (acc + h.Length + 2) loop args 0 member x.ArgNames = @@ -5149,7 +5155,7 @@ type ArgReprInfo = { /// The attributes for the argument // MUTABILITY: used when propagating signature attributes into the implementation. - mutable Attribs: WellKnownValAttribs + mutable Attribs: WellKnownValAttribs /// The name for the argument at this position, if any // MUTABILITY: used when propagating names of parameters from signature into the implementation. @@ -5166,13 +5172,13 @@ type ArgReprInfo = override _.ToString() = "ArgReprInfo(...)" /// Records the extra metadata stored about typars for type parameters -/// compiled as "real" IL type parameters, specifically for values with +/// compiled as "real" IL type parameters, specifically for values with /// ValReprInfo. Any information here is propagated from signature through /// to the compiled code. type TyparReprInfo = TyparReprInfo of Ident * TyparKind type Typars = Typar list - + type Exprs = Expr list type Vals = Val list @@ -5180,42 +5186,42 @@ type Vals = Val list /// Represents an expression in the typed abstract syntax [] type Expr = - /// A constant expression. + /// A constant expression. | Const of value: Const * range: range * constType: TType - /// Reference a value. The flag is only relevant if the value is an object model member - /// and indicates base calls and special uses of object constructors. + /// Reference a value. The flag is only relevant if the value is an object model member + /// and indicates base calls and special uses of object constructors. | Val of valRef: ValRef * flags: ValUseFlag * range: range - /// Sequence expressions, used for "a;b", "let a = e in b;a" and "a then b" (the last an OO constructor). + /// Sequence expressions, used for "a;b", "let a = e in b;a" and "a then b" (the last an OO constructor). | Sequential of expr1: Expr * expr2: Expr * kind: SequentialOpKind * range: range - /// Lambda expressions. - - /// Why multiple vspecs? A Expr.Lambda taking multiple arguments really accepts a tuple. - /// But it is in a convenient form to be compile accepting multiple - /// arguments, e.g. if compiled as a toplevel static method. + /// Lambda expressions. + + /// Why multiple vspecs? A Expr.Lambda taking multiple arguments really accepts a tuple. + /// But it is in a convenient form to be compile accepting multiple + /// arguments, e.g. if compiled as a toplevel static method. | Lambda of unique: Unique * ctorThisValOpt: Val option * baseValOpt: Val option * valParams: Val list * - bodyExpr: Expr * + bodyExpr: Expr * range: range * overallType: TType - /// Type lambdas. These are used for the r.h.s. of polymorphic 'let' bindings and - /// for expressions that implement first-class polymorphic values. + /// Type lambdas. These are used for the r.h.s. of polymorphic 'let' bindings and + /// for expressions that implement first-class polymorphic values. | TyLambda of unique: Unique * typeParams: Typars * @@ -5224,45 +5230,45 @@ type Expr = overallType: TType /// Applications. - /// Applications combine type and term applications, and are normalized so - /// that sequential applications are combined, so "(f x y)" becomes "f [[x];[y]]". - /// The type attached to the function is the formal function type, used to ensure we don't build application - /// nodes that over-apply when instantiating at function types. + /// Applications combine type and term applications, and are normalized so + /// that sequential applications are combined, so "(f x y)" becomes "f [[x];[y]]". + /// The type attached to the function is the formal function type, used to ensure we don't build application + /// nodes that over-apply when instantiating at function types. | App of funcExpr: Expr * formalType: TType * typeArgs: TypeInst * args: Exprs * - range: range + range: range - /// Bind a recursive set of values. + /// Bind a recursive set of values. | LetRec of bindings: Bindings * bodyExpr: Expr * range: range * frees: FreeVarsCache - /// Bind a value. + /// Bind a value. | Let of binding: Binding * bodyExpr: Expr * range: range * frees: FreeVarsCache - // Object expressions: A closure that implements an interface or a base type. - // The base object type might be a delegate type. - | Obj of - unique: Unique * + // Object expressions: A closure that implements an interface or a base type. + // The base object type might be a delegate type. + | Obj of + unique: Unique * objTy: TType * (* <-- NOTE: specifies type parameters for base type *) - baseVal: Val option * - ctorCall: Expr * - overrides: ObjExprMethod list * - interfaceImpls: (TType * ObjExprMethod list) list * + baseVal: Val option * + ctorCall: Expr * + overrides: ObjExprMethod list * + interfaceImpls: (TType * ObjExprMethod list) list * range: range - /// Matches are a more complicated form of "let" with multiple possible destinations - /// and possibly multiple ways to get to each destination. - /// The first range is that of the expression being matched, which is used + /// Matches are a more complicated form of "let" with multiple possible destinations + /// and possibly multiple ways to get to each destination. + /// The first range is that of the expression being matched, which is used /// as the range for all the decision making and binding that happens during the decision tree /// execution. | Match of @@ -5273,24 +5279,24 @@ type Expr = fullRange: range * exprType: TType - /// If we statically know some information then in many cases we can use a more optimized expression - /// This is primarily used by terms in the standard library, particularly those implementing overloaded - /// operators. + /// If we statically know some information then in many cases we can use a more optimized expression + /// This is primarily used by terms in the standard library, particularly those implementing overloaded + /// operators. | StaticOptimization of conditions: StaticOptimization list * expr: Expr * alternativeExpr: Expr * range: range - /// An intrinsic applied to some (strictly evaluated) arguments - /// A few of intrinsics (TOp_try, TOp.While, TOp.IntegerForLoop) expect arguments kept in a normal form involving lambdas + /// An intrinsic applied to some (strictly evaluated) arguments + /// A few of intrinsics (TOp_try, TOp.While, TOp.IntegerForLoop) expect arguments kept in a normal form involving lambdas | Op of op: TOp * typeArgs: TypeInst * args: Exprs * range: range - /// Indicates the expression is a quoted expression tree. + /// Indicates the expression is a quoted expression tree. /// // MUTABILITY: this use of mutability is awkward and perhaps should be removed | Quote of @@ -5298,8 +5304,8 @@ type Expr = quotationInfo: ((ILTypeRef list * TTypes * Exprs * ExprData) * (ILTypeRef list * TTypes * Exprs * ExprData)) option ref * isFromQueryExpression: bool * range: range * - quotedType: TType - + quotedType: TType + /// Used in quotation generation to indicate a witness argument, spliced into a quotation literal. /// /// For example: @@ -5313,28 +5319,28 @@ type Expr = /// /// f$W(witnessForSin, x) { return Deserialize(<@ sin$W _spliceHole1 _spliceHole2 @>, [| WitnessArg(witnessForSin), x |]) } /// - /// where _spliceHole1 will be the location of the witness argument in the quotation data, and + /// where _spliceHole1 will be the location of the witness argument in the quotation data, and /// witnessArg is the lambda for the witness - /// + /// | WitnessArg of traitInfo: TraitConstraintInfo * range: range - /// Indicates a free choice of typars that arises due to - /// minimization of polymorphism at let-rec bindings. These are - /// resolved to a concrete instantiation on subsequent rewrites. + /// Indicates a free choice of typars that arises due to + /// minimization of polymorphism at let-rec bindings. These are + /// resolved to a concrete instantiation on subsequent rewrites. | TyChoose of typeParams: Typars * bodyExpr: Expr * range: range - /// An instance of a link node occurs for every use of a recursively bound variable. When type-checking - /// the recursive bindings a dummy expression is stored in the mutable reference cell. - /// After type checking the bindings this is replaced by a use of the variable, perhaps at an - /// appropriate type instantiation. These are immediately eliminated on subsequent rewrites. + /// An instance of a link node occurs for every use of a recursively bound variable. When type-checking + /// the recursive bindings a dummy expression is stored in the mutable reference cell. + /// After type checking the bindings this is replaced by a use of the variable, perhaps at an + /// appropriate type instantiation. These are immediately eliminated on subsequent rewrites. | Link of Expr ref - /// Indicates a debug point should be placed prior to the expression. + /// Indicates a debug point should be placed prior to the expression. | DebugPoint of DebugPointAtLeafExpr * Expr [] @@ -5342,14 +5348,14 @@ type Expr = override expr.ToString() = expr.ToDebugString(3) - member expr.ToDebugString(depth: int) : string = + member expr.ToDebugString(depth: int) : string = if depth = 0 then ".." else let depth = depth - 1 - match expr with + match expr with | Const (c, _, _) -> string c | Val (v, _, _) -> v.LogicalName | Sequential (e1, e2, _, _) -> "Sequential(" + e1.ToDebugString(depth) + ", " + e2.ToDebugString(depth) + ")" - | Lambda (_, _, _, vs, body, _, _) -> sprintf "Lambda(%+A, " vs + body.ToDebugString(depth) + ")" + | Lambda (_, _, _, vs, body, _, _) -> sprintf "Lambda(%+A, " vs + body.ToDebugString(depth) + ")" | TyLambda (_, tps, body, _, _) -> sprintf "TyLambda(%+A, " tps + body.ToDebugString(depth) + ")" | App (f, _, _, args, _) -> "App(" + f.ToDebugString(depth) + ", [" + String.concat ", " (args |> List.map (fun e -> e.ToDebugString(depth))) + "])" | LetRec _ -> "LetRec(..)" @@ -5368,24 +5374,24 @@ type Expr = member expr.Range = match expr with | Expr.Val (_, _, m) | Expr.Op (_, _, _, m) | Expr.Const (_, m, _) | Expr.Quote (_, _, _, m, _) - | Expr.Obj (_, _, _, _, _, _, m) | Expr.App (_, _, _, _, m) | Expr.Sequential (_, _, _, m) - | Expr.StaticOptimization (_, _, _, m) | Expr.Lambda (_, _, _, _, _, m, _) + | Expr.Obj (_, _, _, _, _, _, m) | Expr.App (_, _, _, _, m) | Expr.Sequential (_, _, _, m) + | Expr.StaticOptimization (_, _, _, m) | Expr.Lambda (_, _, _, _, _, m, _) | Expr.WitnessArg (_, m) | Expr.TyLambda (_, _, _, m, _)| Expr.TyChoose (_, _, m) | Expr.LetRec (_, _, m, _) | Expr.Let (_, _, m, _) | Expr.Match (_, _, _, _, m, _) -> m | Expr.Link eref -> eref.Value.Range | Expr.DebugPoint (_, e2) -> e2.Range - + [] type TOp = /// An operation representing the creation of a union value of the particular union case - | UnionCase of UnionCaseRef + | UnionCase of UnionCaseRef /// An operation representing the creation of an exception value using an F# exception declaration | ExnConstr of TyconRef /// An operation representing the creation of a tuple value - | Tuple of TupInfo + | Tuple of TupInfo /// An operation representing the creation of an anonymous record | AnonRecd of AnonRecdTypeInfo @@ -5400,7 +5406,7 @@ type TOp = | Bytes of byte[] /// Constant uint16 arrays (used for parser tables) - | UInt16s of uint16[] + | UInt16s of uint16[] /// An operation representing a lambda-encoded while loop. The special while loop marker is used to mark compilations of 'foreach' expressions | While of spWhile: DebugPointAtWhile * marker: SpecialWhileLoopMarker @@ -5414,30 +5420,30 @@ type TOp = /// An operation representing a lambda-encoded try/finally | TryFinally of spTry: DebugPointAtTry * spFinally: DebugPointAtFinally - /// Construct a record or object-model value. The ValRef is for self-referential class constructors, otherwise - /// it indicates that we're in a constructor and the purpose of the expression is to - /// fill in the fields of a pre-created but uninitialized object, and to assign the initialized - /// version of the object into the optional mutable cell pointed to be the given value. + /// Construct a record or object-model value. The ValRef is for self-referential class constructors, otherwise + /// it indicates that we're in a constructor and the purpose of the expression is to + /// fill in the fields of a pre-created but uninitialized object, and to assign the initialized + /// version of the object into the optional mutable cell pointed to be the given value. | Recd of RecordConstructionInfo * TyconRef - + /// An operation representing setting a record or class field - | ValFieldSet of RecdFieldRef + | ValFieldSet of RecdFieldRef /// An operation representing getting a record or class field - | ValFieldGet of RecdFieldRef + | ValFieldGet of RecdFieldRef /// An operation representing getting the address of a record field - | ValFieldGetAddr of RecdFieldRef * readonly: bool + | ValFieldGetAddr of RecdFieldRef * readonly: bool /// An operation representing getting an integer tag for a union value representing the union case number - | UnionCaseTagGet of TyconRef + | UnionCaseTagGet of TyconRef /// An operation representing a coercion that proves a union value is of a particular union case. This is not a test, its /// simply added proof to enable us to generate verifiable code for field access on union types | UnionCaseProof of UnionCaseRef /// An operation representing a field-get from a union value, where that value has been proven to be of the corresponding union case. - | UnionCaseFieldGet of UnionCaseRef * int + | UnionCaseFieldGet of UnionCaseRef * int /// An operation representing a field-get from a union value, where that value has been proven to be of the corresponding union case. | UnionCaseFieldGetAddr of UnionCaseRef * int * readonly: bool @@ -5446,27 +5452,27 @@ type TOp = | UnionCaseFieldSet of UnionCaseRef * int /// An operation representing a field-get from an F# exception value. - | ExnFieldGet of TyconRef * int + | ExnFieldGet of TyconRef * int /// An operation representing a field-set on an F# exception value. - | ExnFieldSet of TyconRef * int + | ExnFieldSet of TyconRef * int /// An operation representing a field-get from an F# tuple value. - | TupleFieldGet of TupInfo * int + | TupleFieldGet of TupInfo * int - /// IL assembly code - type list are the types pushed on the stack - | ILAsm of - instrs: ILInstr list * - retTypes: TTypes + /// IL assembly code - type list are the types pushed on the stack + | ILAsm of + instrs: ILInstr list * + retTypes: TTypes - /// Generate a ldflda on an 'a ref. + /// Generate a ldflda on an 'a ref. | RefAddrGet of bool - /// Conversion node, compiled via type-directed translation or to box/unbox - | Coerce + /// Conversion node, compiled via type-directed translation or to box/unbox + | Coerce - /// Represents a "rethrow" operation. May not be rebound, or used outside of try-finally, expecting a unit argument - | Reraise + /// Represents a "rethrow" operation. May not be rebound, or used outside of try-finally, expecting a unit argument + | Reraise /// Used for state machine compilation | Return @@ -5477,34 +5483,34 @@ type TOp = /// Used for state machine compilation | Label of ILCodeLabel - /// Pseudo method calls. This is used for overloaded operations like op_Addition. - | TraitCall of TraitConstraintInfo + /// Pseudo method calls. This is used for overloaded operations like op_Addition. + | TraitCall of TraitConstraintInfo - /// Operation nodes representing C-style operations on byrefs and mutable vals (l-values) - | LValueOp of LValueOperation * ValRef + /// Operation nodes representing C-style operations on byrefs and mutable vals (l-values) + | LValueOp of LValueOperation * ValRef /// IL method calls. - /// isProperty -- used for quotation reflection, property getters & setters - /// noTailCall - DllImport? if so don't tailcall + /// isProperty -- used for quotation reflection, property getters & setters + /// noTailCall - DllImport? if so don't tailcall /// retTypes -- the types of pushed values, if any - | ILCall of - isVirtual: bool * - isProtected: bool * - isStruct: bool * - isCtor: bool * - valUseFlag: ValUseFlag * - isProperty: bool * - noTailCall: bool * - ilMethRef: ILMethodRef * - enclTypeInst: TypeInst * - methInst: TypeInst * - retTypes: TTypes + | ILCall of + isVirtual: bool * + isProtected: bool * + isStruct: bool * + isCtor: bool * + valUseFlag: ValUseFlag * + isProperty: bool * + noTailCall: bool * + ilMethRef: ILMethodRef * + enclTypeInst: TypeInst * + methInst: TypeInst * + retTypes: TTypes [] member x.DebugText = x.ToString() - - override op.ToString() = - match op with + + override op.ToString() = + match op with | UnionCase ucref -> "UnionCase(" + ucref.CaseName + ")" | ExnConstr ecref -> "ExnConstr(" + ecref.LogicalName + ")" | Tuple _tupinfo -> "Tuple" @@ -5541,13 +5547,13 @@ type TOp = | ILCall (_,_,_,_,_,_,_,ilMethRef,_,_,_) -> "ILCall(" + ilMethRef.ToString() + ",..)" /// Represents the kind of record construction operation. -type RecordConstructionInfo = +type RecordConstructionInfo = - /// We're in an explicit constructor. The purpose of the record expression is to - /// fill in the fields of a pre-created but uninitialized object + /// We're in an explicit constructor. The purpose of the record expression is to + /// fill in the fields of a pre-created but uninitialized object | RecdExprIsObjInit - /// Normal record construction + /// Normal record construction | RecdExpr /// If this is Some ty then it indicates that a .NET 2.0 constrained call is required, with the given type as the @@ -5555,52 +5561,52 @@ type RecordConstructionInfo = type ConstrainedCallInfo = TType option /// Represents the kind of looping operation. -type SpecialWhileLoopMarker = +type SpecialWhileLoopMarker = | NoSpecialWhileLoopMarker /// Marks the compiled form of a 'for ... in ... do ' expression | WhileLoopForCompiledForEachExprMarker - + /// Represents the kind of looping operation. -type ForLoopStyle = +type ForLoopStyle = /// Evaluate start and end once, loop up - | FSharpForLoopUp + | FSharpForLoopUp /// Evaluate start and end once, loop down - | FSharpForLoopDown + | FSharpForLoopDown /// Evaluate start once and end multiple times, loop up | CSharpForLoopUp /// Indicates what kind of pointer operation this is. -type LValueOperation = +type LValueOperation = - /// In C syntax this is: &localv + /// In C syntax this is: &localv | LAddrOf of readonly: bool - /// In C syntax this is: *localv_ptr - | LByrefGet + /// In C syntax this is: *localv_ptr + | LByrefGet /// In C syntax this is: localv = e, note == *(&localv) = e == LAddrOf; LByrefSet - | LSet + | LSet - /// In C syntax this is: *localv_ptr = e - | LByrefSet + /// In C syntax this is: *localv_ptr = e + | LByrefSet /// Represents the kind of sequential operation, i.e. "normal" or "to a before returning b" -type SequentialOpKind = - /// a ; b - | NormalSeq +type SequentialOpKind = + /// a ; b + | NormalSeq - /// let res = a in b;res - | ThenDoSeq + /// let res = a in b;res + | ThenDoSeq /// Indicates how a value, function or member is being used at a particular usage point. type ValUseFlag = /// Indicates a use of a value represents a call to a method that may require - /// a .NET 2.0 constrained call. A constrained call is only used for calls where + /// a .NET 2.0 constrained call. A constrained call is only used for calls where // the object argument is a value type or generic type, and the call is to a method // on System.Object, System.ValueType, System.Enum or an interface methods. | PossibleConstrainedCall of ty: TType @@ -5616,21 +5622,21 @@ type ValUseFlag = /// A call to a base method, e.g. 'base.OnPaint(args)' | VSlotDirectCall - + /// Represents the kind of an F# core library static optimization construct -type StaticOptimization = +type StaticOptimization = /// Indicates the static optimization applies when a type equality holds | TTyconEqualsTycon of ty1: TType * ty2: TType /// Indicates the static optimization applies when a type is a struct - | TTyconIsStruct of ty: TType - -/// A representation of a method in an object expression. + | TTyconIsStruct of ty: TType + +/// A representation of a method in an object expression. /// /// TObjExprMethod(slotsig, attribs, methTyparsOfOverridingMethod, methodParams, methodBodyExpr, m) [] -type ObjExprMethod = +type ObjExprMethod = | TObjExprMethod of slotSig: SlotSig * @@ -5651,7 +5657,7 @@ type ObjExprMethod = /// /// TSlotSig(methodName, declaringType, declaringTypeParameters, methodTypeParameters, slotParameters, returnTy) [] -type SlotSig = +type SlotSig = | TSlotSig of methodName: string * declaringType: TType * @@ -5663,7 +5669,7 @@ type SlotSig = /// The name of the method member ss.Name = let (TSlotSig(nm, _, _, _, _, _)) = ss in nm - /// The (instantiated) type which the slot is logically a part of + /// The (instantiated) type which the slot is logically a part of member ss.DeclaringType = let (TSlotSig(_, ty, _, _, _, _)) = ss in ty /// The class type parameters of the slot @@ -5683,11 +5689,11 @@ type SlotSig = override ss.ToString() = sprintf "TSlotSig(%s, ...)" ss.Name -/// Represents a parameter to an abstract method slot. +/// Represents a parameter to an abstract method slot. /// /// TSlotParam(nm, ty, inFlag, outFlag, optionalFlag, attribs) [] -type SlotParam = +type SlotParam = | TSlotParam of paramName: string option * paramType: TType * @@ -5707,19 +5713,19 @@ type SlotParam = type OpenDeclaration = { /// Syntax after 'open' as it's presented in source code. Target: SynOpenDeclTarget - + /// Full range of the open declaration. Range: range option /// Modules or namespaces which is opened with this declaration. - Modules: ModuleOrNamespaceRef list - + Modules: ModuleOrNamespaceRef list + /// Types whose static content is opened with this declaration. Types: TType list /// Scope in which open declaration is visible. - AppliedScope: range - + AppliedScope: range + /// If it's `namespace Xxx.Yyy` declaration. IsOwnNamespace: bool } @@ -5728,24 +5734,24 @@ type OpenDeclaration = static member Create(target: SynOpenDeclTarget, modules: ModuleOrNamespaceRef list, types: TType list, appliedScope: range, isOwnNamespace: bool) = { Target = target Range = - match target with + match target with | SynOpenDeclTarget.ModuleOrNamespace (range=m) | SynOpenDeclTarget.Type (range=m) -> Some m Types = types Modules = modules AppliedScope = appliedScope IsOwnNamespace = isOwnNamespace } - -/// The contents of a module-or-namespace-fragment definition + +/// The contents of a module-or-namespace-fragment definition [] -type ModuleOrNamespaceContents = - /// Indicates the module fragment is made of several module fragments in succession - | TMDefs of defs: ModuleOrNamespaceContents list +type ModuleOrNamespaceContents = + /// Indicates the module fragment is made of several module fragments in succession + | TMDefs of defs: ModuleOrNamespaceContents list /// Indicates the given 'open' declarations are active | TMDefOpens of openDecls: OpenDeclaration list - /// Indicates the module fragment is a 'let' definition + /// Indicates the module fragment is a 'let' definition | TMDefLet of binding: Binding * range: range /// Indicates the module fragment is an evaluation of expression for side-effects @@ -5758,19 +5764,19 @@ type ModuleOrNamespaceContents = //[] member x.DebugText = x.ToString() - override x.ToString() = sprintf "%+A" x + override x.ToString() = sprintf "%+A" x -/// A named module-or-namespace-fragment definition +/// A named module-or-namespace-fragment definition [] -type ModuleOrNamespaceBinding = +type ModuleOrNamespaceBinding = - | Binding of binding: Binding + | Binding of binding: Binding /// The moduleOrNamespace represents the signature of the module. /// The moduleOrNamespaceContents contains the definitions of the module. /// The same set of entities are bound in the ModuleOrNamespace as in the ModuleOrNamespaceContents. - | Module of - moduleOrNamespace: ModuleOrNamespace * + | Module of + moduleOrNamespace: ModuleOrNamespace * moduleOrNamespaceContents: ModuleOrNamespaceContents [] @@ -5785,16 +5791,16 @@ type NamedDebugPointKey = override x.GetHashCode() = hash x.Name + hash x.Range - override x.Equals(yobj: objnull) = - match yobj with + override x.Equals(yobj: objnull) = + match yobj with | :? NamedDebugPointKey as y -> equals x.Range y.Range && x.Name = y.Name | _ -> false interface IComparable with member x.CompareTo(yobj: obj) = - match yobj with - | :? NamedDebugPointKey as y -> - let c = rangeOrder.Compare(x.Range, y.Range) + match yobj with + | :? NamedDebugPointKey as y -> + let c = rangeOrder.Compare(x.Range, y.Range) if c <> 0 then c else compare x.Name y.Name | _ -> -1 @@ -5803,8 +5809,8 @@ type NamedDebugPointKey = /// /// CheckedImplFile (qualifiedNameOfFile, pragmas, signature, contents, hasExplicitEntryPoint, isScript, anonRecdTypeInfo) [] -type CheckedImplFile = - | CheckedImplFile of +type CheckedImplFile = + | CheckedImplFile of qualifiedNameOfFile: QualifiedNameOfFile * signature: ModuleOrNamespaceType * contents: ModuleOrNamespaceContents * @@ -5830,8 +5836,8 @@ type CheckedImplFile = /// Represents a complete typechecked assembly, made up of multiple implementation files. [] -type CheckedImplFileAfterOptimization = - { ImplFile: CheckedImplFile +type CheckedImplFileAfterOptimization = + { ImplFile: CheckedImplFile OptimizeDuringCodeGen: bool -> Expr -> Expr } [] @@ -5841,7 +5847,7 @@ type CheckedImplFileAfterOptimization = /// Represents a complete typechecked assembly, made up of multiple implementation files. [] -type CheckedAssemblyAfterOptimization = +type CheckedAssemblyAfterOptimization = | CheckedAssemblyAfterOptimization of CheckedImplFileAfterOptimization list [] @@ -5850,53 +5856,53 @@ type CheckedAssemblyAfterOptimization = override x.ToString() = "CheckedAssemblyAfterOptimization(...)" [] -type CcuData = +type CcuData = { - /// Holds the file name for the DLL, if any - FileName: string option - - /// Holds the data indicating how this assembly/module is referenced from the code being compiled. + /// Holds the file name for the DLL, if any + FileName: string option + + /// Holds the data indicating how this assembly/module is referenced from the code being compiled. ILScopeRef: ILScopeRef - - /// A unique stamp for this DLL + + /// A unique stamp for this DLL Stamp: Stamp - - /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations - QualifiedName: string option - - /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) - SourceCodeDirectory: string - + + /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations + QualifiedName: string option + + /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) + SourceCodeDirectory: string + /// Indicates that this DLL was compiled using the F# compiler and has F# metadata - IsFSharp: bool - + IsFSharp: bool + #if !NO_TYPEPROVIDERS /// Is the CCu an assembly injected by a type provider - IsProviderGenerated: bool + IsProviderGenerated: bool /// Triggered when the contents of the CCU are invalidated - InvalidateEvent: IEvent + InvalidateEvent: IEvent - /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality /// logic in tastops.fs - ImportProvidedType: Tainted -> TType - + ImportProvidedType: Tainted -> TType + #endif /// Indicates that this DLL uses pre-F#-4.0 quotation literals somewhere. This is used to implement a restriction on static linking mutable UsesFSharp20PlusQuotations: bool - + /// A handle to the full specification of the contents of the module contained in this ccu - // NOTE: may contain transient state during typechecking + // NOTE: may contain transient state during typechecking mutable Contents: ModuleOrNamespace - - /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + + /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality /// logic in tastops.fs - TryGetILModuleDef: unit -> ILModuleDef option - - /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality + TryGetILModuleDef: unit -> ILModuleDef option + + /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality /// logic in tastops.fs - MemberSignatureEquality: TType -> TType -> bool - + MemberSignatureEquality: TType -> TType -> bool + /// The table of .NET CLI type forwarders for this assembly TypeForwarders: CcuTypeForwarderTable @@ -5939,7 +5945,7 @@ type CcuTypeForwarderTable = Root : CcuTypeForwarderTree } - static member Empty : CcuTypeForwarderTable = { Root = CcuTypeForwarderTree.Empty } + static member Empty : CcuTypeForwarderTable = { Root = CcuTypeForwarderTree.Empty } member this.TryGetValue (path:string array) (item:string): Lazy option = CcuTypeForwarderTable.findInTree (ArraySegment path) item this.Root @@ -5964,7 +5970,7 @@ type CcuReference = string // ILAssemblyRef // the data structure, or it is a delayed fixup, i.e. an invalid dangling // reference that has not had an appropriate fixup applied. [] -type CcuThunk = +type CcuThunk = { /// ccu.target is null when a reference is missing in the transitive closure of static references that /// may potentially be required for the metadata of referenced DLLs. @@ -5972,36 +5978,36 @@ type CcuThunk = name: CcuReference } - /// Dereference the assembly reference - member ccu.Deref = - if isNull (box ccu.target) then + /// Dereference the assembly reference + member ccu.Deref = + if isNull (box ccu.target) then raise(UnresolvedReferenceNoRange ccu.name) ccu.target - + /// Indicates if this assembly reference is unresolved member ccu.IsUnresolvedReference = isNull (box ccu.target) /// Ensure the ccu is derefable in advance. Supply a path to attach to any resulting error message. - member ccu.EnsureDerefable(requiringPath: string[]) = - if ccu.IsUnresolvedReference then + member ccu.EnsureDerefable(requiringPath: string[]) = + if ccu.IsUnresolvedReference then let path = String.Join(".", requiringPath) raise(UnresolvedPathReferenceNoRange(ccu.name, path)) - + /// Indicates that this DLL uses F# 2.0+ quotation literals somewhere. This is used to implement a restriction on static linking. - member ccu.UsesFSharp20PlusQuotations - with get() = ccu.Deref.UsesFSharp20PlusQuotations + member ccu.UsesFSharp20PlusQuotations + with get() = ccu.Deref.UsesFSharp20PlusQuotations and set v = ccu.Deref.UsesFSharp20PlusQuotations <- v /// The short name of the assembly being referenced member ccu.AssemblyName = ccu.name - /// Holds the data indicating how this assembly/module is referenced from the code being compiled. + /// Holds the data indicating how this assembly/module is referenced from the code being compiled. member ccu.ILScopeRef = ccu.Deref.ILScopeRef /// A unique stamp for this assembly member ccu.Stamp = ccu.Deref.Stamp - /// Holds the file name for the assembly, if any + /// Holds the file name for the assembly, if any member ccu.FileName = ccu.Deref.FileName /// Try to get the .NET Assembly, if known. May not be present for `IsFSharp` for @@ -6016,17 +6022,17 @@ type CcuThunk = member ccu.ImportProvidedType ty: TType = ccu.Deref.ImportProvidedType ty #endif - /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations + /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations member ccu.QualifiedName = ccu.Deref.QualifiedName - /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) + /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) member ccu.SourceCodeDirectory = ccu.Deref.SourceCodeDirectory /// Indicates that this DLL was compiled using the F# compiler and has F# metadata member ccu.IsFSharp = ccu.Deref.IsFSharp /// A handle to the full specification of the contents of the module contained in this ccu - // NOTE: may contain transient state during typechecking + // NOTE: may contain transient state during typechecking member ccu.Contents = ccu.Deref.Contents /// The table of type forwarders for this assembly @@ -6039,41 +6045,41 @@ type CcuThunk = member ccu.RootTypeAndExceptionDefinitions = ccu.Contents.ModuleOrNamespaceType.TypeAndExceptionDefinitions /// Create a CCU with the given name and contents - static member Create(nm, x) = - { target = x + static member Create(nm, x) = + { target = x name = nm } /// Create a CCU with the given name but where the contents have not yet been specified - static member CreateDelayed nm = - { target = Unchecked.defaultof<_> + static member CreateDelayed nm = + { target = Unchecked.defaultof<_> name = nm } /// Fixup a CCU to have the given contents - member x.Fixup(avail: CcuThunk) = + member x.Fixup(avail: CcuThunk) = match box x.target with | null -> () - | _ -> + | _ -> // In the IDE we tolerate a double-fixup of FSHarp.Core when editing the FSharp.Core project itself - if x.AssemblyName <> "FSharp.Core" then + if x.AssemblyName <> "FSharp.Core" then errorR(Failure("internal error: Fixup: the ccu thunk for assembly "+x.AssemblyName+" not delayed!")) assert (avail.AssemblyName = x.AssemblyName) - x.target <- + x.target <- match box avail.target with | null -> error(Failure("internal error: ccu thunk '"+avail.name+"' not fixed up!")) | _ -> avail.target /// Try to resolve a path into the CCU by referencing the .NET/CLI type forwarder table of the CCU - member ccu.TryForward(nlpath: string[], item: string) : EntityRef option = + member ccu.TryForward(nlpath: string[], item: string) : EntityRef option = ccu.EnsureDerefable nlpath ccu.TypeForwarders.TryGetValue nlpath item |> Option.map (fun entity -> entity.Force()) /// Used to make forward calls into the type/assembly loader when comparing member signatures during linking - member ccu.MemberSignatureEquality(ty1: TType, ty2: TType) = + member ccu.MemberSignatureEquality(ty1: TType, ty2: TType) = ccu.Deref.MemberSignatureEquality ty1 ty2 - + [] member x.DebugText = x.ToString() @@ -6123,12 +6129,12 @@ type FreeLocals = Zset /// (never cached type checking). Cached in expressions. Not pickled. type FreeTypars = Zset -/// Represents a set of 'free' named type definitions. Used to collect the named type definitions referred to +/// Represents a set of 'free' named type definitions. Used to collect the named type definitions referred to /// from a type or expression. Computed and cached by later phases (never cached type checking). Cached /// in expressions. Not pickled. type FreeTycons = Zset -/// Represents a set of 'free' record field definitions. Used to collect the record field definitions referred to +/// Represents a set of 'free' record field definitions. Used to collect the record field definitions referred to /// from an expression. type FreeRecdFields = Zset @@ -6138,17 +6144,17 @@ type FreeUnionCases = Zset /// Represents a set of 'free' type-related elements, including named types, trait solutions, union cases and /// record fields. [] -type FreeTyvars = +type FreeTyvars = { - /// The summary of locally defined type definitions used in the expression. These may be made private by a signature - /// and we have to check various conditions associated with that. + /// The summary of locally defined type definitions used in the expression. These may be made private by a signature + /// and we have to check various conditions associated with that. FreeTycons: FreeTycons /// The summary of values used as trait solutions FreeTraitSolutions: FreeLocals - - /// The summary of type parameters used in the expression. These may not escape the enclosing generic construct - /// and we have to check various conditions associated with that. + + /// The summary of type parameters used in the expression. These may not escape the enclosing generic construct + /// and we have to check various conditions associated with that. FreeTypars: FreeTypars } @@ -6162,36 +6168,36 @@ type FreeVarsCache = FreeVars cache /// Represents the set of free variables in an expression [] -type FreeVars = +type FreeVars = { - /// The summary of locally defined variables used in the expression. These may be hidden at let bindings etc. - /// or made private by a signature or marked 'internal' or 'private', and we have to check various conditions associated with that. + /// The summary of locally defined variables used in the expression. These may be hidden at let bindings etc. + /// or made private by a signature or marked 'internal' or 'private', and we have to check various conditions associated with that. FreeLocals: FreeLocals - - /// Indicates if the expression contains a call to a protected member or a base call. - /// Calls to protected members and direct calls to super classes can't escape, also code can't be inlined - UsesMethodLocalConstructs: bool - /// Indicates if the expression contains a call to rethrow that is not bound under a (try-)with branch. - /// Rethrow may only occur in such locations. - UsesUnboundRethrow: bool + /// Indicates if the expression contains a call to a protected member or a base call. + /// Calls to protected members and direct calls to super classes can't escape, also code can't be inlined + UsesMethodLocalConstructs: bool + + /// Indicates if the expression contains a call to rethrow that is not bound under a (try-)with branch. + /// Rethrow may only occur in such locations. + UsesUnboundRethrow: bool /// Indicates if the expression contains a direct IL field load/store — a cheap over-approximate /// gate the optimizer refines to protected (family) fields (issue #19963). Never read by escape checks. - ContainsILFieldAccess: bool + ContainsILFieldAccess: bool - /// The summary of locally defined tycon representations used in the expression. These may be made private by a signature - /// or marked 'internal' or 'private' and we have to check various conditions associated with that. - FreeLocalTyconReprs: FreeTycons + /// The summary of locally defined tycon representations used in the expression. These may be made private by a signature + /// or marked 'internal' or 'private' and we have to check various conditions associated with that. + FreeLocalTyconReprs: FreeTycons - /// The summary of fields used in the expression. These may be made private by a signature - /// or marked 'internal' or 'private' and we have to check various conditions associated with that. + /// The summary of fields used in the expression. These may be made private by a signature + /// or marked 'internal' or 'private' and we have to check various conditions associated with that. FreeRecdFields: FreeRecdFields - + /// The summary of union constructors used in the expression. These may be /// marked 'internal' or 'private' and we have to check various conditions associated with that. FreeUnionCases: FreeUnionCases - + /// See FreeTyvars above. FreeTyvars: FreeTyvars } @@ -6201,27 +6207,27 @@ type FreeVars = override x.ToString() = "FreeVars(...)" /// A set of static methods for constructing types. -type Construct() = +type Construct() = + + static let taccessPublic = TAccess [] - static let taccessPublic = TAccess [] - /// Key a Tycon or TyconRef by decoded name - static member KeyTyconByDecodedName<'T> (nm: string) (x: 'T) : KeyValuePair = + static member KeyTyconByDecodedName<'T> (nm: string) (x: 'T) : KeyValuePair = KeyValuePair(DecodeGenericTypeName nm, x) /// Key a Tycon or TyconRef by both mangled and demangled name. /// Generic types can be accessed either by 'List' or 'List`1'. /// This lists both keys. - static member KeyTyconByAccessNames<'T> (nm: string) (x: 'T) : KeyValuePair[] = + static member KeyTyconByAccessNames<'T> (nm: string) (x: 'T) : KeyValuePair[] = match TryDemangleGenericNameAndPos nm with | ValueSome pos -> - let dnm = DemangleGenericTypeNameWithPos pos nm + let dnm = DemangleGenericTypeNameWithPos pos nm [| KeyValuePair(nm, x); KeyValuePair(dnm, x) |] | _ -> [| KeyValuePair(nm, x) |] /// Create a new node for the contents of a module or namespace - static member NewModuleOrNamespaceType mkind tycons vals = + static member NewModuleOrNamespaceType mkind tycons vals = ModuleOrNamespaceType(mkind, QueueList.ofList vals, QueueList.ofList tycons) /// Create a new node for an empty module or namespace contents @@ -6231,37 +6237,37 @@ type Construct() = static member NewEmptyFSharpTyconData kind = { fsobjmodel_cases = Construct.MakeUnionCases [] - fsobjmodel_kind = kind + fsobjmodel_kind = kind fsobjmodel_vslots = [] fsobjmodel_rfields = Construct.MakeRecdFieldsTable [] } #if !NO_TYPEPROVIDERS /// Create a new node for the representation information for a provided type definition - static member NewProvidedTyconRepr(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m) = + static member NewProvidedTyconRepr(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m) = let isErased = st.PUntaint((fun st -> st.IsErased), m) - let lazyBaseTy = - LazyWithContext.Create - ((fun (m, objTy) -> + let lazyBaseTy = + LazyWithContext.Create + ((fun (m, objTy) -> let baseSystemTy = st.PApplyOption((fun st -> match st.BaseType with null -> None | ty -> Some ty), m) - match baseSystemTy with - | None -> objTy + match baseSystemTy with + | None -> objTy | Some t -> importProvidedType t), findOriginalException) - TProvidedTypeRepr + TProvidedTypeRepr { ResolutionEnvironment=resolutionEnvironment ProvidedType=st LazyBaseType=lazyBaseTy UnderlyingTypeOfEnum = (fun () -> importProvidedType (st.PApply((fun st -> st.GetEnumUnderlyingType()), m))) - IsDelegate = (fun () -> st.PUntaint((fun st -> - let baseType = st.BaseType - match baseType with + IsDelegate = (fun () -> st.PUntaint((fun st -> + let baseType = st.BaseType + match baseType with | Null -> false - | NonNull x -> - match x with + | NonNull x -> + match x with | x when x.IsGenericType -> false | x when x.DeclaringType <> null -> false | x -> x.FullName = "System.Delegate" || x.FullName = "System.MulticastDelegate"), m)) @@ -6275,25 +6281,25 @@ type Construct() = IsSuppressRelocate = isSuppressRelocate } /// Create a new entity node for a provided type definition - static member NewProvidedTycon(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m, ?access, ?cpath) = - let stamp = newStamp() + static member NewProvidedTycon(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m, ?access, ?cpath) = + let stamp = newStamp() let name = st.PUntaint((fun st -> st.Name), m) let id = ident (name, m) - let kind = - let isMeasure = + let kind = + let isMeasure = st.PApplyWithProvider((fun (st, provider) -> ignore provider st.IsMeasure), m) .PUntaintNoFailure(Operators.id) if isMeasure then TyparKind.Measure else TyparKind.Type - let access = - match access with - | Some a -> a + let access = + match access with + | Some a -> a | None -> TAccess [] - let cpath = - match cpath with - | None -> + let cpath = + match cpath with + | None -> let ilScopeRef = st.TypeProviderAssemblyRef let enclosingName = GetFSharpPathToProvidedType(st, m) CompPath(ilScopeRef, SyntaxAccess.Unknown, enclosingName |> List.map(fun id->id, ModuleOrNamespaceKind.Namespace true)) @@ -6321,13 +6327,13 @@ type Construct() = | TyparKind.Type, TAccess [] -> None | _ -> Some { Entity.NewEmptyEntityOptData() with entity_kind = kind - entity_accessibility = access } } + entity_accessibility = access } } #endif /// Create a new entity node for a module or namespace - static member NewModuleOrNamespace cpath access (id: Ident) (xml: XmlDoc) attribs mtype = - let stamp = newStamp() - // Put the module suffix on if needed + static member NewModuleOrNamespace cpath access (id: Ident) (xml: XmlDoc) attribs mtype = + let stamp = newStamp() + // Put the module suffix on if needed Tycon.New "mspec" { entity_logical_name=id.idText entity_range = id.idRange @@ -6347,20 +6353,20 @@ type Construct() = | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = xml entity_tycon_repr_accessibility = access - entity_accessibility = access } } + entity_accessibility = access } } /// Create a new unfilled cache for free variable calculations static member NewFreeVarsCache() = newCache () /// Create the field tables for a record or class type - static member MakeRecdFieldsTable ucs: TyconRecdFields = - { FieldsByIndex = Array.ofList ucs + static member MakeRecdFieldsTable ucs: TyconRecdFields = + { FieldsByIndex = Array.ofList ucs FieldsByName = ucs |> NameMap.ofKeyedList (fun rfld -> rfld.LogicalName) } /// Create the union case tables for a union type - static member MakeUnionCases ucs: TyconUnionData = - { CasesTable = - { CasesByIndex = Array.ofList ucs + static member MakeUnionCases ucs: TyconUnionData = + { CasesTable = + { CasesByIndex = Array.ofList ucs CasesByName = NameMap.ofKeyedList (fun uc -> uc.LogicalName) ucs } CompiledRepresentation=newCache() } @@ -6376,11 +6382,11 @@ type Construct() = TFSharpTyconRepr repr /// Create a new type parameter node - static member NewTypar (kind, rigid, SynTypar(id, staticReq, isCompGen), isFromError, dynamicReq, attribs, eqDep, compDep) = + static member NewTypar (kind, rigid, SynTypar(id, staticReq, isCompGen), isFromError, dynamicReq, attribs, eqDep, compDep) = Typar.New - { typar_id = id - typar_stamp = newStamp() - typar_flags= TyparFlags(kind, rigid, isFromError, isCompGen, staticReq, dynamicReq, eqDep, compDep, false) + { typar_id = id + typar_stamp = newStamp() + typar_flags= TyparFlags(kind, rigid, isFromError, isCompGen, staticReq, dynamicReq, eqDep, compDep, false) typar_solution = None typar_astype = Unchecked.defaultof<_> typar_opt_data = @@ -6393,7 +6399,7 @@ type Construct() = Construct.NewTypar (TyparKind.Type, TyparRigidity.Rigid, SynTypar(mkSynId m nm, TyparStaticReq.None, true), false, TyparDynamicReq.Yes, [], false, false) /// Create a new union case node - static member NewUnionCase id tys retTy attribs docOption access: UnionCase = + static member NewUnionCase id tys retTy attribs docOption access: UnionCase = { Id = id OwnXmlDoc = docOption OtherXmlDoc = XmlDoc.Empty @@ -6401,11 +6407,11 @@ type Construct() = Accessibility = access FieldTable = Construct.MakeRecdFieldsTable tys ReturnType = retTy - Attribs = attribs - OtherRangeOpt = None } + Attribs = attribs + OtherRangeOpt = None } /// Create a new TAST Entity node for an F# exception definition - static member NewExn cpath (id: Ident) access repr attribs (doc: XmlDoc) = + static member NewExn cpath (id: Ident) access repr attribs (doc: XmlDoc) = Tycon.New "exnc" { entity_stamp = newStamp() entity_attribs = WellKnownEntityAttribs.Create(attribs) @@ -6422,7 +6428,7 @@ type Construct() = entity_opt_data = match doc, access, repr with | doc, TAccess [], TExnNone when doc.IsEmpty -> None - | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = doc; entity_accessibility = access; entity_tycon_repr_accessibility = access; entity_exn_info = repr } } + | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = doc; entity_accessibility = access; entity_tycon_repr_accessibility = access; entity_exn_info = repr } } /// Create a new TAST RecdField node for an F# class, struct or record field static member NewRecdField stat konst id nameGenerated ty isMutable isVolatile pattribs fattribs docOption access secret = @@ -6441,10 +6447,10 @@ type Construct() = rfield_id = id rfield_name_generated = nameGenerated rfield_other_range = None } - + /// Create a new type definition node static member NewTycon (cpath, nm, m, access, reprAccess, kind, typars, doc: XmlDoc, usesPrefixDisplay, preEstablishedHasDefaultCtor, hasSelfReferentialCtor, mtyp) = - let stamp = newStamp() + let stamp = newStamp() Tycon.New "tycon" { entity_stamp=stamp entity_logical_name=nm @@ -6461,7 +6467,7 @@ type Construct() = entity_opt_data = match kind, doc, reprAccess, access with | TyparKind.Type, doc, TAccess [], TAccess [] when doc.IsEmpty -> None - | _ -> Some { Entity.NewEmptyEntityOptData() with entity_kind = kind; entity_xmldoc = doc; entity_tycon_repr_accessibility = reprAccess; entity_accessibility=access } } + | _ -> Some { Entity.NewEmptyEntityOptData() with entity_kind = kind; entity_xmldoc = doc; entity_tycon_repr_accessibility = reprAccess; entity_accessibility=access } } /// Create a new type definition node for a .NET type definition static member NewILTycon nlpath (nm, m) tps (scoref: ILScopeRef, enc, tdef: ILTypeDef) mtyp = @@ -6497,10 +6503,10 @@ type Construct() = actualParent) : Val = let stamp = newStamp() - let optData = + let optData = match compiledName, arity, konst, access, doc, specialRepr, actualParent, attribs with | None, None, None, TAccess [], doc, None, ParentNone, [] when doc.IsEmpty -> None - | _ -> + | _ -> { Val.NewEmptyValOptData() with val_compiled_name = (match compiledName with Some v when v <> logicalName -> compiledName | _ -> None) val_repr_info = arity @@ -6527,26 +6533,28 @@ type Construct() = static member NewCcuContents sref m nm mty = Construct.NewModuleOrNamespace (Some(CompPath(sref, SyntaxAccess.Unknown, []))) taccessPublic (ident(nm, m)) XmlDoc.Empty [] (MaybeLazy.Strict mty) - /// Create a tycon based on an existing one using the function 'f'. - /// We require that we be given the new parent for the new tycon. - /// We pass the new tycon to 'f' in case it needs to reparent the - /// contents of the tycon. - static member NewModifiedTycon f (orig: Tycon) = + /// Create a tycon based on an existing one using the function 'f'. + /// We require that we be given the new parent for the new tycon. + /// We pass the new tycon to 'f' in case it needs to reparent the + /// contents of the tycon. + static member NewModifiedTycon f (orig: Tycon) = let data = { orig with entity_stamp = newStamp() } - Tycon.New "NewModifiedTycon" (f data) - - /// Create a module Tycon based on an existing one using the function 'f'. - /// We require that we be given the parent for the new module. - /// We pass the new module to 'f' in case it needs to reparent the - /// contents of the module. - static member NewModifiedModuleOrNamespace f orig = - orig |> Construct.NewModifiedTycon (fun d -> - { d with entity_modul_type = MaybeLazy.Strict (f (d.entity_modul_type.Force())) }) - - /// Create a Val based on an existing one using the function 'f'. - /// We require that we be given the parent for the new Val. - static member NewModifiedVal f (orig: Val) = - let stamp = newStamp() + Tycon.New "NewModifiedTycon" (f data) + + /// Create a module Tycon based on an existing one using the function 'f'. + /// We require that we be given the parent for the new module. + /// We pass the new module to 'f' in case it needs to reparent the + /// contents of the module. + static member NewModifiedModuleOrNamespace f orig = + orig |> Construct.NewModifiedTycon (fun d -> + match d.entity_modul_type with + | null -> d + | entity_modul_type -> { d with entity_modul_type = MaybeLazy.Strict (f (entity_modul_type.Force())) }) + + /// Create a Val based on an existing one using the function 'f'. + /// We require that we be given the parent for the new Val. + static member NewModifiedVal f (orig: Val) = + let stamp = newStamp() let data' = f { orig with val_stamp=stamp } Val.New data' @@ -6564,9 +6572,9 @@ type Construct() = let attrs = p.PUntaintNoFailure(fun x -> x.GetDefinitionLocationAttribute(p.TypeProvider.PUntaintNoFailure id)) match attrs with | None | Some (Null, _, _) -> None - | Some (NonNull filePath, line, column) -> + | Some (NonNull filePath, line, column) -> // Coordinates from type provider are 1-based for lines and columns // Coordinates internally in the F# compiler are 1-based for lines and 0-based for columns - let pos = Position.mkPos line (max 0 (column - 1)) + let pos = Position.mkPos line (max 0 (column - 1)) mkRange !!filePath pos pos |> Some #endif diff --git a/src/Compiler/TypedTree/TypedTree.fsi b/src/Compiler/TypedTree/TypedTree.fsi index 988f462b0f8..d05ba2f905f 100644 --- a/src/Compiler/TypedTree/TypedTree.fsi +++ b/src/Compiler/TypedTree/TypedTree.fsi @@ -444,10 +444,10 @@ type Entity = mutable entity_tycon_repr: TyconRepresentation /// The methods type properties of the type - mutable entity_tycon_tcaug: TyconAugmentation + mutable entity_tycon_tcaug: TyconAugmentation | null /// This field is used when the 'tycon' is really a module definition. It holds statically nested type definitions type nested modules - mutable entity_modul_type: MaybeLazy + mutable entity_modul_type: MaybeLazy | null /// The stable path to the type, e.g. Microsoft.FSharp.Core.FSharpFunc`2 mutable entity_pubpath: PublicPath option diff --git a/src/Compiler/TypedTree/TypedTreeOps.Remapping.fs b/src/Compiler/TypedTree/TypedTreeOps.Remapping.fs index 516c1010bec..58e3f5b950e 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.Remapping.fs +++ b/src/Compiler/TypedTree/TypedTreeOps.Remapping.fs @@ -2172,21 +2172,24 @@ module internal ExprRemapping = | TAsmRepr _ -> repr | TMeasureableRepr x -> TMeasureableRepr(remapType tmenv x) - and remapTyconAug tmenv (x: TyconAugmentation) = - { x with - tcaug_equals = x.tcaug_equals |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) - tcaug_compare = x.tcaug_compare |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) - tcaug_compare_withc = x.tcaug_compare_withc |> Option.map (remapValRef tmenv) - tcaug_hash_and_equals_withc = - x.tcaug_hash_and_equals_withc - |> Option.map (mapQuadruple (remapValRef tmenv, remapValRef tmenv, remapValRef tmenv, Option.map (remapValRef tmenv))) - tcaug_adhoc = x.tcaug_adhoc |> NameMap.map (List.map (remapValRef tmenv)) - tcaug_adhoc_list = - x.tcaug_adhoc_list - |> ResizeArray.map (fun (flag, vref) -> (flag, remapValRef tmenv vref)) - tcaug_super = x.tcaug_super |> Option.map (remapType tmenv) - tcaug_interfaces = x.tcaug_interfaces |> List.map (map1Of3 (remapType tmenv)) - } + and remapTyconAug tmenv (x: TyconAugmentation | null) = + match x with + | null -> null + | x -> + { x with + tcaug_equals = x.tcaug_equals |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) + tcaug_compare = x.tcaug_compare |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) + tcaug_compare_withc = x.tcaug_compare_withc |> Option.map (remapValRef tmenv) + tcaug_hash_and_equals_withc = + x.tcaug_hash_and_equals_withc + |> Option.map (mapQuadruple (remapValRef tmenv, remapValRef tmenv, remapValRef tmenv, Option.map (remapValRef tmenv))) + tcaug_adhoc = x.tcaug_adhoc |> NameMap.map (List.map (remapValRef tmenv)) + tcaug_adhoc_list = + x.tcaug_adhoc_list + |> ResizeArray.map (fun (flag, vref) -> (flag, remapValRef tmenv vref)) + tcaug_super = x.tcaug_super |> Option.map (remapType tmenv) + tcaug_interfaces = x.tcaug_interfaces |> List.map (map1Of3 (remapType tmenv)) + } and remapTyconExnInfo ctxt tmenv inp = match inp with @@ -2291,7 +2294,10 @@ module internal ExprRemapping = tcdR.entity_tycon_repr <- tcd.entity_tycon_repr |> remapTyconRepr ctxt tmenvinner2 let typeAbbrevR = tcd.TypeAbbrev |> Option.map (remapType tmenvinner2) tcdR.entity_tycon_tcaug <- tcd.entity_tycon_tcaug |> remapTyconAug tmenvinner2 - tcdR.entity_modul_type <- MaybeLazy.Strict(tcd.entity_modul_type.Value |> mapImmediateValsAndTycons lookupTycon lookupVal) + tcdR.entity_modul_type <- + match tcd.entity_modul_type with + | null -> null + | ty -> MaybeLazy.Strict(ty.Force() |> mapImmediateValsAndTycons lookupTycon lookupVal) let exnInfoR = tcd.ExceptionInfo |> remapTyconExnInfo ctxt tmenvinner2 match tcdR.entity_opt_data with diff --git a/src/Compiler/TypedTree/TypedTreeOps.Remapping.fsi b/src/Compiler/TypedTree/TypedTreeOps.Remapping.fsi index 5372d2a2511..1e4da87eedc 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.Remapping.fsi +++ b/src/Compiler/TypedTree/TypedTreeOps.Remapping.fsi @@ -253,7 +253,7 @@ module internal ExprRemapping = val remapTyconRepr: RemapContext -> Remap -> TyconRepresentation -> TyconRepresentation - val remapTyconAug: Remap -> TyconAugmentation -> TyconAugmentation + val remapTyconAug: Remap -> TyconAugmentation | null -> TyconAugmentation | null val remapTyconExnInfo: RemapContext -> Remap -> ExceptionInfo -> ExceptionInfo diff --git a/src/Compiler/TypedTree/TypedTreeOps.Transforms.fs b/src/Compiler/TypedTree/TypedTreeOps.Transforms.fs index 55e8e71b3f2..9598f5beacd 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.Transforms.fs +++ b/src/Compiler/TypedTree/TypedTreeOps.Transforms.fs @@ -988,7 +988,7 @@ module internal Rewriting = let modulContentsR = MaybeLazy.Strict( - d.entity_modul_type.Value + d.ModuleOrNamespaceType |> mapImmediateValsAndTycons (remapTyconToNonLocal ctxt tmenv) (remapValToNonLocal ctxt tmenv) ) diff --git a/src/Compiler/TypedTree/TypedTreePickle.fs b/src/Compiler/TypedTree/TypedTreePickle.fs index 9adfca4e3a8..661e9e836e8 100644 --- a/src/Compiler/TypedTree/TypedTreePickle.fs +++ b/src/Compiler/TypedTree/TypedTreePickle.fs @@ -718,8 +718,6 @@ let private p_lazy_impl p v st = let p_lazy p x st = p_lazy_impl p (InterruptibleLazy.force x) st -let p_maybe_lazy p (x: MaybeLazy<_>) st = p_lazy_impl p x.Value st - let p_hole () = let mutable h = None @@ -2689,7 +2687,7 @@ let rec p_tycon_repr x st = let allFieldsText = fields - |> Array.map (fun f -> f.LogicalName) + |> Seq.map _.LogicalName |> String.concat System.Environment.NewLine raise (Error(FSComp.SR.pickleFsharpCoreBackwardsCompatible ("fields in union", allFieldsText), firstFieldRange)) @@ -2802,7 +2800,7 @@ and p_entity_spec_data (x: Entity) st = p_attribs (x.entity_attribs.AsList()) st let flagBit = p_tycon_repr x.entity_tycon_repr st p_option p_ty x.TypeAbbrev st - p_tcaug x.entity_tycon_tcaug st + p_tcaug x.TypeContents st p_string System.String.Empty st p_kind x.TypeOrMeasureKind st @@ -2815,7 +2813,7 @@ and p_entity_spec_data (x: Entity) st = st p_option p_cpath x.entity_cpath st - p_maybe_lazy p_modul_typ x.entity_modul_type st + p_lazy_impl p_modul_typ x.ModuleOrNamespaceType st p_exnc_repr x.ExceptionInfo st if st.oInMem then @@ -2823,7 +2821,7 @@ and p_entity_spec_data (x: Entity) st = else p_space 1 () st -and p_tcaug p st = +and p_tcaug (p : TyconAugmentation) st = p_tup9 (p_option (p_tup2 (p_vref "compare_obj") (p_vref "compare"))) (p_option (p_vref "compare_withc")) @@ -2840,13 +2838,13 @@ and p_tcaug p st = |> Option.map (fun (v1, v2, v3, _) -> (v1, v2, v3)), p.tcaug_equals, (p.tcaug_adhoc_list - |> ResizeArray.toList // Explicit impls of interfaces only get kept in the adhoc list // in order to get check the well-formedness of an interface. // Keeping them across assembly boundaries is not valid, because relinking their ValRefs // does not work correctly (they may get incorrectly relinked to a default member) - |> List.filter (fun (isExplicitImpl, _) -> not isExplicitImpl) - |> List.map (fun (_, vref) -> vref.LogicalName, vref)), + |> Seq.filter (fun (isExplicitImpl, _) -> not isExplicitImpl) + |> Seq.map (fun (_, vref) -> vref.LogicalName, vref) + |> Seq.toList), p.tcaug_interfaces, p.tcaug_super, p.tcaug_abstract, diff --git a/src/Compiler/Utilities/lib.fs b/src/Compiler/Utilities/lib.fs index a1395e5589e..7a53f1993e7 100755 --- a/src/Compiler/Utilities/lib.fs +++ b/src/Compiler/Utilities/lib.fs @@ -419,7 +419,7 @@ type DisposablesTracker() = let items = Stack() /// Register some items to dispose - member _.Register (i:#IDisposable | null) = + member _.Register (i:#IDisposable | null) = match box i with | null -> () | _ -> items.Push (!!i) @@ -498,6 +498,10 @@ module WeakMap = | true, value -> value | false, _ -> let value = valueFactory key - if shouldCache value then + if shouldCache value then +#if NETSTANDARD2_0 try table.Add(key, value) with _ -> () +#else + table.TryAdd(key, value) |> ignore +#endif value diff --git a/vsintegration/src/FSharp.Editor/Common/Extensions.fs b/vsintegration/src/FSharp.Editor/Common/Extensions.fs index 82d161a7e64..75e26983f9e 100644 --- a/vsintegration/src/FSharp.Editor/Common/Extensions.fs +++ b/vsintegration/src/FSharp.Editor/Common/Extensions.fs @@ -71,14 +71,14 @@ type Project with type TextViewEventsHandler ( - onChangeCaretHandler: (IVsTextView * int * int -> unit) option, - onKillFocus: (IVsTextView -> unit) option, - onSetFocus: (IVsTextView -> unit) option + onChangeCaretHandler: (IVsTextView * int * int -> unit) voption, + onKillFocus: (IVsTextView -> unit) voption, + onSetFocus: (IVsTextView -> unit) voption ) = interface IVsTextViewEvents with member this.OnChangeCaretLine(view: IVsTextView, newline: int, oldline: int) = onChangeCaretHandler - |> Option.iter (fun handler -> handler (view, newline, oldline)) + |> ValueOption.iter (fun handler -> handler (view, newline, oldline)) member this.OnChangeScrollInfo (_view: IVsTextView, _iBar: int, _iMinUnit: int, _iMaxUnits: int, _iVisibleUnits: int, _iFirstVisibleUnit: int) @@ -86,14 +86,14 @@ type TextViewEventsHandler () member this.OnKillFocus(view: IVsTextView) = - onKillFocus |> Option.iter (fun handler -> handler (view)) + onKillFocus |> ValueOption.iter (fun handler -> handler (view)) member this.OnSetBuffer(_view: IVsTextView, _buffer: IVsTextLines) = () member this.OnSetFocus(view: IVsTextView) = - onSetFocus |> Option.iter (fun handler -> handler (view)) + onSetFocus |> ValueOption.iter (fun handler -> handler (view)) -type ConnectionPointSubscription = System.IDisposable option +type ConnectionPointSubscription = System.IDisposable voption // Usage example: // If a handler is None, to not handle that event @@ -108,16 +108,16 @@ let subscribeToTextViewEvents (textView: IVsTextView, onChangeCaretHandler, onKi let mutable cookie = 0u match cpContainer.FindConnectionPoint(ref riid) with - | null -> None + | null -> ValueNone | cp -> - Some( + ValueSome( cp.Advise(handler, &cookie) { new IDisposable with member _.Dispose() = cp.Unadvise(cookie) } ) - | _ -> None + | _ -> ValueNone type Document with @@ -129,7 +129,7 @@ type Document with | null -> None | languageServices -> languageServices.GetService<'T>() |> Some - member this.TryGetIVsTextView() : IVsTextView option = + member this.TryGetIVsTextView() : IVsTextView voption = match ServiceProvider.GlobalProvider.GetService(typeof) with | :? IVsTextManager as textManager -> // Grab IVsRunningDocumentTable @@ -140,20 +140,20 @@ type Document with match Marshal.GetObjectForIUnknown docData with | :? IVsTextBuffer as ivsTextBuffer -> match textManager.GetActiveView(0, ivsTextBuffer) with - | hr, vsTextView when ErrorHandler.Succeeded(hr) -> Some vsTextView - | _ -> None - | _ -> None - | _ -> None - | _ -> None - | _ -> None - - member this.TryGetTextViewAndCaretPos() : (IVsTextView * Position) option = + | hr, vsTextView when ErrorHandler.Succeeded(hr) -> ValueSome vsTextView + | _ -> ValueNone + | _ -> ValueNone + | _ -> ValueNone + | _ -> ValueNone + | _ -> ValueNone + + member this.TryGetTextViewAndCaretPos() : (IVsTextView * Position) voption = match this.TryGetIVsTextView() with - | Some textView -> + | ValueSome textView -> match textView.GetCaretPos() with - | hr, line, column when ErrorHandler.Succeeded(hr) -> Some(textView, Position.fromZ line column) - | _ -> None - | None -> None + | hr, line, column when ErrorHandler.Succeeded(hr) -> ValueSome(textView, Position.fromZ line column) + | _ -> ValueNone + | ValueNone -> ValueNone member this.IsFSharpScript = isScriptFile this.FilePath diff --git a/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs b/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs index 08bfbbddaa8..fd821f7c361 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs @@ -200,7 +200,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = cancellableTask { let! ct = CancellableTask.getCancellationToken () let! fileStamp = document.GetTextVersionAsync(ct) - let textViewAndCaret () : (IVsTextView * Position) option = document.TryGetTextViewAndCaretPos() + let textViewAndCaret () : (IVsTextView * Position) voption = document.TryGetTextViewAndCaretPos() match singleFileCache.TryGetValue(document.Id) with | false, _ -> @@ -210,7 +210,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = let caret = textViewAndCaret () match caret with - | None -> + | ValueNone -> checker.GetProjectOptionsFromScript( document.FilePath, sourceText.ToFSharpSourceText(), @@ -219,7 +219,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = userOpName = userOpName ) - | Some(_, caret) -> + | ValueSome(_, caret) -> checker.GetProjectOptionsFromScript( document.FilePath, sourceText.ToFSharpSourceText(), @@ -234,14 +234,12 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = let otherOptions = if project.IsFSharpMetadata then - project.ProjectReferences - |> Seq.map (fun x -> "-r:" + project.Solution.GetProject(x.ProjectId).OutputFilePath) - |> Array.ofSeq - |> Array.append ( - project.MetadataReferences.OfType() - |> Seq.map (fun x -> "-r:" + x.FilePath) - |> Array.ofSeq - ) + [| + for x in project.ProjectReferences do + yield "-r:" + project.Solution.GetProject(x.ProjectId).OutputFilePath + for x in project.MetadataReferences.OfType() do + yield "-r:" + x.FilePath + |] else [||] @@ -284,9 +282,14 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = | projectId, fileStamp, parsingOptions, projectOptions, _ -> let subscription = match textViewAndCaret () with - | Some(textView, _) -> - subscribeToTextViewEvents (textView, (Some onChangeCaretHandler), (Some onKillFocus), (Some onSetFocus)) - | None -> None + | ValueSome(textView, _) -> + subscribeToTextViewEvents ( + textView, + (ValueSome onChangeCaretHandler), + (ValueSome onKillFocus), + (ValueSome onSetFocus) + ) + | ValueNone -> ValueNone (projectId, fileStamp, parsingOptions, projectOptions, subscription) @@ -294,7 +297,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = document.Id, // The key to the cache (fun _ value -> addToCacheAndSubscribe value), // Function to add the cached value if the key does not exist (fun _ _ value -> value), // Function to update the value if the key exists - (document.Project, fileStamp, parsingOptions, projectOptions, None) // The value to add or update + (document.Project, fileStamp, parsingOptions, projectOptions, ValueNone) // The value to add or update ) |> ignore @@ -303,7 +306,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = | true, (oldProject, oldFileStamp, parsingOptions, projectOptions, _) -> if fileStamp <> oldFileStamp || isProjectInvalidated document.Project oldProject ct then match singleFileCache.TryRemove(document.Id) with - | true, (_, _, _, _, Some subscription) -> subscription.Dispose() + | true, (_, _, _, _, ValueSome subscription) -> subscription.Dispose() | _ -> () return! tryComputeOptionsBySingleScriptOrFile document userOpName @@ -519,7 +522,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = | true, (_, _, _, projectOptions, subscription) -> lastSuccessfulCompilations.TryRemove(documentId.ProjectId) |> ignore checker.ClearCache([ projectOptions ]) - subscription |> Option.iter (fun handler -> handler.Dispose()) + subscription |> ValueOption.iter (fun handler -> handler.Dispose()) | _ -> () }