diff --git a/src/absil/il.fs b/src/absil/il.fs index 2b172b3a126..5d07cb5b5cf 100644 --- a/src/absil/il.fs +++ b/src/absil/il.fs @@ -1233,14 +1233,14 @@ type | DemandChoice [] -type ILPermission = - | PermissionSet of ILSecurityAction * byte[] +type ILSecurityDecl = + | ILSecurityDecl of ILSecurityAction * byte[] [] -type ILPermissions = - | SecurityDecls of ILPermission list - | SecurityDeclsLazy of Lazy - member x.AsList = match x with SecurityDecls m -> m | SecurityDeclsLazy m -> m.Force() +type ILSecurityDecls = + | ILSecurityDecls of ILSecurityDecl list + | ILSecurityDeclsLazy of Lazy + member x.AsList = match x with ILSecurityDecls m -> m | ILSecurityDeclsLazy m -> m.Force() [] type PInvokeCharBestFit = @@ -1347,13 +1347,13 @@ type ILGenericVariance = | ContraVariant type ILGenericParameterDef = - { Name: string; - Constraints: ILTypes; - Variance: ILGenericVariance; - HasReferenceTypeConstraint: bool; - CustomAttrs : ILAttributes; - HasNotNullableValueTypeConstraint: bool; - HasDefaultConstructorConstraint: bool; } + { Name: string + Constraints: ILTypes + Variance: ILGenericVariance + HasReferenceTypeConstraint: bool + CustomAttrs : ILAttributes + HasNotNullableValueTypeConstraint: bool + HasDefaultConstructorConstraint: bool } override x.ToString() = x.Name @@ -1381,28 +1381,45 @@ let convertMemberAccess (ilMemberAccess:ILMemberAccess) = let inline conditionalAdd condition flagToAdd source = if condition then source ||| flagToAdd else source &&& ~~~flagToAdd [] -type ILMethodDef = - { Name: string; - Attributes: MethodAttributes; - ImplAttributes: MethodImplAttributes; - CallingConv: ILCallingConv; - Parameters: ILParameters; - Return: ILReturn; - mdBody: ILLazyMethodBody; - SecurityDecls: ILPermissions; - IsEntryPoint:bool; - GenericParams: ILGenericParameterDefs; - CustomAttrs: ILAttributes; } +type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: MethodImplAttributes, callingConv: ILCallingConv, parameters: ILParameters, ret: ILReturn, body: ILLazyMethodBody, securityDecls: ILSecurityDecls, isEntryPoint:bool, genericParams: ILGenericParameterDefs, customAttrs: ILAttributes) = + + member __.Name = name + member __.Attributes = attributes + member __.ImplAttributes = implAttributes + member __.CallingConv = callingConv + member __.Parameters = parameters + member __.Return = ret + member __.Body = body + member __.SecurityDecls = securityDecls + member __.IsEntryPoint = isEntryPoint + member __.GenericParams = genericParams + member __.CustomAttrs = customAttrs + + member x.With (?name: string, ?attributes: MethodAttributes, ?implAttributes: MethodImplAttributes, ?callingConv: ILCallingConv, ?parameters: ILParameters, ?ret: ILReturn, ?body: ILLazyMethodBody, ?securityDecls: ILSecurityDecls, ?isEntryPoint:bool, ?genericParams: ILGenericParameterDefs, ?customAttrs: ILAttributes) = + ILMethodDef (name = defaultArg name x.Name, + attributes = defaultArg attributes x.Attributes, + implAttributes = defaultArg implAttributes x.ImplAttributes, + callingConv = defaultArg callingConv x.CallingConv, + parameters = defaultArg parameters x.Parameters, + ret = defaultArg ret x.Return, + body = defaultArg body x.Body, + securityDecls = defaultArg securityDecls x.SecurityDecls, + isEntryPoint = defaultArg isEntryPoint x.IsEntryPoint, + genericParams = defaultArg genericParams x.GenericParams, + customAttrs = defaultArg customAttrs x.CustomAttrs) + member x.ParameterTypes = typesOfILParams x.Parameters - // Whidbey feature: SafeHandle finalizer must be run + member md.Code = - match md.mdBody.Contents with + match md.Body.Contents with | MethodBody.IL il-> Some il.Code | _ -> None - member x.IsIL = match x.mdBody.Contents with | MethodBody.IL _ -> true | _ -> false - member x.Locals = match x.mdBody.Contents with | MethodBody.IL il -> il.Locals | _ -> [] - member x.MethodBody = match x.mdBody.Contents with MethodBody.IL il -> il | _ -> failwith "not IL" + member x.IsIL = match x.Body.Contents with | MethodBody.IL _ -> true | _ -> false + + member x.Locals = match x.Body.Contents with | MethodBody.IL il -> il.Locals | _ -> [] + + member x.MethodBody = match x.Body.Contents with MethodBody.IL il -> il | _ -> failwith "not IL" member x.SourceMarker = x.MethodBody.SourceMarker member x.MaxStack = x.MethodBody.MaxStack @@ -1436,24 +1453,23 @@ type ILMethodDef = member x.IsAggressiveInline= x.ImplAttributes &&& MethodImplAttributes.AggressiveInlining <> enum 0 member x.IsMustRun = x.ImplAttributes &&& MethodImplAttributes.NoOptimization <> enum 0 - member x.WithSpecialName = { x with Attributes = x.Attributes ||| MethodAttributes.SpecialName } + member x.WithSpecialName = x.With(attributes = (x.Attributes ||| MethodAttributes.SpecialName)) member x.WithHideBySig() = - { x with - Attributes = + x.With(attributes = ( if x.IsVirtual then x.Attributes &&& ~~~MethodAttributes.CheckAccessOnOverride ||| MethodAttributes.HideBySig - else failwith "WithHideBySig" } - member x.WithHideBySig(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition MethodAttributes.HideBySig} - member x.WithFinal(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition MethodAttributes.Final} - member x.WithAbstract(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition MethodAttributes.Abstract} - member x.WithAccess(access) = { x with Attributes = x.Attributes &&& ~~~MethodAttributes.MemberAccessMask ||| convertMemberAccess access } - member x.WithNewSlot = { x with Attributes = x.Attributes ||| MethodAttributes.NewSlot } - member x.WithSecurity(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition MethodAttributes.HasSecurity} - member x.WithPInvoke(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition MethodAttributes.PinvokeImpl} - member x.WithPreserveSig(condition) = { x with ImplAttributes = x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.PreserveSig} - member x.WithSynchronized(condition) = { x with ImplAttributes = x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.Synchronized} - member x.WithNoInlining(condition) = { x with ImplAttributes = x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.NoInlining} - member x.WithAggressiveInlining(condition) = { x with ImplAttributes = x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.AggressiveInlining} - member x.WithRuntime(condition) = { x with ImplAttributes = x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.Runtime} + else failwith "WithHideBySig")) + member x.WithHideBySig(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition MethodAttributes.HideBySig)) + member x.WithFinal(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition MethodAttributes.Final)) + member x.WithAbstract(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition MethodAttributes.Abstract)) + member x.WithAccess(access) = x.With(attributes = (x.Attributes &&& ~~~MethodAttributes.MemberAccessMask ||| convertMemberAccess access)) + member x.WithNewSlot = x.With(attributes = (x.Attributes ||| MethodAttributes.NewSlot)) + member x.WithSecurity(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition MethodAttributes.HasSecurity)) + member x.WithPInvoke(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition MethodAttributes.PinvokeImpl)) + member x.WithPreserveSig(condition) = x.With(implAttributes = (x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.PreserveSig)) + member x.WithSynchronized(condition) = x.With(implAttributes = (x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.Synchronized)) + member x.WithNoInlining(condition) = x.With(implAttributes = (x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.NoInlining)) + member x.WithAggressiveInlining(condition) = x.With(implAttributes = (x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.AggressiveInlining)) + member x.WithRuntime(condition) = x.With(implAttributes = (x.ImplAttributes |> conditionalAdd condition MethodImplAttributes.Runtime)) /// Index table by name and arity. type MethodDefMap = Map @@ -1486,15 +1502,25 @@ type ILMethodDefs(f : (unit -> ILMethodDef[])) = member x.FindByNameAndArity (nm,arity) = x.FindByName nm |> List.filter (fun x -> List.length x.Parameters = arity) [] -type ILEventDef = - { Type: ILType option; - Name: string; - Attributes: EventAttributes - AddMethod: ILMethodRef; - RemoveMethod: ILMethodRef; - FireMethod: ILMethodRef option; - OtherMethods: ILMethodRef list; - CustomAttrs: ILAttributes; } +type ILEventDef(eventType: ILType option, name: string, attributes: EventAttributes, addMethod: ILMethodRef, removeMethod: ILMethodRef, fireMethod: ILMethodRef option, otherMethods: ILMethodRef list, customAttrs: ILAttributes) = + + member x.EventType = eventType + member x.Name = name + member x.Attributes = attributes + member x.AddMethod = addMethod + member x.RemoveMethod = removeMethod + member x.FireMethod = fireMethod + member x.OtherMethods = otherMethods + member x.CustomAttrs = customAttrs + member x.With(?eventType, ?name, ?attributes, ?addMethod, ?removeMethod, ?fireMethod, ?otherMethods, ?customAttrs) = + ILEventDef(eventType= defaultArg eventType x.EventType, + name= defaultArg name x.Name, + attributes= defaultArg attributes x.Attributes, + addMethod=defaultArg addMethod x.AddMethod, + removeMethod=defaultArg removeMethod x.RemoveMethod, + fireMethod= defaultArg fireMethod x.FireMethod, + otherMethods= defaultArg otherMethods x.OtherMethods, + customAttrs=defaultArg customAttrs x.CustomAttrs) member x.IsSpecialName = (x.Attributes &&& EventAttributes.SpecialName) <> enum<_>(0) member x.IsRTSpecialName = (x.Attributes &&& EventAttributes.RTSpecialName) <> enum<_>(0) override x.ToString() = "event " + x.Name @@ -1502,21 +1528,32 @@ type ILEventDef = (* Index table by name. *) [] type ILEventDefs = - | Events of LazyOrderedMultiMap - member x.AsList = let (Events t) = x in t.Entries() - member x.LookupByName s = let (Events t) = x in t.[s] + | ILEvents of LazyOrderedMultiMap + member x.AsList = let (ILEvents t) = x in t.Entries() + member x.LookupByName s = let (ILEvents t) = x in t.[s] [] -type ILPropertyDef = - { Name: string; - Attributes: PropertyAttributes; - SetMethod: ILMethodRef option; - GetMethod: ILMethodRef option; - CallingConv: ILThisConvention; - Type: ILType; - Init: ILFieldInit option; - Args: ILTypes; - CustomAttrs: ILAttributes; } +type ILPropertyDef(name: string, attributes: PropertyAttributes, setMethod: ILMethodRef option, getMethod: ILMethodRef option, callingConv: ILThisConvention, propertyType: ILType, init: ILFieldInit option, args: ILTypes, customAttrs: ILAttributes) = + member x.Name = name + member x.Attributes = attributes + member x.GetMethod = getMethod + member x.SetMethod = setMethod + member x.CallingConv = callingConv + member x.PropertyType = propertyType + member x.Init = init + member x.Args = args + member x.CustomAttrs = customAttrs + member x.With(?name, ?attributes, ?setMethod, ?getMethod, ?callingConv, ?propertyType, ?init, ?args, ?customAttrs) = + ILPropertyDef(name=defaultArg name x.Name, + attributes=defaultArg attributes x.Attributes, + setMethod=defaultArg setMethod x.SetMethod, + getMethod=defaultArg getMethod x.GetMethod, + callingConv=defaultArg callingConv x.CallingConv, + propertyType=defaultArg propertyType x.PropertyType, + init=defaultArg init x.Init, + args=defaultArg args x.Args, + customAttrs=defaultArg customAttrs x.CustomAttrs) + member x.IsSpecialName = (x.Attributes &&& PropertyAttributes.SpecialName) <> enum<_>(0) member x.IsRTSpecialName = (x.Attributes &&& PropertyAttributes.RTSpecialName) <> enum<_>(0) override x.ToString() = "property " + x.Name @@ -1524,9 +1561,9 @@ type ILPropertyDef = // Index table by name. [] type ILPropertyDefs = - | Properties of LazyOrderedMultiMap - member x.AsList = let (Properties t) = x in t.Entries() - member x.LookupByName s = let (Properties t) = x in t.[s] + | ILProperties of LazyOrderedMultiMap + member x.AsList = let (ILProperties t) = x in t.Entries() + member x.LookupByName s = let (ILProperties t) = x in t.[s] let convertFieldAccess (ilMemberAccess:ILMemberAccess) = match ilMemberAccess with @@ -1538,35 +1575,46 @@ let convertFieldAccess (ilMemberAccess:ILMemberAccess) = | ILMemberAccess.Public -> FieldAttributes.Public [] -type ILFieldDef = - { Name: string; - Type: ILType; - Attributes: FieldAttributes; - Data: byte[] option; - LiteralValue: ILFieldInit option; - Offset: int32 option; - Marshal: ILNativeType option; - CustomAttrs: ILAttributes; } +type ILFieldDef(name: string, fieldType: ILType, attributes: FieldAttributes, data: byte[] option, literalValue: ILFieldInit option, offset: int32 option, marshal: ILNativeType option, customAttrs: ILAttributes) = + + member __.Name=name + member __.FieldType = fieldType + member __.Attributes=attributes + member __.Data=data + member __.LiteralValue=literalValue + member __.Offset=offset + member __.Marshal=marshal + member __.CustomAttrs=customAttrs + + member x.With(?name: string, ?fieldType: ILType, ?attributes: FieldAttributes, ?data: byte[] option, ?literalValue: ILFieldInit option, ?offset: int32 option, ?marshal: ILNativeType option, ?customAttrs: ILAttributes) = + ILFieldDef(name=defaultArg name x.Name, + fieldType=defaultArg fieldType x.FieldType, + attributes=defaultArg attributes x.Attributes, + data=defaultArg data x.Data, + literalValue=defaultArg literalValue x.LiteralValue, + offset=defaultArg offset x.Offset, + marshal=defaultArg marshal x.Marshal, + customAttrs=defaultArg customAttrs x.CustomAttrs) member x.IsStatic = x.Attributes &&& FieldAttributes.Static <> enum 0 member x.IsSpecialName = x.Attributes &&& FieldAttributes.SpecialName <> enum 0 member x.IsLiteral = x.Attributes &&& FieldAttributes.Literal <> enum 0 member x.NotSerialized = x.Attributes &&& FieldAttributes.NotSerialized <> enum 0 member x.IsInitOnly = x.Attributes &&& FieldAttributes.InitOnly <> enum 0 member x.Access = memberAccessOfFlags (int x.Attributes) - member x.WithAccess(access) = { x with Attributes = x.Attributes &&& ~~~FieldAttributes.FieldAccessMask ||| convertFieldAccess access } - member x.WithInitOnly(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition FieldAttributes.InitOnly } - member x.WithStatic(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition FieldAttributes.Static } - member x.WithSpecialName(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition (FieldAttributes.SpecialName ||| FieldAttributes.RTSpecialName) } - member x.WithNotSerialized(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition FieldAttributes.NotSerialized } - member x.WithLiteralDefaultValue(literal) = { x with LiteralValue = literal; Attributes = x.Attributes |> conditionalAdd literal.IsSome (FieldAttributes.Literal ||| FieldAttributes.HasDefault) } - member x.WithFieldMarshal(marshal) = { x with Marshal = marshal; Attributes = x.Attributes |> conditionalAdd marshal.IsSome FieldAttributes.HasFieldMarshal } + member x.WithAccess(access) = x.With(attributes = (x.Attributes &&& ~~~FieldAttributes.FieldAccessMask ||| convertFieldAccess access)) + member x.WithInitOnly(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition FieldAttributes.InitOnly)) + member x.WithStatic(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition FieldAttributes.Static)) + member x.WithSpecialName(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition (FieldAttributes.SpecialName ||| FieldAttributes.RTSpecialName))) + member x.WithNotSerialized(condition) = x.With(attributes = (x.Attributes |> conditionalAdd condition FieldAttributes.NotSerialized)) + member x.WithLiteralDefaultValue(literal) = x.With(literalValue = literal, attributes = (x.Attributes |> conditionalAdd literal.IsSome (FieldAttributes.Literal ||| FieldAttributes.HasDefault))) + member x.WithFieldMarshal(marshal) = x.With(marshal = marshal, attributes = (x.Attributes |> conditionalAdd marshal.IsSome FieldAttributes.HasFieldMarshal)) // Index table by name. Keep a canonical list to make sure field order is not disturbed for binary manipulation. type ILFieldDefs = - | Fields of LazyOrderedMultiMap - member x.AsList = let (Fields t) = x in t.Entries() - member x.LookupByName s = let (Fields t) = x in t.[s] + | ILFields of LazyOrderedMultiMap + member x.AsList = let (ILFields t) = x in t.Entries() + member x.LookupByName s = let (ILFields t) = x in t.[s] type ILMethodImplDef = { Overrides: ILOverridesSpec; @@ -1574,8 +1622,8 @@ type ILMethodImplDef = // Index table by name and arity. type ILMethodImplDefs = - | MethodImpls of Lazy - member x.AsList = let (MethodImpls ltab) = x in Map.foldBack (fun _x y r -> y@r) (ltab.Force()) [] + | ILMethodImpls of Lazy + member x.AsList = let (ILMethodImpls ltab) = x in Map.foldBack (fun _x y r -> y@r) (ltab.Force()) [] and MethodImplsMap = Map @@ -1693,21 +1741,39 @@ let convertInitSemantics (init:ILTypeInit) = | ILTypeInit.OnAny -> enum 0 [] -type ILTypeDef = - { Name: string; - Attributes: TypeAttributes; - GenericParams: ILGenericParameterDefs; (* class is generic *) - Layout: ILTypeDefLayout; - NestedTypes: ILTypeDefs; - Implements: ILTypes; - Extends: ILType option; - Methods: ILMethodDefs; - SecurityDecls: ILPermissions; - Fields: ILFieldDefs; - MethodImpls: ILMethodImplDefs; - Events: ILEventDefs; - Properties: ILPropertyDefs; - CustomAttrs: ILAttributes; } +type ILTypeDef(name: string, attributes: TypeAttributes, layout: ILTypeDefLayout, implements: ILTypes, genericParams: ILGenericParameterDefs, + extends: ILType option, methods: ILMethodDefs, nestedTypes: ILTypeDefs, fields: ILFieldDefs, methodImpls: ILMethodImplDefs, + events: ILEventDefs, properties: ILPropertyDefs, customAttrs: ILAttributes, securityDecls: ILSecurityDecls) = + + member __.Name = name + member __.Attributes = attributes + member __.GenericParams = genericParams + member __.Layout = layout + member __.NestedTypes = nestedTypes + member __.Implements = implements + member __.Extends = extends + member __.Methods = methods + member __.SecurityDecls = securityDecls + member __.Fields = fields + member __.MethodImpls = methodImpls + member __.Events = events + member __.Properties = properties + member __.CustomAttrs = customAttrs + member x.With(?name, ?attributes, ?layout, ?implements, ?genericParams, ?extends, ?methods, ?nestedTypes, ?fields, ?methodImpls, ?events, ?properties, ?customAttrs, ?securityDecls) = + ILTypeDef(name=defaultArg name x.Name, + attributes=defaultArg attributes x.Attributes, + layout=defaultArg layout x.Layout, + genericParams = defaultArg genericParams x.GenericParams, + nestedTypes = defaultArg nestedTypes x.NestedTypes, + implements = defaultArg implements x.Implements, + extends = defaultArg extends x.Extends, + methods = defaultArg methods x.Methods, + securityDecls = defaultArg securityDecls x.SecurityDecls, + fields = defaultArg fields x.Fields, + methodImpls = defaultArg methodImpls x.MethodImpls, + events = defaultArg events x.Events, + properties = defaultArg properties x.Properties, + customAttrs = defaultArg customAttrs x.CustomAttrs) member x.IsClass = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Class member x.IsStruct = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.ValueType member x.IsInterface = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Interface @@ -1722,18 +1788,18 @@ type ILTypeDef = member x.HasSecurity = x.Attributes &&& TypeAttributes.HasSecurity <> enum 0 member x.Encoding = typeEncodingOfFlags (int x.Attributes) member x.IsStructOrEnum = x.IsStruct || x.IsEnum - member x.WithAccess(access) = { x with Attributes = x.Attributes &&& ~~~TypeAttributes.VisibilityMask ||| convertTypeAccessFlags access } - member x.WithNestedAccess(access) = { x with Attributes = x.Attributes &&& ~~~TypeAttributes.VisibilityMask ||| convertToNestedTypeAccess access } - member x.WithSealed(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition TypeAttributes.Sealed } - member x.WithSerializable(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition TypeAttributes.Serializable } - member x.WithAbstract(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition TypeAttributes.Abstract } - member x.WithImport(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition TypeAttributes.Import } - member x.WithHasSecurity(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition TypeAttributes.HasSecurity } - member x.WithLayout(layout) = { x with Attributes = x.Attributes ||| convertLayout layout; Layout = layout } - member x.WithKind(kind) = { x with Attributes = x.Attributes ||| convertTypeKind kind; Extends = match kind with ILTypeDefKind.Interface -> None | _ -> x.Extends } - member x.WithEncoding(encoding) = { x with Attributes = x.Attributes &&& ~~~TypeAttributes.StringFormatMask ||| convertEncoding encoding } - member x.WithSpecialName(condition) = { x with Attributes = x.Attributes |> conditionalAdd condition TypeAttributes.SpecialName} - member x.WithInitSemantics(init) = { x with Attributes = x.Attributes ||| convertInitSemantics init } + member x.WithAccess(access) = x.With(attributes=(x.Attributes &&& ~~~TypeAttributes.VisibilityMask ||| convertTypeAccessFlags access)) + member x.WithNestedAccess(access) = x.With(attributes=(x.Attributes &&& ~~~TypeAttributes.VisibilityMask ||| convertToNestedTypeAccess access)) + member x.WithSealed(condition) = x.With(attributes=(x.Attributes |> conditionalAdd condition TypeAttributes.Sealed)) + member x.WithSerializable(condition) = x.With(attributes=(x.Attributes |> conditionalAdd condition TypeAttributes.Serializable)) + member x.WithAbstract(condition) = x.With(attributes=(x.Attributes |> conditionalAdd condition TypeAttributes.Abstract)) + member x.WithImport(condition) = x.With(attributes=(x.Attributes |> conditionalAdd condition TypeAttributes.Import)) + member x.WithHasSecurity(condition) = x.With(attributes=(x.Attributes |> conditionalAdd condition TypeAttributes.HasSecurity)) + member x.WithLayout(layout) = x.With(attributes=(x.Attributes ||| convertLayout layout), layout = layout) + member x.WithKind(kind) = x.With(attributes=(x.Attributes ||| convertTypeKind kind), extends = match kind with ILTypeDefKind.Interface -> None | _ -> x.Extends) + member x.WithEncoding(encoding) = x.With(attributes=(x.Attributes &&& ~~~TypeAttributes.StringFormatMask ||| convertEncoding encoding)) + member x.WithSpecialName(condition) = x.With(attributes=(x.Attributes |> conditionalAdd condition TypeAttributes.SpecialName)) + member x.WithInitSemantics(init) = x.With(attributes=(x.Attributes ||| convertInitSemantics init)) and [] ILTypeDefs(f : unit -> (string list * string * ILAttributes * Lazy)[]) = @@ -1826,48 +1892,48 @@ type ILAssemblyLongevity = type ILAssemblyManifest = - { Name: string; - AuxModuleHashAlgorithm: int32; - SecurityDecls: ILPermissions; - PublicKey: byte[] option; - Version: ILVersionInfo option; - Locale: Locale option; - CustomAttrs: ILAttributes; - - AssemblyLongevity: ILAssemblyLongevity; - DisableJitOptimizations: bool; - JitTracking: bool; - IgnoreSymbolStoreSequencePoints: bool; - Retargetable: bool; + { Name: string + AuxModuleHashAlgorithm: int32 + SecurityDecls: ILSecurityDecls + PublicKey: byte[] option + Version: ILVersionInfo option + Locale: Locale option + CustomAttrs: ILAttributes + + AssemblyLongevity: ILAssemblyLongevity + DisableJitOptimizations: bool + JitTracking: bool + IgnoreSymbolStoreSequencePoints: bool + Retargetable: bool /// Records the types implemented by other modules. - ExportedTypes: ILExportedTypesAndForwarders; + ExportedTypes: ILExportedTypesAndForwarders /// Records whether the entrypoint resides in another module. - EntrypointElsewhere: ILModuleRef option; + EntrypointElsewhere: ILModuleRef option } type ILModuleDef = - { Manifest: ILAssemblyManifest option; - CustomAttrs: ILAttributes; - Name: string; - TypeDefs: ILTypeDefs; + { Manifest: ILAssemblyManifest option + CustomAttrs: ILAttributes + Name: string + TypeDefs: ILTypeDefs SubsystemVersion : int * int UseHighEntropyVA : bool (* Random bits of relatively uninteresting data *) - SubSystemFlags: int32; - IsDLL: bool; - IsILOnly: bool; - Platform: ILPlatform option; - StackReserveSize: int32 option; - Is32Bit: bool; - Is32BitPreferred: bool; - Is64Bit: bool; - VirtualAlignment: int32; - PhysicalAlignment: int32; - ImageBase: int32; - MetadataVersion: string; - Resources: ILResources; - NativeResources: list>; (* e.g. win32 resources *) + SubSystemFlags: int32 + IsDLL: bool + IsILOnly: bool + Platform: ILPlatform option + StackReserveSize: int32 option + Is32Bit: bool + Is32BitPreferred: bool + Is64Bit: bool + VirtualAlignment: int32 + PhysicalAlignment: int32 + ImageBase: int32 + MetadataVersion: string + Resources: ILResources + NativeResources: list> (* e.g. win32 resources *) } member x.ManifestOfAssembly = match x.Manifest with @@ -1956,16 +2022,16 @@ let isTypeNameForGlobalFunctions d = (d = typeNameForGlobalFunctions) let mkILMethRef (tref,callconv,nm,gparams,args,rty) = - { mrefParent=tref; - mrefCallconv=callconv; - mrefGenericArity=gparams; - mrefName=nm; - mrefArgs=args; + { mrefParent=tref + mrefCallconv=callconv + mrefGenericArity=gparams + mrefName=nm + mrefArgs=args mrefReturn=rty} let mkILMethSpecForMethRefInTy (mref,typ,minst) = - { mspecMethodRef=mref; - mspecDeclaringType=typ; + { mspecMethodRef=mref + mspecDeclaringType=typ mspecMethodInst=minst } let mkILMethSpec (mref, vc, tinst, minst) = mkILMethSpecForMethRefInTy (mref,mkILNamedTy vc mref.DeclaringTypeRef tinst, minst) @@ -2051,9 +2117,9 @@ let nonBranchingInstrsToCode instrs : ILCode = // // -------------------------------------------------------------------- -let emptyILSecurityDecls = ILPermissions.SecurityDecls [] -let mkILSecurityDecls l = match l with [] -> emptyILSecurityDecls | _ -> ILPermissions.SecurityDecls l -let mkILLazySecurityDecls l = ILPermissions.SecurityDeclsLazy l +let emptyILSecurityDecls = ILSecurityDecls.ILSecurityDecls [] +let mkILSecurityDecls l = match l with [] -> emptyILSecurityDecls | _ -> ILSecurityDecls.ILSecurityDecls l +let mkILLazySecurityDecls l = ILSecurityDecls.ILSecurityDeclsLazy l let mkILTyvarTy tv = ILType.TypeVar tv @@ -2451,17 +2517,17 @@ let mkILVoidReturn = mkILReturn ILType.Void let mkILCtor (access,args,impl) = - { Name=".ctor"; - Attributes=convertMemberAccess access ||| MethodAttributes.SpecialName ||| MethodAttributes.RTSpecialName; - ImplAttributes=MethodImplAttributes.Managed - CallingConv=ILCallingConv.Instance; - Parameters = args - Return= mkILVoidReturn; - mdBody= mkMethBodyAux impl; - SecurityDecls=emptyILSecurityDecls; - IsEntryPoint=false; - GenericParams=mkILEmptyGenericParams; - CustomAttrs = emptyILCustomAttrs; } + ILMethodDef(name=".ctor", + attributes=(convertMemberAccess access ||| MethodAttributes.SpecialName ||| MethodAttributes.RTSpecialName), + implAttributes=MethodImplAttributes.Managed, + callingConv=ILCallingConv.Instance, + parameters = args, + ret= mkILVoidReturn, + body= mkMethBodyAux impl, + securityDecls=emptyILSecurityDecls, + isEntryPoint=false, + genericParams=mkILEmptyGenericParams, + customAttrs = emptyILCustomAttrs) // -------------------------------------------------------------------- // Do-nothing ctor, just pass on to monomorphic superclass @@ -2490,33 +2556,33 @@ let mkILNonGenericEmptyCtor tag superTy = // -------------------------------------------------------------------- let mkILStaticMethod (genparams,nm,access,args,ret,impl) = - { GenericParams=genparams; - Name=nm; - Attributes=convertMemberAccess access ||| MethodAttributes.Static; - ImplAttributes=MethodImplAttributes.Managed - CallingConv = ILCallingConv.Static; - Parameters = args - Return= ret; - SecurityDecls=emptyILSecurityDecls; - IsEntryPoint=false; - CustomAttrs = emptyILCustomAttrs; - mdBody= mkMethBodyAux impl; } + ILMethodDef(genericParams=genparams, + name=nm, + attributes=(convertMemberAccess access ||| MethodAttributes.Static), + implAttributes=MethodImplAttributes.Managed, + callingConv = ILCallingConv.Static, + parameters = args, + ret= ret, + securityDecls=emptyILSecurityDecls, + isEntryPoint=false, + customAttrs = emptyILCustomAttrs, + body= mkMethBodyAux impl) let mkILNonGenericStaticMethod (nm,access,args,ret,impl) = mkILStaticMethod (mkILEmptyGenericParams,nm,access,args,ret,impl) let mkILClassCtor impl = - { Name=".cctor"; - Attributes=MethodAttributes.Private ||| MethodAttributes.Static ||| MethodAttributes.SpecialName ||| MethodAttributes.RTSpecialName; - ImplAttributes=MethodImplAttributes.Managed - CallingConv=ILCallingConv.Static; - GenericParams=mkILEmptyGenericParams; - Parameters = [] - Return=mkILVoidReturn; - IsEntryPoint=false; - SecurityDecls=emptyILSecurityDecls; - CustomAttrs = emptyILCustomAttrs; - mdBody= mkMethBodyAux impl; } + ILMethodDef(name=".cctor", + attributes=(MethodAttributes.Private ||| MethodAttributes.Static ||| MethodAttributes.SpecialName ||| MethodAttributes.RTSpecialName), + implAttributes=MethodImplAttributes.Managed, + callingConv=ILCallingConv.Static, + genericParams=mkILEmptyGenericParams, + parameters = [], + ret=mkILVoidReturn, + isEntryPoint=false, + securityDecls=emptyILSecurityDecls, + customAttrs = emptyILCustomAttrs, + body= mkMethBodyAux impl) // -------------------------------------------------------------------- // Make a virtual method, where the overriding is simply the default @@ -2527,36 +2593,36 @@ let mk_ospec (typ:ILType,callconv,nm,genparams,formal_args,formal_ret) = OverridesSpec (mkILMethRef (typ.TypeRef, callconv, nm, genparams, formal_args,formal_ret), typ) let mkILGenericVirtualMethod (nm,access,genparams,actual_args,actual_ret,impl) = - { Name=nm; - Attributes= - convertMemberAccess access ||| - MethodAttributes.CheckAccessOnOverride ||| - (match impl with MethodBody.Abstract -> MethodAttributes.Abstract ||| MethodAttributes.Virtual | _ -> MethodAttributes.Virtual); - ImplAttributes=MethodImplAttributes.Managed - GenericParams=genparams; - CallingConv=ILCallingConv.Instance; - Parameters=actual_args; - Return=actual_ret; - IsEntryPoint=false; - SecurityDecls=emptyILSecurityDecls; - CustomAttrs = emptyILCustomAttrs; - mdBody= mkMethBodyAux impl; } + ILMethodDef(name=nm, + attributes= + (convertMemberAccess access ||| + MethodAttributes.CheckAccessOnOverride ||| + (match impl with MethodBody.Abstract -> MethodAttributes.Abstract ||| MethodAttributes.Virtual | _ -> MethodAttributes.Virtual)), + implAttributes=MethodImplAttributes.Managed, + genericParams=genparams, + callingConv=ILCallingConv.Instance, + parameters=actual_args, + ret=actual_ret, + isEntryPoint=false, + securityDecls=emptyILSecurityDecls, + customAttrs = emptyILCustomAttrs, + body= mkMethBodyAux impl) let mkILNonGenericVirtualMethod (nm,access,args,ret,impl) = - mkILGenericVirtualMethod (nm,access,mkILEmptyGenericParams,args,ret,impl) + mkILGenericVirtualMethod (nm,access,mkILEmptyGenericParams,args,ret,impl) let mkILGenericNonVirtualMethod (nm,access,genparams, actual_args,actual_ret, impl) = - { Name=nm; - Attributes=convertMemberAccess access ||| MethodAttributes.HideBySig; // see Bug343136: missing HideBySig attribute makes it problematic for C# to consume F# method overloads. - ImplAttributes=MethodImplAttributes.Managed - GenericParams=genparams; - CallingConv=ILCallingConv.Instance; - Parameters=actual_args; - Return=actual_ret; - IsEntryPoint=false; - SecurityDecls=emptyILSecurityDecls; - CustomAttrs = emptyILCustomAttrs; - mdBody= mkMethBodyAux impl; } + ILMethodDef(name=nm, + attributes=(convertMemberAccess access ||| MethodAttributes.HideBySig), + implAttributes=MethodImplAttributes.Managed, + genericParams=genparams, + callingConv=ILCallingConv.Instance, + parameters=actual_args, + ret=actual_ret, + isEntryPoint=false, + securityDecls=emptyILSecurityDecls, + customAttrs = emptyILCustomAttrs, + body= mkMethBodyAux impl) let mkILNonGenericInstanceMethod (nm,access,args,ret,impl) = mkILGenericNonVirtualMethod (nm,access,mkILEmptyGenericParams,args,ret,impl) @@ -2570,13 +2636,13 @@ let mkILNonGenericInstanceMethod (nm,access,args,ret,impl) = let ilmbody_code2code f (il: ILMethodBody) = {il with Code = f il.Code} -let mdef_code2code f md = +let mdef_code2code f (md: ILMethodDef) = let il = - match md.mdBody.Contents with + match md.Body.Contents with | MethodBody.IL il-> il | _ -> failwith "mdef_code2code - method not IL" let b = MethodBody.IL (ilmbody_code2code f il) - {md with mdBody= mkMethBodyAux b } + md.With(body= mkMethBodyAux b) let prependInstrsToCode (instrs: ILInstr list) (c2: ILCode) = let instrs = Array.ofList instrs @@ -2602,7 +2668,7 @@ let prependInstrsToMethod new_code md = mdef_code2code (prependInstrsToCode new_code) md // Creates cctor if needed -let cdef_cctorCode2CodeOrCreate tag f cd = +let cdef_cctorCode2CodeOrCreate tag f (cd: ILTypeDef) = let mdefs = cd.Methods let cctor = match mdefs.FindByName ".cctor" with @@ -2611,7 +2677,7 @@ let cdef_cctorCode2CodeOrCreate tag f cd = | _ -> failwith "bad method table: more than one .cctor found" let methods = ILMethodDefs (fun () -> [| yield f cctor; for md in mdefs do if md.Name <> ".cctor" then yield md |]) - {cd with Methods = methods} + cd.With(methods = methods) let code_of_mdef (md:ILMethodDef) = @@ -2622,10 +2688,10 @@ let code_of_mdef (md:ILMethodDef) = let mkRefToILMethod (tref, md: ILMethodDef) = mkILMethRef (tref, md.CallingConv, md.Name, md.GenericParams.Length, md.ParameterTypes, md.Return.Type) -let mkRefToILField (tref,fdef:ILFieldDef) = mkILFieldRef (tref, fdef.Name, fdef.Type) +let mkRefToILField (tref,fdef:ILFieldDef) = mkILFieldRef (tref, fdef.Name, fdef.FieldType) let mkRefForILMethod scope (tdefs,tdef) mdef = mkRefToILMethod (mkRefForNestedILTypeDef scope (tdefs,tdef), mdef) -let mkRefForILField scope (tdefs,tdef) (fdef:ILFieldDef) = mkILFieldRef (mkRefForNestedILTypeDef scope (tdefs,tdef), fdef.Name, fdef.Type) +let mkRefForILField scope (tdefs,tdef) (fdef:ILFieldDef) = mkILFieldRef (mkRefForNestedILTypeDef scope (tdefs,tdef), fdef.Name, fdef.FieldType) (* Creates cctor if needed *) @@ -2634,18 +2700,19 @@ let prependInstrsToClassCtor instrs tag cd = let mkILField (isStatic,nm,ty,(init:ILFieldInit option),(at: byte [] option),access,isLiteral) = - { Name=nm; - Type=ty; - Attributes=convertFieldAccess access ||| - (if isStatic then FieldAttributes.Static else enum 0) ||| - (if isLiteral then FieldAttributes.Literal else enum 0) ||| - (if init.IsSome then FieldAttributes.HasDefault else enum 0) ||| - (if at.IsSome then FieldAttributes.HasFieldRVA else enum 0) - LiteralValue = init; - Data=at; - Offset=None; - Marshal=None; - CustomAttrs=emptyILCustomAttrs } + ILFieldDef(name=nm, + fieldType=ty, + attributes= + (convertFieldAccess access ||| + (if isStatic then FieldAttributes.Static else enum 0) ||| + (if isLiteral then FieldAttributes.Literal else enum 0) ||| + (if init.IsSome then FieldAttributes.HasDefault else enum 0) ||| + (if at.IsSome then FieldAttributes.HasFieldRVA else enum 0)), + literalValue = init, + data=at, + offset=None, + marshal=None, + customAttrs=emptyILCustomAttrs) let mkILInstanceField (nm,ty,init,access) = mkILField (false,nm,ty,init,None,access,false) let mkILStaticField (nm,ty,init,at,access) = mkILField (true,nm,ty,init,at,access,false) @@ -2665,15 +2732,15 @@ type ILLocalsAllocator(numPrealloc:int) = member tmps.Close() = ResizeArray.toList newLocals -let mkILFieldsLazy l = Fields (LazyOrderedMultiMap((fun (f:ILFieldDef) -> f.Name),l)) +let mkILFieldsLazy l = ILFields (LazyOrderedMultiMap((fun (f:ILFieldDef) -> f.Name),l)) let mkILFields l = mkILFieldsLazy (notlazy l) let emptyILFields = mkILFields [] -let mkILEventsLazy l = Events (LazyOrderedMultiMap((fun (e: ILEventDef) -> e.Name),l)) +let mkILEventsLazy l = ILEvents (LazyOrderedMultiMap((fun (e: ILEventDef) -> e.Name),l)) let mkILEvents l = mkILEventsLazy (notlazy l) let emptyILEvents = mkILEvents [] -let mkILPropertiesLazy l = Properties (LazyOrderedMultiMap((fun (p: ILPropertyDef) -> p.Name),l) ) +let mkILPropertiesLazy l = ILProperties (LazyOrderedMultiMap((fun (p: ILPropertyDef) -> p.Name),l) ) let mkILProperties l = mkILPropertiesLazy (notlazy l) let emptyILProperties = mkILProperties [] @@ -2705,8 +2772,8 @@ let addMethodImplToTable y tab = let prev = Map.tryFindMulti key tab Map.add key (y::prev) tab -let mkILMethodImpls l = MethodImpls (notlazy (List.foldBack addMethodImplToTable l Map.empty)) -let mkILMethodImplsLazy l = MethodImpls (lazy (List.foldBack addMethodImplToTable (Lazy.force l) Map.empty)) +let mkILMethodImpls l = ILMethodImpls (notlazy (List.foldBack addMethodImplToTable l Map.empty)) +let mkILMethodImplsLazy l = ILMethodImpls (lazy (List.foldBack addMethodImplToTable (Lazy.force l) Map.empty)) let emptyILMethodImpls = mkILMethodImpls [] @@ -2750,37 +2817,36 @@ let mkILStorageCtor(tag,preblock,typ,flds,access) = mkILStorageCtorWithParamName let mkILGenericClass (nm, access, genparams, extends, impl, methods, fields, nestedTypes, props, events, attrs, init) = - { Name=nm; - Attributes=convertTypeAccessFlags access ||| TypeAttributes.AutoLayout ||| TypeAttributes.Class ||| (match init with | ILTypeInit.BeforeField -> TypeAttributes.BeforeFieldInit | _ -> enum 0) ||| TypeAttributes.AnsiClass; - GenericParams= genparams; - Implements = impl; - Layout=ILTypeDefLayout.Auto; - Extends = Some extends; - Methods= methods; - Fields= fields; - NestedTypes=nestedTypes; - CustomAttrs=attrs; - MethodImpls=emptyILMethodImpls; - Properties=props; - Events=events; - SecurityDecls=emptyILSecurityDecls; -} + ILTypeDef(name=nm, + attributes=(convertTypeAccessFlags access ||| TypeAttributes.AutoLayout ||| TypeAttributes.Class ||| (match init with | ILTypeInit.BeforeField -> TypeAttributes.BeforeFieldInit | _ -> enum 0) ||| TypeAttributes.AnsiClass), + genericParams= genparams, + implements = impl, + layout=ILTypeDefLayout.Auto, + extends = Some extends, + methods= methods , + fields= fields, + nestedTypes=nestedTypes, + customAttrs=attrs, + methodImpls=emptyILMethodImpls, + properties=props, + events=events, + securityDecls=emptyILSecurityDecls) let mkRawDataValueTypeDef (iltyp_ValueType: ILType) (nm,size,pack) = - { Name = nm; - GenericParams= []; - Attributes = TypeAttributes.NotPublic ||| TypeAttributes.Sealed ||| TypeAttributes.ExplicitLayout ||| TypeAttributes.BeforeFieldInit ||| TypeAttributes.AnsiClass; - Implements = [] - Extends = Some iltyp_ValueType; - Layout=ILTypeDefLayout.Explicit { Size=Some size; Pack=Some pack }; - Methods= emptyILMethods; - Fields= emptyILFields; - NestedTypes=emptyILTypeDefs; - CustomAttrs=emptyILCustomAttrs; - MethodImpls=emptyILMethodImpls; - Properties=emptyILProperties; - Events=emptyILEvents; - SecurityDecls=emptyILSecurityDecls; } + ILTypeDef(name = nm, + genericParams= [], + attributes = (TypeAttributes.NotPublic ||| TypeAttributes.Sealed ||| TypeAttributes.ExplicitLayout ||| TypeAttributes.BeforeFieldInit ||| TypeAttributes.AnsiClass), + implements = [], + extends = Some iltyp_ValueType, + layout=ILTypeDefLayout.Explicit { Size=Some size; Pack=Some pack }, + methods= emptyILMethods, + fields= emptyILFields, + nestedTypes=emptyILTypeDefs, + customAttrs=emptyILCustomAttrs, + methodImpls=emptyILMethodImpls, + properties=emptyILProperties, + events=emptyILEvents, + securityDecls=emptyILSecurityDecls) let mkILSimpleClass (ilg: ILGlobals) (nm, access, methods, fields, nestedTypes, props, events, attrs, init) = @@ -2795,41 +2861,41 @@ let destTypeDefsWithGlobalFunctionsFirst ilg (tdefs: ILTypeDefs) = top2@nontop let mkILSimpleModule assname modname dll subsystemVersion useHighEntropyVA tdefs hashalg locale flags exportedTypes metadataVersion = - { Manifest= - Some { Name=assname; - AuxModuleHashAlgorithm= match hashalg with | Some(alg) -> alg | _ -> 0x8004; // SHA1 - SecurityDecls=emptyILSecurityDecls; - PublicKey= None; - Version= None; - Locale=locale - CustomAttrs=emptyILCustomAttrs; - AssemblyLongevity=ILAssemblyLongevity.Unspecified; - DisableJitOptimizations = 0 <> (flags &&& 0x4000); - JitTracking = (0 <> (flags &&& 0x8000)); // always turn these on - IgnoreSymbolStoreSequencePoints = (0 <> (flags &&& 0x2000)); - Retargetable = (0 <> (flags &&& 0x100)); - ExportedTypes=exportedTypes; - EntrypointElsewhere=None - }; - CustomAttrs=emptyILCustomAttrs; - Name=modname; - NativeResources=[]; - TypeDefs=tdefs; + let manifest = + { Name=assname + AuxModuleHashAlgorithm= match hashalg with | Some(alg) -> alg | _ -> 0x8004 // SHA1 + SecurityDecls=emptyILSecurityDecls + PublicKey= None + Version= None + Locale=locale + CustomAttrs=emptyILCustomAttrs + AssemblyLongevity=ILAssemblyLongevity.Unspecified + DisableJitOptimizations = 0 <> (flags &&& 0x4000) + JitTracking = (0 <> (flags &&& 0x8000)) // always turn these on + IgnoreSymbolStoreSequencePoints = (0 <> (flags &&& 0x2000)) + Retargetable = (0 <> (flags &&& 0x100)) + ExportedTypes=exportedTypes + EntrypointElsewhere=None } + { Manifest= Some manifest + CustomAttrs=emptyILCustomAttrs + Name=modname + NativeResources=[] + TypeDefs=tdefs SubsystemVersion = subsystemVersion UseHighEntropyVA = useHighEntropyVA - SubSystemFlags=defaultSubSystem; - IsDLL=dll; - IsILOnly=true; - Platform=None; - StackReserveSize=None; - Is32Bit=false; - Is32BitPreferred=false; - Is64Bit=false; - PhysicalAlignment=defaultPhysAlignment; - VirtualAlignment=defaultVirtAlignment; - ImageBase=defaultImageBase; - MetadataVersion=metadataVersion; - Resources=mkILResources []; + SubSystemFlags=defaultSubSystem + IsDLL=dll + IsILOnly=true + Platform=None + StackReserveSize=None + Is32Bit=false + Is32BitPreferred=false + Is64Bit=false + PhysicalAlignment=defaultPhysAlignment + VirtualAlignment=defaultVirtAlignment + ImageBase=defaultImageBase + MetadataVersion=metadataVersion + Resources=mkILResources [] } @@ -2882,7 +2948,7 @@ let getTyOfILEnumInfo info = info.enumType let computeILEnumInfo (mdName,mdFields: ILFieldDefs) = match (List.partition (fun (fd:ILFieldDef) -> fd.IsStatic) mdFields.AsList) with | staticFields,[vfd] -> - { enumType = vfd.Type; + { enumType = vfd.FieldType; enumValues = staticFields |> List.map (fun fd -> (fd.Name, match fd.LiteralValue with Some i -> i | None -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": static field does not have an default value"))) } | _,[] -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": no non-static field found") | _,_ -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": more than one non-static field found") @@ -3210,7 +3276,7 @@ let MscorlibScopeRef = ILScopeRef.Assembly (ILAssemblyRef.Create("mscorlib", Non let EcmaMscorlibILGlobals = mkILGlobals MscorlibScopeRef -// PermissionSet is a 'blob' having the following format: +// ILSecurityDecl is a 'blob' having the following format: // - A byte containing a period (.). // - A compressed int32 containing the number of attributes encoded in the blob. // - An array of attributes each containing the following: @@ -3231,7 +3297,7 @@ let mkPermissionSet (ilg: ILGlobals) (action,attributes: list<(ILTypeRef * (stri yield! z_unsigned_int bytes.Length; yield! bytes |] - ILPermission.PermissionSet(action,bytes) + ILSecurityDecl.ILSecurityDecl(action,bytes) // Parse an IL type signature argument within a custom attribute blob @@ -3618,11 +3684,11 @@ and refs_of_mbody s x = | MethodBody.PInvoke (attr) -> refs_of_modref s attr.Where | _ -> () -and refs_of_mdef s md = - List.iter (refs_of_param s) md.Parameters; - refs_of_return s md.Return; - refs_of_mbody s md.mdBody.Contents; - refs_of_custom_attrs s md.CustomAttrs; +and refs_of_mdef s (md: ILMethodDef) = + List.iter (refs_of_param s) md.Parameters + refs_of_return s md.Return + refs_of_mbody s md.Body.Contents + refs_of_custom_attrs s md.CustomAttrs refs_of_genparams s md.GenericParams and refs_of_param s p = refs_of_typ s p.Type @@ -3630,26 +3696,26 @@ and refs_of_return s (rt:ILReturn) = refs_of_typ s rt.Type and refs_of_mdefs s x = Seq.iter (refs_of_mdef s) x and refs_of_event_def s (ed: ILEventDef) = - Option.iter (refs_of_typ s) ed.Type ; - refs_of_mref s ed.AddMethod ; - refs_of_mref s ed.RemoveMethod; - Option.iter (refs_of_mref s) ed.FireMethod ; - List.iter (refs_of_mref s) ed.OtherMethods ; - refs_of_custom_attrs s ed.CustomAttrs + Option.iter (refs_of_typ s) ed.EventType + refs_of_mref s ed.AddMethod + refs_of_mref s ed.RemoveMethod + Option.iter (refs_of_mref s) ed.FireMethod + List.iter (refs_of_mref s) ed.OtherMethods + refs_of_custom_attrs s ed.CustomAttrs and refs_of_events s (x: ILEventDefs) = List.iter (refs_of_event_def s) x.AsList -and refs_of_property_def s pd = - Option.iter (refs_of_mref s) pd.SetMethod ; - Option.iter (refs_of_mref s) pd.GetMethod ; - refs_of_typ s pd.Type ; - refs_of_typs s pd.Args ; - refs_of_custom_attrs s pd.CustomAttrs +and refs_of_property_def s (pd: ILPropertyDef) = + Option.iter (refs_of_mref s) pd.SetMethod + Option.iter (refs_of_mref s) pd.GetMethod + refs_of_typ s pd.PropertyType + refs_of_typs s pd.Args + refs_of_custom_attrs s pd.CustomAttrs and refs_of_properties s (x: ILPropertyDefs) = List.iter (refs_of_property_def s) x.AsList -and refs_of_fdef s fd = - refs_of_typ s fd.Type; +and refs_of_fdef s (fd: ILFieldDef) = + refs_of_typ s fd.FieldType refs_of_custom_attrs s fd.CustomAttrs and refs_of_fields s fields = List.iter (refs_of_fdef s) fields @@ -3657,22 +3723,22 @@ and refs_of_fields s fields = List.iter (refs_of_fdef s) fields and refs_of_method_impls s mimpls = List.iter (refs_of_method_impl s) mimpls and refs_of_method_impl s m = - refs_of_ospec s m.Overrides; + refs_of_ospec s m.Overrides refs_of_mspec s m.OverrideBy and refs_of_tdef_kind _s _k = () and refs_of_tdef s (td : ILTypeDef) = - refs_of_types s td.NestedTypes; - refs_of_genparams s td.GenericParams; - refs_of_typs s td.Implements; - Option.iter (refs_of_typ s) td.Extends; - refs_of_mdefs s td.Methods; - refs_of_fields s td.Fields.AsList; - refs_of_method_impls s td.MethodImpls.AsList; - refs_of_events s td.Events; - refs_of_tdef_kind s td; - refs_of_custom_attrs s td.CustomAttrs; + refs_of_types s td.NestedTypes + refs_of_genparams s td.GenericParams + refs_of_typs s td.Implements + Option.iter (refs_of_typ s) td.Extends + refs_of_mdefs s td.Methods + refs_of_fields s td.Fields.AsList + refs_of_method_impls s td.MethodImpls.AsList + refs_of_events s td.Events + refs_of_tdef_kind s td + refs_of_custom_attrs s td.CustomAttrs refs_of_properties s td.Properties and refs_of_string _s _ = () @@ -3690,18 +3756,18 @@ and refs_of_resource_where s x = | ILResourceLocation.Assembly aref -> refs_of_assref s aref and refs_of_resource s x = - refs_of_resource_where s x.Location; + refs_of_resource_where s x.Location refs_of_custom_attrs s x.CustomAttrs and refs_of_resources s (tab: ILResources) = List.iter (refs_of_resource s) tab.AsList and refs_of_modul s m = - refs_of_types s m.TypeDefs; - refs_of_resources s m.Resources; + refs_of_types s m.TypeDefs + refs_of_resources s m.Resources Option.iter (refs_of_manifest s) m.Manifest and refs_of_manifest s m = - refs_of_custom_attrs s m.CustomAttrs; + refs_of_custom_attrs s m.CustomAttrs refs_of_exported_types s m.ExportedTypes let computeILRefs modul = @@ -3709,7 +3775,7 @@ let computeILRefs modul = { refsA = HashSet<_>(HashIdentity.Structural) refsM = HashSet<_>(HashIdentity.Structural) } - refs_of_modul s modul; + refs_of_modul s modul { AssemblyReferences = Seq.fold (fun acc x -> x::acc) [] s.refsA ModuleReferences = Seq.fold (fun acc x -> x::acc) [] s.refsM } @@ -3730,19 +3796,19 @@ let parseILVersion (vstr : string) = failwith "Invalid version format" else // set the build number to the number of days since Jan 1, 2000 - versionComponents.[2] <- defaultBuild.ToString() ; + versionComponents.[2] <- defaultBuild.ToString() // Set the revision number to number of seconds today / 2 - vstr <- System.String.Join(".",versionComponents) + "." + defaultRevision.ToString() ; + vstr <- System.String.Join(".",versionComponents) + "." + defaultRevision.ToString() elif versionComponents.Length > 3 && versionComponents.[3] = "*" then // Set the revision number to number of seconds today / 2 - versionComponents.[3] <- defaultRevision.ToString() ; - vstr <- System.String.Join(".",versionComponents) ; + versionComponents.[3] <- defaultRevision.ToString() + vstr <- System.String.Join(".",versionComponents) let version = System.Version(vstr) let zero32 n = if n < 0 then 0us else uint16(n) // since the minor revision will be -1 if none is specified, we need to truncate to 0 to not break existing code let minorRevision = if version.Revision = -1 then 0us else uint16(version.MinorRevision) - (zero32 version.Major, zero32 version.Minor, zero32 version.Build, minorRevision);; + (zero32 version.Major, zero32 version.Minor, zero32 version.Build, minorRevision) let compareILVersions (a1,a2,a3,a4) ((b1,b2,b3,b4) : ILVersionInfo) = @@ -3782,7 +3848,7 @@ and unscopeILTypes i = and unscopeILCallSig csig = mkILCallSig (csig.CallingConv,unscopeILTypes csig.ArgTypes,unscopeILType csig.ReturnType) -let resolveILMethodRefWithRescope r td (mref:ILMethodRef) = +let resolveILMethodRefWithRescope r (td: ILTypeDef) (mref:ILMethodRef) = let args = mref.ArgTypes let nargs = args.Length let nm = mref.Name @@ -3815,7 +3881,7 @@ let ungenericizeTypeName n = (let m = String.rindex n sym let res = ref (m < n.Length - 1) for i = m + 1 to n.Length - 1 do - res := !res && n.[i] >= '0' && n.[i] <= '9'; + res := !res && n.[i] >= '0' && n.[i] <= '9' !res) then let pos = String.rindex n sym diff --git a/src/absil/il.fsi b/src/absil/il.fsi index 514725a3bd7..d16c91002d3 100644 --- a/src/absil/il.fsi +++ b/src/absil/il.fsi @@ -71,7 +71,7 @@ type ILPlatform = /// points and some other locations. [] type ILSourceDocument = - static member Create : language: ILGuid option * vendor: ILGuid option * documentType: ILGuid option * file: string -> ILSourceDocument + static member Create: language: ILGuid option * vendor: ILGuid option * documentType: ILGuid option * file: string -> ILSourceDocument member Language: ILGuid option member Vendor: ILGuid option member DocumentType: ILGuid option @@ -80,7 +80,7 @@ type ILSourceDocument = [] type ILSourceMarker = - static member Create : document: ILSourceDocument * line: int * column: int * endLine:int * endColumn: int-> ILSourceMarker + static member Create: document: ILSourceDocument * line: int * column: int * endLine:int * endColumn: int-> ILSourceMarker member Document: ILSourceDocument member Line: int member Column: int @@ -101,8 +101,8 @@ type ILVersionInfo = uint16 * uint16 * uint16 * uint16 [] type ILAssemblyRef = - static member Create : name: string * hash: byte[] option * publicKey: PublicKey option * retargetable: bool * version: ILVersionInfo option * locale: string option -> ILAssemblyRef - static member FromAssemblyName : System.Reflection.AssemblyName -> ILAssemblyRef + static member Create: name: string * hash: byte[] option * publicKey: PublicKey option * retargetable: bool * version: ILVersionInfo option * locale: string option -> ILAssemblyRef + static member FromAssemblyName: System.Reflection.AssemblyName -> ILAssemblyRef member Name: string /// The fully qualified name of the assembly reference, e.g. mscorlib, Version=1.0.3705 etc. member QualifiedName: string @@ -116,7 +116,7 @@ type ILAssemblyRef = [] type ILModuleRef = - static member Create : name: string * hasMetadata: bool * hash: byte[] option -> ILModuleRef + static member Create: name: string * hasMetadata: bool * hash: byte[] option -> ILModuleRef member Name: string member HasMetadata: bool member Hash: byte[] option @@ -228,13 +228,13 @@ type ILThisConvention = [] type ILCallingConv = | Callconv of ILThisConvention * ILArgConvention - member IsInstance : bool - member IsInstanceExplicit : bool - member IsStatic : bool - member ThisConv : ILThisConvention - member BasicConv : ILArgConvention - static member Instance : ILCallingConv - static member Static : ILCallingConv + member IsInstance: bool + member IsInstanceExplicit: bool + member IsStatic: bool + member ThisConv: ILThisConvention + member BasicConv: ILArgConvention + static member Instance: ILCallingConv + static member Static : ILCallingConv /// Array shapes. For most purposes, including verification, the /// rank is the only thing that matters. @@ -245,10 +245,10 @@ type ILArrayBounds = ILArrayBound * ILArrayBound [] type ILArrayShape = | ILArrayShape of ILArrayBounds list // lobound/size pairs - member Rank : int + member Rank: int /// Bounds for a single dimensional, zero based array static member SingleDimensional: ILArrayShape - static member FromRank : int -> ILArrayShape + static member FromRank: int -> ILArrayShape [] type ILBoxity = @@ -265,7 +265,7 @@ type ILGenericVariance = type ILTypeRef = /// Create a ILTypeRef. - static member Create : scope: ILScopeRef * enclosing: string list * name: string -> ILTypeRef + static member Create: scope: ILScopeRef * enclosing: string list * name: string -> ILTypeRef /// Where is the type, i.e. is it in this module, in another module in this assembly or in another assembly? member Scope: ILScopeRef @@ -280,7 +280,7 @@ type ILTypeRef = member FullName: string /// The name of the type in the assembly using the '+' notation for nested types. - member BasicQualifiedName : string + member BasicQualifiedName: string member QualifiedName: string @@ -301,7 +301,7 @@ type ILTypeRef = [] type ILTypeSpec = - static member Create : typeRef:ILTypeRef * instantiation:ILGenericArgs -> ILTypeSpec + static member Create: typeRef:ILTypeRef * instantiation:ILGenericArgs -> ILTypeSpec /// Which type is being referred to? member TypeRef: ILTypeRef @@ -341,14 +341,14 @@ and ILTypeRef * /// The type being modified. ILType - member TypeSpec : ILTypeSpec - member Boxity : ILBoxity - member TypeRef : ILTypeRef - member IsNominal : bool - member GenericArgs : ILGenericArgs - member IsTyvar : bool - member BasicQualifiedName : string - member QualifiedNameWithNoShortPrimaryAssembly : string + member TypeSpec: ILTypeSpec + member Boxity: ILBoxity + member TypeRef: ILTypeRef + member IsNominal: bool + member GenericArgs: ILGenericArgs + member IsTyvar: bool + member BasicQualifiedName: string + member QualifiedNameWithNoShortPrimaryAssembly: string and [] ILCallingSignature = @@ -372,7 +372,7 @@ and ILTypes = list [] type ILMethodRef = - static member Create : enclosingTypeRef: ILTypeRef * callingConv: ILCallingConv * name: string * genericArity: int * argTypes: ILTypes * returnType: ILType -> ILMethodRef + static member Create: enclosingTypeRef: ILTypeRef * callingConv: ILCallingConv * name: string * genericArity: int * argTypes: ILTypes * returnType: ILType -> ILMethodRef member DeclaringTypeRef: ILTypeRef member CallingConv: ILCallingConv member Name: string @@ -406,7 +406,7 @@ type ILFieldRef = [] type ILMethodSpec = - static member Create : ILType * ILMethodRef * ILGenericArgs -> ILMethodSpec + static member Create: ILType * ILMethodRef * ILGenericArgs -> ILMethodSpec member MethodRef: ILMethodRef member DeclaringType: ILType member GenericArgs: ILGenericArgs @@ -426,7 +426,7 @@ type ILFieldSpec = member DeclaringTypeRef: ILTypeRef member Name: string member FormalType: ILType - member ActualType : ILType + member ActualType: ILType /// ILCode labels. In structured code each code label /// refers to a basic block somewhere in the code of the method. @@ -636,7 +636,7 @@ type ILInstr = // Varargs - C++ only | I_arglist - // Local aggregates, i.e. stack allocated data (alloca) : C++ only + // Local aggregates, i.e. stack allocated data (alloca): C++ only | I_localloc | I_cpblk of ILAlignment * ILVolatility | I_initblk of ILAlignment * ILVolatility @@ -854,8 +854,8 @@ type ILAttribute = [] type ILAttributes = - member AsArray : ILAttribute [] - member AsList : ILAttribute list + member AsArray: ILAttribute [] + member AsList: ILAttribute list /// Method parameters and return values. @@ -873,7 +873,7 @@ type ILParameter = type ILParameters = list -val typesOfILParams : ILParameters -> ILType list +val typesOfILParams: ILParameters -> ILType list /// Method return values. [] @@ -882,7 +882,7 @@ type ILReturn = Type: ILType CustomAttrs: ILAttributes } -/// Security ILPermissions +/// Security ILSecurityDecls /// Attached to various structures... [] type ILSecurityAction = @@ -905,14 +905,14 @@ type ILSecurityAction = | InheritanceDemandChoice | DemandChoice -type ILPermission = - | PermissionSet of ILSecurityAction * byte[] +type ILSecurityDecl = + | ILSecurityDecl of ILSecurityAction * byte[] -/// Abstract type equivalent to ILPermission list - use helpers +/// Abstract type equivalent to ILSecurityDecl list - use helpers /// below to construct/destruct these. [] -type ILPermissions = - member AsList : ILPermission list +type ILSecurityDecls = + member AsList: ILSecurityDecl list /// PInvoke attributes. [] @@ -1000,68 +1000,71 @@ type MethodCodeKind = /// may include the bounds, if any, on the generic parameter. type ILGenericParameterDef = { Name: string - /// At most one is the parent type, the others are interface types. + + /// At most one is the parent type, the others are interface types. Constraints: ILTypes + /// Variance of type parameters, only applicable to generic parameters for generic interfaces and delegates. Variance: ILGenericVariance + /// Indicates the type argument must be a reference type. HasReferenceTypeConstraint: bool - CustomAttrs : ILAttributes + + CustomAttrs: ILAttributes + /// Indicates the type argument must be a value type, but not Nullable. HasNotNullableValueTypeConstraint: bool + /// Indicates the type argument must have a public nullary constructor. HasDefaultConstructorConstraint: bool } - type ILGenericParameterDefs = ILGenericParameterDef list [] type ILLazyMethodBody = - member Contents : MethodBody + member Contents: MethodBody -/// Method definitions. +/// IL Method definitions. /// -/// There are several different flavours of methods (constructors, -/// abstract, virtual, static, instance, class constructors). There -/// is no perfect factorization of these as the combinations are not -/// independent. - +/// This type is immutable and record-like. We use a class to get control over the representation +/// used, which allows more efficient representation of the information. [] type ILMethodDef = - { Name: string - Attributes: MethodAttributes - ImplAttributes: MethodImplAttributes - CallingConv: ILCallingConv - Parameters: ILParameters - Return: ILReturn - mdBody: ILLazyMethodBody - SecurityDecls: ILPermissions - IsEntryPoint:bool - GenericParams: ILGenericParameterDefs - CustomAttrs: ILAttributes } + + /// Functional creation of a value + new: name: string * attributes: MethodAttributes * implAttributes: MethodImplAttributes * callingConv: ILCallingConv * parameters: ILParameters * ret: ILReturn * body: ILLazyMethodBody * securityDecls: ILSecurityDecls * isEntryPoint:bool * genericParams: ILGenericParameterDefs * customAttrs: ILAttributes -> ILMethodDef + member Name: string + member Attributes: MethodAttributes + member ImplAttributes: MethodImplAttributes + member CallingConv: ILCallingConv + member Parameters: ILParameters + member Return: ILReturn + member Body: ILLazyMethodBody + member SecurityDecls: ILSecurityDecls + member IsEntryPoint:bool + member GenericParams: ILGenericParameterDefs + member CustomAttrs: ILAttributes member ParameterTypes: ILTypes - member IsIL : bool - member Code : ILCode option - member Locals : ILLocals - member MaxStack : int32 - member IsZeroInit : bool + member IsIL: bool + member Code: ILCode option + member Locals: ILLocals + member MaxStack: int32 + member IsZeroInit: bool - /// .cctor methods. The predicates (IsClassInitializer,IsConstructor,IsStatic,IsNonVirtualInstance,IsVirtual) - /// form a complete, non-overlapping classification of this type. + /// Indicates a .cctor method. member IsClassInitializer: bool - /// .ctor methods. The predicates (IsClassInitializer,IsConstructor,IsStatic,IsNonVirtualInstance,IsVirtual) - /// form a complete, non-overlapping classification of this type. + + /// Indicates a .ctor method. member IsConstructor: bool - /// static methods. The predicates (IsClassInitializer,IsConstructor,IsStatic,IsNonVirtualInstance,IsVirtual) - /// form a complete, non-overlapping classification of this type. + + /// Indicates a static method. member IsStatic: bool - /// instance methods that are not virtual. The predicates (IsClassInitializer,IsConstructor,IsStatic,IsNonVirtualInstance,IsVirtual) - /// form a complete, non-overlapping classification of this type. + + /// Indicates this is an instance methods that is not virtual. member IsNonVirtualInstance: bool - /// instance methods that are virtual or abstract or implement an interface slot. - /// The predicates (IsClassInitializer,IsConstructor,IsStatic,IsNonVirtualInstance,IsVirtual) - /// form a complete, non-overlapping classification of this type. + + /// Indicates an instance methods that is virtual or abstract or implements an interface slot. member IsVirtual: bool member IsFinal: bool @@ -1073,9 +1076,11 @@ type ILMethodDef = member Access: ILMemberAccess member IsHideBySig: bool member IsSpecialName: bool + /// The method is exported to unmanaged code using COM interop. member IsUnmanagedExport: bool member IsReqSecObj: bool + /// Some methods are marked "HasSecurity" even if there are no permissions attached, e.g. if they use SuppressUnmanagedCodeSecurityAttribute member HasSecurity: bool member IsManaged: bool @@ -1085,9 +1090,12 @@ type ILMethodDef = member IsSynchronized: bool member IsNoInline: bool member IsAggressiveInline: bool - /// .NET 2.0 feature: SafeHandle finalizer must be run. + + /// SafeHandle finalizer must be run. member IsMustRun: bool + /// Functional update of the value + member With: ?name: string * ?attributes: MethodAttributes * ?implAttributes: MethodImplAttributes * ?callingConv: ILCallingConv * ?parameters: ILParameters * ?ret: ILReturn * ?body: ILLazyMethodBody * ?securityDecls: ILSecurityDecls * ?isEntryPoint:bool * ?genericParams: ILGenericParameterDefs * ?customAttrs: ILAttributes -> ILMethodDef member WithSpecialName: ILMethodDef member WithHideBySig: unit -> ILMethodDef member WithHideBySig: bool -> ILMethodDef @@ -1106,103 +1114,134 @@ type ILMethodDef = /// Tables of methods. Logically equivalent to a list of methods but /// the table is kept in a form optimized for looking up methods by /// name and arity. - -/// abstract type equivalent to [ILMethodDef list] +/// +/// This type is immutable and record-like. We use a class to get control over the representation +/// used, which allows more efficient representation of the information. [] type ILMethodDefs = interface IEnumerable - member AsArray : ILMethodDef[] - member AsList : ILMethodDef list - member FindByName : string -> ILMethodDef list + member AsArray: ILMethodDef[] + member AsList: ILMethodDef list + member FindByName: string -> ILMethodDef list /// Field definitions. +/// +/// This type is immutable and record-like. We use a class to get control over the representation +/// used, which allows more efficient representation of the information. [] type ILFieldDef = - { Name: string - Type: ILType - Attributes: FieldAttributes - Data: byte[] option - LiteralValue: ILFieldInit option - /// The explicit offset in bytes when explicit layout is used. - Offset: int32 option - Marshal: ILNativeType option - CustomAttrs: ILAttributes } - member IsStatic: bool - member IsSpecialName: bool - member IsLiteral: bool - member NotSerialized: bool - member IsInitOnly: bool - member Access: ILMemberAccess - member WithAccess: ILMemberAccess -> ILFieldDef - member WithInitOnly: bool -> ILFieldDef - member WithStatic: bool -> ILFieldDef - member WithSpecialName: bool -> ILFieldDef - member WithNotSerialized: bool -> ILFieldDef - member WithLiteralDefaultValue: ILFieldInit option -> ILFieldDef - member WithFieldMarshal: ILNativeType option -> ILFieldDef + + /// Functional creation of a value + new: name: string * fieldType: ILType * attributes: FieldAttributes * data: byte[] option * literalValue: ILFieldInit option * offset: int32 option * marshal: ILNativeType option * customAttrs: ILAttributes -> ILFieldDef + + member Name: string + member FieldType: ILType + member Attributes: FieldAttributes + member Data: byte[] option + member LiteralValue: ILFieldInit option + + /// The explicit offset in bytes when explicit layout is used. + member Offset: int32 option + member Marshal: ILNativeType option + member CustomAttrs: ILAttributes + member IsStatic: bool + member IsSpecialName: bool + member IsLiteral: bool + member NotSerialized: bool + member IsInitOnly: bool + member Access: ILMemberAccess + + /// Functional update of the value + member With: ?name: string * ?fieldType: ILType * ?attributes: FieldAttributes * ?data: byte[] option * ?literalValue: ILFieldInit option * ?offset: int32 option * ?marshal: ILNativeType option * ?customAttrs: ILAttributes -> ILFieldDef + member WithAccess: ILMemberAccess -> ILFieldDef + member WithInitOnly: bool -> ILFieldDef + member WithStatic: bool -> ILFieldDef + member WithSpecialName: bool -> ILFieldDef + member WithNotSerialized: bool -> ILFieldDef + member WithLiteralDefaultValue: ILFieldInit option -> ILFieldDef + member WithFieldMarshal: ILNativeType option -> ILFieldDef /// Tables of fields. Logically equivalent to a list of fields but /// the table is kept in a form optimized for looking up fields by /// name. [] type ILFieldDefs = - member AsList : ILFieldDef list - member LookupByName : string -> ILFieldDef list + member AsList: ILFieldDef list + member LookupByName: string -> ILFieldDef list /// Event definitions. +/// +/// This type is immutable and record-like. We use a class to get control over the representation +/// used, which allows more efficient representation of the information. [] type ILEventDef = - { Type: ILType option - Name: string - Attributes: EventAttributes - AddMethod: ILMethodRef - RemoveMethod: ILMethodRef - FireMethod: ILMethodRef option - OtherMethods: ILMethodRef list - CustomAttrs: ILAttributes } - member IsSpecialName : bool - member IsRTSpecialName : bool + + /// Functional creation of a value + new: eventType: ILType option * name: string * attributes: EventAttributes * addMethod: ILMethodRef * removeMethod: ILMethodRef * fireMethod: ILMethodRef option * otherMethods: ILMethodRef list * customAttrs: ILAttributes -> ILEventDef + + member EventType: ILType option + member Name: string + member Attributes: EventAttributes + member AddMethod: ILMethodRef + member RemoveMethod: ILMethodRef + member FireMethod: ILMethodRef option + member OtherMethods: ILMethodRef list + member CustomAttrs: ILAttributes + member IsSpecialName: bool + member IsRTSpecialName: bool + + /// Functional update of the value + member With: ?eventType: ILType option * ?name: string * ?attributes: EventAttributes * ?addMethod: ILMethodRef * ?removeMethod: ILMethodRef * ?fireMethod: ILMethodRef option * ?otherMethods: ILMethodRef list * ?customAttrs: ILAttributes -> ILEventDef /// Table of those events in a type definition. +/// +/// This type is immutable and record-like. We use a class to get control over the representation +/// used, which allows more efficient representation of the information. [] type ILEventDefs = - member AsList : ILEventDef list - member LookupByName : string -> ILEventDef list + member AsList: ILEventDef list + member LookupByName: string -> ILEventDef list -/// Property definitions. +/// Property definitions +/// +/// This type is immutable and record-like. We use a class to get control over the representation +/// used, which allows more efficient representation of the information. [] type ILPropertyDef = - { Name: string - Attributes: PropertyAttributes - SetMethod: ILMethodRef option - GetMethod: ILMethodRef option - CallingConv: ILThisConvention - Type: ILType - Init: ILFieldInit option - Args: ILTypes - CustomAttrs: ILAttributes } - member IsSpecialName : bool - member IsRTSpecialName : bool -/// Table of those properties in a type definition. + /// Functional creation of a value + new: name: string * attributes: PropertyAttributes * setMethod: ILMethodRef option * getMethod: ILMethodRef option * callingConv: ILThisConvention * propertyType: ILType * init: ILFieldInit option * args: ILTypes * customAttrs: ILAttributes -> ILPropertyDef + + /// Functional update of the value + member With: ?name: string * ?attributes: PropertyAttributes * ?setMethod: ILMethodRef option * ?getMethod: ILMethodRef option * ?callingConv: ILThisConvention * ?propertyType: ILType * ?init: ILFieldInit option * ?args: ILTypes * ?customAttrs: ILAttributes -> ILPropertyDef + + member Name: string + member Attributes: PropertyAttributes + member SetMethod: ILMethodRef option + member GetMethod: ILMethodRef option + member CallingConv: ILThisConvention + member PropertyType: ILType + member Init: ILFieldInit option + member Args: ILTypes + member CustomAttrs: ILAttributes + member IsSpecialName: bool + member IsRTSpecialName: bool + +/// Table of properties in an IL type definition. [] [] type ILPropertyDefs = - member AsList : ILPropertyDef list - member LookupByName : string -> ILPropertyDef list + member AsList: ILPropertyDef list + member LookupByName: string -> ILPropertyDef list /// Method Impls -/// -/// If there is an entry (pms --> ms) in this table, then method [ms] -/// is used to implement method [pms] for the purposes of this class -/// and its subclasses. type ILMethodImplDef = { Overrides: ILOverridesSpec OverrideBy: ILMethodSpec } [] type ILMethodImplDefs = - member AsList : ILMethodImplDef list + member AsList: ILMethodImplDef list /// Type Layout information. [] @@ -1236,20 +1275,6 @@ type ILTypeDefAccess = | Nested of ILMemberAccess /// A categorization of type definitions into "kinds" - -//------------------------------------------------------------------- -// A note for the nit-picky.... In theory, the "kind" of a type -// definition can only be partially determined prior to binding. -// For example, you cannot really, absolutely tell if a type is -// really, absolutely a value type until you bind the -// super class and test it for type equality against System.ValueType. -// However, this is unbearably annoying, as it means you -// have to load "primary runtime assembly (System.Runtime or mscorlib)" and perform bind operations -// in order to be able to determine some quite simple -// things. So we approximate by simply looking at the name -// of the superclass when loading. -// ------------------------------------------------------------------ - [] type ILTypeDefKind = | Class @@ -1260,48 +1285,54 @@ type ILTypeDefKind = /// Tables of named type definitions. The types and table may contain on-demand /// (lazy) computations, e.g. the actual reading of some aspects -/// of a type definition may be delayed if the reader being used supports -/// this. -/// -/// This is an abstract type equivalent to "ILTypeDef list". +/// of a type definition may be delayed. [] [] type ILTypeDefs = interface IEnumerable - member AsArray : ILTypeDef[] - member AsList : ILTypeDef list + + member AsArray: ILTypeDef[] + + member AsList: ILTypeDef list /// Get some information about the type defs, but do not force the read of the type defs themselves. - member AsArrayOfLazyTypeDefs : (string list * string * ILAttributes * Lazy) array + member AsArrayOfLazyTypeDefs: (string list * string * ILAttributes * Lazy) array /// Calls to FindByName will result in any laziness in the overall /// set of ILTypeDefs being read in in addition /// to the details for the type found, but the remaining individual /// type definitions will not be read. - member FindByName : string -> ILTypeDef + member FindByName: string -> ILTypeDef -/// Type Definitions +/// Represents IL Type Definitions. /// -/// As for methods there are several important constraints not encoded -/// in the type definition below, for example that the super class of -/// an interface type is always None, or that enumerations always -/// have a very specific form. +/// This type is immutable and record-like. We use a class to get control over the representation +/// used, which allows more efficient representation of the information. and [] ILTypeDef = - { Name: string - Attributes: TypeAttributes - GenericParams: ILGenericParameterDefs - Layout: ILTypeDefLayout - NestedTypes: ILTypeDefs - Implements: ILTypes - Extends: ILType option - Methods: ILMethodDefs - SecurityDecls: ILPermissions - Fields: ILFieldDefs - MethodImpls: ILMethodImplDefs - Events: ILEventDefs - Properties: ILPropertyDefs - CustomAttrs: ILAttributes } + + /// Create the contents + new: name: string * attributes: TypeAttributes * layout: ILTypeDefLayout * implements: ILTypes * genericParams: ILGenericParameterDefs * + extends: ILType option * methods: ILMethodDefs * nestedTypes: ILTypeDefs * fields: ILFieldDefs * methodImpls: ILMethodImplDefs * + events: ILEventDefs * properties: ILPropertyDefs * customAttrs: ILAttributes * securityDecls: ILSecurityDecls -> ILTypeDef + + /// Update the contents + member With: ?name: string * ?attributes: TypeAttributes * ?layout: ILTypeDefLayout * ?implements: ILTypes * ?genericParams:ILGenericParameterDefs * ?extends:ILType option * ?methods:ILMethodDefs * ?nestedTypes:ILTypeDefs * ?fields: ILFieldDefs * ?methodImpls:ILMethodImplDefs * ?events:ILEventDefs * ?properties:ILPropertyDefs * ?customAttrs:ILAttributes * ?securityDecls: ILSecurityDecls -> ILTypeDef + + member Name: string + member Attributes: TypeAttributes + member GenericParams: ILGenericParameterDefs + member Layout: ILTypeDefLayout + member NestedTypes: ILTypeDefs + member Implements: ILTypes + member Extends: ILType option + member Methods: ILMethodDefs + member SecurityDecls: ILSecurityDecls + member Fields: ILFieldDefs + member MethodImpls: ILMethodImplDefs + member Events: ILEventDefs + member Properties: ILPropertyDefs + member CustomAttrs: ILAttributes member IsClass: bool member IsStruct: bool member IsInterface: bool @@ -1319,6 +1350,7 @@ and [] /// e.g. if they use SuppressUnmanagedCodeSecurityAttribute member HasSecurity: bool member Encoding: ILDefaultPInvokeEncoding + member WithAccess: ILTypeDefAccess -> ILTypeDef member WithNestedAccess: ILMemberAccess -> ILTypeDef member WithSealed: bool -> ILTypeDef @@ -1335,7 +1367,7 @@ and [] [] [] type ILNestedExportedTypes = - member AsList : ILNestedExportedType list + member AsList: ILNestedExportedType list /// "Classes Elsewhere" - classes in auxiliary modules. /// @@ -1385,7 +1417,7 @@ type ILExportedTypeOrForwarder = [] [] type ILExportedTypesAndForwarders = - member AsList : ILExportedTypeOrForwarder list + member AsList: ILExportedTypeOrForwarder list [] type ILResourceAccess = @@ -1408,13 +1440,13 @@ type ILResource = Access: ILResourceAccess CustomAttrs: ILAttributes } /// Read the bytes from a resource local to an assembly - member Bytes : byte[] + member Bytes: byte[] /// Table of resources in a module. [] [] type ILResources = - member AsList : ILResource list + member AsList: ILResource list [] @@ -1434,7 +1466,7 @@ type ILAssemblyManifest = /// cryptographic hashes: they are simple file hashes. The algorithm /// is normally 0x00008004 indicating the SHA1 hash algorithm. AuxModuleHashAlgorithm: int32 - SecurityDecls: ILPermissions + SecurityDecls: ILSecurityDecls /// This is the public key used to sign this /// assembly (the signature itself is stored elsewhere: see the /// binary format, and may not have been written if delay signing @@ -1466,8 +1498,8 @@ type ILModuleDef = CustomAttrs: ILAttributes Name: string TypeDefs: ILTypeDefs - SubsystemVersion : int * int - UseHighEntropyVA : bool + SubsystemVersion: int * int + UseHighEntropyVA: bool SubSystemFlags: int32 IsDLL: bool IsILOnly: bool @@ -1484,7 +1516,7 @@ type ILModuleDef = /// e.g. win86 resources, as the exact contents of a .res or .obj file. NativeResources: Lazy list } member ManifestOfAssembly: ILAssemblyManifest - member HasManifest : bool + member HasManifest: bool /// Find the method definition corresponding to the given property or /// event operation. These are always in the same class as the property @@ -1541,8 +1573,8 @@ val ungenericizeTypeName: string -> string (* e.g. List`1 --> List *) /// reference items from it via an ILGlobals for that specific version built using mkILGlobals. [] type ILGlobals = - member primaryAssemblyScopeRef : ILScopeRef - member primaryAssemblyName : string + member primaryAssemblyScopeRef: ILScopeRef + member primaryAssemblyName: string member typ_Object: ILType member typ_String: ILType member typ_Type: ILType @@ -1566,7 +1598,7 @@ type ILGlobals = /// Build the table of commonly used references given functions to find types in system assemblies val mkILGlobals: ILScopeRef -> ILGlobals -val EcmaMscorlibILGlobals : ILGlobals +val EcmaMscorlibILGlobals: ILGlobals /// When writing a binary the fake "toplevel" type definition (called ) /// must come first. This function puts it first, and creates it in the returned @@ -1610,7 +1642,7 @@ val mkILArrTy: ILType * ILArrayShape -> ILType val mkILArr1DTy: ILType -> ILType val isILArrTy: ILType -> bool val destILArrTy: ILType -> ILArrayShape * ILType -val mkILBoxedType : ILTypeSpec -> ILType +val mkILBoxedType: ILTypeSpec -> ILType /// Make method references and specs. val mkILMethRef: ILTypeRef * ILCallingConv * string * int * ILType list * ILType -> ILMethodRef @@ -1650,7 +1682,7 @@ val mkILFormalNamedTy: ILBoxity -> ILTypeRef -> ILGenericParameterDef list -> IL val mkILFormalTypars: ILType list -> ILGenericParameterDefs val mkILFormalGenericArgs: int -> ILGenericParameterDefs -> ILGenericArgsList -val mkILSimpleTypar : string -> ILGenericParameterDef +val mkILSimpleTypar: string -> ILGenericParameterDef /// Make custom attributes. val mkILCustomAttribMethRef: ILGlobals @@ -1666,11 +1698,11 @@ val mkILCustomAttribute: ILAttributeNamedArg list (* named args: values and flags indicating if they are fields or properties *) -> ILAttribute -val mkPermissionSet : ILGlobals -> ILSecurityAction * (ILTypeRef * (string * ILType * ILAttribElem) list) list -> ILPermission +val mkPermissionSet: ILGlobals -> ILSecurityAction * (ILTypeRef * (string * ILType * ILAttribElem) list) list -> ILSecurityDecl /// Making code. val generateCodeLabel: unit -> ILCodeLabel -val formatCodeLabel : ILCodeLabel -> string +val formatCodeLabel: ILCodeLabel -> string /// Make some code that is a straight line sequence of instructions. /// The function will add a "return" if the last instruction is not an exiting instruction. @@ -1678,16 +1710,16 @@ val nonBranchingInstrsToCode: ILInstr list -> ILCode /// Helpers for codegen: scopes for allocating new temporary variables. type ILLocalsAllocator = - new : preAlloc: int -> ILLocalsAllocator - member AllocLocal : ILLocal -> uint16 - member Close : unit -> ILLocal list + new: preAlloc: int -> ILLocalsAllocator + member AllocLocal: ILLocal -> uint16 + member Close: unit -> ILLocal list /// Derived functions for making some common patterns of instructions. val mkNormalCall: ILMethodSpec -> ILInstr val mkNormalCallvirt: ILMethodSpec -> ILInstr val mkNormalCallconstraint: ILType * ILMethodSpec -> ILInstr val mkNormalNewobj: ILMethodSpec -> ILInstr -val mkCallBaseConstructor : ILType * ILType list -> ILInstr list +val mkCallBaseConstructor: ILType * ILType list -> ILInstr list val mkNormalStfld: ILFieldSpec -> ILInstr val mkNormalStsfld: ILFieldSpec -> ILInstr val mkNormalLdsfld: ILFieldSpec -> ILInstr @@ -1780,12 +1812,12 @@ val mkILCustomAttrsFromArray: ILAttribute[] -> ILAttributes val mkILComputedCustomAttrs: (unit -> ILAttribute[]) -> ILAttributes val emptyILCustomAttrs: ILAttributes -val mkILSecurityDecls: ILPermission list -> ILPermissions -val mkILLazySecurityDecls: Lazy -> ILPermissions -val emptyILSecurityDecls: ILPermissions +val mkILSecurityDecls: ILSecurityDecl list -> ILSecurityDecls +val mkILLazySecurityDecls: Lazy -> ILSecurityDecls +val emptyILSecurityDecls: ILSecurityDecls -val mkMethBodyAux : MethodBody -> ILLazyMethodBody -val mkMethBodyLazyAux : Lazy -> ILLazyMethodBody +val mkMethBodyAux: MethodBody -> ILLazyMethodBody +val mkMethBodyLazyAux: Lazy -> ILLazyMethodBody val mkILEvents: ILEventDef list -> ILEventDefs val mkILEventsLazy: Lazy -> ILEventDefs @@ -1834,7 +1866,7 @@ val mkILResources: ILResource list -> ILResources val mkILResourcesLazy: Lazy -> ILResources /// Making modules. -val mkILSimpleModule: assemblyName:string -> moduleName:string -> dll:bool -> subsystemVersion : (int * int) -> useHighEntropyVA : bool -> ILTypeDefs -> int32 option -> string option -> int -> ILExportedTypesAndForwarders -> string -> ILModuleDef +val mkILSimpleModule: assemblyName:string -> moduleName:string -> dll:bool -> subsystemVersion: (int * int) -> useHighEntropyVA: bool -> ILTypeDefs -> int32 option -> string option -> int -> ILExportedTypesAndForwarders -> string -> ILModuleDef /// Generate references to existing type definitions, method definitions /// etc. Useful for generating references, e.g. to a class we're processing @@ -1843,9 +1875,9 @@ val mkILSimpleModule: assemblyName:string -> moduleName:string -> dll:bool -> su /// an auxiliary module or are generating multiple assemblies at /// once. -val mkRefForNestedILTypeDef : ILScopeRef -> ILTypeDef list * ILTypeDef -> ILTypeRef -val mkRefForILMethod : ILScopeRef -> ILTypeDef list * ILTypeDef -> ILMethodDef -> ILMethodRef -val mkRefForILField : ILScopeRef -> ILTypeDef list * ILTypeDef -> ILFieldDef -> ILFieldRef +val mkRefForNestedILTypeDef: ILScopeRef -> ILTypeDef list * ILTypeDef -> ILTypeRef +val mkRefForILMethod : ILScopeRef -> ILTypeDef list * ILTypeDef -> ILMethodDef -> ILMethodRef +val mkRefForILField : ILScopeRef -> ILTypeDef list * ILTypeDef -> ILFieldDef -> ILFieldRef val mkRefToILMethod: ILTypeRef * ILMethodDef -> ILMethodRef val mkRefToILField: ILTypeRef * ILFieldDef -> ILFieldRef @@ -1934,7 +1966,7 @@ val isILDoubleTy: ILType -> bool val isILSingleTy: ILType -> bool /// Get a public key token from a public key. -val sha1HashBytes : byte[] -> byte[] (* SHA1 hash *) +val sha1HashBytes: byte[] -> byte[] (* SHA1 hash *) /// Get a version number from a CLR version string, e.g. 1.0.3705.0 val parseILVersion: string -> ILVersionInfo @@ -1959,13 +1991,13 @@ val computeILEnumInfo: string * ILFieldDefs -> ILEnumInfo [] type ILEventRef = - static member Create : ILTypeRef * string -> ILEventRef + static member Create: ILTypeRef * string -> ILEventRef member DeclaringTypeRef: ILTypeRef member Name: string [] type ILPropertyRef = - static member Create : ILTypeRef * string -> ILPropertyRef + static member Create: ILTypeRef * string -> ILPropertyRef member DeclaringTypeRef: ILTypeRef member Name: string interface System.IComparable diff --git a/src/absil/ilmorph.fs b/src/absil/ilmorph.fs index 90b0e267f69..4e8d4ed8c01 100644 --- a/src/absil/ilmorph.fs +++ b/src/absil/ilmorph.fs @@ -155,8 +155,8 @@ let cattrs_typ2typ ilg f (cs: ILAttributes) = mkILCustomAttrs (List.map (cattr_typ2typ ilg f) cs.AsList) let fdef_typ2typ ilg ftype (fd: ILFieldDef) = - {fd with Type=ftype fd.Type; - CustomAttrs=cattrs_typ2typ ilg ftype fd.CustomAttrs} + fd.With(fieldType=ftype fd.FieldType, + customAttrs=cattrs_typ2typ ilg ftype fd.CustomAttrs) let local_typ2typ f (l: ILLocal) = {l with Type = f l.Type} let varargs_typ2typ f (varargs: ILVarArgs) = Option.map (List.map f) varargs @@ -225,16 +225,15 @@ let morphILMethodBody (filmbody) (x: ILLazyMethodBody) = let ospec_typ2typ f (OverridesSpec(mref,ty)) = OverridesSpec(mref_typ2typ f mref, f ty) -let mdef_typ2typ_ilmbody2ilmbody ilg fs md = +let mdef_typ2typ_ilmbody2ilmbody ilg fs (md: ILMethodDef) = let (ftype,filmbody) = fs let ftype' = ftype (Some md) - let body' = morphILMethodBody (filmbody (Some md)) md.mdBody - {md with - GenericParams=gparams_typ2typ ftype' md.GenericParams; - mdBody= body'; - Parameters = List.map (param_typ2typ ilg ftype') md.Parameters; - Return = return_typ2typ ilg ftype' md.Return; - CustomAttrs=cattrs_typ2typ ilg ftype' md.CustomAttrs } + let body' = morphILMethodBody (filmbody (Some md)) md.Body + md.With(genericParams=gparams_typ2typ ftype' md.GenericParams, + body= body', + parameters = List.map (param_typ2typ ilg ftype') md.Parameters, + ret = return_typ2typ ilg ftype' md.Return, + customAttrs=cattrs_typ2typ ilg ftype' md.CustomAttrs) let fdefs_typ2typ ilg f x = fdefs_fdef2fdef (fdef_typ2typ ilg f) x @@ -244,44 +243,41 @@ let mimpl_typ2typ f e = { Overrides = ospec_typ2typ f e.Overrides; OverrideBy = mspec_typ2typ (f,(fun _ -> f)) e.OverrideBy; } -let edef_typ2typ ilg f e = - { e with - Type = Option.map f e.Type; - AddMethod = mref_typ2typ f e.AddMethod; - RemoveMethod = mref_typ2typ f e.RemoveMethod; - FireMethod = Option.map (mref_typ2typ f) e.FireMethod; - OtherMethods = List.map (mref_typ2typ f) e.OtherMethods; - CustomAttrs = cattrs_typ2typ ilg f e.CustomAttrs } - -let pdef_typ2typ ilg f p = - { p with - SetMethod = Option.map (mref_typ2typ f) p.SetMethod; - GetMethod = Option.map (mref_typ2typ f) p.GetMethod; - Type = f p.Type; - Args = List.map f p.Args; - CustomAttrs = cattrs_typ2typ ilg f p.CustomAttrs } +let edef_typ2typ ilg f (e: ILEventDef) = + e.With(eventType = Option.map f e.EventType, + addMethod = mref_typ2typ f e.AddMethod, + removeMethod = mref_typ2typ f e.RemoveMethod, + fireMethod = Option.map (mref_typ2typ f) e.FireMethod, + otherMethods = List.map (mref_typ2typ f) e.OtherMethods, + customAttrs = cattrs_typ2typ ilg f e.CustomAttrs) + +let pdef_typ2typ ilg f (p: ILPropertyDef) = + p.With(setMethod = Option.map (mref_typ2typ f) p.SetMethod, + getMethod = Option.map (mref_typ2typ f) p.GetMethod, + propertyType = f p.PropertyType, + args = List.map f p.Args, + customAttrs = cattrs_typ2typ ilg f p.CustomAttrs) let pdefs_typ2typ ilg f (pdefs: ILPropertyDefs) = mkILProperties (List.map (pdef_typ2typ ilg f) pdefs.AsList) let edefs_typ2typ ilg f (edefs: ILEventDefs) = mkILEvents (List.map (edef_typ2typ ilg f) edefs.AsList) let mimpls_typ2typ f (mimpls : ILMethodImplDefs) = mkILMethodImpls (List.map (mimpl_typ2typ f) mimpls.AsList) -let rec tdef_typ2typ_ilmbody2ilmbody_mdefs2mdefs ilg enc fs td = +let rec tdef_typ2typ_ilmbody2ilmbody_mdefs2mdefs ilg enc fs (td: ILTypeDef) = let (ftype,fmdefs) = fs let ftype' = ftype (Some (enc,td)) None let mdefs' = fmdefs (enc,td) td.Methods let fdefs' = fdefs_typ2typ ilg ftype' td.Fields - {td with Implements= List.map ftype' td.Implements; - GenericParams= gparams_typ2typ ftype' td.GenericParams; - Extends = Option.map ftype' td.Extends; - Methods=mdefs'; - NestedTypes=tdefs_typ2typ_ilmbody2ilmbody_mdefs2mdefs ilg (enc@[td]) fs td.NestedTypes; - Fields=fdefs'; - MethodImpls = mimpls_typ2typ ftype' td.MethodImpls; - Events = edefs_typ2typ ilg ftype' td.Events; - Properties = pdefs_typ2typ ilg ftype' td.Properties; - CustomAttrs = cattrs_typ2typ ilg ftype' td.CustomAttrs; - } + td.With(implements= List.map ftype' td.Implements, + genericParams= gparams_typ2typ ftype' td.GenericParams, + extends = Option.map ftype' td.Extends, + methods=mdefs', + nestedTypes=tdefs_typ2typ_ilmbody2ilmbody_mdefs2mdefs ilg (enc@[td]) fs td.NestedTypes, + fields=fdefs', + methodImpls = mimpls_typ2typ ftype' td.MethodImpls, + events = edefs_typ2typ ilg ftype' td.Events, + properties = pdefs_typ2typ ilg ftype' td.Properties, + customAttrs = cattrs_typ2typ ilg ftype' td.CustomAttrs) and tdefs_typ2typ_ilmbody2ilmbody_mdefs2mdefs ilg enc fs tdefs = morphILTypeDefs (tdef_typ2typ_ilmbody2ilmbody_mdefs2mdefs ilg enc fs) tdefs diff --git a/src/absil/ilprint.fs b/src/absil/ilprint.fs index abad68c9772..f2b722292fd 100644 --- a/src/absil/ilprint.fs +++ b/src/absil/ilprint.fs @@ -270,14 +270,14 @@ and goutput_permission _env os p = match p with - | PermissionSet (sa,b) -> + | ILSecurityDecl (sa,b) -> output_string os " .permissionset " output_security_action os sa output_string os " = (" output_bytes os b output_string os ")" -and goutput_security_decls env os (ps: ILPermissions) = output_seq " " (goutput_permission env) os ps.AsList +and goutput_security_decls env os (ps: ILSecurityDecls) = output_seq " " (goutput_permission env) os ps.AsList and goutput_gparam env os (gf: ILGenericParameterDef) = output_string os (tyvar_generator gf.Name); @@ -469,30 +469,30 @@ let output_custom_attr_data os data = output_string os " = "; output_parens output_bytes os data let goutput_custom_attr env os attr = - output_string os " .custom "; - goutput_mspec env os attr.Method; + output_string os " .custom " + goutput_mspec env os attr.Method output_custom_attr_data os attr.Data let goutput_custom_attrs env os (attrs : ILAttributes) = List.iter (fun attr -> goutput_custom_attr env os attr; output_string os "\n" ) attrs.AsList -let goutput_fdef _tref env os fd = - output_string os " .field "; +let goutput_fdef _tref env os (fd: ILFieldDef) = + output_string os " .field " match fd.Offset with Some i -> output_string os "["; output_i32 os i; output_string os "] " | None -> () match fd.Marshal with Some _i -> output_string os "// marshal attribute not printed\n"; | None -> () - output_member_access os fd.Access; - output_string os " "; - if fd.IsStatic then output_string os " static "; - if fd.IsLiteral then output_string os " literal "; - if fd.IsSpecialName then output_string os " specialname rtspecialname "; - if fd.IsInitOnly then output_string os " initonly "; - if fd.NotSerialized then output_string os " notserialized "; - goutput_typ env os fd.Type; - output_string os " "; - output_id os fd.Name; - output_option output_at os fd.Data; - output_option output_field_init os fd.LiteralValue; - output_string os "\n"; + output_member_access os fd.Access + output_string os " " + if fd.IsStatic then output_string os " static " + if fd.IsLiteral then output_string os " literal " + if fd.IsSpecialName then output_string os " specialname rtspecialname " + if fd.IsInitOnly then output_string os " initonly " + if fd.NotSerialized then output_string os " notserialized " + goutput_typ env os fd.FieldType + output_string os " " + output_id os fd.Name + output_option output_at os fd.Data + output_option output_field_init os fd.LiteralValue + output_string os "\n" goutput_custom_attrs env os fd.CustomAttrs @@ -768,7 +768,7 @@ let goutput_ilmbody env os (il: ILMethodBody) = output_string os ")\n" -let goutput_mbody is_entrypoint env os md = +let goutput_mbody is_entrypoint env os (md: ILMethodDef) = if md.ImplAttributes &&& MethodImplAttributes.Native <> enum 0 then output_string os "native " elif md.ImplAttributes &&& MethodImplAttributes.IL <> enum 0 then output_string os "cil " else output_string os "runtime " @@ -779,7 +779,7 @@ let goutput_mbody is_entrypoint env os md = output_string os " \n{ \n" ; goutput_security_decls env os md.SecurityDecls; goutput_custom_attrs env os md.CustomAttrs; - match md.mdBody.Contents with + match md.Body.Contents with | MethodBody.IL il -> goutput_ilmbody env os il | _ -> () if is_entrypoint then output_string os " .entrypoint"; @@ -799,7 +799,7 @@ let goutput_mdef env os (md:ILMethodDef) = elif md.IsConstructor then "rtspecialname" elif md.IsStatic then "static "^ - (match md.mdBody.Contents with + (match md.Body.Contents with MethodBody.PInvoke (attr) -> "pinvokeimpl(\""^ attr.Where.Name^"\" as \""^ attr.Name ^"\""^ (match attr.CallingConv with @@ -852,7 +852,7 @@ let goutput_mdef env os (md:ILMethodDef) = (goutput_mbody is_entrypoint menv) os md; output_string os "\n" -let goutput_pdef env os pd = +let goutput_pdef env os (pd: ILPropertyDef) = output_string os "property\n\tgetter: "; (match pd.GetMethod with None -> () | Some mref -> goutput_mref env os mref); output_string os "\n\tsetter: "; @@ -891,7 +891,7 @@ let goutput_mdefs env os (mdefs: ILMethodDefs) = let goutput_pdefs env os (pdefs: ILPropertyDefs) = List.iter (fun f -> (goutput_pdef env) os f; output_string os "\n" ) pdefs.AsList -let rec goutput_tdef (enc) env contents os cd = +let rec goutput_tdef enc env contents os (cd: ILTypeDef) = let env = ppenv_enter_tdef cd.GenericParams env let layout_attr,pp_layout_decls = splitTypeLayout cd.Layout if isTypeNameForGlobalFunctions cd.Name then @@ -939,26 +939,26 @@ and output_init_semantics os f = and goutput_lambdas env os lambdas = match lambdas with | Lambdas_forall (gf,l) -> - output_angled (goutput_gparam env) os gf; - output_string os " "; + output_angled (goutput_gparam env) os gf + output_string os " " (goutput_lambdas env) os l | Lambdas_lambda (ps,l) -> output_parens (goutput_param env) os ps; - output_string os " "; + output_string os " " (goutput_lambdas env) os l | Lambdas_return typ -> output_string os "--> "; (goutput_typ env) os typ -and goutput_tdefs contents (enc) env os (td: ILTypeDefs) = +and goutput_tdefs contents enc env os (td: ILTypeDefs) = List.iter (goutput_tdef enc env contents os) td.AsList let output_ver os (a,b,c,d) = - output_string os " .ver "; - output_u16 os a; - output_string os " : "; - output_u16 os b; - output_string os " : "; - output_u16 os c; - output_string os " : "; + output_string os " .ver " + output_u16 os a + output_string os " : " + output_u16 os b + output_string os " : " + output_u16 os c + output_string os " : " output_u16 os d let output_locale os s = output_string os " .Locale "; output_qstring os s diff --git a/src/absil/ilread.fs b/src/absil/ilread.fs index e89164a42a0..aca3d1ee155 100644 --- a/src/absil/ilread.fs +++ b/src/absil/ilread.fs @@ -1009,7 +1009,7 @@ type ILReaderContext = seekReadMemberRefAsMethodData : MemberRefAsMspecIdx -> VarArgMethodData seekReadMemberRefAsFieldSpec : MemberRefAsFspecIdx -> ILFieldSpec seekReadCustomAttr : CustomAttrIdx -> ILAttribute - seekReadSecurityDecl : SecurityDeclIdx -> ILPermission + seekReadSecurityDecl : SecurityDeclIdx -> ILSecurityDecl seekReadTypeRef : int ->ILTypeRef seekReadTypeRefAsType : TypeRefAsTypIdx -> ILType readBlobHeapAsPropertySig : BlobAsPropSigIdx -> ILThisConvention * ILType * ILTypes @@ -1703,20 +1703,20 @@ and seekReadTypeDef ctxt toponly (idx:int) = let mimpls = seekReadMethodImpls ctxt numtypars idx let props = seekReadProperties ctxt numtypars idx let events = seekReadEvents ctxt numtypars idx - { Name=nm - GenericParams=typars - Attributes= enum(flags) - Layout = layout - NestedTypes= nested - Implements = impls - Extends = super - Methods = mdefs - SecurityDecls = sdecls - Fields=fdefs - MethodImpls=mimpls - Events= events - Properties=props - CustomAttrs=cas } + ILTypeDef(name=nm, + genericParams=typars , + attributes= enum(flags), + layout = layout, + nestedTypes= nested, + implements = impls, + extends = super, + methods = mdefs, + securityDecls = sdecls, + fields=fdefs, + methodImpls=mimpls, + events= events, + properties=props, + customAttrs=cas) Some (ns, n, cas, rest) and seekReadTopTypeDefs ctxt () = @@ -1888,32 +1888,33 @@ and seekReadOptionalTypeDefOrRef ctxt numtypars boxity idx = else Some (seekReadTypeDefOrRef ctxt numtypars boxity List.empty idx) and seekReadField ctxt (numtypars, hasLayout) (idx:int) = - let (flags, nameIdx, typeIdx) = seekReadFieldRow ctxt idx - let nm = readStringHeap ctxt nameIdx - let isStatic = (flags &&& 0x0010) <> 0 - let fd = - { Name = nm - Type= readBlobHeapAsFieldSig ctxt numtypars typeIdx - Attributes = enum(flags) - LiteralValue = if (flags &&& 0x8000) = 0 then None else Some (seekReadConstant ctxt (TaggedIndex(hc_FieldDef, idx))) - Marshal = - if (flags &&& 0x1000) = 0 then None else - Some (seekReadIndexedRow (ctxt.getNumRows TableNames.FieldMarshal, seekReadFieldMarshalRow ctxt, - fst, hfmCompare (TaggedIndex(hfm_FieldDef, idx)), - isSorted ctxt TableNames.FieldMarshal, - (snd >> readBlobHeapAsNativeType ctxt))) - Data = - if (flags &&& 0x0100) = 0 then None - else - let rva = seekReadIndexedRow (ctxt.getNumRows TableNames.FieldRVA, seekReadFieldRVARow ctxt, - snd, simpleIndexCompare idx, isSorted ctxt TableNames.FieldRVA, fst) - Some (rvaToData ctxt "field" rva) - Offset = - if hasLayout && not isStatic then - Some (seekReadIndexedRow (ctxt.getNumRows TableNames.FieldLayout, seekReadFieldLayoutRow ctxt, - snd, simpleIndexCompare idx, isSorted ctxt TableNames.FieldLayout, fst)) else None - CustomAttrs=seekReadCustomAttrs ctxt (TaggedIndex(hca_FieldDef, idx)) } - fd + let (flags, nameIdx, typeIdx) = seekReadFieldRow ctxt idx + let nm = readStringHeap ctxt nameIdx + let isStatic = (flags &&& 0x0010) <> 0 + ILFieldDef(name = nm, + fieldType= readBlobHeapAsFieldSig ctxt numtypars typeIdx, + attributes = enum(flags), + literalValue = (if (flags &&& 0x8000) = 0 then None else Some (seekReadConstant ctxt (TaggedIndex(hc_FieldDef, idx)))), + marshal = + (if (flags &&& 0x1000) = 0 then + None + else + Some (seekReadIndexedRow (ctxt.getNumRows TableNames.FieldMarshal, seekReadFieldMarshalRow ctxt, + fst, hfmCompare (TaggedIndex(hfm_FieldDef, idx)), + isSorted ctxt TableNames.FieldMarshal, + (snd >> readBlobHeapAsNativeType ctxt)))), + data = + (if (flags &&& 0x0100) = 0 then + None + else + let rva = seekReadIndexedRow (ctxt.getNumRows TableNames.FieldRVA, seekReadFieldRVARow ctxt, + snd, simpleIndexCompare idx, isSorted ctxt TableNames.FieldRVA, fst) + Some (rvaToData ctxt "field" rva)), + offset = + (if hasLayout && not isStatic then + Some (seekReadIndexedRow (ctxt.getNumRows TableNames.FieldLayout, seekReadFieldLayoutRow ctxt, + snd, simpleIndexCompare idx, isSorted ctxt TableNames.FieldLayout, fst)) else None), + customAttrs=seekReadCustomAttrs ctxt (TaggedIndex(hca_FieldDef, idx) )) and seekReadFields ctxt (numtypars, hasLayout) fidx1 fidx2 = mkILFieldsLazy @@ -2254,27 +2255,26 @@ and seekReadMethod ctxt numtypars (idx:int) = let ret, ilParams = seekReadParams ctxt (retty, argtys) paramIdx endParamIdx - { Name=nm - Attributes = enum(flags) - ImplAttributes= enum(implflags) - SecurityDecls=seekReadSecurityDecls ctxt (TaggedIndex(hds_MethodDef, idx)) - IsEntryPoint= (fst ctxt.entryPointToken = TableNames.Method && snd ctxt.entryPointToken = idx) - GenericParams=seekReadGenericParams ctxt numtypars (tomd_MethodDef, idx) - CustomAttrs=seekReadCustomAttrs ctxt (TaggedIndex(hca_MethodDef, idx)) - Parameters= ilParams - CallingConv=cc - Return=ret - mdBody= - if (codetype = 0x01) && pinvoke then - mkMethBodyLazyAux (notlazy MethodBody.Native) - elif pinvoke then - seekReadImplMap ctxt nm idx - elif internalcall || abstr || unmanaged || (codetype <> 0x00) then - //if codeRVA <> 0x0 then dprintn "non-IL or abstract method with non-zero RVA" - mkMethBodyLazyAux (notlazy MethodBody.Abstract) - else - seekReadMethodRVA ctxt (idx, nm, internalcall, noinline, aggressiveinline, numtypars) codeRVA - } + ILMethodDef(name=nm, + attributes = enum(flags), + implAttributes= enum(implflags), + securityDecls=seekReadSecurityDecls ctxt (TaggedIndex(hds_MethodDef, idx)), + isEntryPoint= (fst ctxt.entryPointToken = TableNames.Method && snd ctxt.entryPointToken = idx), + genericParams=seekReadGenericParams ctxt numtypars (tomd_MethodDef, idx), + customAttrs=seekReadCustomAttrs ctxt (TaggedIndex(hca_MethodDef, idx)) , + parameters= ilParams, + callingConv=cc, + ret=ret, + body= + (if (codetype = 0x01) && pinvoke then + mkMethBodyLazyAux (notlazy MethodBody.Native) + elif pinvoke then + seekReadImplMap ctxt nm idx + elif internalcall || abstr || unmanaged || (codetype <> 0x00) then + //if codeRVA <> 0x0 then dprintn "non-IL or abstract method with non-zero RVA" + mkMethBodyLazyAux (notlazy MethodBody.Abstract) + else + seekReadMethodRVA ctxt (idx, nm, internalcall, noinline, aggressiveinline, numtypars) codeRVA)) and seekReadParams ctxt (retty, argtys) pidx1 pidx2 = @@ -2358,14 +2358,14 @@ and seekReadMethodSemantics ctxt id = and seekReadEvent ctxt numtypars idx = let (flags, nameIdx, typIdx) = seekReadEventRow ctxt idx - { Type = seekReadOptionalTypeDefOrRef ctxt numtypars AsObject typIdx - Name = readStringHeap ctxt nameIdx - Attributes = enum(flags) - AddMethod= seekReadMethodSemantics ctxt (0x0008, TaggedIndex(hs_Event, idx)) - RemoveMethod=seekReadMethodSemantics ctxt (0x0010, TaggedIndex(hs_Event, idx)) - FireMethod=seekReadoptional_MethodSemantics ctxt (0x0020, TaggedIndex(hs_Event, idx)) - OtherMethods = seekReadMultipleMethodSemantics ctxt (0x0004, TaggedIndex(hs_Event, idx)) - CustomAttrs=seekReadCustomAttrs ctxt (TaggedIndex(hca_Event, idx)) } + ILEventDef(eventType = seekReadOptionalTypeDefOrRef ctxt numtypars AsObject typIdx, + name = readStringHeap ctxt nameIdx, + attributes = enum(flags), + addMethod= seekReadMethodSemantics ctxt (0x0008, TaggedIndex(hs_Event, idx)), + removeMethod=seekReadMethodSemantics ctxt (0x0010, TaggedIndex(hs_Event, idx)), + fireMethod=seekReadoptional_MethodSemantics ctxt (0x0020, TaggedIndex(hs_Event, idx)), + otherMethods = seekReadMultipleMethodSemantics ctxt (0x0004, TaggedIndex(hs_Event, idx)), + customAttrs=seekReadCustomAttrs ctxt (TaggedIndex(hca_Event, idx))) (* REVIEW: can substantially reduce numbers of EventMap and PropertyMap reads by first checking if the whole table is sorted according to ILTypeDef tokens and then doing a binary chop *) and seekReadEvents ctxt numtypars tidx = @@ -2398,15 +2398,15 @@ and seekReadProperty ctxt numtypars idx = match setter with | Some mref -> mref.CallingConv .ThisConv | None -> cc - { Name=readStringHeap ctxt nameIdx - CallingConv = cc2 - Attributes = enum(flags) - SetMethod=setter - GetMethod=getter - Type=retty - Init= if (flags &&& 0x1000) = 0 then None else Some (seekReadConstant ctxt (TaggedIndex(hc_Property, idx))) - Args=argtys - CustomAttrs=seekReadCustomAttrs ctxt (TaggedIndex(hca_Property, idx)) } + ILPropertyDef(name=readStringHeap ctxt nameIdx, + callingConv = cc2, + attributes = enum(flags), + setMethod=setter, + getMethod=getter, + propertyType=retty, + init= (if (flags &&& 0x1000) = 0 then None else Some (seekReadConstant ctxt (TaggedIndex(hc_Property, idx)))), + args=argtys, + customAttrs=seekReadCustomAttrs ctxt (TaggedIndex(hca_Property, idx))) and seekReadProperties ctxt numtypars tidx = mkILPropertiesLazy @@ -2461,10 +2461,9 @@ and seekReadSecurityDecl ctxt (a, b) = and seekReadSecurityDeclUncached ctxtH (SecurityDeclIdx (act, ty)) = let ctxt = getHole ctxtH - PermissionSet ((if List.memAssoc (int act) (Lazy.force ILSecurityActionRevMap) then List.assoc (int act) (Lazy.force ILSecurityActionRevMap) else failwith "unknown security action"), + ILSecurityDecl ((if List.memAssoc (int act) (Lazy.force ILSecurityActionRevMap) then List.assoc (int act) (Lazy.force ILSecurityActionRevMap) else failwith "unknown security action"), readBlobHeap ctxt ty) - and seekReadConstant ctxt idx = let kind, vidx = seekReadIndexedRow (ctxt.getNumRows TableNames.Constant, seekReadConstantRow ctxt, diff --git a/src/absil/ilreflect.fs b/src/absil/ilreflect.fs index 8f040838c60..6fc0c03e122 100644 --- a/src/absil/ilreflect.fs +++ b/src/absil/ilreflect.fs @@ -1474,17 +1474,12 @@ let rec buildMethodPass2 cenv tref (typB:TypeBuilder) emEnv (mdef : ILMethodDef) let implflags = mdef.ImplAttributes let cconv = convCallConv mdef.CallingConv let mref = mkRefToILMethod (tref, mdef) - let emEnv = if mdef.IsEntryPoint && isNil mdef.ParameterTypes then - (* Bug 2209: - Here, we collect the entry points generated by ilxgen corresponding to the top-level effects. - Users can (now) annotate their own functions with EntryPoint attributes. - However, these user entry points functions must take string[] argument. - By only adding entry points with no arguments, we only collect the top-level effects. - *) - envAddEntryPt emEnv (typB, mdef.Name) - else - emEnv - match mdef.mdBody.Contents with + let emEnv = + if mdef.IsEntryPoint && isNil mdef.ParameterTypes then + envAddEntryPt emEnv (typB, mdef.Name) + else + emEnv + match mdef.Body.Contents with #if !FX_RESHAPED_REFEMIT | MethodBody.PInvoke p -> let argtys = convTypesToArray cenv emEnv mdef.ParameterTypes @@ -1508,17 +1503,7 @@ let rec buildMethodPass2 cenv tref (typB:TypeBuilder) emEnv (mdef : ILMethodDef) (* p.CharBestFit *) (* p.NoMangle *) - let methB = typB.DefinePInvokeMethod(mdef.Name, - p.Where.Name, - p.Name, - attrs, - cconv, - rty, - null, null, - argtys, - null, null, - pcc, - pcs) + let methB = typB.DefinePInvokeMethod(mdef.Name, p.Where.Name, p.Name, attrs, cconv, rty, null, null, argtys, null, null, pcc, pcs) methB.SetImplementationFlagsAndLog(implflags); envBindMethodRef emEnv mref methB #endif @@ -1554,7 +1539,7 @@ let rec buildMethodPass2 cenv tref (typB:TypeBuilder) emEnv (mdef : ILMethodDef) let rec buildMethodPass3 cenv tref modB (typB:TypeBuilder) emEnv (mdef : ILMethodDef) = let mref = mkRefToILMethod (tref, mdef) let isPInvoke = - match mdef.mdBody.Contents with + match mdef.Body.Contents with | MethodBody.PInvoke _p -> true | _ -> false match mdef.Name with @@ -1566,7 +1551,7 @@ let rec buildMethodPass3 cenv tref modB (typB:TypeBuilder) emEnv (mdef : ILMetho let defineParameter (i, attr, name) = consB.DefineParameterAndLog(i+1, attr, name) mdef.Parameters |> List.iteri (emitParameter cenv emEnv defineParameter); // Body - emitMethodBody cenv modB emEnv consB.GetILGenerator mdef.Name mdef.mdBody; + emitMethodBody cenv modB emEnv consB.GetILGenerator mdef.Name mdef.Body; emitCustomAttrs cenv emEnv (wrapCustomAttr consB.SetCustomAttribute) mdef.CustomAttrs; () | _name -> @@ -1587,7 +1572,7 @@ let rec buildMethodPass3 cenv tref modB (typB:TypeBuilder) emEnv (mdef : ILMetho mdef.Parameters |> List.iteri (fun a b -> emitParameter cenv emEnv defineParameter a b); // Body if not isPInvoke then - emitMethodBody cenv modB emEnv methB.GetILGeneratorAndLog mdef.Name mdef.mdBody; + emitMethodBody cenv modB emEnv methB.GetILGeneratorAndLog mdef.Name mdef.Body; let emEnv = envPopTyvars emEnv // case fold later... emitCustomAttrs cenv emEnv methB.SetCustomAttributeAndLog mdef.CustomAttrs @@ -1597,11 +1582,8 @@ let rec buildMethodPass3 cenv tref modB (typB:TypeBuilder) emEnv (mdef : ILMetho let buildFieldPass2 cenv tref (typB:TypeBuilder) emEnv (fdef : ILFieldDef) = - (*{ -Data: bytes option; - -Marshal: NativeType option; *) - let attrs = fdef.Attributes - let fieldT = convType cenv emEnv fdef.Type + let fieldT = convType cenv emEnv fdef.FieldType let fieldB = match fdef.Data with | Some d -> typB.DefineInitializedData(fdef.Name, d, attrs) @@ -1628,11 +1610,11 @@ let buildFieldPass2 cenv tref (typB:TypeBuilder) emEnv (fdef : ILFieldDef) = fdef.Offset |> Option.iter (fun offset -> fieldB.SetOffset(offset)); // custom attributes: done on pass 3 as they may reference attribute constructors generated on // pass 2. - let fref = mkILFieldRef (tref, fdef.Name, fdef.Type) + let fref = mkILFieldRef (tref, fdef.Name, fdef.FieldType) envBindFieldRef emEnv fref fieldB let buildFieldPass3 cenv tref (_typB:TypeBuilder) emEnv (fdef : ILFieldDef) = - let fref = mkILFieldRef (tref, fdef.Name, fdef.Type) + let fref = mkILFieldRef (tref, fdef.Name, fdef.FieldType) let fieldB = envGetFieldB emEnv fref emitCustomAttrs cenv emEnv (wrapCustomAttr fieldB.SetCustomAttribute) fdef.CustomAttrs @@ -1644,7 +1626,7 @@ let buildPropertyPass2 cenv tref (typB:TypeBuilder) emEnv (prop : ILPropertyDef) let attrs = flagsIf prop.IsRTSpecialName PropertyAttributes.RTSpecialName ||| flagsIf prop.IsSpecialName PropertyAttributes.SpecialName - let propB = typB.DefinePropertyAndLog(prop.Name, attrs, convType cenv emEnv prop.Type, convTypesToArray cenv emEnv prop.Args) + let propB = typB.DefinePropertyAndLog(prop.Name, attrs, convType cenv emEnv prop.PropertyType, convTypesToArray cenv emEnv prop.Args) prop.SetMethod |> Option.iter (fun mref -> propB.SetSetMethod(envGetMethB emEnv mref)); prop.GetMethod |> Option.iter (fun mref -> propB.SetGetMethod(envGetMethB emEnv mref)); @@ -1667,8 +1649,8 @@ let buildPropertyPass3 cenv tref (_typB:TypeBuilder) emEnv (prop : ILPropertyDef let buildEventPass3 cenv (typB:TypeBuilder) emEnv (eventDef : ILEventDef) = let attrs = flagsIf eventDef.IsSpecialName EventAttributes.SpecialName ||| flagsIf eventDef.IsRTSpecialName EventAttributes.RTSpecialName - assert eventDef.Type.IsSome - let eventB = typB.DefineEventAndLog(eventDef.Name, attrs, convType cenv emEnv eventDef.Type.Value) + assert eventDef.EventType.IsSome + let eventB = typB.DefineEventAndLog(eventDef.Name, attrs, convType cenv emEnv eventDef.EventType.Value) eventDef.AddMethod |> (fun mref -> eventB.SetAddOnMethod(envGetMethB emEnv mref)); eventDef.RemoveMethod |> (fun mref -> eventB.SetRemoveOnMethod(envGetMethB emEnv mref)); @@ -1911,33 +1893,33 @@ let verbose2 = false let createTypeRef (visited : Dictionary<_, _>, created : Dictionary<_, _>) emEnv tref = let rec traverseTypeDef (tref:ILTypeRef) (tdef:ILTypeDef) = - if verbose2 then dprintf "buildTypeDefPass4: Creating Enclosing Types of %s\n" tdef.Name; + if verbose2 then dprintf "buildTypeDefPass4: Creating Enclosing Types of %s\n" tdef.Name for enc in getEnclosingTypeRefs tref do traverseTypeRef enc // WORKAROUND (ProductStudio FSharp 1.0 bug 615): the constraints on generic method parameters // are resolved overly eagerly by reflection emit's CreateType. - if verbose2 then dprintf "buildTypeDefPass4: Doing type typar constraints of %s\n" tdef.Name; + if verbose2 then dprintf "buildTypeDefPass4: Doing type typar constraints of %s\n" tdef.Name for gp in tdef.GenericParams do for cx in gp.Constraints do traverseType CollectTypes.All cx - if verbose2 then dprintf "buildTypeDefPass4: Doing method constraints of %s\n" tdef.Name; + if verbose2 then dprintf "buildTypeDefPass4: Doing method constraints of %s\n" tdef.Name for md in tdef.Methods.AsList do for gp in md.GenericParams do for cx in gp.Constraints do traverseType CollectTypes.All cx // We absolutely need the exact parent type... - if verbose2 then dprintf "buildTypeDefPass4: Creating Super Class Chain of %s\n" tdef.Name; + if verbose2 then dprintf "buildTypeDefPass4: Creating Super Class Chain of %s\n" tdef.Name tdef.Extends |> Option.iter (traverseType CollectTypes.All) // We absolutely need the exact interface types... - if verbose2 then dprintf "buildTypeDefPass4: Creating Interface Chain of %s\n" tdef.Name; + if verbose2 then dprintf "buildTypeDefPass4: Creating Interface Chain of %s\n" tdef.Name tdef.Implements |> List.iter (traverseType CollectTypes.All) - if verbose2 then dprintf "buildTypeDefPass4: Do value types in fields of %s\n" tdef.Name; - tdef.Fields.AsList |> List.iter (fun fd -> traverseType CollectTypes.ValueTypesOnly fd.Type) + if verbose2 then dprintf "buildTypeDefPass4: Do value types in fields of %s\n" tdef.Name + tdef.Fields.AsList |> List.iter (fun fd -> traverseType CollectTypes.ValueTypesOnly fd.FieldType) if verbose2 then dprintf "buildTypeDefPass4: Done with dependencies of %s\n" tdef.Name diff --git a/src/absil/ilwrite.fs b/src/absil/ilwrite.fs index e1af01dd561..3b307720a30 100644 --- a/src/absil/ilwrite.fs +++ b/src/absil/ilwrite.fs @@ -1120,7 +1120,7 @@ and GetTypeDefAsEventMapRow cenv tidx = SimpleIndex (TableNames.Event, cenv.eventDefs.Count + 1) |] and GetKeyForFieldDef tidx (fd: ILFieldDef) = - FieldDefKey (tidx, fd.Name, fd.Type) + FieldDefKey (tidx, fd.Name, fd.FieldType) and GenFieldDefPass2 cenv tidx fd = ignore (cenv.fieldDefs.AddUniqueEntry "field" (fun (fdkey:FieldDefKey) -> fdkey.Name) (GetKeyForFieldDef tidx fd)) @@ -1144,7 +1144,7 @@ and GenMethodDefPass2 cenv tidx md = cenv.methodDefIdxs.[md] <- idx and GetKeyForPropertyDef tidx (x: ILPropertyDef) = - PropKey (tidx, x.Name, x.Type, x.Args) + PropKey (tidx, x.Name, x.PropertyType, x.Args) and GenPropertyDefPass2 cenv tidx x = ignore (cenv.propertyDefs.AddUniqueEntry "property" (fun (PropKey (_, n, _, _)) -> n) (GetKeyForPropertyDef tidx x)) @@ -1400,10 +1400,10 @@ and GenCustomAttrsPass3Or4 cenv hca (attrs: ILAttributes) = attrs.AsList |> List.iter (GenCustomAttrPass3Or4 cenv hca) // -------------------------------------------------------------------- -// ILPermissionSet --> DeclSecurity rows +// ILSecurityDecl --> DeclSecurity rows // -------------------------------------------------------------------- *) -let rec GetSecurityDeclRow cenv hds (PermissionSet (action, s)) = +let rec GetSecurityDeclRow cenv hds (ILSecurityDecl (action, s)) = UnsharedRow [| UShort (uint16 (List.assoc action (Lazy.force ILSecurityActionMap))) HasDeclSecurity (fst hds, snd hds) @@ -2323,7 +2323,7 @@ let rec GetFieldDefAsFieldDefRow cenv env (fd: ILFieldDef) = StringE (GetStringHeapIdx cenv fd.Name) Blob (GetFieldDefSigAsBlobIdx cenv env fd ) |] -and GetFieldDefSigAsBlobIdx cenv env fd = GetFieldDefTypeAsBlobIdx cenv env fd.Type +and GetFieldDefSigAsBlobIdx cenv env fd = GetFieldDefTypeAsBlobIdx cenv env fd.FieldType and GenFieldDefPass3 cenv env fd = let fidx = AddUnsharedRow cenv TableNames.Field (GetFieldDefAsFieldDefRow cenv env fd) @@ -2492,7 +2492,7 @@ let GenMethodDefAsRow cenv env midx (md: ILMethodDef) = if cenv.entrypoint <> None then failwith "duplicate entrypoint" else cenv.entrypoint <- Some (true, midx) let codeAddr = - (match md.mdBody.Contents with + (match md.Body.Contents with | MethodBody.IL ilmbody -> let addr = cenv.nextCodeAddr let (localToken, code, seqpoints, rootScope) = GenILMethodBody md.Name cenv env ilmbody @@ -2563,7 +2563,7 @@ let GenMethodDefPass3 cenv env (md:ILMethodDef) = md.CustomAttrs |> GenCustomAttrsPass3Or4 cenv (hca_MethodDef, midx) md.SecurityDecls.AsList |> GenSecurityDeclsPass3 cenv (hds_MethodDef, midx) md.GenericParams |> List.iteri (fun n gp -> GenGenericParamPass3 cenv env n (tomd_MethodDef, midx) gp) - match md.mdBody.Contents with + match md.Body.Contents with | MethodBody.PInvoke attr -> let flags = begin match attr.CallingConv with @@ -2616,12 +2616,12 @@ let GenPropertyMethodSemanticsPass3 cenv pidx kind mref = let rec GetPropertySigAsBlobIdx cenv env prop = GetBytesAsBlobIdx cenv (GetPropertySigAsBytes cenv env prop) -and GetPropertySigAsBytes cenv env prop = +and GetPropertySigAsBytes cenv env (prop: ILPropertyDef) = emitBytesViaBuffer (fun bb -> let b = ((hasthisToByte prop.CallingConv) ||| e_IMAGE_CEE_CS_CALLCONV_PROPERTY) bb.EmitByte b bb.EmitZ32 prop.Args.Length - EmitType cenv env bb prop.Type + EmitType cenv env bb prop.PropertyType prop.Args |> List.iter (EmitType cenv env bb)) and GetPropertyAsPropertyRow cenv env (prop:ILPropertyDef) = @@ -2658,7 +2658,7 @@ let rec GenEventMethodSemanticsPass3 cenv eidx kind mref = /// ILEventDef --> Event Row + MethodSemantics entries and GenEventAsEventRow cenv env (md: ILEventDef) = let flags = md.Attributes - let tdorTag, tdorRow = GetTypeOptionAsTypeDefOrRef cenv env md.Type + let tdorTag, tdorRow = GetTypeOptionAsTypeDefOrRef cenv env md.EventType UnsharedRow [| UShort (uint16 flags) StringE (GetStringHeapIdx cenv md.Name) diff --git a/src/absil/ilx.fs b/src/absil/ilx.fs index d28ff3d2f4f..1914ace9b07 100644 --- a/src/absil/ilx.fs +++ b/src/absil/ilx.fs @@ -22,7 +22,7 @@ let mkLowerName (nm: string) = type IlxUnionField(fd: ILFieldDef) = let lowerName = mkLowerName fd.Name member x.ILField = fd - member x.Type = x.ILField.Type + member x.Type = x.ILField.FieldType member x.Name = x.ILField.Name member x.LowerName = lowerName diff --git a/src/fsharp/IlxGen.fs b/src/fsharp/IlxGen.fs index ed07bc51d72..90385b2c2ea 100644 --- a/src/fsharp/IlxGen.fs +++ b/src/fsharp/IlxGen.fs @@ -434,14 +434,13 @@ and GenTypeAux amap m (tyenv: TypeReprEnv) voidOK ptrsOK ty = // Generate ILX references to closures, classunions etc. given a tyenv //-------------------------------------------------------------------------- -and GenUnionCaseRef (amap: ImportMap) m tyenv i (fspecs:RecdField array) = +and GenUnionCaseRef (amap: ImportMap) m tyenv i (fspecs:RecdField[]) = let g = amap.g fspecs |> Array.mapi (fun j fspec -> let ilFieldDef = IL.mkILInstanceField(fspec.Name,GenType amap m tyenv fspec.FormalType, None, ILMemberAccess.Public) + // These properties on the "field" of an alternative end up going on a property generated by cu_erase.fs IlxUnionField - { ilFieldDef with - // These properties on the "field" of an alternative end up going on a property generated by cu_erase.fs - CustomAttrs = mkILCustomAttrs [(mkCompilationMappingAttrWithVariantNumAndSeqNum g (int SourceConstructFlags.Field) i j )] } ) + (ilFieldDef.With(customAttrs = mkILCustomAttrs [(mkCompilationMappingAttrWithVariantNumAndSeqNum g (int SourceConstructFlags.Field) i j )]))) and GenUnionRef (amap: ImportMap) m (tcref: TyconRef) = @@ -1047,9 +1046,9 @@ let MergeOptions m o1 o2 = #endif Some x -let MergePropertyPair m (pd: ILPropertyDef) pdef = - {pd with GetMethod=MergeOptions m pd.GetMethod pdef.GetMethod - SetMethod=MergeOptions m pd.SetMethod pdef.SetMethod} +let MergePropertyPair m (pd: ILPropertyDef) (pdef: ILPropertyDef) = + pd.With(getMethod=MergeOptions m pd.GetMethod pdef.GetMethod, + setMethod=MergeOptions m pd.SetMethod pdef.SetMethod) type PropKey = PropKey of string * ILTypes * ILThisConvention @@ -1073,7 +1072,7 @@ let MergePropertyDefs m ilPropertyDefs = //-------------------------------------------------------------------------- /// Information collected imperatively for each type definition -type TypeDefBuilder(tdef, tdefDiscards) = +type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = let gmethods = new ResizeArray(0) let gfields = new ResizeArray(0) let gproperties : Dictionary = new Dictionary<_,_>(3,HashIdentity.Structural) @@ -1081,16 +1080,16 @@ type TypeDefBuilder(tdef, tdefDiscards) = let gnested = new TypeDefsBuilder() member b.Close() = - { tdef with - Methods = mkILMethods (tdef.Methods.AsList @ ResizeArray.toList gmethods) - Fields = mkILFields (tdef.Fields.AsList @ ResizeArray.toList gfields) - Properties = mkILProperties (tdef.Properties.AsList @ HashRangeSorted gproperties ) - Events = mkILEvents (tdef.Events.AsList @ ResizeArray.toList gevents) - NestedTypes = mkILTypeDefs (tdef.NestedTypes.AsList @ gnested.Close()) } - + tdef.With(methods = mkILMethods (tdef.Methods.AsList @ ResizeArray.toList gmethods), + fields = mkILFields (tdef.Fields.AsList @ ResizeArray.toList gfields), + properties = mkILProperties (tdef.Properties.AsList @ HashRangeSorted gproperties ), + events = mkILEvents (tdef.Events.AsList @ ResizeArray.toList gevents), + nestedTypes = mkILTypeDefs (tdef.NestedTypes.AsList @ gnested.Close())) member b.AddEventDef(edef) = gevents.Add edef + member b.AddFieldDef(ilFieldDef) = gfields.Add ilFieldDef + member b.AddMethodDef(ilMethodDef) = let discard = match tdefDiscards with @@ -1098,7 +1097,9 @@ type TypeDefBuilder(tdef, tdefDiscards) = | None -> false if not discard then gmethods.Add ilMethodDef + member b.NestedTypeDefs = gnested + member b.GetCurrentFields() = gfields |> Seq.readonly /// Merge Get and Set property nodes, which we generate independently for F# code @@ -1185,7 +1186,7 @@ type AssemblyBuilder(cenv:cenv) as mgbuf = match explicitEntryPointInfo with | Some tref -> let IntializeCompiledScript(fspec,m) = - mgbuf.AddExplicitInitToSpecificMethodDef((fun md -> md.IsEntryPoint), tref, fspec, GenPossibleILSourceMarker cenv m, [], []) + mgbuf.AddExplicitInitToSpecificMethodDef((fun (md:ILMethodDef) -> md.IsEntryPoint), tref, fspec, GenPossibleILSourceMarker cenv m, [], []) scriptInitFspecs |> List.iter IntializeCompiledScript | None -> () @@ -1500,7 +1501,7 @@ let GenConstArray cenv (cgbuf:CodeGenBuffer) eenv ilElementType (data:'a[]) (wri let ilFieldName = CompilerGeneratedName ("field" + string(newUnique())) let fty = ILType.Value vtspec let ilFieldDef = mkILStaticField (ilFieldName,fty, None, Some bytes, ILMemberAccess.Assembly) - let ilFieldDef = { ilFieldDef with CustomAttrs = mkILCustomAttrs [ cenv.g.DebuggerBrowsableNeverAttribute ] } + let ilFieldDef = ilFieldDef.With(customAttrs = mkILCustomAttrs [ cenv.g.DebuggerBrowsableNeverAttribute ]) let fspec = mkILFieldSpecInTy (mkILTyForCompLoc eenv.cloc,ilFieldName, fty) CountStaticFieldDef() cgbuf.mgbuf.AddFieldDef(fspec.DeclaringTypeRef,ilFieldDef) @@ -3524,7 +3525,7 @@ and fixupVirtualSlotFlags (mdef:ILMethodDef) = mdef.WithHideBySig() and renameMethodDef nameOfOverridingMethod (mdef : ILMethodDef) = - {mdef with Name=nameOfOverridingMethod } + mdef.With(name=nameOfOverridingMethod) and fixupMethodImplFlags (mdef:ILMethodDef) = mdef.WithAccess(ILMemberAccess.Private).WithHideBySig().WithFinal(true).WithNewSlot @@ -3560,7 +3561,7 @@ and GenObjectMethod cenv eenvinner (cgbuf:CodeGenBuffer) useMethodImpl tmethod = // fixup attributes to generate a method impl let mdef = if useMethodImpl then fixupMethodImplFlags mdef else mdef let mdef = fixupVirtualSlotFlags mdef - let mdef = { mdef with CustomAttrs = mkILCustomAttrs ilAttribs } + let mdef = mdef.With(customAttrs = mkILCustomAttrs ilAttribs) [(useMethodImpl,methodImplGenerator,methTyparsOfOverridingMethod),mdef] and GenObjectExpr cenv cgbuf eenvouter expr (baseType,baseValOpt,basecall,overrides,interfaceImpls,m) sequel = @@ -3713,24 +3714,30 @@ and GenClosureTypeDefs cenv (tref:ILTypeRef, ilGenParams, attrs, ilCloFreeVars, cloStructure=ilCloLambdas cloCode=notlazy ilCtorBody } - let td = - { Name = tref.Name - Layout = ILTypeDefLayout.Auto - Attributes = enum 0 - GenericParams = ilGenParams - CustomAttrs = mkILCustomAttrs(attrs @ [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Closure) ]) - Fields = emptyILFields - Events= emptyILEvents - Properties = emptyILProperties - Methods= mkILMethods mdefs - MethodImpls= mkILMethodImpls mimpls - NestedTypes=emptyILTypeDefs - Implements = ilIntfTys - Extends= Some ext - SecurityDecls= emptyILSecurityDecls } - let td = td.WithSealed(true).WithSerializable(true).WithSpecialName(true).WithAccess(ComputeTypeAccess tref true).WithLayout(ILTypeDefLayout.Auto).WithEncoding(ILDefaultPInvokeEncoding.Auto).WithInitSemantics(ILTypeInit.BeforeField) - - let tdefs = EraseClosures.convIlxClosureDef cenv.g.ilxPubCloEnv tref.Enclosing td cloInfo + let tdef = + ILTypeDef(name = tref.Name, + layout = ILTypeDefLayout.Auto, + attributes = enum 0, + genericParams = ilGenParams, + customAttrs = mkILCustomAttrs(attrs @ [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Closure) ]), + fields = emptyILFields, + events= emptyILEvents, + properties = emptyILProperties, + methods= mkILMethods mdefs, + methodImpls= mkILMethodImpls mimpls, + nestedTypes=emptyILTypeDefs, + implements = ilIntfTys, + extends= Some ext, + securityDecls= emptyILSecurityDecls) + .WithSealed(true) + .WithSerializable(true) + .WithSpecialName(true) + .WithAccess(ComputeTypeAccess tref true) + .WithLayout(ILTypeDefLayout.Auto) + .WithEncoding(ILDefaultPInvokeEncoding.Auto) + .WithInitSemantics(ILTypeInit.BeforeField) + + let tdefs = EraseClosures.convIlxClosureDef cenv.g.ilxPubCloEnv tref.Enclosing tdef cloInfo tdefs and GenGenericParams cenv eenv tps = tps |> DropErasedTypars |> List.map (GenGenericParam cenv eenv) @@ -3761,20 +3768,20 @@ and GenLambdaClosure cenv (cgbuf:CodeGenBuffer) eenv isLocalTypeFunc selfv expr let ilContractMeths = [ilContractCtor; mkILGenericVirtualMethod("DirectInvoke",ILMemberAccess.Assembly,ilContractMethTyargs,[],mkILReturn ilContractFormalRetTy, MethodBody.Abstract) ] let ilContractTypeDef = - { Name = ilContractTypeRef.Name - Layout = ILTypeDefLayout.Auto - Attributes = enum 0 - GenericParams = ilContractGenericParams - CustomAttrs = mkILCustomAttrs [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Closure) ] - Fields = emptyILFields - Events= emptyILEvents - Properties = emptyILProperties - Methods= mkILMethods ilContractMeths - MethodImpls= emptyILMethodImpls - NestedTypes=emptyILTypeDefs - Implements = [] - Extends= Some cenv.g.ilg.typ_Object - SecurityDecls= emptyILSecurityDecls } + ILTypeDef(name = ilContractTypeRef.Name, + layout = ILTypeDefLayout.Auto, + attributes = enum 0, + genericParams = ilContractGenericParams, + customAttrs = mkILCustomAttrs [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Closure) ], + fields = emptyILFields, + events= emptyILEvents, + properties = emptyILProperties, + methods= mkILMethods ilContractMeths, + methodImpls= emptyILMethodImpls, + nestedTypes=emptyILTypeDefs, + implements = [], + extends= Some cenv.g.ilg.typ_Object, + securityDecls= emptyILSecurityDecls) let ilContractTypeDef = ilContractTypeDef.WithAbstract(true).WithAccess(ComputeTypeAccess ilContractTypeRef true).WithSerializable(true).WithSpecialName(true).WithLayout(ILTypeDefLayout.Auto).WithInitSemantics(ILTypeInit.BeforeField).WithEncoding(ILDefaultPInvokeEncoding.Auto) // the contract type is an abstract type and not sealed cgbuf.mgbuf.AddTypeDef(ilContractTypeRef, ilContractTypeDef, false, false, None) @@ -4700,15 +4707,15 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec,rhsExpr,_)) sta let ilAttribs = GenAttrs cenv eenv vspec.Attribs let ilTy = ilGetterMethSpec.FormalReturnType let ilPropDef = - { Name = PrettyNaming.ChopPropertyName ilGetterMethSpec.Name - Attributes = PropertyAttributes.None - SetMethod = None - GetMethod = Some ilGetterMethSpec.MethodRef - CallingConv = ILThisConvention.Static - Type = ilTy - Init = None - Args = [] - CustomAttrs = mkILCustomAttrs ilAttribs } + ILPropertyDef(name = PrettyNaming.ChopPropertyName ilGetterMethSpec.Name, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some ilGetterMethSpec.MethodRef, + callingConv = ILThisConvention.Static, + propertyType = ilTy, + init = None, + args = [], + customAttrs = mkILCustomAttrs ilAttribs) cgbuf.mgbuf.AddOrMergePropertyDef(ilGetterMethSpec.MethodRef.DeclaringTypeRef, ilPropDef,m) let ilMethodDef = @@ -4755,9 +4762,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec,rhsExpr,_)) sta else GenAttrs cenv eenv vspec.Attribs // literals have no property, so preserve all the attributes on the field itself - let ilFieldDef = - { ilFieldDef with - CustomAttrs = mkILCustomAttrs (ilAttribs @ [ cenv.g.DebuggerBrowsableNeverAttribute ]) } + let ilFieldDef = ilFieldDef.With(customAttrs = mkILCustomAttrs (ilAttribs @ [ cenv.g.DebuggerBrowsableNeverAttribute ])) [ (fspec.DeclaringTypeRef, ilFieldDef) ] @@ -4774,15 +4779,15 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec,rhsExpr,_)) sta |> List.filter (fun (Attrib(_,_,_,_,_,targets,_)) -> canTarget(targets, System.AttributeTargets.Property)) |> GenAttrs cenv eenv // property only gets attributes that target properties let ilPropDef = - { Name=ilPropName - Attributes = PropertyAttributes.None - SetMethod=if mut || cenv.opts.isInteractiveItExpr then Some ilSetterMethRef else None - GetMethod=Some ilGetterMethRef - CallingConv=ILThisConvention.Static - Type=fty - Init=None - Args = [] - CustomAttrs=mkILCustomAttrs (ilAttribs @ [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Value)]) } + ILPropertyDef(name=ilPropName, + attributes = PropertyAttributes.None, + setMethod=(if mut || cenv.opts.isInteractiveItExpr then Some ilSetterMethRef else None), + getMethod=Some ilGetterMethRef, + callingConv=ILThisConvention.Static, + propertyType=fty, + init=None, + args = [], + customAttrs=mkILCustomAttrs (ilAttribs @ [mkCompilationMappingAttr cenv.g (int SourceConstructFlags.Value)])) cgbuf.mgbuf.AddOrMergePropertyDef(ilTypeRefForProperty,ilPropDef,m) let getterMethod = @@ -5014,15 +5019,15 @@ and GenReturnInfo cenv eenv ilRetTy (retInfo : ArgReprInfo) : ILReturn = and GenPropertyForMethodDef compileAsInstance tref mdef (v:Val) (memberInfo:ValMemberInfo) ilArgTys ilPropTy ilAttrs compiledName = let name = match compiledName with | Some n -> n | _ -> v.PropertyName in (* chop "get_" *) - { Name = name - Attributes = PropertyAttributes.None - SetMethod = (if memberInfo.MemberFlags.MemberKind= MemberKind.PropertySet then Some(mkRefToILMethod(tref,mdef)) else None) - GetMethod = (if memberInfo.MemberFlags.MemberKind= MemberKind.PropertyGet then Some(mkRefToILMethod(tref,mdef)) else None) - CallingConv = (if compileAsInstance then ILThisConvention.Instance else ILThisConvention.Static) - Type = ilPropTy - Init = None - Args = ilArgTys - CustomAttrs = ilAttrs } + ILPropertyDef(name = name, + attributes = PropertyAttributes.None, + setMethod = (if memberInfo.MemberFlags.MemberKind= MemberKind.PropertySet then Some(mkRefToILMethod(tref,mdef)) else None), + getMethod = (if memberInfo.MemberFlags.MemberKind= MemberKind.PropertyGet then Some(mkRefToILMethod(tref,mdef)) else None), + callingConv = (if compileAsInstance then ILThisConvention.Instance else ILThisConvention.Static), + propertyType = ilPropTy, + init = None, + args = ilArgTys, + customAttrs = ilAttrs) and GenEventForProperty cenv eenvForMeth (mspec:ILMethodSpec) (v:Val) ilAttrsThatGoOnPrimaryItem m returnTy = let evname = v.PropertyName @@ -5031,14 +5036,14 @@ and GenEventForProperty cenv eenvForMeth (mspec:ILMethodSpec) (v:Val) ilAttrsTha let ilThisTy = mspec.DeclaringType let addMethRef = mkILMethRef (ilThisTy.TypeRef,mspec.CallingConv,"add_" + evname,0,[ilDelegateTy],ILType.Void) let removeMethRef = mkILMethRef (ilThisTy.TypeRef,mspec.CallingConv,"remove_" + evname,0,[ilDelegateTy],ILType.Void) - { Type = Some(ilDelegateTy) - Name= evname - Attributes = EventAttributes.None - AddMethod = addMethRef - RemoveMethod = removeMethRef - FireMethod= None - OtherMethods= [] - CustomAttrs = mkILCustomAttrs ilAttrsThatGoOnPrimaryItem } + ILEventDef(eventType = Some ilDelegateTy, + name= evname, + attributes = EventAttributes.None, + addMethod = addMethRef, + removeMethod = removeMethRef, + fireMethod= None, + otherMethods= [], + customAttrs = mkILCustomAttrs ilAttrsThatGoOnPrimaryItem) and ComputeFlagFixupsForMemberBinding cenv (v:Val,memberInfo:ValMemberInfo) = @@ -5205,12 +5210,15 @@ and GenMethodForBinding // Does the function have an explicit [] attribute? let isExplicitEntryPoint = HasFSharpAttribute cenv.g cenv.g.attrib_EntryPointAttribute attrs - let mdef = mdef.WithSecurity(not (List.isEmpty securityAttributes)).WithPInvoke(hasDllImport) - let mdef = mdef.WithPreserveSig(hasPreserveSigImplFlag || hasPreserveSigNamedArg).WithSynchronized(hasSynchronizedImplFlag).WithNoInlining(hasNoInliningFlag).WithAggressiveInlining(hasAggressiveInliningImplFlag) - let mdef = - { mdef with - IsEntryPoint = isExplicitEntryPoint - SecurityDecls = secDecls } + let mdef = + mdef + .WithSecurity(not (List.isEmpty securityAttributes)) + .WithPInvoke(hasDllImport) + .WithPreserveSig(hasPreserveSigImplFlag || hasPreserveSigNamedArg) + .WithSynchronized(hasSynchronizedImplFlag) + .WithNoInlining(hasNoInliningFlag) + .WithAggressiveInlining(hasAggressiveInliningImplFlag) + .With(isEntryPoint=isExplicitEntryPoint, securityDecls=secDecls) let mdef = if // operator names @@ -5237,13 +5245,13 @@ and GenMethodForBinding if memberInfo.MemberFlags.MemberKind = MemberKind.Constructor then assert (isNil ilMethTypars) let mdef = mkILCtor (access,ilParams,ilMethodBody) - let mdef = { mdef with CustomAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated) } + let mdef = mdef.With(customAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated)) EmitTheMethodDef mdef elif memberInfo.MemberFlags.MemberKind = MemberKind.ClassConstructor then assert (isNil ilMethTypars) let mdef = mkILClassCtor ilMethodBody - let mdef = { mdef with CustomAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated) } + let mdef = mdef.With(customAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated)) EmitTheMethodDef mdef // Generate virtual/override methods + method-impl information if needed @@ -5300,10 +5308,10 @@ and GenMethodForBinding cgbuf.mgbuf.AddOrMergePropertyDef(tref,ilPropDef,m) // Add the special name flag for all properties - let mdef = { mdef.WithSpecialName with CustomAttrs= mkILCustomAttrs ((GenAttrs cenv eenv attrsAppliedToGetterOrSetter) @ sourceNameAttribs @ ilAttrsCompilerGenerated) } + let mdef = mdef.WithSpecialName.With(customAttrs= mkILCustomAttrs ((GenAttrs cenv eenv attrsAppliedToGetterOrSetter) @ sourceNameAttribs @ ilAttrsCompilerGenerated)) EmitTheMethodDef mdef | _ -> - let mdef = { mdef with CustomAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated) } + let mdef = mdef.With(customAttrs= mkILCustomAttrs (ilAttrsThatGoOnPrimaryItem @ sourceNameAttribs @ ilAttrsCompilerGenerated)) EmitTheMethodDef mdef | _ -> @@ -5319,7 +5327,7 @@ and GenMethodForBinding | _ -> ilAttrsThatGoOnPrimaryItem let ilCustomAttrs = mkILCustomAttrs (ilAttrs @ sourceNameAttribs @ ilAttrsCompilerGenerated) - let mdef = { mdef with CustomAttrs= ilCustomAttrs } + let mdef = mdef.With(customAttrs= ilCustomAttrs) EmitTheMethodDef mdef @@ -5952,7 +5960,7 @@ and GenTopImpl cenv mgbuf mainInfoOpt eenv (TImplFile(qname, _, mexpr, hasExplic // generate main@ let ilMainMethodDef = let mdef = mkILNonGenericStaticMethod(mainMethName,ILMemberAccess.Public,[],mkILReturn ILType.Void, MethodBody.IL topCode) - {mdef with IsEntryPoint= true; CustomAttrs = ilAttrs } + mdef.With(isEntryPoint= true, customAttrs = ilAttrs) mgbuf.AddMethodDef(initClassTy.TypeRef,ilMainMethodDef) @@ -6062,7 +6070,7 @@ and GenAbstractBinding cenv eenv tref (vref:ValRef) = | MemberKind.ClassConstructor | MemberKind.Constructor | MemberKind.Member -> - let mdef = {mdef with CustomAttrs= mkILCustomAttrs ilAttrs } + let mdef = mdef.With(customAttrs= mkILCustomAttrs ilAttrs) [mdef], [], [] | MemberKind.PropertyGetSet -> error(Error(FSComp.SR.ilUnexpectedGetSetAnnotation(),m)) | MemberKind.PropertySet | MemberKind.PropertyGet -> @@ -6104,22 +6112,23 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = let sprintfMethSpec = mkILMethSpec(sprintfMethSpec.MethodRef,AsObject,[],[funcTy]) // Here's the body of the method. Call printf, then invoke the function it returns let callInstrs = EraseClosures.mkCallFunc cenv.g.ilxPubCloEnv (fun _ -> 0us) eenv.tyenv.Count Normalcall (Apps_app(ilThisTy, Apps_done cenv.g.ilg.typ_String)) - let ilMethodDef = mkILNonGenericVirtualMethod ("ToString",ILMemberAccess.Public,[], - mkILReturn cenv.g.ilg.typ_String, - mkMethodBody (true,[],2,nonBranchingInstrsToCode - ([ // load the hardwired format string - yield I_ldstr "%+A" - // make the printf format object - yield mkNormalNewobj newFormatMethSpec - // call sprintf - yield mkNormalCall sprintfMethSpec - // call the function returned by sprintf - yield mkLdarg0 - if ilThisTy.Boxity = ILBoxity.AsValue then - yield mkNormalLdobj ilThisTy ] @ - callInstrs), - None)) - let mdef = { ilMethodDef with CustomAttrs = mkILCustomAttrs [ cenv.g.CompilerGeneratedAttribute ] } + let mdef = + mkILNonGenericVirtualMethod ("ToString",ILMemberAccess.Public,[], + mkILReturn cenv.g.ilg.typ_String, + mkMethodBody (true,[],2,nonBranchingInstrsToCode + ([ // load the hardwired format string + yield I_ldstr "%+A" + // make the printf format object + yield mkNormalNewobj newFormatMethSpec + // call sprintf + yield mkNormalCall sprintfMethSpec + // call the function returned by sprintf + yield mkLdarg0 + if ilThisTy.Boxity = ILBoxity.AsValue then + yield mkNormalLdobj ilThisTy ] @ + callInstrs), + None)) + let mdef = mdef.With(customAttrs = mkILCustomAttrs [ cenv.g.CompilerGeneratedAttribute ]) yield mdef | None,_ -> () | _,None -> () @@ -6342,16 +6351,15 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = let literalValue = Option.map (GenFieldInit m) fspec.LiteralValue let fdef = - { Name = ilFieldName - Type = ilPropType - Attributes = enum 0 - Data = None - LiteralValue = None - Offset = ilFieldOffset - Marshal = None - CustomAttrs = mkILCustomAttrs (GenAttrs cenv eenv fattribs @ extraAttribs) } - let fdef = - fdef.WithAccess(access) + ILFieldDef(name = ilFieldName, + fieldType = ilPropType, + attributes = enum 0, + data = None, + literalValue = None, + offset = ilFieldOffset, + marshal = None, + customAttrs = mkILCustomAttrs (GenAttrs cenv eenv fattribs @ extraAttribs)) + .WithAccess(access) .WithStatic(isStatic) .WithSpecialName(ilFieldName="value__" && tycon.IsEnumTycon) .WithNotSerialized(ilNotSerialized) @@ -6371,15 +6379,15 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = let ilHasSetter = isCLIMutable || isFSharpMutable let ilFieldAttrs = GenAttrs cenv eenv propAttribs @ [mkCompilationMappingAttrWithSeqNum cenv.g (int SourceConstructFlags.Field) i] yield - { Name = ilPropName - Attributes = PropertyAttributes.None - SetMethod = (if ilHasSetter then Some(mkILMethRef(tref,ilCallingConv,"set_" + ilPropName,0,[ilPropType],ILType.Void)) else None) - GetMethod = Some(mkILMethRef(tref,ilCallingConv,"get_" + ilPropName,0,[],ilPropType)) - CallingConv = ilCallingConv.ThisConv - Type = ilPropType - Init = None - Args = [] - CustomAttrs = mkILCustomAttrs ilFieldAttrs } ] + ILPropertyDef(name= ilPropName, + attributes= PropertyAttributes.None, + setMethod= (if ilHasSetter then Some(mkILMethRef(tref,ilCallingConv,"set_" + ilPropName,0,[ilPropType],ILType.Void)) else None), + getMethod= Some(mkILMethRef(tref,ilCallingConv,"get_" + ilPropName,0,[],ilPropType)), + callingConv= ilCallingConv.ThisConv, + propertyType= ilPropType, + init= None, + args= [], + customAttrs = mkILCustomAttrs ilFieldAttrs) ] let methodDefs = [ // Generate property getter methods for those fields that have properties @@ -6520,9 +6528,9 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = match tycon.TypeReprInfo with | TILObjectRepr _ -> - let td = tycon.ILTyconRawMetadata.WithAccess(access) - {td with CustomAttrs = mkILCustomAttrs ilCustomAttrs - GenericParams = ilGenParams }, None + let tdef = tycon.ILTyconRawMetadata.WithAccess(access) + let tdef = tdef.With(customAttrs = mkILCustomAttrs ilCustomAttrs, genericParams = ilGenParams) + tdef, None | TRecdRepr _ | TFSharpObjectRepr _ as tyconRepr -> let super = superOfTycon cenv.g tycon @@ -6563,7 +6571,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = let isTheSealedAttribute = tyconRefEq cenv.g tcref cenv.g.attrib_SealedAttribute.TyconRef let tdef = tdef.WithSealed(isSealedTy cenv.g thisTy || isTheSealedAttribute).WithSerializable(isSerializable).WithAbstract(isAbstract).WithImport(isComInteropTy cenv.g thisTy) - let tdef = { tdef with MethodImpls=mkILMethodImpls methodImpls } + let tdef = tdef.With(methodImpls=mkILMethodImpls methodImpls) let tdLayout,tdEncoding = match TryFindFSharpAttribute cenv.g cenv.g.attrib_StructLayoutAttribute tycon.Attribs with @@ -6609,14 +6617,14 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = ILTypeDefLayout.Auto, ILDefaultPInvokeEncoding.Ansi // if the type's layout is Explicit, ensure that each field has a valid offset - let validateExplicit fdef = + let validateExplicit (fdef: ILFieldDef) = match fdef.Offset with // Remove field suffix "@" for pretty printing | None -> errorR(Error(FSComp.SR.ilFieldDoesNotHaveValidOffsetForStructureLayout(tdef.Name, fdef.Name.Replace("@","")), (trimRangeToLine m))) | _ -> () // if the type's layout is Sequential, no offsets should be applied - let validateSequential fdef = + let validateSequential (fdef: ILFieldDef) = match fdef.Offset with | Some _ -> errorR(Error(FSComp.SR.ilFieldHasOffsetForSequentialLayout(), (trimRangeToLine m))) | _ -> () @@ -6655,26 +6663,33 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = else ILTypeDefLayout.Auto + let cattrs = + mkILCustomAttrs (ilCustomAttrs @ + [mkCompilationMappingAttr cenv.g + (int (if hiddenRepr + then SourceConstructFlags.SumType ||| SourceConstructFlags.NonPublicRepresentation + else SourceConstructFlags.SumType)) ]) let tdef = - { Name = ilTypeName - Layout = layout - Attributes = enum 0 - GenericParams = ilGenParams - CustomAttrs = - mkILCustomAttrs (ilCustomAttrs @ - [mkCompilationMappingAttr cenv.g - (int (if hiddenRepr - then SourceConstructFlags.SumType ||| SourceConstructFlags.NonPublicRepresentation - else SourceConstructFlags.SumType)) ]) - Fields = ilFields - Events= ilEvents - Properties = ilProperties - Methods= mkILMethods ilMethods - MethodImpls= mkILMethodImpls methodImpls - NestedTypes=emptyILTypeDefs - Implements = ilIntfTys - Extends= Some (if tycon.IsStructOrEnumTycon then cenv.g.iltyp_ValueType else cenv.g.ilg.typ_Object) - SecurityDecls= emptyILSecurityDecls }.WithLayout(layout).WithSerializable(isSerializable).WithSealed(true).WithEncoding(ILDefaultPInvokeEncoding.Auto).WithAccess(access).WithInitSemantics(ILTypeInit.BeforeField) + ILTypeDef(name = ilTypeName, + layout = layout, + attributes = enum 0, + genericParams = ilGenParams, + customAttrs = cattrs, + fields = ilFields, + events= ilEvents, + properties = ilProperties, + methods= mkILMethods ilMethods, + methodImpls= mkILMethodImpls methodImpls, + nestedTypes=emptyILTypeDefs, + implements = ilIntfTys, + extends= Some (if tycon.IsStructOrEnumTycon then cenv.g.iltyp_ValueType else cenv.g.ilg.typ_Object), + securityDecls= emptyILSecurityDecls) + .WithLayout(layout) + .WithSerializable(isSerializable) + .WithSealed(true) + .WithEncoding(ILDefaultPInvokeEncoding.Auto) + .WithAccess(access) + .WithInitSemantics(ILTypeInit.BeforeField) let tdef2 = cenv.g.eraseClassUnionDef tref tdef cuinfo @@ -6697,9 +6712,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = | _ -> failwith "??" let tdef = tdef.WithHasSecurity(not (List.isEmpty securityAttrs)) - let tdef = - { tdef with - SecurityDecls = secDecls } + let tdef = tdef.With(securityDecls = secDecls) mgbuf.AddTypeDef(tref, tdef, false, false, tdefDiscards) // If a non-generic type is written with "static let" and "static do" (i.e. it has a ".cctor") @@ -6735,15 +6748,15 @@ and GenExnDef cenv mgbuf eenv m (exnc:Tycon) = let ilMethodDef = mkLdfldMethodDef (ilMethName,reprAccess,false,ilThisTy,ilFieldName,ilPropType) let ilFieldDef = IL.mkILInstanceField(ilFieldName,ilPropType, None, ILMemberAccess.Assembly) let ilPropDef = - { Name = ilPropName - Attributes = PropertyAttributes.None - SetMethod = None - GetMethod = Some(mkILMethRef(tref,ILCallingConv.Instance,ilMethName,0,[],ilPropType)) - CallingConv = ILThisConvention.Instance - Type = ilPropType - Init = None - Args = [] - CustomAttrs=mkILCustomAttrs (GenAttrs cenv eenv fld.PropertyAttribs @ [mkCompilationMappingAttrWithSeqNum cenv.g (int SourceConstructFlags.Field) i]) } + ILPropertyDef(name = ilPropName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some(mkILMethRef(tref,ILCallingConv.Instance,ilMethName,0,[],ilPropType)), + callingConv = ILThisConvention.Instance, + propertyType = ilPropType, + init = None, + args = [], + customAttrs=mkILCustomAttrs (GenAttrs cenv eenv fld.PropertyAttribs @ [mkCompilationMappingAttrWithSeqNum cenv.g (int SourceConstructFlags.Field) i])) yield (ilMethodDef,ilFieldDef,ilPropDef,(ilPropName,ilFieldName,ilPropType)) ] |> List.unzip4 diff --git a/src/fsharp/IlxGen.fsi b/src/fsharp/IlxGen.fsi index f7a5071d146..25c727eca82 100644 --- a/src/fsharp/IlxGen.fsi +++ b/src/fsharp/IlxGen.fsi @@ -89,7 +89,7 @@ type public IlxAssemblyGenerator = member GenerateCode : IlxGenOptions * TypedAssemblyAfterOptimization * Attribs * Attribs -> IlxGenResults /// Create the CAS permission sets for an assembly fragment - member CreatePermissionSets : Attrib list -> ILPermission list + member CreatePermissionSets : Attrib list -> ILSecurityDecl list /// Invert the compilation of the given value and clear the storage of the value member ClearGeneratedValue : ExecutionContext * Val -> unit diff --git a/src/fsharp/NicePrint.fs b/src/fsharp/NicePrint.fs index d3116650608..e3ad74ad0d3 100755 --- a/src/fsharp/NicePrint.fs +++ b/src/fsharp/NicePrint.fs @@ -260,7 +260,7 @@ module private PrintIL = let staticL = if f.IsStatic then WordL.keywordStatic else emptyL let name = adjustILName f.Name let nameL = wordL (tagField name) - let typL = layoutILType denv ilTyparSubst f.Type + let typL = layoutILType denv ilTyparSubst f.FieldType staticL ^^ WordL.keywordVal ^^ nameL ^^ WordL.colon ^^ typL let private layoutILEventDef denv ilTyparSubst (e: ILEventDef) = @@ -268,7 +268,7 @@ module private PrintIL = let name = adjustILName e.Name let nameL = wordL (tagEvent name) let typL = - match e.Type with + match e.EventType with | Some t -> layoutILType denv ilTyparSubst t | _ -> emptyL staticL ^^ WordL.keywordEvent ^^ nameL ^^ WordL.colon ^^ typL @@ -295,16 +295,16 @@ module private PrintIL = let typL = match p.GetMethod, p.SetMethod with - | None, None -> layoutILType denv ilTyparSubst p.Type // shouldn't happen - | Some getterRef, _ -> layoutGetterType getterRef - | None, Some setterRef -> layoutSetterType setterRef + | None, None -> layoutILType denv ilTyparSubst p.PropertyType // shouldn't happen + | Some getterRef, _ -> layoutGetterType getterRef + | None, Some setterRef -> layoutSetterType setterRef let specGetSetL = match p.GetMethod, p.SetMethod with - | None,None - | Some _, None -> emptyL - | None, Some _ -> WordL.keywordWith ^^ WordL.keywordSet - | Some _, Some _ -> WordL.keywordWith ^^ WordL.keywordGet ^^ RightL.comma ^^ WordL.keywordSet + | None,None + | Some _, None -> emptyL + | None, Some _ -> WordL.keywordWith ^^ WordL.keywordSet + | Some _, Some _ -> WordL.keywordWith ^^ WordL.keywordGet ^^ RightL.comma ^^ WordL.keywordSet staticL ^^ WordL.keywordMember ^^ nameL ^^ WordL.colon ^^ typL ^^ specGetSetL let layoutILFieldInit x = diff --git a/src/fsharp/TcGlobals.fs b/src/fsharp/TcGlobals.fs index 72c8fbb0a75..64ea4e96d6f 100755 --- a/src/fsharp/TcGlobals.fs +++ b/src/fsharp/TcGlobals.fs @@ -719,9 +719,9 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d | res -> res mkILCustomAttrs (attrs.AsList @ attribs) - let addMethodGeneratedAttrs (mdef:ILMethodDef) = {mdef with CustomAttrs = addGeneratedAttrs mdef.CustomAttrs} - let addPropertyGeneratedAttrs (pdef:ILPropertyDef) = {pdef with CustomAttrs = addGeneratedAttrs pdef.CustomAttrs} - let addFieldGeneratedAttrs (fdef:ILFieldDef) = {fdef with CustomAttrs = addGeneratedAttrs fdef.CustomAttrs} + let addMethodGeneratedAttrs (mdef:ILMethodDef) = mdef.With(customAttrs = addGeneratedAttrs mdef.CustomAttrs) + let addPropertyGeneratedAttrs (pdef:ILPropertyDef) = pdef.With(customAttrs = addGeneratedAttrs pdef.CustomAttrs) + let addFieldGeneratedAttrs (fdef:ILFieldDef) = fdef.With(customAttrs = addGeneratedAttrs fdef.CustomAttrs) let tref_DebuggerBrowsableAttribute n = let typ_DebuggerBrowsableState = @@ -738,8 +738,8 @@ type public TcGlobals(compilingFslib: bool, ilg:ILGlobals, fslibCcu: CcuThunk, d | Some res -> res let addNeverAttrs (attrs: ILAttributes) = mkILCustomAttrs (attrs.AsList @ [mkDebuggerBrowsableNeverAttribute()]) - let addPropertyNeverAttrs (pdef:ILPropertyDef) = {pdef with CustomAttrs = addNeverAttrs pdef.CustomAttrs} - let addFieldNeverAttrs (fdef:ILFieldDef) = {fdef with CustomAttrs = addNeverAttrs fdef.CustomAttrs} + let addPropertyNeverAttrs (pdef:ILPropertyDef) = pdef.With(customAttrs = addNeverAttrs pdef.CustomAttrs) + let addFieldNeverAttrs (fdef:ILFieldDef) = fdef.With(customAttrs = addNeverAttrs fdef.CustomAttrs) let mkDebuggerTypeProxyAttribute (ty : ILType) = mkILCustomAttribute ilg (findSysILTypeRef tname_DebuggerTypeProxyAttribute, [ilg.typ_Type], [ILAttribElem.TypeRef (Some ty.TypeRef)], []) let betterTyconEntries = diff --git a/src/fsharp/fsc.fs b/src/fsharp/fsc.fs index 699b6c52ec8..f0aa3d96a2f 100644 --- a/src/fsharp/fsc.fs +++ b/src/fsharp/fsc.fs @@ -1188,14 +1188,14 @@ module StaticLinker = TypeDefs = mkILTypeDefs ([ for td in fakeModule.TypeDefs do - yield {td with - Methods = - td.Methods.AsList - |> List.map (fun md -> - {md with CustomAttrs = - mkILCustomAttrs (td.CustomAttrs.AsList |> List.filter (fun ilattr -> - ilattr.Method.DeclaringType.TypeRef.FullName <> "System.Runtime.TargetedPatchingOptOutAttribute") )}) - |> mkILMethods } ])} + let meths = td.Methods.AsList + |> List.map (fun md -> + md.With(customAttrs = + mkILCustomAttrs (td.CustomAttrs.AsList |> List.filter (fun ilattr -> + ilattr.Method.DeclaringType.TypeRef.FullName <> "System.Runtime.TargetedPatchingOptOutAttribute")))) + |> mkILMethods + let td = td.With(methods=meths) + yield td.With(methods=meths) ])} //ILAsciiWriter.output_module stdout fakeModule fakeModule.TypeDefs.AsList @@ -1416,9 +1416,8 @@ module StaticLinker = | ILTypeDefAccess.Private -> ILTypeDefAccess.Nested ILMemberAccess.Private | _ -> ilOrigTypeDef.Access) else ilOrigTypeDef - { ilOrigTypeDef with - Name = ilTgtTyRef.Name - NestedTypes = mkILTypeDefs (List.map buildRelocatedGeneratedType ch) } + ilOrigTypeDef.With(name = ilTgtTyRef.Name, + nestedTypes = mkILTypeDefs (List.map buildRelocatedGeneratedType ch)) else // If there is no matching IL type definition, then make a simple container class if debugStaticLinking then printfn "Generating simple class '%s' because we didn't find an original type '%s' in a provider generated assembly" ilTgtTyRef.QualifiedName ilOrigTyRef.QualifiedName @@ -1452,7 +1451,7 @@ module StaticLinker = (ltdefs, fresh, rtdefs) | (ltdefs, Some htd, rtdefs) -> (ltdefs, htd, rtdefs) - let htd = { htd with NestedTypes = implantTypeDef true htd.NestedTypes t td } + let htd = htd.With(nestedTypes = implantTypeDef true htd.NestedTypes t td) mkILTypeDefs (ltdefs @ [htd] @ rtdefs) let newTypeDefs = @@ -1471,7 +1470,7 @@ module StaticLinker = let ilOrigTyRef = mkILNestedTyRef (ilOrigScopeRef, enc, tdef.Name) if not (ilOrigTyRefsForProviderGeneratedTypesToRelocate.ContainsKey ilOrigTyRef) then if debugStaticLinking then printfn "Keep provided type %s in place because it wasn't relocated" ilOrigTyRef.QualifiedName - yield { tdef with NestedTypes = rw (enc@[tdef.Name]) tdef.NestedTypes } ] + yield tdef.With(nestedTypes = rw (enc@[tdef.Name]) tdef.NestedTypes) ] rw [] ilModule.TypeDefs (ccu, { ilModule with TypeDefs = ilTypeDefsAfterRemovingRelocatedTypes })) diff --git a/src/fsharp/infos.fs b/src/fsharp/infos.fs index ca5cb778136..f6fb690c623 100755 --- a/src/fsharp/infos.fs +++ b/src/fsharp/infos.fs @@ -1676,7 +1676,7 @@ type ILFieldInfo = /// Get the type of the field as an IL type member x.ILFieldType = match x with - | ILFieldInfo (_,fdef) -> fdef.Type + | ILFieldInfo (_,fdef) -> fdef.FieldType #if !NO_EXTENSIONTYPING | ProvidedField(amap,fi,m) -> Import.ImportProvidedTypeAsILType amap m (fi.PApply((fun fi -> fi.FieldType),m)) #endif @@ -1684,7 +1684,7 @@ type ILFieldInfo = /// Get the type of the field as an F# type member x.FieldType(amap,m) = match x with - | ILFieldInfo (tinfo,fdef) -> ImportILTypeFromMetadata amap m tinfo.ILScopeRef tinfo.TypeInstOfRawMetadata [] fdef.Type + | ILFieldInfo (tinfo,fdef) -> ImportILTypeFromMetadata amap m tinfo.ILScopeRef tinfo.TypeInstOfRawMetadata [] fdef.FieldType #if !NO_EXTENSIONTYPING | ProvidedField(amap,fi,m) -> Import.ImportProvidedType amap m (fi.PApply((fun fi -> fi.FieldType),m)) #endif @@ -1848,7 +1848,7 @@ type ILPropInfo = /// Any type parameters of the enclosing type are instantiated in the type returned. member x.GetPropertyType (amap,m) = let (ILPropInfo (tinfo,pdef)) = x - ImportILTypeFromMetadata amap m tinfo.ILScopeRef tinfo.TypeInstOfRawMetadata [] pdef.Type + ImportILTypeFromMetadata amap m tinfo.ILScopeRef tinfo.TypeInstOfRawMetadata [] pdef.PropertyType override x.ToString() = x.ILTypeInfo.ToString() + "::" + x.PropertyName @@ -2405,8 +2405,8 @@ type EventInfo = | ILEvent(ILEventInfo(tinfo,edef)) -> // Get the delegate type associated with an IL event, taking into account the instantiation of the // declaring type. - if Option.isNone edef.Type then error (nonStandardEventError x.EventName m) - ImportILTypeFromMetadata amap m tinfo.ILScopeRef tinfo.TypeInstOfRawMetadata [] edef.Type.Value + if Option.isNone edef.EventType then error (nonStandardEventError x.EventName m) + ImportILTypeFromMetadata amap m tinfo.ILScopeRef tinfo.TypeInstOfRawMetadata [] edef.EventType.Value | FSEvent(g,p,_,_) -> FindDelegateTypeOfPropertyEvent g amap x.EventName m (p.GetPropertyType(amap,m)) diff --git a/src/ilx/EraseClosures.fs b/src/ilx/EraseClosures.fs index c8adbfff69b..92476961fe9 100644 --- a/src/ilx/EraseClosures.fs +++ b/src/ilx/EraseClosures.fs @@ -123,8 +123,8 @@ type cenv = addFieldNeverAttrs: ILFieldDef -> ILFieldDef addMethodGeneratedAttrs: ILMethodDef -> ILMethodDef } -let addMethodGeneratedAttrsToTypeDef cenv tdef = - { tdef with Methods = tdef.Methods.AsList |> List.map (fun md -> md |> cenv.addMethodGeneratedAttrs) |> mkILMethods } +let addMethodGeneratedAttrsToTypeDef cenv (tdef: ILTypeDef) = + tdef.With(methods = (tdef.Methods.AsList |> List.map (fun md -> md |> cenv.addMethodGeneratedAttrs) |> mkILMethods)) let newIlxPubCloEnv(ilg, addMethodGeneratedAttrs, addFieldGeneratedAttrs, addFieldNeverAttrs) = { ilg = ilg @@ -314,8 +314,8 @@ let convMethodBody thisClo = function | x -> x let convMethodDef thisClo (md: ILMethodDef) = - let b' = convMethodBody thisClo (md.mdBody.Contents) - {md with mdBody=mkMethBodyAux b'} + let b' = convMethodBody thisClo (md.Body.Contents) + md.With(body=mkMethBodyAux b') // -------------------------------------------------------------------- // Make fields for free variables of a type abstraction. @@ -428,8 +428,7 @@ let rec convIlxClosureDef cenv encl (td: ILTypeDef) clo = let laterCode = rewriteCodeToAccessArgsFromEnv laterCloSpec [(0, selfFreeVar)] let laterTypeDefs = convIlxClosureDef cenv encl - {td with GenericParams=laterGenericParams - Name=laterTypeName} + (td.With(genericParams=laterGenericParams, name=laterTypeName)) {clo with cloStructure=laterStruct cloFreeVars=laterFields cloCode=notlazy laterCode} @@ -479,20 +478,27 @@ let rec convIlxClosureDef cenv encl (td: ILTypeDef) clo = |> cenv.addMethodGeneratedAttrs let cloTypeDef = - { Name = td.Name - GenericParams= td.GenericParams - Attributes = td.Attributes - Implements = List.empty - NestedTypes = emptyILTypeDefs - Layout=ILTypeDefLayout.Auto - Extends= Some cenv.mkILTyFuncTy - Methods= mkILMethods ([ctorMethodDef] @ [nowApplyMethDef]) - Fields= mkILFields (mkILCloFldDefs cenv nowFields) - CustomAttrs=emptyILCustomAttrs - MethodImpls=emptyILMethodImpls - Properties=emptyILProperties - Events=emptyILEvents - SecurityDecls=emptyILSecurityDecls }.WithSpecialName(false).WithImport(false).WithHasSecurity(false).WithAbstract(false).WithSealed(true).WithInitSemantics(ILTypeInit.BeforeField).WithEncoding(ILDefaultPInvokeEncoding.Ansi) + ILTypeDef(name = td.Name, + genericParams= td.GenericParams, + attributes = td.Attributes, + implements = [], + nestedTypes = emptyILTypeDefs, + layout=ILTypeDefLayout.Auto, + extends= Some cenv.mkILTyFuncTy, + methods= mkILMethods ([ctorMethodDef] @ [nowApplyMethDef]) , + fields= mkILFields (mkILCloFldDefs cenv nowFields), + customAttrs=emptyILCustomAttrs, + methodImpls=emptyILMethodImpls, + properties=emptyILProperties, + events=emptyILEvents, + securityDecls=emptyILSecurityDecls) + .WithSpecialName(false) + .WithImport(false) + .WithHasSecurity(false) + .WithAbstract(false) + .WithSealed(true) + .WithInitSemantics(ILTypeInit.BeforeField) + .WithEncoding(ILDefaultPInvokeEncoding.Ansi) [ cloTypeDef] // CASE 2 - Term Application @@ -536,8 +542,7 @@ let rec convIlxClosureDef cenv encl (td: ILTypeDef) clo = let laterTypeDefs = convIlxClosureDef cenv encl - {td with GenericParams=laterGenericParams - Name=laterTypeName} + (td.With(genericParams=laterGenericParams, name=laterTypeName)) {clo with cloStructure=laterStruct cloFreeVars=laterFields cloCode=notlazy laterCode} @@ -570,20 +575,27 @@ let rec convIlxClosureDef cenv encl (td: ILTypeDef) clo = ILMemberAccess.Assembly) |> cenv.addMethodGeneratedAttrs - { Name = td.Name - GenericParams= td.GenericParams - Attributes = td.Attributes - Implements = [] - Layout=ILTypeDefLayout.Auto - NestedTypes = emptyILTypeDefs - Extends= Some nowEnvParentClass - Methods= mkILMethods ([ctorMethodDef] @ [nowApplyMethDef]) - Fields= mkILFields (mkILCloFldDefs cenv nowFields) - CustomAttrs=emptyILCustomAttrs - MethodImpls=emptyILMethodImpls - Properties=emptyILProperties - Events=emptyILEvents - SecurityDecls=emptyILSecurityDecls }.WithHasSecurity(false).WithSpecialName(false).WithAbstract(false).WithImport(false).WithEncoding(ILDefaultPInvokeEncoding.Ansi).WithSealed(true).WithInitSemantics(ILTypeInit.BeforeField) + ILTypeDef(name = td.Name, + genericParams= td.GenericParams, + attributes = td.Attributes, + implements = [], + layout=ILTypeDefLayout.Auto, + nestedTypes = emptyILTypeDefs, + extends= Some nowEnvParentClass, + methods= mkILMethods ([ctorMethodDef] @ [nowApplyMethDef]), + fields= mkILFields (mkILCloFldDefs cenv nowFields), + customAttrs=emptyILCustomAttrs, + methodImpls=emptyILMethodImpls, + properties=emptyILProperties, + events=emptyILEvents, + securityDecls=emptyILSecurityDecls) + .WithHasSecurity(false) + .WithSpecialName(false) + .WithAbstract(false) + .WithImport(false) + .WithEncoding(ILDefaultPInvokeEncoding.Ansi) + .WithSealed(true) + .WithInitSemantics(ILTypeInit.BeforeField) [cloTypeDef] @@ -613,13 +625,12 @@ let rec convIlxClosureDef cenv encl (td: ILTypeDef) clo = None)) let cloTypeDef = - { td with - Implements= td.Implements - Extends= (match td.Extends with None -> Some cenv.ilg.typ_Object | Some x -> Some(x)) - Name = td.Name - GenericParams= td.GenericParams - Methods= mkILMethods (ctorMethodDef :: List.map (convMethodDef (Some nowCloSpec)) td.Methods.AsList) - Fields= mkILFields (mkILCloFldDefs cenv nowFields @ td.Fields.AsList) } + td.With(implements= td.Implements, + extends= (match td.Extends with None -> Some cenv.ilg.typ_Object | Some x -> Some(x)), + name = td.Name, + genericParams= td.GenericParams, + methods= mkILMethods (ctorMethodDef :: List.map (convMethodDef (Some nowCloSpec)) td.Methods.AsList), + fields= mkILFields (mkILCloFldDefs cenv nowFields @ td.Fields.AsList)) [cloTypeDef] diff --git a/src/ilx/EraseUnions.fs b/src/ilx/EraseUnions.fs index 6eece54f247..51ae9a26e9b 100644 --- a/src/ilx/EraseUnions.fs +++ b/src/ilx/EraseUnions.fs @@ -614,15 +614,15 @@ let mkMethodsAndPropertiesForFields (addMethodGeneratedAttrs, addPropertyGenerat let basicProps = fields |> Array.map (fun field -> - { Name = adjustFieldName hasHelpers field.Name - Attributes = PropertyAttributes.None - SetMethod = None - GetMethod = Some (mkILMethRef (typ.TypeRef, ILCallingConv.Instance, "get_" + adjustFieldName hasHelpers field.Name, 0, [], field.Type)) - CallingConv = ILThisConvention.Instance - Type = field.Type - Init = None - Args = [] - CustomAttrs = field.ILField.CustomAttrs } + ILPropertyDef(name = adjustFieldName hasHelpers field.Name, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some (mkILMethRef (typ.TypeRef, ILCallingConv.Instance, "get_" + adjustFieldName hasHelpers field.Name, 0, [], field.Type)), + callingConv = ILThisConvention.Instance, + propertyType = field.Type, + init = None, + args = [], + customAttrs = field.ILField.CustomAttrs) |> addPropertyGeneratedAttrs ) |> Array.toList @@ -648,7 +648,7 @@ let convAlternativeDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addP let repr = cudefRepr // Attributes on unions get attached to the construction methods in the helpers - let addAltAttribs (mdef: ILMethodDef) = { mdef with CustomAttrs=alt.altCustomAttrs } + let addAltAttribs (mdef: ILMethodDef) = mdef.With(customAttrs=alt.altCustomAttrs) // The stdata instruction is only ever used for the F# "List" type // @@ -698,15 +698,15 @@ let convAlternativeDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addP mkMethodBody(true,[],2,nonBranchingInstrsToCode ([ mkLdarg0 ] @ mkIsData ilg (true, cuspec, num)), attr)) |> addMethodGeneratedAttrs ], - [ { Name = mkTesterName altName - Attributes = PropertyAttributes.None - SetMethod = None - GetMethod = Some (mkILMethRef (baseTy.TypeRef, ILCallingConv.Instance, "get_" + mkTesterName altName, 0, [], ilg.typ_Bool)) - CallingConv = ILThisConvention.Instance - Type = ilg.typ_Bool - Init = None - Args = [] - CustomAttrs = emptyILCustomAttrs } + [ ILPropertyDef(name = mkTesterName altName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some (mkILMethRef (baseTy.TypeRef, ILCallingConv.Instance, "get_" + mkTesterName altName, 0, [], ilg.typ_Bool)), + callingConv = ILThisConvention.Instance, + propertyType = ilg.typ_Bool, + init = None, + args = [], + customAttrs = emptyILCustomAttrs) |> addPropertyGeneratedAttrs |> addPropertyNeverAttrs ] @@ -726,15 +726,15 @@ let convAlternativeDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addP let nullaryProp = - { Name = altName - Attributes = PropertyAttributes.None - SetMethod = None - GetMethod = Some (mkILMethRef (baseTy.TypeRef, ILCallingConv.Static, "get_" + altName, 0, [], baseTy)) - CallingConv = ILThisConvention.Static - Type = baseTy - Init = None - Args = [] - CustomAttrs = emptyILCustomAttrs } + ILPropertyDef(name = altName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some (mkILMethRef (baseTy.TypeRef, ILCallingConv.Static, "get_" + altName, 0, [], baseTy)), + callingConv = ILThisConvention.Static, + propertyType = baseTy, + init = None, + args = [], + customAttrs = emptyILCustomAttrs) |> addPropertyGeneratedAttrs |> addPropertyNeverAttrs @@ -827,15 +827,15 @@ let convAlternativeDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addP let debugProxyGetterProps = fields |> Array.map (fun fdef -> - { Name = fdef.Name - Attributes = PropertyAttributes.None - SetMethod = None - GetMethod = Some(mkILMethRef(debugProxyTy.TypeRef,ILCallingConv.Instance,"get_" + fdef.Name,0,[],fdef.Type)) - CallingConv = ILThisConvention.Instance - Type = fdef.Type - Init = None - Args = [] - CustomAttrs = fdef.ILField.CustomAttrs } + ILPropertyDef(name = fdef.Name, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some(mkILMethRef(debugProxyTy.TypeRef,ILCallingConv.Instance,"get_" + fdef.Name,0,[],fdef.Type)), + callingConv = ILThisConvention.Instance, + propertyType = fdef.Type, + init = None, + args = [], + customAttrs = fdef.ILField.CustomAttrs) |> addPropertyGeneratedAttrs) |> Array.toList @@ -881,7 +881,7 @@ let convAlternativeDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addP | TailOrNull -> failwith "unreachable" ], altTy, - (basicFields |> List.map (fun fdef -> fdef.Name, fdef.Type) ), + (basicFields |> List.map (fun fdef -> fdef.Name, fdef.FieldType) ), (if cuspec.HasHelpers = AllHelpers then ILMemberAccess.Assembly else cud.cudReprAccess)) |> addMethodGeneratedAttrs @@ -1039,15 +1039,15 @@ let mkClassUnionDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addProp [ mkILNonGenericInstanceMethod("get_" + tagPropertyName,cud.cudHelpersAccess,[],mkILReturn tagFieldType,body) |> addMethodGeneratedAttrs ], - [ { Name = tagPropertyName - Attributes = PropertyAttributes.None - SetMethod = None - GetMethod = Some(mkILMethRef(baseTy.TypeRef,ILCallingConv.Instance,"get_" + tagPropertyName,0,[], tagFieldType)) - CallingConv = ILThisConvention.Instance - Type = tagFieldType - Init = None - Args = [] - CustomAttrs = emptyILCustomAttrs } + [ ILPropertyDef(name = tagPropertyName, + attributes = PropertyAttributes.None, + setMethod = None, + getMethod = Some(mkILMethRef(baseTy.TypeRef,ILCallingConv.Instance,"get_" + tagPropertyName,0,[], tagFieldType)), + callingConv = ILThisConvention.Instance, + propertyType = tagFieldType, + init = None, + args = [], + customAttrs = emptyILCustomAttrs) |> addPropertyGeneratedAttrs |> addPropertyNeverAttrs ] @@ -1065,29 +1065,36 @@ let mkClassUnionDef (addMethodGeneratedAttrs, addPropertyGeneratedAttrs, addProp if tagEnumFields.Length <= 1 then None else - Some( - { Name = "Tags" - NestedTypes = emptyILTypeDefs - GenericParams= td.GenericParams - Attributes = enum 0 - Layout=ILTypeDefLayout.Auto - Implements = [] - Extends= Some ilg.typ_Object - Methods= emptyILMethods - SecurityDecls=emptyILSecurityDecls - Fields=mkILFields tagEnumFields - MethodImpls=emptyILMethodImpls - Events=emptyILEvents - Properties=emptyILProperties - CustomAttrs= emptyILCustomAttrs }.WithNestedAccess(cud.cudReprAccess).WithAbstract(true).WithSealed(true).WithImport(false).WithEncoding(ILDefaultPInvokeEncoding.Ansi).WithHasSecurity(false)) + let tdef = + ILTypeDef(name = "Tags", + nestedTypes = emptyILTypeDefs, + genericParams= td.GenericParams, + attributes = enum 0, + layout=ILTypeDefLayout.Auto, + implements = [], + extends= Some ilg.typ_Object, + methods= emptyILMethods, + securityDecls=emptyILSecurityDecls, + fields=mkILFields tagEnumFields, + methodImpls=emptyILMethodImpls, + events=emptyILEvents, + properties=emptyILProperties, + customAttrs= emptyILCustomAttrs) + .WithNestedAccess(cud.cudReprAccess) + .WithAbstract(true) + .WithSealed(true) + .WithImport(false) + .WithEncoding(ILDefaultPInvokeEncoding.Ansi) + .WithHasSecurity(false) + Some tdef let baseTypeDef = - { td.WithInitSemantics(ILTypeInit.BeforeField) with - NestedTypes = mkILTypeDefs (Option.toList enumTypeDef @ altTypeDefs @ altDebugTypeDefs @ td.NestedTypes.AsList) - Extends= (match td.Extends with None -> Some ilg.typ_Object | _ -> td.Extends) - Methods= mkILMethods (ctorMeths @ baseMethsFromAlt @ selfMeths @ tagMeths @ altUniqObjMeths @ existingMeths) - Fields=mkILFields (selfAndTagFields @ List.map (fun (_,_,_,_,fdef,_) -> fdef) altNullaryFields @ td.Fields.AsList) - Properties=mkILProperties (tagProps @ basePropsFromAlt @ selfProps @ existingProps) } + td.WithInitSemantics(ILTypeInit.BeforeField) + .With(nestedTypes = mkILTypeDefs (Option.toList enumTypeDef @ altTypeDefs @ altDebugTypeDefs @ td.NestedTypes.AsList), + extends= (match td.Extends with None -> Some ilg.typ_Object | _ -> td.Extends), + methods= mkILMethods (ctorMeths @ baseMethsFromAlt @ selfMeths @ tagMeths @ altUniqObjMeths @ existingMeths), + fields=mkILFields (selfAndTagFields @ List.map (fun (_,_,_,_,fdef,_) -> fdef) altNullaryFields @ td.Fields.AsList), + properties=mkILProperties (tagProps @ basePropsFromAlt @ selfProps @ existingProps)) // The .cctor goes on the Cases type since that's where the constant fields for nullary constructors live |> addConstFieldInit