diff --git a/src/absil/il.fs b/src/absil/il.fs index 012a2385925..c1a8bc55b03 100644 --- a/src/absil/il.fs +++ b/src/absil/il.fs @@ -52,7 +52,7 @@ let notlazy v = Lazy<_>.CreateFromValue v /// A little ugly, but the idea is that if a data structure does not /// contain lazy values then we don't add laziness. So if the thing to map /// is already evaluated then immediately apply the function. -let lazyMap f (x:Lazy<_>) = +let lazyMap f (x: Lazy<_>) = if x.IsValueCreated then notlazy (f (x.Force())) else lazy (f (x.Force())) [] @@ -75,14 +75,14 @@ type PrimaryAssembly = // Utilities: type names // -------------------------------------------------------------------- -let splitNameAt (nm:string) idx = +let splitNameAt (nm: string) idx = if idx < 0 then failwith "splitNameAt: idx < 0" let last = nm.Length - 1 if idx > last then failwith "splitNameAt: idx > last" (nm.Substring(0, idx)), (if idx < last then nm.Substring (idx+1, last - idx) else "") -let rec splitNamespaceAux (nm:string) = +let rec splitNamespaceAux (nm: string) = match nm.IndexOf '.' with | -1 -> [nm] | idx -> @@ -111,7 +111,7 @@ let splitNamespaceToArray nm = let x = Array.ofList (splitNamespace nm) x) -let splitILTypeName (nm:string) = +let splitILTypeName (nm: string) = match nm.LastIndexOf '.' with | -1 -> [], nm | idx -> @@ -126,7 +126,7 @@ let emptyStringArray = ([| |] : string[]) // Foo.Bar,"1.0" // This is because the ImportSystemType code goes via Abstract IL type references. Ultimately this probably isn't // the best way to do things. -let splitILTypeNameWithPossibleStaticArguments (nm:string) = +let splitILTypeNameWithPossibleStaticArguments (nm: string) = let nm, suffix = match nm.IndexOf ',' with | -1 -> nm, None @@ -154,7 +154,7 @@ let unsplitTypeName (ns, n) = | [] -> String.concat "." ns + "." + n | _ -> n -let splitTypeNameRightAux (nm:string) = +let splitTypeNameRightAux (nm: string) = let idx = nm.LastIndexOf '.' if idx = -1 then None, nm else let s1, s2 = splitNameAt nm idx @@ -209,7 +209,7 @@ let b3 n = ((n >>> 24) &&& 0xFF) module SHA1 = - let inline (>>>&) (x:int) (y:int) = int32 (uint32 x >>> y) + let inline (>>>&) (x: int) (y: int) = int32 (uint32 x >>> y) let f(t, b, c, d) = if t < 20 then (b &&& c) ||| ((~~~b) &&& d) @@ -395,7 +395,7 @@ type ILAssemblyRef(data) = assemRefVersion=version assemRefLocale=locale } - static member FromAssemblyName (aname:System.Reflection.AssemblyName) = + static member FromAssemblyName (aname: System.Reflection.AssemblyName) = let locale = None @@ -419,8 +419,8 @@ type ILAssemblyRef(data) = member aref.QualifiedName = let b = new System.Text.StringBuilder(100) - let add (s:string) = (b.Append(s) |> ignore) - let addC (s:char) = (b.Append(s) |> ignore) + let add (s: string) = b.Append(s) |> ignore + let addC (s: char) = b.Append(s) |> ignore add(aref.Name) match aref.Version with | None -> () @@ -595,7 +595,7 @@ type ILTypeRef = member x.ApproxId = x.hashCode - member x.AsBoxedType (tspec:ILTypeSpec) = + member x.AsBoxedType (tspec: ILTypeSpec) = if isNil tspec.tspecInst then let v = x.asBoxedType match box v with @@ -769,7 +769,7 @@ and ILTypes = list let mkILCallSig (cc, args, ret) = { ArgTypes=args; CallingConv=cc; ReturnType=ret} -let mkILBoxedType (tspec:ILTypeSpec) = tspec.TypeRef.AsBoxedType tspec +let mkILBoxedType (tspec: ILTypeSpec) = tspec.TypeRef.AsBoxedType tspec [] type ILMethodRef = @@ -1220,7 +1220,7 @@ type ILLocalDebugInfo = [] type ILCode = { Labels: Dictionary - Instrs:ILInstr[] + Instrs: ILInstr[] Exceptions: ILExceptionSpec list Locals: ILLocalDebugInfo list } @@ -1527,7 +1527,7 @@ let mkMethBodyAux mb = ILLazyMethodBody (notlazy mb) let mkMethBodyLazyAux mb = ILLazyMethodBody mb -let typesOfILParams (ps:ILParameters) : ILTypes = ps |> List.map (fun p -> p.Type) +let typesOfILParams (ps: ILParameters) : ILTypes = ps |> List.map (fun p -> p.Type) [] type ILGenericVariance = @@ -1566,7 +1566,7 @@ let memberAccessOfFlags flags = elif f = 0x00000003 then ILMemberAccess.Assembly else ILMemberAccess.CompilerControlled -let convertMemberAccess (ilMemberAccess:ILMemberAccess) = +let convertMemberAccess (ilMemberAccess: ILMemberAccess) = match ilMemberAccess with | ILMemberAccess.Public -> MethodAttributes.Public | ILMemberAccess.Private -> MethodAttributes.Private @@ -1582,7 +1582,7 @@ let NoMetadataIdx = -1 [] type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: MethodImplAttributes, callingConv: ILCallingConv, - parameters: ILParameters, ret: ILReturn, body: ILLazyMethodBody, isEntryPoint:bool, genericParams: ILGenericParameterDefs, + parameters: ILParameters, ret: ILReturn, body: ILLazyMethodBody, isEntryPoint: bool, genericParams: ILGenericParameterDefs, securityDeclsStored: ILSecurityDeclsStored, customAttrsStored: ILAttributesStored, metadataIndex: int32) = new (name, attributes, implAttributes, callingConv, parameters, ret, body, isEntryPoint, genericParams, securityDecls, customAttrs) = @@ -1616,7 +1616,7 @@ type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: Me member x.With (?name: string, ?attributes: MethodAttributes, ?implAttributes: MethodImplAttributes, ?callingConv: ILCallingConv, ?parameters: ILParameters, ?ret: ILReturn, - ?body: ILLazyMethodBody, ?securityDecls: ILSecurityDecls, ?isEntryPoint:bool, + ?body: ILLazyMethodBody, ?securityDecls: ILSecurityDecls, ?isEntryPoint: bool, ?genericParams: ILGenericParameterDefs, ?customAttrs: ILAttributes) = ILMethodDef (name = defaultArg name x.Name, @@ -1829,7 +1829,7 @@ type ILPropertyDefs = 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) = +let convertFieldAccess (ilMemberAccess: ILMemberAccess) = match ilMemberAccess with | ILMemberAccess.Assembly -> FieldAttributes.Assembly | ILMemberAccess.CompilerControlled -> enum(0) @@ -1952,7 +1952,7 @@ type ILTypeDefKind = | Enum | Delegate -let typeKindOfFlags nm _mdefs _fdefs (super:ILType option) flags = +let typeKindOfFlags nm _mdefs _fdefs (super: ILType option) flags = if (flags &&& 0x00000020) <> 0x0 then ILTypeDefKind.Interface else let isEnum, isDelegate, isMulticastDelegate, isValueType = @@ -2001,7 +2001,7 @@ let convertEncoding encoding = | ILDefaultPInvokeEncoding.Ansi -> TypeAttributes.AnsiClass | ILDefaultPInvokeEncoding.Unicode -> TypeAttributes.UnicodeClass -let convertToNestedTypeAccess (ilMemberAccess:ILMemberAccess) = +let convertToNestedTypeAccess (ilMemberAccess: ILMemberAccess) = match ilMemberAccess with | ILMemberAccess.Assembly -> TypeAttributes.NestedAssembly | ILMemberAccess.CompilerControlled -> failwith "Method access compiler controlled." @@ -2011,7 +2011,7 @@ let convertToNestedTypeAccess (ilMemberAccess:ILMemberAccess) = | ILMemberAccess.Private -> TypeAttributes.NestedPrivate | ILMemberAccess.Public -> TypeAttributes.NestedPublic -let convertInitSemantics (init:ILTypeInit) = +let convertInitSemantics (init: ILTypeInit) = match init with | ILTypeInit.BeforeField -> TypeAttributes.BeforeFieldInit | ILTypeInit.OnAny -> enum 0 @@ -2324,7 +2324,7 @@ let mkILTySpec (tref, inst) = ILTypeSpec.Create(tref, inst) let mkILNonGenericTySpec tref = mkILTySpec (tref, []) -let mkILTyRefInTyRef (tref:ILTypeRef, nm) = +let mkILTyRefInTyRef (tref: ILTypeRef, nm) = mkILNestedTyRef (tref.Scope, tref.Enclosing@[tref.Name], nm) let mkILTy boxed tspec = @@ -2374,16 +2374,16 @@ let mkILMethSpec (mref, vc, tinst, minst) = mkILMethSpecForMethRefInTy (mref, mk let mkILMethSpecInTypeRef (tref, vc, cc, nm, args, rty, tinst, minst) = mkILMethSpec (mkILMethRef ( tref, cc, nm, List.length minst, args, rty), vc, tinst, minst) -let mkILMethSpecInTy (ty:ILType, cc, nm, args, rty, minst:ILGenericArgs) = +let mkILMethSpecInTy (ty: ILType, cc, nm, args, rty, minst: ILGenericArgs) = mkILMethSpecForMethRefInTy (mkILMethRef (ty.TypeRef, cc, nm, minst.Length, args, rty), ty, minst) let mkILNonGenericMethSpecInTy (ty, cc, nm, args, rty) = mkILMethSpecInTy (ty, cc, nm, args, rty, []) -let mkILInstanceMethSpecInTy (ty:ILType, nm, args, rty, minst) = +let mkILInstanceMethSpecInTy (ty: ILType, nm, args, rty, minst) = mkILMethSpecInTy (ty, ILCallingConv.Instance, nm, args, rty, minst) -let mkILNonGenericInstanceMethSpecInTy (ty:ILType, nm, args, rty) = +let mkILNonGenericInstanceMethSpecInTy (ty: ILType, nm, args, rty) = mkILInstanceMethSpecInTy (ty, nm, args, rty, []) let mkILStaticMethSpecInTy (ty, nm, args, rty, minst) = @@ -2409,7 +2409,7 @@ let mkILFieldRef(tref, nm, ty) = { DeclaringTypeRef=tref; Name=nm; Type=ty} let mkILFieldSpec (tref, ty) = { FieldRef= tref; DeclaringType=ty } -let mkILFieldSpecInTy (ty:ILType, nm, fty) = +let mkILFieldSpecInTy (ty: ILType, nm, fty) = mkILFieldSpec (mkILFieldRef (ty.TypeRef, nm, fty), ty) @@ -2420,7 +2420,7 @@ let andTailness x y = // Basic operations on code. // -------------------------------------------------------------------- -let formatCodeLabel (x:int) = "L"+string x +let formatCodeLabel (x: int) = "L"+string x // ++GLOBAL MUTABLE STATE (concurrency safe) let codeLabelCount = ref 0 @@ -2459,11 +2459,11 @@ let mkILSimpleTypar nm = CustomAttrsStored = storeILCustomAttrs emptyILCustomAttrs MetadataIndex = NoMetadataIdx } -let gparam_of_gactual (_ga:ILType) = mkILSimpleTypar "T" +let gparam_of_gactual (_ga: ILType) = mkILSimpleTypar "T" let mkILFormalTypars (x: ILGenericArgsList) = List.map gparam_of_gactual x -let mkILFormalGenericArgs numtypars (gparams:ILGenericParameterDefs) = +let mkILFormalGenericArgs numtypars (gparams: ILGenericParameterDefs) = List.mapi (fun n _gf -> mkILTyvarTy (uint16 (numtypars + n))) gparams let mkILFormalBoxedTy tref gparams = mkILBoxedTy tref (mkILFormalGenericArgs 0 gparams) @@ -2474,14 +2474,14 @@ let mkILFormalNamedTy bx tref gparams = mkILNamedTy bx tref (mkILFormalGenericAr // Operations on class etc. defs. // -------------------------------------------------------------------- -let mkRefForNestedILTypeDef scope (enc:ILTypeDef list, td:ILTypeDef) = +let mkRefForNestedILTypeDef scope (enc: ILTypeDef list, td: ILTypeDef) = mkILNestedTyRef(scope, (enc |> List.map (fun etd -> etd.Name)), td.Name) // -------------------------------------------------------------------- // Operations on type tables. // -------------------------------------------------------------------- -let mkILPreTypeDef (td:ILTypeDef) = +let mkILPreTypeDef (td: ILTypeDef) = let ns, n = splitILTypeName td.Name ILPreTypeDef(ns, n, NoMetadataIdx, ILTypeDefStored.Given td) let mkILPreTypeDefComputed (ns, n, f) = @@ -2684,7 +2684,7 @@ let isILBoxedTy = function ILType.Boxed _ -> true | _ -> false let isILValueTy = function ILType.Value _ -> true | _ -> false -let isPrimaryAssemblyTySpec (tspec:ILTypeSpec) n = +let isPrimaryAssemblyTySpec (tspec: ILTypeSpec) n = let tref = tspec.TypeRef let scoref = tref.Scope (tref.Name = n) && @@ -2693,10 +2693,10 @@ let isPrimaryAssemblyTySpec (tspec:ILTypeSpec) n = | ILScopeRef.Module _ -> false | ILScopeRef.Local -> true -let isILBoxedPrimaryAssemblyTy (ty:ILType) n = +let isILBoxedPrimaryAssemblyTy (ty: ILType) n = isILBoxedTy ty && isPrimaryAssemblyTySpec ty.TypeSpec n -let isILValuePrimaryAssemblyTy (ty:ILType) n = +let isILValuePrimaryAssemblyTy (ty: ILType) n = isILValueTy ty && isPrimaryAssemblyTySpec ty.TypeSpec n let isILObjectTy ty = isILBoxedPrimaryAssemblyTy ty tname_Object @@ -2745,7 +2745,7 @@ let rescopeILScopeRef scoref scoref1 = | ILScopeRef.Module _, _ -> scoref1 | _ -> scoref1 -let rescopeILTypeRef scoref (tref1:ILTypeRef) = +let rescopeILTypeRef scoref (tref1: ILTypeRef) = let scoref1 = tref1.Scope let scoref2 = rescopeILScopeRef scoref scoref1 if scoref1 === scoref2 then tref1 @@ -2754,7 +2754,7 @@ let rescopeILTypeRef scoref (tref1:ILTypeRef) = // ORIGINAL IMPLEMENTATION (too many allocations // { tspecTypeRef=rescopeILTypeRef scoref tref // tspecInst=rescopeILTypes scoref tinst } -let rec rescopeILTypeSpec scoref (tspec1:ILTypeSpec) = +let rec rescopeILTypeSpec scoref (tspec1: ILTypeSpec) = let tref1 = tspec1.TypeRef let tinst1 = tspec1.GenericArgs let tref2 = rescopeILTypeRef scoref tref1 @@ -2796,7 +2796,7 @@ and rescopeILTypes scoref i = and rescopeILCallSig scoref csig = mkILCallSig (csig.CallingConv, rescopeILTypes scoref csig.ArgTypes, rescopeILType scoref csig.ReturnType) -let rescopeILMethodRef scoref (x:ILMethodRef) = +let rescopeILMethodRef scoref (x: ILMethodRef) = { mrefParent = rescopeILTypeRef scoref x.DeclaringTypeRef mrefCallconv = x.mrefCallconv mrefGenericArity=x.mrefGenericArity @@ -2813,10 +2813,10 @@ let rescopeILFieldRef scoref x = // Instantiate polymorphism in types // -------------------------------------------------------------------- -let rec instILTypeSpecAux numFree inst (tspec:ILTypeSpec) = +let rec instILTypeSpecAux numFree inst (tspec: ILTypeSpec) = ILTypeSpec.Create(tspec.TypeRef, instILGenericArgsAux numFree inst tspec.GenericArgs) -and instILTypeAux numFree (inst:ILGenericArgs) ty = +and instILTypeAux numFree (inst: ILGenericArgs) ty = match ty with | ILType.Ptr t -> ILType.Ptr (instILTypeAux numFree inst t) | ILType.FunctionPointer t -> ILType.FunctionPointer (instILCallSigAux numFree inst t) @@ -2982,7 +2982,7 @@ let mkILClassCtor impl = // (i.e. overrides by name/signature) // -------------------------------------------------------------------- -let mk_ospec (ty:ILType, callconv, nm, genparams, formal_args, formal_ret) = +let mk_ospec (ty: ILType, callconv, nm, genparams, formal_args, formal_ret) = OverridesSpec (mkILMethRef (ty.TypeRef, callconv, nm, genparams, formal_args, formal_ret), ty) let mkILGenericVirtualMethod (nm, access, genparams, actual_args, actual_ret, impl) = @@ -3073,7 +3073,7 @@ let cdef_cctorCode2CodeOrCreate tag f (cd: ILTypeDef) = cd.With(methods = methods) -let code_of_mdef (md:ILMethodDef) = +let code_of_mdef (md: ILMethodDef) = match md.Code with | Some x -> x | None -> failwith "code_of_mdef: not IL" @@ -3081,17 +3081,17 @@ 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.FieldType) +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.FieldType) +let mkRefForILField scope (tdefs, tdef) (fdef: ILFieldDef) = mkILFieldRef (mkRefForNestedILTypeDef scope (tdefs, tdef), fdef.Name, fdef.FieldType) // Creates cctor if needed let prependInstrsToClassCtor instrs tag cd = cdef_cctorCode2CodeOrCreate tag (prependInstrsToMethod instrs) cd -let mkILField (isStatic, nm, ty, (init:ILFieldInit option), (at: byte [] option), access, isLiteral) = +let mkILField (isStatic, nm, ty, (init: ILFieldInit option), (at: byte [] option), access, isLiteral) = ILFieldDef(name=nm, fieldType=ty, attributes= @@ -3116,7 +3116,7 @@ let mkILLiteralField (nm, ty, init, at, access) = mkILField (true, nm, ty, Some // Scopes for allocating new temporary variables. // -------------------------------------------------------------------- -type ILLocalsAllocator(numPrealloc:int) = +type ILLocalsAllocator(numPrealloc: int) = let newLocals = ResizeArray() member tmps.AllocLocal loc = let locn = uint16(numPrealloc + newLocals.Count) @@ -3126,7 +3126,7 @@ type ILLocalsAllocator(numPrealloc:int) = member tmps.Close() = ResizeArray.toList newLocals -let mkILFieldsLazy l = ILFields (LazyOrderedMultiMap((fun (f:ILFieldDef) -> f.Name), l)) +let mkILFieldsLazy l = ILFields (LazyOrderedMultiMap((fun (f: ILFieldDef) -> f.Name), l)) let mkILFields l = mkILFieldsLazy (notlazy l) @@ -3148,7 +3148,7 @@ let addExportedTypeToTable (y: ILExportedTypeOrForwarder) tab = Map.add y.Name y let mkILExportedTypes l = ILExportedTypesAndForwarders (notlazy (List.foldBack addExportedTypeToTable l Map.empty)) -let mkILExportedTypesLazy (l:Lazy<_>) = ILExportedTypesAndForwarders (lazy (List.foldBack addExportedTypeToTable (l.Force()) Map.empty)) +let mkILExportedTypesLazy (l: Lazy<_>) = ILExportedTypesAndForwarders (lazy (List.foldBack addExportedTypeToTable (l.Force()) Map.empty)) let addNestedExportedTypeToTable (y: ILNestedExportedType) tab = Map.add y.Name y tab @@ -3164,7 +3164,7 @@ let mkTypeForwarder scopeRef name nested customAttrs access = let mkILNestedExportedTypes l = ILNestedExportedTypes (notlazy (List.foldBack addNestedExportedTypeToTable l Map.empty)) -let mkILNestedExportedTypesLazy (l:Lazy<_>) = +let mkILNestedExportedTypesLazy (l: Lazy<_>) = ILNestedExportedTypes (lazy (List.foldBack addNestedExportedTypeToTable (l.Force()) Map.empty)) let mkILResources l = ILResources l @@ -3315,7 +3315,7 @@ let mkILSimpleModule assemblyName modname dll subsystemVersion useHighEntropyVA // REVIEW: this function shows up on performance traces. If we eliminated the last ILX->IL rewrites from the // F# compiler we could get rid of this structured code representation from Abstract IL altogether and // never convert F# code into this form. -let buildILCode (_methName:string) lab2pc instrs tryspecs localspecs : ILCode = +let buildILCode (_methName: string) lab2pc instrs tryspecs localspecs : ILCode = { Labels = lab2pc Instrs = instrs Exceptions = tryspecs @@ -3326,7 +3326,7 @@ let buildILCode (_methName:string) lab2pc instrs tryspecs localspecs : ILCode = // Detecting Delegates // -------------------------------------------------------------------- -let mkILDelegateMethods (access) (ilg: ILGlobals) (iltyp_AsyncCallback, iltyp_IAsyncResult) (parms, rtv:ILReturn) = +let mkILDelegateMethods (access) (ilg: ILGlobals) (iltyp_AsyncCallback, iltyp_IAsyncResult) (parms, rtv: ILReturn) = let rty = rtv.Type let one nm args ret = let mdef = mkILNonGenericVirtualMethod (nm, access, args, mkILReturn ret, MethodBody.Abstract) @@ -3339,7 +3339,7 @@ let mkILDelegateMethods (access) (ilg: ILGlobals) (iltyp_AsyncCallback, iltyp_IA one "EndInvoke" [mkILParamNamed("result", iltyp_IAsyncResult)] rty ] -let mkCtorMethSpecForDelegate (ilg: ILGlobals) (ty:ILType, useUIntPtr) = +let mkCtorMethSpecForDelegate (ilg: ILGlobals) (ty: ILType, useUIntPtr) = let scoref = ty.TypeRef.Scope mkILInstanceMethSpecInTy (ty, ".ctor", [rescopeILType scoref ilg.typ_Object rescopeILType scoref (if useUIntPtr then ilg.typ_UIntPtr else ilg.typ_IntPtr)], @@ -3352,7 +3352,7 @@ type ILEnumInfo = let getTyOfILEnumInfo info = info.enumType let computeILEnumInfo (mdName, mdFields: ILFieldDefs) = - match (List.partition (fun (fd:ILFieldDef) -> fd.IsStatic) mdFields.AsList) with + match (List.partition (fun (fd: ILFieldDef) -> fd.IsStatic) mdFields.AsList) with | staticFields, [vfd] -> { 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"))) } @@ -3416,9 +3416,9 @@ let sigptr_get_u64 bytes sigptr = let u, sigptr = sigptr_get_i64 bytes sigptr uint64 u, sigptr -let float32_of_bits (x:int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) +let float32_of_bits (x: int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) -let float_of_bits (x:int64) = System.BitConverter.Int64BitsToDouble(x) +let float_of_bits (x: int64) = System.BitConverter.Int64BitsToDouble(x) let sigptr_get_ieee32 bytes sigptr = let u, sigptr = sigptr_get_i32 bytes sigptr @@ -3428,7 +3428,7 @@ let sigptr_get_ieee64 bytes sigptr = let u, sigptr = sigptr_get_i64 bytes sigptr float_of_bits u, sigptr -let sigptr_get_intarray n (bytes:byte[]) sigptr = +let sigptr_get_intarray n (bytes: byte[]) sigptr = let res = Bytes.zeroCreate n for i = 0 to n - 1 do res.[i] <- bytes.[sigptr + i] @@ -3485,7 +3485,7 @@ let z_unsigned_int n = byte ((n >>>& 8) &&& 0xFF) byte (n &&& 0xFF) |] -let string_as_utf8_bytes (s:string) = System.Text.Encoding.UTF8.GetBytes s +let string_as_utf8_bytes (s: string) = System.Text.Encoding.UTF8.GetBytes s (* Little-endian encoding of int64 *) let dw7 n = byte ((n >>> 56) &&& 0xFFL) @@ -3504,7 +3504,7 @@ let dw1 n = byte ((n >>> 8) &&& 0xFFL) let dw0 n = byte (n &&& 0xFFL) -let u8AsBytes (i:byte) = [| i |] +let u8AsBytes (i: byte) = [| i |] let u16AsBytes x = let n = (int x) in [| byte (b0 n); byte (b1 n) |] @@ -3512,17 +3512,17 @@ let i32AsBytes i = [| byte (b0 i); byte (b1 i); byte (b2 i); byte (b3 i) |] let i64AsBytes i = [| dw0 i; dw1 i; dw2 i; dw3 i; dw4 i; dw5 i; dw6 i; dw7 i |] -let i8AsBytes (i:sbyte) = u8AsBytes (byte i) +let i8AsBytes (i: sbyte) = u8AsBytes (byte i) -let i16AsBytes (i:int16) = u16AsBytes (uint16 i) +let i16AsBytes (i: int16) = u16AsBytes (uint16 i) -let u32AsBytes (i:uint32) = i32AsBytes (int32 i) +let u32AsBytes (i: uint32) = i32AsBytes (int32 i) -let u64AsBytes (i:uint64) = i64AsBytes (int64 i) +let u64AsBytes (i: uint64) = i64AsBytes (int64 i) -let bits_of_float32 (x:float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) +let bits_of_float32 (x: float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) -let bits_of_float (x:float) = System.BitConverter.DoubleToInt64Bits(x) +let bits_of_float (x: float) = System.BitConverter.DoubleToInt64Bits(x) let ieee32AsBytes i = i32AsBytes (bits_of_float32 i) @@ -3675,7 +3675,7 @@ let encodeCustomAttrNamedArg ilg (nm, ty, prop, elem) = yield! encodeCustomAttrString nm yield! encodeCustomAttrValue ilg ty elem |] -let encodeCustomAttrArgs (ilg: ILGlobals) (mspec:ILMethodSpec) (fixedArgs: list<_>) (namedArgs: list<_>) = +let encodeCustomAttrArgs (ilg: ILGlobals) (mspec: ILMethodSpec) (fixedArgs: list<_>) (namedArgs: list<_>) = let argtys = mspec.MethodRef.ArgTypes [| yield! [| 0x01uy; 0x00uy; |] for (argty, fixedArg) in Seq.zip argtys fixedArgs do @@ -3684,11 +3684,11 @@ let encodeCustomAttrArgs (ilg: ILGlobals) (mspec:ILMethodSpec) (fixedArgs: list< for namedArg in namedArgs do yield! encodeCustomAttrNamedArg ilg namedArg |] -let encodeCustomAttr (ilg: ILGlobals) (mspec:ILMethodSpec, fixedArgs: list<_>, namedArgs: list<_>) = +let encodeCustomAttr (ilg: ILGlobals) (mspec: ILMethodSpec, fixedArgs: list<_>, namedArgs: list<_>) = let args = encodeCustomAttrArgs ilg mspec fixedArgs namedArgs ILAttribute.Encoded (mspec, args, fixedArgs @ (namedArgs |> List.map (fun (_, _, _, e) -> e))) -let mkILCustomAttribMethRef (ilg: ILGlobals) (mspec:ILMethodSpec, fixedArgs: list<_>, namedArgs: list<_>) = +let mkILCustomAttribMethRef (ilg: ILGlobals) (mspec: ILMethodSpec, fixedArgs: list<_>, namedArgs: list<_>) = encodeCustomAttr ilg (mspec, fixedArgs, namedArgs) let mkILCustomAttribute ilg (tref, argtys, argvs, propvs) = @@ -3716,7 +3716,7 @@ let mkPermissionSet (ilg: ILGlobals) (action, attributes: list<(ILTypeRef * (str let bytes = [| yield (byte '.') yield! z_unsigned_int attributes.Length - for (tref:ILTypeRef, props) in attributes do + for (tref: ILTypeRef, props) in attributes do yield! encodeCustomAttrString tref.QualifiedName let bytes = [| yield! z_unsigned_int props.Length @@ -4006,8 +4006,8 @@ let emptyILRefs = ModuleReferences = [] } (* Now find references. *) -let refs_of_assemblyRef (s:ILReferencesAccumulator) x = s.refsA.Add x |> ignore -let refs_of_modref (s:ILReferencesAccumulator) x = s.refsM.Add x |> ignore +let refs_of_assemblyRef (s: ILReferencesAccumulator) x = s.refsA.Add x |> ignore +let refs_of_modref (s: ILReferencesAccumulator) x = s.refsM.Add x |> ignore let refs_of_scoref s x = match x with @@ -4015,7 +4015,7 @@ let refs_of_scoref s x = | ILScopeRef.Assembly assemblyRef -> refs_of_assemblyRef s assemblyRef | ILScopeRef.Module modref -> refs_of_modref s modref -let refs_of_tref s (x:ILTypeRef) = refs_of_scoref s x.Scope +let refs_of_tref s (x: ILTypeRef) = refs_of_scoref s x.Scope let rec refs_of_typ s x = match x with @@ -4027,14 +4027,14 @@ let rec refs_of_typ s x = | ILType.FunctionPointer mref -> refs_of_callsig s mref and refs_of_inst s i = refs_of_tys s i -and refs_of_tspec s (x:ILTypeSpec) = refs_of_tref s x.TypeRef; refs_of_inst s x.GenericArgs +and refs_of_tspec s (x: ILTypeSpec) = refs_of_tref s x.TypeRef; refs_of_inst s x.GenericArgs and refs_of_callsig s csig = refs_of_tys s csig.ArgTypes; refs_of_typ s csig.ReturnType and refs_of_genparam s x = refs_of_tys s x.Constraints and refs_of_genparams s b = List.iter (refs_of_genparam s) b and refs_of_dloc s ts = refs_of_tref s ts -and refs_of_mref s (x:ILMethodRef) = +and refs_of_mref s (x: ILMethodRef) = refs_of_dloc s x.DeclaringTypeRef refs_of_tys s x.mrefArgs refs_of_typ s x.mrefReturn @@ -4122,7 +4122,7 @@ and refs_of_mdef s (md: ILMethodDef) = and refs_of_param s p = refs_of_typ s p.Type -and refs_of_return s (rt:ILReturn) = refs_of_typ s rt.Type +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 @@ -4257,7 +4257,7 @@ let compareILVersions (a1, a2, a3, a4) ((b1, b2, b3, b4) : ILVersionInfo) = let unscopeILTypeRef (x: ILTypeRef) = ILTypeRef.Create(ILScopeRef.Local, x.Enclosing, x.Name) -let rec unscopeILTypeSpec (tspec:ILTypeSpec) = +let rec unscopeILTypeSpec (tspec: ILTypeSpec) = let tref = tspec.TypeRef let tinst = tspec.GenericArgs let tref = unscopeILTypeRef tref @@ -4281,7 +4281,7 @@ and unscopeILTypes i = and unscopeILCallSig csig = mkILCallSig (csig.CallingConv, unscopeILTypes csig.ArgTypes, unscopeILType csig.ReturnType) -let resolveILMethodRefWithRescope r (td: ILTypeDef) (mref:ILMethodRef) = +let resolveILMethodRefWithRescope r (td: ILTypeDef) (mref: ILMethodRef) = let args = mref.ArgTypes let nargs = args.Length let nm = mref.Name diff --git a/src/absil/illib.fs b/src/absil/illib.fs index 94bf28c6a93..71946a24910 100644 --- a/src/absil/illib.fs +++ b/src/absil/illib.fs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. module public FSharp.Compiler.AbstractIL.Internal.Library #nowarn "1178" // The struct, record or union type 'internal_instr_extension' is not structurally comparable because the type @@ -18,7 +18,7 @@ open Microsoft.FSharp.Core.ReflectionAdapters // Logical shift right treating int32 as unsigned integer. // Code that uses this should probably be adjusted to use unsigned integer types. -let (>>>&) (x:int32) (n:int32) = int32 (uint32 x >>> n) +let (>>>&) (x: int32) (n: int32) = int32 (uint32 x >>> n) let notlazy v = Lazy<_>.CreateFromValue v @@ -90,15 +90,15 @@ let notFound() = raise (KeyNotFoundException()) module Order = let orderBy (p : 'T -> 'U) = - { new IComparer<'T> with member __.Compare(x,xx) = compare (p x) (p xx) } + { new IComparer<'T> with member __.Compare(x, xx) = compare (p x) (p xx) } let orderOn p (pxOrder: IComparer<'U>) = - { new IComparer<'T> with member __.Compare(x,xx) = pxOrder.Compare (p x, p xx) } + { new IComparer<'T> with member __.Compare(x, xx) = pxOrder.Compare (p x, p xx) } - let toFunction (pxOrder: IComparer<'U>) x y = pxOrder.Compare(x,y) + let toFunction (pxOrder: IComparer<'U>) x y = pxOrder.Compare(x, y) //------------------------------------------------------------------------- -// Library: arrays,lists,options,resizearrays +// Library: arrays, lists, options, resizearrays //------------------------------------------------------------------------- module Array = @@ -122,7 +122,7 @@ module Array = let order (eltOrder: IComparer<'T>) = { new IComparer> with - member __.Compare(xs,ys) = + member __.Compare(xs, ys) = let c = compare xs.Length ys.Length if c <> 0 then c else let rec loop i = @@ -143,7 +143,7 @@ module Array = loop p l 0 let existsTrue (arr: bool[]) = - let rec loop n = (n < arr.Length) && (arr.[n] || loop (n+1)) + let rec loop n = (n < arr.Length) && (arr.[n] || loop (n+1)) loop 0 let findFirstIndexWhereTrue (arr: _[]) p = @@ -249,10 +249,10 @@ module Option = let mapFold f s opt = match opt with - | None -> None,s + | None -> None, s | Some x -> - let x',s' = f s x - Some x',s' + let x2, s2 = f s x + Some x2, s2 let attempt (f: unit -> 'T) = try Some (f()) with _ -> None @@ -267,7 +267,7 @@ module List = let sortWithOrder (c: IComparer<'T>) elements = List.sortWith (Order.toFunction c) elements let splitAfter n l = - let rec split_after_acc n l1 l2 = if n <= 0 then List.rev l1,l2 else split_after_acc (n-1) ((List.head l2):: l1) (List.tail l2) + let rec split_after_acc n l1 l2 = if n <= 0 then List.rev l1, l2 else split_after_acc (n-1) ((List.head l2):: l1) (List.tail l2) split_after_acc n [] l let existsi f xs = @@ -285,17 +285,17 @@ module List = let rec findi n f l = match l with | [] -> None - | h::t -> if f h then Some (h,n) else findi (n+1) f t + | h::t -> if f h then Some (h, n) else findi (n+1) f t let rec drop n l = match l with - | [] -> [] + | [] -> [] | _::xs -> if n=0 then l else drop (n-1) xs let splitChoose select l = let rec ch acc1 acc2 l = match l with - | [] -> List.rev acc1,List.rev acc2 + | [] -> List.rev acc1, List.rev acc2 | x::xs -> match select x with | Choice1Of2 sx -> ch (sx::acc1) acc2 xs @@ -304,8 +304,8 @@ module List = ch [] [] l let rec checkq l1 l2 = - match l1,l2 with - | h1::t1,h2::t2 -> h1 === h2 && checkq t1 t2 + match l1, l2 with + | h1::t1, h2::t2 -> h1 === h2 && checkq t1 t2 | _ -> true let mapq (f: 'T -> 'T) inp = @@ -334,8 +334,8 @@ module List = | [] -> Debug.Assert(false, "empty list") invalidArg "l" "empty list" - | [h] -> List.rev acc,h - | h::t -> loop (h::acc) t + | [h] -> List.rev acc, h + | h::t -> loop (h::acc) t loop [] l let tryRemove f inp = @@ -343,25 +343,25 @@ module List = match l with | [] -> None | h :: t -> if f h then Some (h, List.rev acc @ t) else loop (h::acc) t - loop [] inp + loop [] inp let headAndTail l = match l with | [] -> Debug.Assert(false, "empty list") failwith "List.headAndTail" - | h::t -> h,t + | h::t -> h, t let zip4 l1 l2 l3 l4 = - List.zip l1 (List.zip3 l2 l3 l4) |> List.map (fun (x1,(x2,x3,x4)) -> (x1,x2,x3,x4)) + List.zip l1 (List.zip3 l2 l3 l4) |> List.map (fun (x1, (x2, x3, x4)) -> (x1, x2, x3, x4)) let unzip4 l = - let a,b,cd = List.unzip3 (List.map (fun (x,y,z,w) -> (x,y,(z,w))) l) - let c,d = List.unzip cd - a,b,c,d + let a, b, cd = List.unzip3 (List.map (fun (x, y, z, w) -> (x, y, (z, w))) l) + let c, d = List.unzip cd + a, b, c, d let rec iter3 f l1 l2 l3 = - match l1,l2,l3 with + match l1, l2, l3 with | h1::t1, h2::t2, h3::t3 -> f h1 h2 h3; iter3 f t1 t2 t3 | [], [], [] -> () | _ -> failwith "iter3" @@ -369,20 +369,21 @@ module List = let takeUntil p l = let rec loop acc l = match l with - | [] -> List.rev acc,[] + | [] -> List.rev acc, [] | x::xs -> if p x then List.rev acc, l else loop (x::acc) xs loop [] l let order (eltOrder: IComparer<'T>) = { new IComparer> with - member __.Compare(xs,ys) = + member __.Compare(xs, ys) = let rec loop xs ys = - match xs,ys with - | [],[] -> 0 - | [],_ -> -1 - | _,[] -> 1 - | x::xs,y::ys -> let cxy = eltOrder.Compare(x,y) - if cxy=0 then loop xs ys else cxy + match xs, ys with + | [], [] -> 0 + | [], _ -> -1 + | _, [] -> 1 + | x::xs, y::ys -> + let cxy = eltOrder.Compare(x, y) + if cxy=0 then loop xs ys else cxy loop xs ys } module FrontAndBack = @@ -395,12 +396,12 @@ module List = let rec assoc x l = match l with | [] -> indexNotFound() - | ((h,r)::t) -> if x = h then r else assoc x t + | ((h, r)::t) -> if x = h then r else assoc x t let rec memAssoc x l = match l with | [] -> false - | ((h,_)::t) -> x = h || memAssoc x t + | ((h, _)::t) -> x = h || memAssoc x t let rec memq x l = match l with @@ -443,7 +444,7 @@ module List = let existsSquared f xss = xss |> List.exists (fun xs -> xs |> List.exists (fun x -> f x)) - let mapiFoldSquared f z xss = mapFoldSquared f z (xss |> mapiSquared (fun i j x -> (i,j,x))) + let mapiFoldSquared f z xss = mapFoldSquared f z (xss |> mapiSquared (fun i j x -> (i, j, x))) module ResizeArray = @@ -511,34 +512,34 @@ type String with module String = let make (n: int) (c: char) : string = new String(c, n) - let get (str:string) i = str.[i] + let get (str: string) i = str.[i] - let sub (s:string) (start:int) (len:int) = s.Substring(start,len) + let sub (s: string) (start: int) (len: int) = s.Substring(start, len) - let contains (s:string) (c:char) = s.IndexOf(c) <> -1 + let contains (s: string) (c: char) = s.IndexOf(c) <> -1 let order = LanguagePrimitives.FastGenericComparer - let lowercase (s:string) = + let lowercase (s: string) = s.ToLowerInvariant() - let uppercase (s:string) = + let uppercase (s: string) = s.ToUpperInvariant() - let isUpper (s:string) = + let isUpper (s: string) = s.Length >= 1 && Char.IsUpper s.[0] && not (Char.IsLower s.[0]) - let capitalize (s:string) = + let capitalize (s: string) = if s.Length = 0 then s else uppercase s.[0..0] + s.[ 1.. s.Length - 1 ] - let uncapitalize (s:string) = - if s.Length = 0 then s + let uncapitalize (s: string) = + if s.Length = 0 then s else lowercase s.[0..0] + s.[ 1.. s.Length - 1 ] - let dropPrefix (s:string) (t:string) = s.[t.Length..s.Length - 1] + let dropPrefix (s: string) (t: string) = s.[t.Length..s.Length - 1] - let dropSuffix (s:string) (t:string) = s.[0..s.Length - t.Length - 1] + let dropSuffix (s: string) (t: string) = s.[0..s.Length - t.Length - 1] let inline toCharArray (str: string) = str.ToCharArray() @@ -571,7 +572,7 @@ module String = /// Splits a string into substrings based on the strings in the array separators let split options (separator: string []) (value: string) = - if isNull value then null else value.Split(separator, options) + if isNull value then null else value.Split(separator, options) let (|StartsWith|_|) pattern value = if String.IsNullOrWhiteSpace value then @@ -601,7 +602,7 @@ module String = |] module Dictionary = - let inline newWithSize (size: int) = Dictionary<_,_>(size, HashIdentity.Structural) + let inline newWithSize (size: int) = Dictionary<_, _>(size, HashIdentity.Structural) [] type DictionaryExtensions() = @@ -636,13 +637,13 @@ type ExecutionToken = interface end /// the lifetime of stack-based calls. This is not checked, it is a discipline within the compiler code. type CompilationThreadToken() = interface ExecutionToken -/// Represents a place where we are stating that execution on the compilation thread is required. The +/// Represents a place where we are stating that execution on the compilation thread is required. The /// reason why will be documented in a comment in the code at the callsite. let RequireCompilationThread (_ctok: CompilationThreadToken) = () /// Represents a place in the compiler codebase where we are passed a CompilationThreadToken unnecessarily. /// This reprents code that may potentially not need to be executed on the compilation thread. -let DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent (_ctok: CompilationThreadToken) = () +let DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent (_ctok: CompilationThreadToken) = () /// Represents a place in the compiler codebase where we assume we are executing on a compilation thread let AssumeCompilationThreadWithoutEvidence () = Unchecked.defaultof @@ -679,7 +680,7 @@ module ResultOrException = let success a = Result a - let raze (b:exn) = Exception b + let raze (b: exn) = Exception b // map let (|?>) res f = @@ -787,20 +788,20 @@ module Cancellable = ValueOrCancelled.Value (Choice2Of2 err)) /// Implement try/finally for a cancellable computation - let tryFinally e compensation = - catch e |> bind (fun res -> + let tryFinally e compensation = + catch e |> bind (fun res -> compensation() match res with Choice1Of2 r -> ret r | Choice2Of2 err -> raise err) /// Implement try/with for a cancellable computation - let tryWith e handler = - catch e |> bind (fun res -> + let tryWith e handler = + catch e |> bind (fun res -> match res with Choice1Of2 r -> ret r | Choice2Of2 err -> handler err) - // Run the cancellable computation within an Async computation. This isn't actually used in the codebase, but left + // Run the cancellable computation within an Async computation. This isn't actually used in the codebase, but left // here in case we need it in the future // - // let toAsync e = + // let toAsync e = // async { // let! ct = Async.CancellationToken // return! @@ -815,19 +816,19 @@ module Cancellable = type CancellableBuilder() = - member x.Bind(e,k) = Cancellable.bind k e + member x.Bind(e, k) = Cancellable.bind k e member x.Return(v) = Cancellable.ret v member x.ReturnFrom(v) = v - member x.Combine(e1,e2) = e1 |> Cancellable.bind (fun () -> e2) + member x.Combine(e1, e2) = e1 |> Cancellable.bind (fun () -> e2) - member x.TryWith(e,handler) = Cancellable.tryWith e handler + member x.TryWith(e, handler) = Cancellable.tryWith e handler - member x.Using(resource,e) = Cancellable.tryFinally (e resource) (fun () -> (resource :> IDisposable).Dispose()) + member x.Using(resource, e) = Cancellable.tryFinally (e resource) (fun () -> (resource :> IDisposable).Dispose()) - member x.TryFinally(e,compensation) = Cancellable.tryFinally e compensation + member x.TryFinally(e, compensation) = Cancellable.tryFinally e compensation member x.Delay(f) = Cancellable.delay f @@ -859,7 +860,7 @@ module Eventually = | Done x -> Done (Operators.box x) | NotYetDone (work) -> NotYetDone (fun ctok -> box (work ctok)) - let rec forceWhile ctok check e = + let rec forceWhile ctok check e = match e with | Done x -> Some(x) | NotYetDone (work) -> @@ -910,7 +911,7 @@ module Eventually = | NotYetDone work -> NotYetDone (fun ctok -> bind k (work ctok)) let fold f acc seq = - (Done acc,seq) ||> Seq.fold (fun acc x -> acc |> bind (fun acc -> f acc x)) + (Done acc, seq) ||> Seq.fold (fun acc x -> acc |> bind (fun acc -> f acc x)) let rec catch e = match e with @@ -924,7 +925,7 @@ module Eventually = let delay (f: unit -> Eventually<'T>) = NotYetDone (fun _ctok -> f()) - let tryFinally e compensation = + let tryFinally e compensation = catch (e) |> bind (fun res -> compensation() @@ -932,7 +933,7 @@ module Eventually = | Result v -> Eventually.Done v | Exception e -> raise e) - let tryWith e handler = + let tryWith e handler = catch e |> bind (function Result v -> Done v | Exception e -> handler e) @@ -942,17 +943,17 @@ module Eventually = type EventuallyBuilder() = - member x.Bind(e,k) = Eventually.bind k e + member x.Bind(e, k) = Eventually.bind k e member x.Return(v) = Eventually.Done v member x.ReturnFrom(v) = v - member x.Combine(e1,e2) = e1 |> Eventually.bind (fun () -> e2) + member x.Combine(e1, e2) = e1 |> Eventually.bind (fun () -> e2) - member x.TryWith(e,handler) = Eventually.tryWith e handler + member x.TryWith(e, handler) = Eventually.tryWith e handler - member x.TryFinally(e,compensation) = Eventually.tryFinally e compensation + member x.TryFinally(e, compensation) = Eventually.tryFinally e compensation member x.Delay(f) = Eventually.delay f @@ -970,7 +971,7 @@ let _ = eventually { use x = null in return 1 } /// Generates unique stamps type UniqueStampGenerator<'T when 'T : equality>() = - let encodeTab = new Dictionary<'T,int>(HashIdentity.Structural) + let encodeTab = new Dictionary<'T, int>(HashIdentity.Structural) let mutable nItems = 0 let encode str = match encodeTab.TryGetValue(str) with @@ -981,24 +982,24 @@ type UniqueStampGenerator<'T when 'T : equality>() = nItems <- nItems + 1 idx - member this.Encode(str) = encode str + member this.Encode(str) = encode str member this.Table = encodeTab.Keys /// memoize tables (all entries cached, never collected) -type MemoizationTable<'T,'U>(compute: 'T -> 'U, keyComparer: IEqualityComparer<'T>, ?canMemoize) = +type MemoizationTable<'T, 'U>(compute: 'T -> 'U, keyComparer: IEqualityComparer<'T>, ?canMemoize) = - let table = new Dictionary<'T,'U>(keyComparer) + let table = new Dictionary<'T, 'U>(keyComparer) member t.Apply(x) = if (match canMemoize with None -> true | Some f -> f x) then let mutable res = Unchecked.defaultof<'U> - let ok = table.TryGetValue(x,&res) + let ok = table.TryGetValue(x, &res) if ok then res else lock table (fun () -> let mutable res = Unchecked.defaultof<'U> - let ok = table.TryGetValue(x,&res) + let ok = table.TryGetValue(x, &res) if ok then res else let res = compute x @@ -1009,7 +1010,7 @@ type MemoizationTable<'T,'U>(compute: 'T -> 'U, keyComparer: IEqualityComparer<' exception UndefinedException -type LazyWithContextFailure(exn:exn) = +type LazyWithContextFailure(exn: exn) = static let undefined = new LazyWithContextFailure(UndefinedException) @@ -1021,7 +1022,7 @@ type LazyWithContextFailure(exn:exn) = /// on forcing back to at least one sensible user location [] [] -type LazyWithContext<'T,'ctxt> = +type LazyWithContext<'T, 'ctxt> = { /// This field holds the result of a successful computation. It's initial value is Unchecked.defaultof mutable value : 'T @@ -1032,12 +1033,12 @@ type LazyWithContext<'T,'ctxt> = /// A helper to ensure we rethrow the "original" exception findOriginalException : exn -> exn } - static member Create(f: ('ctxt->'T), findOriginalException) : LazyWithContext<'T,'ctxt> = + static member Create(f: ('ctxt->'T), findOriginalException) : LazyWithContext<'T, 'ctxt> = { value = Unchecked.defaultof<'T> funcOrException = box f findOriginalException = findOriginalException } - static member NotLazy(x:'T) : LazyWithContext<'T,'ctxt> = + static member NotLazy(x:'T) : LazyWithContext<'T, 'ctxt> = { value = x funcOrException = null findOriginalException = id } @@ -1046,7 +1047,7 @@ type LazyWithContext<'T,'ctxt> = member x.IsForced = (match x.funcOrException with null -> true | _ -> false) - member x.Force(ctxt:'ctxt) = + member x.Force(ctxt:'ctxt) = match x.funcOrException with | null -> x.value | _ -> @@ -1079,13 +1080,15 @@ type LazyWithContext<'T,'ctxt> = /// Intern tables to save space. module Tables = let memoize f = - let t = new Dictionary<_,_>(1000, HashIdentity.Structural) + let t = new Dictionary<_, _>(1000, HashIdentity.Structural) fun x -> let mutable res = Unchecked.defaultof<_> if t.TryGetValue(x, &res) then res else - res <- f x; t.[x] <- res; res + res <- f x + t.[x] <- res + res /// Interface that defines methods for comparing objects using partial equality relation type IPartialEqualityComparer<'T> = @@ -1106,14 +1109,14 @@ module IPartialEqualityComparer = type private WrapType<'T> = Wrap of 'T // Like Seq.distinctBy but only filters out duplicates for some of the elements - let partialDistinctBy (per:IPartialEqualityComparer<'T>) seq = + let partialDistinctBy (per: IPartialEqualityComparer<'T>) seq = let wper = { new IPartialEqualityComparer> with member __.InEqualityRelation (Wrap x) = per.InEqualityRelation (x) member __.Equals(Wrap x, Wrap y) = per.Equals(x, y) member __.GetHashCode (Wrap x) = per.GetHashCode(x) } // Wrap a Wrap _ around all keys in case the key type is itself a type using null as a representation - let dict = Dictionary,obj>(wper) + let dict = Dictionary, obj>(wper) seq |> List.filter (fun v -> let key = Wrap(v) if (per.InEqualityRelation(v)) then @@ -1124,11 +1127,11 @@ module IPartialEqualityComparer = // Library: Name maps //------------------------------------------------------------------------ -type NameMap<'T> = Map +type NameMap<'T> = Map type NameMultiMap<'T> = NameMap<'T list> -type MultiMap<'T,'U when 'T : comparison> = Map<'T,'U list> +type MultiMap<'T, 'U when 'T : comparison> = Map<'T, 'U list> [] module NameMap = @@ -1137,7 +1140,7 @@ module NameMap = let range m = List.rev (Map.foldBack (fun _ x sofar -> x :: sofar) m []) - let foldBack f (m:NameMap<'T>) z = Map.foldBack f m z + let foldBack f (m: NameMap<'T>) z = Map.foldBack f m z let forall f m = Map.foldBack (fun x y sofar -> sofar && f x y) m true @@ -1160,8 +1163,8 @@ module NameMap = /// Union entries by identical key, using the provided function to union sets of values let union unionf (ms: NameMap<_> seq) = seq { for m in ms do yield! m } - |> Seq.groupBy (fun (KeyValue(k,_v)) -> k) - |> Seq.map (fun (k,es) -> (k,unionf (Seq.map (fun (KeyValue(_k,v)) -> v) es))) + |> Seq.groupBy (fun (KeyValue(k, _v)) -> k) + |> Seq.map (fun (k, es) -> (k, unionf (Seq.map (fun (KeyValue(_k, v)) -> v) es))) |> Map.ofSeq /// For every entry in m2 find an entry in m1 and fold @@ -1171,7 +1174,7 @@ module NameMap = let suball2 errf p m1 m2 = subfold2 errf (fun _ x1 x2 acc -> p x1 x2 && acc) m1 m2 true let mapFold f s (l: NameMap<'T>) = - Map.foldBack (fun x y (l',s') -> let y',s'' = f s' x y in Map.add x y' l',s'') l (Map.empty,s) + Map.foldBack (fun x y (l2, sx) -> let y2, sy = f sx x y in Map.add x y2 l2, sy) l (Map.empty, s) let foldBackRange f (l: NameMap<'T>) acc = Map.foldBack (fun _ y acc -> f y acc) l acc @@ -1193,9 +1196,9 @@ module NameMap = let add v x (m: NameMap<'T>) = Map.add v x m - let isEmpty (m: NameMap<'T>) = (Map.isEmpty m) + let isEmpty (m: NameMap<'T>) = (Map.isEmpty m) - let existsInRange p m = Map.foldBack (fun _ y acc -> acc || p y) m false + let existsInRange p m = Map.foldBack (fun _ y acc -> acc || p y) m false let tryFindInRange p m = Map.foldBack (fun _ y acc -> @@ -1222,49 +1225,49 @@ module NameMultiMap = let empty : NameMultiMap<'T> = Map.empty - let initBy f xs : NameMultiMap<'T> = xs |> Seq.groupBy f |> Seq.map (fun (k,v) -> (k,List.ofSeq v)) |> Map.ofSeq + let initBy f xs : NameMultiMap<'T> = xs |> Seq.groupBy f |> Seq.map (fun (k, v) -> (k, List.ofSeq v)) |> Map.ofSeq - let ofList (xs: (string * 'T) list) : NameMultiMap<'T> = xs |> Seq.groupBy fst |> Seq.map (fun (k,v) -> (k,List.ofSeq (Seq.map snd v))) |> Map.ofSeq + let ofList (xs: (string * 'T) list) : NameMultiMap<'T> = xs |> Seq.groupBy fst |> Seq.map (fun (k, v) -> (k, List.ofSeq (Seq.map snd v))) |> Map.ofSeq [] module MultiMap = - let existsInRange f (m: MultiMap<_,_>) = Map.exists (fun _ l -> List.exists f l) m + let existsInRange f (m: MultiMap<_, _>) = Map.exists (fun _ l -> List.exists f l) m - let find v (m: MultiMap<_,_>) = match m.TryGetValue v with true, r -> r | _ -> [] + let find v (m: MultiMap<_, _>) = match m.TryGetValue v with true, r -> r | _ -> [] - let add v x (m: MultiMap<_,_>) = Map.add v (x :: find v m) m + let add v x (m: MultiMap<_, _>) = Map.add v (x :: find v m) m - let range (m: MultiMap<_,_>) = Map.foldBack (fun _ x sofar -> x @ sofar) m [] + let range (m: MultiMap<_, _>) = Map.foldBack (fun _ x sofar -> x @ sofar) m [] - let empty : MultiMap<_,_> = Map.empty + let empty : MultiMap<_, _> = Map.empty - let initBy f xs : MultiMap<_,_> = xs |> Seq.groupBy f |> Seq.map (fun (k,v) -> (k,List.ofSeq v)) |> Map.ofSeq + let initBy f xs : MultiMap<_, _> = xs |> Seq.groupBy f |> Seq.map (fun (k, v) -> (k, List.ofSeq v)) |> Map.ofSeq -type LayeredMap<'Key,'Value when 'Key : comparison> = Map<'Key,'Value> +type LayeredMap<'Key, 'Value when 'Key : comparison> = Map<'Key, 'Value> -type Map<'Key,'Value when 'Key : comparison> with +type Map<'Key, 'Value when 'Key : comparison> with - static member Empty : Map<'Key,'Value> = Map.empty + static member Empty : Map<'Key, 'Value> = Map.empty - member x.Values = [ for (KeyValue(_,v)) in x -> v ] + member x.Values = [ for (KeyValue(_, v)) in x -> v ] - member x.AddAndMarkAsCollapsible (kvs: _[]) = (x,kvs) ||> Array.fold (fun x (KeyValue(k,v)) -> x.Add(k,v)) + member x.AddAndMarkAsCollapsible (kvs: _[]) = (x, kvs) ||> Array.fold (fun x (KeyValue(k, v)) -> x.Add(k, v)) member x.LinearTryModifyThenLaterFlatten (key, f: 'Value option -> 'Value) = x.Add (key, f (x.TryFind key)) - member x.MarkAsCollapsible () = x + member x.MarkAsCollapsible () = x /// Immutable map collection, with explicit flattening to a backing dictionary [] -type LayeredMultiMap<'Key,'Value when 'Key : equality and 'Key : comparison>(contents : LayeredMap<'Key,'Value list>) = +type LayeredMultiMap<'Key, 'Value when 'Key : equality and 'Key : comparison>(contents : LayeredMap<'Key, 'Value list>) = - member x.Add (k,v) = LayeredMultiMap(contents.Add(k,v :: x.[k])) + member x.Add (k, v) = LayeredMultiMap(contents.Add(k, v :: x.[k])) member x.Item with get k = match contents.TryGetValue k with true, l -> l | _ -> [] - member x.AddAndMarkAsCollapsible (kvs: _[]) = - let x = (x,kvs) ||> Array.fold (fun x (KeyValue(k,v)) -> x.Add(k,v)) + member x.AddAndMarkAsCollapsible (kvs: _[]) = + let x = (x, kvs) ||> Array.fold (fun x (KeyValue(k, v)) -> x.Add(k, v)) x.MarkAsCollapsible() member x.MarkAsCollapsible() = LayeredMultiMap(contents.MarkAsCollapsible()) @@ -1275,7 +1278,7 @@ type LayeredMultiMap<'Key,'Value when 'Key : equality and 'Key : comparison>(con member x.Values = contents.Values |> List.concat - static member Empty : LayeredMultiMap<'Key,'Value> = LayeredMultiMap LayeredMap.Empty + static member Empty : LayeredMultiMap<'Key, 'Value> = LayeredMultiMap LayeredMap.Empty [] module Shim = @@ -1288,27 +1291,27 @@ module Shim = type IFileSystem = /// A shim over File.ReadAllBytes - abstract ReadAllBytesShim: fileName:string -> byte[] + abstract ReadAllBytesShim: fileName: string -> byte[] - /// A shim over FileStream with FileMode.Open,FileAccess.Read,FileShare.ReadWrite - abstract FileStreamReadShim: fileName:string -> Stream + /// A shim over FileStream with FileMode.Open, FileAccess.Read, FileShare.ReadWrite + abstract FileStreamReadShim: fileName: string -> Stream - /// A shim over FileStream with FileMode.Create,FileAccess.Write,FileShare.Read - abstract FileStreamCreateShim: fileName:string -> Stream + /// A shim over FileStream with FileMode.Create, FileAccess.Write, FileShare.Read + abstract FileStreamCreateShim: fileName: string -> Stream - /// A shim over FileStream with FileMode.Open,FileAccess.Write,FileShare.Read - abstract FileStreamWriteExistingShim: fileName:string -> Stream + /// A shim over FileStream with FileMode.Open, FileAccess.Write, FileShare.Read + abstract FileStreamWriteExistingShim: fileName: string -> Stream /// Take in a filename with an absolute path, and return the same filename /// but canonicalized with respect to extra path separators (e.g. C:\\\\foo.txt) /// and '..' portions - abstract GetFullPathShim: fileName:string -> string + abstract GetFullPathShim: fileName: string -> string /// A shim over Path.IsPathRooted - abstract IsPathRootedShim: path:string -> bool + abstract IsPathRootedShim: path: string -> bool /// A shim over Path.IsInvalidPath - abstract IsInvalidPathShim: filename:string -> bool + abstract IsInvalidPathShim: filename: string -> bool /// A shim over Path.GetTempPath abstract GetTempPathShim : unit -> string @@ -1343,24 +1346,24 @@ module Shim = member __.ReadAllBytesShim (fileName: string) = File.ReadAllBytes fileName - member __.FileStreamReadShim (fileName: string) = new FileStream(fileName,FileMode.Open,FileAccess.Read,FileShare.ReadWrite) :> Stream + member __.FileStreamReadShim (fileName: string) = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) :> Stream - member __.FileStreamCreateShim (fileName: string) = new FileStream(fileName,FileMode.Create,FileAccess.Write,FileShare.Read ,0x1000,false) :> Stream + member __.FileStreamCreateShim (fileName: string) = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.Read , 0x1000, false) :> Stream - member __.FileStreamWriteExistingShim (fileName: string) = new FileStream(fileName,FileMode.Open,FileAccess.Write,FileShare.Read ,0x1000,false) :> Stream + member __.FileStreamWriteExistingShim (fileName: string) = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.Read , 0x1000, false) :> Stream member __.GetFullPathShim (fileName: string) = System.IO.Path.GetFullPath fileName member __.IsPathRootedShim (path: string) = Path.IsPathRooted path member __.IsInvalidPathShim(path: string) = - let isInvalidPath(p:string) = + let isInvalidPath(p: string) = String.IsNullOrEmpty(p) || p.IndexOfAny(Path.GetInvalidPathChars()) <> -1 - let isInvalidFilename(p:string) = + let isInvalidFilename(p: string) = String.IsNullOrEmpty(p) || p.IndexOfAny(Path.GetInvalidFileNameChars()) <> -1 - let isInvalidDirectory(d:string) = + let isInvalidDirectory(d: string) = d=null || d.IndexOfAny(Path.GetInvalidPathChars()) <> -1 isInvalidPath (path) || @@ -1370,11 +1373,11 @@ module Shim = member __.GetTempPathShim() = Path.GetTempPath() - member __.GetLastWriteTimeShim (fileName:string) = File.GetLastWriteTimeUtc fileName + member __.GetLastWriteTimeShim (fileName: string) = File.GetLastWriteTimeUtc fileName - member __.SafeExists (fileName:string) = File.Exists fileName + member __.SafeExists (fileName: string) = File.Exists fileName - member __.FileDelete (fileName:string) = File.Delete fileName + member __.FileDelete (fileName: string) = File.Delete fileName member __.IsStableFileHeuristic (fileName: string) = let directory = Path.GetDirectoryName(fileName) diff --git a/src/absil/ilprint.fs b/src/absil/ilprint.fs index f9f7fb7af19..5614522f02b 100644 --- a/src/absil/ilprint.fs +++ b/src/absil/ilprint.fs @@ -33,12 +33,17 @@ type ppenv = { ilGlobals: ILGlobals ppenvClassFormals: int ppenvMethodFormals: int } + let ppenv_enter_method mgparams env = {env with ppenvMethodFormals=mgparams} + let ppenv_enter_tdef gparams env = {env with ppenvClassFormals=List.length gparams; ppenvMethodFormals=0} + let mk_ppenv ilg = { ilGlobals = ilg; ppenvClassFormals = 0; ppenvMethodFormals = 0 } + let debug_ppenv = mk_ppenv + let ppenv_enter_modul env = { env with ppenvClassFormals=0; ppenvMethodFormals=0 } // -------------------------------------------------------------------- @@ -46,8 +51,11 @@ let ppenv_enter_modul env = { env with ppenvClassFormals=0; ppenvMethodFormals= // -------------------------------------------------------------------- let output_string (os: TextWriter) (s:string) = os.Write s + let output_char (os: TextWriter) (c:char) = os.Write c + let output_int os (i:int) = output_string os (string i) + let output_hex_digit os i = assert (i >= 0 && i < 16) if i > 9 then output_char os (char (int32 'A' + (i-10))) @@ -106,7 +114,9 @@ let output_array sep f os (a:_ []) = f os (a.[a.Length - 1]) let output_parens f os a = output_string os "("; f os a; output_string os ")" + let output_angled f os a = output_string os "<"; f os a; output_string os ">" + let output_bracks f os a = output_string os "["; f os a; output_string os "]" let output_id os n = output_sqstring os n @@ -114,6 +124,7 @@ let output_id os n = output_sqstring os n let output_label os n = output_string os n let output_lid os lid = output_seq "." output_string os lid + let string_of_type_name (_,n) = n let output_byte os i = @@ -127,17 +138,27 @@ let output_bytes os (bytes:byte[]) = let bits_of_float32 (x:float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x),0) + let bits_of_float (x:float) = System.BitConverter.DoubleToInt64Bits(x) let output_u8 os (x:byte) = output_string os (string (int x)) + let output_i8 os (x:sbyte) = output_string os (string (int x)) + let output_u16 os (x:uint16) = output_string os (string (int x)) + let output_i16 os (x:int16) = output_string os (string (int x)) + let output_u32 os (x:uint32) = output_string os (string (int64 x)) + let output_i32 os (x:int32) = output_string os (string x) + let output_u64 os (x:uint64) = output_string os (string (int64 x)) + let output_i64 os (x:int64) = output_string os (string x) + let output_ieee32 os (x:float32) = output_string os "float32 ("; output_string os (string (bits_of_float32 x)); output_string os ")" + let output_ieee64 os (x:float) = output_string os "float64 ("; output_string os (string (bits_of_float x)); output_string os ")" let rec goutput_scoref _env os = function @@ -155,8 +176,8 @@ and goutput_tref env os (x:ILTypeRef) = and goutput_typ env os ty = match ty with - | ILType.Boxed tr -> goutput_tspec env os tr - | ILType.TypeVar tv -> + | ILType.Boxed tr -> goutput_tspec env os tr + | ILType.TypeVar tv -> // Special rule to print method type variables in Generic EE preferred form // when an environment is available to help us do this. let cgparams = env.ppenvClassFormals @@ -164,36 +185,36 @@ and goutput_typ env os ty = if int tv < cgparams then output_string os "!" output_tyvar os tv - elif int tv - cgparams < mgparams then + elif int tv - cgparams < mgparams then output_string os "!!" - output_int os (int tv - cgparams) + output_int os (int tv - cgparams) else output_string os "!" output_tyvar os tv output_int os (int tv) | ILType.Byref typ -> goutput_typ env os typ; output_string os "&" - | ILType.Ptr typ -> goutput_typ env os typ; output_string os "*" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_SByte.TypeSpec.Name -> output_string os "int8" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int16.TypeSpec.Name -> output_string os "int16" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int32.TypeSpec.Name -> output_string os "int32" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int64.TypeSpec.Name -> output_string os "int64" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_IntPtr.TypeSpec.Name -> output_string os "native int" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Byte.TypeSpec.Name -> output_string os "unsigned int8" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt16.TypeSpec.Name -> output_string os "unsigned int16" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt32.TypeSpec.Name -> output_string os "unsigned int32" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt64.TypeSpec.Name -> output_string os "unsigned int64" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UIntPtr.TypeSpec.Name -> output_string os "native unsigned int" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Double.TypeSpec.Name -> output_string os "float64" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Single.TypeSpec.Name -> output_string os "float32" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Bool.TypeSpec.Name -> output_string os "bool" - | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Char.TypeSpec.Name -> output_string os "char" + | ILType.Ptr typ -> goutput_typ env os typ; output_string os "*" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_SByte.TypeSpec.Name -> output_string os "int8" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int16.TypeSpec.Name -> output_string os "int16" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int32.TypeSpec.Name -> output_string os "int32" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Int64.TypeSpec.Name -> output_string os "int64" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_IntPtr.TypeSpec.Name -> output_string os "native int" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Byte.TypeSpec.Name -> output_string os "unsigned int8" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt16.TypeSpec.Name -> output_string os "unsigned int16" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt32.TypeSpec.Name -> output_string os "unsigned int32" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UInt64.TypeSpec.Name -> output_string os "unsigned int64" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_UIntPtr.TypeSpec.Name -> output_string os "native unsigned int" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Double.TypeSpec.Name -> output_string os "float64" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Single.TypeSpec.Name -> output_string os "float32" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Bool.TypeSpec.Name -> output_string os "bool" + | ILType.Value tspec when tspec.Name = EcmaMscorlibILGlobals.typ_Char.TypeSpec.Name -> output_string os "char" | ILType.Value tspec -> output_string os "value class " goutput_tref env os tspec.TypeRef output_string os " " goutput_gactuals env os tspec.GenericArgs - | ILType.Void -> output_string os "void" + | ILType.Void -> output_string os "void" | ILType.Array (bounds,ty) -> goutput_typ env os ty output_string os "[" @@ -253,30 +274,28 @@ and output_arr_bounds os = function l and goutput_permission _env os p = - let output_security_action os x = + let output_security_action os x = output_string os (match x with - | ILSecurityAction.Request -> "request" - | ILSecurityAction.Demand -> "demand" - | ILSecurityAction.Assert-> "assert" - | ILSecurityAction.Deny-> "deny" - | ILSecurityAction.PermitOnly-> "permitonly" - | ILSecurityAction.LinkCheck-> "linkcheck" - | ILSecurityAction.InheritCheck-> "inheritcheck" - | ILSecurityAction.ReqMin-> "reqmin" - | ILSecurityAction.ReqOpt-> "reqopt" - | ILSecurityAction.ReqRefuse-> "reqrefuse" - | ILSecurityAction.PreJitGrant-> "prejitgrant" - | ILSecurityAction.PreJitDeny-> "prejitdeny" - | ILSecurityAction.NonCasDemand-> "noncasdemand" - | ILSecurityAction.NonCasLinkDemand-> "noncaslinkdemand" - | ILSecurityAction.NonCasInheritance-> "noncasinheritance" + | ILSecurityAction.Request -> "request" + | ILSecurityAction.Demand -> "demand" + | ILSecurityAction.Assert-> "assert" + | ILSecurityAction.Deny-> "deny" + | ILSecurityAction.PermitOnly-> "permitonly" + | ILSecurityAction.LinkCheck-> "linkcheck" + | ILSecurityAction.InheritCheck-> "inheritcheck" + | ILSecurityAction.ReqMin-> "reqmin" + | ILSecurityAction.ReqOpt-> "reqopt" + | ILSecurityAction.ReqRefuse-> "reqrefuse" + | ILSecurityAction.PreJitGrant-> "prejitgrant" + | ILSecurityAction.PreJitDeny-> "prejitdeny" + | ILSecurityAction.NonCasDemand-> "noncasdemand" + | ILSecurityAction.NonCasLinkDemand-> "noncaslinkdemand" + | ILSecurityAction.NonCasInheritance-> "noncasinheritance" | ILSecurityAction.LinkDemandChoice -> "linkdemandchoice" | ILSecurityAction.InheritanceDemandChoice -> "inheritancedemandchoice" | ILSecurityAction.DemandChoice -> "demandchoice") - - match p with | ILSecurityDecl (sa,b) -> output_string os " .permissionset " @@ -459,10 +478,10 @@ let goutput_cuspec env os (IlxUnionSpec(IlxUnionRef(_,tref,_,_,_),i)) = let output_basic_type os x = output_string os (match x with - | DT_I1 -> "i1" - | DT_U1 -> "u1" - | DT_I2 -> "i2" - | DT_U2 -> "u2" + | DT_I1 -> "i1" + | DT_U1 -> "u1" + | DT_I2 -> "i2" + | DT_U2 -> "u2" | DT_I4 -> "i4" | DT_U4 -> "u4" | DT_I8 -> "i8" @@ -505,7 +524,6 @@ let goutput_fdef _tref env os (fd: ILFieldDef) = output_string os "\n" goutput_custom_attrs env os fd.CustomAttrs - let output_alignment os = function Aligned -> () | Unaligned1 -> output_string os "unaligned. 1 " @@ -528,11 +546,11 @@ let rec goutput_apps env os = function output_angled (goutput_gparam env) os (mkILSimpleTypar "T") output_string os " " goutput_apps env os cs - | Apps_app(ty,cs) -> + | Apps_app(ty,cs) -> output_parens (goutput_typ env) os ty output_string os " " goutput_apps env os cs - | Apps_done ty -> + | Apps_done ty -> output_string os "--> " goutput_typ env os ty @@ -540,6 +558,7 @@ let rec goutput_apps env os = function let output_short_u16 os (x:uint16) = if int x < 256 then (output_string os ".s "; output_u16 os x) else output_string os " "; output_u16 os x + let output_short_i32 os i32 = if i32 < 256 && 0 >= i32 then (output_string os ".s "; output_i32 os i32) else output_string os " "; output_i32 os i32 @@ -553,7 +572,7 @@ let goutput_local env os (l: ILLocal) = let goutput_param env os (l: ILParameter) = match l.Name with - None -> goutput_typ env os l.Type + None -> goutput_typ env os l.Type | Some n -> goutput_typ env os l.Type; output_string os " "; output_sqstring os n let goutput_params env os ps = @@ -624,7 +643,7 @@ let rec goutput_instr env os inst = output_string os "ldc."; output_basic_type os dt; output_string os " "; output_ieee32 os x | (AI_ldc (dt, ILConst.R8 x)) -> output_string os "ldc."; output_basic_type os dt; output_string os " "; output_ieee64 os x - | I_ldftn mspec -> output_string os "ldftn "; goutput_mspec env os mspec + | I_ldftn mspec -> output_string os "ldftn "; goutput_mspec env os mspec | I_ldvirtftn mspec -> output_string os "ldvirtftn "; goutput_mspec env os mspec | I_ldind (al,vol,dt) -> output_alignment os al @@ -779,7 +798,6 @@ let goutput_ilmbody env os (il: ILMethodBody) = output_seq ",\n " (goutput_local env) os il.Locals output_string os ")\n" - 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 " @@ -892,14 +910,15 @@ let output_type_layout_info os info = let splitTypeLayout = function | ILTypeDefLayout.Auto -> "auto",(fun _os () -> ()) - | ILTypeDefLayout.Sequential info -> "sequential", (fun os () -> output_type_layout_info os info) - | ILTypeDefLayout.Explicit info -> "explicit", (fun os () -> output_type_layout_info os info) - + | ILTypeDefLayout.Sequential info -> "sequential", (fun os () -> output_type_layout_info os info) + | ILTypeDefLayout.Explicit info -> "explicit", (fun os () -> output_type_layout_info os info) let goutput_fdefs tref env os (fdefs: ILFieldDefs) = List.iter (fun f -> (goutput_fdef tref env) os f; output_string os "\n" ) fdefs.AsList + let goutput_mdefs env os (mdefs: ILMethodDefs) = Array.iter (fun f -> (goutput_mdef env) os f; output_string os "\n" ) mdefs.AsArray + let goutput_pdefs env os (pdefs: ILPropertyDefs) = List.iter (fun f -> (goutput_pdef env) os f; output_string os "\n" ) pdefs.AsList @@ -954,7 +973,7 @@ and goutput_lambdas env os lambdas = output_angled (goutput_gparam env) os gf output_string os " " (goutput_lambdas env) os l - | Lambdas_lambda (ps,l) -> + | Lambdas_lambda (ps,l) -> output_parens (goutput_param env) os ps output_string os " " (goutput_lambdas env) os l @@ -1046,7 +1065,7 @@ let output_module_fragment_aux _refs os (ilg: ILGlobals) modul = let env = ppenv_enter_modul env goutput_tdefs false ([]) env os modul.TypeDefs goutput_tdefs true ([]) env os modul.TypeDefs - with e -> + with e -> output_string os "*** Error during printing : "; output_string os (e.ToString()); os.Flush() reraise() @@ -1078,7 +1097,7 @@ let output_module os (ilg: ILGlobals) modul = output_module_refs os refs goutput_module_manifest env os modul output_module_fragment_aux refs os ilg modul - with e -> + with e -> output_string os "*** Error during printing : "; output_string os (e.ToString()); os.Flush() raise e diff --git a/src/absil/ilread.fs b/src/absil/ilread.fs index 5383896efd5..7bb25a58363 100644 --- a/src/absil/ilread.fs +++ b/src/absil/ilread.fs @@ -33,14 +33,14 @@ open System.Reflection let checking = false let logging = false -let _ = if checking then dprintn "warning : ILBinaryReader.checking is on" +let _ = if checking then dprintn "warning: ILBinaryReader.checking is on" let noStableFileHeuristic = try (System.Environment.GetEnvironmentVariable("FSharp_NoStableFileHeuristic") <> null) with _ -> false let alwaysMemoryMapFSC = try (System.Environment.GetEnvironmentVariable("FSharp_AlwaysMemoryMapCommandLineCompiler") <> null) with _ -> false let stronglyHeldReaderCacheSizeDefault = 30 let stronglyHeldReaderCacheSize = try (match System.Environment.GetEnvironmentVariable("FSharp_StronglyHeldBinaryReaderCacheSize") with null -> stronglyHeldReaderCacheSizeDefault | s -> int32 s) with _ -> stronglyHeldReaderCacheSizeDefault -let singleOfBits (x:int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) -let doubleOfBits (x:int64) = System.BitConverter.Int64BitsToDouble(x) +let singleOfBits (x: int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) +let doubleOfBits (x: int64) = System.BitConverter.Int64BitsToDouble(x) //--------------------------------------------------------------------- // Utilities. @@ -48,7 +48,7 @@ let doubleOfBits (x:int64) = System.BitConverter.Int64BitsToDouble(x) let align alignment n = ((n + alignment - 0x1) / alignment) * alignment -let uncodedToken (tab:TableName) idx = ((tab.Index <<< 24) ||| idx) +let uncodedToken (tab: TableName) idx = ((tab.Index <<< 24) ||| idx) let i32ToUncodedToken tok = let idx = tok &&& 0xffffff @@ -59,7 +59,7 @@ let i32ToUncodedToken tok = [] type TaggedIndex<'T> = val tag: 'T - val index : int32 + val index: int32 new(tag, index) = { tag=tag; index=index } let uncodedTokenToTypeDefOrRefOrSpec (tab, tok) = @@ -77,7 +77,7 @@ let uncodedTokenToMethodDefOrRef (tab, tok) = else failwith "bad table in uncodedTokenToMethodDefOrRef" TaggedIndex(tag, tok) -let (|TaggedIndex|) (x:TaggedIndex<'T>) = x.tag, x.index +let (|TaggedIndex|) (x: TaggedIndex<'T>) = x.tag, x.index let tokToTaggedIdx f nbits tok = let tagmask = if nbits = 1 then 1 @@ -91,11 +91,11 @@ let tokToTaggedIdx f nbits tok = TaggedIndex(f tag, idx) type Statistics = - { mutable rawMemoryFileCount : int - mutable memoryMapFileOpenedCount : int - mutable memoryMapFileClosedCount : int - mutable weakByteFileCount : int - mutable byteFileCount : int } + { mutable rawMemoryFileCount: int + mutable memoryMapFileOpenedCount: int + mutable memoryMapFileClosedCount: int + mutable weakByteFileCount: int + mutable byteFileCount: int } let stats = { rawMemoryFileCount = 0 @@ -113,22 +113,22 @@ let GetStatistics() = stats type BinaryView() = /// Read a byte from the file - abstract ReadByte : addr:int -> byte + abstract ReadByte: addr: int -> byte /// Read a chunk of bytes from the file - abstract ReadBytes : addr:int -> int -> byte[] + abstract ReadBytes: addr: int -> int -> byte[] /// Read an Int32 from the file - abstract ReadInt32 : addr:int -> int + abstract ReadInt32: addr: int -> int /// Read a UInt16 from the file - abstract ReadUInt16 : addr:int -> uint16 + abstract ReadUInt16: addr: int -> uint16 /// Read a length of a UTF8 string from the file - abstract CountUtf8String : addr:int -> int + abstract CountUtf8String: addr: int -> int /// Read a UTF8 string from the file - abstract ReadUTF8String : addr: int -> string + abstract ReadUTF8String: addr: int -> string /// An abstraction over how we access the contents of .NET binaries. May be backed by managed or unmanaged memory, /// memory mapped file or by on-disk resources. @@ -136,10 +136,10 @@ type BinaryFile = /// Return a BinaryView for temporary use which eagerly holds any necessary memory resources for the duration of its lifetime, /// and is faster to access byte-by-byte. The returned BinaryView should _not_ be captured in a closure that outlives the /// desired lifetime. - abstract GetView : unit -> BinaryView + abstract GetView: unit -> BinaryView /// A view over a raw pointer to memory -type RawMemoryView(obj: obj, start:nativeint, len: int) = +type RawMemoryView(obj: obj, start: nativeint, len: int) = inherit BinaryView() override m.ReadByte i = @@ -238,7 +238,7 @@ module MemoryMapping = /// A view over a raw pointer to memory given by a memory mapped file. /// NOTE: we should do more checking of validity here. -type MemoryMapView(start:nativeint) = +type MemoryMapView(start: nativeint) = inherit BinaryView() override m.ReadByte i = @@ -270,7 +270,7 @@ type MemoryMapView(start:nativeint) = /// lock on the file is only released when the object is disposed. /// For memory mapping we currently take one view and never release it. [] -type MemoryMapFile(fileName: string, view: MemoryMapView, hMap: MemoryMapping.HANDLE, hView:nativeint) = +type MemoryMapFile(fileName: string, view: MemoryMapView, hMap: MemoryMapping.HANDLE, hView: nativeint) = do stats.memoryMapFileOpenedCount <- stats.memoryMapFileOpenedCount + 1 let mutable closed = false @@ -306,7 +306,7 @@ type MemoryMapFile(fileName: string, view: MemoryMapView, hMap: MemoryMapping.HA override __.GetView() = (view :> BinaryView) /// Read file from memory blocks -type ByteView(bytes:byte[]) = +type ByteView(bytes: byte[]) = inherit BinaryView() override __.ReadByte addr = bytes.[addr] @@ -337,7 +337,7 @@ type ByteView(bytes:byte[]) = /// A BinaryFile backed by an array of bytes held strongly as managed memory [] -type ByteFile(fileName: string, bytes:byte[]) = +type ByteFile(fileName: string, bytes: byte[]) = let view = ByteView(bytes) do stats.byteFileCount <- stats.byteFileCount + 1 member __.FileName = fileName @@ -384,10 +384,10 @@ type WeakByteFile(fileName: string, chunk: (int * int) option) = (ByteView(strongBytes) :> BinaryView) -let seekReadByte (mdv:BinaryView) addr = mdv.ReadByte addr -let seekReadBytes (mdv:BinaryView) addr len = mdv.ReadBytes addr len -let seekReadInt32 (mdv:BinaryView) addr = mdv.ReadInt32 addr -let seekReadUInt16 (mdv:BinaryView) addr = mdv.ReadUInt16 addr +let seekReadByte (mdv: BinaryView) addr = mdv.ReadByte addr +let seekReadBytes (mdv: BinaryView) addr len = mdv.ReadBytes addr len +let seekReadInt32 (mdv: BinaryView) addr = mdv.ReadInt32 addr +let seekReadUInt16 (mdv: BinaryView) addr = mdv.ReadUInt16 addr let seekReadByteAsInt32 mdv addr = int32 (seekReadByte mdv addr) @@ -452,16 +452,16 @@ let seekReadUncodedToken mdv addr = // Primitives to help read signatures. These do not use the file cursor //--------------------------------------------------------------------- -let sigptrCheck (bytes:byte[]) sigptr = +let sigptrCheck (bytes: byte[]) sigptr = if checking && sigptr >= bytes.Length then failwith "read past end of sig. " // All this code should be moved to use a mutable index into the signature // -//type SigPtr(bytes:byte[], sigptr:int) = +//type SigPtr(bytes: byte[], sigptr: int) = // let mutable curr = sigptr // member x.GetByte() = let res = bytes.[curr] in curr <- curr + 1; res -let sigptrGetByte (bytes:byte[]) sigptr = +let sigptrGetByte (bytes: byte[]) sigptr = sigptrCheck bytes sigptr bytes.[sigptr], sigptr + 1 @@ -526,18 +526,18 @@ let sigptrGetZInt32 bytes sigptr = let b3, sigptr = sigptrGetByte bytes sigptr (int b0 <<< 24) ||| (int b1 <<< 16) ||| (int b2 <<< 8) ||| int b3, sigptr -let rec sigptrFoldAcc f n (bytes:byte[]) (sigptr:int) i acc = +let rec sigptrFoldAcc f n (bytes: byte[]) (sigptr: int) i acc = if i < n then let x, sp = f bytes sigptr sigptrFoldAcc f n bytes sp (i+1) (x::acc) else List.rev acc, sigptr -let sigptrFold f n (bytes:byte[]) (sigptr:int) = +let sigptrFold f n (bytes: byte[]) (sigptr: int) = sigptrFoldAcc f n bytes sigptr 0 [] -let sigptrGetBytes n (bytes:byte[]) sigptr = +let sigptrGetBytes n (bytes: byte[]) sigptr = if checking && sigptr + n >= bytes.Length then dprintn "read past end of sig. in sigptrGetString" Bytes.zeroCreate 0, sigptr @@ -845,28 +845,28 @@ let kindIllegal = RowKind [ ] // kind of element in that column. //--------------------------------------------------------------------- -let hcCompare (TaggedIndex((t1: HasConstantTag), (idx1:int))) (TaggedIndex((t2: HasConstantTag), idx2)) = +let hcCompare (TaggedIndex((t1: HasConstantTag), (idx1: int))) (TaggedIndex((t2: HasConstantTag), idx2)) = if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag -let hsCompare (TaggedIndex((t1:HasSemanticsTag), (idx1:int))) (TaggedIndex((t2:HasSemanticsTag), idx2)) = +let hsCompare (TaggedIndex((t1: HasSemanticsTag), (idx1: int))) (TaggedIndex((t2: HasSemanticsTag), idx2)) = if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag -let hcaCompare (TaggedIndex((t1:HasCustomAttributeTag), (idx1:int))) (TaggedIndex((t2:HasCustomAttributeTag), idx2)) = +let hcaCompare (TaggedIndex((t1: HasCustomAttributeTag), (idx1: int))) (TaggedIndex((t2: HasCustomAttributeTag), idx2)) = if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag -let mfCompare (TaggedIndex((t1:MemberForwardedTag), (idx1:int))) (TaggedIndex((t2:MemberForwardedTag), idx2)) = +let mfCompare (TaggedIndex((t1: MemberForwardedTag), (idx1: int))) (TaggedIndex((t2: MemberForwardedTag), idx2)) = if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag -let hdsCompare (TaggedIndex((t1:HasDeclSecurityTag), (idx1:int))) (TaggedIndex((t2:HasDeclSecurityTag), idx2)) = +let hdsCompare (TaggedIndex((t1: HasDeclSecurityTag), (idx1: int))) (TaggedIndex((t2: HasDeclSecurityTag), idx2)) = if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag -let hfmCompare (TaggedIndex((t1:HasFieldMarshalTag), idx1)) (TaggedIndex((t2:HasFieldMarshalTag), idx2)) = +let hfmCompare (TaggedIndex((t1: HasFieldMarshalTag), idx1)) (TaggedIndex((t2: HasFieldMarshalTag), idx2)) = if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag -let tomdCompare (TaggedIndex((t1:TypeOrMethodDefTag), idx1)) (TaggedIndex((t2:TypeOrMethodDefTag), idx2)) = +let tomdCompare (TaggedIndex((t1: TypeOrMethodDefTag), idx1)) (TaggedIndex((t2: TypeOrMethodDefTag), idx2)) = if idx1 < idx2 then -1 elif idx1 > idx2 then 1 else compare t1.Tag t2.Tag -let simpleIndexCompare (idx1:int) (idx2:int) = +let simpleIndexCompare (idx1: int) (idx2: int) = compare idx1 idx2 //--------------------------------------------------------------------- @@ -894,9 +894,9 @@ let mkCacheInt32 lowMem _inbase _nm _sz = let cache = ref null let count = ref 0 #if STATISTICS - addReport (fun oc -> if !count <> 0 then oc.WriteLine ((_inbase + string !count + " "+ _nm + " cache hits") : string)) + addReport (fun oc -> if !count <> 0 then oc.WriteLine ((_inbase + string !count + " "+ _nm + " cache hits"): string)) #endif - fun f (idx:int32) -> + fun f (idx: int32) -> let cache = match !cache with | null -> cache := new Dictionary(11) @@ -917,12 +917,12 @@ let mkCacheGeneric lowMem _inbase _nm _sz = let cache = ref null let count = ref 0 #if STATISTICS - addReport (fun oc -> if !count <> 0 then oc.WriteLine ((_inbase + string !count + " " + _nm + " cache hits") : string)) + addReport (fun oc -> if !count <> 0 then oc.WriteLine ((_inbase + string !count + " " + _nm + " cache hits"): string)) #endif fun f (idx :'T) -> let cache = match !cache with - | null -> cache := new Dictionary<_, _>(11 (* sz:int *) ) + | null -> cache := new Dictionary<_, _>(11 (* sz: int *) ) | _ -> () !cache match cache.TryGetValue(idx) with @@ -1054,19 +1054,19 @@ type PEReader = #endif entryPointToken: TableName * int pefile: BinaryFile - textSegmentPhysicalLoc : int32 - textSegmentPhysicalSize : int32 - dataSegmentPhysicalLoc : int32 - dataSegmentPhysicalSize : int32 - anyV2P : (string * int32) -> int32 + textSegmentPhysicalLoc: int32 + textSegmentPhysicalSize: int32 + dataSegmentPhysicalLoc: int32 + dataSegmentPhysicalSize: int32 + anyV2P: (string * int32) -> int32 metadataAddr: int32 - sectionHeaders : (int32 * int32 * int32) list - nativeResourcesAddr:int32 - nativeResourcesSize:int32 - resourcesAddr:int32 - strongnameAddr:int32 - vtableFixupsAddr:int32 - noFileOnDisk:bool + sectionHeaders: (int32 * int32 * int32) list + nativeResourcesAddr: int32 + nativeResourcesSize: int32 + resourcesAddr: int32 + strongnameAddr: int32 + vtableFixupsAddr: int32 + noFileOnDisk: bool } [] @@ -1077,7 +1077,7 @@ type ILMetadataReader = pectxtCaptured: PEReader option // only set when reading full PE including code etc. for static linking entryPointToken: TableName * int dataEndPoints: Lazy - fileName:string + fileName: string getNumRows: TableName -> int userStringsStreamPhysicalLoc: int32 stringsStreamPhysicalLoc: int32 @@ -1087,47 +1087,47 @@ type ILMetadataReader = memoizeString: string -> string readStringHeap: (int32 -> string) readBlobHeap: (int32 -> byte[]) - guidsStreamPhysicalLoc : int32 - rowAddr : (TableName -> int -> int32) - tableBigness : bool array - rsBigness : bool - tdorBigness : bool - tomdBigness : bool - hcBigness : bool - hcaBigness : bool - hfmBigness : bool - hdsBigness : bool - mrpBigness : bool - hsBigness : bool - mdorBigness : bool - mfBigness : bool - iBigness : bool - catBigness : bool + guidsStreamPhysicalLoc: int32 + rowAddr: (TableName -> int -> int32) + tableBigness: bool [] + rsBigness: bool + tdorBigness: bool + tomdBigness: bool + hcBigness: bool + hcaBigness: bool + hfmBigness: bool + hdsBigness: bool + mrpBigness: bool + hsBigness: bool + mdorBigness: bool + mfBigness: bool + iBigness: bool + catBigness: bool stringsBigness: bool guidsBigness: bool blobsBigness: bool - seekReadNestedRow : int -> int * int - seekReadConstantRow : int -> uint16 * TaggedIndex * int32 - seekReadMethodSemanticsRow : int -> int32 * int * TaggedIndex - seekReadTypeDefRow : int -> int32 * int32 * int32 * TaggedIndex * int * int - seekReadAssemblyRef : int -> ILAssemblyRef - seekReadMethodSpecAsMethodData : MethodSpecAsMspecIdx -> VarArgMethodData - seekReadMemberRefAsMethodData : MemberRefAsMspecIdx -> VarArgMethodData - seekReadMemberRefAsFieldSpec : MemberRefAsFspecIdx -> ILFieldSpec - seekReadCustomAttr : CustomAttrIdx -> ILAttribute - seekReadTypeRef : int ->ILTypeRef - seekReadTypeRefAsType : TypeRefAsTypIdx -> ILType - readBlobHeapAsPropertySig : BlobAsPropSigIdx -> ILThisConvention * ILType * ILTypes - readBlobHeapAsFieldSig : BlobAsFieldSigIdx -> ILType - readBlobHeapAsMethodSig : BlobAsMethodSigIdx -> bool * int32 * ILCallingConv * ILType * ILTypes * ILVarArgs - readBlobHeapAsLocalsSig : BlobAsLocalSigIdx -> ILLocal list - seekReadTypeDefAsType : TypeDefAsTypIdx -> ILType - seekReadMethodDefAsMethodData : int -> MethodData - seekReadGenericParams : GenericParamsIdx -> ILGenericParameterDef list - seekReadFieldDefAsFieldSpec : int -> ILFieldSpec - customAttrsReader_Module : ILAttributesStored - customAttrsReader_Assembly : ILAttributesStored - customAttrsReader_TypeDef : ILAttributesStored + seekReadNestedRow: int -> int * int + seekReadConstantRow: int -> uint16 * TaggedIndex * int32 + seekReadMethodSemanticsRow: int -> int32 * int * TaggedIndex + seekReadTypeDefRow: int -> int32 * int32 * int32 * TaggedIndex * int * int + seekReadAssemblyRef: int -> ILAssemblyRef + seekReadMethodSpecAsMethodData: MethodSpecAsMspecIdx -> VarArgMethodData + seekReadMemberRefAsMethodData: MemberRefAsMspecIdx -> VarArgMethodData + seekReadMemberRefAsFieldSpec: MemberRefAsFspecIdx -> ILFieldSpec + seekReadCustomAttr: CustomAttrIdx -> ILAttribute + seekReadTypeRef: int ->ILTypeRef + seekReadTypeRefAsType: TypeRefAsTypIdx -> ILType + readBlobHeapAsPropertySig: BlobAsPropSigIdx -> ILThisConvention * ILType * ILTypes + readBlobHeapAsFieldSig: BlobAsFieldSigIdx -> ILType + readBlobHeapAsMethodSig: BlobAsMethodSigIdx -> bool * int32 * ILCallingConv * ILType * ILTypes * ILVarArgs + readBlobHeapAsLocalsSig: BlobAsLocalSigIdx -> ILLocal list + seekReadTypeDefAsType: TypeDefAsTypIdx -> ILType + seekReadMethodDefAsMethodData: int -> MethodData + seekReadGenericParams: GenericParamsIdx -> ILGenericParameterDef list + seekReadFieldDefAsFieldSpec: int -> ILFieldSpec + customAttrsReader_Module: ILAttributesStored + customAttrsReader_Assembly: ILAttributesStored + customAttrsReader_TypeDef: ILAttributesStored customAttrsReader_GenericParam: ILAttributesStored customAttrsReader_FieldDef: ILAttributesStored customAttrsReader_MethodDef: ILAttributesStored @@ -1136,10 +1136,10 @@ type ILMetadataReader = customAttrsReader_Property: ILAttributesStored customAttrsReader_ManifestResource: ILAttributesStored customAttrsReader_ExportedType: ILAttributesStored - securityDeclsReader_TypeDef : ILSecurityDeclsStored - securityDeclsReader_MethodDef : ILSecurityDeclsStored - securityDeclsReader_Assembly : ILSecurityDeclsStored - typeDefReader : ILTypeDefStored } + securityDeclsReader_TypeDef: ILSecurityDeclsStored + securityDeclsReader_MethodDef: ILSecurityDeclsStored + securityDeclsReader_Assembly: ILSecurityDeclsStored + typeDefReader: ILTypeDefStored } let seekReadUInt16Adv mdv (addr: byref) = @@ -1165,7 +1165,7 @@ let seekReadTaggedIdx f nbits big mdv (addr: byref) = let seekReadIdx big mdv (addr: byref) = if big then seekReadInt32Adv mdv &addr else seekReadUInt16AsInt32Adv mdv &addr -let seekReadUntaggedIdx (tab:TableName) (ctxt: ILMetadataReader) mdv (addr: byref) = +let seekReadUntaggedIdx (tab: TableName) (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadIdx ctxt.tableBigness.[tab.Index] mdv &addr @@ -1207,7 +1207,7 @@ let seekReadTypeRefRow (ctxt: ILMetadataReader) mdv idx = /// Read Table ILTypeDef. let seekReadTypeDefRow (ctxt: ILMetadataReader) idx = ctxt.seekReadTypeDefRow idx let seekReadTypeDefRowUncached ctxtH idx = - let (ctxt : ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let mutable addr = ctxt.rowAddr TableNames.TypeDef idx let flags = seekReadInt32Adv mdv &addr @@ -1624,7 +1624,7 @@ let rvaToData (ctxt: ILMetadataReader) (pectxt: PEReader) nm rva = // Read the AbsIL structure (lazily) by reading off the relevant rows. // ---------------------------------------------------------------------- -let isSorted (ctxt: ILMetadataReader) (tab:TableName) = ((ctxt.sorted &&& (int64 1 <<< tab.Index)) <> int64 0x0) +let isSorted (ctxt: ILMetadataReader) (tab: TableName) = ((ctxt.sorted &&& (int64 1 <<< tab.Index)) <> int64 0x0) // Note, pectxtEager and pevEager must not be captured by the results of this function let rec seekReadModule (ctxt: ILMetadataReader) (pectxtEager: PEReader) pevEager peinfo ilMetadataVersion idx = @@ -1759,7 +1759,7 @@ and readBlobHeapAsTypeName ctxt (nameIdx, namespaceIdx) = | None -> name | Some ns -> ctxt.memoizeString (ns+"."+name) -and seekReadTypeDefRowExtents (ctxt: ILMetadataReader) _info (idx:int) = +and seekReadTypeDefRowExtents (ctxt: ILMetadataReader) _info (idx: int) = if idx >= ctxt.getNumRows TableNames.TypeDef then ctxt.getNumRows TableNames.Field + 1, ctxt.getNumRows TableNames.Method + 1 @@ -1767,11 +1767,11 @@ and seekReadTypeDefRowExtents (ctxt: ILMetadataReader) _info (idx:int) = let (_, _, _, _, fieldsIdx, methodsIdx) = seekReadTypeDefRow ctxt (idx + 1) fieldsIdx, methodsIdx -and seekReadTypeDefRowWithExtents ctxt (idx:int) = +and seekReadTypeDefRowWithExtents ctxt (idx: int) = let info= seekReadTypeDefRow ctxt idx info, seekReadTypeDefRowExtents ctxt info idx -and seekReadPreTypeDef ctxt toponly (idx:int) = +and seekReadPreTypeDef ctxt toponly (idx: int) = let (flags, nameIdx, namespaceIdx, _, _, _) = seekReadTypeDefRow ctxt idx if toponly && not (isTopTypeDef flags) then None else @@ -1779,7 +1779,7 @@ and seekReadPreTypeDef ctxt toponly (idx:int) = // Return the ILPreTypeDef Some (mkILPreTypeDefRead (ns, n, idx, ctxt.typeDefReader)) -and typeDefReader ctxtH : ILTypeDefStored = +and typeDefReader ctxtH: ILTypeDefStored = mkILTypeDefReader (fun idx -> let (ctxt: ILMetadataReader) = getHole ctxtH @@ -1841,7 +1841,7 @@ and seekReadInterfaceImpls (ctxt: ILMetadataReader) mdv numtypars tidx = isSorted ctxt TableNames.InterfaceImpl, (snd >> seekReadTypeDefOrRef ctxt numtypars AsObject (*ok*) List.empty)) -and seekReadGenericParams ctxt numtypars (a, b) : ILGenericParameterDefs = +and seekReadGenericParams ctxt numtypars (a, b): ILGenericParameterDefs = ctxt.seekReadGenericParams (GenericParamsIdx(numtypars, a, b)) and seekReadGenericParamsUncached ctxtH (GenericParamsIdx(numtypars, a, b)) = @@ -1881,7 +1881,7 @@ and seekReadGenericParamConstraints (ctxt: ILMetadataReader) mdv numtypars gpid isSorted ctxt TableNames.GenericParamConstraint, (snd >> seekReadTypeDefOrRef ctxt numtypars AsObject (*ok*) List.empty)) -and seekReadTypeDefAsType (ctxt: ILMetadataReader) boxity (ginst:ILTypes) idx = +and seekReadTypeDefAsType (ctxt: ILMetadataReader) boxity (ginst: ILTypes) idx = ctxt.seekReadTypeDefAsType (TypeDefAsTypIdx (boxity, ginst, idx)) and seekReadTypeDefAsTypeUncached ctxtH (TypeDefAsTypIdx (boxity, ginst, idx)) = @@ -1913,7 +1913,7 @@ and seekReadTypeRefAsTypeUncached ctxtH (TypeRefAsTypIdx (boxity, ginst, idx)) = let ctxt = getHole ctxtH mkILTy boxity (ILTypeSpec.Create(seekReadTypeRef ctxt idx, ginst)) -and seekReadTypeDefOrRef (ctxt: ILMetadataReader) numtypars boxity (ginst:ILTypes) (TaggedIndex(tag, idx) ) = +and seekReadTypeDefOrRef (ctxt: ILMetadataReader) numtypars boxity (ginst: ILTypes) (TaggedIndex(tag, idx) ) = let mdv = ctxt.mdfile.GetView() match tag with | tag when tag = tdor_TypeDef -> seekReadTypeDefAsType ctxt boxity ginst idx @@ -1990,7 +1990,7 @@ and seekReadOptionalTypeDefOrRef (ctxt: ILMetadataReader) numtypars boxity idx if idx = TaggedIndex(tdor_TypeDef, 0) then None else Some (seekReadTypeDefOrRef ctxt numtypars boxity List.empty idx) -and seekReadField ctxt mdv (numtypars, hasLayout) (idx:int) = +and seekReadField ctxt mdv (numtypars, hasLayout) (idx: int) = let (flags, nameIdx, typeIdx) = seekReadFieldRow ctxt mdv idx let nm = readStringHeap ctxt nameIdx let isStatic = (flags &&& 0x0010) <> 0 @@ -2149,7 +2149,7 @@ and sigptrGetLocal (ctxt: ILMetadataReader) numtypars bytes sigptr = else false, sigptr let ty, sigptr = sigptrGetTy ctxt numtypars bytes sigptr - let loc : ILLocal = { IsPinned = pinned; Type = ty; DebugInfo = None } + let loc: ILLocal = { IsPinned = pinned; Type = ty; DebugInfo = None } loc, sigptr and readBlobHeapAsMethodSig (ctxt: ILMetadataReader) numtypars blobIdx = @@ -2232,7 +2232,7 @@ and byteAsCallConv b = let generic = (b &&& e_IMAGE_CEE_CS_CALLCONV_GENERIC) <> 0x0uy generic, Callconv (byteAsHasThis b, cc) -and seekReadMemberRefAsMethodData ctxt numtypars idx : VarArgMethodData = +and seekReadMemberRefAsMethodData ctxt numtypars idx: VarArgMethodData = ctxt.seekReadMemberRefAsMethodData (MemberRefAsMspecIdx (numtypars, idx)) and seekReadMemberRefAsMethodDataUncached ctxtH (MemberRefAsMspecIdx (numtypars, idx)) = @@ -2245,7 +2245,7 @@ and seekReadMemberRefAsMethodDataUncached ctxtH (MemberRefAsMspecIdx (numtypars, let minst = List.init genarity (fun n -> mkILTyvarTy (uint16 (numtypars+n))) (VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, minst)) -and seekReadMemberRefAsMethDataNoVarArgs ctxt numtypars idx : MethodData = +and seekReadMemberRefAsMethDataNoVarArgs ctxt numtypars idx: MethodData = let (VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, minst)) = seekReadMemberRefAsMethodData ctxt numtypars idx if Option.isSome varargs then dprintf "ignoring sentinel and varargs in ILMethodDef token signature" (MethodData(enclTy, cc, nm, argtys, retty, minst)) @@ -2356,7 +2356,7 @@ and seekReadFieldDefAsFieldSpecUncached ctxtH idx = // Put it together. mkILFieldSpecInTy(enclTy, nm, retty) -and seekReadMethod (ctxt: ILMetadataReader) mdv numtypars (idx:int) = +and seekReadMethod (ctxt: ILMetadataReader) mdv numtypars (idx: int) = let (codeRVA, implflags, flags, nameIdx, typeIdx, paramIdx) = seekReadMethodRow ctxt mdv idx let nm = readStringHeap ctxt nameIdx let abstr = (flags &&& 0x0400) <> 0x0 @@ -2415,7 +2415,7 @@ and seekReadParams (ctxt: ILMetadataReader) mdv (retty, argtys) pidx1 pidx2 = seekReadParamExtras ctxt mdv (retRes, paramsRes) i !retRes, List.ofArray paramsRes -and seekReadParamExtras (ctxt: ILMetadataReader) mdv (retRes, paramsRes) (idx:int) = +and seekReadParamExtras (ctxt: ILMetadataReader) mdv (retRes, paramsRes) (idx: int) = let (flags, seq, nameIdx) = seekReadParamRow ctxt mdv idx let inOutMasked = (flags &&& 0x00FF) let hasMarshal = (flags &&& 0x2000) <> 0x0 @@ -2551,7 +2551,7 @@ and seekReadProperties (ctxt: ILMetadataReader) numtypars tidx = yield seekReadProperty ctxt mdv numtypars i ]) -and customAttrsReader ctxtH tag : ILAttributesStored = +and customAttrsReader ctxtH tag: ILAttributesStored = mkILCustomAttrsReader (fun idx -> let (ctxt: ILMetadataReader) = getHole ctxtH @@ -2671,7 +2671,7 @@ and seekReadImplMap (ctxt: ILMetadataReader) nm midx = | Some nm2 -> nm2) Where = seekReadModuleRef ctxt mdv scopeIdx }) -and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz:int) start seqpoints = +and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start seqpoints = let labelsOfRawOffsets = new Dictionary<_, _>(sz/2) let ilOffsetsOfLabels = new Dictionary<_, _>(sz/2) let tryRawToLabel rawOffset = @@ -2872,7 +2872,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz:int) start s curr := !curr + 4 (* REVIEW: this incorrectly labels all MemberRef tokens as ILMethod's: we should go look at the MemberRef sig to determine if it is a field or method *) let token_info = - if tab = TableNames.Method || tab = TableNames.MemberRef (* REVIEW:generics or tab = TableNames.MethodSpec *) then + if tab = TableNames.Method || tab = TableNames.MemberRef (* REVIEW: generics or tab = TableNames.MethodSpec *) then let (MethodData(enclTy, cc, nm, argtys, retty, minst)) = seekReadMethodDefOrRefNoVarargs ctxt numtypars (uncodedTokenToMethodDefOrRef (tab, idx)) ILToken.ILMethod (mkILMethSpecInTy (enclTy, cc, nm, argtys, retty, minst)) elif tab = TableNames.Field then @@ -2973,7 +2973,7 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int |> List.filter (fun l -> let k, _idx = pdbVariableGetAddressAttributes l k = 1 (* ADDR_IL_OFFSET *)) - let ilinfos : ILLocalDebugMapping list = + let ilinfos: ILLocalDebugMapping list = ilvs |> List.map (fun ilv -> let _k, idx = pdbVariableGetAddressAttributes ilv let n = pdbVariableGetName ilv @@ -2983,7 +2983,7 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int let thisOne = (fun raw2nextLab -> { Range= (raw2nextLab a, raw2nextLab b) - DebugMappings = ilinfos } : ILLocalDebugInfo ) + DebugMappings = ilinfos }: ILLocalDebugInfo ) let others = List.foldBack (scopes >> (@)) (Array.toList (pdbScopeGetChildren scp)) [] thisOne :: others let localPdbInfos = [] (* scopes fail for mscorlib scopes rootScope *) @@ -3117,7 +3117,7 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int | true, prev -> sehMap.[key] <- prev @ [clause] | _ -> sehMap.[key] <- [clause]) clauses - ([], sehMap) ||> Seq.fold (fun acc (KeyValue(key, bs)) -> [ for b in bs -> {Range=key; Clause=b} : ILExceptionSpec ] @ acc) + ([], sehMap) ||> Seq.fold (fun acc (KeyValue(key, bs)) -> [ for b in bs -> {Range=key; Clause=b}: ILExceptionSpec ] @ acc) seh := sehClauses moreSections := (sectionFlag &&& e_CorILMethod_Sect_MoreSects) <> 0x0uy nextSectionBase := sectionBase + sectionSize @@ -3141,7 +3141,7 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int if logging then failwith "unknown format" MethodBody.Abstract) -and int32AsILVariantType (ctxt: ILMetadataReader) (n:int32) = +and int32AsILVariantType (ctxt: ILMetadataReader) (n: int32) = if List.memAssoc n (Lazy.force ILVariantTypeRevMap) then List.assoc n (Lazy.force ILVariantTypeRevMap) elif (n &&& vt_ARRAY) <> 0x0 then ILNativeVariant.Array (int32AsILVariantType ctxt (n &&& (~~~ vt_ARRAY))) @@ -3253,7 +3253,7 @@ and seekReadManifestResources (ctxt: ILMetadataReader) (mdv: BinaryView) (pectxt MetadataIndex = i } yield r ] -and seekReadNestedExportedTypes ctxt (exported: _ array) (nested: Lazy<_ array>) parentIdx = +and seekReadNestedExportedTypes ctxt (exported: _ []) (nested: Lazy<_ []>) parentIdx = mkILNestedExportedTypesLazy (lazy nested.Force().[parentIdx-1] @@ -3465,7 +3465,7 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p prevNumRowIdx := !prevNumRowIdx + 4 List.rev !present, numRows, !prevNumRowIdx - let getNumRows (tab:TableName) = tableRowCount.[tab.Index] + let getNumRows (tab: TableName) = tableRowCount.[tab.Index] let numTables = tablesPresent.Length let stringsBigness = (heapSizes &&& 1) <> 0 let guidsBigness = (heapSizes &&& 2) <> 0 @@ -3627,12 +3627,12 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p let cacheMethodSemanticsRow = mkCacheInt32 reduceMemoryUsage inbase "MethodSemantics Rows" (getNumRows TableNames.MethodSemantics / 20 + 1) let cacheTypeDefRow = mkCacheInt32 reduceMemoryUsage inbase "ILTypeDef Rows" (getNumRows TableNames.TypeDef / 20 + 1) - let rowAddr (tab:TableName) idx = tablePhysLocations.[tab.Index] + (idx - 1) * tableRowSizes.[tab.Index] + let rowAddr (tab: TableName) idx = tablePhysLocations.[tab.Index] + (idx - 1) * tableRowSizes.[tab.Index] // Build the reader context // Use an initialization hole let ctxtH = ref None - let ctxt : ILMetadataReader = + let ctxt: ILMetadataReader = { ilg=ilGlobals sorted=sorted getNumRows=getNumRows @@ -3890,7 +3890,7 @@ let openPEFileReader (fileName, pefile: BinaryFile, pdbDirPath, noFileOnDisk) = getPdbReader pdbDirPath fileName #endif - let pectxt : PEReader = + let pectxt: PEReader = { pdb=pdb textSegmentPhysicalLoc=textSegmentPhysicalLoc textSegmentPhysicalSize=textSegmentPhysicalSize @@ -3948,8 +3948,8 @@ type ILReaderOptions = type ILModuleReader = - abstract ILModuleDef : ILModuleDef - abstract ILAssemblyRefs : ILAssemblyRef list + abstract ILModuleDef: ILModuleDef + abstract ILAssemblyRefs: ILAssemblyRef list /// ILModuleReader objects only need to be explicitly disposed if memory mapping is used, i.e. reduceMemoryUsage = false inherit System.IDisposable diff --git a/src/absil/ilreflect.fs b/src/absil/ilreflect.fs index 1381efd591f..0ff14a5696e 100644 --- a/src/absil/ilreflect.fs +++ b/src/absil/ilreflect.fs @@ -164,20 +164,20 @@ type System.Reflection.Emit.TypeBuilder with if logRefEmitCalls then printfn "let constructorBuilder%d = typeBuilder%d.DefineConstructor(enum %d, CallingConventions.%A, %A)" (abs <| hash consB) (abs <| hash typB) (LanguagePrimitives.EnumToValue attrs) cconv parms consB - member typB.DefineFieldAndLog(nm, ty:System.Type, attrs) = + member typB.DefineFieldAndLog(nm, ty: System.Type, attrs) = let fieldB = typB.DefineField(nm, ty, attrs) if logRefEmitCalls then printfn "let fieldBuilder%d = typeBuilder%d.DefineField(\"%s\", typeof<%s>, enum %d)" (abs <| hash fieldB) (abs <| hash typB) nm ty.FullName (LanguagePrimitives.EnumToValue attrs) fieldB - member typB.DefinePropertyAndLog(nm, attrs, ty:System.Type, args) = + member typB.DefinePropertyAndLog(nm, attrs, ty: System.Type, args) = if logRefEmitCalls then printfn "typeBuilder%d.DefineProperty(\"%A\", enum %d, typeof<%s>, %A)" (abs <| hash typB) nm (LanguagePrimitives.EnumToValue attrs) ty.FullName args typB.DefineProperty(nm, attrs, ty, args) - member typB.DefineEventAndLog(nm, attrs, ty:System.Type) = + member typB.DefineEventAndLog(nm, attrs, ty: System.Type) = if logRefEmitCalls then printfn "typeBuilder%d.DefineEvent(\"%A\", enum %d, typeof<%A>)" (abs <| hash typB) nm (LanguagePrimitives.EnumToValue attrs) ty.FullName typB.DefineEvent(nm, attrs, ty) - member typB.SetParentAndLog(ty:System.Type) = + member typB.SetParentAndLog(ty: System.Type) = if logRefEmitCalls then printfn "typeBuilder%d.SetParent(typeof<%s>)" (abs <| hash typB) ty.FullName typB.SetParent(ty) @@ -207,7 +207,7 @@ type System.Reflection.Emit.OpCode with member opcode.RefEmitName = (string (System.Char.ToUpper(opcode.Name.[0])) + opcode.Name.[1..]).Replace(".", "_").Replace("_i4", "_I4") type System.Reflection.Emit.ILGenerator with - member ilG.DeclareLocalAndLog(ty:System.Type, isPinned) = + member ilG.DeclareLocalAndLog(ty: System.Type, isPinned) = if logRefEmitCalls then printfn "ilg%d.DeclareLocal(typeof<%s>, %b)" (abs <| hash ilG) ty.FullName isPinned ilG.DeclareLocal(ty, isPinned) @@ -249,31 +249,31 @@ type System.Reflection.Emit.ILGenerator with if logRefEmitCalls then printfn "let label%d_%d = ilg%d.DefineLabel()" (abs <| hash ilG) (abs <| hash lab) (abs <| hash ilG) lab - member x.EmitAndLog (op:OpCode) = + member x.EmitAndLog (op: OpCode) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s)" (abs <| hash x) op.RefEmitName x.Emit(op) - member x.EmitAndLog (op:OpCode, v:Label) = + member x.EmitAndLog (op: OpCode, v: Label) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, label%d_%d)" (abs <| hash x) op.RefEmitName (abs <| hash x) (abs <| hash v) x.Emit(op, v) - member x.EmitAndLog (op:OpCode, v:int16) = + member x.EmitAndLog (op: OpCode, v: int16) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, int16 %d)" (abs <| hash x) op.RefEmitName v x.Emit(op, v) - member x.EmitAndLog (op:OpCode, v:int32) = + member x.EmitAndLog (op: OpCode, v: int32) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, %d)" (abs <| hash x) op.RefEmitName v x.Emit(op, v) - member x.EmitAndLog (op:OpCode, v:MethodInfo) = + member x.EmitAndLog (op: OpCode, v: MethodInfo) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, methodBuilder%d) // method %s" (abs <| hash x) op.RefEmitName (abs <| hash v) v.Name x.Emit(op, v) - member x.EmitAndLog (op:OpCode, v:string) = + member x.EmitAndLog (op: OpCode, v: string) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, \"@%s\")" (abs <| hash x) op.RefEmitName v x.Emit(op, v) - member x.EmitAndLog (op:OpCode, v:Type) = + member x.EmitAndLog (op: OpCode, v: Type) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, typeof<%s>)" (abs <| hash x) op.RefEmitName v.FullName x.Emit(op, v) - member x.EmitAndLog (op:OpCode, v:FieldInfo) = + member x.EmitAndLog (op: OpCode, v: FieldInfo) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, fieldBuilder%d) // field %s" (abs <| hash x) op.RefEmitName (abs <| hash v) v.Name x.Emit(op, v) - member x.EmitAndLog (op:OpCode, v:ConstructorInfo) = + member x.EmitAndLog (op: OpCode, v: ConstructorInfo) = if logRefEmitCalls then printfn "ilg%d.Emit(OpCodes.%s, constructor_%s)" (abs <| hash x) op.RefEmitName v.DeclaringType.Name x.Emit(op, v) @@ -287,13 +287,13 @@ let inline flagsIf b x = if b then x else enum 0 module Zmap = let force x m str = match Zmap.tryFind x m with Some y -> y | None -> failwithf "Zmap.force: %s: x = %+A" str x -let equalTypes (s:Type) (t:Type) = s.Equals(t) +let equalTypes (s: Type) (t: Type) = s.Equals(t) let equalTypeLists ss tt = List.lengthsEqAndForall2 equalTypes ss tt let equalTypeArrays ss tt = Array.lengthsEqAndForall2 equalTypes ss tt -let getGenericArgumentsOfType (typT : Type) = +let getGenericArgumentsOfType (typT: Type) = if typT.IsGenericType then typT.GetGenericArguments() else [| |] -let getGenericArgumentsOfMethod (methI : MethodInfo) = +let getGenericArgumentsOfMethod (methI: MethodInfo) = if methI.IsGenericMethod then methI.GetGenericArguments() else [| |] let getTypeConstructor (ty: Type) = @@ -303,7 +303,7 @@ let getTypeConstructor (ty: Type) = // convAssemblyRef //---------------------------------------------------------------------------- -let convAssemblyRef (aref:ILAssemblyRef) = +let convAssemblyRef (aref: ILAssemblyRef) = let asmName = new System.Reflection.AssemblyName() asmName.Name <- aref.Name (match aref.PublicKey with @@ -323,7 +323,7 @@ let convAssemblyRef (aref:ILAssemblyRef) = /// The global environment. type cenv = { ilg: ILGlobals - tryFindSysILTypeRef : string -> ILTypeRef option + tryFindSysILTypeRef: string -> ILTypeRef option generatePdb: bool resolveAssemblyRef: (ILAssemblyRef -> Choice option) } @@ -334,7 +334,7 @@ type cenv = // [] , name -> name // [ns] , name -> ns+name // [ns;typeA;typeB], name -> ns+typeA+typeB+name -let convTypeRefAux (cenv:cenv) (tref:ILTypeRef) = +let convTypeRefAux (cenv: cenv) (tref: ILTypeRef) = let qualifiedName = (String.concat "+" (tref.Enclosing @ [ tref.Name ])).Replace(",", @"\,") match tref.Scope with | ILScopeRef.Assembly asmref -> @@ -364,16 +364,16 @@ let convTypeRefAux (cenv:cenv) (tref:ILTypeRef) = /// and could be placed as hash tables in the global environment. [] type emEnv = - { emTypMap : Zmap - emConsMap : Zmap - emMethMap : Zmap - emFieldMap : Zmap - emPropMap : Zmap - emLocals : LocalBuilder[] - emLabels : Zmap - emTyvars : Type[] list; // stack - emEntryPts : (TypeBuilder * string) list - delayedFieldInits : (unit -> unit) list} + { emTypMap: Zmap + emConsMap: Zmap + emMethMap: Zmap + emFieldMap: Zmap + emPropMap: Zmap + emLocals: LocalBuilder[] + emLabels: Zmap + emTyvars: Type[] list; // stack + emEntryPts: (TypeBuilder * string) list + delayedFieldInits: (unit -> unit) list} let orderILTypeRef = ComparisonIdentity.Structural let orderILMethodRef = ComparisonIdentity.Structural @@ -392,12 +392,12 @@ let emEnv0 = emEntryPts = [] delayedFieldInits = [] } -let envBindTypeRef emEnv (tref:ILTypeRef) (typT, typB, typeDef) = +let envBindTypeRef emEnv (tref: ILTypeRef) (typT, typB, typeDef) = match typT with | null -> failwithf "binding null type in envBindTypeRef: %s\n" tref.Name | _ -> {emEnv with emTypMap = Zmap.add tref (typT, typB, typeDef, None) emEnv.emTypMap} -let envUpdateCreatedTypeRef emEnv (tref:ILTypeRef) = +let envUpdateCreatedTypeRef emEnv (tref: ILTypeRef) = // The tref's TypeBuilder has been created, so we have a Type proper. // Update the tables to include this created type (the typT held prior to this is (i think) actually (TypeBuilder :> Type). // The (TypeBuilder :> Type) does not implement all the methods that a Type proper does. @@ -423,7 +423,7 @@ let envUpdateCreatedTypeRef emEnv (tref:ILTypeRef) = #endif emEnv -let convTypeRef cenv emEnv preferCreated (tref:ILTypeRef) = +let convTypeRef cenv emEnv preferCreated (tref: ILTypeRef) = let res = match Zmap.tryFind tref emEnv.emTypMap with | Some (_typT, _typB, _typeDef, Some createdTy) when preferCreated -> createdTy @@ -433,16 +433,16 @@ let convTypeRef cenv emEnv preferCreated (tref:ILTypeRef) = | null -> error(Error(FSComp.SR.itemNotFoundDuringDynamicCodeGen ("type", tref.QualifiedName, tref.Scope.QualifiedName), range0)) | _ -> res -let envBindConsRef emEnv (mref:ILMethodRef) consB = +let envBindConsRef emEnv (mref: ILMethodRef) consB = {emEnv with emConsMap = Zmap.add mref consB emEnv.emConsMap} -let envGetConsB emEnv (mref:ILMethodRef) = +let envGetConsB emEnv (mref: ILMethodRef) = Zmap.force mref emEnv.emConsMap "envGetConsB: failed" -let envBindMethodRef emEnv (mref:ILMethodRef) methB = +let envBindMethodRef emEnv (mref: ILMethodRef) methB = {emEnv with emMethMap = Zmap.add mref methB emEnv.emMethMap} -let envGetMethB emEnv (mref:ILMethodRef) = +let envGetMethB emEnv (mref: ILMethodRef) = Zmap.force mref emEnv.emMethMap "envGetMethB: failed" let envBindFieldRef emEnv fref fieldB = @@ -451,17 +451,17 @@ let envBindFieldRef emEnv fref fieldB = let envGetFieldB emEnv fref = Zmap.force fref emEnv.emFieldMap "- envGetMethB: failed" -let envBindPropRef emEnv (pref:ILPropertyRef) propB = +let envBindPropRef emEnv (pref: ILPropertyRef) propB = {emEnv with emPropMap = Zmap.add pref propB emEnv.emPropMap} let envGetPropB emEnv pref = Zmap.force pref emEnv.emPropMap "- envGetPropB: failed" -let envGetTypB emEnv (tref:ILTypeRef) = +let envGetTypB emEnv (tref: ILTypeRef) = Zmap.force tref emEnv.emTypMap "envGetTypB: failed" |> (fun (_typT, typB, _typeDef, _createdTypOpt) -> typB) -let envGetTypeDef emEnv (tref:ILTypeRef) = +let envGetTypeDef emEnv (tref: ILTypeRef) = Zmap.force tref emEnv.emTypMap "envGetTypeDef: failed" |> (fun (_typT, _typB, typeDef, _createdTypOpt) -> typeDef) @@ -514,7 +514,7 @@ let convCallConv (Callconv (hasThis, basic)) = // convType //---------------------------------------------------------------------------- -let rec convTypeSpec cenv emEnv preferCreated (tspec:ILTypeSpec) = +let rec convTypeSpec cenv emEnv preferCreated (tspec: ILTypeSpec) = let typT = convTypeRef cenv emEnv preferCreated tspec.TypeRef let tyargs = List.map (convTypeAux cenv emEnv preferCreated) tspec.GenericArgs let res = @@ -582,9 +582,9 @@ let convTypeOrTypeDef cenv emEnv ty = | ILType.Boxed tspec when tspec.GenericArgs.IsEmpty -> convTypeRef cenv emEnv false tspec.TypeRef | _ -> convType cenv emEnv ty -let convTypes cenv emEnv (tys:ILTypes) = List.map (convType cenv emEnv) tys +let convTypes cenv emEnv (tys: ILTypes) = List.map (convType cenv emEnv) tys -let convTypesToArray cenv emEnv (tys:ILTypes) = convTypes cenv emEnv tys |> List.toArray +let convTypesToArray cenv emEnv (tys: ILTypes) = convTypes cenv emEnv tys |> List.toArray /// Uses the .CreateType() for emitted type if available. let convCreatedType cenv emEnv ty = convTypeAux cenv emEnv true ty @@ -653,7 +653,7 @@ let TypeBuilderInstantiationT = assert (not (isNull ty)) ty -let typeIsNotQueryable (ty : Type) = +let typeIsNotQueryable (ty: Type) = #if FX_RESHAPED_REFLECTION let ty = ty.GetTypeInfo() #endif @@ -662,13 +662,13 @@ let typeIsNotQueryable (ty : Type) = // convFieldSpec //---------------------------------------------------------------------------- -let queryableTypeGetField _emEnv (parentT:Type) (fref: ILFieldRef) = +let queryableTypeGetField _emEnv (parentT: Type) (fref: ILFieldRef) = let res = parentT.GetField(fref.Name, BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.Static ) match res with | null -> error(Error(FSComp.SR.itemNotFoundInTypeDuringDynamicCodeGen ("field", fref.Name, fref.DeclaringTypeRef.FullName, fref.DeclaringTypeRef.Scope.QualifiedName), range0)) | _ -> res -let nonQueryableTypeGetField (parentTI:Type) (fieldInfo : FieldInfo) : FieldInfo = +let nonQueryableTypeGetField (parentTI: Type) (fieldInfo: FieldInfo) : FieldInfo = let res = if parentTI.IsGenericType then TypeBuilder.GetField(parentTI, fieldInfo) else fieldInfo @@ -697,7 +697,7 @@ let convFieldSpec cenv emEnv fspec = //---------------------------------------------------------------------------- // convMethodRef //---------------------------------------------------------------------------- -let queryableTypeGetMethodBySearch cenv emEnv parentT (mref:ILMethodRef) = +let queryableTypeGetMethodBySearch cenv emEnv parentT (mref: ILMethodRef) = assert(not (typeIsNotQueryable(parentT))) let cconv = (if mref.CallingConv.IsStatic then BindingFlags.Static else BindingFlags.Instance) let methInfos = parentT.GetMethods(cconv ||| BindingFlags.Public ||| BindingFlags.NonPublic) |> Array.toList @@ -721,7 +721,7 @@ let queryableTypeGetMethodBySearch cenv emEnv parentT (mref:ILMethodRef) = elif // both are generic p.IsGenericType && a.IsGenericType - // non obvious due to contravariance: Action where T : IFoo accepts Action (for FooImpl : IFoo) + // non obvious due to contravariance: Action where T: IFoo accepts Action (for FooImpl: IFoo) && p.GetGenericTypeDefinition().IsAssignableFrom(a.GetGenericTypeDefinition()) then true else false @@ -730,7 +730,7 @@ let queryableTypeGetMethodBySearch cenv emEnv parentT (mref:ILMethodRef) = if Array.length args <> Array.length ps then false else Array.forall2 satisfiesParameter args ps - let select (methInfo:MethodInfo) = + let select (methInfo: MethodInfo) = (* mref implied Types *) let mtyargTIs = getGenericArgumentsOfMethod methInfo @@ -769,7 +769,7 @@ let queryableTypeGetMethodBySearch cenv emEnv parentT (mref:ILMethodRef) = failwithf "convMethodRef: could not bind to method '%A' of type '%s'" (System.String.Join(", ", methNames)) parentT.AssemblyQualifiedName | Some methInfo -> methInfo (* return MethodInfo for (generic) type's (generic) method *) -let queryableTypeGetMethod cenv emEnv parentT (mref:ILMethodRef) = +let queryableTypeGetMethod cenv emEnv parentT (mref: ILMethodRef) = assert(not (typeIsNotQueryable(parentT))) if mref.GenericArity = 0 then let tyargTs = getGenericArgumentsOfType parentT @@ -786,9 +786,9 @@ let queryableTypeGetMethod cenv emEnv parentT (mref:ILMethodRef) = null, argTs, #if FX_RESHAPED_REFLECTION - (null:obj[])) + (null: obj[])) #else - (null:ParameterModifier[])) + (null: ParameterModifier[])) #endif // This can fail if there is an ambiguity w.r.t. return type with _ -> null @@ -799,13 +799,13 @@ let queryableTypeGetMethod cenv emEnv parentT (mref:ILMethodRef) = else queryableTypeGetMethodBySearch cenv emEnv parentT mref -let nonQueryableTypeGetMethod (parentTI:Type) (methInfo : MethodInfo) : MethodInfo = +let nonQueryableTypeGetMethod (parentTI: Type) (methInfo: MethodInfo) : MethodInfo = if (parentTI.IsGenericType && not (equalTypes parentTI (getTypeConstructor parentTI))) then TypeBuilder.GetMethod(parentTI, methInfo ) else methInfo -let convMethodRef cenv emEnv (parentTI:Type) (mref:ILMethodRef) = +let convMethodRef cenv emEnv (parentTI: Type) (mref: ILMethodRef) = let parent = mref.DeclaringTypeRef let res = if isEmittedTypeRef emEnv parent then @@ -829,7 +829,7 @@ let convMethodRef cenv emEnv (parentTI:Type) (mref:ILMethodRef) = // convMethodSpec //---------------------------------------------------------------------------- -let convMethodSpec cenv emEnv (mspec:ILMethodSpec) = +let convMethodSpec cenv emEnv (mspec: ILMethodSpec) = let typT = convType cenv emEnv mspec.DeclaringType (* (instanced) parent Type *) let methInfo = convMethodRef cenv emEnv typT mspec.MethodRef (* (generic) method of (generic) parent *) let methInfo = @@ -845,7 +845,7 @@ let convMethodSpec cenv emEnv (mspec:ILMethodSpec) = // - QueryableTypeGetConstructors: get a constructor on a non-TypeBuilder type //---------------------------------------------------------------------------- -let queryableTypeGetConstructor cenv emEnv (parentT:Type) (mref:ILMethodRef) = +let queryableTypeGetConstructor cenv emEnv (parentT: Type) (mref: ILMethodRef) = let tyargTs = getGenericArgumentsOfType parentT let reqArgTs = let emEnv = envPushTyvars emEnv tyargTs @@ -856,14 +856,14 @@ let queryableTypeGetConstructor cenv emEnv (parentT:Type) (mref:ILMethodRef) = | _ -> res -let nonQueryableTypeGetConstructor (parentTI:Type) (consInfo : ConstructorInfo) : ConstructorInfo = +let nonQueryableTypeGetConstructor (parentTI: Type) (consInfo: ConstructorInfo) : ConstructorInfo = if parentTI.IsGenericType then TypeBuilder.GetConstructor(parentTI, consInfo) else consInfo //---------------------------------------------------------------------------- // convConstructorSpec (like convMethodSpec) //---------------------------------------------------------------------------- -let convConstructorSpec cenv emEnv (mspec:ILMethodSpec) = +let convConstructorSpec cenv emEnv (mspec: ILMethodSpec) = let mref = mspec.MethodRef let parentTI = convType cenv emEnv mspec.DeclaringType let res = @@ -886,7 +886,7 @@ let convConstructorSpec cenv emEnv (mspec:ILMethodSpec) = // emitLabelMark //---------------------------------------------------------------------------- -let emitLabelMark emEnv (ilG:ILGenerator) (label:ILCodeLabel) = +let emitLabelMark emEnv (ilG: ILGenerator) (label: ILCodeLabel) = let lab = envGetLabel emEnv label ilG.MarkLabelAndLog(lab) @@ -895,7 +895,7 @@ let emitLabelMark emEnv (ilG:ILGenerator) (label:ILCodeLabel) = //---------------------------------------------------------------------------- ///Emit comparison instructions. -let emitInstrCompare emEnv (ilG:ILGenerator) comp targ = +let emitInstrCompare emEnv (ilG: ILGenerator) comp targ = match comp with | BI_beq -> ilG.EmitAndLog(OpCodes.Beq, envGetLabel emEnv targ) | BI_bge -> ilG.EmitAndLog(OpCodes.Bge , envGetLabel emEnv targ) @@ -912,33 +912,33 @@ let emitInstrCompare emEnv (ilG:ILGenerator) comp targ = /// Emit the volatile. prefix -let emitInstrVolatile (ilG:ILGenerator) = function +let emitInstrVolatile (ilG: ILGenerator) = function | Volatile -> ilG.EmitAndLog(OpCodes.Volatile) | Nonvolatile -> () /// Emit the align. prefix -let emitInstrAlign (ilG:ILGenerator) = function +let emitInstrAlign (ilG: ILGenerator) = function | Aligned -> () | Unaligned1 -> ilG.Emit(OpCodes.Unaligned, 1L) // note: doc says use "long" overload! | Unaligned2 -> ilG.Emit(OpCodes.Unaligned, 2L) | Unaligned4 -> ilG.Emit(OpCodes.Unaligned, 3L) /// Emit the tail. prefix if necessary -let emitInstrTail (ilG:ILGenerator) tail emitTheCall = +let emitInstrTail (ilG: ILGenerator) tail emitTheCall = match tail with | Tailcall -> ilG.EmitAndLog(OpCodes.Tailcall); emitTheCall(); ilG.EmitAndLog(OpCodes.Ret) | Normalcall -> emitTheCall() -let emitInstrNewobj cenv emEnv (ilG:ILGenerator) mspec varargs = +let emitInstrNewobj cenv emEnv (ilG: ILGenerator) mspec varargs = match varargs with | None -> ilG.EmitAndLog(OpCodes.Newobj, convConstructorSpec cenv emEnv mspec) | Some _varargTys -> failwith "emit: pending new varargs" // XXX - gap -let emitSilverlightCheck (ilG:ILGenerator) = +let emitSilverlightCheck (ilG: ILGenerator) = ignore ilG () -let emitInstrCall cenv emEnv (ilG:ILGenerator) opCall tail (mspec:ILMethodSpec) varargs = +let emitInstrCall cenv emEnv (ilG: ILGenerator) opCall tail (mspec: ILMethodSpec) varargs = emitInstrTail ilG tail (fun () -> if mspec.MethodRef.Name = ".ctor" || mspec.MethodRef.Name = ".cctor" then let cinfo = convConstructorSpec cenv emEnv mspec @@ -952,7 +952,7 @@ let emitInstrCall cenv emEnv (ilG:ILGenerator) opCall tail (mspec:ILMethodSpec) | Some varargTys -> ilG.EmitCall (opCall, minfo, convTypesToArray cenv emEnv varargTys) ) -let getGenericMethodDefinition q (ty:Type) = +let getGenericMethodDefinition q (ty: Type) = let gminfo = match q with | Quotations.Patterns.Call(_, minfo, _) -> minfo.GetGenericMethodDefinition() @@ -978,7 +978,7 @@ let setArrayMethInfo n ty = // emitInstr cenv //---------------------------------------------------------------------------- -let rec emitInstr cenv (modB : ModuleBuilder) emEnv (ilG:ILGenerator) instr = +let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = match instr with | AI_add -> ilG.EmitAndLog(OpCodes.Add) | AI_add_ovf -> ilG.EmitAndLog(OpCodes.Add_Ovf) @@ -1277,7 +1277,7 @@ let rec emitInstr cenv (modB : ModuleBuilder) emEnv (ilG:ILGenerator) instr = setArrayMethInfo shape.Rank ety else #endif - modB.GetArrayMethodAndLog(aty, "Set", System.Reflection.CallingConventions.HasThis, (null:Type), Array.append (Array.create shape.Rank (typeof)) (Array.ofList [ ety ])) + modB.GetArrayMethodAndLog(aty, "Set", System.Reflection.CallingConventions.HasThis, (null: Type), Array.append (Array.create shape.Rank (typeof)) (Array.ofList [ ety ])) ilG.EmitAndLog(OpCodes.Call, meth) | I_newarr (shape, ty) -> @@ -1285,7 +1285,7 @@ let rec emitInstr cenv (modB : ModuleBuilder) emEnv (ilG:ILGenerator) instr = then ilG.EmitAndLog(OpCodes.Newarr, convType cenv emEnv ty) else let aty = convType cenv emEnv (ILType.Array(shape, ty)) - let meth = modB.GetArrayMethodAndLog(aty, ".ctor", System.Reflection.CallingConventions.HasThis, (null:Type), Array.create shape.Rank (typeof)) + let meth = modB.GetArrayMethodAndLog(aty, ".ctor", System.Reflection.CallingConventions.HasThis, (null: Type), Array.create shape.Rank (typeof)) ilG.EmitAndLog(OpCodes.Newobj, meth) | I_ldlen -> ilG.EmitAndLog(OpCodes.Ldlen) @@ -1300,7 +1300,7 @@ let rec emitInstr cenv (modB : ModuleBuilder) emEnv (ilG:ILGenerator) instr = () #else if cenv.generatePdb && not (src.Document.File.EndsWithOrdinal("stdin")) then - let guid x = match x with None -> Guid.Empty | Some g -> Guid(g:byte[]) in + let guid x = match x with None -> Guid.Empty | Some g -> Guid(g: byte[]) in let symDoc = modB.DefineDocumentAndLog(src.Document.File, guid src.Document.Language, guid src.Document.Vendor, guid src.Document.DocumentType) ilG.MarkSequencePointAndLog(symDoc, src.Line, src.Column, src.EndLine, src.EndColumn) #endif @@ -1324,7 +1324,7 @@ let rec emitInstr cenv (modB : ModuleBuilder) emEnv (ilG:ILGenerator) instr = | i -> failwithf "the IL instruction %s cannot be emitted" (i.ToString()) -let emitCode cenv modB emEnv (ilG:ILGenerator) (code: ILCode) = +let emitCode cenv modB emEnv (ilG: ILGenerator) (code: ILCode) = // Pre-define the labels pending determining their actual marks let pc2lab = Dictionary() let emEnv = @@ -1391,7 +1391,7 @@ let emitCode cenv modB emEnv (ilG:ILGenerator) (code: ILCode) = | i -> emitInstr cenv modB emEnv ilG i -let emitLocal cenv emEnv (ilG : ILGenerator) (local: ILLocal) = +let emitLocal cenv emEnv (ilG: ILGenerator) (local: ILLocal) = let ty = convType cenv emEnv local.Type let locBuilder = ilG.DeclareLocalAndLog(ty, local.IsPinned) #if !FX_NO_PDB_WRITER @@ -1401,7 +1401,7 @@ let emitLocal cenv emEnv (ilG : ILGenerator) (local: ILLocal) = #endif locBuilder -let emitILMethodBody cenv modB emEnv (ilG:ILGenerator) (ilmbody: ILMethodBody) = +let emitILMethodBody cenv modB emEnv (ilG: ILGenerator) (ilmbody: ILMethodBody) = let localBs = Array.map (emitLocal cenv emEnv ilG) (List.toArray ilmbody.Locals) let emEnv = envSetLocals emEnv localBs emitCode cenv modB emEnv ilG ilmbody.Code @@ -1424,13 +1424,13 @@ let convCustomAttr cenv emEnv (cattr: ILAttribute) = (methInfo, data) let emitCustomAttr cenv emEnv add cattr = add (convCustomAttr cenv emEnv cattr) -let emitCustomAttrs cenv emEnv add (cattrs : ILAttributes) = Array.iter (emitCustomAttr cenv emEnv add) cattrs.AsArray +let emitCustomAttrs cenv emEnv add (cattrs: ILAttributes) = Array.iter (emitCustomAttr cenv emEnv add) cattrs.AsArray //---------------------------------------------------------------------------- // buildGenParams //---------------------------------------------------------------------------- -let buildGenParamsPass1 _emEnv defineGenericParameters (gps : ILGenericParameterDefs) = +let buildGenParamsPass1 _emEnv defineGenericParameters (gps: ILGenericParameterDefs) = match gps with | [] -> () | gps -> @@ -1438,17 +1438,17 @@ let buildGenParamsPass1 _emEnv defineGenericParameters (gps : ILGenericParameter defineGenericParameters (Array.ofList gpsNames) |> ignore -let buildGenParamsPass1b cenv emEnv (genArgs : Type array) (gps : ILGenericParameterDefs) = +let buildGenParamsPass1b cenv emEnv (genArgs: Type array) (gps: ILGenericParameterDefs) = #if FX_RESHAPED_REFLECTION let genpBs = genArgs |> Array.map (fun x -> (x.GetTypeInfo() :?> GenericTypeParameterBuilder)) #else let genpBs = genArgs |> Array.map (fun x -> (x :?> GenericTypeParameterBuilder)) #endif - gps |> List.iteri (fun i (gp:ILGenericParameterDef) -> + gps |> List.iteri (fun i (gp: ILGenericParameterDef) -> let gpB = genpBs.[i] // the Constraints are either the parent (base) type or interfaces. let constraintTs = convTypes cenv emEnv gp.Constraints - let interfaceTs, baseTs = List.partition (fun (ty:System.Type) -> ty.IsInterface) constraintTs + let interfaceTs, baseTs = List.partition (fun (ty: System.Type) -> ty.IsInterface) constraintTs // set base type constraint (match baseTs with [ ] -> () // Q: should a baseType be set? It is in some samples. Should this be a failure case? @@ -1476,7 +1476,7 @@ let buildGenParamsPass1b cenv emEnv (genArgs : Type array) (gps : ILGenericParam // emitParameter //---------------------------------------------------------------------------- -let emitParameter cenv emEnv (defineParameter : int * ParameterAttributes * string -> ParameterBuilder) i (param: ILParameter) = +let emitParameter cenv emEnv (defineParameter: int * ParameterAttributes * string -> ParameterBuilder) i (param: ILParameter) = // -Type: ty // -Default: ILFieldInit option // -Marshal: NativeType option; (* Marshalling map for parameters. COM Interop only. *) @@ -1495,7 +1495,7 @@ let emitParameter cenv emEnv (defineParameter : int * ParameterAttributes * stri // buildMethodPass2 //---------------------------------------------------------------------------- -let rec buildMethodPass2 cenv tref (typB:TypeBuilder) emEnv (mdef : ILMethodDef) = +let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) = let attrs = mdef.Attributes let implflags = mdef.ImplAttributes let cconv = convCallConv mdef.CallingConv @@ -1573,7 +1573,7 @@ let rec buildMethodPass2 cenv tref (typB:TypeBuilder) emEnv (mdef : ILMethodDef) // buildMethodPass3 cenv //---------------------------------------------------------------------------- -let rec buildMethodPass3 cenv tref modB (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.Body.Contents with @@ -1615,7 +1615,7 @@ let rec buildMethodPass3 cenv tref modB (typB:TypeBuilder) emEnv (mdef : ILMetho // buildFieldPass2 //---------------------------------------------------------------------------- -let buildFieldPass2 cenv tref (typB:TypeBuilder) emEnv (fdef : ILFieldDef) = +let buildFieldPass2 cenv tref (typB: TypeBuilder) emEnv (fdef: ILFieldDef) = let attrs = fdef.Attributes let fieldT = convType cenv emEnv fdef.FieldType @@ -1648,7 +1648,7 @@ let buildFieldPass2 cenv tref (typB:TypeBuilder) emEnv (fdef : ILFieldDef) = let fref = mkILFieldRef (tref, fdef.Name, fdef.FieldType) envBindFieldRef emEnv fref fieldB -let buildFieldPass3 cenv tref (_typB:TypeBuilder) emEnv (fdef : ILFieldDef) = +let buildFieldPass3 cenv tref (_typB: TypeBuilder) emEnv (fdef: ILFieldDef) = let fref = mkILFieldRef (tref, fdef.Name, fdef.FieldType) let fieldB = envGetFieldB emEnv fref emitCustomAttrs cenv emEnv (wrapCustomAttr fieldB.SetCustomAttribute) fdef.CustomAttrs @@ -1657,7 +1657,7 @@ let buildFieldPass3 cenv tref (_typB:TypeBuilder) emEnv (fdef : ILFieldDef) = // buildPropertyPass2, 3 //---------------------------------------------------------------------------- -let buildPropertyPass2 cenv tref (typB:TypeBuilder) emEnv (prop : ILPropertyDef) = +let buildPropertyPass2 cenv tref (typB: TypeBuilder) emEnv (prop: ILPropertyDef) = let attrs = flagsIf prop.IsRTSpecialName PropertyAttributes.RTSpecialName ||| flagsIf prop.IsSpecialName PropertyAttributes.SpecialName @@ -1671,7 +1671,7 @@ let buildPropertyPass2 cenv tref (typB:TypeBuilder) emEnv (prop : ILPropertyDef) let pref = ILPropertyRef.Create (tref, prop.Name) envBindPropRef emEnv pref propB -let buildPropertyPass3 cenv tref (_typB:TypeBuilder) emEnv (prop : ILPropertyDef) = +let buildPropertyPass3 cenv tref (_typB: TypeBuilder) emEnv (prop: ILPropertyDef) = let pref = ILPropertyRef.Create (tref, prop.Name) let propB = envGetPropB emEnv pref emitCustomAttrs cenv emEnv (wrapCustomAttr propB.SetCustomAttribute) prop.CustomAttrs @@ -1681,7 +1681,7 @@ let buildPropertyPass3 cenv tref (_typB:TypeBuilder) emEnv (prop : ILPropertyDef //---------------------------------------------------------------------------- -let buildEventPass3 cenv (typB:TypeBuilder) emEnv (eventDef : ILEventDef) = +let buildEventPass3 cenv (typB: TypeBuilder) emEnv (eventDef: ILEventDef) = let attrs = flagsIf eventDef.IsSpecialName EventAttributes.SpecialName ||| flagsIf eventDef.IsRTSpecialName EventAttributes.RTSpecialName assert eventDef.EventType.IsSome @@ -1697,7 +1697,7 @@ let buildEventPass3 cenv (typB:TypeBuilder) emEnv (eventDef : ILEventDef) = // buildMethodImplsPass3 //---------------------------------------------------------------------------- -let buildMethodImplsPass3 cenv _tref (typB:TypeBuilder) emEnv (mimpl : IL.ILMethodImplDef) = +let buildMethodImplsPass3 cenv _tref (typB: TypeBuilder) emEnv (mimpl: IL.ILMethodImplDef) = let bodyMethInfo = convMethodRef cenv emEnv (typB.AsType()) mimpl.OverrideBy.MethodRef // doc: must be MethodBuilder let (OverridesSpec (mref, dtyp)) = mimpl.Overrides let declMethTI = convType cenv emEnv dtyp @@ -1763,7 +1763,7 @@ let typeAttributesOfTypeLayout cenv emEnv x = // buildTypeDefPass1 cenv //---------------------------------------------------------------------------- -let rec buildTypeDefPass1 cenv emEnv (modB:ModuleBuilder) rootTypeBuilder nesting (tdef : ILTypeDef) = +let rec buildTypeDefPass1 cenv emEnv (modB: ModuleBuilder) rootTypeBuilder nesting (tdef: ILTypeDef) = // -IsComInterop: bool; (* Class or interface generated for COM interop *) // -SecurityDecls: Permissions // -InitSemantics: ILTypeInit @@ -1773,7 +1773,7 @@ let rec buildTypeDefPass1 cenv emEnv (modB:ModuleBuilder) rootTypeBuilder nestin let attrsType = tdef.Attributes // TypeBuilder from TypeAttributes. - let typB : TypeBuilder = rootTypeBuilder (tdef.Name, attrsType) + let typB: TypeBuilder = rootTypeBuilder (tdef.Name, attrsType) cattrsLayout |> Option.iter typB.SetCustomAttributeAndLog buildGenParamsPass1 emEnv typB.DefineGenericParametersAndLog tdef.GenericParams @@ -1792,14 +1792,14 @@ let rec buildTypeDefPass1 cenv emEnv (modB:ModuleBuilder) rootTypeBuilder nestin let emEnv = List.fold buildNestedType emEnv tdef.NestedTypes.AsList emEnv -and buildTypeTypeDef cenv emEnv modB (typB : TypeBuilder) nesting tdef = +and buildTypeTypeDef cenv emEnv modB (typB: TypeBuilder) nesting tdef = buildTypeDefPass1 cenv emEnv modB typB.DefineNestedTypeAndLog nesting tdef //---------------------------------------------------------------------------- // buildTypeDefPass1b //---------------------------------------------------------------------------- -let rec buildTypeDefPass1b cenv nesting emEnv (tdef : ILTypeDef) = +let rec buildTypeDefPass1b cenv nesting emEnv (tdef: ILTypeDef) = let tref = mkRefForNestedILTypeDef ILScopeRef.Local (nesting, tdef) let typB = envGetTypB emEnv tref let genArgs = getGenericArgumentsOfType (typB.AsType()) @@ -1817,7 +1817,7 @@ let rec buildTypeDefPass1b cenv nesting emEnv (tdef : ILTypeDef) = // buildTypeDefPass2 //---------------------------------------------------------------------------- -let rec buildTypeDefPass2 cenv nesting emEnv (tdef : ILTypeDef) = +let rec buildTypeDefPass2 cenv nesting emEnv (tdef: ILTypeDef) = let tref = mkRefForNestedILTypeDef ILScopeRef.Local (nesting, tdef) let typB = envGetTypB emEnv tref let emEnv = envPushTyvars emEnv (getGenericArgumentsOfType (typB.AsType())) @@ -1837,7 +1837,7 @@ let rec buildTypeDefPass2 cenv nesting emEnv (tdef : ILTypeDef) = // buildTypeDefPass3 cenv //---------------------------------------------------------------------------- -let rec buildTypeDefPass3 cenv nesting modB emEnv (tdef : ILTypeDef) = +let rec buildTypeDefPass3 cenv nesting modB emEnv (tdef: ILTypeDef) = let tref = mkRefForNestedILTypeDef ILScopeRef.Local (nesting, tdef) let typB = envGetTypB emEnv tref let emEnv = envPushTyvars emEnv (getGenericArgumentsOfType (typB.AsType())) @@ -1894,7 +1894,7 @@ let rec buildTypeDefPass3 cenv nesting modB emEnv (tdef : ILTypeDef) = //---------------------------------------------------------------------------- -let getEnclosingTypeRefs (tref:ILTypeRef) = +let getEnclosingTypeRefs (tref: ILTypeRef) = match tref.Enclosing with | [] -> [] | h :: t -> List.scan (fun tr nm -> mkILTyRefInTyRef (tr, nm)) (mkILTyRef(tref.Scope, h)) t @@ -1926,9 +1926,9 @@ let rec getTypeRefsInType (allTypes: CollectTypes) ty acc = let verbose2 = false -let createTypeRef (visited : Dictionary<_, _>, created : Dictionary<_, _>) emEnv tref = +let createTypeRef (visited: Dictionary<_, _>, created: Dictionary<_, _>) emEnv tref = - let rec traverseTypeDef (tref:ILTypeRef) (tdef:ILTypeDef) = + let rec traverseTypeDef (tref: ILTypeRef) (tdef: ILTypeDef) = if verbose2 then dprintf "buildTypeDefPass4: Creating Enclosing Types of %s\n" tdef.Name for enc in getEnclosingTypeRefs tref do traverseTypeRef enc @@ -2009,7 +2009,7 @@ let createTypeRef (visited : Dictionary<_, _>, created : Dictionary<_, _>) emEnv traverseTypeRef tref -let rec buildTypeDefPass4 (visited, created) nesting emEnv (tdef : ILTypeDef) = +let rec buildTypeDefPass4 (visited, created) nesting emEnv (tdef: ILTypeDef) = if verbose2 then dprintf "buildTypeDefPass4 %s\n" tdef.Name let tref = mkRefForNestedILTypeDef ILScopeRef.Local (nesting, tdef) createTypeRef (visited, created) emEnv tref @@ -2023,7 +2023,7 @@ let rec buildTypeDefPass4 (visited, created) nesting emEnv (tdef : ILTypeDef) = // buildModuleType //---------------------------------------------------------------------------- -let buildModuleTypePass1 cenv (modB:ModuleBuilder) emEnv (tdef:ILTypeDef) = +let buildModuleTypePass1 cenv (modB: ModuleBuilder) emEnv (tdef: ILTypeDef) = buildTypeDefPass1 cenv emEnv modB modB.DefineTypeAndLog [] tdef let buildModuleTypePass1b cenv emEnv tdef = buildTypeDefPass1b cenv [] emEnv tdef @@ -2035,7 +2035,7 @@ let buildModuleTypePass4 visited emEnv tdef = buildTypeDefPass4 visited [] emE // buildModuleFragment - only the types the fragment get written //---------------------------------------------------------------------------- -let buildModuleFragment cenv emEnv (asmB : AssemblyBuilder) (modB : ModuleBuilder) (m: ILModuleDef) = +let buildModuleFragment cenv emEnv (asmB: AssemblyBuilder) (modB: ModuleBuilder) (m: ILModuleDef) = let tdefs = m.TypeDefs.AsList let emEnv = (emEnv, tdefs) ||> List.fold (buildModuleTypePass1 cenv modB) @@ -2074,7 +2074,7 @@ let buildModuleFragment cenv emEnv (asmB : AssemblyBuilder) (modB : ModuleBuilde //---------------------------------------------------------------------------- // test hook //---------------------------------------------------------------------------- -let defineDynamicAssemblyAndLog(asmName, flags, asmDir:string) = +let defineDynamicAssemblyAndLog(asmName, flags, asmDir: string) = #if FX_NO_APP_DOMAINS let asmB = AssemblyBuilder.DefineDynamicAssembly(asmName, flags) #else @@ -2110,7 +2110,7 @@ let mkDynamicAssemblyAndModule (assemblyName, optimize, debugInfo, collectible) let modB = asmB.DefineDynamicModuleAndLog(assemblyName, filename, debugInfo) asmB, modB -let emitModuleFragment (ilg, emEnv, asmB : AssemblyBuilder, modB : ModuleBuilder, modul : IL.ILModuleDef, debugInfo : bool, resolveAssemblyRef, tryFindSysILTypeRef) = +let emitModuleFragment (ilg, emEnv, asmB: AssemblyBuilder, modB: ModuleBuilder, modul: IL.ILModuleDef, debugInfo: bool, resolveAssemblyRef, tryFindSysILTypeRef) = let cenv = { ilg = ilg ; generatePdb = debugInfo; resolveAssemblyRef=resolveAssemblyRef; tryFindSysILTypeRef=tryFindSysILTypeRef } let emEnv = buildModuleFragment cenv emEnv asmB modB modul @@ -2120,7 +2120,7 @@ let emitModuleFragment (ilg, emEnv, asmB : AssemblyBuilder, modB : ModuleBuilder // REVIEW: remainder of manifest emitCustomAttrs cenv emEnv asmB.SetCustomAttributeAndLog mani.CustomAttrs // invoke entry point methods - let execEntryPtFun ((typB : TypeBuilder), methodName) () = + let execEntryPtFun ((typB: TypeBuilder), methodName) () = try ignore (typB.InvokeMemberAndLog(methodName, BindingFlags.InvokeMethod ||| BindingFlags.Public ||| BindingFlags.Static, [| |])) None @@ -2141,7 +2141,7 @@ let emitModuleFragment (ilg, emEnv, asmB : AssemblyBuilder, modB : ModuleBuilder // However, casting TypeBuilder to Type is not the same as getting Type proper. // The builder version does not implement all methods on the parent. // -// The emEnv stores (typT:Type) for each tref. +// The emEnv stores (typT: Type) for each tref. // Once the emitted type is created this typT is updated to ensure it is the Type proper. // So Type lookup will return the proper Type not TypeBuilder. let LookupTypeRef cenv emEnv tref = convCreatedTypeRef cenv emEnv tref diff --git a/src/absil/ilsupp.fs b/src/absil/ilsupp.fs index 4f4837238cc..63ff3211f03 100644 --- a/src/absil/ilsupp.fs +++ b/src/absil/ilsupp.fs @@ -45,20 +45,20 @@ let MAX_PATH = 260 let E_FAIL = 0x80004005 -let bytesToWord ((b0 : byte) , (b1 : byte)) = +let bytesToWord ((b0: byte) , (b1: byte)) = (int16)b0 ||| ((int16)b1 <<< 8) -let bytesToDWord ((b0 : byte) , (b1 : byte) , (b2 : byte) , (b3 : byte)) = +let bytesToDWord ((b0: byte) , (b1: byte) , (b2: byte) , (b3: byte)) = (int)b0 ||| ((int)b1 <<< 8) ||| ((int)b2 <<< 16) ||| ((int)b3 <<< 24) -let bytesToQWord ((b0 : byte) , (b1 : byte) , (b2 : byte) , (b3 : byte) , (b4 : byte) , (b5 : byte) , (b6 : byte) , (b7 : byte)) = +let bytesToQWord ((b0: byte) , (b1: byte) , (b2: byte) , (b3: byte) , (b4: byte) , (b5: byte) , (b6: byte) , (b7: byte)) = (int64)b0 ||| ((int64)b1 <<< 8) ||| ((int64)b2 <<< 16) ||| ((int64)b3 <<< 24) ||| ((int64)b4 <<< 32) ||| ((int64)b5 <<< 40) ||| ((int64)b6 <<< 48) ||| ((int64)b7 <<< 56) let dwToBytes n = [| (byte)(n &&& 0xff) ; (byte)((n >>> 8) &&& 0xff) ; (byte)((n >>> 16) &&& 0xff) ; (byte)((n >>> 24) &&& 0xff) |], 4 -let wToBytes (n : int16) = [| (byte)(n &&& 0xffs) ; (byte)((n >>> 8) &&& 0xffs) |], 2 +let wToBytes (n: int16) = [| (byte)(n &&& 0xffs) ; (byte)((n >>> 8) &&& 0xffs) |], 2 #if !FX_NO_LINKEDRESOURCES // REVIEW: factor these classes under one hierarchy, use reflection for creation from buffer and toBytes() // Though, everything I'd like to unify is static - metaclasses? -type IMAGE_FILE_HEADER (m:int16, secs:int16, tds:int32, ptst:int32, nos:int32, soh:int16, c:int16) = +type IMAGE_FILE_HEADER (m: int16, secs: int16, tds: int32, ptst: int32, nos: int32, soh: int16, c: int16) = let mutable machine = m let mutable numberOfSections = secs let mutable timeDateStamp = tds @@ -109,7 +109,7 @@ type IMAGE_FILE_HEADER (m:int16, secs:int16, tds:int32, ptst:int32, nos:int32, s buf.EmitUInt16 ((uint16)characteristics) buf.Close() -let bytesToIFH (buffer : byte[]) (offset : int) = +let bytesToIFH (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_FILE_HEADER.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_FILE_HEADER" IMAGE_FILE_HEADER( bytesToWord(buffer.[offset], buffer.[offset+1]), // Machine @@ -120,7 +120,7 @@ let bytesToIFH (buffer : byte[]) (offset : int) = bytesToWord(buffer.[offset+16], buffer.[offset+17]), // SizeOfOptionalHeader bytesToWord(buffer.[offset+18], buffer.[offset+19])) // Characteristics -type IMAGE_SECTION_HEADER(n:int64, ai:int32, va:int32, srd:int32, prd:int32, pr:int32, pln:int32, nr:int16, nl:int16, c:int32) = +type IMAGE_SECTION_HEADER(n: int64, ai: int32, va: int32, srd: int32, prd: int32, pr: int32, pln: int32, nr: int16, nl: int16, c: int32) = let mutable name = n let mutable addressInfo = ai // PhysicalAddress / VirtualSize let mutable virtualAddress = va @@ -194,7 +194,7 @@ type IMAGE_SECTION_HEADER(n:int64, ai:int32, va:int32, srd:int32, prd:int32, pr: buf.Close() -let bytesToISH (buffer : byte[]) (offset : int) = +let bytesToISH (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_SECTION_HEADER.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_SECTION_HEADER" IMAGE_SECTION_HEADER(bytesToQWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3], buffer.[offset+4], buffer.[offset+5], buffer.[offset+6], buffer.[offset+7]), // Name @@ -208,7 +208,7 @@ let bytesToISH (buffer : byte[]) (offset : int) = bytesToWord(buffer.[offset+34], buffer.[offset+35]), // NumberOfLineNumbers bytesToDWord(buffer.[offset+36], buffer.[offset+37], buffer.[offset+38], buffer.[offset+39])) // Characteristics -type IMAGE_SYMBOL(n:int64, v:int32, sn:int16, t:int16, sc:byte, nas:byte) = +type IMAGE_SYMBOL(n: int64, v: int32, sn: int16, t: int16, sc: byte, nas: byte) = let mutable name = n let mutable value = v let mutable sectionNumber = sn @@ -253,7 +253,7 @@ type IMAGE_SYMBOL(n:int64, v:int32, sn:int16, t:int16, sc:byte, nas:byte) = buf.EmitByte numberOfAuxSymbols buf.Close() -let bytesToIS (buffer : byte[]) (offset : int) = +let bytesToIS (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_SYMBOL.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_SYMBOL" IMAGE_SYMBOL( bytesToQWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3], buffer.[offset+4], buffer.[offset+5], buffer.[offset+6], buffer.[offset+7]), // Name @@ -263,7 +263,7 @@ let bytesToIS (buffer : byte[]) (offset : int) = buffer.[offset+16], // StorageClass buffer.[offset+17]) // NumberOfAuxSymbols -type IMAGE_RELOCATION(va:int32, sti:int32, t:int16) = +type IMAGE_RELOCATION(va: int32, sti: int32, t: int16) = let mutable virtualAddress = va // Also RelocCount let mutable symbolTableIndex = sti let mutable ty = t // type @@ -294,14 +294,14 @@ type IMAGE_RELOCATION(va:int32, sti:int32, t:int16) = buf.EmitUInt16 ((uint16)ty) buf.Close() -let bytesToIR (buffer : byte[]) (offset : int) = +let bytesToIR (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_RELOCATION.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_RELOCATION" IMAGE_RELOCATION( bytesToDWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3]), bytesToDWord(buffer.[offset+4], buffer.[offset+5], buffer.[offset+6], buffer.[offset+7]), bytesToWord(buffer.[offset+8], buffer.[offset+9])) -type IMAGE_RESOURCE_DIRECTORY(c:int32, tds:int32, mjv:int16, mnv:int16, nne:int16, nie:int16) = +type IMAGE_RESOURCE_DIRECTORY(c: int32, tds: int32, mjv: int16, mnv: int16, nne: int16, nie: int16) = let mutable characteristics = c let mutable timeDateStamp = tds let mutable majorVersion = mjv @@ -345,7 +345,7 @@ type IMAGE_RESOURCE_DIRECTORY(c:int32, tds:int32, mjv:int16, mnv:int16, nne:int1 buf.EmitUInt16 ((uint16)numberOfIdEntries) buf.Close() -let bytesToIRD (buffer:byte[]) (offset:int) = +let bytesToIRD (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_RESOURCE_DIRECTORY.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_RESOURCE_DIRECTORY" IMAGE_RESOURCE_DIRECTORY( bytesToDWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3]), // Characteristics @@ -355,7 +355,7 @@ let bytesToIRD (buffer:byte[]) (offset:int) = bytesToWord(buffer.[offset+12], buffer.[offset+13]), // NumberOfNamedEntries bytesToWord(buffer.[offset+14], buffer.[offset+15])) // NumberOfIdEntries -type IMAGE_RESOURCE_DIRECTORY_ENTRY(n:int32, o:int32) = +type IMAGE_RESOURCE_DIRECTORY_ENTRY(n: int32, o: int32) = let mutable name = n let mutable offset = o @@ -381,13 +381,13 @@ type IMAGE_RESOURCE_DIRECTORY_ENTRY(n:int32, o:int32) = buf.EmitInt32 offset buf.Close() -let bytesToIRDE (buffer:byte[]) (offset:int) = +let bytesToIRDE (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_RESOURCE_DIRECTORY_ENTRY.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_RESOURCE_DIRECTORY_ENTRY" IMAGE_RESOURCE_DIRECTORY_ENTRY( bytesToDWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3]), // Name bytesToDWord(buffer.[offset+4], buffer.[offset+5], buffer.[offset+6], buffer.[offset+7])) // Offset -type IMAGE_RESOURCE_DATA_ENTRY(o:int32, s:int32, c:int32, r:int32) = +type IMAGE_RESOURCE_DATA_ENTRY(o: int32, s: int32, c: int32, r: int32) = let mutable offsetToData = o let mutable size = s let mutable codePage = c @@ -415,7 +415,7 @@ type IMAGE_RESOURCE_DATA_ENTRY(o:int32, s:int32, c:int32, r:int32) = buf.EmitInt32 codePage buf.EmitInt32 reserved -let bytesToIRDataE (buffer:byte[]) (offset:int) = +let bytesToIRDataE (buffer: byte[]) (offset: int) = if (buffer.Length - offset) < IMAGE_RESOURCE_DATA_ENTRY.Width then invalidArg "buffer" "buffer too small to fit an IMAGE_RESOURCE_DATA_ENTRY" IMAGE_RESOURCE_DATA_ENTRY(bytesToDWord(buffer.[offset], buffer.[offset+1], buffer.[offset+2], buffer.[offset+3]), // OffsetToData @@ -478,7 +478,7 @@ type ResFormatHeader() = buf.EmitInt32 dwCharacteristics buf.Close() -type ResFormatNode(tid:int32, nid:int32, lid:int32, dataOffset:int32, pbLinkedResource:byte[]) = +type ResFormatNode(tid: int32, nid: int32, lid: int32, dataOffset: int32, pbLinkedResource: byte[]) = let mutable resHdr = ResFormatHeader() let mutable dataEntry = Unchecked.defaultof let mutable cType = 0 @@ -518,7 +518,7 @@ type ResFormatNode(tid:int32, nid:int32, lid:int32, dataOffset:int32, pbLinkedRe member x.Name with get() = wzName - member x.Save(ulLinkedResourceBaseRVA:int32, pbLinkedResource:byte[], pUnlinkedResource:byte[], offset:int) = + member x.Save(ulLinkedResourceBaseRVA: int32, pbLinkedResource: byte[], pUnlinkedResource: byte[], offset: int) = // Dump them to pUnlinkedResource // For each resource write header and data let size = ref 0 @@ -529,7 +529,7 @@ type ResFormatNode(tid:int32, nid:int32, lid:int32, dataOffset:int32, pbLinkedRe if Unchecked.defaultof <> wzName then resHdr.HeaderSize <- resHdr.HeaderSize + ((cName + 1) * 2) - 4 - let SaveChunk(p : byte[], sz : int) = + let SaveChunk(p: byte[], sz: int) = if Unchecked.defaultof <> pUnlinkedResource then Bytes.blit p 0 pUnlinkedResource (!unlinkedResourceOffset + offset) sz unlinkedResourceOffset := !unlinkedResourceOffset + sz @@ -537,7 +537,7 @@ type ResFormatNode(tid:int32, nid:int32, lid:int32, dataOffset:int32, pbLinkedRe () - // ---- Constant part of the header : DWORD, DWORD + // ---- Constant part of the header: DWORD, DWORD SaveChunk(dwToBytes resHdr.DataSize) SaveChunk(dwToBytes resHdr.HeaderSize) @@ -578,10 +578,10 @@ type ResFormatNode(tid:int32, nid:int32, lid:int32, dataOffset:int32, pbLinkedRe !size -let linkNativeResources (unlinkedResources:byte[] list) (ulLinkedResourceBaseRVA:int32) (fileType:PEFileType) (outputFilePath:string) = +let linkNativeResources (unlinkedResources: byte[] list) (ulLinkedResourceBaseRVA: int32) (fileType: PEFileType) (outputFilePath: string) = let nPEFileType = match fileType with X86 -> 0 | X64 -> 2 - let mutable tempResFiles : string list = [] - let mutable objBytes : byte[] = [||] + let mutable tempResFiles: string list = [] + let mutable objBytes: byte[] = [||] let unlinkedResources = unlinkedResources |> List.filter (fun arr -> arr.Length > 0) if isNil unlinkedResources then // bail if there's nothing to link @@ -619,7 +619,7 @@ let linkNativeResources (unlinkedResources:byte[] list) (ulLinkedResourceBaseRV let createCvtresArgs path = let tempObjFileName = GetUniqueRandomFileName(path) let mutable cmdLineArgs = sprintf "%s \"/Out:%s\"" cmdLineArgsPreamble tempObjFileName - let mutable resFiles : string list = [] + let mutable resFiles: string list = [] for _ulr in unlinkedResources do let tempResFileName = GetUniqueRandomFileName(path) @@ -633,7 +633,7 @@ let linkNativeResources (unlinkedResources:byte[] list) (ulLinkedResourceBaseRV let attempts = outputFilePaths |> List.map (fun path -> createCvtresArgs path) |> - List.filter (fun ((argstring:string),(_t:string),(_f:string list)) -> (cvtres.Length + argstring.Length) < MAX_PATH) + List.filter (fun ((argstring: string),(_t: string),(_f: string list)) -> (cvtres.Length + argstring.Length) < MAX_PATH) let invoc,tmp,files = match attempts with | [] -> createCvtresArgs ".\\" // hope for the best... @@ -717,7 +717,7 @@ let linkNativeResources (unlinkedResources:byte[] list) (ulLinkedResourceBaseRV let IMAGE_SYM_CLASS_STATIC = 0x3uy let IMAGE_SYM_TYPE_NULL = 0x0s - let GetSymbolEntry (buffer : byte[]) (idx : int) = + let GetSymbolEntry (buffer: byte[]) (idx: int) = bytesToIS buffer (symbolTableHead + (idx * IMAGE_SYMBOL.Width) ) for iReloc = 0 to (int)(rsrc01.NumberOfRelocations - 1s) do @@ -746,7 +746,7 @@ let linkNativeResources (unlinkedResources:byte[] list) (ulLinkedResourceBaseRV // return the buffer pResBuffer -let unlinkResource (ulLinkedResourceBaseRVA:int32) (pbLinkedResource:byte[]) = +let unlinkResource (ulLinkedResourceBaseRVA: int32) (pbLinkedResource: byte[]) = let mutable nResNodes = 0 let pirdType = bytesToIRD pbLinkedResource 0 @@ -778,7 +778,7 @@ let unlinkResource (ulLinkedResourceBaseRVA:int32) (pbLinkedResource:byte[]) = else nResNodes <- nResNodes + 1 - let pResNodes : ResFormatNode [] = Array.zeroCreate nResNodes + let pResNodes: ResFormatNode [] = Array.zeroCreate nResNodes nResNodes <- 0 // fill out the entry buffer @@ -857,153 +857,153 @@ let unlinkResource (ulLinkedResourceBaseRVA:int32) (pbLinkedResource:byte[]) = [] [] type IMetaDataDispenser = - abstract DefineScope : unit -> unit // need this here to fill the first vtable slot - abstract OpenScope : [] szScope : string * [] dwOpenFlags:Int32 * [] riid : System.Guid byref * [] punk:Object byref -> unit + abstract DefineScope: unit -> unit // need this here to fill the first vtable slot + abstract OpenScope: [] szScope: string * [] dwOpenFlags: Int32 * [] riid: System.Guid byref * [] punk: Object byref -> unit [] [] [] type IMetadataImport = - abstract Placeholder : unit -> unit + abstract Placeholder: unit -> unit [] [] [] type IMetadataEmit = - abstract Placeholder : unit -> unit + abstract Placeholder: unit -> unit [] [< Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006") ; InterfaceType(ComInterfaceType.InterfaceIsIUnknown) >] [< ComVisible(false) >] type ISymUnmanagedDocumentWriter = - abstract SetSource : sourceSize : int * [] source : byte[] -> unit - abstract SetCheckSum : algorithmId : System.Guid * checkSumSize : int * [] checkSum : byte [] -> unit + abstract SetSource: sourceSize: int * [] source: byte[] -> unit + abstract SetCheckSum: algorithmId: System.Guid * checkSumSize: int * [] checkSum: byte [] -> unit // Struct used to retrieve info on the debug output [] type ImageDebugDirectory = - val Characteristics : int32 - val TimeDateStamp : int32 - val MajorVersion : int16 - val MinorVersion : int16 - val Type : int32 - val SizeOfData : int32 - val AddressOfRawData : int32 - val PointerToRawData : int32 + val Characteristics: int32 + val TimeDateStamp: int32 + val MajorVersion: int16 + val MinorVersion: int16 + val Type: int32 + val SizeOfData: int32 + val AddressOfRawData: int32 + val PointerToRawData: int32 [] [] type ISymUnmanagedWriter2 = - abstract DefineDocument : [] url : string * - language : System.Guid byref * - languageVendor : System.Guid byref * - documentType : System.Guid byref * - [] RetVal : ISymUnmanagedDocumentWriter byref -> unit - abstract SetUserEntryPoint : entryMethod : uint32 -> unit - abstract OpenMethod : meth : int -> unit - abstract CloseMethod : unit -> unit - abstract OpenScope : startOffset : int * pRetVal : int byref -> unit - abstract CloseScope : endOffset : int -> unit - abstract SetScopeRange : scopeID : int * startOffset : int * endOffset : int -> unit - abstract DefineLocalVariable : [] varname : string * - attributes : int * - cSig : int * - []signature : byte[] * - addressKind : int * - addr1 : int * - addr2 : int * - addr3 : int * - startOffset : int * - endOffset : int -> unit - abstract DefineParameter : [] paramname : string * - attributes : int * - sequence : int * - addressKind : int * - addr1 : int * - addr2 : int * - addr3 : int -> unit - abstract DefineField : parent : int * - [] fieldname : string * - attributes : int * - cSig : int * - []signature : byte[] * - addressKind : int * - addr1 : int * - addr2 : int * - addr3 : int -> unit - abstract DefineGlobalVariable : [] globalvarname : string * - attributes : int * - cSig : int * - []signature : byte[] * - addressKind : int * - addr1 : int * - addr2 : int * - addr3 : int -> unit - abstract Close : unit -> unit - abstract SetSymAttribute : parent : int * - [] attname : string * - cData : int * - []data : byte[] -> unit - abstract OpenNamespace : [] nsname : string -> unit - abstract CloseNamespace : unit -> unit - abstract UsingNamespace : [] fullName : string -> unit - abstract SetMethodSourceRange : startDoc : ISymUnmanagedDocumentWriter * - startLine : int * - startColumn : int * - endDoc : ISymUnmanagedDocumentWriter * - endLine : int * - endColumn : int -> unit - abstract Initialize : emitter : nativeint * - [] filename : string * - stream : IStream * - fullBuild : bool -> unit - abstract GetDebugInfo : iDD : ImageDebugDirectory byref * - cData : int * - pcData : int byref * - []data : byte[] -> unit - abstract DefineSequencePoints : document : ISymUnmanagedDocumentWriter * - spCount : int * - []offsets : int [] * - []lines : int [] * - []columns : int [] * - []endLines : int [] * - []endColumns : int [] -> unit - abstract RemapToken : oldToken : int * newToken : int -> unit - abstract Initialize2 : emitter : nativeint * - [] tempfilename : string * - stream : IStream * - fullBuild : bool * - [] finalfilename : string -> unit - abstract DefineConstant : [] constname : string * - value : Object * - cSig : int * - []signature : byte[] -> unit - abstract Abort : unit -> unit - abstract DefineLocalVariable2 : [] localvarname2 : string * - attributes : int * - sigToken : int * - addressKind : int * - addr1 : int * - addr2 : int * - addr3 : int * - startOffset : int * - endOffset : int -> unit - abstract DefineGlobalVariable2 : [] globalvarname2 : string * - attributes : int * - sigToken : int * - addressKind : int * - addr1 : int * - addr2 : int * - addr3 : int -> unit - abstract DefineConstant2 : [] constantname2 : string * - value : Object * - sigToken : int -> unit - abstract OpenMethod2 : method2 : int * - isect : int * - offset : int -> unit - -type PdbWriter = { symWriter : ISymUnmanagedWriter2 } -type PdbDocumentWriter = { symDocWriter : ISymUnmanagedDocumentWriter } (* pointer to pDocumentWriter COM object *) + abstract DefineDocument: [] url: string * + language: System.Guid byref * + languageVendor: System.Guid byref * + documentType: System.Guid byref * + [] RetVal: ISymUnmanagedDocumentWriter byref -> unit + abstract SetUserEntryPoint: entryMethod: uint32 -> unit + abstract OpenMethod: meth: int -> unit + abstract CloseMethod: unit -> unit + abstract OpenScope: startOffset: int * pRetVal: int byref -> unit + abstract CloseScope: endOffset: int -> unit + abstract SetScopeRange: scopeID: int * startOffset: int * endOffset: int -> unit + abstract DefineLocalVariable: [] varname: string * + attributes: int * + cSig: int * + []signature: byte[] * + addressKind: int * + addr1: int * + addr2: int * + addr3: int * + startOffset: int * + endOffset: int -> unit + abstract DefineParameter: [] paramname: string * + attributes: int * + sequence: int * + addressKind: int * + addr1: int * + addr2: int * + addr3: int -> unit + abstract DefineField: parent: int * + [] fieldname: string * + attributes: int * + cSig: int * + []signature: byte[] * + addressKind: int * + addr1: int * + addr2: int * + addr3: int -> unit + abstract DefineGlobalVariable: [] globalvarname: string * + attributes: int * + cSig: int * + []signature: byte[] * + addressKind: int * + addr1: int * + addr2: int * + addr3: int -> unit + abstract Close: unit -> unit + abstract SetSymAttribute: parent: int * + [] attname: string * + cData: int * + []data: byte[] -> unit + abstract OpenNamespace: [] nsname: string -> unit + abstract CloseNamespace: unit -> unit + abstract UsingNamespace: [] fullName: string -> unit + abstract SetMethodSourceRange: startDoc: ISymUnmanagedDocumentWriter * + startLine: int * + startColumn: int * + endDoc: ISymUnmanagedDocumentWriter * + endLine: int * + endColumn: int -> unit + abstract Initialize: emitter: nativeint * + [] filename: string * + stream: IStream * + fullBuild: bool -> unit + abstract GetDebugInfo: iDD: ImageDebugDirectory byref * + cData: int * + pcData: int byref * + []data: byte[] -> unit + abstract DefineSequencePoints: document: ISymUnmanagedDocumentWriter * + spCount: int * + []offsets: int [] * + []lines: int [] * + []columns: int [] * + []endLines: int [] * + []endColumns: int [] -> unit + abstract RemapToken: oldToken: int * newToken: int -> unit + abstract Initialize2: emitter: nativeint * + [] tempfilename: string * + stream: IStream * + fullBuild: bool * + [] finalfilename: string -> unit + abstract DefineConstant: [] constname: string * + value: Object * + cSig: int * + []signature: byte[] -> unit + abstract Abort: unit -> unit + abstract DefineLocalVariable2: [] localvarname2: string * + attributes: int * + sigToken: int * + addressKind: int * + addr1: int * + addr2: int * + addr3: int * + startOffset: int * + endOffset: int -> unit + abstract DefineGlobalVariable2: [] globalvarname2: string * + attributes: int * + sigToken: int * + addressKind: int * + addr1: int * + addr2: int * + addr3: int -> unit + abstract DefineConstant2: [] constantname2: string * + value: Object * + sigToken: int -> unit + abstract OpenMethod2: method2: int * + isect: int * + offset: int -> unit + +type PdbWriter = { symWriter: ISymUnmanagedWriter2 } +type PdbDocumentWriter = { symDocWriter: ISymUnmanagedDocumentWriter } (* pointer to pDocumentWriter COM object *) type idd = { iddCharacteristics: int32 iddMajorVersion: int32; (* actually u16 in IMAGE_DEBUG_DIRECTORY *) @@ -1013,7 +1013,7 @@ type idd = #endif #if !FX_NO_PDB_WRITER -let pdbInitialize (binaryName:string) (pdbName:string) = +let pdbInitialize (binaryName: string) (pdbName: string) = // collect necessary COM types let CorMetaDataDispenser = System.Type.GetTypeFromProgID("CLRMetaData.CorMetaDataDispenser") @@ -1036,15 +1036,15 @@ let pdbInitialize (binaryName:string) (pdbName:string) = { symWriter = writer } -[] +[] do() -let pdbCloseDocument(documentWriter : PdbDocumentWriter) = +let pdbCloseDocument(documentWriter: PdbDocumentWriter) = Marshal.ReleaseComObject (documentWriter.symDocWriter) |> ignore -[] -let pdbClose (writer:PdbWriter) dllFilename pdbFilename = +[] +let pdbClose (writer: PdbWriter) dllFilename pdbFilename = writer.symWriter.Close() // CorSymWriter objects (ISymUnmanagedWriter) lock the files they're operating // on (both the pdb and the binary). The locks are released only when their ref @@ -1073,7 +1073,7 @@ let pdbClose (writer:PdbWriter) dllFilename pdbFilename = System.GC.WaitForPendingFinalizers() attempts <- attempts + 1 -let pdbSetUserEntryPoint (writer:PdbWriter) (entryMethodToken:int32) = +let pdbSetUserEntryPoint (writer: PdbWriter) (entryMethodToken: int32) = writer.symWriter.SetUserEntryPoint((uint32)entryMethodToken) // Document checksum algorithms @@ -1084,7 +1084,7 @@ let hashSizeOfMD5 = 16 // If the FIPS algorithm policy is enabled on the computer (e.g., for US government employees and contractors) // then obtaining the MD5 implementation in BCL will throw. // In this case, catch the failure, and not set a checksum. -let internal setCheckSum (url:string, writer:ISymUnmanagedDocumentWriter) = +let internal setCheckSum (url: string, writer: ISymUnmanagedDocumentWriter) = try use file = FileSystem.FileStreamReadShim(url) use md5 = System.Security.Cryptography.MD5.Create() @@ -1093,7 +1093,7 @@ let internal setCheckSum (url:string, writer:ISymUnmanagedDocumentWriter) = writer.SetCheckSum (guidSourceHashMD5, hashSizeOfMD5, checkSum) with _ -> () -let pdbDefineDocument (writer:PdbWriter) (url:string) = +let pdbDefineDocument (writer: PdbWriter) (url: string) = //3F5162F8-07C6-11D3-9053-00C04FA302A1 //let mutable corSymLanguageTypeCSharp = System.Guid(0x3F5162F8u, 0x07C6us, 0x11D3us, 0x90uy, 0x53uy, 0x00uy, 0xC0uy, 0x4Fuy, 0xA3uy, 0x02uy, 0xA1uy) let mutable corSymLanguageTypeFSharp = System.Guid(0xAB4F38C9u, 0xB6E6us, 0x43baus, 0xBEuy, 0x3Buy, 0x58uy, 0x08uy, 0x0Buy, 0x2Cuy, 0xCCuy, 0xE3uy) @@ -1104,27 +1104,27 @@ let pdbDefineDocument (writer:PdbWriter) (url:string) = setCheckSum (url, docWriter) { symDocWriter = docWriter } -let pdbOpenMethod (writer:PdbWriter) (methodToken:int32) = +let pdbOpenMethod (writer: PdbWriter) (methodToken: int32) = writer.symWriter.OpenMethod(methodToken) -let pdbCloseMethod (writer:PdbWriter) = +let pdbCloseMethod (writer: PdbWriter) = writer.symWriter.CloseMethod() -let pdbOpenScope (writer:PdbWriter) (startOffset:int32) = +let pdbOpenScope (writer: PdbWriter) (startOffset: int32) = let mutable retInt = 0 writer.symWriter.OpenScope(startOffset, &retInt) check "action" (retInt) -let pdbCloseScope (writer:PdbWriter) (endOffset:int32) = +let pdbCloseScope (writer: PdbWriter) (endOffset: int32) = writer.symWriter.CloseScope(endOffset) -let pdbDefineLocalVariable (writer:PdbWriter) (name:string) (signature:byte[]) (addr1:int32) = +let pdbDefineLocalVariable (writer: PdbWriter) (name: string) (signature: byte[]) (addr1: int32) = writer.symWriter.DefineLocalVariable(name, 0, signature.Length, signature, (int)System.Diagnostics.SymbolStore.SymAddressKind.ILOffset, addr1, 0, 0, 0, 0) -let pdbSetMethodRange (writer:PdbWriter) (docWriter1: PdbDocumentWriter) (startLine:int) (startCol:int) (docWriter2: PdbDocumentWriter) (endLine:int) (endCol:int) = +let pdbSetMethodRange (writer: PdbWriter) (docWriter1: PdbDocumentWriter) (startLine: int) (startCol: int) (docWriter2: PdbDocumentWriter) (endLine: int) (endCol: int) = writer.symWriter.SetMethodSourceRange(docWriter1.symDocWriter, startLine, startCol, docWriter2.symDocWriter, endLine, endCol) -let pdbDefineSequencePoints (writer:PdbWriter) (docWriter: PdbDocumentWriter) (pts: (int * int * int * int * int) array) = +let pdbDefineSequencePoints (writer: PdbWriter) (docWriter: PdbDocumentWriter) (pts: (int * int * int * int * int)[]) = let offsets = (Array.map (fun (x,_,_,_,_) -> x) pts) let lines = (Array.map (fun (_,x,_,_,_) -> x) pts) let columns = (Array.map (fun (_,_,x,_,_) -> x) pts) @@ -1136,7 +1136,7 @@ let pdbWriteDebugInfo (writer: PdbWriter) = let mutable iDD = new ImageDebugDirectory() let mutable length = 0 writer.symWriter.GetDebugInfo(&iDD, 0, &length, null) - let mutable data : byte [] = Array.zeroCreate length + let mutable data: byte [] = Array.zeroCreate length writer.symWriter.GetDebugInfo(&iDD, length, &length, data) { iddCharacteristics = iDD.Characteristics @@ -1163,11 +1163,11 @@ type PdbSequencePoint = pdbSeqPointEndLine: int pdbSeqPointEndColumn: int } -let pdbReadOpen (moduleName:string) (path:string) : PdbReader = +let pdbReadOpen (moduleName: string) (path: string) : PdbReader = let CorMetaDataDispenser = System.Type.GetTypeFromProgID("CLRMetaData.CorMetaDataDispenser") let mutable IID_IMetaDataImport = new Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44") let mdd = System.Activator.CreateInstance(CorMetaDataDispenser) :?> IMetaDataDispenser - let mutable o : Object = new Object() + let mutable o: Object = new Object() mdd.OpenScope(moduleName, 0, &IID_IMetaDataImport, &o) let importerPtr = Marshal.GetComInterfaceForObject(o, typeof) try @@ -1193,44 +1193,44 @@ let pdbReadOpen (moduleName:string) (path:string) : PdbReader = // The symbol reader's finalize method will clean up any unmanaged resources. // If file locks persist, we may want to manually invoke finalize -let pdbReadClose (_reader:PdbReader) : unit = () +let pdbReadClose (_reader: PdbReader) : unit = () -let pdbReaderGetMethod (reader:PdbReader) (token:int32) : PdbMethod = +let pdbReaderGetMethod (reader: PdbReader) (token: int32) : PdbMethod = { symMethod = reader.symReader.GetMethod(System.Diagnostics.SymbolStore.SymbolToken(token)) } -let pdbReaderGetMethodFromDocumentPosition (reader:PdbReader) (document:PdbDocument) (line:int) (column:int) : PdbMethod = +let pdbReaderGetMethodFromDocumentPosition (reader: PdbReader) (document: PdbDocument) (line: int) (column: int) : PdbMethod = { symMethod = reader.symReader.GetMethodFromDocumentPosition(document.symDocument, line, column) } -let pdbReaderGetDocuments (reader:PdbReader) : PdbDocument array = +let pdbReaderGetDocuments (reader: PdbReader) : PdbDocument[] = let arr = reader.symReader.GetDocuments() Array.map (fun i -> { symDocument=i }) arr -let pdbReaderGetDocument (reader:PdbReader) (url:string) (language:byte[]) (languageVendor:byte[]) (documentType:byte[]) : PdbDocument = +let pdbReaderGetDocument (reader: PdbReader) (url: string) (language: byte[]) (languageVendor: byte[]) (documentType: byte[]) : PdbDocument = { symDocument = reader.symReader.GetDocument(url, System.Guid(language), System.Guid(languageVendor), System.Guid(documentType)) } -let pdbDocumentGetURL (document:PdbDocument) : string = +let pdbDocumentGetURL (document: PdbDocument) : string = document.symDocument.URL -let pdbDocumentGetType (document:PdbDocument) : byte[] (* guid *) = +let pdbDocumentGetType (document: PdbDocument) : byte[] (* guid *) = let guid = document.symDocument.DocumentType guid.ToByteArray() -let pdbDocumentGetLanguage (document:PdbDocument) : byte[] (* guid *) = +let pdbDocumentGetLanguage (document: PdbDocument) : byte[] (* guid *) = let guid = document.symDocument.Language guid.ToByteArray() -let pdbDocumentGetLanguageVendor (document:PdbDocument) : byte[] = +let pdbDocumentGetLanguageVendor (document: PdbDocument) : byte[] = let guid = document.symDocument.LanguageVendor guid.ToByteArray() -let pdbDocumentFindClosestLine (document:PdbDocument) (line:int) : int = +let pdbDocumentFindClosestLine (document: PdbDocument) (line: int) : int = document.symDocument.FindClosestLine(line) -let pdbMethodGetToken (meth:PdbMethod) : int32 = +let pdbMethodGetToken (meth: PdbMethod) : int32 = let token = meth.symMethod.Token token.GetToken() -let pdbMethodGetSequencePoints (meth:PdbMethod) : PdbSequencePoint array = +let pdbMethodGetSequencePoints (meth: PdbMethod) : PdbSequencePoint[] = let pSize = meth.symMethod.SequencePointCount let offsets = Array.zeroCreate pSize let docs = Array.zeroCreate pSize @@ -1249,25 +1249,25 @@ let pdbMethodGetSequencePoints (meth:PdbMethod) : PdbSequencePoint array = pdbSeqPointEndLine = endLines.[i] pdbSeqPointEndColumn = endColumns.[i] }) -let pdbScopeGetChildren (scope:PdbMethodScope) : PdbMethodScope array = +let pdbScopeGetChildren (scope: PdbMethodScope) : PdbMethodScope[] = let arr = scope.symScope.GetChildren() Array.map (fun i -> { symScope=i }) arr -let pdbScopeGetOffsets (scope:PdbMethodScope) : int * int = +let pdbScopeGetOffsets (scope: PdbMethodScope) : int * int = (scope.symScope.StartOffset, scope.symScope.EndOffset) -let pdbScopeGetLocals (scope:PdbMethodScope) : PdbVariable array = +let pdbScopeGetLocals (scope: PdbMethodScope) : PdbVariable[] = let arr = scope.symScope.GetLocals() Array.map (fun i -> { symVariable=i }) arr -let pdbVariableGetName (variable:PdbVariable) : string = +let pdbVariableGetName (variable: PdbVariable) : string = variable.symVariable.Name -let pdbVariableGetSignature (variable:PdbVariable) : byte[] = +let pdbVariableGetSignature (variable: PdbVariable) : byte[] = variable.symVariable.GetSignature() // The tuple is (AddressKind, AddressField1) -let pdbVariableGetAddressAttributes (variable:PdbVariable) : (int32 * int32) = +let pdbVariableGetAddressAttributes (variable: PdbVariable) : (int32 * int32) = (int32 variable.symVariable.AddressKind,variable.symVariable.AddressField1) #endif @@ -1283,23 +1283,23 @@ let signerOpenPublicKeyFile filePath = FileSystem.ReadAllBytesShim(filePath) let signerOpenKeyPairFile filePath = FileSystem.ReadAllBytesShim(filePath) -let signerGetPublicKeyForKeyPair (kp:keyPair) : pubkey = +let signerGetPublicKeyForKeyPair (kp: keyPair) : pubkey = let reply = (StrongNameSign.getPublicKeyForKeyPair kp) reply -let signerGetPublicKeyForKeyContainer (_kcName:keyContainerName) : pubkey = +let signerGetPublicKeyForKeyContainer (_kcName: keyContainerName) : pubkey = raise (NotImplementedException("signerGetPublicKeyForKeyContainer is not yet implemented")) -let signerCloseKeyContainer (_kc:keyContainerName) :unit = +let signerCloseKeyContainer (_kc: keyContainerName) : unit = raise (NotImplementedException("signerCloseKeyContainer is not yet implemented")) -let signerSignatureSize (pk:pubkey) : int = +let signerSignatureSize (pk: pubkey) : int = (StrongNameSign.signatureSize pk) -let signerSignFileWithKeyPair (fileName:string) (kp:keyPair) :unit = +let signerSignFileWithKeyPair (fileName: string) (kp: keyPair) : unit = (StrongNameSign.signFile fileName kp) -let signerSignFileWithKeyContainer (_fileName:string) (_kcName:keyContainerName) : unit = +let signerSignFileWithKeyContainer (_fileName: string) (_kcName: keyContainerName) : unit = raise (NotImplementedException("signerSignFileWithKeyContainer is not yet implemented")) #else @@ -1310,104 +1310,104 @@ type UnusedCOMMethod = unit -> unit [] type ICLRMetaHost = [] - abstract GetRuntime : - [] version : string * - [] interfaceId : System.Guid -> [] System.Object + abstract GetRuntime: + [] version: string * + [] interfaceId: System.Guid -> [] System.Object // Methods that we don't need are stubbed out for now... - abstract GetVersionFromFile : UnusedCOMMethod - abstract EnumerateInstalledRuntimes : UnusedCOMMethod - abstract EnumerateLoadedRuntimes : UnusedCOMMethod - abstract Reserved01 : UnusedCOMMethod + abstract GetVersionFromFile: UnusedCOMMethod + abstract EnumerateInstalledRuntimes: UnusedCOMMethod + abstract EnumerateLoadedRuntimes: UnusedCOMMethod + abstract Reserved01: UnusedCOMMethod // We don't currently support ComConversionLoss [] [] type ICLRStrongName = // Methods that we don't need are stubbed out for now... - abstract GetHashFromAssemblyFile : UnusedCOMMethod - abstract GetHashFromAssemblyFileW : UnusedCOMMethod - abstract GetHashFromBlob : UnusedCOMMethod - abstract GetHashFromFile : UnusedCOMMethod - abstract GetHashFromFileW : UnusedCOMMethod - abstract GetHashFromHandle : UnusedCOMMethod - abstract StrongNameCompareAssemblies : UnusedCOMMethod + abstract GetHashFromAssemblyFile: UnusedCOMMethod + abstract GetHashFromAssemblyFileW: UnusedCOMMethod + abstract GetHashFromBlob: UnusedCOMMethod + abstract GetHashFromFile: UnusedCOMMethod + abstract GetHashFromFileW: UnusedCOMMethod + abstract GetHashFromHandle: UnusedCOMMethod + abstract StrongNameCompareAssemblies: UnusedCOMMethod [] - abstract StrongNameFreeBuffer : [] pbMemory : nativeint -> unit + abstract StrongNameFreeBuffer: [] pbMemory: nativeint -> unit - abstract StrongNameGetBlob : UnusedCOMMethod - abstract StrongNameGetBlobFromImage : UnusedCOMMethod + abstract StrongNameGetBlob: UnusedCOMMethod + abstract StrongNameGetBlobFromImage: UnusedCOMMethod [] abstract StrongNameGetPublicKey : - [] pwzKeyContainer : string * - [] pbKeyBlob : byte[] * - [] cbKeyBlob : uint32 * - [] ppbPublicKeyBlob : nativeint byref * - [] pcbPublicKeyBlob : uint32 byref -> unit + [] pwzKeyContainer: string * + [] pbKeyBlob: byte[] * + [] cbKeyBlob: uint32 * + [] ppbPublicKeyBlob: nativeint byref * + [] pcbPublicKeyBlob: uint32 byref -> unit - abstract StrongNameHashSize : UnusedCOMMethod + abstract StrongNameHashSize: UnusedCOMMethod [] - abstract StrongNameKeyDelete : [] pwzKeyContainer : string -> unit + abstract StrongNameKeyDelete: [] pwzKeyContainer: string -> unit - abstract StrongNameKeyGen : UnusedCOMMethod - abstract StrongNameKeyGenEx : UnusedCOMMethod - abstract StrongNameKeyInstall : UnusedCOMMethod + abstract StrongNameKeyGen: UnusedCOMMethod + abstract StrongNameKeyGenEx: UnusedCOMMethod + abstract StrongNameKeyInstall: UnusedCOMMethod [] abstract StrongNameSignatureGeneration : - [] pwzFilePath : string * - [] pwzKeyContainer : string * - [] pbKeyBlob : byte [] * - [] cbKeyBlob : uint32 * - [] ppbSignatureBlob : nativeint * - [] pcbSignatureBlob : uint32 byref -> unit + [] pwzFilePath: string * + [] pwzKeyContainer: string * + [] pbKeyBlob: byte [] * + [] cbKeyBlob: uint32 * + [] ppbSignatureBlob: nativeint * + [] pcbSignatureBlob: uint32 byref -> unit - abstract StrongNameSignatureGenerationEx : UnusedCOMMethod + abstract StrongNameSignatureGenerationEx: UnusedCOMMethod [] abstract StrongNameSignatureSize : - [] pbPublicKeyBlob : byte[] * - [] cbPublicKeyBlob : uint32 * - [] pcbSize : uint32 byref -> unit + [] pbPublicKeyBlob: byte[] * + [] cbPublicKeyBlob: uint32 * + [] pcbSize: uint32 byref -> unit - abstract StrongNameSignatureVerification : UnusedCOMMethod + abstract StrongNameSignatureVerification: UnusedCOMMethod [] abstract StrongNameSignatureVerificationEx : - [] pwzFilePath : string * - [] fForceVerification : bool * - [] pfWasVerified : bool byref -> [] bool + [] pwzFilePath: string * + [] fForceVerification: bool * + [] pfWasVerified: bool byref -> [] bool - abstract StrongNameSignatureVerificationFromImage : UnusedCOMMethod - abstract StrongNameTokenFromAssembly : UnusedCOMMethod - abstract StrongNameTokenFromAssemblyEx : UnusedCOMMethod - abstract StrongNameTokenFromPublicKey : UnusedCOMMethod + abstract StrongNameSignatureVerificationFromImage: UnusedCOMMethod + abstract StrongNameTokenFromAssembly: UnusedCOMMethod + abstract StrongNameTokenFromAssemblyEx: UnusedCOMMethod + abstract StrongNameTokenFromPublicKey: UnusedCOMMethod [] [] type ICLRRuntimeInfo = // REVIEW: Methods that we don't need will be stubbed out for now... - abstract GetVersionString : unit -> unit - abstract GetRuntimeDirectory : unit -> unit - abstract IsLoaded : unit -> unit - abstract LoadErrorString : unit -> unit - abstract LoadLibrary : unit -> unit - abstract GetProcAddress : unit -> unit + abstract GetVersionString: unit -> unit + abstract GetRuntimeDirectory: unit -> unit + abstract IsLoaded: unit -> unit + abstract LoadErrorString: unit -> unit + abstract LoadLibrary: unit -> unit + abstract GetProcAddress: unit -> unit [] abstract GetInterface : - [] coClassId : System.Guid * - [] interfaceId : System.Guid -> []System.Object + [] coClassId: System.Guid * + [] interfaceId: System.Guid -> []System.Object [] [] let CreateInterface ( - ([] _clsidguid : System.Guid), - ([] _guid : System.Guid), + ([] _clsidguid: System.Guid), + ([] _guid: System.Guid), ([] _metaHost : ICLRMetaHost byref)) : unit = failwith "CreateInterface" @@ -1415,7 +1415,7 @@ let signerOpenPublicKeyFile filePath = FileSystem.ReadAllBytesShim(filePath) let signerOpenKeyPairFile filePath = FileSystem.ReadAllBytesShim(filePath) -let mutable iclrsn : ICLRStrongName option = None +let mutable iclrsn: ICLRStrongName option = None let getICLRStrongName () = match iclrsn with | None -> @@ -1445,11 +1445,11 @@ let signerGetPublicKeyForKeyPair kp = snt.InvokeMember("PublicKey", (BindingFlags.GetProperty ||| BindingFlags.Instance ||| BindingFlags.Public), null, sn, [| |], Globalization.CultureInfo.InvariantCulture) :?> byte[] else let mutable pSize = 0u - let mutable pBuffer : nativeint = (nativeint)0 + let mutable pBuffer: nativeint = (nativeint)0 let iclrSN = getICLRStrongName() iclrSN.StrongNameGetPublicKey(Unchecked.defaultof, kp, (uint32) kp.Length, &pBuffer, &pSize) |> ignore - let mutable keybuffer : byte [] = Bytes.zeroCreate ((int)pSize) + let mutable keybuffer: byte [] = Bytes.zeroCreate ((int)pSize) // Copy the marshalled data over - we'll have to free this ourselves Marshal.Copy(pBuffer, keybuffer, 0, (int)pSize) iclrSN.StrongNameFreeBuffer(pBuffer) |> ignore @@ -1457,10 +1457,10 @@ let signerGetPublicKeyForKeyPair kp = let signerGetPublicKeyForKeyContainer kc = let mutable pSize = 0u - let mutable pBuffer : nativeint = (nativeint)0 + let mutable pBuffer: nativeint = (nativeint)0 let iclrSN = getICLRStrongName() iclrSN.StrongNameGetPublicKey(kc, Unchecked.defaultof, 0u, &pBuffer, &pSize) |> ignore - let mutable keybuffer : byte [] = Bytes.zeroCreate ((int)pSize) + let mutable keybuffer: byte [] = Bytes.zeroCreate ((int)pSize) // Copy the marshalled data over - we'll have to free this ourselves later Marshal.Copy(pBuffer, keybuffer, 0, (int)pSize) iclrSN.StrongNameFreeBuffer(pBuffer) |> ignore @@ -1470,7 +1470,7 @@ let signerCloseKeyContainer kc = let iclrSN = getICLRStrongName() iclrSN.StrongNameKeyDelete(kc) |> ignore -let signerSignatureSize (pk:byte[]) = +let signerSignatureSize (pk: byte[]) = if IL.runningOnMono then if pk.Length > 32 then pk.Length - 32 else 128 else @@ -1483,7 +1483,7 @@ let signerSignFileWithKeyPair fileName kp = if IL.runningOnMono then let snt = System.Type.GetType("Mono.Security.StrongName") let sn = System.Activator.CreateInstance(snt, [| box kp |]) - let conv (x:obj) = if (unbox x : bool) then 0 else -1 + let conv (x: obj) = if (unbox x: bool) then 0 else -1 snt.InvokeMember("Sign", (BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| BindingFlags.Public), null, sn, [| box fileName |], Globalization.CultureInfo.InvariantCulture) |> conv |> check "Sign" snt.InvokeMember("Verify", (BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| BindingFlags.Public), null, sn, [| box fileName |], Globalization.CultureInfo.InvariantCulture) |> conv |> check "Verify" else diff --git a/src/absil/ilwrite.fs b/src/absil/ilwrite.fs index a3a4d61f7f5..74cbc5e43b1 100644 --- a/src/absil/ilwrite.fs +++ b/src/absil/ilwrite.fs @@ -49,8 +49,8 @@ let dw2 n = byte ((n >>> 16) &&& 0xFFL) let dw1 n = byte ((n >>> 8) &&& 0xFFL) let dw0 n = byte (n &&& 0xFFL) -let bitsOfSingle (x:float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) -let bitsOfDouble (x:float) = System.BitConverter.DoubleToInt64Bits(x) +let bitsOfSingle (x: float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) +let bitsOfDouble (x: float) = System.BitConverter.DoubleToInt64Bits(x) let emitBytesViaBuffer f = let bb = ByteBuffer.Create 10 in f bb; bb.Close() @@ -104,7 +104,7 @@ type ByteBuffer with if big then buf.EmitInt32 idx2 else buf.EmitInt32AsUInt16 idx2 -let getUncodedToken (tab:TableName) idx = ((tab.Index <<< 24) ||| idx) +let getUncodedToken (tab: TableName) idx = ((tab.Index <<< 24) ||| idx) // From ECMA for UserStrings: // This final byte holds the value 1 if and only if any UTF16 character within the string has any bit set in its top byte, or its low byte is any of the following: @@ -114,7 +114,7 @@ let getUncodedToken (tab:TableName) idx = ((tab.Index <<< 24) ||| idx) // HOWEVER, there is a discrepancy here between the ECMA spec and the Microsoft C# implementation. // The code below follows the latter. We've raised the issue with both teams. See Dev10 bug 850073 for details. -let markerForUnicodeBytes (b:byte[]) = +let markerForUnicodeBytes (b: byte[]) = let len = b.Length let rec scan i = i < len/2 && @@ -143,7 +143,7 @@ let checkFixup32 (data: byte[]) offset exp = if data.[offset + 1] <> b1 exp then failwith "fixup sanity check failed" if data.[offset] <> b0 exp then failwith "fixup sanity check failed" -let applyFixup32 (data:byte[]) offset v = +let applyFixup32 (data: byte[]) offset v = data.[offset] <- b0 v data.[offset+1] <- b1 v data.[offset+2] <- b2 v @@ -278,38 +278,38 @@ module RowElementTags = let [] ResolutionScopeMax = 178 [] -type RowElement(tag:int32, idx: int32) = +type RowElement(tag: int32, idx: int32) = member x.Tag = tag member x.Val = idx // These create RowElements -let UShort (x:uint16) = RowElement(RowElementTags.UShort, int32 x) -let ULong (x:int32) = RowElement(RowElementTags.ULong, x) +let UShort (x: uint16) = RowElement(RowElementTags.UShort, int32 x) +let ULong (x: int32) = RowElement(RowElementTags.ULong, x) /// Index into cenv.data or cenv.resources. Gets fixed up later once we known an overall /// location for the data section. flag indicates if offset is relative to cenv.resources. -let Data (x:int, k:bool) = RowElement((if k then RowElementTags.DataResources else RowElementTags.Data ), x) +let Data (x: int, k: bool) = RowElement((if k then RowElementTags.DataResources else RowElementTags.Data ), x) /// pos. in guid array -let Guid (x:int) = RowElement(RowElementTags.Guid, x) +let Guid (x: int) = RowElement(RowElementTags.Guid, x) /// pos. in blob array -let Blob (x:int) = RowElement(RowElementTags.Blob, x) +let Blob (x: int) = RowElement(RowElementTags.Blob, x) /// pos. in string array -let StringE (x:int) = RowElement(RowElementTags.String, x) +let StringE (x: int) = RowElement(RowElementTags.String, x) /// pos. in some table -let SimpleIndex (t, x:int) = RowElement(RowElementTags.SimpleIndex t, x) -let TypeDefOrRefOrSpec (t, x:int) = RowElement(RowElementTags.TypeDefOrRefOrSpec t, x) -let TypeOrMethodDef (t, x:int) = RowElement(RowElementTags.TypeOrMethodDef t, x) -let HasConstant (t, x:int) = RowElement(RowElementTags.HasConstant t, x) -let HasCustomAttribute (t, x:int) = RowElement(RowElementTags.HasCustomAttribute t, x) -let HasFieldMarshal (t, x:int) = RowElement(RowElementTags.HasFieldMarshal t, x) -let HasDeclSecurity (t, x:int) = RowElement(RowElementTags.HasDeclSecurity t, x) -let MemberRefParent (t, x:int) = RowElement(RowElementTags.MemberRefParent t, x) -let HasSemantics (t, x:int) = RowElement(RowElementTags.HasSemantics t, x) -let MethodDefOrRef (t, x:int) = RowElement(RowElementTags.MethodDefOrRef t, x) -let MemberForwarded (t, x:int) = RowElement(RowElementTags.MemberForwarded t, x) -let Implementation (t, x:int) = RowElement(RowElementTags.Implementation t, x) -let CustomAttributeType (t, x:int) = RowElement(RowElementTags.CustomAttributeType t, x) -let ResolutionScope (t, x:int) = RowElement(RowElementTags.ResolutionScope t, x) +let SimpleIndex (t, x: int) = RowElement(RowElementTags.SimpleIndex t, x) +let TypeDefOrRefOrSpec (t, x: int) = RowElement(RowElementTags.TypeDefOrRefOrSpec t, x) +let TypeOrMethodDef (t, x: int) = RowElement(RowElementTags.TypeOrMethodDef t, x) +let HasConstant (t, x: int) = RowElement(RowElementTags.HasConstant t, x) +let HasCustomAttribute (t, x: int) = RowElement(RowElementTags.HasCustomAttribute t, x) +let HasFieldMarshal (t, x: int) = RowElement(RowElementTags.HasFieldMarshal t, x) +let HasDeclSecurity (t, x: int) = RowElement(RowElementTags.HasDeclSecurity t, x) +let MemberRefParent (t, x: int) = RowElement(RowElementTags.MemberRefParent t, x) +let HasSemantics (t, x: int) = RowElement(RowElementTags.HasSemantics t, x) +let MethodDefOrRef (t, x: int) = RowElement(RowElementTags.MethodDefOrRef t, x) +let MemberForwarded (t, x: int) = RowElement(RowElementTags.MemberForwarded t, x) +let Implementation (t, x: int) = RowElement(RowElementTags.Implementation t, x) +let CustomAttributeType (t, x: int) = RowElement(RowElementTags.CustomAttributeType t, x) +let ResolutionScope (t, x: int) = RowElement(RowElementTags.ResolutionScope t, x) (* type RowElement = | UShort of uint16 @@ -337,18 +337,18 @@ type RowElement = type BlobIndex = int type StringIndex = int -let BlobIndex (x:BlobIndex) : int = x -let StringIndex (x:StringIndex) : int = x +let BlobIndex (x: BlobIndex) : int = x +let StringIndex (x: StringIndex) : int = x let inline combineHash x2 acc = 37 * acc + x2 // (acc <<< 6 + acc >>> 2 + x2 + 0x9e3779b9) -let hashRow (elems:RowElement[]) = +let hashRow (elems: RowElement[]) = let mutable acc = 0 for i in 0 .. elems.Length - 1 do acc <- (acc <<< 1) + elems.[i].Tag + elems.[i].Val + 631 acc -let equalRows (elems:RowElement[]) (elems2:RowElement[]) = +let equalRows (elems: RowElement[]) (elems2: RowElement[]) = if elems.Length <> elems2.Length then false else let mutable ok = true let n = elems.Length @@ -368,7 +368,7 @@ type GenericRow = RowElement[] type SharedRow(elems: RowElement[], hashCode: int) = member x.GenericRow = elems override x.GetHashCode() = hashCode - override x.Equals(obj:obj) = + override x.Equals(obj: obj) = match obj with | :? SharedRow as y -> equalRows elems y.GenericRow | _ -> false @@ -382,7 +382,7 @@ let AssemblyRefRow(s1, s2, s3, s4, l1, b1, nameIdx, str2, b2) = new SharedRow(genericRow, hashCode) /// Special representation the computes the hash more efficiently -let MemberRefRow(mrp:RowElement, nmIdx:StringIndex, blobIdx:BlobIndex) = +let MemberRefRow(mrp: RowElement, nmIdx: StringIndex, blobIdx: BlobIndex) = let hashCode = combineHash (hash blobIdx) (combineHash (hash nmIdx) (hash mrp)) let genericRow = [| mrp; StringE nmIdx; Blob blobIdx |] new SharedRow(genericRow, hashCode) @@ -394,7 +394,7 @@ let MemberRefRow(mrp:RowElement, nmIdx:StringIndex, blobIdx:BlobIndex) = type UnsharedRow(elems: RowElement[]) = member x.GenericRow = elems override x.GetHashCode() = hashRow elems - override x.Equals(obj:obj) = + override x.Equals(obj: obj) = match obj with | :? UnsharedRow as y -> equalRows elems y.GenericRow | _ -> false @@ -409,11 +409,11 @@ type UnsharedRow(elems: RowElement[]) = // This environment keeps track of how many generic parameters are in scope. // This lets us translate AbsIL type variable number to IL type variable numbering type ILTypeWriterEnv = { EnclosingTyparCount: int } -let envForTypeDef (td:ILTypeDef) = { EnclosingTyparCount=td.GenericParams.Length } -let envForMethodRef env (ty:ILType) = { EnclosingTyparCount=(match ty with ILType.Array _ -> env.EnclosingTyparCount | _ -> ty.GenericArgs.Length) } +let envForTypeDef (td: ILTypeDef) = { EnclosingTyparCount=td.GenericParams.Length } +let envForMethodRef env (ty: ILType) = { EnclosingTyparCount=(match ty with ILType.Array _ -> env.EnclosingTyparCount | _ -> ty.GenericArgs.Length) } let envForNonGenericMethodRef _mref = { EnclosingTyparCount=System.Int32.MaxValue } -let envForFieldSpec (fspec:ILFieldSpec) = { EnclosingTyparCount=fspec.DeclaringType.GenericArgs.Length } -let envForOverrideSpec (ospec:ILOverridesSpec) = { EnclosingTyparCount=ospec.DeclaringType.GenericArgs.Length } +let envForFieldSpec (fspec: ILFieldSpec) = { EnclosingTyparCount=fspec.DeclaringType.GenericArgs.Length } +let envForOverrideSpec (ospec: ILOverridesSpec) = { EnclosingTyparCount=ospec.DeclaringType.GenericArgs.Length } //--------------------------------------------------------------------- // TABLES @@ -488,7 +488,7 @@ type MetadataTable<'T> = //--------------------------------------------------------------------- /// We use this key type to help find ILMethodDefs for MethodRefs -type MethodDefKey(tidx:int, garity:int, nm:string, rty:ILType, argtys:ILTypes, isStatic:bool) = +type MethodDefKey(tidx: int, garity: int, nm: string, rty: ILType, argtys: ILTypes, isStatic: bool) = // Precompute the hash. The hash doesn't include the return type or // argument types (only argument type count). This is very important, since // hashing these is way too expensive @@ -505,7 +505,7 @@ type MethodDefKey(tidx:int, garity:int, nm:string, rty:ILType, argtys:ILTypes, i member key.ArgTypes = argtys member key.IsStatic = isStatic override x.GetHashCode() = hashCode - override x.Equals(obj:obj) = + override x.Equals(obj: obj) = match obj with | :? MethodDefKey as y -> tidx = y.TypeIdx && @@ -518,14 +518,14 @@ type MethodDefKey(tidx:int, garity:int, nm:string, rty:ILType, argtys:ILTypes, i | _ -> false /// We use this key type to help find ILFieldDefs for FieldRefs -type FieldDefKey(tidx:int, nm:string, ty:ILType) = +type FieldDefKey(tidx: int, nm: string, ty: ILType) = // precompute the hash. hash doesn't include the type let hashCode = hash tidx |> combineHash (hash nm) member key.TypeIdx = tidx member key.Name = nm member key.Type = ty override x.GetHashCode() = hashCode - override x.Equals(obj:obj) = + override x.Equals(obj: obj) = match obj with | :? FieldDefKey as y -> tidx = y.TypeIdx && @@ -595,7 +595,7 @@ type cenv = userStrings: MetadataTable normalizeAssemblyRefs: ILAssemblyRef -> ILAssemblyRef } - member cenv.GetTable (tab:TableName) = cenv.tables.[tab.Index] + member cenv.GetTable (tab: TableName) = cenv.tables.[tab.Index] member cenv.AddCode ((reqdStringFixupsOffset, requiredStringFixups), code) = @@ -607,13 +607,13 @@ type cenv = member cenv.GetCode() = cenv.codeChunks.Close() -let FindOrAddSharedRow (cenv:cenv) tbl x = cenv.GetTable(tbl).FindOrAddSharedEntry x +let FindOrAddSharedRow (cenv: cenv) tbl x = cenv.GetTable(tbl).FindOrAddSharedEntry x // Shared rows must be hash-cons'd to be made unique (no duplicates according to contents) -let AddSharedRow (cenv:cenv) tbl x = cenv.GetTable(tbl).AddSharedEntry x +let AddSharedRow (cenv: cenv) tbl x = cenv.GetTable(tbl).AddSharedEntry x // Unshared rows correspond to definition elements (e.g. a ILTypeDef or a ILMethodDef) -let AddUnsharedRow (cenv:cenv) tbl (x:UnsharedRow) = cenv.GetTable(tbl).AddUnsharedEntry x +let AddUnsharedRow (cenv: cenv) tbl (x: UnsharedRow) = cenv.GetTable(tbl).AddUnsharedEntry x let metadataSchemaVersionSupportedByCLRVersion v = // Whidbey Beta 1 version numbers are between 2.0.40520.0 and 2.0.40607.0 @@ -661,7 +661,7 @@ let recordRequiredDataFixup requiredDataFixups (buf: ByteBuffer) pos lab = let GetUserStringHeapIdx cenv s = cenv.userStrings.FindOrAddSharedEntry s -let GetBytesAsBlobIdx cenv (bytes:byte[]) = +let GetBytesAsBlobIdx cenv (bytes: byte[]) = if bytes.Length = 0 then 0 else cenv.blobs.FindOrAddSharedEntry bytes @@ -685,7 +685,7 @@ let GetTypeNameAsElemPair cenv n = // Pass 1 - allocate indexes for types //===================================================================== -let rec GenTypeDefPass1 enc cenv (td:ILTypeDef) = +let rec GenTypeDefPass1 enc cenv (td: ILTypeDef) = ignore (cenv.typeDefs.AddUniqueEntry "type index" (fun (TdKey (_, n)) -> n) (TdKey (enc, td.Name))) GenTypeDefsPass1 (enc@[td.Name]) cenv td.NestedTypes.AsList @@ -707,7 +707,7 @@ let rec GetIdxForTypeDef cenv key = // Assembly and module references // -------------------------------------------------------------------- -let rec GetAssemblyRefAsRow cenv (aref:ILAssemblyRef) = +let rec GetAssemblyRefAsRow cenv (aref: ILAssemblyRef) = AssemblyRefRow ((match aref.Version with None -> 0us | Some (x, _, _, _) -> x), (match aref.Version with None -> 0us | Some (_, y, _, _) -> y), @@ -725,11 +725,11 @@ let rec GetAssemblyRefAsRow cenv (aref:ILAssemblyRef) = and GetAssemblyRefAsIdx cenv aref = FindOrAddSharedRow cenv TableNames.AssemblyRef (GetAssemblyRefAsRow cenv (cenv.normalizeAssemblyRefs aref)) -and GetModuleRefAsRow cenv (mref:ILModuleRef) = +and GetModuleRefAsRow cenv (mref: ILModuleRef) = SharedRow [| StringE (GetStringHeapIdx cenv mref.Name) |] -and GetModuleRefAsFileRow cenv (mref:ILModuleRef) = +and GetModuleRefAsFileRow cenv (mref: ILModuleRef) = SharedRow [| ULong (if mref.HasMetadata then 0x0000 else 0x0001) StringE (GetStringHeapIdx cenv mref.Name) @@ -746,8 +746,8 @@ and GetModuleRefAsFileIdx cenv mref = // -------------------------------------------------------------------- let isScopeRefLocal scoref = (scoref = ILScopeRef.Local) -let isTypeRefLocal (tref:ILTypeRef) = isScopeRefLocal tref.Scope -let isTypeLocal (ty:ILType) = ty.IsNominal && isNil ty.GenericArgs && isTypeRefLocal ty.TypeRef +let isTypeRefLocal (tref: ILTypeRef) = isScopeRefLocal tref.Scope +let isTypeLocal (ty: ILType) = ty.IsNominal && isNil ty.GenericArgs && isTypeRefLocal ty.TypeRef // -------------------------------------------------------------------- // Scopes to Implementation elements. @@ -763,7 +763,7 @@ let GetScopeRefAsImplementationElem cenv scoref = // Type references, types etc. // -------------------------------------------------------------------- -let rec GetTypeRefAsTypeRefRow cenv (tref:ILTypeRef) = +let rec GetTypeRefAsTypeRefRow cenv (tref: ILTypeRef) = let nselem, nelem = GetTypeNameAsElemPair cenv tref.Name let rs1, rs2 = GetResolutionScopeAsElem cenv (tref.Scope, tref.Enclosing) SharedRow [| ResolutionScope (rs1, rs2); nelem; nselem |] @@ -834,7 +834,7 @@ let callconvToByte ntypars (Callconv (hasthis, bcc)) = // REVIEW: write into an accumuating buffer -let rec EmitTypeSpec cenv env (bb: ByteBuffer) (et, tspec:ILTypeSpec) = +let rec EmitTypeSpec cenv env (bb: ByteBuffer) (et, tspec: ILTypeSpec) = if isNil tspec.GenericArgs then bb.EmitByte et emitTypeInfoAsTypeDefOrRefEncoded cenv bb (tspec.Scope, tspec.Enclosing, tspec.Name) @@ -845,7 +845,7 @@ let rec EmitTypeSpec cenv env (bb: ByteBuffer) (et, tspec:ILTypeSpec) = bb.EmitZ32 tspec.GenericArgs.Length EmitTypes cenv env bb tspec.GenericArgs -and GetTypeAsTypeDefOrRef cenv env (ty:ILType) = +and GetTypeAsTypeDefOrRef cenv env (ty: ILType) = if isTypeLocal ty then let tref = ty.TypeRef (tdor_TypeDef, GetIdxForTypeDef cenv (TdKey(tref.Enclosing, tref.Name))) @@ -859,10 +859,10 @@ and GetTypeAsBytes cenv env ty = emitBytesViaBuffer (fun bb -> EmitType cenv env and GetTypeOfLocalAsBytes cenv env (l: ILLocal) = emitBytesViaBuffer (fun bb -> EmitLocalInfo cenv env bb l) -and GetTypeAsBlobIdx cenv env (ty:ILType) = +and GetTypeAsBlobIdx cenv env (ty: ILType) = GetBytesAsBlobIdx cenv (GetTypeAsBytes cenv env ty) -and GetTypeAsTypeSpecRow cenv env (ty:ILType) = +and GetTypeAsTypeSpecRow cenv env (ty: ILType) = SharedRow [| Blob (GetTypeAsBlobIdx cenv env ty) |] and GetTypeAsTypeSpecIdx cenv env ty = @@ -922,12 +922,12 @@ and EmitType cenv env bb ty = EmitType cenv env bb ty | _ -> failwith "EmitType" -and EmitLocalInfo cenv env (bb:ByteBuffer) (l:ILLocal) = +and EmitLocalInfo cenv env (bb: ByteBuffer) (l: ILLocal) = if l.IsPinned then bb.EmitByte et_PINNED EmitType cenv env bb l.Type -and EmitCallsig cenv env bb (callconv, args:ILTypes, ret, varargs:ILVarArgs, genarity) = +and EmitCallsig cenv env bb (callconv, args: ILTypes, ret, varargs: ILVarArgs, genarity) = bb.EmitByte (callconvToByte genarity callconv) if genarity > 0 then bb.EmitZ32 genarity bb.EmitZ32 ((args.Length + (match varargs with None -> 0 | Some l -> l.Length))) @@ -970,7 +970,7 @@ let rec GetVariantTypeAsInt32 ty = | _ -> failwith "Unexpected variant type" // based on information in ECMA and asmparse.y in the CLR codebase -let rec GetNativeTypeAsBlobIdx cenv (ty:ILNativeType) = +let rec GetNativeTypeAsBlobIdx cenv (ty: ILNativeType) = GetBytesAsBlobIdx cenv (GetNativeTypeAsBytes ty) and GetNativeTypeAsBytes ty = emitBytesViaBuffer (fun bb -> EmitNativeType bb ty) @@ -1031,7 +1031,7 @@ and EmitNativeType bb ty = // Native types // -------------------------------------------------------------------- -let rec GetFieldInitAsBlobIdx cenv (x:ILFieldInit) = +let rec GetFieldInitAsBlobIdx cenv (x: ILFieldInit) = GetBytesAsBlobIdx cenv (emitBytesViaBuffer (fun bb -> GetFieldInit bb x)) // REVIEW: write into an accumuating buffer @@ -1097,7 +1097,7 @@ let GetTypeAccessFlags access = | ILTypeDefAccess.Nested ILMemberAccess.FamilyOrAssembly -> 0x00000007 | ILTypeDefAccess.Nested ILMemberAccess.Assembly -> 0x00000005 -let rec GetTypeDefAsRow cenv env _enc (td:ILTypeDef) = +let rec GetTypeDefAsRow cenv env _enc (td: ILTypeDef) = let nselem, nelem = GetTypeNameAsElemPair cenv td.Name let flags = if (isTypeNameForGlobalFunctions td.Name) then 0x00000000 @@ -1132,7 +1132,7 @@ and GetKeyForFieldDef tidx (fd: ILFieldDef) = FieldDefKey (tidx, fd.Name, fd.FieldType) and GenFieldDefPass2 cenv tidx fd = - ignore (cenv.fieldDefs.AddUniqueEntry "field" (fun (fdkey:FieldDefKey) -> fdkey.Name) (GetKeyForFieldDef tidx fd)) + ignore (cenv.fieldDefs.AddUniqueEntry "field" (fun (fdkey: FieldDefKey) -> fdkey.Name) (GetKeyForFieldDef tidx fd)) and GetKeyForMethodDef tidx (md: ILMethodDef) = MethodDefKey (tidx, md.GenericParams.Length, md.Name, md.Return.Type, md.ParameterTypes, md.CallingConv.IsStatic) @@ -1141,7 +1141,7 @@ and GenMethodDefPass2 cenv tidx md = let idx = cenv.methodDefIdxsByKey.AddUniqueEntry "method" - (fun (key:MethodDefKey) -> + (fun (key: MethodDefKey) -> dprintn "Duplicate in method table is:" dprintn (" Type index: "+string key.TypeIdx) dprintn (" Method name: "+key.Name) @@ -1173,7 +1173,7 @@ and GetKeyForEvent tidx (x: ILEventDef) = and GenEventDefPass2 cenv tidx x = ignore (cenv.eventDefs.AddUniqueEntry "event" (fun (EventKey(_, b)) -> b) (GetKeyForEvent tidx x)) -and GenTypeDefPass2 pidx enc cenv (td:ILTypeDef) = +and GenTypeDefPass2 pidx enc cenv (td: ILTypeDef) = try let env = envForTypeDef td let tidx = GetIdxForTypeDef cenv (TdKey(enc, td.Name)) @@ -1261,7 +1261,7 @@ and GetFieldDefAsFieldDefIdx cenv tidx fd = // methods in the module being emitted. // -------------------------------------------------------------------- -let GetMethodRefAsMethodDefIdx cenv (mref:ILMethodRef) = +let GetMethodRefAsMethodDefIdx cenv (mref: ILMethodRef) = let tref = mref.DeclaringTypeRef try if not (isTypeRefLocal tref) then @@ -1284,7 +1284,7 @@ let GetMethodRefInfoAsMemberRefIdx cenv env ((_, ty, _, _, _, _, _) as minfo) = let fenv = envForMethodRef env ty FindOrAddSharedRow cenv TableNames.MemberRef (MethodRefInfoAsMemberRefRow cenv env fenv minfo) -let GetMethodRefInfoAsMethodRefOrDef isAlwaysMethodDef cenv env ((nm, ty:ILType, cc, args, ret, varargs, genarity) as minfo) = +let GetMethodRefInfoAsMethodRefOrDef isAlwaysMethodDef cenv env ((nm, ty: ILType, cc, args, ret, varargs, genarity) as minfo) = if Option.isNone varargs && (isAlwaysMethodDef || isTypeLocal ty) then if not ty.IsNominal then failwith "GetMethodRefInfoAsMethodRefOrDef: unexpected local tref-ty" try (mdor_MethodDef, GetMethodRefAsMethodDefIdx cenv (mkILMethRef (ty.TypeRef, cc, nm, genarity, args, ret))) @@ -1296,7 +1296,7 @@ let GetMethodRefInfoAsMethodRefOrDef isAlwaysMethodDef cenv env ((nm, ty:ILType, // ILMethodSpec --> ILMethodRef/ILMethodDef/ILMethodSpec // -------------------------------------------------------------------- -let rec GetMethodSpecInfoAsMethodSpecIdx cenv env (nm, ty, cc, args, ret, varargs, minst:ILGenericArgs) = +let rec GetMethodSpecInfoAsMethodSpecIdx cenv env (nm, ty, cc, args, ret, varargs, minst: ILGenericArgs) = let mdorTag, mdorRow = GetMethodRefInfoAsMethodRefOrDef false cenv env (nm, ty, cc, args, ret, varargs, minst.Length) let blob = emitBytesViaBuffer (fun bb -> @@ -1315,7 +1315,7 @@ and GetMethodDefOrRefAsUncodedToken (tag, idx) = else failwith "GetMethodDefOrRefAsUncodedToken" getUncodedToken tab idx -and GetMethodSpecInfoAsUncodedToken cenv env ((_, _, _, _, _, _, minst:ILGenericArgs) as minfo) = +and GetMethodSpecInfoAsUncodedToken cenv env ((_, _, _, _, _, _, minst: ILGenericArgs) as minfo) = if List.isEmpty minst then GetMethodDefOrRefAsUncodedToken (GetMethodRefInfoAsMethodRefOrDef false cenv env (GetMethodRefInfoOfMethodSpecInfo minfo)) else @@ -1324,7 +1324,7 @@ and GetMethodSpecInfoAsUncodedToken cenv env ((_, _, _, _, _, _, minst:ILGeneric and GetMethodSpecAsUncodedToken cenv env mspec = GetMethodSpecInfoAsUncodedToken cenv env (InfoOfMethodSpec mspec) -and GetMethodRefInfoOfMethodSpecInfo (nm, ty, cc, args, ret, varargs, minst:ILGenericArgs) = +and GetMethodRefInfoOfMethodSpecInfo (nm, ty, cc, args, ret, varargs, minst: ILGenericArgs) = (nm, ty, cc, args, ret, varargs, minst.Length) and GetMethodSpecAsMethodDefOrRef cenv env (mspec, varargs) = @@ -1333,7 +1333,7 @@ and GetMethodSpecAsMethodDefOrRef cenv env (mspec, varargs) = and GetMethodSpecAsMethodDef cenv env (mspec, varargs) = GetMethodRefInfoAsMethodRefOrDef true cenv env (GetMethodRefInfoOfMethodSpecInfo (InfoOfMethodSpec (mspec, varargs))) -and InfoOfMethodSpec (mspec:ILMethodSpec, varargs) = +and InfoOfMethodSpec (mspec: ILMethodSpec, varargs) = (mspec.Name, mspec.DeclaringType, mspec.CallingConv, @@ -1353,7 +1353,7 @@ let rec GetOverridesSpecAsMemberRefIdx cenv env ospec = let row = MethodRefInfoAsMemberRefRow cenv env fenv (ospec.MethodRef.Name, ospec.DeclaringType, ospec.MethodRef.CallingConv, ospec.MethodRef.ArgTypes, ospec.MethodRef.ReturnType, None, ospec.MethodRef.GenericArity) FindOrAddSharedRow cenv TableNames.MemberRef row -and GetOverridesSpecAsMethodDefOrRef cenv env (ospec:ILOverridesSpec) = +and GetOverridesSpecAsMethodDefOrRef cenv env (ospec: ILOverridesSpec) = let ty = ospec.DeclaringType if isTypeLocal ty then if not ty.IsNominal then failwith "GetOverridesSpecAsMethodDefOrRef: unexpected local tref-ty" @@ -1368,11 +1368,11 @@ and GetOverridesSpecAsMethodDefOrRef cenv env (ospec:ILOverridesSpec) = // Used for Custom Attrs. // -------------------------------------------------------------------- -let rec GetMethodRefAsMemberRefIdx cenv env fenv (mref:ILMethodRef) = +let rec GetMethodRefAsMemberRefIdx cenv env fenv (mref: ILMethodRef) = let row = MethodRefInfoAsMemberRefRow cenv env fenv (mref.Name, mkILNonGenericBoxedTy mref.DeclaringTypeRef, mref.CallingConv, mref.ArgTypes, mref.ReturnType, None, mref.GenericArity) FindOrAddSharedRow cenv TableNames.MemberRef row -and GetMethodRefAsCustomAttribType cenv (mref:ILMethodRef) = +and GetMethodRefAsCustomAttribType cenv (mref: ILMethodRef) = let fenv = envForNonGenericMethodRef mref let tref = mref.DeclaringTypeRef if isTypeRefLocal tref then @@ -1385,7 +1385,7 @@ and GetMethodRefAsCustomAttribType cenv (mref:ILMethodRef) = // ILAttributes --> CustomAttribute rows // -------------------------------------------------------------------- -let rec GetCustomAttrDataAsBlobIdx cenv (data:byte[]) = +let rec GetCustomAttrDataAsBlobIdx cenv (data: byte[]) = if data.Length = 0 then 0 else GetBytesAsBlobIdx cenv data and GetCustomAttrRow cenv hca (attr: ILAttribute) = @@ -1429,7 +1429,7 @@ and GenSecurityDeclsPass3 cenv hds attrs = // ILFieldSpec --> FieldRef or ILFieldDef row // -------------------------------------------------------------------- -let rec GetFieldSpecAsMemberRefRow cenv env fenv (fspec:ILFieldSpec) = +let rec GetFieldSpecAsMemberRefRow cenv env fenv (fspec: ILFieldSpec) = MemberRefRow (GetTypeAsMemberRefParent cenv env fspec.DeclaringType, GetStringHeapIdx cenv fspec.Name, GetFieldSpecSigAsBlobIdx cenv fenv fspec) @@ -1439,7 +1439,7 @@ and GetFieldSpecAsMemberRefIdx cenv env fspec = FindOrAddSharedRow cenv TableNames.MemberRef (GetFieldSpecAsMemberRefRow cenv env fenv fspec) // REVIEW: write into an accumuating buffer -and EmitFieldSpecSig cenv env (bb: ByteBuffer) (fspec:ILFieldSpec) = +and EmitFieldSpecSig cenv env (bb: ByteBuffer) (fspec: ILFieldSpec) = bb.EmitByte e_IMAGE_CEE_CS_CALLCONV_FIELD EmitType cenv env bb fspec.FormalType @@ -1449,7 +1449,7 @@ and GetFieldSpecSigAsBytes cenv env x = and GetFieldSpecSigAsBlobIdx cenv env x = GetBytesAsBlobIdx cenv (GetFieldSpecSigAsBytes cenv env x) -and GetFieldSpecAsFieldDefOrRef cenv env (fspec:ILFieldSpec) = +and GetFieldSpecAsFieldDefOrRef cenv env (fspec: ILFieldSpec) = let ty = fspec.DeclaringType if isTypeLocal ty then if not ty.IsNominal then failwith "GetFieldSpecAsFieldDefOrRef: unexpected local tref-ty" @@ -1468,7 +1468,7 @@ and GetFieldDefOrRefAsUncodedToken (tag, idx) = // callsig --> StandAloneSig // -------------------------------------------------------------------- -let GetCallsigAsBlobIdx cenv env (callsig:ILCallingSignature, varargs) = +let GetCallsigAsBlobIdx cenv env (callsig: ILCallingSignature, varargs) = GetBytesAsBlobIdx cenv (GetCallsigAsBytes cenv env (callsig.CallingConv, callsig.ArgTypes, @@ -1535,7 +1535,7 @@ type CodeBuffer = member codebuf.EmitExceptionClause seh = codebuf.seh <- seh :: codebuf.seh - member codebuf.EmitSeqPoint cenv (m:ILSourceMarker) = + member codebuf.EmitSeqPoint cenv (m: ILSourceMarker) = if cenv.generatePdb then // table indexes are 1-based, document array indexes are 0-based let doc = (cenv.documents.FindOrAddSharedEntry m.Document) - 1 @@ -1590,7 +1590,7 @@ module Codebuf = if c = 0 then i elif c < 0 then go n (i-1) else go (i+1) m go 0 (Array.length arr) - let applyBrFixups (origCode :byte[]) origExnClauses origReqdStringFixups (origAvailBrFixups: Dictionary) origReqdBrFixups origSeqPoints origScopes = + let applyBrFixups (origCode : byte[]) origExnClauses origReqdStringFixups (origAvailBrFixups: Dictionary) origReqdBrFixups origSeqPoints origScopes = let orderedOrigReqdBrFixups = origReqdBrFixups |> List.sortBy (fun (_, fixuploc, _) -> fixuploc) let newCode = ByteBuffer.Create origCode.Length @@ -1634,7 +1634,7 @@ module Codebuf = if doingLast then doneLast := true else - let (i, origStartOfInstr, tgs:ILCodeLabel list) = List.head !remainingReqdFixups + let (i, origStartOfInstr, tgs: ILCodeLabel list) = List.head !remainingReqdFixups remainingReqdFixups := List.tail !remainingReqdFixups if origCode.[origStartOfInstr] <> 0x11uy then failwith "br fixup sanity check failed (1)" let i_length = if fst i = i_switch then 5 else 1 @@ -1709,7 +1709,7 @@ module Codebuf = tab.[tglab] <- adjuster origBrDest tab let newReqdStringFixups = List.map (fun (origFixupLoc, stok) -> adjuster origFixupLoc, stok) origReqdStringFixups - let newSeqPoints = Array.map (fun (sp:PdbSequencePoint) -> {sp with Offset=adjuster sp.Offset}) origSeqPoints + let newSeqPoints = Array.map (fun (sp: PdbSequencePoint) -> {sp with Offset=adjuster sp.Offset}) origSeqPoints let newExnClauses = origExnClauses |> List.map (fun (st1, sz1, st2, sz2, kind) -> (adjuster st1, (adjuster (st1 + sz1) - adjuster st1), @@ -2074,8 +2074,8 @@ module Codebuf = // Used to put local debug scopes and exception handlers into a tree form let rangeInsideRange (start_pc1, end_pc1) (start_pc2, end_pc2) = - (start_pc1:int) >= start_pc2 && start_pc1 < end_pc2 && - (end_pc1:int) > start_pc2 && end_pc1 <= end_pc2 + (start_pc1: int) >= start_pc2 && start_pc1 < end_pc2 && + (end_pc1: int) > start_pc2 && end_pc1 <= end_pc2 let lranges_of_clause cl = match cl with @@ -2567,7 +2567,7 @@ let GenMethodImplPass3 cenv env _tgparams tidx mimpl = MethodDefOrRef (midxTag, midxRow) MethodDefOrRef (midx2Tag, midx2Row) |]) |> ignore -let GenMethodDefPass3 cenv env (md:ILMethodDef) = +let GenMethodDefPass3 cenv env (md: ILMethodDef) = let midx = GetMethodDefIdx cenv md let idx2 = AddUnsharedRow cenv TableNames.Method (GenMethodDefAsRow cenv env midx md) if midx <> idx2 then failwith "index of method def on pass 3 does not match index on pass 2" @@ -2637,7 +2637,7 @@ and GetPropertySigAsBytes cenv env (prop: ILPropertyDef) = EmitType cenv env bb prop.PropertyType prop.Args |> List.iter (EmitType cenv env bb)) -and GetPropertyAsPropertyRow cenv env (prop:ILPropertyDef) = +and GetPropertyAsPropertyRow cenv env (prop: ILPropertyDef) = let flags = prop.Attributes UnsharedRow [| UShort (uint16 flags) @@ -2692,7 +2692,7 @@ and GenEventPass3 cenv env (md: ILEventDef) = let rec GetResourceAsManifestResourceRow cenv r = let data, impl = - let embedManagedResources (bytes:byte[]) = + let embedManagedResources (bytes: byte[]) = // Embedded managed resources must be word-aligned. However resource format is // not specified in ECMA. Some mscorlib resources appear to be non-aligned - it seems it doesn't matter.. let offset = cenv.resources.Position @@ -2724,7 +2724,7 @@ and GenResourcePass3 cenv r = // ILTypeDef --> generate ILFieldDef, ILMethodDef, ILPropertyDef etc. rows // -------------------------------------------------------------------- -let rec GenTypeDefPass3 enc cenv (td:ILTypeDef) = +let rec GenTypeDefPass3 enc cenv (td: ILTypeDef) = try let env = envForTypeDef td let tidx = GetIdxForTypeDef cenv (TdKey(enc, td.Name)) @@ -2759,7 +2759,7 @@ and GenTypeDefsPass3 enc cenv tds = /// ILTypeDef --> generate generic params on ILMethodDef: ensures /// GenericParam table is built sorted by owner. -let rec GenTypeDefPass4 enc cenv (td:ILTypeDef) = +let rec GenTypeDefPass4 enc cenv (td: ILTypeDef) = try let env = envForTypeDef td let tidx = GetIdxForTypeDef cenv (TdKey(enc, td.Name)) @@ -2866,7 +2866,7 @@ and deterministicGuid (modul: ILModuleDef) = let m2 = Seq.sum (Seq.mapi (fun i x -> i + int x) modul.Name) // use a stable hash [| b0 n; b1 n; b2 n; b3 n; b0 m2; b1 m2; b2 m2; b3 m2; 0xa7uy; 0x45uy; 0x03uy; 0x83uy; b0 n; b1 n; b2 n; b3 n |] -and GetModuleAsRow (cenv:cenv) (modul: ILModuleDef) = +and GetModuleAsRow (cenv: cenv) (modul: ILModuleDef) = // Store the generated MVID in the environment (needed for generating debug information) let modulGuid = if cenv.deterministic then deterministicGuid modul else newGuid modul cenv.moduleGuid <- modulGuid @@ -2886,7 +2886,7 @@ let rowElemCompare (e1: RowElement) (e2: RowElement) = let TableRequiresSorting tab = List.memAssoc tab sortedTableInfo -let SortTableRows tab (rows:GenericRow[]) = +let SortTableRows tab (rows: GenericRow[]) = assert (TableRequiresSorting tab) let col = List.assoc tab sortedTableInfo rows @@ -2989,7 +2989,7 @@ let generateIL requiredDataFixups (desiredMetadataVersion, generatePdb, ilg : IL Methods = cenv.pdbinfo.ToArray() TableRowCounts = cenv.tables |> Seq.map(fun t -> t.Count) |> Seq.toArray } - let idxForNextedTypeDef (tds:ILTypeDef list, td:ILTypeDef) = + let idxForNextedTypeDef (tds: ILTypeDef list, td: ILTypeDef) = let enc = tds |> List.map (fun td -> td.Name) GetIdxForTypeDef cenv (TdKey(enc, td.Name)) @@ -3111,16 +3111,16 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let tablesStreamStart = next - let stringsStreamUnpaddedSize = count (fun (s:byte[]) -> s.Length) strings + 1 + let stringsStreamUnpaddedSize = count (fun (s: byte[]) -> s.Length) strings + 1 let stringsStreamPaddedSize = align 4 stringsStreamUnpaddedSize - let userStringsStreamUnpaddedSize = count (fun (s:byte[]) -> let n = s.Length + 1 in n + ByteBuffer.Z32Size n) userStrings + 1 + let userStringsStreamUnpaddedSize = count (fun (s: byte[]) -> let n = s.Length + 1 in n + ByteBuffer.Z32Size n) userStrings + 1 let userStringsStreamPaddedSize = align 4 userStringsStreamUnpaddedSize let guidsStreamUnpaddedSize = (Array.length guids) * 0x10 let guidsStreamPaddedSize = align 4 guidsStreamUnpaddedSize - let blobsStreamUnpaddedSize = count (fun (blob:byte[]) -> let n = blob.Length in n + ByteBuffer.Z32Size n) blobs + 1 + let blobsStreamUnpaddedSize = count (fun (blob: byte[]) -> let n = blob.Length in n + ByteBuffer.Z32Size n) blobs + 1 let blobsStreamPaddedSize = align 4 blobsStreamUnpaddedSize let guidsBig = guidsStreamPaddedSize >= 0x10000 @@ -3206,8 +3206,8 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let sizesTable = Array.map Array.length sortedTables let bignessTable = Array.map (fun rows -> Array.length rows >= 0x10000) sortedTables - let bigness (tab:int32) = bignessTable.[tab] - let size (tab:int32) = sizesTable.[tab] + let bigness (tab: int32) = bignessTable.[tab] + let size (tab: int32) = sizesTable.[tab] let codedBigness nbits tab = (tableSize tab) >= (0x10000 >>> nbits) @@ -3517,7 +3517,7 @@ let writeDirectory os dict = writeInt32 os (if dict.size = 0x0 then 0x0 else dict.addr) writeInt32 os dict.size -let writeBytes (os: BinaryWriter) (chunk:byte[]) = os.Write(chunk, 0, chunk.Length) +let writeBytes (os: BinaryWriter) (chunk: byte[]) = os.Write(chunk, 0, chunk.Length) let writeBinaryAndReportMappings (outfile, ilg: ILGlobals, pdbfile: string option, signer: ILStrongNameSigner option, portablePDB, embeddedPDB, @@ -4289,7 +4289,7 @@ type options = emitTailcalls : bool deterministic : bool showTimes: bool - dumpDebugInfo:bool } + dumpDebugInfo: bool } let WriteILBinary (outfile, (args: options), modul, normalizeAssemblyRefs) = writeBinaryAndReportMappings (outfile, diff --git a/src/absil/ilwritepdb.fs b/src/absil/ilwritepdb.fs index 21f79159290..09c765ed416 100644 --- a/src/absil/ilwritepdb.fs +++ b/src/absil/ilwritepdb.fs @@ -31,17 +31,17 @@ type BlobBuildingStream () = override this.CanSeek = false override this.Length = int64(builder.Count) - override this.Write(buffer:byte array, offset:int, count:int) = builder.WriteBytes(buffer, offset, count) - override this.WriteByte(value:byte) = builder.WriteByte(value) - member this.WriteInt32(value:int) = builder.WriteInt32(value) + override this.Write(buffer: byte array, offset: int, count: int) = builder.WriteBytes(buffer, offset, count) + override this.WriteByte(value: byte) = builder.WriteByte(value) + member this.WriteInt32(value: int) = builder.WriteInt32(value) member this.ToImmutableArray() = builder.ToImmutableArray() - member this.TryWriteBytes(stream:Stream, length:int) = builder.TryWriteBytes(stream, length) + member this.TryWriteBytes(stream: Stream, length: int) = builder.TryWriteBytes(stream, length) override this.Flush() = () - override this.Dispose(_disposing:bool) = () - override this.Seek(_offset:int64, _origin:SeekOrigin) = raise (new NotSupportedException()) - override this.Read(_buffer:byte array, _offset:int, _count:int) = raise (new NotSupportedException()) - override this.SetLength(_value:int64) = raise (new NotSupportedException()) + override this.Dispose(_disposing: bool) = () + override this.Seek(_offset: int64, _origin: SeekOrigin) = raise (new NotSupportedException()) + override this.Read(_buffer: byte array, _offset: int, _count: int) = raise (new NotSupportedException()) + override this.SetLength(_value: int64) = raise (new NotSupportedException()) override val Position = 0L with get, set // -------------------------------------------------------------------- @@ -78,7 +78,7 @@ type PdbSequencePoint = type PdbMethodData = { MethToken: int32 - MethName:string + MethName: string LocalSignatureToken: int32 Params: PdbLocalVar array RootScope: PdbMethodScope option @@ -129,7 +129,7 @@ type idd = // Portable PDB Writer //--------------------------------------------------------------------- let cvMagicNumber = 0x53445352L -let pdbGetCvDebugInfo (mvid:byte[]) (timestamp:int32) (filepath:string) (cvChunk:BinaryChunk) = +let pdbGetCvDebugInfo (mvid: byte[]) (timestamp: int32) (filepath: string) (cvChunk: BinaryChunk) = let iddCvBuffer = // Debug directory entry let path = (System.Text.Encoding.UTF8.GetBytes filepath) @@ -153,7 +153,7 @@ let pdbGetCvDebugInfo (mvid:byte[]) (timestamp:int32) (filepath:string) (cvChunk } let pdbMagicNumber= 0x4244504dL -let pdbGetPdbDebugInfo (embeddedPDBChunk:BinaryChunk) (uncompressedLength:int64) (stream:MemoryStream) = +let pdbGetPdbDebugInfo (embeddedPDBChunk: BinaryChunk) (uncompressedLength: int64) (stream: MemoryStream) = let iddPdbBuffer = let buffer = Array.zeroCreate (sizeof + sizeof + int(stream.Length)) let (offset, size) = (0, sizeof) // Magic Number dword: 0x4244504dL @@ -172,7 +172,7 @@ let pdbGetPdbDebugInfo (embeddedPDBChunk:BinaryChunk) (uncompressedLength:int64) iddChunk = embeddedPDBChunk } -let pdbGetDebugInfo (mvid:byte[]) (timestamp:int32) (filepath:string) (cvChunk:BinaryChunk) (embeddedPDBChunk:BinaryChunk option) (uncompressedLength:int64) (stream:MemoryStream option) = +let pdbGetDebugInfo (mvid: byte[]) (timestamp: int32) (filepath: string) (cvChunk: BinaryChunk) (embeddedPDBChunk: BinaryChunk option) (uncompressedLength: int64) (stream: MemoryStream option) = match stream, embeddedPDBChunk with | None, _ | _, None -> [| pdbGetCvDebugInfo mvid timestamp filepath cvChunk |] | Some s, Some chunk -> [| pdbGetCvDebugInfo mvid timestamp filepath cvChunk; pdbGetPdbDebugInfo chunk uncompressedLength s |] @@ -184,7 +184,7 @@ let hashSizeOfMD5 = 16 // If the FIPS algorithm policy is enabled on the computer (e.g., for US government employees and contractors) // then obtaining the MD5 implementation in BCL will throw. // In this case, catch the failure, and not set a checksum. -let checkSum (url:string) = +let checkSum (url: string) = try use file = FileSystem.FileStreamReadShim(url) use md5 = System.Security.Cryptography.MD5.Create() @@ -219,7 +219,7 @@ let getRowCounts tableRowCounts = tableRowCounts |> Seq.iter(fun x -> builder.Add(x)) builder.MoveToImmutable() -let generatePortablePdb (embedAllSource:bool) (embedSourceList:string list) (sourceLink:string) showTimes (info:PdbData) isDeterministic = +let generatePortablePdb (embedAllSource: bool) (embedSourceList: string list) (sourceLink: string) showTimes (info: PdbData) isDeterministic = sortMethods showTimes info let externalRowCounts = getRowCounts info.TableRowCounts let docs = @@ -228,7 +228,7 @@ let generatePortablePdb (embedAllSource:bool) (embedSourceList:string list) (sou | _ -> info.Documents let metadata = MetadataBuilder() - let serializeDocumentName (name:string) = + let serializeDocumentName (name: string) = let count s c = s |> Seq.filter(fun ch -> if c = ch then true else false) |> Seq.length let s1, s2 = '/', '\\' @@ -407,7 +407,7 @@ let generatePortablePdb (embedAllSource:bool) (embedSourceList:string list) (sou // Write the scopes let nextHandle handle = MetadataTokens.LocalVariableHandle(MetadataTokens.GetRowNumber(LocalVariableHandle.op_Implicit(handle)) + 1) let writeMethodScope scope = - let scopeSorter (scope1:PdbMethodScope) (scope2:PdbMethodScope) = + let scopeSorter (scope1: PdbMethodScope) (scope2: PdbMethodScope) = if scope1.StartOffset > scope2.StartOffset then 1 elif scope1.StartOffset < scope2.StartOffset then -1 elif (scope1.EndOffset - scope1.StartOffset) > (scope2.EndOffset - scope2.StartOffset) then -1 @@ -452,7 +452,7 @@ let generatePortablePdb (embedAllSource:bool) (embedSourceList:string list) (sou match isDeterministic with | false -> null | true -> - let convert (content:IEnumerable) = + let convert (content: IEnumerable) = use sha = System.Security.Cryptography.SHA1.Create() // IncrementalHash is core only let hash = content |> Seq.collect (fun c -> c.GetBytes().Array |> sha.ComputeHash) @@ -468,20 +468,20 @@ let generatePortablePdb (embedAllSource:bool) (embedSourceList:string list) (sou reportTime showTimes "PDB: Created" (portablePdbStream.Length, contentId, portablePdbStream) -let compressPortablePdbStream (uncompressedLength:int64) (contentId:BlobContentId) (stream:MemoryStream) = +let compressPortablePdbStream (uncompressedLength: int64) (contentId: BlobContentId) (stream: MemoryStream) = let compressedStream = new MemoryStream() use compressionStream = new DeflateStream(compressedStream, CompressionMode.Compress,true) stream.WriteTo(compressionStream) (uncompressedLength, contentId, compressedStream) -let writePortablePdbInfo (contentId:BlobContentId) (stream:MemoryStream) showTimes fpdb cvChunk = +let writePortablePdbInfo (contentId: BlobContentId) (stream: MemoryStream) showTimes fpdb cvChunk = try FileSystem.FileDelete fpdb with _ -> () use pdbFile = new FileStream(fpdb, FileMode.Create, FileAccess.ReadWrite) stream.WriteTo(pdbFile) reportTime showTimes "PDB: Closed" pdbGetDebugInfo (contentId.Guid.ToByteArray()) (int32 (contentId.Stamp)) fpdb cvChunk None 0L None -let embedPortablePdbInfo (uncompressedLength:int64) (contentId:BlobContentId) (stream:MemoryStream) showTimes fpdb cvChunk pdbChunk = +let embedPortablePdbInfo (uncompressedLength: int64) (contentId: BlobContentId) (stream: MemoryStream) showTimes fpdb cvChunk pdbChunk = reportTime showTimes "PDB: Closed" let fn = Path.GetFileName(fpdb) pdbGetDebugInfo (contentId.Guid.ToByteArray()) (int32 (contentId.Stamp)) fn cvChunk (Some pdbChunk) uncompressedLength (Some stream) @@ -622,15 +622,15 @@ let (?) this memb (args:'Args) : 'R = // Creating instances of needed classes from 'Mono.CompilerServices.SymbolWriter' assembly let monoCompilerSvc = new AssemblyName("Mono.CompilerServices.SymbolWriter, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756") -let ctor (asmName:AssemblyName) clsName (args:obj[]) = +let ctor (asmName: AssemblyName) clsName (args: obj[]) = let asm = Assembly.Load(asmName) let ty = asm.GetType(clsName) System.Activator.CreateInstance(ty, args) -let createSourceMethodImpl (name:string) (token:int) (namespaceID:int) = +let createSourceMethodImpl (name: string) (token: int) (namespaceID: int) = ctor monoCompilerSvc "Mono.CompilerServices.SymbolWriter.SourceMethodImpl" [| box name; box token; box namespaceID |] -let createWriter (f:string) = +let createWriter (f: string) = ctor monoCompilerSvc "Mono.CompilerServices.SymbolWriter.MonoSymbolWriter" [| box f |] //--------------------------------------------------------------------- @@ -675,7 +675,7 @@ let writeMdbInfo fmdb f info = wr?MarkSequencePoint(sp.Offset, cue?get_SourceFile(), sp.Line, sp.Column, false) // Walk through the tree of scopes and write all variables - let rec writeScope (scope:PdbMethodScope) = + let rec writeScope (scope: PdbMethodScope) = wr?OpenScope(scope.StartOffset) |> ignore for local in scope.Locals do wr?DefineLocalVariable(local.Index, local.Name) @@ -701,7 +701,7 @@ let writeMdbInfo fmdb f info = //--------------------------------------------------------------------- open Printf -let logDebugInfo (outfile:string) (info:PdbData) = +let logDebugInfo (outfile: string) (info: PdbData) = use sw = new StreamWriter(new FileStream(outfile + ".debuginfo", FileMode.Create)) fprintfn sw "ENTRYPOINT\r\n %b\r\n" info.EntryPoint.IsSome @@ -727,7 +727,7 @@ let logDebugInfo (outfile:string) (info:PdbData) = // Walk through the tree of scopes and write all variables fprintfn sw " Scopes:" - let rec writeScope offs (scope:PdbMethodScope) = + let rec writeScope offs (scope: PdbMethodScope) = fprintfn sw " %s- [%d-%d]" offs scope.StartOffset scope.EndOffset if scope.Locals.Length > 0 then fprintfn sw " %s Locals: %A" offs [ for p in scope.Locals -> sprintf "%d: %s" p.Index p.Name ] diff --git a/src/absil/zmap.fs b/src/absil/zmap.fs index 4702eec5c72..9644a135c10 100644 --- a/src/absil/zmap.fs +++ b/src/absil/zmap.fs @@ -13,35 +13,35 @@ module internal Zmap = let empty (ord: IComparer<'T>) = Map<_,_,_>.Empty(ord) - let add k v (m:Zmap<_,_>) = m.Add(k,v) - let find k (m:Zmap<_,_>) = m.[k] - let tryFind k (m:Zmap<_,_>) = m.TryFind(k) - let remove k (m:Zmap<_,_>) = m.Remove(k) - let mem k (m:Zmap<_,_>) = m.ContainsKey(k) - let iter f (m:Zmap<_,_>) = m.Iterate(f) - let first f (m:Zmap<_,_>) = m.First(fun k v -> if f k v then Some (k,v) else None) - let exists f (m:Zmap<_,_>) = m.Exists(f) - let forall f (m:Zmap<_,_>) = m.ForAll(f) - let map f (m:Zmap<_,_>) = m.MapRange(f) - let mapi f (m:Zmap<_,_>) = m.Map(f) - let fold f (m:Zmap<_,_>) x = m.Fold f x - let toList (m:Zmap<_,_>) = m.ToList() - let foldSection lo hi f (m:Zmap<_,_>) x = m.FoldSection lo hi f x - - let isEmpty (m:Zmap<_,_>) = m.IsEmpty - - let foldMap f z (m:Zmap<_,_>) = + let add k v (m: Zmap<_,_>) = m.Add(k,v) + let find k (m: Zmap<_,_>) = m.[k] + let tryFind k (m: Zmap<_,_>) = m.TryFind(k) + let remove k (m: Zmap<_,_>) = m.Remove(k) + let mem k (m: Zmap<_,_>) = m.ContainsKey(k) + let iter f (m: Zmap<_,_>) = m.Iterate(f) + let first f (m: Zmap<_,_>) = m.First(fun k v -> if f k v then Some (k,v) else None) + let exists f (m: Zmap<_,_>) = m.Exists(f) + let forall f (m: Zmap<_,_>) = m.ForAll(f) + let map f (m: Zmap<_,_>) = m.MapRange(f) + let mapi f (m: Zmap<_,_>) = m.Map(f) + let fold f (m: Zmap<_,_>) x = m.Fold f x + let toList (m: Zmap<_,_>) = m.ToList() + let foldSection lo hi f (m: Zmap<_,_>) x = m.FoldSection lo hi f x + + let isEmpty (m: Zmap<_,_>) = m.IsEmpty + + let foldMap f z (m: Zmap<_,_>) = let m,z = m.FoldAndMap (fun k v z -> let z,v' = f z k v in v',z) z in z,m - let choose f (m:Zmap<_,_>) = m.First(f) + let choose f (m: Zmap<_,_>) = m.First(f) - let chooseL f (m:Zmap<_,_>) = + let chooseL f (m: Zmap<_,_>) = m.Fold (fun k v s -> match f k v with None -> s | Some x -> x::s) [] let ofList ord xs = Internal.Utilities.Collections.Tagged.Map<_,_>.FromList(ord,xs) - let keys (m:Zmap<_,_>) = m.Fold (fun k _ s -> k::s) [] - let values (m:Zmap<_,_>) = m.Fold (fun _ v s -> v::s) [] + let keys (m: Zmap<_,_>) = m.Fold (fun k _ s -> k::s) [] + let values (m: Zmap<_,_>) = m.Fold (fun _ v s -> v::s) [] let memberOf m k = mem k m diff --git a/src/absil/zset.fs b/src/absil/zset.fs index 2f626674c8d..5d6588a5986 100644 --- a/src/absil/zset.fs +++ b/src/absil/zset.fs @@ -17,27 +17,40 @@ module internal Zset = let empty (ord : IComparer<'T>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Empty(ord) - let isEmpty (s:Zset<_>) = s.IsEmpty + let isEmpty (s: Zset<_>) = s.IsEmpty + + let contains x (s: Zset<_>) = s.Contains(x) + + let add x (s: Zset<_>) = s.Add(x) - let contains x (s:Zset<_>) = s.Contains(x) - let add x (s:Zset<_>) = s.Add(x) let addList xs a = List.fold (fun a x -> add x a) a xs let singleton ord x = add x (empty ord) - let remove x (s:Zset<_>) = s.Remove(x) - - let fold (f : 'T -> 'b -> 'b) (s:Zset<_>) b = s.Fold f b - let iter f (s:Zset<_>) = s.Iterate f - let forall p (s:Zset<_>) = s.ForAll p - let count (s:Zset<_>) = s.Count - let exists p (s:Zset<_>) = s.Exists p - let subset (s1:Zset<_>) (s2:Zset<_>) = s1.IsSubsetOf s2 - let equal (s1:Zset<_>) (s2:Zset<_>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Equality(s1,s2) - let elements (s:Zset<_>) = s.ToList() - let filter p (s:Zset<_>) = s.Filter p - - let union (s1:Zset<_>) (s2:Zset<_>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Union(s1,s2) - let inter (s1:Zset<_>) (s2:Zset<_>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Intersection(s1,s2) - let diff (s1:Zset<_>) (s2:Zset<_>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Difference(s1,s2) + + let remove x (s: Zset<_>) = s.Remove(x) + + let fold (f : 'T -> 'b -> 'b) (s: Zset<_>) b = s.Fold f b + + let iter f (s: Zset<_>) = s.Iterate f + + let forall p (s: Zset<_>) = s.ForAll p + + let count (s: Zset<_>) = s.Count + + let exists p (s: Zset<_>) = s.Exists p + + let subset (s1: Zset<_>) (s2: Zset<_>) = s1.IsSubsetOf s2 + + let equal (s1: Zset<_>) (s2: Zset<_>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Equality(s1,s2) + + let elements (s: Zset<_>) = s.ToList() + + let filter p (s: Zset<_>) = s.Filter p + + let union (s1: Zset<_>) (s2: Zset<_>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Union(s1,s2) + + let inter (s1: Zset<_>) (s2: Zset<_>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Intersection(s1,s2) + + let diff (s1: Zset<_>) (s2: Zset<_>) = Internal.Utilities.Collections.Tagged.Set<_,_>.Difference(s1,s2) let memberOf m k = contains k m diff --git a/src/fsharp/AugmentWithHashCompare.fs b/src/fsharp/AugmentWithHashCompare.fs index c892035d841..4aa0bed68c8 100644 --- a/src/fsharp/AugmentWithHashCompare.fs +++ b/src/fsharp/AugmentWithHashCompare.fs @@ -172,7 +172,7 @@ let mkEqualsTestConjuncts g m exprs = let a, b = List.frontAndBack l List.foldBack (fun e acc -> mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty e acc (mkFalse g m)) a b -let mkMinimalTy (g: TcGlobals) (tcref:TyconRef) = +let mkMinimalTy (g: TcGlobals) (tcref: TyconRef) = if tcref.Deref.IsExceptionDecl then [], g.exn_ty else generalizeTyconRef tcref @@ -196,13 +196,13 @@ let mkBindNullHash g m thise expr = expr /// Build the comparison implementation for a record type -let mkRecdCompare g tcref (tycon:Tycon) = +let mkRecdCompare g tcref (tycon: Tycon) = let m = tycon.Range let fields = tycon.AllInstanceFieldsAsList let tinst, ty = mkMinimalTy g tcref let thisv, thataddrv, thise, thataddre = mkThisVarThatVar g m ty let compe = mkILCallGetComparer g m - let mkTest (fspec:RecdField) = + let mkTest (fspec: RecdField) = let fty = fspec.FormalType let fref = tcref.MakeNestedRecdFieldRef fspec let m = fref.Range @@ -219,14 +219,14 @@ let mkRecdCompare g tcref (tycon:Tycon) = /// Build the comparison implementation for a record type when parameterized by a comparer -let mkRecdCompareWithComparer g tcref (tycon:Tycon) (_thisv, thise) (_, thate) compe = +let mkRecdCompareWithComparer g tcref (tycon: Tycon) (_thisv, thise) (_, thate) compe = let m = tycon.Range let fields = tycon.AllInstanceFieldsAsList let tinst, ty = mkMinimalTy g tcref let tcv, tce = mkCompGenLocal m "objTemp" ty // let tcv = thate let thataddrv, thataddre = mkThatAddrLocal g m ty // let thataddrv = &tcv, if a struct - let mkTest (fspec:RecdField) = + let mkTest (fspec: RecdField) = let fty = fspec.FormalType let fref = tcref.MakeNestedRecdFieldRef fspec let m = fref.Range @@ -245,12 +245,12 @@ let mkRecdCompareWithComparer g tcref (tycon:Tycon) (_thisv, thise) (_, thate) c /// Build the .Equals(that) equality implementation wrapper for a record type -let mkRecdEquality g tcref (tycon:Tycon) = +let mkRecdEquality g tcref (tycon: Tycon) = let m = tycon.Range let fields = tycon.AllInstanceFieldsAsList let tinst, ty = mkMinimalTy g tcref let thisv, thataddrv, thise, thataddre = mkThisVarThatVar g m ty - let mkTest (fspec:RecdField) = + let mkTest (fspec: RecdField) = let fty = fspec.FormalType let fref = tcref.MakeNestedRecdFieldRef fspec let m = fref.Range @@ -265,13 +265,13 @@ let mkRecdEquality g tcref (tycon:Tycon) = thisv, thatv, expr /// Build the equality implementation for a record type when parameterized by a comparer -let mkRecdEqualityWithComparer g tcref (tycon:Tycon) (_thisv, thise) thatobje (thatv, thate) compe = +let mkRecdEqualityWithComparer g tcref (tycon: Tycon) (_thisv, thise) thatobje (thatv, thate) compe = let m = tycon.Range let fields = tycon.AllInstanceFieldsAsList let tinst, ty = mkMinimalTy g tcref let thataddrv, thataddre = mkThatAddrLocal g m ty - let mkTest (fspec:RecdField) = + let mkTest (fspec: RecdField) = let fty = fspec.FormalType let fref = tcref.MakeNestedRecdFieldRef fspec let m = fref.Range @@ -290,11 +290,11 @@ let mkRecdEqualityWithComparer g tcref (tycon:Tycon) (_thisv, thise) thatobje (t expr /// Build the equality implementation for an exception definition -let mkExnEquality (g: TcGlobals) exnref (exnc:Tycon) = +let mkExnEquality (g: TcGlobals) exnref (exnc: Tycon) = let m = exnc.Range let thatv, thate = mkCompGenLocal m "obj" g.exn_ty let thisv, thise = mkThisVar g m g.exn_ty - let mkTest i (rfield:RecdField) = + let mkTest i (rfield: RecdField) = let fty = rfield.FormalType mkCallGenericEqualityEROuter g m fty (mkExnCaseFieldGet(thise, exnref, i, m)) @@ -314,10 +314,10 @@ let mkExnEquality (g: TcGlobals) exnref (exnc:Tycon) = /// Build the equality implementation for an exception definition when parameterized by a comparer -let mkExnEqualityWithComparer g exnref (exnc:Tycon) (_thisv, thise) thatobje (thatv, thate) compe = +let mkExnEqualityWithComparer g exnref (exnc: Tycon) (_thisv, thise) thatobje (thatv, thate) compe = let m = exnc.Range let thataddrv, thataddre = mkThatAddrLocal g m g.exn_ty - let mkTest i (rfield:RecdField) = + let mkTest i (rfield: RecdField) = let fty = rfield.FormalType mkCallGenericEqualityWithComparerOuter g m fty compe @@ -338,7 +338,7 @@ let mkExnEqualityWithComparer g exnref (exnc:Tycon) (_thisv, thise) thatobje (th expr /// Build the comparison implementation for a union type -let mkUnionCompare g tcref (tycon:Tycon) = +let mkUnionCompare g tcref (tycon: Tycon) = let m = tycon.Range let ucases = tycon.UnionCasesAsList let tinst, ty = mkMinimalTy g tcref @@ -354,7 +354,7 @@ let mkUnionCompare g tcref (tycon:Tycon) = let m = cref.Range let rfields = ucase.RecdFields if isNil rfields then None else - let mkTest thise thataddre j (argty:RecdField) = + let mkTest thise thataddre j (argty: RecdField) = mkCallGenericComparisonWithComparerOuter g m argty.FormalType compe (mkUnionCaseFieldGetProvenViaExprAddr(thise, cref, tinst, j, m)) @@ -396,7 +396,7 @@ let mkUnionCompare g tcref (tycon:Tycon) = /// Build the comparison implementation for a union type when parameterized by a comparer -let mkUnionCompareWithComparer g tcref (tycon:Tycon) (_thisv, thise) (_thatobjv, thatcaste) compe = +let mkUnionCompareWithComparer g tcref (tycon: Tycon) (_thisv, thise) (_thatobjv, thatcaste) compe = let m = tycon.Range let ucases = tycon.UnionCasesAsList let tinst, ty = mkMinimalTy g tcref @@ -413,7 +413,7 @@ let mkUnionCompareWithComparer g tcref (tycon:Tycon) (_thisv, thise) (_thatobjv, let rfields = ucase.RecdFields if isNil rfields then None else - let mkTest thise thataddre j (argty:RecdField) = + let mkTest thise thataddre j (argty: RecdField) = mkCallGenericComparisonWithComparerOuter g m argty.FormalType compe (mkUnionCaseFieldGetProvenViaExprAddr(thise, cref, tinst, j, m)) @@ -458,7 +458,7 @@ let mkUnionCompareWithComparer g tcref (tycon:Tycon) (_thisv, thise) (_thatobjv, /// Build the equality implementation for a union type -let mkUnionEquality g tcref (tycon:Tycon) = +let mkUnionEquality g tcref (tycon: Tycon) = let m = tycon.Range let ucases = tycon.UnionCasesAsList let tinst, ty = mkMinimalTy g tcref @@ -474,7 +474,7 @@ let mkUnionEquality g tcref (tycon:Tycon) = let rfields = ucase.RecdFields if isNil rfields then None else - let mkTest thise thataddre j (argty:RecdField) = + let mkTest thise thataddre j (argty: RecdField) = mkCallGenericEqualityEROuter g m argty.FormalType (mkUnionCaseFieldGetProvenViaExprAddr(thise, cref, tinst, j, m)) (mkUnionCaseFieldGetProvenViaExprAddr(thataddre, cref, tinst, j, m)) @@ -517,7 +517,7 @@ let mkUnionEquality g tcref (tycon:Tycon) = thisv, thatv, expr /// Build the equality implementation for a union type when parameterized by a comparer -let mkUnionEqualityWithComparer g tcref (tycon:Tycon) (_thisv, thise) thatobje (thatv, thate) compe = +let mkUnionEqualityWithComparer g tcref (tycon: Tycon) (_thisv, thise) thatobje (thatv, thate) compe = let m = tycon.Range let ucases = tycon.UnionCasesAsList let tinst, ty = mkMinimalTy g tcref @@ -534,7 +534,7 @@ let mkUnionEqualityWithComparer g tcref (tycon:Tycon) (_thisv, thise) thatobje ( let rfields = ucase.RecdFields if isNil rfields then None else - let mkTest thise thataddre j (argty:RecdField) = + let mkTest thise thataddre j (argty: RecdField) = mkCallGenericEqualityWithComparerOuter g m argty.FormalType compe (mkUnionCaseFieldGetProvenViaExprAddr(thise, cref, tinst, j, m)) @@ -584,12 +584,12 @@ let mkUnionEqualityWithComparer g tcref (tycon:Tycon) (_thisv, thise) thatobje ( //------------------------------------------------------------------------- /// Structural hash implementation for record types when parameterized by a comparer -let mkRecdHashWithComparer g tcref (tycon:Tycon) compe = +let mkRecdHashWithComparer g tcref (tycon: Tycon) compe = let m = tycon.Range let fields = tycon.AllInstanceFieldsAsList let tinst, ty = mkMinimalTy g tcref let thisv, thise = mkThisVar g m ty - let mkFieldHash (fspec:RecdField) = + let mkFieldHash (fspec: RecdField) = let fty = fspec.FormalType let fref = tcref.MakeNestedRecdFieldRef fspec let m = fref.Range @@ -604,11 +604,11 @@ let mkRecdHashWithComparer g tcref (tycon:Tycon) compe = thisv, expr /// Structural hash implementation for exception types when parameterized by a comparer -let mkExnHashWithComparer g exnref (exnc:Tycon) compe = +let mkExnHashWithComparer g exnref (exnc: Tycon) compe = let m = exnc.Range let thisv, thise = mkThisVar g m g.exn_ty - let mkHash i (rfield:RecdField) = + let mkHash i (rfield: RecdField) = let fty = rfield.FormalType let e = mkExnCaseFieldGet(thise, exnref, i, m) @@ -621,7 +621,7 @@ let mkExnHashWithComparer g exnref (exnc:Tycon) compe = thisv, expr /// Structural hash implementation for union types when parameterized by a comparer -let mkUnionHashWithComparer g tcref (tycon:Tycon) compe = +let mkUnionHashWithComparer g tcref (tycon: Tycon) compe = let m = tycon.Range let ucases = tycon.UnionCasesAsList let tinst, ty = mkMinimalTy g tcref @@ -633,7 +633,7 @@ let mkUnionHashWithComparer g tcref (tycon:Tycon) compe = let m = c1ref.Range if ucase1.IsNullary then None else - let mkHash thise j (rfield:RecdField) = + let mkHash thise j (rfield: RecdField) = let fty = rfield.FormalType let e = mkUnionCaseFieldGetProvenViaExprAddr(thise, c1ref, tinst, j, m) mkCallGenericHashWithComparerOuter g m fty compe e @@ -674,7 +674,7 @@ let mkUnionHashWithComparer g tcref (tycon:Tycon) compe = // though the interfaces may be discoverable via type tests. //------------------------------------------------------------------------- -let isNominalExnc (exnc:Tycon) = +let isNominalExnc (exnc: Tycon) = match exnc.ExceptionInfo with | TExnAbbrevRepr _ | TExnNone | TExnAsmRepr _ -> false | TExnFresh _ -> true @@ -682,18 +682,18 @@ let isNominalExnc (exnc:Tycon) = let isTrueFSharpStructTycon _g (tycon: Tycon) = (tycon.IsFSharpStructOrEnumTycon && not tycon.IsFSharpEnumTycon) -let canBeAugmentedWithEquals g (tycon:Tycon) = +let canBeAugmentedWithEquals g (tycon: Tycon) = tycon.IsUnionTycon || tycon.IsRecordTycon || (tycon.IsExceptionDecl && isNominalExnc tycon) || isTrueFSharpStructTycon g tycon -let canBeAugmentedWithCompare g (tycon:Tycon) = +let canBeAugmentedWithCompare g (tycon: Tycon) = tycon.IsUnionTycon || tycon.IsRecordTycon || isTrueFSharpStructTycon g tycon -let getAugmentationAttribs g (tycon:Tycon) = +let getAugmentationAttribs g (tycon: Tycon) = canBeAugmentedWithEquals g tycon, canBeAugmentedWithCompare g tycon, TryFindFSharpBoolAttribute g g.attrib_NoEqualityAttribute tycon.Attribs, @@ -704,7 +704,7 @@ let getAugmentationAttribs g (tycon:Tycon) = TryFindFSharpBoolAttribute g g.attrib_CustomComparisonAttribute tycon.Attribs, TryFindFSharpBoolAttribute g g.attrib_StructuralComparisonAttribute tycon.Attribs -let CheckAugmentationAttribs isImplementation g amap (tycon:Tycon) = +let CheckAugmentationAttribs isImplementation g amap (tycon: Tycon) = let m = tycon.Range let attribs = getAugmentationAttribs g tycon match attribs with @@ -822,7 +822,7 @@ let CheckAugmentationAttribs isImplementation g amap (tycon:Tycon) = | _ -> () -let TyconIsCandidateForAugmentationWithCompare (g: TcGlobals) (tycon:Tycon) = +let TyconIsCandidateForAugmentationWithCompare (g: TcGlobals) (tycon: Tycon) = // This type gets defined in prim-types, before we can add attributes to F# type definitions let isUnit = g.compilingFslib && tycon.DisplayName = "Unit" not isUnit && @@ -837,7 +837,7 @@ let TyconIsCandidateForAugmentationWithCompare (g: TcGlobals) (tycon:Tycon) = // other cases | _ -> false -let TyconIsCandidateForAugmentationWithEquals (g: TcGlobals) (tycon:Tycon) = +let TyconIsCandidateForAugmentationWithEquals (g: TcGlobals) (tycon: Tycon) = // This type gets defined in prim-types, before we can add attributes to F# type definitions let isUnit = g.compilingFslib && tycon.DisplayName = "Unit" not isUnit && @@ -883,7 +883,7 @@ let nonVirtualMethod c : ValMemberInfo = let unitArg = ValReprInfo.unitArgData let unaryArg = [ ValReprInfo.unnamedTopArg ] let tupArg = [ [ ValReprInfo.unnamedTopArg1; ValReprInfo.unnamedTopArg1 ] ] -let mkValSpec g (tcref:TyconRef) tmty vis slotsig methn ty argData = +let mkValSpec g (tcref: TyconRef) tmty vis slotsig methn ty argData = let m = tcref.Range let tps = tcref.Typars(m) let final = isUnionTy g tmty || isRecdTy g tmty || isStructTy g tmty @@ -893,7 +893,7 @@ let mkValSpec g (tcref:TyconRef) tmty vis slotsig methn ty argData = let topValInfo = Some (ValReprInfo (ValReprInfo.InferTyparInfo tps, args, ValReprInfo.unnamedRetVal)) NewVal (methn, m, None, ty, Immutable, true, topValInfo, vis, ValNotInRecScope, Some(membInfo), NormalVal, [], inl, XmlDoc.Empty, true, false, false, false, false, false, None, Parent(tcref)) -let MakeValsForCompareAugmentation g (tcref:TyconRef) = +let MakeValsForCompareAugmentation g (tcref: TyconRef) = let m = tcref.Range let _, tmty = mkMinimalTy g tcref let tps = tcref.Typars m @@ -902,14 +902,14 @@ let MakeValsForCompareAugmentation g (tcref:TyconRef) = mkValSpec g tcref tmty vis (Some(mkIComparableCompareToSlotSig g)) "CompareTo" (tps +-> (mkCompareObjTy g tmty)) unaryArg, mkValSpec g tcref tmty vis (Some(mkGenericIComparableCompareToSlotSig g tmty)) "CompareTo" (tps +-> (mkCompareTy g tmty)) unaryArg -let MakeValsForCompareWithComparerAugmentation g (tcref:TyconRef) = +let MakeValsForCompareWithComparerAugmentation g (tcref: TyconRef) = let m = tcref.Range let _, tmty = mkMinimalTy g tcref let tps = tcref.Typars m let vis = tcref.TypeReprAccessibility mkValSpec g tcref tmty vis (Some(mkIStructuralComparableCompareToSlotSig g)) "CompareTo" (tps +-> (mkCompareWithComparerTy g tmty)) tupArg -let MakeValsForEqualsAugmentation g (tcref:TyconRef) = +let MakeValsForEqualsAugmentation g (tcref: TyconRef) = let m = tcref.Range let _, tmty = mkMinimalTy g tcref let vis = tcref.TypeReprAccessibility @@ -919,7 +919,7 @@ let MakeValsForEqualsAugmentation g (tcref:TyconRef) = let nocEqualsVal = mkValSpec g tcref tmty vis (if tcref.Deref.IsExceptionDecl then None else Some(mkGenericIEquatableEqualsSlotSig g tmty)) "Equals" (tps +-> (mkEqualsTy g tmty)) unaryArg objEqualsVal, nocEqualsVal -let MakeValsForEqualityWithComparerAugmentation g (tcref:TyconRef) = +let MakeValsForEqualityWithComparerAugmentation g (tcref: TyconRef) = let _, tmty = mkMinimalTy g tcref let vis = tcref.TypeReprAccessibility let tps = tcref.Typars(tcref.Range) @@ -928,7 +928,7 @@ let MakeValsForEqualityWithComparerAugmentation g (tcref:TyconRef) = let withcEqualsVal = mkValSpec g tcref tmty vis (Some(mkIStructuralEquatableEqualsSlotSig g)) "Equals" (tps +-> (mkEqualsWithComparerTy g tmty)) tupArg objGetHashCodeVal, withcGetHashCodeVal, withcEqualsVal -let MakeBindingsForCompareAugmentation g (tycon:Tycon) = +let MakeBindingsForCompareAugmentation g (tycon: Tycon) = let tcref = mkLocalTyconRef tycon let m = tycon.Range let tps = tycon.Typars(tycon.Range) @@ -961,7 +961,7 @@ let MakeBindingsForCompareAugmentation g (tycon:Tycon) = elif tycon.IsRecordTycon || tycon.IsStructOrEnumTycon then mkCompare mkRecdCompare else [] -let MakeBindingsForCompareWithComparerAugmentation g (tycon:Tycon) = +let MakeBindingsForCompareWithComparerAugmentation g (tycon: Tycon) = let tcref = mkLocalTyconRef tycon let m = tycon.Range let tps = tycon.Typars(tycon.Range) @@ -987,7 +987,7 @@ let MakeBindingsForCompareWithComparerAugmentation g (tycon:Tycon) = elif tycon.IsRecordTycon || tycon.IsStructOrEnumTycon then mkCompare mkRecdCompareWithComparer else [] -let MakeBindingsForEqualityWithComparerAugmentation (g: TcGlobals) (tycon:Tycon) = +let MakeBindingsForEqualityWithComparerAugmentation (g: TcGlobals) (tycon: Tycon) = let tcref = mkLocalTyconRef tycon let m = tycon.Range let tps = tycon.Typars(tycon.Range) @@ -1034,7 +1034,7 @@ let MakeBindingsForEqualityWithComparerAugmentation (g: TcGlobals) (tycon:Tycon) elif tycon.IsExceptionDecl then mkStructuralEquatable mkExnHashWithComparer mkExnEqualityWithComparer else [] -let MakeBindingsForEqualsAugmentation (g: TcGlobals) (tycon:Tycon) = +let MakeBindingsForEqualsAugmentation (g: TcGlobals) (tycon: Tycon) = let tcref = mkLocalTyconRef tycon let m = tycon.Range let tps = tycon.Typars(m) diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index 02998022404..df5ffa8d8b7 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -66,7 +66,7 @@ let FSharpImplFileSuffixes = [".ml";".fs";".fsscript";".fsx"] let resSuffixes = [".resx"] let FSharpScriptFileSuffixes = [".fsscript";".fsx"] let doNotRequireNamespaceOrModuleSuffixes = [".mli";".ml"] @ FSharpScriptFileSuffixes -let FSharpLightSyntaxFileSuffixes : string list = [ ".fs";".fsscript";".fsx";".fsi" ] +let FSharpLightSyntaxFileSuffixes: string list = [ ".fs";".fsscript";".fsx";".fsi" ] //---------------------------------------------------------------------------- @@ -90,7 +90,7 @@ exception HashLoadedSourceHasIssues of (*warnings*) exn list * (*errors*) exn li exception HashLoadedScriptConsideredSource of range -let GetRangeOfDiagnostic(err:PhasedDiagnostic) = +let GetRangeOfDiagnostic(err: PhasedDiagnostic) = let rec RangeFromException = function | ErrorFromAddingConstraint(_, err2, _) -> RangeFromException err2 #if !NO_EXTENSIONTYPING @@ -234,8 +234,8 @@ let GetRangeOfDiagnostic(err:PhasedDiagnostic) = RangeFromException err.Exception -let GetDiagnosticNumber(err:PhasedDiagnostic) = - let rec GetFromException(e:exn) = +let GetDiagnosticNumber(err: PhasedDiagnostic) = + let rec GetFromException(e: exn) = match e with (* DO NOT CHANGE THESE NUMBERS *) | ErrorFromAddingTypeEquation _ -> 1 @@ -398,7 +398,7 @@ let warningOn err level specificWarnOn = | 3180 -> false // abImplicitHeapAllocation - off by default | _ -> level >= GetWarningLevel err -let SplitRelatedDiagnostics(err:PhasedDiagnostic) = +let SplitRelatedDiagnostics(err: PhasedDiagnostic) = let ToPhased(e) = {Exception=e; Phase = err.Phase} let rec SplitRelatedException = function | UnresolvedOverloading(a, overloads, b, c) -> @@ -595,11 +595,11 @@ let TargetInvocationExceptionWrapperE() = DeclareResourceString("TargetInvocatio let getErrorString key = SR.GetString key -let (|InvalidArgument|_|) (exn:exn) = match exn with :? ArgumentException as e -> Some e.Message | _ -> None +let (|InvalidArgument|_|) (exn: exn) = match exn with :? ArgumentException as e -> Some e.Message | _ -> None -let OutputPhasedErrorR (os:StringBuilder) (err:PhasedDiagnostic) = +let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = - let rec OutputExceptionR (os:StringBuilder) error = + let rec OutputExceptionR (os: StringBuilder) error = match error with | ConstraintSolverTupleDiffLengths(_, tl1, tl2, m, m2) -> @@ -1187,7 +1187,7 @@ let OutputPhasedErrorR (os:StringBuilder) (err:PhasedDiagnostic) = #else foundInContext |> ignore // suppress unused variable warning in RELEASE #endif - let fix (s:string) = s.Replace(SR.GetString("FixKeyword"), "").Replace(SR.GetString("FixSymbol"), "").Replace(SR.GetString("FixReplace"), "") + let fix (s: string) = s.Replace(SR.GetString("FixKeyword"), "").Replace(SR.GetString("FixSymbol"), "").Replace(SR.GetString("FixReplace"), "") match (ctxt.ShiftTokens |> List.map Parser.tokenTagToTokenId |> List.filter (function Parser.TOKEN_error | Parser.TOKEN_EOF -> false | _ -> true) @@ -1326,7 +1326,7 @@ let OutputPhasedErrorR (os:StringBuilder) (err:PhasedDiagnostic) = | LetRecUnsound (_, path, _) -> let bos = new System.Text.StringBuilder() - (path.Tail @ [path.Head]) |> List.iter (fun (v:ValRef) -> bos.Append(LetRecUnsoundInnerE().Format v.DisplayName) |> ignore) + (path.Tail @ [path.Head]) |> List.iter (fun (v: ValRef) -> bos.Append(LetRecUnsoundInnerE().Format v.DisplayName) |> ignore) os.Append(LetRecUnsound2E().Format (List.head path).DisplayName (bos.ToString())) |> ignore | LetRecEvaluatedOutOfOrder (_, _, _, _) -> @@ -1527,7 +1527,7 @@ let OutputPhasedErrorR (os:StringBuilder) (err:PhasedDiagnostic) = os.Append(FSComp.SR.buildUnexpectedFileNameCharacter(fileName, string invalidChar)|>snd) |> ignore | HashLoadedSourceHasIssues(warnings, errors, _) -> - let Emit(l:exn list) = + let Emit(l: exn list) = OutputExceptionR os (List.head l) if errors=[] then os.Append(HashLoadedSourceHasIssues1E().Format) |> ignore @@ -1580,7 +1580,7 @@ let OutputPhasedErrorR (os:StringBuilder) (err:PhasedDiagnostic) = // remove any newlines and tabs -let OutputPhasedDiagnostic (os:System.Text.StringBuilder) (err:PhasedDiagnostic) (flattenErrors:bool) = +let OutputPhasedDiagnostic (os: System.Text.StringBuilder) (err: PhasedDiagnostic) (flattenErrors: bool) = let buf = new System.Text.StringBuilder() OutputPhasedErrorR buf err @@ -1610,22 +1610,22 @@ let SanitizeFileName fileName implicitIncludeDir = [] type DiagnosticLocation = - { Range : range - File : string - TextRepresentation : string - IsEmpty : bool } + { Range: range + File: string + TextRepresentation: string + IsEmpty: bool } [] type DiagnosticCanonicalInformation = - { ErrorNumber : int - Subcategory : string - TextRepresentation : string } + { ErrorNumber: int + Subcategory: string + TextRepresentation: string } [] type DiagnosticDetailedInfo = - { Location : DiagnosticLocation option - Canonical : DiagnosticCanonicalInformation - Message : string } + { Location: DiagnosticLocation option + Canonical: DiagnosticCanonicalInformation + Message: string } [] type Diagnostic = @@ -1633,8 +1633,8 @@ type Diagnostic = | Long of bool * DiagnosticDetailedInfo /// returns sequence that contains Diagnostic for the given error + Diagnostic for all related errors -let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError, err:PhasedDiagnostic) = - let outputWhere (showFullPaths, errorStyle) m : DiagnosticLocation = +let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError, err: PhasedDiagnostic) = + let outputWhere (showFullPaths, errorStyle) m: DiagnosticLocation = if m = rangeStartup || m = rangeCmdArgs then { Range = m; TextRepresentation = ""; IsEmpty = true; File = "" } else @@ -1669,7 +1669,7 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt // Here, we want the complete range information so Project Systems can generate proper squiggles | ErrorStyle.VSErrors -> // Show prefix only for real files. Otherwise, we just want a truncated error like: - // parse error FS0031 : blah blah + // parse error FS0031: blah blah if m<>range0 && m<>rangeStartup && m<>rangeCmdArgs then let file = file.Replace("/", "\\") let m = mkRange m.FileName (mkPos m.StartLine (m.StartColumn + 1)) (mkPos m.EndLine (m.EndColumn + 1) ) @@ -1709,11 +1709,11 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt OutputPhasedDiagnostic os mainError flattenErrors os.ToString() - let entry : DiagnosticDetailedInfo = { Location = where; Canonical = canonical; Message = message } + let entry: DiagnosticDetailedInfo = { Location = where; Canonical = canonical; Message = message } errors.Add ( Diagnostic.Long(isError, entry ) ) - let OutputRelatedError(err:PhasedDiagnostic) = + let OutputRelatedError(err: PhasedDiagnostic) = match errorStyle with // Give a canonical string when --vserror. | ErrorStyle.VSErrors -> @@ -1724,7 +1724,7 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt OutputPhasedDiagnostic os err flattenErrors os.ToString() - let entry : DiagnosticDetailedInfo = { Location = relWhere; Canonical = relCanonical; Message = relMessage} + let entry: DiagnosticDetailedInfo = { Location = relWhere; Canonical = relCanonical; Message = relMessage} errors.Add( Diagnostic.Long (isError, entry) ) | _ -> @@ -1744,11 +1744,11 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt #endif | x -> report x - errors :> seq<_> + errors:> seq<_> /// used by fsc.exe and fsi.exe, but not by VS /// prints error and related errors to the specified StringBuilder -let rec OutputDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError) os (err:PhasedDiagnostic) = +let rec OutputDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError) os (err: PhasedDiagnostic) = let errors = CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorStyle, isError, err) for e in errors do @@ -2021,7 +2021,7 @@ let ResolveFileUsingPaths(paths, m, name) = let searchMessage = String.concat "\n " paths raise (FileNameNotResolved(name, searchMessage, m)) -let GetWarningNumber(m, s:string) = +let GetWarningNumber(m, s: string) = try // Okay so ... // #pragma strips FS of the #pragma "FS0004" and validates the warning number @@ -2034,7 +2034,7 @@ let GetWarningNumber(m, s:string) = warning(Error(FSComp.SR.buildInvalidWarningNumber(s), m)) None -let ComputeMakePathAbsolute implicitIncludeDir (path : string) = +let ComputeMakePathAbsolute implicitIncludeDir (path: string) = try // remove any quotation marks from the path first let path = path.Replace("\"", "") @@ -2090,24 +2090,24 @@ type VersionFlag = /// reference backed by information generated by the the compiler service. type IRawFSharpAssemblyData = /// The raw list AutoOpenAttribute attributes in the assembly - abstract GetAutoOpenAttributes : ILGlobals -> string list + abstract GetAutoOpenAttributes: ILGlobals -> string list /// The raw list InternalsVisibleToAttribute attributes in the assembly - abstract GetInternalsVisibleToAttributes : ILGlobals -> string list + abstract GetInternalsVisibleToAttributes: ILGlobals -> string list /// The raw IL module definition in the assembly, if any. This is not present for cross-project references /// in the language service - abstract TryGetILModuleDef : unit -> ILModuleDef option + abstract TryGetILModuleDef: unit -> ILModuleDef option /// The raw F# signature data in the assembly, if any - abstract GetRawFSharpSignatureData : range * ilShortAssemName: string * fileName: string -> (string * (unit -> byte[])) list + abstract GetRawFSharpSignatureData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> byte[])) list /// The raw F# optimization data in the assembly, if any - abstract GetRawFSharpOptimizationData : range * ilShortAssemName: string * fileName: string -> (string * (unit -> byte[])) list + abstract GetRawFSharpOptimizationData: range * ilShortAssemName: string * fileName: string -> (string * (unit -> byte[])) list /// The table of type forwarders in the assembly - abstract GetRawTypeForwarders : unit -> ILExportedTypesAndForwarders + abstract GetRawTypeForwarders: unit -> ILExportedTypesAndForwarders /// The identity of the module - abstract ILScopeRef : ILScopeRef - abstract ILAssemblyRefs : ILAssemblyRef list - abstract ShortAssemblyName : string - abstract HasAnyFSharpSignatureDataAttribute : bool - abstract HasMatchingFSharpSignatureDataAttribute : ILGlobals -> bool + abstract ILScopeRef: ILScopeRef + abstract ILAssemblyRefs: ILAssemblyRef list + abstract ShortAssemblyName: string + abstract HasAnyFSharpSignatureDataAttribute: bool + abstract HasMatchingFSharpSignatureDataAttribute: ILGlobals -> bool /// Cache of time stamps as we traverse a project description type TimeStampCache(defaultTimeStamp: DateTime) = @@ -2134,10 +2134,10 @@ type TimeStampCache(defaultTimeStamp: DateTime) = and IProjectReference = /// The name of the assembly file generated by the project - abstract FileName : string + abstract FileName: string /// Evaluate raw contents of the assembly file generated by the project - abstract EvaluateRawContents : CompilationThreadToken -> Cancellable + abstract EvaluateRawContents: CompilationThreadToken -> Cancellable /// Get the logical timestamp that would be the timestamp of the assembly file generated by the project /// @@ -2147,7 +2147,7 @@ and IProjectReference = /// /// The operation returns None only if it is not possible to create an IncrementalBuilder for the project at all, e.g. if there /// are fatal errors in the options for the project. - abstract TryGetLogicalTimeStamp : TimeStampCache * CompilationThreadToken -> System.DateTime option + abstract TryGetLogicalTimeStamp: TimeStampCache * CompilationThreadToken -> System.DateTime option type AssemblyReference = | AssemblyReference of range * string * IProjectReference option @@ -2173,9 +2173,9 @@ type ImportedBinary = #if !NO_EXTENSIONTYPING ProviderGeneratedAssembly: System.Reflection.Assembly option IsProviderGenerated: bool - ProviderGeneratedStaticLinkMap : ProvidedAssemblyStaticLinkingMap option + ProviderGeneratedStaticLinkMap: ProvidedAssemblyStaticLinkingMap option #endif - ILAssemblyRefs : ILAssemblyRef list + ILAssemblyRefs: ILAssemblyRef list ILScopeRef: ILScopeRef } type ImportedAssembly = @@ -2187,7 +2187,7 @@ type ImportedAssembly = IsProviderGenerated: bool mutable TypeProviders: Tainted list #endif - FSharpOptimizationData : Microsoft.FSharp.Control.Lazy> } + FSharpOptimizationData: Microsoft.FSharp.Control.Lazy> } type AvailableImportedAssembly = | ResolvedImportedAssembly of ImportedAssembly @@ -2199,7 +2199,7 @@ type CcuLoadFailureAction = [] type TcConfigBuilder = - { mutable primaryAssembly : PrimaryAssembly + { mutable primaryAssembly: PrimaryAssembly mutable autoResolveOpenDirectivesToDlls: bool mutable noFeedback: bool mutable stackReserveSize: int32 option @@ -2215,144 +2215,144 @@ type TcConfigBuilder = mutable implicitOpens: string list mutable useFsiAuxLib: bool mutable framework: bool - mutable resolutionEnvironment : ReferenceResolver.ResolutionEnvironment + mutable resolutionEnvironment: ReferenceResolver.ResolutionEnvironment mutable implicitlyResolveAssemblies: bool mutable light: bool option mutable conditionalCompilationDefines: string list mutable loadedSources: (range * string) list - mutable referencedDLLs : AssemblyReference list - mutable projectReferences : IProjectReference list - mutable knownUnresolvedReferences : UnresolvedAssemblyReference list + mutable referencedDLLs: AssemblyReference list + mutable projectReferences: IProjectReference list + mutable knownUnresolvedReferences: UnresolvedAssemblyReference list reduceMemoryUsage: ReduceMemoryFlag - mutable subsystemVersion : int * int - mutable useHighEntropyVA : bool + mutable subsystemVersion: int * int + mutable useHighEntropyVA: bool mutable inputCodePage: int option - mutable embedResources : string list + mutable embedResources: string list mutable errorSeverityOptions: FSharpErrorSeverityOptions mutable mlCompatibility: bool mutable checkOverflow: bool - mutable showReferenceResolutions:bool - mutable outputFile : string option - mutable platform : ILPlatform option - mutable prefer32Bit : bool - mutable useSimpleResolution : bool - mutable target : CompilerTarget - mutable debuginfo : bool - mutable testFlagEmitFeeFeeAs100001 : bool - mutable dumpDebugInfo : bool - mutable debugSymbolFile : string option + mutable showReferenceResolutions: bool + mutable outputFile: string option + mutable platform: ILPlatform option + mutable prefer32Bit: bool + mutable useSimpleResolution: bool + mutable target: CompilerTarget + mutable debuginfo: bool + mutable testFlagEmitFeeFeeAs100001: bool + mutable dumpDebugInfo: bool + mutable debugSymbolFile: string option (* Backend configuration *) - mutable typeCheckOnly : bool - mutable parseOnly : bool - mutable importAllReferencesOnly : bool - mutable simulateException : string option - mutable printAst : bool - mutable tokenizeOnly : bool - mutable testInteractionParser : bool - mutable reportNumDecls : bool - mutable printSignature : bool - mutable printSignatureFile : string - mutable xmlDocOutputFile : string option - mutable stats : bool - mutable generateFilterBlocks : bool (* don't generate filter blocks due to bugs on Mono *) - - mutable signer : string option - mutable container : string option - - mutable delaysign : bool - mutable publicsign : bool - mutable version : VersionFlag - mutable metadataVersion : string option - mutable standalone : bool - mutable extraStaticLinkRoots : string list - mutable noSignatureData : bool - mutable onlyEssentialOptimizationData : bool - mutable useOptimizationDataFile : bool - mutable jitTracking : bool - mutable portablePDB : bool - mutable embeddedPDB : bool - mutable embedAllSource : bool - mutable embedSourceList : string list - mutable sourceLink : string - - mutable ignoreSymbolStoreSequencePoints : bool - mutable internConstantStrings : bool - mutable extraOptimizationIterations : int - - mutable win32res : string - mutable win32manifest : string - mutable includewin32manifest : bool - mutable linkResources : string list + mutable typeCheckOnly: bool + mutable parseOnly: bool + mutable importAllReferencesOnly: bool + mutable simulateException: string option + mutable printAst: bool + mutable tokenizeOnly: bool + mutable testInteractionParser: bool + mutable reportNumDecls: bool + mutable printSignature: bool + mutable printSignatureFile: string + mutable xmlDocOutputFile: string option + mutable stats: bool + mutable generateFilterBlocks: bool (* don't generate filter blocks due to bugs on Mono *) + + mutable signer: string option + mutable container: string option + + mutable delaysign: bool + mutable publicsign: bool + mutable version: VersionFlag + mutable metadataVersion: string option + mutable standalone: bool + mutable extraStaticLinkRoots: string list + mutable noSignatureData: bool + mutable onlyEssentialOptimizationData: bool + mutable useOptimizationDataFile: bool + mutable jitTracking: bool + mutable portablePDB: bool + mutable embeddedPDB: bool + mutable embedAllSource: bool + mutable embedSourceList: string list + mutable sourceLink: string + + mutable ignoreSymbolStoreSequencePoints: bool + mutable internConstantStrings: bool + mutable extraOptimizationIterations: int + + mutable win32res: string + mutable win32manifest: string + mutable includewin32manifest: bool + mutable linkResources: string list mutable legacyReferenceResolver: ReferenceResolver.Resolver - mutable showFullPaths : bool - mutable errorStyle : ErrorStyle - mutable utf8output : bool + mutable showFullPaths: bool + mutable errorStyle: ErrorStyle + mutable utf8output: bool mutable flatErrors: bool - mutable maxErrors : int - mutable abortOnError : bool (* intended for fsi scripts that should exit on first error *) - mutable baseAddress : int32 option + mutable maxErrors: int + mutable abortOnError: bool (* intended for fsi scripts that should exit on first error *) + mutable baseAddress: int32 option #if DEBUG - mutable showOptimizationData : bool + mutable showOptimizationData: bool #endif - mutable showTerms : bool (* show terms between passes? *) - mutable writeTermsToFiles : bool (* show terms to files? *) - mutable doDetuple : bool (* run detuple pass? *) - mutable doTLR : bool (* run TLR pass? *) - mutable doFinalSimplify : bool (* do final simplification pass *) - mutable optsOn : bool (* optimizations are turned on *) - mutable optSettings : Optimizer.OptimizationSettings - mutable emitTailcalls : bool - mutable deterministic : bool + mutable showTerms: bool (* show terms between passes? *) + mutable writeTermsToFiles: bool (* show terms to files? *) + mutable doDetuple: bool (* run detuple pass? *) + mutable doTLR: bool (* run TLR pass? *) + mutable doFinalSimplify: bool (* do final simplification pass *) + mutable optsOn: bool (* optimizations are turned on *) + mutable optSettings: Optimizer.OptimizationSettings + mutable emitTailcalls: bool + mutable deterministic: bool mutable preferredUiLang: string option - mutable lcid : int option - mutable productNameForBannerText : string + mutable lcid: int option + mutable productNameForBannerText: string /// show the MS (c) notice, e.g. with help or fsi? - mutable showBanner : bool + mutable showBanner: bool /// show times between passes? - mutable showTimes : bool - mutable showLoadedAssemblies : bool - mutable continueAfterParseFailure : bool + mutable showTimes: bool + mutable showLoadedAssemblies: bool + mutable continueAfterParseFailure: bool #if !NO_EXTENSIONTYPING /// show messages about extension type resolution? - mutable showExtensionTypeMessages : bool + mutable showExtensionTypeMessages: bool #endif /// pause between passes? - mutable pause : bool + mutable pause: bool /// whenever possible, emit callvirt instead of call - mutable alwaysCallVirt : bool + mutable alwaysCallVirt: bool /// if true, strip away data that would not be of use to end users, but is useful to us for debugging // REVIEW: "stripDebugData"? - mutable noDebugData : bool + mutable noDebugData: bool /// if true, indicates all type checking and code generation is in the context of fsi.exe - isInteractive : bool - isInvalidationSupported : bool + isInteractive: bool + isInvalidationSupported: bool /// used to log sqm data /// if true - every expression in quotations will be augmented with full debug info (filename, location in file) - mutable emitDebugInfoInQuotations : bool + mutable emitDebugInfoInQuotations: bool - mutable exename : string option + mutable exename: string option // If true - the compiler will copy FSharp.Core.dll along the produced binaries - mutable copyFSharpCore : CopyFSharpCoreFlag + mutable copyFSharpCore: CopyFSharpCoreFlag /// When false FSI will lock referenced assemblies requiring process restart, false = disable Shadow Copy false (*default*) - mutable shadowCopyReferences : bool + mutable shadowCopyReferences: bool /// A function to call to try to get an object that acts as a snapshot of the metadata section of a .NET binary, /// and from which we can read the metadata. Only used when metadataOnly=true. - mutable tryGetMetadataSnapshot : ILReaderTryGetMetadataSnapshot + mutable tryGetMetadataSnapshot: ILReaderTryGetMetadataSnapshot - mutable internalTestSpanStackReferring : bool + mutable internalTestSpanStackReferring: bool - mutable noConditionalErasure : bool + mutable noConditionalErasure: bool } static member Initial = @@ -2552,7 +2552,7 @@ type TcConfigBuilder = tcConfigB.outputFile <- Some(outfile) outfile, pdbfile, assemblyName - member tcConfigB.TurnWarningOff(m, s:string) = + member tcConfigB.TurnWarningOff(m, s: string) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter match GetWarningNumber(m, s) with | None -> () @@ -2562,7 +2562,7 @@ type TcConfigBuilder = tcConfigB.errorSeverityOptions <- { tcConfigB.errorSeverityOptions with WarnOff = ListSet.insert (=) n tcConfigB.errorSeverityOptions.WarnOff } - member tcConfigB.TurnWarningOn(m, s:string) = + member tcConfigB.TurnWarningOn(m, s: string) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter match GetWarningNumber(m, s) with | None -> () @@ -2615,7 +2615,7 @@ type TcConfigBuilder = member tcConfigB.RemoveReferencedAssemblyByPath (m, path) = tcConfigB.referencedDLLs <- tcConfigB.referencedDLLs |> List.filter (fun ar-> ar.Range <> m || ar.Text <> path) - static member SplitCommandLineResourceInfo (ri:string) = + static member SplitCommandLineResourceInfo (ri: string) = let p = ri.IndexOf ',' if p <> -1 then let file = String.sub ri 0 p @@ -2634,7 +2634,7 @@ type TcConfigBuilder = let OpenILBinary(filename, reduceMemoryUsage, ilGlobals, pdbDirPath, shadowCopyReferences, tryGetMetadataSnapshot) = - let opts : ILReaderOptions = + let opts: ILReaderOptions = { ilGlobals = ilGlobals metadataOnly = MetadataOnlyFlag.Yes reduceMemoryUsage = reduceMemoryUsage @@ -2660,11 +2660,11 @@ let OpenILBinary(filename, reduceMemoryUsage, ilGlobals, pdbDirPath, shadowCopyR [] #endif type AssemblyResolution = - { originalReference : AssemblyReference - resolvedPath : string - prepareToolTip : unit -> string - sysdir : bool - ilAssemblyRef : ILAssemblyRef option ref + { originalReference: AssemblyReference + resolvedPath: string + prepareToolTip: unit -> string + sysdir: bool + ilAssemblyRef: ILAssemblyRef option ref } override this.ToString() = sprintf "%s%s" (if this.sysdir then "[sys]" else "") this.resolvedPath @@ -2699,7 +2699,7 @@ type AssemblyResolution = match assemblyRefOpt with | Some aref -> aref | None -> - let readerSettings : ILReaderOptions = + let readerSettings: ILReaderOptions = { pdbDirPath=None ilGlobals = EcmaMscorlibILGlobals reduceMemoryUsage = reduceMemoryUsage @@ -2726,7 +2726,7 @@ let MakeScopeRefForILModule (ilModule: ILModuleDef) = | Some m -> ILScopeRef.Assembly (mkRefToILAssembly m) | None -> ILScopeRef.Module (mkRefToILModule ilModule) -let GetCustomAttributesOfILModule (ilModule:ILModuleDef) = +let GetCustomAttributesOfILModule (ilModule: ILModuleDef) = (match ilModule.Manifest with Some m -> m.CustomAttrs | None -> ilModule.CustomAttrs).AsList let GetAutoOpenAttributes ilg ilModule = @@ -2741,7 +2741,7 @@ let GetInternalsVisibleToAttributes ilg ilModule = [] /// This type is immutable and must be kept as such. Do not extract or mutate the underlying data except by cloning it. -type TcConfig private (data : TcConfigBuilder, validate:bool) = +type TcConfig private (data: TcConfigBuilder, validate: bool) = // Validate the inputs - this helps ensure errors in options are shown in visual studio rather than only when built // However we only validate a minimal number of options at the moment @@ -2752,7 +2752,7 @@ type TcConfig private (data : TcConfigBuilder, validate:bool) = let computeKnownDllReference(libraryName) = let defaultCoreLibraryReference = AssemblyReference(range0, libraryName+".dll", None) - let nameOfDll(r:AssemblyReference) = + let nameOfDll(r: AssemblyReference) = let filename = ComputeMakePathAbsolute data.implicitIncludeDir r.Text if FileSystem.SafeExists(filename) then r, Some(filename) @@ -2967,7 +2967,7 @@ type TcConfig private (data : TcConfigBuilder, validate:bool) = member tcConfig.CloneOfOriginalBuilder = { data with conditionalCompilationDefines=data.conditionalCompilationDefines } - member tcConfig.ComputeCanContainEntryPoint(sourceFiles:string list) = + member tcConfig.ComputeCanContainEntryPoint(sourceFiles: string list) = let n = sourceFiles.Length in (sourceFiles |> List.mapi (fun i _ -> (i = n-1)), tcConfig.target.IsExe) @@ -3065,7 +3065,7 @@ type TcConfig private (data : TcConfigBuilder, validate:bool) = /// /// Returning true may mean that the file is locked and/or placed into the /// 'framework' reference set that is potentially shared across multiple compilations. - member tcConfig.IsSystemAssembly (filename:string) = + member tcConfig.IsSystemAssembly (filename: string) = try FileSystem.SafeExists filename && ((tcConfig.GetTargetFrameworkDirectories() |> List.exists (fun clrRoot -> clrRoot = Path.GetDirectoryName filename)) || @@ -3085,7 +3085,7 @@ type TcConfig private (data : TcConfigBuilder, validate:bool) = let result = ComputeMakePathAbsolute tcConfig.implicitIncludeDir path result - member tcConfig.TryResolveLibWithDirectories (r:AssemblyReference) = + member tcConfig.TryResolveLibWithDirectories (r: AssemblyReference) = let m, nm = r.Range, r.Text use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter // Only want to resolve certain extensions (otherwise, 'System.Xml' is ambiguous). @@ -3129,14 +3129,14 @@ type TcConfig private (data : TcConfigBuilder, validate:bool) = resolvedPath = resolved prepareToolTip = (fun () -> let fusionName = System.Reflection.AssemblyName.GetAssemblyName(resolved).ToString() - let line(append:string) = append.Trim([|' '|])+"\n" + let line(append: string) = append.Trim([|' '|])+"\n" line(resolved) + line(fusionName)) sysdir = sysdir ilAssemblyRef = ref None } | None -> None else None - member tcConfig.ResolveLibWithDirectories (ccuLoadFaulureAction, r:AssemblyReference) = + member tcConfig.ResolveLibWithDirectories (ccuLoadFaulureAction, r: AssemblyReference) = let m, nm = r.Range, r.Text use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter // test for both libraries and executables @@ -3167,7 +3167,7 @@ type TcConfig private (data : TcConfigBuilder, validate:bool) = // it must return warnings and errors as data // // NOTE!! if mode=ReportErrors then this method must not raise exceptions. It must just report the errors and recover - static member TryResolveLibsUsingMSBuildRules (tcConfig:TcConfig, originalReferences:AssemblyReference list, errorAndWarningRange:range, mode:ResolveAssemblyReferenceMode) : AssemblyResolution list * UnresolvedAssemblyReference list = + static member TryResolveLibsUsingMSBuildRules (tcConfig: TcConfig, originalReferences: AssemblyReference list, errorAndWarningRange: range, mode: ResolveAssemblyReferenceMode) : AssemblyResolution list * UnresolvedAssemblyReference list = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter if tcConfig.useSimpleResolution then failwith "MSBuild resolution is not supported." @@ -3187,7 +3187,7 @@ type TcConfig private (data : TcConfigBuilder, validate:bool) = |> Array.ofSeq let logMessage showMessages = - if showMessages && tcConfig.showReferenceResolutions then (fun (message:string)->dprintf "%s\n" message) + if showMessages && tcConfig.showReferenceResolutions then (fun (message: string)->dprintf "%s\n" message) else ignore let logDiagnostic showMessages = @@ -3276,7 +3276,7 @@ type TcConfig private (data : TcConfigBuilder, validate:bool) = |> List.concat // O(N^2) here over a small set of referenced assemblies. - let IsResolved(originalName:string) = + let IsResolved(originalName: string) = if resultingResolutions |> List.exists(fun resolution -> resolution.originalReference.Text = originalName) then true else // MSBuild resolution may have unified the result of two duplicate references. Try to re-resolve now. @@ -3340,7 +3340,7 @@ let GetScopedPragmasForInput input = // However this is indicative of a more systematic problem where source-line // sensitive operations (lexfilter and warning filtering) do not always // interact well with #line directives. -type ErrorLoggerFilteringByScopedPragmas (checkFile, scopedPragmas, errorLogger:ErrorLogger) = +type ErrorLoggerFilteringByScopedPragmas (checkFile, scopedPragmas, errorLogger: ErrorLogger) = inherit ErrorLogger("ErrorLoggerFilteringByScopedPragmas") override x.DiagnosticSink (phasedError, isError) = @@ -3528,7 +3528,7 @@ let PostParseModuleSpecs (defaultNamespace, filename, isLastCompiland, ParsedSig type ModuleNamesDict = Map> /// Checks if a module name is already given and deduplicates the name if needed. -let DeduplicateModuleName (moduleNamesDict:ModuleNamesDict) fileName (qualNameOfFile: QualifiedNameOfFile) = +let DeduplicateModuleName (moduleNamesDict: ModuleNamesDict) fileName (qualNameOfFile: QualifiedNameOfFile) = let path = Path.GetDirectoryName fileName let path = if FileSystem.IsPathRootedShim path then try FileSystem.GetFullPathShim path with _ -> path else path match moduleNamesDict.TryGetValue qualNameOfFile.Text with @@ -3557,7 +3557,7 @@ let DeduplicateParsedInputModuleName (moduleNamesDict: ModuleNamesDict) input = let inputT = ParsedInput.SigFile (ParsedSigFileInput.ParsedSigFileInput(fileName, qualNameOfFileT, scopedPragmas, hashDirectives, modules)) inputT, moduleNamesDictT -let ParseInput (lexer, errorLogger:ErrorLogger, lexbuf:UnicodeLexing.Lexbuf, defaultNamespace, filename, isLastCompiland) = +let ParseInput (lexer, errorLogger: ErrorLogger, lexbuf: UnicodeLexing.Lexbuf, defaultNamespace, filename, isLastCompiland) = // The assert below is almost ok, but it fires in two cases: // - fsi.exe sometimes passes "stdin" as a dummy filename // - if you have a #line directive, e.g. @@ -3595,7 +3595,7 @@ let ParseInput (lexer, errorLogger:ErrorLogger, lexbuf:UnicodeLexing.Lexbuf, def // parsing - ParseOneInputFile // Filename is (ml/mli/fs/fsi source). Parse it to AST. //---------------------------------------------------------------------------- -let ParseOneInputLexbuf (tcConfig:TcConfig, lexResourceManager, conditionalCompilationDefines, lexbuf, filename, isLastCompiland, errorLogger) = +let ParseOneInputLexbuf (tcConfig: TcConfig, lexResourceManager, conditionalCompilationDefines, lexbuf, filename, isLastCompiland, errorLogger) = use unwindbuildphase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse try let skip = true in (* don't report whitespace from lexer *) @@ -3658,7 +3658,7 @@ let ParseOneInputFile (tcConfig: TcConfig, lexResourceManager, conditionalCompil [] -type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, unresolved : UnresolvedAssemblyReference list) = +type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, unresolved: UnresolvedAssemblyReference list) = let originalReferenceToResolution = results |> List.map (fun r -> r.originalReference.Text, r) |> Map.ofList let resolvedPathToResolution = results |> List.map (fun r -> r.resolvedPath, r) |> Map.ofList @@ -3672,7 +3672,7 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, /// Get information about referenced DLLs member tcResolutions.GetAssemblyResolutions() = results member tcResolutions.GetUnresolvedReferences() = unresolved - member tcResolutions.TryFindByOriginalReference(assemblyReference:AssemblyReference) = originalReferenceToResolution.TryFind assemblyReference.Text + member tcResolutions.TryFindByOriginalReference(assemblyReference: AssemblyReference) = originalReferenceToResolution.TryFind assemblyReference.Text /// This doesn't need to be cancellable, it is only used by F# Interactive member tcResolution.TryFindByExactILAssemblyRef (ctok, assemblyRef) = @@ -3689,7 +3689,7 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, member tcResolutions.TryFindByResolvedPath nm = resolvedPathToResolution.TryFind nm member tcResolutions.TryFindByOriginalReferenceText nm = originalReferenceToResolution.TryFind nm - static member ResolveAssemblyReferences (ctok, tcConfig:TcConfig, assemblyList:AssemblyReference list, knownUnresolved:UnresolvedAssemblyReference list) : TcAssemblyResolutions = + static member ResolveAssemblyReferences (ctok, tcConfig: TcConfig, assemblyList: AssemblyReference list, knownUnresolved: UnresolvedAssemblyReference list) : TcAssemblyResolutions = let resolved, unresolved = if tcConfig.useSimpleResolution then let resolutions = @@ -3709,7 +3709,7 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, TcAssemblyResolutions(tcConfig, resolved, unresolved @ knownUnresolved) - static member GetAllDllReferences (tcConfig:TcConfig) = + static member GetAllDllReferences (tcConfig: TcConfig) = [ let primaryReference = tcConfig.PrimaryAssemblyDllReference() yield primaryReference @@ -3729,7 +3729,7 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, yield! tcConfig.referencedDLLs ] - static member SplitNonFoundationalResolutions (ctok, tcConfig:TcConfig) = + static member SplitNonFoundationalResolutions (ctok, tcConfig: TcConfig) = let assemblyList = TcAssemblyResolutions.GetAllDllReferences tcConfig let resolutions = TcAssemblyResolutions.ResolveAssemblyReferences (ctok, tcConfig, assemblyList, tcConfig.knownUnresolvedReferences) let frameworkDLLs, nonFrameworkReferences = resolutions.GetAssemblyResolutions() |> List.partition (fun r -> r.sysdir) @@ -3761,7 +3761,7 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, #endif frameworkDLLs, nonFrameworkReferences, unresolved - static member BuildFromPriorResolutions (ctok, tcConfig:TcConfig, resolutions, knownUnresolved) = + static member BuildFromPriorResolutions (ctok, tcConfig: TcConfig, resolutions, knownUnresolved) = let references = resolutions |> List.map (fun r -> r.originalReference) TcAssemblyResolutions.ResolveAssemblyReferences (ctok, tcConfig, references, knownUnresolved) @@ -3922,10 +3922,10 @@ type TcConfigProvider = /// Represents a table of imported assemblies with their resolutions. [] -type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResolutions, importsBase:TcImports option, ilGlobalsOpt) = +type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolutions, importsBase: TcImports option, ilGlobalsOpt) = let mutable resolutions = initialResolutions - let mutable importsBase : TcImports option = importsBase + let mutable importsBase: TcImports option = importsBase let mutable dllInfos: ImportedBinary list = [] let mutable dllTable: NameMap = NameMap.empty let mutable ccuInfos: ImportedAssembly list = [] @@ -3941,7 +3941,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti let CheckDisposed() = if disposed then assert false - static let ccuHasType (ccu : CcuThunk) (nsname : string list) (tname : string) = + static let ccuHasType (ccu: CcuThunk) (nsname: string list) (tname: string) = match (Some ccu.Contents, nsname) ||> List.fold (fun entityOpt n -> match entityOpt with None -> None | Some entity -> entity.ModuleOrNamespaceType.AllEntitiesByCompiledAndLogicalMangledNames.TryFind n) with | Some ns -> match Map.tryFind tname ns.ModuleOrNamespaceType.TypesByMangledName with @@ -3987,7 +3987,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti member tcImports.TryFindDllInfo (ctok: CompilationThreadToken, m, assemblyName, lookupOnly) = CheckDisposed() - let rec look (t:TcImports) = + let rec look (t: TcImports) = match NameMap.tryFind assemblyName t.DllTable with | Some res -> Some(res) | None -> @@ -4023,7 +4023,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti // This is the main "assembly reference --> assembly" resolution routine. member tcImports.FindCcuInfo (ctok, m, assemblyName, lookupOnly) = CheckDisposed() - let rec look (t:TcImports) = + let rec look (t: TcImports) = match NameMap.tryFind assemblyName t.CcuTable with | Some res -> Some(res) | None -> @@ -4046,7 +4046,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti | ResolvedImportedAssembly(importedAssembly) -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) | UnresolvedImportedAssembly(assemblyName) -> UnresolvedCcu(assemblyName) - member tcImports.FindCcuFromAssemblyRef(ctok, m, assemblyRef:ILAssemblyRef) = + member tcImports.FindCcuFromAssemblyRef(ctok, m, assemblyRef: ILAssemblyRef) = CheckDisposed() match tcImports.FindCcuInfo(ctok, m, assemblyRef.Name, lookupOnly=false) with | ResolvedImportedAssembly(importedAssembly) -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) @@ -4075,7 +4075,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti let bytes = assembly.PApplyWithProvider((fun (assembly, provider) -> assembly.GetManifestModuleContents(provider)), m).PUntaint(id, m) let tcConfig = tcConfigP.Get(ctok) let ilModule, ilAssemblyRefs = - let opts : ILReaderOptions = + let opts: ILReaderOptions = { ilGlobals = g.ilg reduceMemoryUsage = tcConfig.reduceMemoryUsage pdbDirPath = None @@ -4094,7 +4094,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti ILScopeRef = ilScopeRef ILAssemblyRefs = ilAssemblyRefs } tcImports.RegisterDll(dllinfo) - let ccuData : CcuData = + let ccuData: CcuData = { IsFSharp=false UsesFSharp20PlusQuotations=false InvalidateEvent=(new Event<_>()).Publish @@ -4246,11 +4246,11 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti #if !NO_EXTENSIONTYPING member private tcImports.InjectProvidedNamespaceOrTypeIntoEntity (typeProviderEnvironment, - tcConfig:TcConfig, - m, entity:Entity, + tcConfig: TcConfig, + m, entity: Entity, injectedNamspace, remainingNamespace, provider, - st:Tainted option) = + st: Tainted option) = match remainingNamespace with | next::rest -> // Inject the namespace entity @@ -4292,11 +4292,11 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti | _ -> failwith "Unexpected representation in namespace entity referred to by a type provider" member tcImports.ImportTypeProviderExtensions - (ctok, tcConfig:TcConfig, + (ctok, tcConfig: TcConfig, fileNameOfRuntimeAssembly, ilScopeRefOfRuntimeAssembly, - runtimeAssemblyAttributes:ILAttribute list, - entityToInjectInto, invalidateCcu:Event<_>, m) = + runtimeAssemblyAttributes: ILAttribute list, + entityToInjectInto, invalidateCcu: Event<_>, m) = let startingErrorCount = CompileThreadStatic.ErrorLogger.ErrorCount @@ -4406,7 +4406,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti #endif /// Query information about types available in target system runtime library - member tcImports.SystemRuntimeContainsType (typeName : string) : bool = + member tcImports.SystemRuntimeContainsType (typeName: string) : bool = let ns, typeName = IL.splitILTypeName typeName let tcGlobals = tcImports.GetTcGlobals() tcGlobals.TryFindSysTyconRef ns typeName |> Option.isSome @@ -4418,7 +4418,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti // Compact Framework binaries must use this. However it is not // clear when else it is required, e.g. for Mono. - member tcImports.PrepareToImportReferencedILAssembly (ctok, m, filename, dllinfo:ImportedBinary) = + member tcImports.PrepareToImportReferencedILAssembly (ctok, m, filename, dllinfo: ImportedBinary) = CheckDisposed() let tcConfig = tcConfigP.Get(ctok) assert dllinfo.RawMetadata.TryGetILModuleDef().IsSome @@ -4455,7 +4455,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti [ResolvedImportedAssembly(ccuinfo)] phase2 - member tcImports.PrepareToImportReferencedFSharpAssembly (ctok, m, filename, dllinfo:ImportedBinary) = + member tcImports.PrepareToImportReferencedFSharpAssembly (ctok, m, filename, dllinfo: ImportedBinary) = CheckDisposed() #if !NO_EXTENSIONTYPING let tcConfig = tcConfigP.Get(ctok) @@ -4474,7 +4474,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti let optDatas = Map.ofList optDataReaders - let minfo : PickledCcuInfo = data.RawData + let minfo: PickledCcuInfo = data.RawData let mspec = minfo.mspec #if !NO_EXTENSIONTYPING @@ -4482,7 +4482,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti #endif let codeDir = minfo.compileTimeWorkingDir - let ccuData : CcuData = + let ccuData: CcuData = { ILScopeRef=ilScopeRef Stamp = newStamp() FileName = Some filename @@ -4549,7 +4549,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti // NOTE: When used in the Language Service this can cause the transitive checking of projects. Hence it must be cancellable. - member tcImports.RegisterAndPrepareToImportReferencedDll (ctok, r:AssemblyResolution) : Cancellable<_ * (unit -> AvailableImportedAssembly list)> = + member tcImports.RegisterAndPrepareToImportReferencedDll (ctok, r: AssemblyResolution) : Cancellable<_ * (unit -> AvailableImportedAssembly list)> = cancellable { CheckDisposed() let m = r.originalReference.Range @@ -4603,7 +4603,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti } // NOTE: When used in the Language Service this can cause the transitive checking of projects. Hence it must be cancellable. - member tcImports.RegisterAndImportReferencedAssemblies (ctok, nms:AssemblyResolution list) = + member tcImports.RegisterAndImportReferencedAssemblies (ctok, nms: AssemblyResolution list) = cancellable { CheckDisposed() @@ -4647,7 +4647,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti else tryFile (assemblyName + ".exe") |> ignore #if !NO_EXTENSIONTYPING - member tcImports.TryFindProviderGeneratedAssemblyByName(ctok, assemblyName:string) : System.Reflection.Assembly option = + member tcImports.TryFindProviderGeneratedAssemblyByName(ctok, assemblyName: string) : System.Reflection.Assembly option = // The assembly may not be in the resolutions, but may be in the load set including EST injected assemblies match tcImports.TryFindDllInfo (ctok, range0, assemblyName, lookupOnly=true) with | Some res -> @@ -4661,10 +4661,10 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti resolutions.TryFindBySimpleAssemblyName (ctok, simpleAssemName) |> Option.map (fun r -> r.resolvedPath) /// This doesn't need to be cancellable, it is only used by F# Interactive - member tcImports.TryFindExistingFullyQualifiedPathByExactAssemblyRef(ctok, assemblyRef:ILAssemblyRef) : string option = + member tcImports.TryFindExistingFullyQualifiedPathByExactAssemblyRef(ctok, assemblyRef: ILAssemblyRef) : string option = resolutions.TryFindByExactILAssemblyRef (ctok, assemblyRef) |> Option.map (fun r -> r.resolvedPath) - member tcImports.TryResolveAssemblyReference(ctok, assemblyReference:AssemblyReference, mode:ResolveAssemblyReferenceMode) : OperationResult = + member tcImports.TryResolveAssemblyReference(ctok, assemblyReference: AssemblyReference, mode: ResolveAssemblyReferenceMode) : OperationResult = let tcConfig = tcConfigP.Get(ctok) // First try to lookup via the original reference text. match resolutions.TryFindByOriginalReference assemblyReference with @@ -4720,7 +4720,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti // // If this ever changes then callers may need to begin disposing the TcImports (though remember, not before all derived // non-framework TcImports built related to this framework TcImports are disposed). - static member BuildFrameworkTcImports (ctok, tcConfigP:TcConfigProvider, frameworkDLLs, nonFrameworkDLLs) = + static member BuildFrameworkTcImports (ctok, tcConfigP: TcConfigProvider, frameworkDLLs, nonFrameworkDLLs) = cancellable { let tcConfig = tcConfigP.Get(ctok) @@ -4807,7 +4807,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti member tcImports.ReportUnresolvedAssemblyReferences(knownUnresolved) = // Report that an assembly was not resolved. - let reportAssemblyNotResolved(file, originalReferences:AssemblyReference list) = + let reportAssemblyNotResolved(file, originalReferences: AssemblyReference list) = originalReferences |> List.iter(fun originalReference -> errorR(AssemblyNotResolved(file, originalReference.Range))) knownUnresolved |> List.map (function UnresolvedAssemblyReference(file, originalReferences) -> file, originalReferences) @@ -4815,7 +4815,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti // Note: This returns a TcImports object. TcImports are disposable - the caller owns the returned TcImports object // and when hosted in Visual Studio or another long-running process must dispose this object. - static member BuildNonFrameworkTcImports (ctok, tcConfigP:TcConfigProvider, tcGlobals:TcGlobals, baseTcImports, nonFrameworkReferences, knownUnresolved) = + static member BuildNonFrameworkTcImports (ctok, tcConfigP: TcConfigProvider, tcGlobals: TcGlobals, baseTcImports, nonFrameworkReferences, knownUnresolved) = cancellable { let tcConfig = tcConfigP.Get(ctok) let tcResolutions = TcAssemblyResolutions.BuildFromPriorResolutions(ctok, tcConfig, nonFrameworkReferences, knownUnresolved) @@ -4830,7 +4830,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti // and if hosted in Visual Studio or another long-running process must dispose this object. However this // function is currently only used from fsi.exe. If we move to a long-running hosted evaluation service API then // we should start disposing these objects. - static member BuildTcImports(ctok, tcConfigP:TcConfigProvider) = + static member BuildTcImports(ctok, tcConfigP: TcConfigProvider) = cancellable { let tcConfig = tcConfigP.Get(ctok) //let foundationalTcImports, tcGlobals = TcImports.BuildFoundationalTcImports(tcConfigP) @@ -4855,7 +4855,7 @@ type TcImports(tcConfigP:TcConfigProvider, initialResolutions:TcAssemblyResoluti /// Process #r in F# Interactive. /// Adds the reference to the tcImports and add the ccu to the type checking environment. -let RequireDLL (ctok, tcImports:TcImports, tcEnv, thisAssemblyName, m, file) = +let RequireDLL (ctok, tcImports: TcImports, tcEnv, thisAssemblyName, m, file) = let resolutions = CommitOperationResult(tcImports.TryResolveAssemblyReference(ctok, AssemblyReference(m, file, None), ResolveAssemblyReferenceMode.ReportErrors)) let dllinfos, ccuinfos = tcImports.RegisterAndImportReferencedAssemblies(ctok, resolutions) |> Cancellable.runWithoutCancellation @@ -4875,7 +4875,7 @@ let ProcessMetaCommandsFromInput (nowarnF: 'state -> range * string -> 'state, dllRequireF: 'state -> range * string -> 'state, loadSourceF: 'state -> range * string -> unit) - (tcConfig:TcConfigBuilder, inp, pathOfMetaCommandSource, state0) = + (tcConfig: TcConfigBuilder, inp, pathOfMetaCommandSource, state0) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse @@ -4981,7 +4981,7 @@ let ProcessMetaCommandsFromInput let state = List.fold ProcessMetaCommandsFromModuleImpl state impls state -let ApplyNoWarnsToTcConfig (tcConfig:TcConfig, inp:ParsedInput, pathOfMetaCommandSource) = +let ApplyNoWarnsToTcConfig (tcConfig: TcConfig, inp: ParsedInput, pathOfMetaCommandSource) = // Clone let tcConfigB = tcConfig.CloneOfOriginalBuilder let addNoWarn = fun () (m, s) -> tcConfigB.TurnWarningOff(m, s) @@ -4990,7 +4990,7 @@ let ApplyNoWarnsToTcConfig (tcConfig:TcConfig, inp:ParsedInput, pathOfMetaComman ProcessMetaCommandsFromInput (addNoWarn, addReferencedAssemblyByPath, addLoadedSource) (tcConfigB, inp, pathOfMetaCommandSource, ()) TcConfig.Create(tcConfigB, validate=false) -let ApplyMetaCommandsFromInputToTcConfig (tcConfig:TcConfig, inp:ParsedInput, pathOfMetaCommandSource) = +let ApplyMetaCommandsFromInputToTcConfig (tcConfig: TcConfig, inp: ParsedInput, pathOfMetaCommandSource) = // Clone let tcConfigB = tcConfig.CloneOfOriginalBuilder let getWarningNumber = fun () _ -> () @@ -5003,7 +5003,7 @@ let ApplyMetaCommandsFromInputToTcConfig (tcConfig:TcConfig, inp:ParsedInput, pa // Compute the load closure of a set of script files //-------------------------------------------------------------------------- -let GetAssemblyResolutionInformation(ctok, tcConfig : TcConfig) = +let GetAssemblyResolutionInformation(ctok, tcConfig: TcConfig) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter let assemblyList = TcAssemblyResolutions.GetAllDllReferences(tcConfig) let resolutions = TcAssemblyResolutions.ResolveAssemblyReferences (ctok, tcConfig, assemblyList, []) @@ -5024,7 +5024,7 @@ type LoadClosure = /// The resolved references along with the ranges of the #r positions in each file. References: (string * AssemblyResolution list) list /// The list of references that were not resolved during load closure. These may still be extension references. - UnresolvedReferences : UnresolvedAssemblyReference list + UnresolvedReferences: UnresolvedAssemblyReference list /// The list of all sources in the closure with inputs when available Inputs: LoadClosureInput list /// The #load, including those that didn't resolve @@ -5032,11 +5032,11 @@ type LoadClosure = /// The #nowarns NoWarns: (string * range list) list /// Diagnostics seen while processing resolutions - ResolutionDiagnostics : (PhasedDiagnostic * bool) list + ResolutionDiagnostics: (PhasedDiagnostic * bool) list /// Diagnostics seen while parsing root of closure - AllRootFileDiagnostics : (PhasedDiagnostic * bool) list + AllRootFileDiagnostics: (PhasedDiagnostic * bool) list /// Diagnostics seen while processing the compiler options implied root of closure - LoadClosureRootFileDiagnostics : (PhasedDiagnostic * bool) list } + LoadClosureRootFileDiagnostics: (PhasedDiagnostic * bool) list } [] @@ -5066,8 +5066,8 @@ module private ScriptPreprocessClosure = /// Parse a script from source. let ParseScriptText - (filename:string, source:string, tcConfig:TcConfig, codeContext, - lexResourceManager:Lexhelp.LexResourceManager, errorLogger:ErrorLogger) = + (filename: string, source: string, tcConfig: TcConfig, codeContext, + lexResourceManager: Lexhelp.LexResourceManager, errorLogger: ErrorLogger) = // fsc.exe -- COMPILED\!INTERACTIVE // fsi.exe -- !COMPILED\INTERACTIVE @@ -5087,7 +5087,7 @@ module private ScriptPreprocessClosure = /// Create a TcConfig for load closure starting from a single .fsx file let CreateScriptTextTcConfig (legacyReferenceResolver, defaultFSharpBinariesDir, - filename:string, codeContext, + filename: string, codeContext, useSimpleResolution, useFsiAuxLib, basicReferences, applyCommandLineArgs, assumeDotNetFramework, tryGetMetadataSnapshot, @@ -5136,7 +5136,7 @@ module private ScriptPreprocessClosure = [] let ApplyMetaCommandsFromInputToTcConfigAndGatherNoWarn - (tcConfig:TcConfig, inp:ParsedInput, pathOfMetaCommandSource) = + (tcConfig: TcConfig, inp: ParsedInput, pathOfMetaCommandSource) = let tcConfigB = tcConfig.CloneOfOriginalBuilder let nowarns = ref [] @@ -5157,8 +5157,8 @@ module private ScriptPreprocessClosure = TcConfig.Create(tcConfigB, validate=false), nowarns let FindClosureFiles - (closureSources, tcConfig:TcConfig, codeContext, - lexResourceManager:Lexhelp.LexResourceManager) = + (closureSources, tcConfig: TcConfig, codeContext, + lexResourceManager: Lexhelp.LexResourceManager) = let tcConfig = ref tcConfig @@ -5211,7 +5211,7 @@ module private ScriptPreprocessClosure = closureSources |> List.collect loop, !tcConfig /// Reduce the full directive closure into LoadClosure - let GetLoadClosure(ctok, rootFilename, closureFiles, tcConfig:TcConfig, codeContext) = + let GetLoadClosure(ctok, rootFilename, closureFiles, tcConfig: TcConfig, codeContext) = // Mark the last file as isLastCompiland. let closureFiles = @@ -5273,7 +5273,7 @@ module private ScriptPreprocessClosure = // Filter out non-root errors and warnings let allRootDiagnostics = allRootDiagnostics |> List.filter (fst >> isRootRange) - let result : LoadClosure = + let result: LoadClosure = { SourceFiles = List.groupBy fst sourceFiles |> List.map (map2Of2 (List.map snd)) References = List.groupBy fst references |> List.map (map2Of2 (List.map snd)) UnresolvedReferences = unresolvedReferences @@ -5291,7 +5291,7 @@ module private ScriptPreprocessClosure = (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, filename, source, codeContext, useSimpleResolution, useFsiAuxLib, - lexResourceManager:Lexhelp.LexResourceManager, + lexResourceManager: Lexhelp.LexResourceManager, applyCommmandLineArgs, assumeDotNetFramework, tryGetMetadataSnapshot, reduceMemoryUsage) = @@ -5322,10 +5322,10 @@ module private ScriptPreprocessClosure = /// Given source filename, find the full load closure /// Used from fsi.fs and fsc.fs, for #load and command line let GetFullClosureOfScriptFiles - (ctok, tcConfig:TcConfig, + (ctok, tcConfig: TcConfig, files:(string*range) list, codeContext, - lexResourceManager:Lexhelp.LexResourceManager) = + lexResourceManager: Lexhelp.LexResourceManager) = let mainFile = fst (List.last files) let closureSources = files |> List.collect (fun (filename, m) -> ClosureSourceOfFilename(filename, m, tcConfig.inputCodePage, true)) @@ -5336,8 +5336,8 @@ type LoadClosure with /// Analyze a script text and find the closure of its references. static member ComputeClosureOfScriptText (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, - filename:string, source:string, codeContext, useSimpleResolution:bool, - useFsiAuxLib, lexResourceManager:Lexhelp.LexResourceManager, + filename: string, source: string, codeContext, useSimpleResolution: bool, + useFsiAuxLib, lexResourceManager: Lexhelp.LexResourceManager, applyCommmandLineArgs, assumeDotNetFramework, tryGetMetadataSnapshot, reduceMemoryUsage) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse @@ -5348,8 +5348,8 @@ type LoadClosure with /// Analyze a set of script files and find the closure of their references. static member ComputeClosureOfScriptFiles - (ctok, tcConfig:TcConfig, files:(string*range) list, codeContext, - lexResourceManager:Lexhelp.LexResourceManager) = + (ctok, tcConfig: TcConfig, files:(string*range) list, codeContext, + lexResourceManager: Lexhelp.LexResourceManager) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse ScriptPreprocessClosure.GetFullClosureOfScriptFiles (ctok, tcConfig, files, codeContext, lexResourceManager) @@ -5361,7 +5361,7 @@ type LoadClosure with //-------------------------------------------------------------------------- /// Build the initial type checking environment -let GetInitialTcEnv (thisAssemblyName:string, initm:range, tcConfig:TcConfig, tcImports:TcImports, tcGlobals) = +let GetInitialTcEnv (thisAssemblyName: string, initm: range, tcConfig: TcConfig, tcImports: TcImports, tcGlobals) = let initm = initm.StartRange let ccus = @@ -5382,7 +5382,7 @@ let GetInitialTcEnv (thisAssemblyName:string, initm:range, tcConfig:TcConfig, tc // Fault injection /// Inject faults into checking -let CheckSimulateException(tcConfig:TcConfig) = +let CheckSimulateException(tcConfig: TcConfig) = match tcConfig.simulateException with | Some("tc-oom") -> raise(System.OutOfMemoryException()) | Some("tc-an") -> raise(System.ArgumentNullException("simulated")) @@ -5415,7 +5415,7 @@ let CheckSimulateException(tcConfig:TcConfig) = type RootSigs = Zmap type RootImpls = Zset -let qnameOrder = Order.orderBy (fun (q:QualifiedNameOfFile) -> q.Text) +let qnameOrder = Order.orderBy (fun (q: QualifiedNameOfFile) -> q.Text) type TcState = { tcsCcu: CcuThunk @@ -5450,13 +5450,13 @@ type TcState = /// Create the initial type checking state for compiling an assembly -let GetInitialTcState(m, ccuName, tcConfig:TcConfig, tcGlobals, tcImports:TcImports, niceNameGen, tcEnv0) = +let GetInitialTcState(m, ccuName, tcConfig: TcConfig, tcGlobals, tcImports: TcImports, niceNameGen, tcEnv0) = ignore tcImports // Create a ccu to hold all the results of compilation let ccuType = NewCcuContents ILScopeRef.Local m ccuName (NewEmptyModuleOrNamespaceType Namespace) - let ccuData : CcuData = + let ccuData: CcuData = { IsFSharp=true UsesFSharp20PlusQuotations=false #if !NO_EXTENSIONTYPING @@ -5493,7 +5493,7 @@ let GetInitialTcState(m, ccuName, tcConfig:TcConfig, tcGlobals, tcImports:TcImpo /// Typecheck a single file (or interactive entry into F# Interactive) -let TypeCheckOneInputEventually (checkForErrors, tcConfig:TcConfig, tcImports:TcImports, tcGlobals, prefixPathOpt, tcSink, tcState: TcState, inp: ParsedInput) = +let TypeCheckOneInputEventually (checkForErrors, tcConfig: TcConfig, tcImports: TcImports, tcGlobals, prefixPathOpt, tcSink, tcState: TcState, inp: ParsedInput) = eventually { try diff --git a/src/fsharp/CompileOptions.fs b/src/fsharp/CompileOptions.fs index 9a441c51fd0..eb3c6364acf 100644 --- a/src/fsharp/CompileOptions.fs +++ b/src/fsharp/CompileOptions.fs @@ -25,7 +25,7 @@ module Attributes = open System.Runtime.CompilerServices //[] - [] + [] do() //---------------------------------------------------------------------------- @@ -65,15 +65,15 @@ and CompilerOptionBlock = PublicOptions of string * CompilerOption list | Priv let GetOptionsOfBlock block = match block with - | PublicOptions (_,opts) -> opts + | PublicOptions (_, opts) -> opts | PrivateOptions opts -> opts let FilterCompilerOptionBlock pred block = match block with - | PublicOptions(heading,opts) -> PublicOptions(heading,List.filter pred opts) + | PublicOptions(heading, opts) -> PublicOptions(heading, List.filter pred opts) | PrivateOptions(opts) -> PrivateOptions(List.filter pred opts) -let compilerOptionUsage (CompilerOption(s,tag,spec,_,_)) = +let compilerOptionUsage (CompilerOption(s, tag, spec, _, _)) = let s = if s="--" then "" else s (* s="flag" for "--flag" options. s="--" for "--" option. Adjust printing here for "--" case. *) match spec with | (OptionUnit _ | OptionSet _ | OptionClear _ | OptionHelp _) -> sprintf "--%s" s @@ -88,7 +88,7 @@ let compilerOptionUsage (CompilerOption(s,tag,spec,_,_)) = | OptionRest _ -> sprintf "--%s ..." s | OptionGeneral _ -> if tag="" then sprintf "%s" s else sprintf "%s:%s" s tag (* still being decided *) -let PrintCompilerOption (CompilerOption(_s,_tag,_spec,_,help) as compilerOption) = +let PrintCompilerOption (CompilerOption(_s, _tag, _spec, _, help) as compilerOption) = let flagWidth = 42 // fixed width for printing of flags, e.g. --debug:{full|pdbonly|portable|embedded} let defaultLineWidth = 80 // the fallback width let lineWidth = @@ -116,7 +116,7 @@ let PrintCompilerOption (CompilerOption(_s,_tag,_spec,_,help) as compilerOption) let _finalColumn = Array.fold printWord flagWidth words printfn "" (* newline *) -let PrintPublicOptions (heading,opts) = +let PrintPublicOptions (heading, opts) = if not (isNil opts) then printfn "" printfn "" @@ -125,13 +125,13 @@ let PrintPublicOptions (heading,opts) = let PrintCompilerOptionBlocks blocks = let equals x y = x=y - let publicBlocks = List.choose (function PrivateOptions _ -> None | PublicOptions (heading,opts) -> Some (heading,opts)) blocks + let publicBlocks = List.choose (function PrivateOptions _ -> None | PublicOptions (heading, opts) -> Some (heading, opts)) blocks let consider doneHeadings (heading, _opts) = if Set.contains heading doneHeadings then doneHeadings else let headingOptions = List.filter (fst >> equals heading) publicBlocks |> List.collect snd - PrintPublicOptions (heading,headingOptions) + PrintPublicOptions (heading, headingOptions) Set.add heading doneHeadings List.fold consider Set.empty publicBlocks |> ignore> @@ -155,7 +155,7 @@ let dumpCompilerOption prefix (CompilerOption(str, _, spec, _, _)) = | OptionGeneral _ -> printf "OptionGeneral" printf "\n" let dumpCompilerOptionBlock = function - | PublicOptions (heading,opts) -> List.iter (dumpCompilerOption heading) opts + | PublicOptions (heading, opts) -> List.iter (dumpCompilerOption heading) opts | PrivateOptions opts -> List.iter (dumpCompilerOption "NoSection") opts let DumpCompilerOptionBlocks blocks = List.iter dumpCompilerOptionBlock blocks @@ -169,7 +169,7 @@ module ResponseFile = | CompilerOptionSpec of string | Comment of string - let parseFile path : Choice = + let parseFile path: Choice = let parseLine (l: string) = match l with | s when String.IsNullOrWhiteSpace(s) -> None @@ -188,13 +188,13 @@ module ResponseFile = Choice2Of2 e -let ParseCompilerOptions (collectOtherArgument : string -> unit, blocks: CompilerOptionBlock list, args) = +let ParseCompilerOptions (collectOtherArgument: string -> unit, blocks: CompilerOptionBlock list, args) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Parameter let specs = List.collect GetOptionsOfBlock blocks // returns a tuple - the option token, the option argument string - let parseOption (s : string) = + let parseOption (s: string) = // grab the option token let opts = s.Split([|':'|]) let mutable opt = opts.[0] @@ -215,22 +215,22 @@ let ParseCompilerOptions (collectOtherArgument : string -> unit, blocks: Compile opt <- "" // get the argument string - let optArgs = if opts.Length > 1 then String.Join(":",opts.[1 ..]) else "" + let optArgs = if opts.Length > 1 then String.Join(":", opts.[1 ..]) else "" opt, optArgs - let getOptionArg compilerOption (argString : string) = + let getOptionArg compilerOption (argString: string) = if argString = "" then - errorR(Error(FSComp.SR.buildOptionRequiresParameter(compilerOptionUsage compilerOption),rangeCmdArgs)) + errorR(Error(FSComp.SR.buildOptionRequiresParameter(compilerOptionUsage compilerOption), rangeCmdArgs)) argString - let getOptionArgList compilerOption (argString : string) = + let getOptionArgList compilerOption (argString: string) = if argString = "" then - errorR(Error(FSComp.SR.buildOptionRequiresParameter(compilerOptionUsage compilerOption),rangeCmdArgs)) + errorR(Error(FSComp.SR.buildOptionRequiresParameter(compilerOptionUsage compilerOption), rangeCmdArgs)) [] else argString.Split([|',';';'|]) |> List.ofArray - let getSwitchOpt (opt : string) = + let getSwitchOpt (opt: string) = // if opt is a switch, strip the '+' or '-' if opt <> "--" && opt.Length > 1 && (opt.EndsWithOrdinal("+") || opt.EndsWithOrdinal("-")) then opt.[0 .. opt.Length - 2] @@ -254,15 +254,15 @@ let ParseCompilerOptions (collectOtherArgument : string -> unit, blocks: Compile match fullpath with | None -> - errorR(Error(FSComp.SR.optsResponseFileNameInvalid(rsp),rangeCmdArgs)) + errorR(Error(FSComp.SR.optsResponseFileNameInvalid(rsp), rangeCmdArgs)) [] | Some(path) when not (FileSystem.SafeExists path) -> - errorR(Error(FSComp.SR.optsResponseFileNotFound(rsp, path),rangeCmdArgs)) + errorR(Error(FSComp.SR.optsResponseFileNotFound(rsp, path), rangeCmdArgs)) [] | Some path -> match ResponseFile.parseFile path with | Choice2Of2 _ -> - errorR(Error(FSComp.SR.optsInvalidResponseFile(rsp, path),rangeCmdArgs)) + errorR(Error(FSComp.SR.optsInvalidResponseFile(rsp, path), rangeCmdArgs)) [] | Choice1Of2 rspData -> let onlyOptions l = @@ -310,7 +310,7 @@ let ParseCompilerOptions (collectOtherArgument : string -> unit, blocks: Compile let oa = getOptionArg compilerOption argString if oa <> "" then f (try int32 (oa) with _ -> - errorR(Error(FSComp.SR.buildArgInvalidInt(getOptionArg compilerOption argString),rangeCmdArgs)); 0) + errorR(Error(FSComp.SR.buildArgInvalidInt(getOptionArg compilerOption argString), rangeCmdArgs)); 0) t | (CompilerOption(s, _, OptionFloat f, d, _) as compilerOption :: _) when optToken = s -> reportDeprecatedOption d @@ -326,14 +326,14 @@ let ParseCompilerOptions (collectOtherArgument : string -> unit, blocks: Compile reportDeprecatedOption d let al = getOptionArgList compilerOption argString if al <> [] then - List.iter (fun i -> f (try int32 i with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt(i),rangeCmdArgs)); 0)) al + List.iter (fun i -> f (try int32 i with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt(i), rangeCmdArgs)); 0)) al t | (CompilerOption(s, _, OptionIntListSwitch f, d, _) as compilerOption :: _) when getSwitchOpt(optToken) = s -> reportDeprecatedOption d let al = getOptionArgList compilerOption argString if al <> [] then let switch = getSwitch(opt) - List.iter (fun i -> f (try int32 i with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt(i),rangeCmdArgs)); 0) switch) al + List.iter (fun i -> f (try int32 i with _ -> errorR(Error(FSComp.SR.buildArgInvalidInt(i), rangeCmdArgs)); 0) switch) al t // here | (CompilerOption(s, _, OptionStringList f, d, _) as compilerOption :: _) when optToken = s -> @@ -349,7 +349,7 @@ let ParseCompilerOptions (collectOtherArgument : string -> unit, blocks: Compile let switch = getSwitch(opt) List.iter (fun s -> f s switch) (getOptionArgList compilerOption argString) t - | (CompilerOption(_, _, OptionGeneral (pred,exec), d, _) :: _) when pred args -> + | (CompilerOption(_, _, OptionGeneral (pred, exec), d, _) :: _) when pred args -> reportDeprecatedOption d let rest = exec args in rest // arguments taken, rest remaining | (_ :: more) -> attempt more @@ -358,7 +358,7 @@ let ParseCompilerOptions (collectOtherArgument : string -> unit, blocks: Compile then // want the whole opt token - delimiter and all let unrecOpt = (opt.Split([|':'|]).[0]) - errorR(Error(FSComp.SR.buildUnrecognizedOption(unrecOpt),rangeCmdArgs)) + errorR(Error(FSComp.SR.buildUnrecognizedOption(unrecOpt), rangeCmdArgs)) t else (collectOtherArgument opt; t) @@ -380,7 +380,7 @@ let setFlag r n = | 1 -> r true | _ -> raise (Failure "expected 0/1") -let SetOptimizeOff(tcConfigB : TcConfigBuilder) = +let SetOptimizeOff(tcConfigB: TcConfigBuilder) = tcConfigB.optSettings <- { tcConfigB.optSettings with jitOptUser = Some false } tcConfigB.optSettings <- { tcConfigB.optSettings with localOptUser = Some false } tcConfigB.optSettings <- { tcConfigB.optSettings with crossModuleOptUser = Some false } @@ -389,7 +389,7 @@ let SetOptimizeOff(tcConfigB : TcConfigBuilder) = tcConfigB.doTLR <- false tcConfigB.doFinalSimplify <- false -let SetOptimizeOn(tcConfigB : TcConfigBuilder) = +let SetOptimizeOn(tcConfigB: TcConfigBuilder) = tcConfigB.optSettings <- { tcConfigB.optSettings with jitOptUser = Some true } tcConfigB.optSettings <- { tcConfigB.optSettings with localOptUser = Some true } tcConfigB.optSettings <- { tcConfigB.optSettings with crossModuleOptUser = Some true } @@ -398,34 +398,34 @@ let SetOptimizeOn(tcConfigB : TcConfigBuilder) = tcConfigB.doTLR <- true tcConfigB.doFinalSimplify <- true -let SetOptimizeSwitch (tcConfigB : TcConfigBuilder) switch = +let SetOptimizeSwitch (tcConfigB: TcConfigBuilder) switch = if (switch = OptionSwitch.On) then SetOptimizeOn(tcConfigB) else SetOptimizeOff(tcConfigB) -let SetTailcallSwitch (tcConfigB : TcConfigBuilder) switch = +let SetTailcallSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.emitTailcalls <- (switch = OptionSwitch.On) -let SetDeterministicSwitch (tcConfigB : TcConfigBuilder) switch = +let SetDeterministicSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.deterministic <- (switch = OptionSwitch.On) -let jitoptimizeSwitch (tcConfigB : TcConfigBuilder) switch = +let jitoptimizeSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.optSettings <- { tcConfigB.optSettings with jitOptUser = Some (switch = OptionSwitch.On) } -let localoptimizeSwitch (tcConfigB : TcConfigBuilder) switch = +let localoptimizeSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.optSettings <- { tcConfigB.optSettings with localOptUser = Some (switch = OptionSwitch.On) } -let crossOptimizeSwitch (tcConfigB : TcConfigBuilder) switch = +let crossOptimizeSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.optSettings <- { tcConfigB.optSettings with crossModuleOptUser = Some (switch = OptionSwitch.On) } -let splittingSwitch (tcConfigB : TcConfigBuilder) switch = +let splittingSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.optSettings <- { tcConfigB.optSettings with abstractBigTargets = switch = OptionSwitch.On } -let callVirtSwitch (tcConfigB : TcConfigBuilder) switch = +let callVirtSwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.alwaysCallVirt <- switch = OptionSwitch.On -let useHighEntropyVASwitch (tcConfigB : TcConfigBuilder) switch = +let useHighEntropyVASwitch (tcConfigB: TcConfigBuilder) switch = tcConfigB.useHighEntropyVA <- switch = OptionSwitch.On -let subSystemVersionSwitch (tcConfigB : TcConfigBuilder) (text : string) = +let subSystemVersionSwitch (tcConfigB: TcConfigBuilder) (text: string) = let fail() = error(Error(FSComp.SR.optsInvalidSubSystemVersion(text), rangeCmdArgs)) // per spec for 357994: Validate input string, should be two positive integers x.y when x>=4 and y>=0 and both <= 65535 @@ -444,15 +444,15 @@ let subSystemVersionSwitch (tcConfigB : TcConfigBuilder) (text : string) = let (++) x s = x @ [s] -let SetTarget (tcConfigB : TcConfigBuilder)(s : string) = +let SetTarget (tcConfigB: TcConfigBuilder)(s: string) = match s.ToLowerInvariant() with | "exe" -> tcConfigB.target <- CompilerTarget.ConsoleExe | "winexe" -> tcConfigB.target <- CompilerTarget.WinExe | "library" -> tcConfigB.target <- CompilerTarget.Dll | "module" -> tcConfigB.target <- CompilerTarget.Module - | _ -> error(Error(FSComp.SR.optsUnrecognizedTarget(s),rangeCmdArgs)) + | _ -> error(Error(FSComp.SR.optsUnrecognizedTarget(s), rangeCmdArgs)) -let SetDebugSwitch (tcConfigB : TcConfigBuilder) (dtype : string option) (s : OptionSwitch) = +let SetDebugSwitch (tcConfigB: TcConfigBuilder) (dtype: string option) (s: OptionSwitch) = match dtype with | Some(s) -> match s with @@ -487,7 +487,7 @@ let SetDebugSwitch (tcConfigB : TcConfigBuilder) (dtype : string option) (s : Op | None -> tcConfigB.portablePDB <- false; tcConfigB.embeddedPDB <- false; tcConfigB.jitTracking <- s = OptionSwitch.On tcConfigB.debuginfo <- s = OptionSwitch.On -let SetEmbedAllSourceSwitch (tcConfigB : TcConfigBuilder) switch = +let SetEmbedAllSourceSwitch (tcConfigB: TcConfigBuilder) switch = if (switch = OptionSwitch.On) then tcConfigB.embedAllSource <- true else tcConfigB.embedAllSource <- false let setOutFileName tcConfigB s = @@ -545,12 +545,12 @@ let PrintOptionInfo (tcConfigB:TcConfigBuilder) = //------------------------- let inputFileFlagsBoth (tcConfigB : TcConfigBuilder) = - [ CompilerOption("reference", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup,s)), None, + [ CompilerOption("reference", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup, s)), None, Some (FSComp.SR.optsReference()) ) ] -let referenceFlagAbbrev (tcConfigB : TcConfigBuilder) = - CompilerOption("r", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup,s)), None, +let referenceFlagAbbrev (tcConfigB: TcConfigBuilder) = + CompilerOption("r", tagFile, OptionString (fun s -> tcConfigB.AddReferencedAssemblyByPath (rangeStartup, s)), None, Some(FSComp.SR.optsShortFormOf("--reference")) ) let inputFileFlagsFsi tcConfigB = inputFileFlagsBoth tcConfigB @@ -566,7 +566,7 @@ let errorsAndWarningsFlags (tcConfigB: TcConfigBuilder) = try Some (int32 (trimFS s)) with _ -> - errorR(Error(FSComp.SR.buildArgInvalidInt(s),rangeCmdArgs)) + errorR(Error(FSComp.SR.buildArgInvalidInt(s), rangeCmdArgs)) None [ CompilerOption("warnaserror", tagNone, OptionSwitch(fun switch -> @@ -609,62 +609,62 @@ let errorsAndWarningsFlags (tcConfigB: TcConfigBuilder) = // OptionBlock: Output files //-------------------------- -let outputFileFlagsFsi (_tcConfigB : TcConfigBuilder) = [] +let outputFileFlagsFsi (_tcConfigB: TcConfigBuilder) = [] -let outputFileFlagsFsc (tcConfigB : TcConfigBuilder) = +let outputFileFlagsFsc (tcConfigB: TcConfigBuilder) = [ CompilerOption - ("out", tagFile, + ("out", tagFile, OptionString (setOutFileName tcConfigB), None, Some (FSComp.SR.optsNameOfOutputFile()) ) CompilerOption - ("target", tagExe, + ("target", tagExe, OptionString (SetTarget tcConfigB), None, Some (FSComp.SR.optsBuildConsole())) CompilerOption - ("target", tagWinExe, + ("target", tagWinExe, OptionString (SetTarget tcConfigB), None, Some (FSComp.SR.optsBuildWindows())) CompilerOption - ("target", tagLibrary, + ("target", tagLibrary, OptionString (SetTarget tcConfigB), None, Some (FSComp.SR.optsBuildLibrary())) CompilerOption - ("target", tagModule, + ("target", tagModule, OptionString (SetTarget tcConfigB), None, Some (FSComp.SR.optsBuildModule())) CompilerOption - ("delaysign", tagNone, + ("delaysign", tagNone, OptionSwitch (fun s -> tcConfigB.delaysign <- (s = OptionSwitch.On)), None, Some (FSComp.SR.optsDelaySign())) CompilerOption - ("publicsign", tagNone, + ("publicsign", tagNone, OptionSwitch (fun s -> tcConfigB.publicsign <- (s = OptionSwitch.On)), None, Some (FSComp.SR.optsPublicSign())) CompilerOption - ("doc", tagFile, + ("doc", tagFile, OptionString (fun s -> tcConfigB.xmlDocOutputFile <- Some s), None, Some (FSComp.SR.optsWriteXml())) CompilerOption - ("keyfile", tagFile, - OptionString (fun s -> tcConfigB.signer <- Some(s)), None, + ("keyfile", tagFile, + OptionString (fun s -> tcConfigB.signer <- Some(s)), None, Some (FSComp.SR.optsStrongKeyFile())) CompilerOption - ("keycontainer", tagString, - OptionString(fun s -> tcConfigB.container <- Some(s)),None, + ("keycontainer", tagString, + OptionString(fun s -> tcConfigB.container <- Some(s)), None, Some(FSComp.SR.optsStrongKeyContainer())) CompilerOption - ("platform", tagString, + ("platform", tagString, OptionString (fun s -> tcConfigB.platform <- match s with @@ -675,27 +675,27 @@ let outputFileFlagsFsc (tcConfigB : TcConfigBuilder) = tcConfigB.prefer32Bit <- true None | "anycpu" -> None - | _ -> error(Error(FSComp.SR.optsUnknownPlatform(s),rangeCmdArgs))), None, + | _ -> error(Error(FSComp.SR.optsUnknownPlatform(s), rangeCmdArgs))), None, Some(FSComp.SR.optsPlatform())) CompilerOption - ("nooptimizationdata", tagNone, + ("nooptimizationdata", tagNone, OptionUnit (fun () -> tcConfigB.onlyEssentialOptimizationData <- true), None, Some (FSComp.SR.optsNoOpt())) CompilerOption - ("nointerfacedata", tagNone, + ("nointerfacedata", tagNone, OptionUnit (fun () -> tcConfigB.noSignatureData <- true), None, Some (FSComp.SR.optsNoInterface())) CompilerOption - ("sig", tagFile, + ("sig", tagFile, OptionString (setSignatureFile tcConfigB), None, Some (FSComp.SR.optsSig())) CompilerOption - ("nocopyfsharpcore", tagNone, - OptionUnit (fun () -> tcConfigB.copyFSharpCore <- CopyFSharpCoreFlag.No), None, + ("nocopyfsharpcore", tagNone, + OptionUnit (fun () -> tcConfigB.copyFSharpCore <- CopyFSharpCoreFlag.No), None, Some (FSComp.SR.optsNoCopyFsharpCore())) ] @@ -703,31 +703,31 @@ let outputFileFlagsFsc (tcConfigB : TcConfigBuilder) = // OptionBlock: Resources //----------------------- -let resourcesFlagsFsi (_tcConfigB : TcConfigBuilder) = [] -let resourcesFlagsFsc (tcConfigB : TcConfigBuilder) = +let resourcesFlagsFsi (_tcConfigB: TcConfigBuilder) = [] +let resourcesFlagsFsc (tcConfigB: TcConfigBuilder) = [ CompilerOption - ("win32res", tagFile, + ("win32res", tagFile, OptionString (fun s -> tcConfigB.win32res <- s), None, Some (FSComp.SR.optsWin32res())) CompilerOption - ("win32manifest", tagFile, + ("win32manifest", tagFile, OptionString (fun s -> tcConfigB.win32manifest <- s), None, Some (FSComp.SR.optsWin32manifest())) CompilerOption - ("nowin32manifest", tagNone, + ("nowin32manifest", tagNone, OptionUnit (fun () -> tcConfigB.includewin32manifest <- false), None, Some (FSComp.SR.optsNowin32manifest())) CompilerOption - ("resource", tagResInfo, + ("resource", tagResInfo, OptionString (fun s -> tcConfigB.AddEmbeddedResource s), None, Some (FSComp.SR.optsResource())) CompilerOption - ("linkresource", tagResInfo, + ("linkresource", tagResInfo, OptionString (fun s -> tcConfigB.linkResources <- tcConfigB.linkResources ++ s), None, Some (FSComp.SR.optsLinkresource())) ] @@ -736,53 +736,53 @@ let resourcesFlagsFsc (tcConfigB : TcConfigBuilder) = // OptionBlock: Code generation //----------------------------- -let codeGenerationFlags isFsi (tcConfigB : TcConfigBuilder) = +let codeGenerationFlags isFsi (tcConfigB: TcConfigBuilder) = let debug = [ CompilerOption - ("debug", tagNone, + ("debug", tagNone, OptionSwitch (SetDebugSwitch tcConfigB None), None, Some (FSComp.SR.optsDebugPM())) CompilerOption - ("debug", tagFullPDBOnlyPortable, + ("debug", tagFullPDBOnlyPortable, OptionString (fun s -> SetDebugSwitch tcConfigB (Some(s)) OptionSwitch.On), None, Some (FSComp.SR.optsDebug(if isFsi then "pdbonly" else "full"))) ] let embed = [ CompilerOption - ("embed", tagNone, - OptionSwitch (SetEmbedAllSourceSwitch tcConfigB) , None, + ("embed", tagNone, + OptionSwitch (SetEmbedAllSourceSwitch tcConfigB) , None, Some (FSComp.SR.optsEmbedAllSource())) CompilerOption - ("embed", tagFileList, - OptionStringList (fun f -> tcConfigB.AddEmbeddedSourceFile f), None, + ("embed", tagFileList, + OptionStringList (fun f -> tcConfigB.AddEmbeddedSourceFile f), None, Some ( FSComp.SR.optsEmbedSource())) CompilerOption - ("sourcelink", tagFile, - OptionString (fun f -> tcConfigB.sourceLink <- f), None, + ("sourcelink", tagFile, + OptionString (fun f -> tcConfigB.sourceLink <- f), None, Some ( FSComp.SR.optsSourceLink())) ] let codegen = [ CompilerOption - ("optimize", tagNone, - OptionSwitch (SetOptimizeSwitch tcConfigB) , None, + ("optimize", tagNone, + OptionSwitch (SetOptimizeSwitch tcConfigB) , None, Some (FSComp.SR.optsOptimize())) CompilerOption - ("tailcalls", tagNone, + ("tailcalls", tagNone, OptionSwitch (SetTailcallSwitch tcConfigB), None, Some (FSComp.SR.optsTailcalls())) CompilerOption - ("deterministic", tagNone, + ("deterministic", tagNone, OptionSwitch (SetDeterministicSwitch tcConfigB), None, Some (FSComp.SR.optsDeterministic())) CompilerOption - ("crossoptimize", tagNone, + ("crossoptimize", tagNone, OptionSwitch (crossOptimizeSwitch tcConfigB), None, Some (FSComp.SR.optsCrossoptimize())) ] @@ -794,22 +794,22 @@ let codeGenerationFlags isFsi (tcConfigB : TcConfigBuilder) = let defineSymbol tcConfigB s = tcConfigB.conditionalCompilationDefines <- s :: tcConfigB.conditionalCompilationDefines -let mlCompatibilityFlag (tcConfigB : TcConfigBuilder) = +let mlCompatibilityFlag (tcConfigB: TcConfigBuilder) = CompilerOption - ("mlcompatibility", tagNone, - OptionUnit (fun () -> tcConfigB.mlCompatibility<-true; tcConfigB.TurnWarningOff(rangeCmdArgs,"62")), None, + ("mlcompatibility", tagNone, + OptionUnit (fun () -> tcConfigB.mlCompatibility<-true; tcConfigB.TurnWarningOff(rangeCmdArgs, "62")), None, Some (FSComp.SR.optsMlcompatibility())) let languageFlags tcConfigB = [ CompilerOption - ("checked", tagNone, - OptionSwitch (fun switch -> tcConfigB.checkOverflow <- (switch = OptionSwitch.On)), None, + ("checked", tagNone, + OptionSwitch (fun switch -> tcConfigB.checkOverflow <- (switch = OptionSwitch.On)), None, Some (FSComp.SR.optsChecked())) CompilerOption - ("define", tagString, - OptionString (defineSymbol tcConfigB), None, + ("define", tagString, + OptionString (defineSymbol tcConfigB), None, Some (FSComp.SR.optsDefine())) mlCompatibilityFlag tcConfigB @@ -819,51 +819,51 @@ let languageFlags tcConfigB = // OptionBlock: Advanced user options //----------------------------------- -let libFlag (tcConfigB : TcConfigBuilder) = +let libFlag (tcConfigB: TcConfigBuilder) = CompilerOption - ("lib", tagDirList, - OptionStringList (fun s -> tcConfigB.AddIncludePath (rangeStartup,s,tcConfigB.implicitIncludeDir)), None, + ("lib", tagDirList, + OptionStringList (fun s -> tcConfigB.AddIncludePath (rangeStartup, s, tcConfigB.implicitIncludeDir)), None, Some (FSComp.SR.optsLib())) -let libFlagAbbrev (tcConfigB : TcConfigBuilder) = +let libFlagAbbrev (tcConfigB: TcConfigBuilder) = CompilerOption - ("I", tagDirList, - OptionStringList (fun s -> tcConfigB.AddIncludePath (rangeStartup,s,tcConfigB.implicitIncludeDir)), None, + ("I", tagDirList, + OptionStringList (fun s -> tcConfigB.AddIncludePath (rangeStartup, s, tcConfigB.implicitIncludeDir)), None, Some (FSComp.SR.optsShortFormOf("--lib"))) -let codePageFlag (tcConfigB : TcConfigBuilder) = +let codePageFlag (tcConfigB: TcConfigBuilder) = CompilerOption - ("codepage", tagInt, + ("codepage", tagInt, OptionInt (fun n -> try System.Text.Encoding.GetEncoding(n) |> ignore with :? System.ArgumentException as err -> - error(Error(FSComp.SR.optsProblemWithCodepage(n,err.Message),rangeCmdArgs)) + error(Error(FSComp.SR.optsProblemWithCodepage(n, err.Message), rangeCmdArgs)) tcConfigB.inputCodePage <- Some(n)), None, Some (FSComp.SR.optsCodepage())) let preferredUiLang (tcConfigB: TcConfigBuilder) = CompilerOption - ("preferreduilang", tagString, - OptionString (fun s -> tcConfigB.preferredUiLang <- Some(s)), None, + ("preferreduilang", tagString, + OptionString (fun s -> tcConfigB.preferredUiLang <- Some(s)), None, Some(FSComp.SR.optsPreferredUiLang())) let utf8OutputFlag (tcConfigB: TcConfigBuilder) = CompilerOption - ("utf8output", tagNone, + ("utf8output", tagNone, OptionUnit (fun () -> tcConfigB.utf8output <- true), None, Some (FSComp.SR.optsUtf8output())) -let fullPathsFlag (tcConfigB : TcConfigBuilder) = +let fullPathsFlag (tcConfigB: TcConfigBuilder) = CompilerOption - ("fullpaths", tagNone, + ("fullpaths", tagNone, OptionUnit (fun () -> tcConfigB.showFullPaths <- true), None, Some (FSComp.SR.optsFullpaths())) -let cliRootFlag (_tcConfigB : TcConfigBuilder) = +let cliRootFlag (_tcConfigB: TcConfigBuilder) = CompilerOption - ("cliroot", tagString, + ("cliroot", tagString, OptionString (fun _ -> ()), Some(DeprecatedCommandLineOptionFull(FSComp.SR.optsClirootDeprecatedMsg(), rangeCmdArgs)), Some(FSComp.SR.optsClirootDescription())) @@ -886,20 +886,20 @@ let advancedFlagsBoth tcConfigB = yield fullPathsFlag tcConfigB yield libFlag tcConfigB yield CompilerOption - ("simpleresolution", - tagNone, - OptionUnit (fun () -> tcConfigB.useSimpleResolution<-true), None, + ("simpleresolution", + tagNone, + OptionUnit (fun () -> tcConfigB.useSimpleResolution<-true), None, Some (FSComp.SR.optsSimpleresolution())) yield CompilerOption - ("targetprofile", tagString, - OptionString (SetTargetProfile tcConfigB), None, + ("targetprofile", tagString, + OptionString (SetTargetProfile tcConfigB), None, Some(FSComp.SR.optsTargetProfile())) ] let noFrameworkFlag isFsc tcConfigB = CompilerOption - ("noframework", tagNone, + ("noframework", tagNone, OptionUnit (fun () -> tcConfigB.framework <- false if isFsc then @@ -916,14 +916,14 @@ let advancedFlagsFsc tcConfigB = advancedFlagsBoth tcConfigB @ [ yield CompilerOption - ("baseaddress", tagAddress, - OptionString (fun s -> tcConfigB.baseAddress <- Some(int32 s)), None, + ("baseaddress", tagAddress, + OptionString (fun s -> tcConfigB.baseAddress <- Some(int32 s)), None, Some (FSComp.SR.optsBaseaddress())) yield noFrameworkFlag true tcConfigB yield CompilerOption - ("standalone", tagNone, + ("standalone", tagNone, OptionUnit (fun _ -> tcConfigB.openDebugInformationForLaterStaticLinking <- true tcConfigB.standalone <- true @@ -931,36 +931,36 @@ let advancedFlagsFsc tcConfigB = Some (FSComp.SR.optsStandalone())) yield CompilerOption - ("staticlink", tagFile, + ("staticlink", tagFile, OptionString (fun s -> tcConfigB.extraStaticLinkRoots <- tcConfigB.extraStaticLinkRoots @ [s]), None, Some (FSComp.SR.optsStaticlink())) #if ENABLE_MONO_SUPPORT if runningOnMono then yield CompilerOption - ("resident", tagFile, + ("resident", tagFile, OptionUnit (fun () -> ()), None, Some (FSComp.SR.optsResident())) #endif yield CompilerOption - ("pdb", tagString, + ("pdb", tagString, OptionString (fun s -> tcConfigB.debugSymbolFile <- Some s), None, Some (FSComp.SR.optsPdb())) yield CompilerOption - ("highentropyva", tagNone, - OptionSwitch (useHighEntropyVASwitch tcConfigB), None, + ("highentropyva", tagNone, + OptionSwitch (useHighEntropyVASwitch tcConfigB), None, Some (FSComp.SR.optsUseHighEntropyVA())) yield CompilerOption - ("subsystemversion", tagString, - OptionString (subSystemVersionSwitch tcConfigB), None, + ("subsystemversion", tagString, + OptionString (subSystemVersionSwitch tcConfigB), None, Some (FSComp.SR.optsSubSystemVersion())) yield CompilerOption - ("quotations-debug", tagNone, - OptionSwitch(fun switch -> tcConfigB.emitDebugInfoInQuotations <- switch = OptionSwitch.On), None, + ("quotations-debug", tagNone, + OptionSwitch(fun switch -> tcConfigB.emitDebugInfoInQuotations <- switch = OptionSwitch.On), None, Some(FSComp.SR.optsEmitDebugInfoInQuotations())) ] @@ -970,7 +970,7 @@ let advancedFlagsFsc tcConfigB = let testFlag tcConfigB = CompilerOption - ("test", tagString, + ("test", tagString, OptionString (fun s -> match s with | "StackSpan" -> tcConfigB.internalTestSpanStackReferring <- true @@ -985,7 +985,7 @@ let testFlag tcConfigB = | "DumpDebugInfo" -> tcConfigB.dumpDebugInfo <- true | "ShowLoadedAssemblies" -> tcConfigB.showLoadedAssemblies <- true | "ContinueAfterParseFailure" -> tcConfigB.continueAfterParseFailure <- true - | str -> warning(Error(FSComp.SR.optsUnknownArgumentToTheTestSwitch(str),rangeCmdArgs))), None, + | str -> warning(Error(FSComp.SR.optsUnknownArgumentToTheTestSwitch(str), rangeCmdArgs))), None, None) // Not shown in fsc.exe help, no warning on use, motivation is for use from tooling. @@ -1003,192 +1003,192 @@ let editorSpecificFlags (tcConfigB: TcConfigBuilder) = let internalFlags (tcConfigB:TcConfigBuilder) = [ CompilerOption - ("stamps", tagNone, - OptionUnit ignore, + ("stamps", tagNone, + OptionUnit ignore, Some(InternalCommandLineOption("--stamps", rangeCmdArgs)), None) CompilerOption - ("ranges", tagNone, - OptionSet Tastops.DebugPrint.layoutRanges, + ("ranges", tagNone, + OptionSet Tastops.DebugPrint.layoutRanges, Some(InternalCommandLineOption("--ranges", rangeCmdArgs)), None) CompilerOption - ("terms" , tagNone, - OptionUnit (fun () -> tcConfigB.showTerms <- true), + ("terms" , tagNone, + OptionUnit (fun () -> tcConfigB.showTerms <- true), Some(InternalCommandLineOption("--terms", rangeCmdArgs)), None) CompilerOption - ("termsfile" , tagNone, - OptionUnit (fun () -> tcConfigB.writeTermsToFiles <- true), + ("termsfile" , tagNone, + OptionUnit (fun () -> tcConfigB.writeTermsToFiles <- true), Some(InternalCommandLineOption("--termsfile", rangeCmdArgs)), None) #if DEBUG CompilerOption - ("debug-parse", tagNone, - OptionUnit (fun () -> Internal.Utilities.Text.Parsing.Flags.debug <- true), + ("debug-parse", tagNone, + OptionUnit (fun () -> Internal.Utilities.Text.Parsing.Flags.debug <- true), Some(InternalCommandLineOption("--debug-parse", rangeCmdArgs)), None) #endif CompilerOption - ("pause", tagNone, - OptionUnit (fun () -> tcConfigB.pause <- true), + ("pause", tagNone, + OptionUnit (fun () -> tcConfigB.pause <- true), Some(InternalCommandLineOption("--pause", rangeCmdArgs)), None) CompilerOption - ("detuple", tagNone, - OptionInt (setFlag (fun v -> tcConfigB.doDetuple <- v)), + ("detuple", tagNone, + OptionInt (setFlag (fun v -> tcConfigB.doDetuple <- v)), Some(InternalCommandLineOption("--detuple", rangeCmdArgs)), None) CompilerOption - ("simulateException", tagNone, - OptionString (fun s -> tcConfigB.simulateException <- Some(s)), + ("simulateException", tagNone, + OptionString (fun s -> tcConfigB.simulateException <- Some(s)), Some(InternalCommandLineOption("--simulateException", rangeCmdArgs)), Some "Simulate an exception from some part of the compiler") CompilerOption - ("stackReserveSize", tagNone, - OptionString (fun s -> tcConfigB.stackReserveSize <- Some(int32 s)), + ("stackReserveSize", tagNone, + OptionString (fun s -> tcConfigB.stackReserveSize <- Some(int32 s)), Some(InternalCommandLineOption("--stackReserveSize", rangeCmdArgs)), Some ("for an exe, set stack reserve size")) CompilerOption - ("tlr", tagInt, - OptionInt (setFlag (fun v -> tcConfigB.doTLR <- v)), + ("tlr", tagInt, + OptionInt (setFlag (fun v -> tcConfigB.doTLR <- v)), Some(InternalCommandLineOption("--tlr", rangeCmdArgs)), None) CompilerOption - ("finalSimplify", tagInt, - OptionInt (setFlag (fun v -> tcConfigB.doFinalSimplify <- v)), + ("finalSimplify", tagInt, + OptionInt (setFlag (fun v -> tcConfigB.doFinalSimplify <- v)), Some(InternalCommandLineOption("--finalSimplify", rangeCmdArgs)), None) CompilerOption - ("parseonly", tagNone, - OptionUnit (fun () -> tcConfigB.parseOnly <- true), + ("parseonly", tagNone, + OptionUnit (fun () -> tcConfigB.parseOnly <- true), Some(InternalCommandLineOption("--parseonly", rangeCmdArgs)), None) CompilerOption - ("typecheckonly", tagNone, - OptionUnit (fun () -> tcConfigB.typeCheckOnly <- true), + ("typecheckonly", tagNone, + OptionUnit (fun () -> tcConfigB.typeCheckOnly <- true), Some(InternalCommandLineOption("--typecheckonly", rangeCmdArgs)), None) CompilerOption - ("ast", tagNone, - OptionUnit (fun () -> tcConfigB.printAst <- true), + ("ast", tagNone, + OptionUnit (fun () -> tcConfigB.printAst <- true), Some(InternalCommandLineOption("--ast", rangeCmdArgs)), None) CompilerOption - ("tokenize", tagNone, - OptionUnit (fun () -> tcConfigB.tokenizeOnly <- true), + ("tokenize", tagNone, + OptionUnit (fun () -> tcConfigB.tokenizeOnly <- true), Some(InternalCommandLineOption("--tokenize", rangeCmdArgs)), None) CompilerOption - ("testInteractionParser", tagNone, - OptionUnit (fun () -> tcConfigB.testInteractionParser <- true), + ("testInteractionParser", tagNone, + OptionUnit (fun () -> tcConfigB.testInteractionParser <- true), Some(InternalCommandLineOption("--testInteractionParser", rangeCmdArgs)), None) CompilerOption - ("testparsererrorrecovery", tagNone, - OptionUnit (fun () -> tcConfigB.reportNumDecls <- true), + ("testparsererrorrecovery", tagNone, + OptionUnit (fun () -> tcConfigB.reportNumDecls <- true), Some(InternalCommandLineOption("--testparsererrorrecovery", rangeCmdArgs)), None) CompilerOption - ("inlinethreshold", tagInt, - OptionInt (fun n -> tcConfigB.optSettings <- { tcConfigB.optSettings with lambdaInlineThreshold = n }), + ("inlinethreshold", tagInt, + OptionInt (fun n -> tcConfigB.optSettings <- { tcConfigB.optSettings with lambdaInlineThreshold = n }), Some(InternalCommandLineOption("--inlinethreshold", rangeCmdArgs)), None) CompilerOption - ("extraoptimizationloops", tagNone, - OptionInt (fun n -> tcConfigB.extraOptimizationIterations <- n), + ("extraoptimizationloops", tagNone, + OptionInt (fun n -> tcConfigB.extraOptimizationIterations <- n), Some(InternalCommandLineOption("--extraoptimizationloops", rangeCmdArgs)), None) CompilerOption - ("abortonerror", tagNone, - OptionUnit (fun () -> tcConfigB.abortOnError <- true), + ("abortonerror", tagNone, + OptionUnit (fun () -> tcConfigB.abortOnError <- true), Some(InternalCommandLineOption("--abortonerror", rangeCmdArgs)), None) CompilerOption - ("implicitresolution", tagNone, - OptionUnit (fun _ -> tcConfigB.implicitlyResolveAssemblies <- true), + ("implicitresolution", tagNone, + OptionUnit (fun _ -> tcConfigB.implicitlyResolveAssemblies <- true), Some(InternalCommandLineOption("--implicitresolution", rangeCmdArgs)), None) // "Display assembly reference resolution information") CompilerOption - ("resolutions", tagNone, - OptionUnit (fun () -> tcConfigB.showReferenceResolutions <- true), + ("resolutions", tagNone, + OptionUnit (fun () -> tcConfigB.showReferenceResolutions <- true), Some(InternalCommandLineOption("", rangeCmdArgs)), None) // "The base registry key to use for assembly resolution. This part in brackets here: HKEY_LOCAL_MACHINE\[SOFTWARE\Microsoft\.NETFramework]\v2.0.50727\AssemblyFoldersEx") CompilerOption - ("resolutionframeworkregistrybase", tagString, - OptionString (fun _ -> ()), + ("resolutionframeworkregistrybase", tagString, + OptionString (fun _ -> ()), Some(InternalCommandLineOption("", rangeCmdArgs)), None) // "The base registry key to use for assembly resolution. This part in brackets here: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727\[AssemblyFoldersEx]") CompilerOption - ("resolutionassemblyfoldersuffix", tagString, - OptionString (fun _ -> ()), + ("resolutionassemblyfoldersuffix", tagString, + OptionString (fun _ -> ()), Some(InternalCommandLineOption("resolutionassemblyfoldersuffix", rangeCmdArgs)), None) - // "Additional reference resolution conditions. For example \"OSVersion=5.1.2600.0,PlatformID=id") + // "Additional reference resolution conditions. For example \"OSVersion=5.1.2600.0, PlatformID=id") CompilerOption - ("resolutionassemblyfoldersconditions", tagString, - OptionString (fun _ -> ()), + ("resolutionassemblyfoldersconditions", tagString, + OptionString (fun _ -> ()), Some(InternalCommandLineOption("resolutionassemblyfoldersconditions", rangeCmdArgs)), None) // "Resolve assembly references using MSBuild resolution rules rather than directory based (Default=true except when running fsc.exe under mono)") CompilerOption - ("msbuildresolution", tagNone, - OptionUnit (fun () -> tcConfigB.useSimpleResolution<-false), + ("msbuildresolution", tagNone, + OptionUnit (fun () -> tcConfigB.useSimpleResolution<-false), Some(InternalCommandLineOption("msbuildresolution", rangeCmdArgs)), None) CompilerOption - ("alwayscallvirt",tagNone, + ("alwayscallvirt", tagNone, OptionSwitch(callVirtSwitch tcConfigB), - Some(InternalCommandLineOption("alwayscallvirt",rangeCmdArgs)), None) + Some(InternalCommandLineOption("alwayscallvirt", rangeCmdArgs)), None) CompilerOption - ("nodebugdata",tagNone, + ("nodebugdata", tagNone, OptionUnit (fun () -> tcConfigB.noDebugData<-true), - Some(InternalCommandLineOption("--nodebugdata",rangeCmdArgs)), None) + Some(InternalCommandLineOption("--nodebugdata", rangeCmdArgs)), None) testFlag tcConfigB ] @ editorSpecificFlags tcConfigB @ [ CompilerOption - ("jit", tagNone, - OptionSwitch (jitoptimizeSwitch tcConfigB), + ("jit", tagNone, + OptionSwitch (jitoptimizeSwitch tcConfigB), Some(InternalCommandLineOption("jit", rangeCmdArgs)), None) CompilerOption - ("localoptimize", tagNone, + ("localoptimize", tagNone, OptionSwitch(localoptimizeSwitch tcConfigB), Some(InternalCommandLineOption("localoptimize", rangeCmdArgs)), None) CompilerOption - ("splitting", tagNone, + ("splitting", tagNone, OptionSwitch(splittingSwitch tcConfigB), Some(InternalCommandLineOption("splitting", rangeCmdArgs)), None) CompilerOption - ("versionfile", tagString, - OptionString (fun s -> tcConfigB.version <- VersionFile s), + ("versionfile", tagString, + OptionString (fun s -> tcConfigB.version <- VersionFile s), Some(InternalCommandLineOption("versionfile", rangeCmdArgs)), None) // "Display timing profiles for compilation" CompilerOption - ("times" , tagNone, - OptionUnit (fun () -> tcConfigB.showTimes <- true), + ("times" , tagNone, + OptionUnit (fun () -> tcConfigB.showTimes <- true), Some(InternalCommandLineOption("times", rangeCmdArgs)), None) #if !NO_EXTENSIONTYPING // "Display information about extension type resolution") CompilerOption - ("showextensionresolution" , tagNone, - OptionUnit (fun () -> tcConfigB.showExtensionTypeMessages <- true), + ("showextensionresolution" , tagNone, + OptionUnit (fun () -> tcConfigB.showExtensionTypeMessages <- true), Some(InternalCommandLineOption("showextensionresolution", rangeCmdArgs)), None) #endif CompilerOption - ("metadataversion", tagString, - OptionString (fun s -> tcConfigB.metadataVersion <- Some(s)), + ("metadataversion", tagString, + OptionString (fun s -> tcConfigB.metadataVersion <- Some(s)), Some(InternalCommandLineOption("metadataversion", rangeCmdArgs)), None) ] @@ -1196,61 +1196,61 @@ let internalFlags (tcConfigB:TcConfigBuilder) = // OptionBlock: Deprecated flags (fsc, service only) //-------------------------------------------------- -let compilingFsLibFlag (tcConfigB : TcConfigBuilder) = +let compilingFsLibFlag (tcConfigB: TcConfigBuilder) = CompilerOption - ("compiling-fslib", tagNone, + ("compiling-fslib", tagNone, OptionUnit (fun () -> tcConfigB.compilingFslib <- true - tcConfigB.TurnWarningOff(rangeStartup,"42") + tcConfigB.TurnWarningOff(rangeStartup, "42") ErrorLogger.reportLibraryOnlyFeatures <- false - IlxSettings.ilxCompilingFSharpCoreLib := true), + IlxSettings.ilxCompilingFSharpCoreLib := true), Some(InternalCommandLineOption("--compiling-fslib", rangeCmdArgs)), None) -let compilingFsLib20Flag (tcConfigB : TcConfigBuilder) = +let compilingFsLib20Flag (tcConfigB: TcConfigBuilder) = CompilerOption - ("compiling-fslib-20", tagNone, - OptionString (fun s -> tcConfigB.compilingFslib20 <- Some s ), + ("compiling-fslib-20", tagNone, + OptionString (fun s -> tcConfigB.compilingFslib20 <- Some s ), Some(InternalCommandLineOption("--compiling-fslib-20", rangeCmdArgs)), None) -let compilingFsLib40Flag (tcConfigB : TcConfigBuilder) = +let compilingFsLib40Flag (tcConfigB: TcConfigBuilder) = CompilerOption - ("compiling-fslib-40", tagNone, - OptionUnit (fun () -> tcConfigB.compilingFslib40 <- true ), + ("compiling-fslib-40", tagNone, + OptionUnit (fun () -> tcConfigB.compilingFslib40 <- true ), Some(InternalCommandLineOption("--compiling-fslib-40", rangeCmdArgs)), None) -let compilingFsLibNoBigIntFlag (tcConfigB : TcConfigBuilder) = +let compilingFsLibNoBigIntFlag (tcConfigB: TcConfigBuilder) = CompilerOption - ("compiling-fslib-nobigint", tagNone, - OptionUnit (fun () -> tcConfigB.compilingFslibNoBigInt <- true ), + ("compiling-fslib-nobigint", tagNone, + OptionUnit (fun () -> tcConfigB.compilingFslibNoBigInt <- true ), Some(InternalCommandLineOption("--compiling-fslib-nobigint", rangeCmdArgs)), None) let mlKeywordsFlag = CompilerOption - ("ml-keywords", tagNone, - OptionUnit (fun () -> ()), + ("ml-keywords", tagNone, + OptionUnit (fun () -> ()), Some(DeprecatedCommandLineOptionNoDescription("--ml-keywords", rangeCmdArgs)), None) let gnuStyleErrorsFlag tcConfigB = CompilerOption - ("gnu-style-errors", tagNone, - OptionUnit (fun () -> tcConfigB.errorStyle <- ErrorStyle.EmacsErrors), + ("gnu-style-errors", tagNone, + OptionUnit (fun () -> tcConfigB.errorStyle <- ErrorStyle.EmacsErrors), Some(DeprecatedCommandLineOptionNoDescription("--gnu-style-errors", rangeCmdArgs)), None) let deprecatedFlagsBoth tcConfigB = [ CompilerOption - ("light", tagNone, - OptionUnit (fun () -> tcConfigB.light <- Some(true)), + ("light", tagNone, + OptionUnit (fun () -> tcConfigB.light <- Some(true)), Some(DeprecatedCommandLineOptionNoDescription("--light", rangeCmdArgs)), None) CompilerOption - ("indentation-syntax", tagNone, - OptionUnit (fun () -> tcConfigB.light <- Some(true)), + ("indentation-syntax", tagNone, + OptionUnit (fun () -> tcConfigB.light <- Some(true)), Some(DeprecatedCommandLineOptionNoDescription("--indentation-syntax", rangeCmdArgs)), None) CompilerOption - ("no-indentation-syntax", tagNone, - OptionUnit (fun () -> tcConfigB.light <- Some(false)), + ("no-indentation-syntax", tagNone, + OptionUnit (fun () -> tcConfigB.light <- Some(false)), Some(DeprecatedCommandLineOptionNoDescription("--no-indentation-syntax", rangeCmdArgs)), None) ] @@ -1261,28 +1261,28 @@ let deprecatedFlagsFsc tcConfigB = [ cliRootFlag tcConfigB CompilerOption - ("jit-optimize", tagNone, - OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with jitOptUser = Some true }), + ("jit-optimize", tagNone, + OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with jitOptUser = Some true }), Some(DeprecatedCommandLineOptionNoDescription("--jit-optimize", rangeCmdArgs)), None) CompilerOption - ("no-jit-optimize", tagNone, - OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with jitOptUser = Some false }), + ("no-jit-optimize", tagNone, + OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with jitOptUser = Some false }), Some(DeprecatedCommandLineOptionNoDescription("--no-jit-optimize", rangeCmdArgs)), None) CompilerOption - ("jit-tracking", tagNone, - OptionUnit (fun _ -> (tcConfigB.jitTracking <- true) ), + ("jit-tracking", tagNone, + OptionUnit (fun _ -> (tcConfigB.jitTracking <- true) ), Some(DeprecatedCommandLineOptionNoDescription("--jit-tracking", rangeCmdArgs)), None) CompilerOption - ("no-jit-tracking", tagNone, - OptionUnit (fun _ -> (tcConfigB.jitTracking <- false) ), + ("no-jit-tracking", tagNone, + OptionUnit (fun _ -> (tcConfigB.jitTracking <- false) ), Some(DeprecatedCommandLineOptionNoDescription("--no-jit-tracking", rangeCmdArgs)), None) CompilerOption - ("progress", tagNone, - OptionUnit (fun () -> progress := true), + ("progress", tagNone, + OptionUnit (fun () -> progress := true), Some(DeprecatedCommandLineOptionNoDescription("--progress", rangeCmdArgs)), None) compilingFsLibFlag tcConfigB @@ -1291,68 +1291,68 @@ let deprecatedFlagsFsc tcConfigB = compilingFsLibNoBigIntFlag tcConfigB CompilerOption - ("version", tagString, - OptionString (fun s -> tcConfigB.version <- VersionString s), + ("version", tagString, + OptionString (fun s -> tcConfigB.version <- VersionString s), Some(DeprecatedCommandLineOptionNoDescription("--version", rangeCmdArgs)), None) CompilerOption - ("local-optimize", tagNone, - OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with localOptUser = Some true }), + ("local-optimize", tagNone, + OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with localOptUser = Some true }), Some(DeprecatedCommandLineOptionNoDescription("--local-optimize", rangeCmdArgs)), None) CompilerOption - ("no-local-optimize", tagNone, - OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with localOptUser = Some false }), + ("no-local-optimize", tagNone, + OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with localOptUser = Some false }), Some(DeprecatedCommandLineOptionNoDescription("--no-local-optimize", rangeCmdArgs)), None) CompilerOption - ("cross-optimize", tagNone, - OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with crossModuleOptUser = Some true }), + ("cross-optimize", tagNone, + OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with crossModuleOptUser = Some true }), Some(DeprecatedCommandLineOptionNoDescription("--cross-optimize", rangeCmdArgs)), None) CompilerOption - ("no-cross-optimize", tagNone, - OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with crossModuleOptUser = Some false }), + ("no-cross-optimize", tagNone, + OptionUnit (fun _ -> tcConfigB.optSettings <- { tcConfigB.optSettings with crossModuleOptUser = Some false }), Some(DeprecatedCommandLineOptionNoDescription("--no-cross-optimize", rangeCmdArgs)), None) CompilerOption - ("no-string-interning", tagNone, - OptionUnit (fun () -> tcConfigB.internConstantStrings <- false), + ("no-string-interning", tagNone, + OptionUnit (fun () -> tcConfigB.internConstantStrings <- false), Some(DeprecatedCommandLineOptionNoDescription("--no-string-interning", rangeCmdArgs)), None) CompilerOption - ("statistics", tagNone, - OptionUnit (fun () -> tcConfigB.stats <- true), + ("statistics", tagNone, + OptionUnit (fun () -> tcConfigB.stats <- true), Some(DeprecatedCommandLineOptionNoDescription("--statistics", rangeCmdArgs)), None) CompilerOption - ("generate-filter-blocks", tagNone, - OptionUnit (fun () -> tcConfigB.generateFilterBlocks <- true), + ("generate-filter-blocks", tagNone, + OptionUnit (fun () -> tcConfigB.generateFilterBlocks <- true), Some(DeprecatedCommandLineOptionNoDescription("--generate-filter-blocks", rangeCmdArgs)), None) //CompilerOption - // ("no-generate-filter-blocks", tagNone, - // OptionUnit (fun () -> tcConfigB.generateFilterBlocks <- false), + // ("no-generate-filter-blocks", tagNone, + // OptionUnit (fun () -> tcConfigB.generateFilterBlocks <- false), // Some(DeprecatedCommandLineOptionNoDescription("--generate-filter-blocks", rangeCmdArgs)), None) CompilerOption - ("max-errors", tagInt, - OptionInt (fun n -> tcConfigB.maxErrors <- n), - Some(DeprecatedCommandLineOptionSuggestAlternative("--max-errors", "--maxerrors", rangeCmdArgs)),None) + ("max-errors", tagInt, + OptionInt (fun n -> tcConfigB.maxErrors <- n), + Some(DeprecatedCommandLineOptionSuggestAlternative("--max-errors", "--maxerrors", rangeCmdArgs)), None) CompilerOption - ("debug-file", tagNone, - OptionString (fun s -> tcConfigB.debugSymbolFile <- Some s), + ("debug-file", tagNone, + OptionString (fun s -> tcConfigB.debugSymbolFile <- Some s), Some(DeprecatedCommandLineOptionSuggestAlternative("--debug-file", "--pdb", rangeCmdArgs)), None) CompilerOption - ("no-debug-file", tagNone, - OptionUnit (fun () -> tcConfigB.debuginfo <- false), + ("no-debug-file", tagNone, + OptionUnit (fun () -> tcConfigB.debuginfo <- false), Some(DeprecatedCommandLineOptionSuggestAlternative("--no-debug-file", "--debug-", rangeCmdArgs)), None) CompilerOption - ("Ooff", tagNone, - OptionUnit (fun () -> SetOptimizeOff(tcConfigB)), + ("Ooff", tagNone, + OptionUnit (fun () -> SetOptimizeOff(tcConfigB)), Some(DeprecatedCommandLineOptionSuggestAlternative("-Ooff", "--optimize-", rangeCmdArgs)), None) mlKeywordsFlag @@ -1405,48 +1405,48 @@ let abbreviatedFlagsFsc tcConfigB = abbreviatedFlagsBoth tcConfigB @ [ // FSC only abbreviated options CompilerOption - ("o", tagString, - OptionString (setOutFileName tcConfigB), None, + ("o", tagString, + OptionString (setOutFileName tcConfigB), None, Some(FSComp.SR.optsShortFormOf("--out"))) CompilerOption - ("a", tagString, - OptionUnit (fun () -> tcConfigB.target <- CompilerTarget.Dll), None, + ("a", tagString, + OptionUnit (fun () -> tcConfigB.target <- CompilerTarget.Dll), None, Some(FSComp.SR.optsShortFormOf("--target library"))) // FSC help abbreviations. FSI has it's own help options... CompilerOption - ("?" , tagNone, - OptionHelp (fun blocks -> displayHelpFsc tcConfigB blocks), None, + ("?" , tagNone, + OptionHelp (fun blocks -> displayHelpFsc tcConfigB blocks), None, Some(FSComp.SR.optsShortFormOf("--help"))) CompilerOption - ("help" , tagNone, - OptionHelp (fun blocks -> displayHelpFsc tcConfigB blocks), None, + ("help" , tagNone, + OptionHelp (fun blocks -> displayHelpFsc tcConfigB blocks), None, Some(FSComp.SR.optsShortFormOf("--help"))) CompilerOption - ("full-help", tagNone, - OptionHelp (fun blocks -> displayHelpFsc tcConfigB blocks), None, + ("full-help", tagNone, + OptionHelp (fun blocks -> displayHelpFsc tcConfigB blocks), None, Some(FSComp.SR.optsShortFormOf("--help"))) ] let GetAbbrevFlagSet tcConfigB isFsc = - let mutable argList : string list = [] + let mutable argList: string list = [] for c in ((if isFsc then abbreviatedFlagsFsc else abbreviatedFlagsFsi) tcConfigB) do match c with - | CompilerOption(arg,_,OptionString _,_,_) - | CompilerOption(arg,_,OptionStringList _,_,_) -> argList <- argList @ ["-"+arg;"/"+arg] + | CompilerOption(arg, _, OptionString _, _, _) + | CompilerOption(arg, _, OptionStringList _, _, _) -> argList <- argList @ ["-"+arg;"/"+arg] | _ -> () Set.ofList argList // check for abbreviated options that accept spaces instead of colons, and replace the spaces // with colons when necessary -let PostProcessCompilerArgs (abbrevArgs : string Set) (args : string []) = +let PostProcessCompilerArgs (abbrevArgs: string Set) (args: string []) = let mutable i = 0 let mutable idx = 0 let len = args.Length - let mutable arga : string[] = Array.create len "" + let mutable arga: string[] = Array.create len "" while i < len do if not(abbrevArgs.Contains(args.[i])) || i = (len - 1) then @@ -1464,8 +1464,8 @@ let PostProcessCompilerArgs (abbrevArgs : string Set) (args : string []) = let testingAndQAFlags _tcConfigB = [ CompilerOption - ("dumpAllCommandLineOptions", tagNone, - OptionHelp(fun blocks -> DumpCompilerOptionBlocks blocks), + ("dumpAllCommandLineOptions", tagNone, + OptionHelp(fun blocks -> DumpCompilerOptionBlocks blocks), None, None) // "Command line options") ] @@ -1504,13 +1504,13 @@ let testingAndQAFlags _tcConfigB = /// The core/common options used by fsc.exe. [not currently extended by fsc.fs]. let GetCoreFscCompilerOptions (tcConfigB: TcConfigBuilder) = - [ PublicOptions(FSComp.SR.optsHelpBannerOutputFiles(), outputFileFlagsFsc tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerInputFiles(), inputFileFlagsFsc tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerResources(), resourcesFlagsFsc tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerCodeGen(), codeGenerationFlags false tcConfigB) + [ PublicOptions(FSComp.SR.optsHelpBannerOutputFiles(), outputFileFlagsFsc tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerInputFiles(), inputFileFlagsFsc tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerResources(), resourcesFlagsFsc tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerCodeGen(), codeGenerationFlags false tcConfigB) PublicOptions(FSComp.SR.optsHelpBannerErrsAndWarns(), errorsAndWarningsFlags tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerLanguage(), languageFlags tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerMisc(), miscFlagsFsc tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerLanguage(), languageFlags tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerMisc(), miscFlagsFsc tcConfigB) PublicOptions(FSComp.SR.optsHelpBannerAdvanced(), advancedFlagsFsc tcConfigB) PrivateOptions(List.concat [ internalFlags tcConfigB abbreviatedFlagsFsc tcConfigB @@ -1521,7 +1521,7 @@ let GetCoreFscCompilerOptions (tcConfigB: TcConfigBuilder) = /// The core/common options used by the F# VS Language Service. /// Filter out OptionHelp which does printing then exit. This is not wanted in the context of VS!! let GetCoreServiceCompilerOptions (tcConfigB:TcConfigBuilder) = - let isHelpOption = function CompilerOption(_,_,OptionHelp _,_,_) -> true | _ -> false + let isHelpOption = function CompilerOption(_, _, OptionHelp _, _, _) -> true | _ -> false List.map (FilterCompilerOptionBlock (isHelpOption >> not)) (GetCoreFscCompilerOptions tcConfigB) /// The core/common options used by fsi.exe. [note, some additional options are added in fsi.fs]. @@ -1626,7 +1626,7 @@ let ReportTime (tcConfig:TcConfig) descr = let wsNow = ptime.WorkingSet64/1000000L match !tPrev, !nPrev with - | Some (timePrev,gcPrev:int []),Some prevDescr -> + | Some (timePrev, gcPrev:int []), Some prevDescr -> let spanGC = [| for i in 0 .. maxGen -> System.GC.CollectionCount(i) - gcPrev.[i] |] dprintf "TIME: %4.1f Delta: %4.1f Mem: %3d" timeNow (timeNow - timePrev) @@ -1636,7 +1636,7 @@ let ReportTime (tcConfig:TcConfig) descr = prevDescr | _ -> () - tPrev := Some (timeNow,gcNow) + tPrev := Some (timeNow, gcNow) nPrev := Some descr @@ -1682,17 +1682,17 @@ let ApplyAllOptimizations (tcConfig:TcConfig, tcGlobals, tcVal, outfile, importM let optSettings = { optSettings with abstractBigTargets = tcConfig.doTLR } let optSettings = { optSettings with reportingPhase = true } - let results,(optEnvFirstLoop,_,_,_) = - ((optEnv0,optEnv0,optEnv0,SignatureHidingInfo.Empty),implFiles) + let results, (optEnvFirstLoop, _, _, _) = + ((optEnv0, optEnv0, optEnv0, SignatureHidingInfo.Empty), implFiles) - ||> List.mapFold (fun (optEnvFirstLoop,optEnvExtraLoop,optEnvFinalSimplify,hidden) implFile -> + ||> List.mapFold (fun (optEnvFirstLoop, optEnvExtraLoop, optEnvFinalSimplify, hidden) implFile -> //ReportTime tcConfig ("Initial simplify") - let (optEnvFirstLoop,implFile,implFileOptData,hidden), optimizeDuringCodeGen = + let (optEnvFirstLoop, implFile, implFileOptData, hidden), optimizeDuringCodeGen = Optimizer.OptimizeImplFile - (optSettings,ccu,tcGlobals,tcVal,importMap, - optEnvFirstLoop,isIncrementalFragment, - tcConfig.emitTailcalls,hidden,implFile) + (optSettings, ccu, tcGlobals, tcVal, importMap, + optEnvFirstLoop, isIncrementalFragment, + tcConfig.emitTailcalls, hidden, implFile) let implFile = AutoBox.TransformImplFile tcGlobals importMap implFile @@ -1703,20 +1703,20 @@ let ApplyAllOptimizations (tcConfig:TcConfig, tcGlobals, tcVal, outfile, importM dprintf "Optimization implFileOptData:\n%s\n" (Layout.showL (Layout.squashTo 192 (Optimizer.moduleInfoL tcGlobals implFileOptData))) #endif - let implFile,optEnvExtraLoop = + let implFile, optEnvExtraLoop = if tcConfig.extraOptimizationIterations > 0 then //ReportTime tcConfig ("Extra simplification loop") - let (optEnvExtraLoop,implFile, _, _), _ = + let (optEnvExtraLoop, implFile, _, _), _ = Optimizer.OptimizeImplFile - (optSettings,ccu,tcGlobals,tcVal, importMap, - optEnvExtraLoop,isIncrementalFragment, - tcConfig.emitTailcalls,hidden,implFile) + (optSettings, ccu, tcGlobals, tcVal, importMap, + optEnvExtraLoop, isIncrementalFragment, + tcConfig.emitTailcalls, hidden, implFile) //PrintWholeAssemblyImplementation tcConfig outfile (sprintf "extra-loop-%d" n) implFile - implFile,optEnvExtraLoop + implFile, optEnvExtraLoop else - implFile,optEnvExtraLoop + implFile, optEnvExtraLoop let implFile = if tcConfig.doDetuple then @@ -1734,23 +1734,23 @@ let ApplyAllOptimizations (tcConfig:TcConfig, tcGlobals, tcVal, outfile, importM let implFile = LowerCallsAndSeqs.LowerImplFile tcGlobals implFile - let implFile,optEnvFinalSimplify = + let implFile, optEnvFinalSimplify = if tcConfig.doFinalSimplify then //ReportTime tcConfig ("Final simplify pass") - let (optEnvFinalSimplify,implFile, _, _),_ = + let (optEnvFinalSimplify, implFile, _, _), _ = Optimizer.OptimizeImplFile - (optSettings,ccu,tcGlobals,tcVal, importMap,optEnvFinalSimplify, - isIncrementalFragment,tcConfig.emitTailcalls,hidden,implFile) + (optSettings, ccu, tcGlobals, tcVal, importMap, optEnvFinalSimplify, + isIncrementalFragment, tcConfig.emitTailcalls, hidden, implFile) //PrintWholeAssemblyImplementation tcConfig outfile "post-rec-opt" implFile - implFile,optEnvFinalSimplify + implFile, optEnvFinalSimplify else - implFile,optEnvFinalSimplify + implFile, optEnvFinalSimplify - ((implFile,optimizeDuringCodeGen),implFileOptData),(optEnvFirstLoop,optEnvExtraLoop,optEnvFinalSimplify,hidden)) + ((implFile, optimizeDuringCodeGen), implFileOptData), (optEnvFirstLoop, optEnvExtraLoop, optEnvFinalSimplify, hidden)) - let implFiles,implFileOptDatas = List.unzip results + let implFiles, implFileOptDatas = List.unzip results let assemblyOptData = Optimizer.UnionOptimizationInfos implFileOptDatas let tassembly = TypedAssemblyAfterOptimization(implFiles) PrintWholeAssemblyImplementation tcConfig outfile "pass-end" (List.map fst implFiles) @@ -1763,15 +1763,15 @@ let ApplyAllOptimizations (tcConfig:TcConfig, tcGlobals, tcVal, outfile, importM // ILX generation //---------------------------------------------------------------------------- -let CreateIlxAssemblyGenerator (_tcConfig:TcConfig,tcImports:TcImports,tcGlobals, tcVal, generatedCcu) = +let CreateIlxAssemblyGenerator (_tcConfig:TcConfig, tcImports:TcImports, tcGlobals, tcVal, generatedCcu) = let ilxGenerator = new IlxGen.IlxAssemblyGenerator (tcImports.GetImportMap(), tcGlobals, tcVal, generatedCcu) let ccus = tcImports.GetCcusInDeclOrder() ilxGenerator.AddExternalCcus ccus ilxGenerator let GenerateIlxCode - (ilxBackend, isInteractiveItExpr, isInteractiveOnMono, - tcConfig:TcConfig, topAttrs: TypeChecker.TopAttribs, optimizedImpls, + (ilxBackend, isInteractiveItExpr, isInteractiveOnMono, + tcConfig:TcConfig, topAttrs: TypeChecker.TopAttribs, optimizedImpls, fragName, ilxGenerator: IlxAssemblyGenerator) = let mainMethodInfo = @@ -1779,7 +1779,7 @@ let GenerateIlxCode None else Some topAttrs.mainMethodAttrs - let ilxGenOpts : IlxGenOptions = + let ilxGenOpts: IlxGenOptions = { generateFilterBlocks = tcConfig.generateFilterBlocks emitConstantArraysUsingStaticDataBlobs = not isInteractiveOnMono workAroundReflectionEmitBugs=tcConfig.isInteractive // REVIEW: is this still required? @@ -1793,7 +1793,7 @@ let GenerateIlxCode isInteractiveItExpr = isInteractiveItExpr alwaysCallVirt = tcConfig.alwaysCallVirt } - ilxGenerator.GenerateCode (ilxGenOpts, optimizedImpls, topAttrs.assemblyAttrs,topAttrs.netModuleAttrs) + ilxGenerator.GenerateCode (ilxGenOpts, optimizedImpls, topAttrs.assemblyAttrs, topAttrs.netModuleAttrs) //---------------------------------------------------------------------------- // Assembly ref normalization: make sure all assemblies are referred to @@ -1820,7 +1820,7 @@ let foreBackColor () = try let c = Console.ForegroundColor // may fail, perhaps on Mac, and maybe ForegroundColor is Black let b = Console.BackgroundColor // may fail, perhaps on Mac, and maybe BackgroundColor is White - Some (c,b) + Some (c, b) with e -> None @@ -1830,7 +1830,7 @@ let DoWithColor newColor f = | true, None -> // could not get console colours, so no attempt to change colours, can not set them back f() - | true, Some (c,_) -> + | true, Some (c, _) -> try ignoreFailureOnMono1_1_16 (fun () -> Console.ForegroundColor <- newColor) f() diff --git a/src/fsharp/ConstraintSolver.fs b/src/fsharp/ConstraintSolver.fs index dbe2feee9c6..c6f418e9dbe 100644 --- a/src/fsharp/ConstraintSolver.fs +++ b/src/fsharp/ConstraintSolver.fs @@ -98,7 +98,7 @@ let NewInferenceTypes l = l |> List.map (fun _ -> NewInferenceType ()) // condition anyway, so we could get away with a non-rigid typar. This // would sort of be cleaner, though give errors later. let FreshenAndFixupTypars m rigid fctps tinst tpsorig = - let copy_tyvar (tp:Typar) = NewCompGenTypar (tp.Kind, rigid, tp.StaticReq, (if rigid=TyparRigidity.Rigid then TyparDynamicReq.Yes else TyparDynamicReq.No), false) + let copy_tyvar (tp: Typar) = NewCompGenTypar (tp.Kind, rigid, tp.StaticReq, (if rigid=TyparRigidity.Rigid then TyparDynamicReq.Yes else TyparDynamicReq.No), false) let tps = tpsorig |> List.map copy_tyvar let renaming, tinst = FixupNewTypars m fctps tinst tpsorig tps tps, renaming, tinst @@ -113,7 +113,7 @@ let FreshenTypars m tpsorig = let _, _, tptys = FreshenTypeInst m tpsorig tptys -let FreshenMethInfo m (minfo:MethInfo) = +let FreshenMethInfo m (minfo: MethInfo) = let _, _, tptys = FreshMethInst m (minfo.GetFormalTyparsOfDeclaringType m) minfo.DeclaringTypeInst minfo.FormalMethodTypars tptys @@ -391,7 +391,7 @@ exception LocallyAbortOperationThatLosesAbbrevs let localAbortD = ErrorD LocallyAbortOperationThatLosesAbbrevs /// Return true if we would rather unify this variable v1 := v2 than vice versa -let PreferUnifyTypar (v1:Typar) (v2:Typar) = +let PreferUnifyTypar (v1: Typar) (v2: Typar) = match v1.Rigidity, v2.Rigidity with // Rigid > all | TyparRigidity.Rigid, _ -> false @@ -438,7 +438,7 @@ let FindPreferredTypar vs = let rec find vs = match vs with | [] -> vs - | (v:Typar, e)::vs -> + | (v: Typar, e)::vs -> match find vs with | [] -> [(v, e)] | (v', e')::vs' -> @@ -447,7 +447,7 @@ let FindPreferredTypar vs = else (v', e') :: (v, e) :: vs' find vs -let SubstMeasure (r:Typar) ms = +let SubstMeasure (r: Typar) ms = if r.Rigidity = TyparRigidity.Rigid then error(InternalError("SubstMeasure: rigid", r.Range)) if r.Kind = TyparKind.Type then error(InternalError("SubstMeasure: kind=type", r.Range)) @@ -455,7 +455,7 @@ let SubstMeasure (r:Typar) ms = | None -> r.typar_solution <- Some (TType_measure ms) | Some _ -> error(InternalError("already solved", r.Range)) -let rec TransactStaticReq (csenv:ConstraintSolverEnv) (trace:OptionalTrace) (tpr:Typar) req = +let rec TransactStaticReq (csenv: ConstraintSolverEnv) (trace: OptionalTrace) (tpr: Typar) req = let m = csenv.m if tpr.Rigidity.ErrorIfUnified && tpr.StaticReq <> req then ErrorD(ConstraintSolverError(FSComp.SR.csTypeCannotBeResolvedAtCompileTime(tpr.Name), m, m)) @@ -464,12 +464,12 @@ let rec TransactStaticReq (csenv:ConstraintSolverEnv) (trace:OptionalTrace) (tpr trace.Exec (fun () -> tpr.SetStaticReq req) (fun () -> tpr.SetStaticReq orig) CompleteD -and SolveTypStaticReqTypar (csenv:ConstraintSolverEnv) trace req (tpr:Typar) = +and SolveTypStaticReqTypar (csenv: ConstraintSolverEnv) trace req (tpr: Typar) = let orig = tpr.StaticReq let req2 = JoinTyparStaticReq req orig if orig <> req2 then TransactStaticReq csenv trace tpr req2 else CompleteD -and SolveTypStaticReq (csenv:ConstraintSolverEnv) trace req ty = +and SolveTypStaticReq (csenv: ConstraintSolverEnv) trace req ty = match req with | NoStaticReq -> CompleteD | HeadTypeStaticReq -> @@ -486,12 +486,12 @@ and SolveTypStaticReq (csenv:ConstraintSolverEnv) trace req ty = | ValueSome tpr -> SolveTypStaticReqTypar csenv trace req tpr | ValueNone -> CompleteD -let TransactDynamicReq (trace:OptionalTrace) (tpr:Typar) req = +let TransactDynamicReq (trace: OptionalTrace) (tpr: Typar) req = let orig = tpr.DynamicReq trace.Exec (fun () -> tpr.SetDynamicReq req) (fun () -> tpr.SetDynamicReq orig) CompleteD -let SolveTypDynamicReq (csenv:ConstraintSolverEnv) trace req ty = +let SolveTypDynamicReq (csenv: ConstraintSolverEnv) trace req ty = match req with | TyparDynamicReq.No -> CompleteD | TyparDynamicReq.Yes -> @@ -500,12 +500,12 @@ let SolveTypDynamicReq (csenv:ConstraintSolverEnv) trace req ty = TransactDynamicReq trace tpr TyparDynamicReq.Yes | _ -> CompleteD -let TransactIsCompatFlex (trace:OptionalTrace) (tpr:Typar) req = +let TransactIsCompatFlex (trace: OptionalTrace) (tpr: Typar) req = let orig = tpr.IsCompatFlex trace.Exec (fun () -> tpr.SetIsCompatFlex req) (fun () -> tpr.SetIsCompatFlex orig) CompleteD -let SolveTypIsCompatFlex (csenv:ConstraintSolverEnv) trace req ty = +let SolveTypIsCompatFlex (csenv: ConstraintSolverEnv) trace req ty = if req then match tryAnyParTy csenv.g ty with | ValueSome tpr when not tpr.IsCompatFlex -> TransactIsCompatFlex trace tpr req @@ -513,7 +513,7 @@ let SolveTypIsCompatFlex (csenv:ConstraintSolverEnv) trace req ty = else CompleteD -let SubstMeasureWarnIfRigid (csenv:ConstraintSolverEnv) trace (v:Typar) ms = trackErrors { +let SubstMeasureWarnIfRigid (csenv: ConstraintSolverEnv) trace (v: Typar) ms = trackErrors { if v.Rigidity.WarnIfUnified && not (isAnyParTy csenv.g (TType_measure ms)) then // NOTE: we grab the name eagerly to make sure the type variable prints as a type variable let tpnmOpt = if v.IsCompilerGenerated then None else Some v.Name @@ -536,7 +536,7 @@ let SubstMeasureWarnIfRigid (csenv:ConstraintSolverEnv) trace (v:Typar) ms = tra /// - ms contains no non-rigid unit variables, and so cannot be unified with 1 /// - ms has the form v^e * ms' for some non-rigid variable v, non-zero exponent e, and measure expression ms' /// the most general unifier is then simply v := ms' ^ -(1/e) -let UnifyMeasureWithOne (csenv:ConstraintSolverEnv) trace ms = +let UnifyMeasureWithOne (csenv: ConstraintSolverEnv) trace ms = // Gather the rigid and non-rigid unit variables in this measure expression together with their exponents let rigidVars, nonRigidVars = ListMeasureVarOccsWithNonZeroExponents ms @@ -555,7 +555,7 @@ let UnifyMeasureWithOne (csenv:ConstraintSolverEnv) trace ms = | [] -> if measureEquiv csenv.g ms Measure.One then CompleteD else localAbortD /// Imperatively unify unit-of-measure expression ms1 against ms2 -let UnifyMeasures (csenv:ConstraintSolverEnv) trace ms1 ms2 = +let UnifyMeasures (csenv: ConstraintSolverEnv) trace ms1 ms2 = UnifyMeasureWithOne csenv trace (Measure.Prod(ms1, Measure.Inv ms2)) /// Simplify a unit-of-measure expression ms that forms part of a type scheme. @@ -679,7 +679,7 @@ let NormalizeExponentsInTypeScheme uvars ty = // Essentially this is the *reduced row echelon* matrix from linear algebra, with adjustment to ensure that // exponents are integers where possible (in the reduced row echelon form, a1, b2, etc. would be 1, possibly // forcing other entries to be non-integers). -let SimplifyMeasuresInTypeScheme g resultFirst (generalizable:Typar list) ty constraints = +let SimplifyMeasuresInTypeScheme g resultFirst (generalizable: Typar list) ty constraints = // Only bother if we're generalizing over at least one unit-of-measure variable let uvars, vars = generalizable @@ -694,7 +694,7 @@ let SimplifyMeasuresInTypeScheme g resultFirst (generalizable:Typar list) ty con let freshMeasure () = Measure.Var (NewInferenceMeasurePar ()) -let CheckWarnIfRigid (csenv:ConstraintSolverEnv) ty1 (r:Typar) ty = +let CheckWarnIfRigid (csenv: ConstraintSolverEnv) ty1 (r: Typar) ty = let g = csenv.g let denv = csenv.DisplayEnv if not r.Rigidity.WarnIfUnified then CompleteD else @@ -716,7 +716,7 @@ let CheckWarnIfRigid (csenv:ConstraintSolverEnv) ty1 (r:Typar) ty = /// Add the constraint "ty1 = ty" to the constraint problem, where ty1 is a type variable. /// Propagate all effects of adding this constraint, e.g. to solve other variables -let rec SolveTyparEqualsType (csenv:ConstraintSolverEnv) ndeep m2 (trace:OptionalTrace) ty1 ty = trackErrors { +let rec SolveTyparEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTrace) ty1 ty = trackErrors { let m = csenv.m do! DepthCheck ndeep m match ty1 with @@ -748,7 +748,7 @@ let rec SolveTyparEqualsType (csenv:ConstraintSolverEnv) ndeep m2 (trace:Optiona /// Apply the constraints on 'typar' to the type 'ty' -and solveTypMeetsTyparConstraints (csenv:ConstraintSolverEnv) ndeep m2 trace ty (r: Typar) = trackErrors { +and solveTypMeetsTyparConstraints (csenv: ConstraintSolverEnv) ndeep m2 trace ty (r: Typar) = trackErrors { let g = csenv.g // Propagate compat flex requirements from 'tp' to 'ty' do! SolveTypIsCompatFlex csenv trace r.IsCompatFlex ty @@ -786,7 +786,7 @@ and solveTypMeetsTyparConstraints (csenv:ConstraintSolverEnv) ndeep m2 trace ty } -and SolveAnonInfoEqualsAnonInfo (csenv:ConstraintSolverEnv) m2 (anonInfo1: AnonRecdTypeInfo) (anonInfo2: AnonRecdTypeInfo) = +and SolveAnonInfoEqualsAnonInfo (csenv: ConstraintSolverEnv) m2 (anonInfo1: AnonRecdTypeInfo) (anonInfo2: AnonRecdTypeInfo) = if evalTupInfoIsStruct anonInfo1.TupInfo <> evalTupInfoIsStruct anonInfo2.TupInfo then ErrorD (ConstraintSolverError(FSComp.SR.tcTupleStructMismatch(), csenv.m,m2)) else (match anonInfo1.Assembly, anonInfo2.Assembly with | ccu1, ccu2 -> if not (ccuEq ccu1 ccu2) then ErrorD (ConstraintSolverError(FSComp.SR.tcAnonRecdCcuMismatch(ccu1.AssemblyName, ccu2.AssemblyName), csenv.m,m2)) else ResultD () @@ -800,7 +800,7 @@ and SolveAnonInfoEqualsAnonInfo (csenv:ConstraintSolverEnv) m2 (anonInfo1: AnonR /// Add the constraint "ty1 = ty2" to the constraint problem. /// Propagate all effects of adding this constraint, e.g. to solve type variables -and SolveTypeEqualsType (csenv:ConstraintSolverEnv) ndeep m2 (trace: OptionalTrace) (cxsln:(TraitConstraintInfo * TraitConstraintSln) option) ty1 ty2 = +and SolveTypeEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTrace) (cxsln:(TraitConstraintInfo * TraitConstraintSln) option) ty1 ty2 = let ndeep = ndeep + 1 let aenv = csenv.EquivEnv let g = csenv.g @@ -887,7 +887,7 @@ and SolveFunTypeEqn csenv ndeep m2 trace cxsln d1 d2 r1 r2 = trackErrors { // // "ty2 casts to ty1" // "a value of type ty2 can be used where a value of type ty1 is expected" -and SolveTypeSubsumesType (csenv:ConstraintSolverEnv) ndeep m2 (trace: OptionalTrace) cxsln ty1 ty2 = +and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTrace) cxsln ty1 ty2 = // 'a :> obj ---> let ndeep = ndeep + 1 let g = csenv.g @@ -992,7 +992,7 @@ and SolveTypeSubsumesTypeKeepAbbrevs csenv ndeep m2 trace cxsln ty1 ty2 = //------------------------------------------------------------------------- -and SolveTyparSubtypeOfType (csenv:ConstraintSolverEnv) ndeep m2 trace tp ty1 = +and SolveTyparSubtypeOfType (csenv: ConstraintSolverEnv) ndeep m2 trace tp ty1 = let g = csenv.g if isObjTy g ty1 then CompleteD elif typeEquiv g ty1 (mkTyparTy tp) then CompleteD @@ -1005,7 +1005,7 @@ and DepthCheck ndeep m = if ndeep > 300 then error(Error(FSComp.SR.csTypeInferenceMaxDepth(), m)) else CompleteD // If this is a type that's parameterized on a unit-of-measure (expected to be numeric), unify its measure with 1 -and SolveDimensionlessNumericType (csenv:ConstraintSolverEnv) ndeep m2 trace ty = +and SolveDimensionlessNumericType (csenv: ConstraintSolverEnv) ndeep m2 trace ty = match GetMeasureOfType csenv.g ty with | Some (tcref, _) -> SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace ty (mkAppTy tcref [TType_measure Measure.One]) @@ -1028,7 +1028,7 @@ and SolveDimensionlessNumericType (csenv:ConstraintSolverEnv) ndeep m2 trace ty /// permitWeakResolution also applies to resolutions of multi-type-variable constraints via method overloads. Method overloading gets applied even if /// only one of the two type variables is known /// -and SolveMemberConstraint (csenv:ConstraintSolverEnv) ignoreUnresolvedOverload permitWeakResolution ndeep m2 trace (TTrait(tys, nm, memFlags, argtys, rty, sln)): OperationResult = trackErrors { +and SolveMemberConstraint (csenv: ConstraintSolverEnv) ignoreUnresolvedOverload permitWeakResolution ndeep m2 trace (TTrait(tys, nm, memFlags, argtys, rty, sln)): OperationResult = trackErrors { // Do not re-solve if already solved if sln.Value.IsSome then return true else let g = csenv.g @@ -1388,7 +1388,7 @@ and SolveMemberConstraint (csenv:ConstraintSolverEnv) ignoreUnresolvedOverload p do! SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty rty2 return TTraitSolvedRecdProp(rfinfo, isSetProp) - | None, None, Some (calledMeth:CalledMeth<_>) -> + | None, None, Some (calledMeth: CalledMeth<_>) -> // OK, the constraint is solved. let minfo = calledMeth.Method @@ -1494,13 +1494,13 @@ and MemberConstraintSolutionOfMethInfo css m minfo minst = #endif /// Write into the reference cell stored in the TAST and add to the undo trace if necessary -and TransactMemberConstraintSolution traitInfo (trace:OptionalTrace) sln = +and TransactMemberConstraintSolution traitInfo (trace: OptionalTrace) sln = let prev = traitInfo.Solution trace.Exec (fun () -> traitInfo.Solution <- Some sln) (fun () -> traitInfo.Solution <- prev) /// Only consider overload resolution if canonicalizing or all the types are now nominal. /// That is, don't perform resolution if more nominal information may influence the set of available overloads -and GetRelevantMethodsForTrait (csenv:ConstraintSolverEnv) permitWeakResolution nm (TTrait(tys, _, memFlags, argtys, rty, soln) as traitInfo): MethInfo list = +and GetRelevantMethodsForTrait (csenv: ConstraintSolverEnv) permitWeakResolution nm (TTrait(tys, _, memFlags, argtys, rty, soln) as traitInfo): MethInfo list = let results = if permitWeakResolution || MemberConstraintSupportIsReadyForDeterminingOverloads csenv traitInfo then let m = csenv.m @@ -1532,20 +1532,20 @@ and GetRelevantMethodsForTrait (csenv:ConstraintSolverEnv) permitWeakResolution /// The nominal support of the member constraint -and GetSupportOfMemberConstraint (csenv:ConstraintSolverEnv) (TTrait(tys, _, _, _, _, _)) = +and GetSupportOfMemberConstraint (csenv: ConstraintSolverEnv) (TTrait(tys, _, _, _, _, _)) = tys |> List.choose (tryAnyParTyOption csenv.g) /// Check if the support is fully solved. -and SupportOfMemberConstraintIsFullySolved (csenv:ConstraintSolverEnv) (TTrait(tys, _, _, _, _, _)) = +and SupportOfMemberConstraintIsFullySolved (csenv: ConstraintSolverEnv) (TTrait(tys, _, _, _, _, _)) = tys |> List.forall (isAnyParTy csenv.g >> not) // This may be relevant to future bug fixes, see https://github.com/Microsoft/visualfsharp/issues/3814 // /// Check if some part of the support is solved. -// and SupportOfMemberConstraintIsPartiallySolved (csenv:ConstraintSolverEnv) (TTrait(tys, _, _, _, _, _)) = +// and SupportOfMemberConstraintIsPartiallySolved (csenv: ConstraintSolverEnv) (TTrait(tys, _, _, _, _, _)) = // tys |> List.exists (isAnyParTy csenv.g >> not) /// Get all the unsolved typars (statically resolved or not) relevant to the member constraint -and GetFreeTyparsOfMemberConstraint (csenv:ConstraintSolverEnv) (TTrait(tys, _, _, argtys, rty, _)) = +and GetFreeTyparsOfMemberConstraint (csenv: ConstraintSolverEnv) (TTrait(tys, _, _, argtys, rty, _)) = freeInTypesLeftToRightSkippingConstraints csenv.g (tys@argtys@ Option.toList rty) and MemberConstraintIsReadyForWeakResolution csenv traitInfo = @@ -1560,7 +1560,7 @@ and MemberConstraintSupportIsReadyForDeterminingOverloads csenv traitInfo = /// Re-solve the global constraints involving any of the given type variables. /// Trait constraints can't always be solved using the pessimistic rules. We only canonicalize /// them forcefully (permitWeakResolution=true) prior to generalization. -and SolveRelevantMemberConstraints (csenv:ConstraintSolverEnv) ndeep permitWeakResolution trace tps = +and SolveRelevantMemberConstraints (csenv: ConstraintSolverEnv) ndeep permitWeakResolution trace tps = RepeatWhileD ndeep (fun ndeep -> tps @@ -1573,7 +1573,7 @@ and SolveRelevantMemberConstraints (csenv:ConstraintSolverEnv) ndeep permitWeakR | ValueNone -> ResultD false)) -and SolveRelevantMemberConstraintsForTypar (csenv:ConstraintSolverEnv) ndeep permitWeakResolution (trace:OptionalTrace) tp = +and SolveRelevantMemberConstraintsForTypar (csenv: ConstraintSolverEnv) ndeep permitWeakResolution (trace: OptionalTrace) tp = let cxst = csenv.SolverState.ExtraCxs let tpn = tp.Stamp let cxs = cxst.FindAll tpn @@ -1587,10 +1587,10 @@ and SolveRelevantMemberConstraintsForTypar (csenv:ConstraintSolverEnv) ndeep per let csenv = { csenv with m = m2 } SolveMemberConstraint csenv true permitWeakResolution (ndeep+1) m2 trace traitInfo) -and CanonicalizeRelevantMemberConstraints (csenv:ConstraintSolverEnv) ndeep trace tps = +and CanonicalizeRelevantMemberConstraints (csenv: ConstraintSolverEnv) ndeep trace tps = SolveRelevantMemberConstraints csenv ndeep true trace tps -and AddMemberConstraint (csenv:ConstraintSolverEnv) ndeep m2 trace traitInfo support frees = +and AddMemberConstraint (csenv: ConstraintSolverEnv) ndeep m2 trace traitInfo support frees = let g = csenv.g let aenv = csenv.EquivEnv let cxst = csenv.SolverState.ExtraCxs @@ -1618,7 +1618,7 @@ and AddMemberConstraint (csenv:ConstraintSolverEnv) ndeep m2 trace traitInfo sup /// Record a constraint on an inference type variable. -and AddConstraint (csenv:ConstraintSolverEnv) ndeep m2 trace tp newConstraint = +and AddConstraint (csenv: ConstraintSolverEnv) ndeep m2 trace tp newConstraint = let g = csenv.g let aenv = csenv.EquivEnv let amap = csenv.amap @@ -1788,7 +1788,7 @@ and AddConstraint (csenv:ConstraintSolverEnv) ndeep m2 trace tp newConstraint = } -and SolveTypeSupportsNull (csenv:ConstraintSolverEnv) ndeep m2 trace ty = +and SolveTypeSupportsNull (csenv: ConstraintSolverEnv) ndeep m2 trace ty = let g = csenv.g let m = csenv.m let denv = csenv.DisplayEnv @@ -1803,7 +1803,7 @@ and SolveTypeSupportsNull (csenv:ConstraintSolverEnv) ndeep m2 trace ty = | _ -> ErrorD (ConstraintSolverError(FSComp.SR.csTypeDoesNotHaveNull(NicePrint.minimalStringOfType denv ty), m, m2)) -and SolveTypeSupportsComparison (csenv:ConstraintSolverEnv) ndeep m2 trace ty = +and SolveTypeSupportsComparison (csenv: ConstraintSolverEnv) ndeep m2 trace ty = let g = csenv.g let m = csenv.m let amap = csenv.amap @@ -1819,7 +1819,7 @@ and SolveTypeSupportsComparison (csenv:ConstraintSolverEnv) ndeep m2 trace ty = | _ -> match ty with | SpecialComparableHeadType g tinst -> - tinst |> IterateD (SolveTypeSupportsComparison (csenv:ConstraintSolverEnv) ndeep m2 trace) + tinst |> IterateD (SolveTypeSupportsComparison (csenv: ConstraintSolverEnv) ndeep m2 trace) | _ -> // Check the basic requirement - IComparable or IStructuralComparable or assumed if ExistsSameHeadTypeInHierarchy g amap m2 ty g.mk_IComparable_ty || @@ -1831,7 +1831,7 @@ and SolveTypeSupportsComparison (csenv:ConstraintSolverEnv) ndeep m2 trace ty = // Check the (possibly inferred) structural dependencies (tinst, tcref.TyparsNoRange) ||> Iterate2D (fun ty tp -> if tp.ComparisonConditionalOn then - SolveTypeSupportsComparison (csenv:ConstraintSolverEnv) ndeep m2 trace ty + SolveTypeSupportsComparison (csenv: ConstraintSolverEnv) ndeep m2 trace ty else CompleteD) | _ -> @@ -1848,7 +1848,7 @@ and SolveTypeSupportsComparison (csenv:ConstraintSolverEnv) ndeep m2 trace ty = else ErrorD (ConstraintSolverError(FSComp.SR.csTypeDoesNotSupportComparison2(NicePrint.minimalStringOfType denv ty), m, m2)) -and SolveTypeSupportsEquality (csenv:ConstraintSolverEnv) ndeep m2 trace ty = +and SolveTypeSupportsEquality (csenv: ConstraintSolverEnv) ndeep m2 trace ty = let g = csenv.g let m = csenv.m let denv = csenv.DisplayEnv @@ -1862,7 +1862,7 @@ and SolveTypeSupportsEquality (csenv:ConstraintSolverEnv) ndeep m2 trace ty = | _ -> match ty with | SpecialEquatableHeadType g tinst -> - tinst |> IterateD (SolveTypeSupportsEquality (csenv:ConstraintSolverEnv) ndeep m2 trace) + tinst |> IterateD (SolveTypeSupportsEquality (csenv: ConstraintSolverEnv) ndeep m2 trace) | SpecialNotEquatableHeadType g _ -> ErrorD (ConstraintSolverError(FSComp.SR.csTypeDoesNotSupportEquality2(NicePrint.minimalStringOfType denv ty), m, m2)) | _ -> @@ -1878,13 +1878,13 @@ and SolveTypeSupportsEquality (csenv:ConstraintSolverEnv) ndeep m2 trace ty = // Check the (possibly inferred) structural dependencies (tinst, tcref.TyparsNoRange) ||> Iterate2D (fun ty tp -> if tp.EqualityConditionalOn then - SolveTypeSupportsEquality (csenv:ConstraintSolverEnv) ndeep m2 trace ty + SolveTypeSupportsEquality (csenv: ConstraintSolverEnv) ndeep m2 trace ty else CompleteD) | _ -> CompleteD -and SolveTypeIsEnum (csenv:ConstraintSolverEnv) ndeep m2 trace ty underlying = +and SolveTypeIsEnum (csenv: ConstraintSolverEnv) ndeep m2 trace ty underlying = trackErrors { let g = csenv.g let m = csenv.m @@ -1900,7 +1900,7 @@ and SolveTypeIsEnum (csenv:ConstraintSolverEnv) ndeep m2 trace ty underlying = return! ErrorD (ConstraintSolverError(FSComp.SR.csTypeIsNotEnumType(NicePrint.minimalStringOfType denv ty), m, m2)) } -and SolveTypeIsDelegate (csenv:ConstraintSolverEnv) ndeep m2 trace ty aty bty = +and SolveTypeIsDelegate (csenv: ConstraintSolverEnv) ndeep m2 trace ty aty bty = trackErrors { let g = csenv.g let m = csenv.m @@ -1920,7 +1920,7 @@ and SolveTypeIsDelegate (csenv:ConstraintSolverEnv) ndeep m2 trace ty aty bty = return! ErrorD (ConstraintSolverError(FSComp.SR.csTypeIsNotDelegateType(NicePrint.minimalStringOfType denv ty), m, m2)) } -and SolveTypeIsNonNullableValueType (csenv:ConstraintSolverEnv) ndeep m2 trace ty = +and SolveTypeIsNonNullableValueType (csenv: ConstraintSolverEnv) ndeep m2 trace ty = trackErrors { let g = csenv.g let m = csenv.m @@ -1937,7 +1937,7 @@ and SolveTypeIsNonNullableValueType (csenv:ConstraintSolverEnv) ndeep m2 trace t return! ErrorD (ConstraintSolverError(FSComp.SR.csGenericConstructRequiresStructType(NicePrint.minimalStringOfType denv ty), m, m2)) } -and SolveTypeIsUnmanaged (csenv:ConstraintSolverEnv) ndeep m2 trace ty = +and SolveTypeIsUnmanaged (csenv: ConstraintSolverEnv) ndeep m2 trace ty = let g = csenv.g let m = csenv.m let denv = csenv.DisplayEnv @@ -1951,7 +1951,7 @@ and SolveTypeIsUnmanaged (csenv:ConstraintSolverEnv) ndeep m2 trace ty = ErrorD (ConstraintSolverError(FSComp.SR.csGenericConstructRequiresUnmanagedType(NicePrint.minimalStringOfType denv ty), m, m2)) -and SolveTypeChoice (csenv:ConstraintSolverEnv) ndeep m2 trace ty tys = +and SolveTypeChoice (csenv: ConstraintSolverEnv) ndeep m2 trace ty tys = let g = csenv.g let m = csenv.m let denv = csenv.DisplayEnv @@ -1963,7 +1963,7 @@ and SolveTypeChoice (csenv:ConstraintSolverEnv) ndeep m2 trace ty tys = else ErrorD (ConstraintSolverError(FSComp.SR.csTypeNotCompatibleBecauseOfPrintf((NicePrint.minimalStringOfType denv ty), (String.concat "," (List.map (NicePrint.prettyStringOfTy denv) tys))), m, m2)) -and SolveTypeIsReferenceType (csenv:ConstraintSolverEnv) ndeep m2 trace ty = +and SolveTypeIsReferenceType (csenv: ConstraintSolverEnv) ndeep m2 trace ty = let g = csenv.g let m = csenv.m let denv = csenv.DisplayEnv @@ -1974,7 +1974,7 @@ and SolveTypeIsReferenceType (csenv:ConstraintSolverEnv) ndeep m2 trace ty = if isRefTy g ty then CompleteD else ErrorD (ConstraintSolverError(FSComp.SR.csGenericConstructRequiresReferenceSemantics(NicePrint.minimalStringOfType denv ty), m, m)) -and SolveTypeRequiresDefaultConstructor (csenv:ConstraintSolverEnv) ndeep m2 trace origTy = +and SolveTypeRequiresDefaultConstructor (csenv: ConstraintSolverEnv) ndeep m2 trace origTy = let g = csenv.g let amap = csenv.amap let m = csenv.m @@ -2008,14 +2008,14 @@ and SolveTypeRequiresDefaultConstructor (csenv:ConstraintSolverEnv) ndeep m2 tra // Parameterized compatibility relation between member signatures. The real work // is done by "equateTypes" and "subsumeTypes" and "subsumeArg" and CanMemberSigsMatchUpToCheck - (csenv:ConstraintSolverEnv) + (csenv: ConstraintSolverEnv) permitOptArgs // are we allowed to supply optional and/or "param" arguments? alwaysCheckReturn // always check the return type? unifyTypes // used to equate the formal method instantiation with the actual method instantiation for a generic method, and the return types subsumeTypes // used to compare the "obj" type (subsumeArg: CalledArg -> CallerArg<_> -> OperationResult) // used to compare the arguments for compatibility reqdRetTyOpt - (calledMeth:CalledMeth<_>): ImperativeOperationResult = + (calledMeth: CalledMeth<_>): ImperativeOperationResult = trackErrors { let g = csenv.g let amap = csenv.amap @@ -2104,7 +2104,7 @@ and CanMemberSigsMatchUpToCheck // // "ty2 casts to ty1" // "a value of type ty2 can be used where a value of type ty1 is expected" -and private SolveTypeSubsumesTypeWithReport (csenv:ConstraintSolverEnv) ndeep m trace cxsln ty1 ty2 = +and private SolveTypeSubsumesTypeWithReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln ty1 ty2 = TryD (fun () -> SolveTypeSubsumesTypeKeepAbbrevs csenv ndeep m trace cxsln ty1 ty2) (function | LocallyAbortOperationThatFailsToResolveOverload -> CompleteD @@ -2119,14 +2119,14 @@ and private SolveTypeSubsumesTypeWithReport (csenv:ConstraintSolverEnv) ndeep m // ty1: actual // ty2: expected -and private SolveTypeEqualsTypeWithReport (csenv:ConstraintSolverEnv) ndeep m trace cxsln actual expected = +and private SolveTypeEqualsTypeWithReport (csenv: ConstraintSolverEnv) ndeep m trace cxsln actual expected = TryD (fun () -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m trace cxsln actual expected) (function | LocallyAbortOperationThatFailsToResolveOverload -> CompleteD | res -> ErrorD (ErrorFromAddingTypeEquation(csenv.g, csenv.DisplayEnv, actual, expected, res, m))) and ArgsMustSubsumeOrConvert - (csenv:ConstraintSolverEnv) + (csenv: ConstraintSolverEnv) ndeep trace cxsln @@ -2149,18 +2149,18 @@ and MustUnify csenv ndeep trace cxsln ty1 ty2 = and MustUnifyInsideUndo csenv ndeep trace cxsln ty1 ty2 = SolveTypeEqualsTypeWithReport csenv ndeep csenv.m (WithTrace trace) cxsln ty1 ty2 -and ArgsMustSubsumeOrConvertInsideUndo (csenv:ConstraintSolverEnv) ndeep trace cxsln isConstraint calledArg (CallerArg(callerArgTy, m, _, _) as callerArg) = +and ArgsMustSubsumeOrConvertInsideUndo (csenv: ConstraintSolverEnv) ndeep trace cxsln isConstraint calledArg (CallerArg(callerArgTy, m, _, _) as callerArg) = let calledArgTy = AdjustCalledArgType csenv.InfoReader isConstraint calledArg callerArg SolveTypeSubsumesTypeWithReport csenv ndeep m (WithTrace trace) cxsln calledArgTy callerArgTy -and TypesMustSubsumeOrConvertInsideUndo (csenv:ConstraintSolverEnv) ndeep trace cxsln m calledArgTy callerArgTy = +and TypesMustSubsumeOrConvertInsideUndo (csenv: ConstraintSolverEnv) ndeep trace cxsln m calledArgTy callerArgTy = SolveTypeSubsumesTypeWithReport csenv ndeep m trace cxsln calledArgTy callerArgTy -and ArgsEquivInsideUndo (csenv:ConstraintSolverEnv) isConstraint calledArg (CallerArg(callerArgTy, m, _, _) as callerArg) = +and ArgsEquivInsideUndo (csenv: ConstraintSolverEnv) isConstraint calledArg (CallerArg(callerArgTy, m, _, _) as callerArg) = let calledArgTy = AdjustCalledArgType csenv.InfoReader isConstraint calledArg callerArg if typeEquiv csenv.g calledArgTy callerArgTy then CompleteD else ErrorD(Error(FSComp.SR.csArgumentTypesDoNotMatch(), m)) -and ReportNoCandidatesError (csenv:ConstraintSolverEnv) (nUnnamedCallerArgs, nNamedCallerArgs) methodName ad (calledMethGroup:CalledMeth<_> list) isSequential = +and ReportNoCandidatesError (csenv: ConstraintSolverEnv) (nUnnamedCallerArgs, nNamedCallerArgs) methodName ad (calledMethGroup: CalledMeth<_> list) isSequential = let amap = csenv.amap let m = csenv.m @@ -2285,7 +2285,7 @@ and ReportNoCandidatesErrorSynExpr csenv callerArgCounts methodName ad calledMet // Resolve the overloading of a method // This is used after analyzing the types of arguments and ResolveOverloading - (csenv:ConstraintSolverEnv) + (csenv: ConstraintSolverEnv) trace // The undo trace, if any methodName // The name of the method being called, for error reporting ndeep // Depth of inference @@ -2417,7 +2417,7 @@ and ResolveOverloading (ty1, ty2) ||> compareCond (fun x1 x2 -> TypeFeasiblySubsumesType ndeep csenv.g csenv.amap m x2 CanCoerce x1) /// Compare arguments under the feasibly-subsumes ordering and the adhoc Func-is-better-than-other-delegates rule - let compareArg (calledArg1:CalledArg) (calledArg2:CalledArg) = + let compareArg (calledArg1: CalledArg) (calledArg2: CalledArg) = let c = compareTypes calledArg1.CalledArgumentType calledArg2.CalledArgumentType if c <> 0 then c else @@ -2441,7 +2441,7 @@ and ResolveOverloading if c <> 0 then c else 0 - let better (candidate:CalledMeth<_>, candidateWarnings, _) (other:CalledMeth<_>, otherwarnings, _) = + let better (candidate: CalledMeth<_>, candidateWarnings, _) (other: CalledMeth<_>, otherwarnings, _) = let candidateWarnCount = List.length candidateWarnings let otherWarnCount = List.length otherwarnings // Prefer methods that don't give "this code is less generic" warnings @@ -2603,11 +2603,11 @@ and ResolveOverloading /// This is used before analyzing the types of arguments in a single overload resolution let UnifyUniqueOverloading - (csenv:ConstraintSolverEnv) + (csenv: ConstraintSolverEnv) callerArgCounts methodName ad - (calledMethGroup:CalledMeth list) + (calledMethGroup: CalledMeth list) reqdRetTy // The expected return type, if known = let m = csenv.m @@ -2639,7 +2639,7 @@ let UnifyUniqueOverloading | _ -> ResultD false -let EliminateConstraintsForGeneralizedTypars csenv (trace:OptionalTrace) (generalizedTypars: Typars) = +let EliminateConstraintsForGeneralizedTypars csenv (trace: OptionalTrace) (generalizedTypars: Typars) = // Remove the global constraints where this type variable appears in the support of the constraint generalizedTypars |> List.iter (fun tp -> @@ -2752,7 +2752,7 @@ let AddCxTypeIsDelegate denv css m trace ty aty bty = (fun res -> ErrorD (ErrorFromAddingConstraint(denv, res, m))) |> RaiseOperationResult -let CodegenWitnessThatTypeSupportsTraitConstraint tcVal g amap m (traitInfo:TraitConstraintInfo) argExprs = trackErrors { +let CodegenWitnessThatTypeSupportsTraitConstraint tcVal g amap m (traitInfo: TraitConstraintInfo) argExprs = trackErrors { let css = { g = g amap = amap @@ -2881,7 +2881,7 @@ let CheckDeclaredTypars denv css m typars1 typars2 = /// An approximation used during name resolution for intellisense to eliminate extension members which will not /// apply to a particular object argument. This is given as the isApplicableMeth argument to the partial name resolution /// functions in nameres.fs. -let IsApplicableMethApprox g amap m (minfo:MethInfo) availObjTy = +let IsApplicableMethApprox g amap m (minfo: MethInfo) availObjTy = // Prepare an instance of a constraint solver // If it's an instance method, then try to match the object argument against the required object argument if minfo.IsExtensionMember then diff --git a/src/fsharp/DetupleArgs.fs b/src/fsharp/DetupleArgs.fs index 160c0e66526..67f5f43d617 100644 --- a/src/fsharp/DetupleArgs.fs +++ b/src/fsharp/DetupleArgs.fs @@ -201,7 +201,7 @@ module GlobalUsageAnalysis = /// Log the use of a value with a particular tuple chape at a callsite /// Note: this routine is called very frequently - let logUse (f:Val) tup z = + let logUse (f: Val) tup z = {z with Uses = match Zmap.tryFind f z.Uses with | Some sites -> Zmap.add f (tup::sites) z.Uses @@ -215,7 +215,7 @@ module GlobalUsageAnalysis = /// Log the definition of a non-recursive binding - let logNonRecBinding z (bind:Binding) = + let logNonRecBinding z (bind: Binding) = let v = bind.Var let vs = [v] {z with RecursiveBindings = Zmap.add v (false, vs) z.RecursiveBindings @@ -453,7 +453,7 @@ type Transform = // transform - mkTransform - decided, create necessary stuff //------------------------------------------------------------------------- -let mkTransform g (f:Val) m tps x1Ntys rty (callPattern, tyfringes: (TType list * Val list) list) = +let mkTransform g (f: Val) m tps x1Ntys rty (callPattern, tyfringes: (TType list * Val list) list) = // Create formal choices for x1...xp under callPattern let transformedFormals = (callPattern, tyfringes) ||> List.map2 (fun cpi (tyfringe, vs) -> @@ -522,7 +522,7 @@ let zipCallPatternArgTys m g (callPattern : TupleStructure list) (vss : Val list // transform - vTransforms - defnSuggestedCP //------------------------------------------------------------------------- -/// v = LAM tps. lam vs1:ty1 ... vsN:tyN. body. +/// v = LAM tps. lam vs1: ty1 ... vsN: tyN. body. /// The types suggest a tuple structure CallPattern. /// The buildProjections of the vsi trim this down, /// since do not want to take as components any tuple that is required (projected to). @@ -559,7 +559,7 @@ let decideFormalSuggestedCP g z tys vss = // transform - decideTransform //------------------------------------------------------------------------- -let decideTransform g z v callPatterns (m, tps, vss:Val list list, rty) = +let decideTransform g z v callPatterns (m, tps, vss: Val list list, rty) = let tys = List.map (typeOfLambdaArg m) vss (* arg types *) (* NOTE: 'a in arg types may have been instanced at different tuples... *) (* commonCallPattern has to handle those cases. *) @@ -587,7 +587,7 @@ let decideTransform g z v callPatterns (m, tps, vss:Val list list, rty) = // Public f could be used beyond assembly. // For now, suppressing any transforms on these. // Later, could transform f and fix up local calls and provide an f wrapper for beyond. -let eligibleVal g m (v:Val) = +let eligibleVal g m (v: Val) = let dllImportStubOrOtherNeverInline = (v.InlineInfo = ValInline.Never) let mutableVal = v.IsMutable let byrefVal = isByrefLikeTy g m v.Type @@ -679,7 +679,7 @@ let buildProjections env bindings x xtys = let bindings = pushL (List.rev binds) bindings bindings, vixs -let rec collapseArg env bindings ts (x:Expr) = +let rec collapseArg env bindings ts (x: Expr) = let m = x.Range let env = rangeE env m match ts, x with @@ -715,10 +715,10 @@ and collapseArgs env bindings n (callPattern) args = //------------------------------------------------------------------------- // REVIEW: use mkLet etc. -let mkLets binds (body:Expr) = +let mkLets binds (body: Expr) = (binds, body) ||> List.foldBack (fun b acc -> mkLetBind acc.Range b acc) -let fixupApp (penv:penv) (fx, fty, tys, args, m) = +let fixupApp (penv: penv) (fx, fty, tys, args, m) = // Is it a val app, where the val has a transform? match fx with @@ -820,7 +820,7 @@ let passBinds penv binds = binds |> List.map (passBind penv) let passBindRhs conv (TBind (v, repr, letSeqPtOpt)) = TBind(v, conv repr, letSeqPtOpt) -let preInterceptExpr (penv:penv) conv expr = +let preInterceptExpr (penv: penv) conv expr = match expr with | Expr.LetRec (binds, e, m, _) -> let binds = List.map (passBindRhs conv) binds @@ -837,8 +837,7 @@ let preInterceptExpr (penv:penv) conv expr = Some (fixupApp penv (f, fty, tys, args, m) ) | _ -> None - -let postTransformExpr (penv:penv) expr = +let postTransformExpr (penv: penv) expr = match expr with | Expr.LetRec (binds, e, m, _) -> let binds = passBinds penv binds diff --git a/src/fsharp/ExtensionTyping.fs b/src/fsharp/ExtensionTyping.fs index ce02e3a53e3..16e83147d1b 100755 --- a/src/fsharp/ExtensionTyping.fs +++ b/src/fsharp/ExtensionTyping.fs @@ -62,10 +62,10 @@ module internal ExtensionTyping = /// Load a the design-time part of a type-provider into the host process, and look for types /// marked with the TypeProviderAttribute attribute. - let GetTypeProviderImplementationTypes (runTimeAssemblyFileName, designTimeAssemblyNameString, m:range) = + let GetTypeProviderImplementationTypes (runTimeAssemblyFileName, designTimeAssemblyNameString, m: range) = // Report an error, blaming the particular type provider component - let raiseError (e:exn) = + let raiseError (e: exn) = raise (TypeProviderError(FSComp.SR.etProviderHasWrongDesignerAssembly(typeof.Name, designTimeAssemblyNameString, e.Message), runTimeAssemblyFileName, m)) // Find and load the designer assembly for the type provider component. @@ -138,7 +138,7 @@ module internal ExtensionTyping = raiseError e | None -> [] - let StripException (e:exn) = + let StripException (e: exn) = match e with #if !FX_REDUCED_EXCEPTIONS | :? System.Reflection.TargetInvocationException as e -> e.InnerException @@ -148,11 +148,11 @@ module internal ExtensionTyping = /// Create an instance of a type provider from the implementation type for the type provider in the /// design-time assembly by using reflection-invoke on a constructor for the type provider. - let CreateTypeProvider (typeProviderImplementationType:System.Type, + let CreateTypeProvider (typeProviderImplementationType: System.Type, runtimeAssemblyPath, - resolutionEnvironment:ResolutionEnvironment, - isInvalidationSupported:bool, - isInteractive:bool, + resolutionEnvironment: ResolutionEnvironment, + isInvalidationSupported: bool, + isInteractive: bool, systemRuntimeContainsType, systemRuntimeAssemblyVersion, m) = @@ -188,15 +188,15 @@ module internal ExtensionTyping = raise (TypeProviderError(FSComp.SR.etProviderDoesNotHaveValidConstructor(), typeProviderImplementationType.FullName, m)) let GetTypeProvidersOfAssembly - (runTimeAssemblyFileName:string, - ilScopeRefOfRuntimeAssembly:ILScopeRef, - designTimeAssemblyNameString:string, - resolutionEnvironment:ResolutionEnvironment, - isInvalidationSupported:bool, - isInteractive:bool, + (runTimeAssemblyFileName: string, + ilScopeRefOfRuntimeAssembly: ILScopeRef, + designTimeAssemblyNameString: string, + resolutionEnvironment: ResolutionEnvironment, + isInvalidationSupported: bool, + isInteractive: bool, systemRuntimeContainsType : string -> bool, systemRuntimeAssemblyVersion : System.Version, - m:range) = + m: range) = let providerSpecs = try @@ -232,10 +232,10 @@ module internal ExtensionTyping = providers - let unmarshal (t:Tainted<_>) = t.PUntaintNoFailure id + let unmarshal (t: Tainted<_>) = t.PUntaintNoFailure id /// Try to access a member on a provided type, catching and reporting errors - let TryTypeMember(st:Tainted<_>, fullName, memberName, m, recover, f) = + let TryTypeMember(st: Tainted<_>, fullName, memberName, m, recover, f) = try st.PApply (f, m) with :? TypeProviderError as tpe -> @@ -243,7 +243,7 @@ module internal ExtensionTyping = st.PApplyNoFailure(fun _ -> recover) /// Try to access a member on a provided type, where the result is an array of values, catching and reporting errors - let TryTypeMemberArray (st:Tainted<_>, fullName, memberName, m, f) = + let TryTypeMemberArray (st: Tainted<_>, fullName, memberName, m, f) = let result = try st.PApplyArray(f, memberName, m) @@ -256,7 +256,7 @@ module internal ExtensionTyping = | r -> r /// Try to access a member on a provided type, catching and reporting errors and checking the result is non-null, - let TryTypeMemberNonNull (st:Tainted<_>, fullName, memberName, m, recover, f) = + let TryTypeMemberNonNull (st: Tainted<_>, fullName, memberName, m, recover, f) = match TryTypeMember(st, fullName, memberName, m, recover, f) with | Tainted.Null -> errorR(Error(FSComp.SR.etUnexpectedNullFromProvidedTypeMember(fullName, memberName), m)); @@ -264,7 +264,7 @@ module internal ExtensionTyping = | r -> r /// Try to access a property or method on a provided member, catching and reporting errors - let TryMemberMember (mi:Tainted<_>, typeName, memberName, memberMemberName, m, recover, f) = + let TryMemberMember (mi: Tainted<_>, typeName, memberName, memberMemberName, m, recover, f) = try mi.PApply (f, m) with :? TypeProviderError as tpe -> @@ -272,11 +272,11 @@ module internal ExtensionTyping = mi.PApplyNoFailure(fun _ -> recover) /// Get the string to show for the name of a type provider - let DisplayNameOfTypeProvider(resolver:Tainted, m:range) = + let DisplayNameOfTypeProvider(resolver: Tainted, m: range) = resolver.PUntaint((fun tp -> tp.GetType().Name), m) /// Validate a provided namespace name - let ValidateNamespaceName(name, typeProvider:Tainted, m, nsp:string) = + let ValidateNamespaceName(name, typeProvider: Tainted, m, nsp: string) = if nsp<>null then // Null namespace designates the global namespace. if String.IsNullOrWhiteSpace nsp then // Empty namespace is not allowed @@ -304,10 +304,10 @@ module internal ExtensionTyping = // to preserve object identity when presenting the types to the F# compiler. let providedSystemTypeComparer = - let key (ty:System.Type) = (ty.Assembly.FullName, ty.FullName) + let key (ty: System.Type) = (ty.Assembly.FullName, ty.FullName) { new IEqualityComparer with - member __.GetHashCode(ty:Type) = hash (key ty) - member __.Equals(ty1:Type, ty2:Type) = (key ty1 = key ty2) } + member __.GetHashCode(ty: Type) = hash (key ty) + member __.Equals(ty1: Type, ty2: Type) = (key ty1 = key ty2) } /// The context used to interpret information in the closure of System.Type, System.MethodInfo and other /// info objects coming from the type provider. @@ -347,7 +347,7 @@ module internal ExtensionTyping = let mutable res = Unchecked.defaultof<_> if d.TryGetValue(st, &res) then Some res else None - member ctxt.RemapTyconRefs (f:obj->obj) = + member ctxt.RemapTyconRefs (f: obj->obj) = match ctxt with | NoEntries -> NoEntries | Entries(d1, d2) -> @@ -360,7 +360,7 @@ module internal ExtensionTyping = type CustomAttributeTypedArgument = System.Reflection.CustomAttributeTypedArgument [] - type ProvidedType (x:System.Type, ctxt: ProvidedTypeContext) = + type ProvidedType (x: System.Type, ctxt: ProvidedTypeContext) = inherit ProvidedMemberInfo(x, ctxt) let provide () = ProvidedCustomAttributeProvider.Create (fun _provider -> x.CustomAttributes) interface IProvidedCustomAttributeProvider with @@ -426,7 +426,7 @@ module internal ExtensionTyping = static member Create ctxt x = match x with null -> null | t -> ProvidedType (t, ctxt) static member CreateWithNullCheck ctxt name x = match x with null -> nullArg name | t -> ProvidedType (t, ctxt) static member CreateArray ctxt xs = match xs with null -> null | _ -> xs |> Array.map (ProvidedType.Create ctxt) - static member CreateNoContext (x:Type) = ProvidedType.Create ProvidedTypeContext.Empty x + static member CreateNoContext (x: Type) = ProvidedType.Create ProvidedTypeContext.Empty x static member Void = ProvidedType.CreateNoContext typeof member __.Handle = x override __.Equals y = assert false; match y with :? ProvidedType as y -> x.Equals y.Handle | _ -> false @@ -434,23 +434,23 @@ module internal ExtensionTyping = member __.TryGetILTypeRef() = ctxt.TryGetILTypeRef x member __.TryGetTyconRef() = ctxt.TryGetTyconRef x member __.Context = ctxt - static member ApplyContext (pt:ProvidedType, ctxt) = ProvidedType(pt.Handle, ctxt) - static member TaintedEquals (pt1:Tainted, pt2:Tainted) = + static member ApplyContext (pt: ProvidedType, ctxt) = ProvidedType(pt.Handle, ctxt) + static member TaintedEquals (pt1: Tainted, pt2: Tainted) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) and [] IProvidedCustomAttributeProvider = - abstract GetDefinitionLocationAttribute : provider:ITypeProvider -> (string * int * int) option - abstract GetXmlDocAttributes : provider:ITypeProvider -> string[] - abstract GetHasTypeProviderEditorHideMethodsAttribute : provider:ITypeProvider -> bool - abstract GetAttributeConstructorArgs: provider:ITypeProvider * attribName:string -> (obj option list * (string * obj option) list) option + abstract GetDefinitionLocationAttribute : provider: ITypeProvider -> (string * int * int) option + abstract GetXmlDocAttributes : provider: ITypeProvider -> string[] + abstract GetHasTypeProviderEditorHideMethodsAttribute : provider: ITypeProvider -> bool + abstract GetAttributeConstructorArgs: provider: ITypeProvider * attribName: string -> (obj option list * (string * obj option) list) option and ProvidedCustomAttributeProvider = static member Create (attributes :(ITypeProvider -> seq)) : IProvidedCustomAttributeProvider = - let (|Member|_|) (s:string) (x: CustomAttributeNamedArgument) = if x.MemberName = s then Some x.TypedValue else None + let (|Member|_|) (s: string) (x: CustomAttributeNamedArgument) = if x.MemberName = s then Some x.TypedValue else None let (|Arg|_|) (x: CustomAttributeTypedArgument) = match x.Value with null -> None | v -> Some v - let findAttribByName tyFullName (a:CustomAttributeData) = (a.Constructor.DeclaringType.FullName = tyFullName) - let findAttrib (ty:System.Type) a = findAttribByName ty.FullName a + let findAttribByName tyFullName (a: CustomAttributeData) = (a.Constructor.DeclaringType.FullName = tyFullName) + let findAttrib (ty: System.Type) a = findAttribByName ty.FullName a { new IProvidedCustomAttributeProvider with member __.GetAttributeConstructorArgs (provider, attribName) = attributes(provider) @@ -551,9 +551,9 @@ module internal ExtensionTyping = member __.GetParameters() = x.GetParameters() |> ProvidedParameterInfo.CreateArray ctxt member __.GetGenericArguments() = x.GetGenericArguments() |> ProvidedType.CreateArray ctxt member __.Handle = x - static member TaintedGetHashCode (x:Tainted) = + static member TaintedGetHashCode (x: Tainted) = Tainted.GetHashCodeTainted (x.PApplyNoFailure(fun st -> (st.Name, st.DeclaringType.Assembly.FullName, st.DeclaringType.FullName))) - static member TaintedEquals (pt1:Tainted, pt2:Tainted) = + static member TaintedEquals (pt1: Tainted, pt2: Tainted) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) member __.GetStaticParametersForMethod(provider: ITypeProvider) = @@ -574,7 +574,7 @@ module internal ExtensionTyping = staticParams |> ProvidedParameterInfo.CreateArray ctxt - member __.ApplyStaticArgumentsForMethod(provider: ITypeProvider, fullNameAfterArguments:string, staticArgs: obj[]) = + member __.ApplyStaticArgumentsForMethod(provider: ITypeProvider, fullNameAfterArguments: string, staticArgs: obj[]) = let bindingFlags = BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.InvokeMethod let mb = @@ -620,7 +620,7 @@ module internal ExtensionTyping = member __.IsFamilyAndAssembly = x.IsFamilyAndAssembly override __.Equals y = assert false; match y with :? ProvidedFieldInfo as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = assert false; x.GetHashCode() - static member TaintedEquals (pt1:Tainted, pt2:Tainted) = + static member TaintedEquals (pt1: Tainted, pt2: Tainted) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) @@ -656,9 +656,9 @@ module internal ExtensionTyping = member __.Handle = x override __.Equals y = assert false; match y with :? ProvidedPropertyInfo as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = assert false; x.GetHashCode() - static member TaintedGetHashCode (x:Tainted) = + static member TaintedGetHashCode (x: Tainted) = Tainted.GetHashCodeTainted (x.PApplyNoFailure(fun st -> (st.Name, st.DeclaringType.Assembly.FullName, st.DeclaringType.FullName))) - static member TaintedEquals (pt1:Tainted, pt2:Tainted) = + static member TaintedEquals (pt1: Tainted, pt2: Tainted) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) and [] @@ -673,9 +673,9 @@ module internal ExtensionTyping = member __.Handle = x override __.Equals y = assert false; match y with :? ProvidedEventInfo as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = assert false; x.GetHashCode() - static member TaintedGetHashCode (x:Tainted) = + static member TaintedGetHashCode (x: Tainted) = Tainted.GetHashCodeTainted (x.PApplyNoFailure(fun st -> (st.Name, st.DeclaringType.Assembly.FullName, st.DeclaringType.FullName))) - static member TaintedEquals (pt1:Tainted, pt2:Tainted) = + static member TaintedEquals (pt1: Tainted, pt2: Tainted) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) and [] @@ -688,7 +688,7 @@ module internal ExtensionTyping = override __.GetHashCode() = assert false; x.GetHashCode() [] - type ProvidedExpr (x:Quotations.Expr, ctxt) = + type ProvidedExpr (x: Quotations.Expr, ctxt) = member __.Type = x.Type |> ProvidedType.Create ctxt member __.Handle = x member __.Context = ctxt @@ -699,42 +699,42 @@ module internal ExtensionTyping = override __.GetHashCode() = x.GetHashCode() [] - type ProvidedVar (x:Quotations.Var, ctxt) = + type ProvidedVar (x: Quotations.Var, ctxt) = member __.Type = x.Type |> ProvidedType.Create ctxt member __.Name = x.Name member __.IsMutable = x.IsMutable member __.Handle = x member __.Context = ctxt static member Create ctxt t = match box t with null -> null | _ -> ProvidedVar (t, ctxt) - static member Fresh (nm, ty:ProvidedType) = ProvidedVar.Create ty.Context (new Quotations.Var(nm, ty.Handle)) + static member Fresh (nm, ty: ProvidedType) = ProvidedVar.Create ty.Context (new Quotations.Var(nm, ty.Handle)) static member CreateArray ctxt xs = match xs with null -> null | _ -> xs |> Array.map (ProvidedVar.Create ctxt) override __.Equals y = match y with :? ProvidedVar as y -> x.Equals y.Handle | _ -> false override __.GetHashCode() = x.GetHashCode() /// Detect a provided new-object expression - let (|ProvidedNewObjectExpr|_|) (x:ProvidedExpr) = + let (|ProvidedNewObjectExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.NewObject(ctor, args) -> Some (ProvidedConstructorInfo.Create x.Context ctor, [| for a in args -> ProvidedExpr.Create x.Context a |]) | _ -> None /// Detect a provided while-loop expression - let (|ProvidedWhileLoopExpr|_|) (x:ProvidedExpr) = + let (|ProvidedWhileLoopExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.WhileLoop(guardExpr, bodyExpr) -> Some (ProvidedExpr.Create x.Context guardExpr, ProvidedExpr.Create x.Context bodyExpr) | _ -> None /// Detect a provided new-delegate expression - let (|ProvidedNewDelegateExpr|_|) (x:ProvidedExpr) = + let (|ProvidedNewDelegateExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.NewDelegate(ty, vs, expr) -> Some (ProvidedType.Create x.Context ty, ProvidedVar.CreateArray x.Context (List.toArray vs), ProvidedExpr.Create x.Context expr) | _ -> None /// Detect a provided call expression - let (|ProvidedCallExpr|_|) (x:ProvidedExpr) = + let (|ProvidedCallExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.Call(objOpt, meth, args) -> Some ((match objOpt with None -> None | Some obj -> Some (ProvidedExpr.Create x.Context obj)), @@ -743,87 +743,87 @@ module internal ExtensionTyping = | _ -> None /// Detect a provided default-value expression - let (|ProvidedDefaultExpr|_|) (x:ProvidedExpr) = + let (|ProvidedDefaultExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.DefaultValue ty -> Some (ProvidedType.Create x.Context ty) | _ -> None /// Detect a provided constant expression - let (|ProvidedConstantExpr|_|) (x:ProvidedExpr) = + let (|ProvidedConstantExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.Value(obj, ty) -> Some (obj, ProvidedType.Create x.Context ty) | _ -> None /// Detect a provided type-as expression - let (|ProvidedTypeAsExpr|_|) (x:ProvidedExpr) = + let (|ProvidedTypeAsExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.Coerce(arg, ty) -> Some (ProvidedExpr.Create x.Context arg, ProvidedType.Create x.Context ty) | _ -> None /// Detect a provided new-tuple expression - let (|ProvidedNewTupleExpr|_|) (x:ProvidedExpr) = + let (|ProvidedNewTupleExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.NewTuple(args) -> Some (ProvidedExpr.CreateArray x.Context (Array.ofList args)) | _ -> None /// Detect a provided tuple-get expression - let (|ProvidedTupleGetExpr|_|) (x:ProvidedExpr) = + let (|ProvidedTupleGetExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.TupleGet(arg, n) -> Some (ProvidedExpr.Create x.Context arg, n) | _ -> None /// Detect a provided new-array expression - let (|ProvidedNewArrayExpr|_|) (x:ProvidedExpr) = + let (|ProvidedNewArrayExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.NewArray(ty, args) -> Some (ProvidedType.Create x.Context ty, ProvidedExpr.CreateArray x.Context (Array.ofList args)) | _ -> None /// Detect a provided sequential expression - let (|ProvidedSequentialExpr|_|) (x:ProvidedExpr) = + let (|ProvidedSequentialExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.Sequential(e1, e2) -> Some (ProvidedExpr.Create x.Context e1, ProvidedExpr.Create x.Context e2) | _ -> None /// Detect a provided lambda expression - let (|ProvidedLambdaExpr|_|) (x:ProvidedExpr) = + let (|ProvidedLambdaExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.Lambda(v, body) -> Some (ProvidedVar.Create x.Context v, ProvidedExpr.Create x.Context body) | _ -> None /// Detect a provided try/finally expression - let (|ProvidedTryFinallyExpr|_|) (x:ProvidedExpr) = + let (|ProvidedTryFinallyExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.TryFinally(b1, b2) -> Some (ProvidedExpr.Create x.Context b1, ProvidedExpr.Create x.Context b2) | _ -> None /// Detect a provided try/with expression - let (|ProvidedTryWithExpr|_|) (x:ProvidedExpr) = + let (|ProvidedTryWithExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.TryWith(b, v1, e1, v2, e2) -> Some (ProvidedExpr.Create x.Context b, ProvidedVar.Create x.Context v1, ProvidedExpr.Create x.Context e1, ProvidedVar.Create x.Context v2, ProvidedExpr.Create x.Context e2) | _ -> None #if PROVIDED_ADDRESS_OF - let (|ProvidedAddressOfExpr|_|) (x:ProvidedExpr) = + let (|ProvidedAddressOfExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.AddressOf(e) -> Some (ProvidedExpr.Create x.Context e) | _ -> None #endif /// Detect a provided type-test expression - let (|ProvidedTypeTestExpr|_|) (x:ProvidedExpr) = + let (|ProvidedTypeTestExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.TypeTest(e, ty) -> Some (ProvidedExpr.Create x.Context e, ProvidedType.Create x.Context ty) | _ -> None /// Detect a provided 'let' expression - let (|ProvidedLetExpr|_|) (x:ProvidedExpr) = + let (|ProvidedLetExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.Let(v, e, b) -> Some (ProvidedVar.Create x.Context v, ProvidedExpr.Create x.Context e, ProvidedExpr.Create x.Context b) | _ -> None /// Detect a provided expression which is a for-loop over integers - let (|ProvidedForIntegerRangeLoopExpr|_|) (x:ProvidedExpr) = + let (|ProvidedForIntegerRangeLoopExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.ForIntegerRangeLoop (v, e1, e2, e3) -> Some (ProvidedVar.Create x.Context v, @@ -833,19 +833,19 @@ module internal ExtensionTyping = | _ -> None /// Detect a provided 'set variable' expression - let (|ProvidedVarSetExpr|_|) (x:ProvidedExpr) = + let (|ProvidedVarSetExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.VarSet(v, e) -> Some (ProvidedVar.Create x.Context v, ProvidedExpr.Create x.Context e) | _ -> None /// Detect a provided 'IfThenElse' expression - let (|ProvidedIfThenElseExpr|_|) (x:ProvidedExpr) = + let (|ProvidedIfThenElseExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.IfThenElse(g, t, e) -> Some (ProvidedExpr.Create x.Context g, ProvidedExpr.Create x.Context t, ProvidedExpr.Create x.Context e) | _ -> None /// Detect a provided 'Var' expression - let (|ProvidedVarExpr|_|) (x:ProvidedExpr) = + let (|ProvidedVarExpr|_|) (x: ProvidedExpr) = match x.Handle with | Quotations.Patterns.Var v -> Some (ProvidedVar.Create x.Context v) | _ -> None @@ -855,7 +855,7 @@ module internal ExtensionTyping = provider.GetInvokerExpression(methodBase.Handle, [| for p in paramExprs -> Quotations.Expr.Var(p.Handle) |]) |> ProvidedExpr.Create methodBase.Context /// Compute the Name or FullName property of a provided type, reporting appropriate errors - let CheckAndComputeProvidedNameProperty(m, st:Tainted, proj, propertyString) = + let CheckAndComputeProvidedNameProperty(m, st: Tainted, proj, propertyString) = let name = try st.PUntaint(proj, m) with :? TypeProviderError as tpe -> @@ -866,7 +866,7 @@ module internal ExtensionTyping = name /// Verify that this type provider has supported attributes - let ValidateAttributesOfProvidedType (m, st:Tainted) = + let ValidateAttributesOfProvidedType (m, st: Tainted) = let fullName = CheckAndComputeProvidedNameProperty(m, st, (fun st -> st.FullName), "FullName") if TryTypeMember(st, fullName, "IsGenericType", m, false, fun st->st.IsGenericType) |> unmarshal then errorR(Error(FSComp.SR.etMustNotBeGeneric(fullName), m)) @@ -882,7 +882,7 @@ module internal ExtensionTyping = raise (TypeProviderError(FSComp.SR.etProvidedTypeHasUnexpectedName(expectedName, name), st.TypeProviderDesignation, m)) let namespaceName = TryTypeMember(st, name, "Namespace", m, "", fun st -> st.Namespace) |> unmarshal - let rec declaringTypes (st:Tainted) accu = + let rec declaringTypes (st: Tainted) accu = match TryTypeMember(st, name, "DeclaringType", m, null, fun st -> st.DeclaringType) with | Tainted.Null -> accu | dt -> declaringTypes dt (CheckAndComputeProvidedNameProperty(m, dt, (fun dt -> dt.Name), "Name")::accu) @@ -898,7 +898,7 @@ module internal ExtensionTyping = errorR(Error(FSComp.SR.etProvidedTypeHasUnexpectedPath(expectedPath, path), m)) /// Eagerly validate a range of conditions on a provided type, after static instantiation (if any) has occurred - let ValidateProvidedTypeAfterStaticInstantiation(m, st:Tainted, expectedPath : string[], expectedName : string) = + let ValidateProvidedTypeAfterStaticInstantiation(m, st: Tainted, expectedPath : string[], expectedName : string) = // Do all the calling into st up front with recovery let fullName, namespaceName, usedMembers = let name = CheckAndComputeProvidedNameProperty(m, st, (fun st -> st.Name), "Name") @@ -1000,7 +1000,7 @@ module internal ExtensionTyping = | None -> errorR(Error(FSComp.SR.etUnsupportedMemberKind(memberName, fullName), m)) - let ValidateProvidedTypeDefinition(m, st:Tainted, expectedPath : string[], expectedName : string) = + let ValidateProvidedTypeDefinition(m, st: Tainted, expectedPath : string[], expectedName : string) = // Validate the Name, Namespace and FullName properties let name = CheckAndComputeProvidedNameProperty(m, st, (fun st -> st.Name), "Name") @@ -1023,7 +1023,7 @@ module internal ExtensionTyping = /// Resolve a (non-nested) provided type given a full namespace name and a type name. /// May throw an exception which will be turned into an error message by one of the 'Try' function below. /// If resolution is successful the type is then validated. - let ResolveProvidedType (resolver:Tainted, m, moduleOrNamespace:string[], typeName) = + let ResolveProvidedType (resolver: Tainted, m, moduleOrNamespace: string[], typeName) = let displayName = String.Join(".", moduleOrNamespace) // Try to find the type in the given provided namespace @@ -1055,7 +1055,7 @@ module internal ExtensionTyping = | Some res -> res /// Try to resolve a type against the given host with the given resolution environment. - let TryResolveProvidedType(resolver:Tainted, m, moduleOrNamespace, typeName) = + let TryResolveProvidedType(resolver: Tainted, m, moduleOrNamespace, typeName) = try match ResolveProvidedType(resolver, m, moduleOrNamespace, typeName) with | Tainted.Null -> None @@ -1064,8 +1064,8 @@ module internal ExtensionTyping = errorRecovery e m None - let ILPathToProvidedType (st:Tainted, m) = - let nameContrib (st:Tainted) = + let ILPathToProvidedType (st: Tainted, m) = + let nameContrib (st: Tainted) = let typeName = st.PUntaint((fun st -> st.Name), m) match st.PApply((fun st -> st.DeclaringType), m) with | Tainted.Null -> @@ -1074,7 +1074,7 @@ module internal ExtensionTyping = | ns -> ns + "." + typeName | _ -> typeName - let rec encContrib (st:Tainted) = + let rec encContrib (st: Tainted) = match st.PApply((fun st ->st.DeclaringType), m) with | Tainted.Null -> [] | enc -> encContrib enc @ [ nameContrib enc ] @@ -1089,7 +1089,7 @@ module internal ExtensionTyping = PrettyNaming.computeMangledNameWithoutDefaultArgValues(nm, staticArgs, defaultArgValues) /// Apply the given provided method to the given static arguments (the arguments are assumed to have been sorted into application order) - let TryApplyProvidedMethod(methBeforeArgs:Tainted, staticArgs:obj[], m:range) = + let TryApplyProvidedMethod(methBeforeArgs: Tainted, staticArgs: obj[], m: range) = if staticArgs.Length = 0 then Some methBeforeArgs else @@ -1109,7 +1109,7 @@ module internal ExtensionTyping = /// Apply the given provided type to the given static arguments (the arguments are assumed to have been sorted into application order - let TryApplyProvidedType(typeBeforeArguments:Tainted, optGeneratedTypePath: string list option, staticArgs:obj[], m:range) = + let TryApplyProvidedType(typeBeforeArguments: Tainted, optGeneratedTypePath: string list option, staticArgs: obj[], m: range) = if staticArgs.Length = 0 then Some (typeBeforeArguments , (fun () -> ())) else @@ -1138,7 +1138,7 @@ module internal ExtensionTyping = /// Given a mangled name reference to a non-nested provided type, resolve it. /// If necessary, demangle its static arguments before applying them. - let TryLinkProvidedType(resolver:Tainted, moduleOrNamespace:string[], typeLogicalName:string, m:range) = + let TryLinkProvidedType(resolver: Tainted, moduleOrNamespace: string[], typeLogicalName: string, m: range) = // Demangle the static parameters let typeName, argNamesAndValues = @@ -1206,24 +1206,24 @@ module internal ExtensionTyping = | None -> None /// Get the parts of a .NET namespace. Special rules: null means global, empty is not allowed. - let GetPartsOfNamespaceRecover(namespaceName:string) = + let GetPartsOfNamespaceRecover(namespaceName: string) = if namespaceName=null then [] elif namespaceName.Length = 0 then [""] else splitNamespace namespaceName /// Get the parts of a .NET namespace. Special rules: null means global, empty is not allowed. - let GetProvidedNamespaceAsPath (m, resolver:Tainted, namespaceName:string) = + let GetProvidedNamespaceAsPath (m, resolver: Tainted, namespaceName: string) = if namespaceName<>null && namespaceName.Length = 0 then errorR(Error(FSComp.SR.etEmptyNamespaceNotAllowed(DisplayNameOfTypeProvider(resolver.TypeProvider, m)), m)) GetPartsOfNamespaceRecover namespaceName /// Get the parts of the name that encloses the .NET type including nested types. - let GetFSharpPathToProvidedType (st:Tainted, m) = + let GetFSharpPathToProvidedType (st: Tainted, m) = // Can't use st.Fullname because it may be like IEnumerable // We want [System;Collections;Generic] let namespaceParts = GetPartsOfNamespaceRecover(st.PUntaint((fun st -> st.Namespace), m)) - let rec walkUpNestedClasses(st:Tainted, soFar) = + let rec walkUpNestedClasses(st: Tainted, soFar) = match st with | Tainted.Null -> soFar | st -> walkUpNestedClasses(st.PApply((fun st ->st.DeclaringType), m), soFar) @ [st.PUntaint((fun st -> st.Name), m)] @@ -1233,13 +1233,13 @@ module internal ExtensionTyping = /// Get the ILAssemblyRef for a provided assembly. Do not take into account /// any type relocations or static linking for generated types. - let GetOriginalILAssemblyRefOfProvidedAssembly (assembly:Tainted, m) = + let GetOriginalILAssemblyRefOfProvidedAssembly (assembly: Tainted, m) = let aname = assembly.PUntaint((fun assembly -> assembly.GetName()), m) ILAssemblyRef.FromAssemblyName aname /// Get the ILTypeRef for the provided type (including for nested types). Do not take into account /// any type relocations or static linking for generated types. - let GetOriginalILTypeRefOfProvidedType (st:Tainted, m) = + let GetOriginalILTypeRefOfProvidedType (st: Tainted, m) = let aref = GetOriginalILAssemblyRefOfProvidedAssembly (st.PApply((fun st -> st.Assembly), m), m) let scoperef = ILScopeRef.Assembly aref @@ -1249,7 +1249,7 @@ module internal ExtensionTyping = /// Get the ILTypeRef for the provided type (including for nested types). Take into account /// any type relocations or static linking for generated types. - let GetILTypeRefOfProvidedType (st:Tainted, m) = + let GetILTypeRefOfProvidedType (st: Tainted, m) = match st.PUntaint((fun st -> st.TryGetILTypeRef()), m) with | Some ilTypeRef -> ilTypeRef | None -> GetOriginalILTypeRefOfProvidedType (st, m) diff --git a/src/fsharp/FindUnsolved.fs b/src/fsharp/FindUnsolved.fs index 0bfd0b5de81..280a6234608 100644 --- a/src/fsharp/FindUnsolved.fs +++ b/src/fsharp/FindUnsolved.fs @@ -35,24 +35,24 @@ let accTypeInst cenv env tyargs = let rec accExpr (cenv:cenv) (env:env) expr = let expr = stripExpr expr match expr with - | Expr.Sequential (e1,e2,_,_,_) -> + | Expr.Sequential (e1, e2, _, _, _) -> accExpr cenv env e1 accExpr cenv env e2 - | Expr.Let (bind,body,_,_) -> + | Expr.Let (bind, body, _, _) -> accBind cenv env bind accExpr cenv env body - | Expr.Const (_,_,ty) -> + | Expr.Const (_, _, ty) -> accTy cenv env ty - | Expr.Val (_v,_vFlags,_m) -> () + | Expr.Val (_v, _vFlags, _m) -> () - | Expr.Quote(ast,_,_,_m,ty) -> + | Expr.Quote(ast, _, _, _m, ty) -> accExpr cenv env ast accTy cenv env ty - | Expr.Obj (_,ty,basev,basecall,overrides,iimpls,_m) -> + | Expr.Obj (_, ty, basev, basecall, overrides, iimpls, _m) -> accTy cenv env ty accExpr cenv env basecall accMethods cenv env basev overrides @@ -65,43 +65,43 @@ let rec accExpr (cenv:cenv) (env:env) expr = // tailcall accExpr cenv env argLast - | Expr.Op (c,tyargs,args,m) -> - accOp cenv env (c,tyargs,args,m) + | Expr.Op (c, tyargs, args, m) -> + accOp cenv env (c, tyargs, args, m) - | Expr.App(f,fty,tyargs,argsl,_m) -> + | Expr.App(f, fty, tyargs, argsl, _m) -> accTy cenv env fty accTypeInst cenv env tyargs accExpr cenv env f accExprs cenv env argsl - | Expr.Lambda(_,_ctorThisValOpt,_baseValOpt,argvs,_body,m,rty) -> - let topValInfo = ValReprInfo ([],[argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)],ValReprInfo.unnamedRetVal) + | Expr.Lambda(_, _ctorThisValOpt, _baseValOpt, argvs, _body, m, rty) -> + let topValInfo = ValReprInfo ([], [argvs |> List.map (fun _ -> ValReprInfo.unnamedTopArg1)], ValReprInfo.unnamedRetVal) let ty = mkMultiLambdaTy m argvs rty accLambdas cenv env topValInfo expr ty - | Expr.TyLambda(_,tps,_body,_m,rty) -> - let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps,[],ValReprInfo.unnamedRetVal) + | Expr.TyLambda(_, tps, _body, _m, rty) -> + let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) accTy cenv env rty let ty = mkForallTyIfNeeded tps rty accLambdas cenv env topValInfo expr ty - | Expr.TyChoose(_tps,e1,_m) -> + | Expr.TyChoose(_tps, e1, _m) -> accExpr cenv env e1 - | Expr.Match(_,_exprm,dtree,targets,m,ty) -> + | Expr.Match(_, _exprm, dtree, targets, m, ty) -> accTy cenv env ty accDTree cenv env dtree accTargets cenv env m ty targets - | Expr.LetRec (binds,e,_m,_) -> + | Expr.LetRec (binds, e, _m, _) -> accBinds cenv env binds accExpr cenv env e - | Expr.StaticOptimization (constraints,e2,e3,_m) -> + | Expr.StaticOptimization (constraints, e2, e3, _m) -> accExpr cenv env e2 accExpr cenv env e3 constraints |> List.iter (function - | TTyconEqualsTycon(ty1,ty2) -> + | TTyconEqualsTycon(ty1, ty2) -> accTy cenv env ty1 accTy cenv env ty2 | TTyconIsStruct(ty1) -> @@ -112,42 +112,42 @@ let rec accExpr (cenv:cenv) (env:env) expr = and accMethods cenv env baseValOpt l = List.iter (accMethod cenv env baseValOpt) l -and accMethod cenv env _baseValOpt (TObjExprMethod(_slotsig,_attribs,_tps,vs,e,_m)) = +and accMethod cenv env _baseValOpt (TObjExprMethod(_slotsig, _attribs, _tps, vs, e, _m)) = vs |> List.iterSquared (accVal cenv env) accExpr cenv env e and accIntfImpls cenv env baseValOpt l = List.iter (accIntfImpl cenv env baseValOpt) l -and accIntfImpl cenv env baseValOpt (ty,overrides) = +and accIntfImpl cenv env baseValOpt (ty, overrides) = accTy cenv env ty accMethods cenv env baseValOpt overrides -and accOp cenv env (op,tyargs,args,_m) = +and accOp cenv env (op, tyargs, args, _m) = // Special cases accTypeInst cenv env tyargs accExprs cenv env args match op with // Handle these as special cases since mutables are allowed inside their bodies - | TOp.ILCall (_,_,_,_,_,_,_,_,enclTypeArgs,methTypeArgs,tys) -> + | TOp.ILCall (_, _, _, _, _, _, _, _, enclTypeArgs, methTypeArgs, tys) -> accTypeInst cenv env enclTypeArgs accTypeInst cenv env methTypeArgs accTypeInst cenv env tys - | TOp.TraitCall(TTrait(tys,_nm,_,argtys,rty,_sln)) -> + | TOp.TraitCall(TTrait(tys, _nm, _, argtys, rty, _sln)) -> argtys |> accTypeInst cenv env rty |> Option.iter (accTy cenv env) tys |> List.iter (accTy cenv env) - | TOp.ILAsm (_,tys) -> + | TOp.ILAsm (_, tys) -> accTypeInst cenv env tys | _ -> () and accLambdas cenv env topValInfo e ety = match e with - | Expr.TyChoose(_tps,e1,_m) -> accLambdas cenv env topValInfo e1 ety + | Expr.TyChoose(_tps, e1, _m) -> accLambdas cenv env topValInfo e1 ety | Expr.Lambda _ | Expr.TyLambda _ -> - let _tps,ctorThisValOpt,baseValOpt,vsl,body,bodyty = destTopLambda cenv.g cenv.amap topValInfo (e, ety) + let _tps, ctorThisValOpt, baseValOpt, vsl, body, bodyty = destTopLambda cenv.g cenv.amap topValInfo (e, ety) accTy cenv env bodyty vsl |> List.iterSquared (accVal cenv env) baseValOpt |> Option.iter (accVal cenv env) @@ -162,36 +162,36 @@ and accExprs cenv env exprs = and accTargets cenv env m ty targets = Array.iter (accTarget cenv env m ty) targets -and accTarget cenv env _m _ty (TTarget(_vs,e,_)) = +and accTarget cenv env _m _ty (TTarget(_vs, e, _)) = accExpr cenv env e and accDTree cenv env x = match x with - | TDSuccess (es,_n) -> accExprs cenv env es - | TDBind(bind,rest) -> accBind cenv env bind; accDTree cenv env rest - | TDSwitch (e,cases,dflt,m) -> accSwitch cenv env (e,cases,dflt,m) + | TDSuccess (es, _n) -> accExprs cenv env es + | TDBind(bind, rest) -> accBind cenv env bind; accDTree cenv env rest + | TDSwitch (e, cases, dflt, m) -> accSwitch cenv env (e, cases, dflt, m) -and accSwitch cenv env (e,cases,dflt,_m) = +and accSwitch cenv env (e, cases, dflt, _m) = accExpr cenv env e - cases |> List.iter (fun (TCase(discrim,e)) -> accDiscrim cenv env discrim; accDTree cenv env e) + cases |> List.iter (fun (TCase(discrim, e)) -> accDiscrim cenv env discrim; accDTree cenv env e) dflt |> Option.iter (accDTree cenv env) and accDiscrim cenv env d = match d with - | DecisionTreeTest.UnionCase(_ucref,tinst) -> accTypeInst cenv env tinst - | DecisionTreeTest.ArrayLength(_,ty) -> accTy cenv env ty + | DecisionTreeTest.UnionCase(_ucref, tinst) -> accTypeInst cenv env tinst + | DecisionTreeTest.ArrayLength(_, ty) -> accTy cenv env ty | DecisionTreeTest.Const _ | DecisionTreeTest.IsNull -> () - | DecisionTreeTest.IsInst (srcty,tgty) -> accTy cenv env srcty; accTy cenv env tgty + | DecisionTreeTest.IsInst (srcty, tgty) -> accTy cenv env srcty; accTy cenv env tgty | DecisionTreeTest.ActivePatternCase (exp, tys, _, _, _) -> accExpr cenv env exp accTypeInst cenv env tys -and accAttrib cenv env (Attrib(_,_k,args,props,_,_,_m)) = - args |> List.iter (fun (AttribExpr(expr1,expr2)) -> +and accAttrib cenv env (Attrib(_, _k, args, props, _, _, _m)) = + args |> List.iter (fun (AttribExpr(expr1, expr2)) -> accExpr cenv env expr1 accExpr cenv env expr2) - props |> List.iter (fun (AttribNamedArg(_nm,ty,_flg,AttribExpr(expr,expr2))) -> + props |> List.iter (fun (AttribNamedArg(_nm, ty, _flg, AttribExpr(expr, expr2))) -> accExpr cenv env expr accExpr cenv env expr2 accTy cenv env ty) @@ -199,7 +199,7 @@ and accAttrib cenv env (Attrib(_,_k,args,props,_,_,_m)) = and accAttribs cenv env attribs = List.iter (accAttrib cenv env) attribs -and accValReprInfo cenv env (ValReprInfo(_,args,ret)) = +and accValReprInfo cenv env (ValReprInfo(_, args, ret)) = args |> List.iterSquared (accArgReprInfo cenv env) ret |> accArgReprInfo cenv env @@ -244,11 +244,11 @@ and accModuleOrNamespaceDefs cenv env x = and accModuleOrNamespaceDef cenv env x = match x with - | TMDefRec(_,tycons,mbinds,_m) -> + | TMDefRec(_, tycons, mbinds, _m) -> accTycons cenv env tycons accModuleOrNamespaceBinds cenv env mbinds - | TMDefLet(bind,_m) -> accBind cenv env bind - | TMDefDo(e,_m) -> accExpr cenv env e + | TMDefLet(bind, _m) -> accBind cenv env bind + | TMDefDo(e, _m) -> accExpr cenv env e | TMAbstract(def) -> accModuleOrNamespaceExpr cenv env def | TMDefs(defs) -> accModuleOrNamespaceDefs cenv env defs diff --git a/src/fsharp/IlxGen.fs b/src/fsharp/IlxGen.fs index 1d503c8d767..011fd9e5932 100644 --- a/src/fsharp/IlxGen.fs +++ b/src/fsharp/IlxGen.fs @@ -37,16 +37,16 @@ open FSharp.Compiler.Tastops.DebugPrint open FSharp.Compiler.TcGlobals open FSharp.Compiler.TypeRelations -let IsNonErasedTypar (tp:Typar) = +let IsNonErasedTypar (tp: Typar) = not tp.IsErased -let DropErasedTypars (tps:Typar list) = +let DropErasedTypars (tps: Typar list) = tps |> List.filter IsNonErasedTypar let DropErasedTyargs tys = tys |> List.filter (fun ty -> match ty with TType_measure _ -> false | _ -> true) -let AddNonUserCompilerGeneratedAttribs (g: TcGlobals) (mdef:ILMethodDef) = +let AddNonUserCompilerGeneratedAttribs (g: TcGlobals) (mdef: ILMethodDef) = g.AddMethodGeneratedAttributes mdef let debugDisplayMethodName = "__DebugDisplay" @@ -138,7 +138,7 @@ let AddReport f = let old = reports reports <- (fun oc -> old oc; f oc) -let ReportStatistics (oc:TextWriter) = +let ReportStatistics (oc: TextWriter) = reports oc let NewCounter nm = @@ -162,7 +162,7 @@ type IlxGenIntraAssemblyInfo = /// only accessible intra-assembly. Across assemblies, taking the address of static mutable module-bound values is not permitted. /// The key to the table is the method ref for the property getter for the value, which is a stable name for the Val's /// that come from both the signature and the implementation. - StaticFieldInfo : Dictionary + StaticFieldInfo: Dictionary } /// Helper to make sure we take tailcalls in some situations @@ -231,7 +231,7 @@ type cenv = /// A callback for TcVal in the typechecker. Used to generalize values when finding witnesses. /// It is unfortunate this is needed but it is until we supply witnesses through the compiation. - TcVal : ConstraintSolver.TcValF + TcVal: ConstraintSolver.TcValF /// The TAST for the assembly being emitted viewCcu: CcuThunk @@ -243,13 +243,13 @@ type cenv = mutable ilUnitTy: ILType option /// Other information from the emit of this assembly - intraAssemblyInfo : IlxGenIntraAssemblyInfo + intraAssemblyInfo: IlxGenIntraAssemblyInfo /// Cache methods with SecurityAttribute applied to them, to prevent unnecessary calls to ExistsInEntireHierarchyOfType - casApplied : Dictionary + casApplied: Dictionary /// Used to apply forced inlining optimizations to witnesses generated late during codegen - mutable optimizeDuringCodeGen : (Expr -> Expr) + mutable optimizeDuringCodeGen: (Expr -> Expr) } @@ -258,10 +258,10 @@ let mkTypeOfExpr cenv m ilty = [mkAsmExpr ([ I_ldtoken (ILToken.ILType ilty) ], [], [], [cenv.g.system_RuntimeTypeHandle_ty], m)], [cenv.g.system_Type_ty], m) -let mkGetNameExpr cenv (ilt : ILType) m = +let mkGetNameExpr cenv (ilt: ILType) m = mkAsmExpr ([I_ldstr ilt.BasicQualifiedName], [], [], [cenv.g.string_ty], m) -let useCallVirt cenv boxity (mspec : ILMethodSpec) isBaseCall = +let useCallVirt cenv boxity (mspec: ILMethodSpec) isBaseCall = cenv.opts.alwaysCallVirt && (boxity = AsObject) && not mspec.CallingConv.IsStatic && @@ -287,16 +287,16 @@ type CompileLocation = let mkTopName ns n = String.concat "." (match ns with Some x -> [x;n] | None -> [n]) -let CompLocForFragment fragName (ccu:CcuThunk) = +let CompLocForFragment fragName (ccu: CcuThunk) = { QualifiedNameOfFile = fragName TopImplQualifiedName = fragName Scope = ccu.ILScopeRef Namespace = None Enclosing = []} -let CompLocForCcu (ccu:CcuThunk) = CompLocForFragment ccu.AssemblyName ccu +let CompLocForCcu (ccu: CcuThunk) = CompLocForFragment ccu.AssemblyName ccu -let CompLocForSubModuleOrNamespace cloc (submod:ModuleOrNamespace) = +let CompLocForSubModuleOrNamespace cloc (submod: ModuleOrNamespace) = let n = submod.CompiledName match submod.ModuleOrNamespaceType.ModuleOrNamespaceKind with | FSharpModuleWithSuffix | ModuleOrType -> { cloc with Enclosing= cloc.Enclosing @ [n]} @@ -314,7 +314,7 @@ let CompLocForFixedPath fragName qname (CompPath(sref, cpath)) = Namespace = ns Enclosing = encl } -let CompLocForFixedModule fragName qname (mspec:ModuleOrNamespace) = +let CompLocForFixedModule fragName qname (mspec: ModuleOrNamespace) = let cloc = CompLocForFixedPath fragName qname mspec.CompilationPath let cloc = CompLocForSubModuleOrNamespace cloc mspec cloc @@ -326,7 +326,7 @@ let NestedTypeRefForCompLoc cloc n = mkILTyRef(cloc.Scope, tyname) | h::t -> mkILNestedTyRef(cloc.Scope, mkTopName cloc.Namespace h :: t, n) -let CleanUpGeneratedTypeName (nm:string) = +let CleanUpGeneratedTypeName (nm: string) = if nm.IndexOfAny IllegalCharactersInTypeAndNamespaceNames = -1 then nm else @@ -371,7 +371,7 @@ let ComputeMemberAccess hidden = if hidden then ILMemberAccess.Assembly else ILM // Under --publicasinternal change types from Public to Private (internal for types) let ComputePublicTypeAccess() = ILTypeDefAccess.Public -let ComputeTypeAccess (tref:ILTypeRef) hidden = +let ComputeTypeAccess (tref: ILTypeRef) hidden = match tref.Enclosing with | [] -> if hidden then ILTypeDefAccess.Private else ComputePublicTypeAccess() | _ -> ILTypeDefAccess.Nested (ComputeMemberAccess hidden) @@ -382,10 +382,10 @@ let ComputeTypeAccess (tref:ILTypeRef) hidden = /// Indicates how type parameters are mapped to IL type variables [] -type TypeReprEnv(reprs : Map, count: int) = +type TypeReprEnv(reprs: Map, count: int) = /// Lookup a type parameter - member __.Item (tp:Typar, m:range) = + member __.Item (tp: Typar, m: range) = try reprs.[tp.Stamp] with :? KeyNotFoundException -> errorR(InternalError("Undefined or unsolved type variable: " + showL(typarL tp), m)) @@ -416,11 +416,11 @@ type TypeReprEnv(reprs : Map, count: int) = TypeReprEnv.Empty.Add tps /// Get the environment for within a type definition - static member ForTycon (tycon:Tycon) = + static member ForTycon (tycon: Tycon) = TypeReprEnv.ForTypars (tycon.TyparsNoRange) /// Get the environment for generating a reference to items within a type definition - static member ForTyconRef (tycon:TyconRef) = + static member ForTyconRef (tycon: TyconRef) = TypeReprEnv.ForTycon tycon.Deref @@ -429,7 +429,7 @@ type TypeReprEnv(reprs : Map, count: int) = //-------------------------------------------------------------------------- /// Get the ILTypeRef or other representation information for a type -let GenTyconRef (tcref:TyconRef) = +let GenTyconRef (tcref: TyconRef) = assert(not tcref.IsTypeAbbrev) tcref.CompiledRepresentation @@ -490,7 +490,7 @@ and GenILTyAppAux amap m tyenv (tref, boxity, ilTypeOpt) tinst = | Some ilType -> ilType // monomorphic types include a cached ilType to avoid reallocation of an ILType node -and GenNamedTyAppAux (amap:ImportMap) m tyenv ptrsOK tcref tinst = +and GenNamedTyAppAux (amap: ImportMap) m tyenv ptrsOK tcref tinst = let g = amap.g let tinst = DropErasedTyargs tinst @@ -544,7 +544,7 @@ 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[]) = +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) @@ -575,7 +575,7 @@ and GenUnionRef (amap: ImportMap) m (tcref: TyconRef) = let boxity = (if tcref.IsStructOrEnumTycon then ILBoxity.AsValue else ILBoxity.AsObject) IlxUnionRef(boxity, tref, alternatives, nullPermitted, hasHelpers)) -and ComputeUnionHasHelpers g (tcref : TyconRef) = +and ComputeUnionHasHelpers g (tcref: TyconRef) = if tyconRefEq g tcref g.unit_tcr_canon then NoHelpers elif tyconRefEq g tcref g.list_tcr_canon then SpecialFSharpListHelpers elif tyconRefEq g tcref g.option_tcr_canon then SpecialFSharpOptionHelpers @@ -594,7 +594,7 @@ and GenUnionSpec amap m tyenv tcref tyargs = let tinst = GenTypeArgs amap m tyenv tyargs IlxUnionSpec(curef, tinst) -and GenUnionCaseSpec amap m tyenv (ucref:UnionCaseRef) tyargs = +and GenUnionCaseSpec amap m tyenv (ucref: UnionCaseRef) tyargs = let cuspec = GenUnionSpec amap m tyenv ucref.TyconRef tyargs cuspec, ucref.Index @@ -646,7 +646,7 @@ and GenTypePermitVoidAux amap m tyenv ty = GenTypeAux amap m tyenv VoidOK PtrTyp // Computes the location where the static field for a value lives. // - Literals go in their type/module. // - For interactive code, we always place fields in their type/module with an accurate name -let GenFieldSpecForStaticField (isInteractive, g, ilContainerTy, vspec:Val, nm, m, cloc, ilTy) = +let GenFieldSpecForStaticField (isInteractive, g, ilContainerTy, vspec: Val, nm, m, cloc, ilTy) = if isInteractive || HasFSharpAttribute g g.attrib_LiteralAttribute vspec.Attribs then let fieldName = vspec.CompiledName let fieldName = if isInteractive then CompilerGeneratedName fieldName else fieldName @@ -656,13 +656,13 @@ let GenFieldSpecForStaticField (isInteractive, g, ilContainerTy, vspec:Val, nm, let ilFieldContainerTy = mkILTyForCompLoc (CompLocForInitClass cloc) mkILFieldSpecInTy (ilFieldContainerTy, fieldName, ilTy) -let GenRecdFieldRef m cenv tyenv (rfref:RecdFieldRef) tyargs = +let GenRecdFieldRef m cenv tyenv (rfref: RecdFieldRef) tyargs = let tyenvinner = TypeReprEnv.ForTycon rfref.Tycon mkILFieldSpecInTy(GenTyApp cenv.amap m tyenv rfref.TyconRef.CompiledRepresentation tyargs, ComputeFieldName rfref.Tycon rfref.RecdField, GenType cenv.amap m tyenvinner rfref.RecdField.FormalType) -let GenExnType amap m tyenv (ecref:TyconRef) = GenTyApp amap m tyenv ecref.CompiledRepresentation [] +let GenExnType amap m tyenv (ecref: TyconRef) = GenTyApp amap m tyenv ecref.CompiledRepresentation [] //-------------------------------------------------------------------------- // Closure summaries @@ -705,9 +705,9 @@ type IlxClosureInfo = /// The free type parameters occuring in the type of the closure (and not just its body) /// This is used for local type functions, whose contract class must use these types /// type Contract<'fv> = - /// abstract DirectInvoke : ty['fv] + /// abstract DirectInvoke: ty['fv] /// type Implementation<'fv, 'fv2> : Contract<'fv> = - /// override DirectInvoke : ty['fv] = expr['fv, 'fv2] + /// override DirectInvoke: ty['fv] = expr['fv, 'fv2] /// /// At the callsite we generate /// unbox ty['fv] @@ -894,12 +894,12 @@ let StorageForVal m v eenv = let StorageForValRef m (v: ValRef) eenv = StorageForVal m v.Deref eenv -let IsValRefIsDllImport g (vref:ValRef) = +let IsValRefIsDllImport g (vref: ValRef) = vref.Attribs |> HasFSharpAttributeOpt g g.attrib_DllImportAttribute /// Determine how a top level value is represented, when it is being represented /// as a method. -let GetMethodSpecForMemberVal amap g (memberInfo:ValMemberInfo) (vref:ValRef) = +let GetMethodSpecForMemberVal amap g (memberInfo: ValMemberInfo) (vref: ValRef) = let m = vref.Range let tps, curriedArgInfos, returnTy, retInfo = assert(vref.ValReprInfo.IsSome) @@ -959,7 +959,7 @@ let GetMethodSpecForMemberVal amap g (memberInfo:ValMemberInfo) (vref:ValRef) = mspec, ctps, mtps, paramInfos, retInfo, methodArgTys /// Determine how a top-level value is represented, when representing as a field, by computing an ILFieldSpec -let ComputeFieldSpecForVal(optIntraAssemblyInfo:IlxGenIntraAssemblyInfo option, isInteractive, g, ilTyForProperty, vspec:Val, nm, m, cloc, ilTy, ilGetterMethRef) = +let ComputeFieldSpecForVal(optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, isInteractive, g, ilTyForProperty, vspec: Val, nm, m, cloc, ilTy, ilGetterMethRef) = assert vspec.IsCompiledAsTopLevel let generate() = GenFieldSpecForStaticField (isInteractive, g, ilTyForProperty, vspec, nm, m, cloc, ilTy) match optIntraAssemblyInfo with @@ -978,7 +978,7 @@ let ComputeFieldSpecForVal(optIntraAssemblyInfo:IlxGenIntraAssemblyInfo option, /// Compute the representation information for an F#-declared value (not a member nor a function). /// Mutable and literal static fields must have stable names and live in the "public" location -let ComputeStorageForFSharpValue amap g cloc optIntraAssemblyInfo optShadowLocal isInteractive returnTy (vref:ValRef) m = +let ComputeStorageForFSharpValue amap g cloc optIntraAssemblyInfo optShadowLocal isInteractive returnTy (vref: ValRef) m = let nm = vref.CompiledName let vspec = vref.Deref let ilTy = GenType amap m TypeReprEnv.Empty returnTy (* TypeReprEnv.Empty ok: not a field in a generic class *) @@ -992,14 +992,14 @@ let ComputeStorageForFSharpValue amap g cloc optIntraAssemblyInfo optShadowLocal StaticField (ilFieldSpec, vref, hasLiteralAttr, ilTyForProperty, nm, ilTy, ilGetterMethRef, ilSetterMethRef, optShadowLocal) /// Compute the representation information for an F#-declared member -let ComputeStorageForFSharpMember amap g topValInfo memberInfo (vref:ValRef) m = +let ComputeStorageForFSharpMember amap g topValInfo memberInfo (vref: ValRef) m = let mspec, _, _, paramInfos, retInfo, methodArgTys = GetMethodSpecForMemberVal amap g memberInfo vref Method (topValInfo, vref, mspec, m, paramInfos, methodArgTys, retInfo) /// Compute the representation information for an F#-declared function in a module or an F#-decalared extension member. /// Note, there is considerable overlap with ComputeStorageForFSharpMember/GetMethodSpecForMemberVal and these could be /// rationalized. -let ComputeStorageForFSharpFunctionOrFSharpExtensionMember amap g cloc topValInfo (vref:ValRef) m = +let ComputeStorageForFSharpFunctionOrFSharpExtensionMember amap g cloc topValInfo (vref: ValRef) m = let nm = vref.CompiledName let (tps, curriedArgInfos, returnTy, retInfo) = GetTopValTypeInCompiledForm g topValInfo vref.Type m let tyenvUnderTypars = TypeReprEnv.ForTypars tps @@ -1012,7 +1012,7 @@ let ComputeStorageForFSharpFunctionOrFSharpExtensionMember amap g cloc topValInf Method (topValInfo, vref, mspec, m, paramInfos, methodArgTys, retInfo) /// Determine if an F#-declared value, method or function is compiled as a method. -let IsFSharpValCompiledAsMethod g (v:Val) = +let IsFSharpValCompiledAsMethod g (v: Val) = match v.ValReprInfo with | None -> false | Some topValInfo -> @@ -1027,7 +1027,7 @@ let IsFSharpValCompiledAsMethod g (v:Val) = /// If it's a function or is polymorphic, then it gets represented as a /// method (possibly and instance method). Otherwise it gets represented as a /// static field and property. -let ComputeStorageForTopVal (amap, g, optIntraAssemblyInfo:IlxGenIntraAssemblyInfo option, isInteractive, optShadowLocal, vref:ValRef, cloc) = +let ComputeStorageForTopVal (amap, g, optIntraAssemblyInfo: IlxGenIntraAssemblyInfo option, isInteractive, optShadowLocal, vref: ValRef, cloc) = if isUnitTy g vref.Type && not vref.IsMemberOrModuleBinding && not vref.IsMutable then Null @@ -1065,18 +1065,18 @@ let ComputeStorageForTopVal (amap, g, optIntraAssemblyInfo:IlxGenIntraAssemblyIn ComputeStorageForFSharpFunctionOrFSharpExtensionMember amap g cloc topValInfo vref m /// Determine how an F#-declared value, function or member is represented, if it is in the assembly being compiled. -let ComputeAndAddStorageForLocalTopVal (amap, g, intraAssemblyFieldTable, isInteractive, optShadowLocal) cloc (v:Val) eenv = +let ComputeAndAddStorageForLocalTopVal (amap, g, intraAssemblyFieldTable, isInteractive, optShadowLocal) cloc (v: Val) eenv = let storage = ComputeStorageForTopVal (amap, g, Some intraAssemblyFieldTable, isInteractive, optShadowLocal, mkLocalValRef v, cloc) AddStorageForVal g (v, notlazy storage) eenv /// Determine how an F#-declared value, function or member is represented, if it is an external assembly. -let ComputeStorageForNonLocalTopVal amap g cloc modref (v:Val) = +let ComputeStorageForNonLocalTopVal amap g cloc modref (v: Val) = match v.ValReprInfo with | None -> error(InternalError("ComputeStorageForNonLocalTopVal, expected an arity for " + v.LogicalName, v.Range)) | Some _ -> ComputeStorageForTopVal (amap, g, None, false, NoShadowLocal, mkNestedValRef modref v, cloc) /// Determine how all the F#-decalred top level values, functions and members are represented, for an external module or namespace. -let rec AddStorageForNonLocalModuleOrNamespaceRef amap g cloc acc (modref:ModuleOrNamespaceRef) (modul:ModuleOrNamespace) = +let rec AddStorageForNonLocalModuleOrNamespaceRef amap g cloc acc (modref: ModuleOrNamespaceRef) (modul: ModuleOrNamespace) = let acc = (acc, modul.ModuleOrNamespaceType.ModuleAndNamespaceDefinitions) ||> List.fold (fun acc smodul -> AddStorageForNonLocalModuleOrNamespaceRef amap g (CompLocForSubModuleOrNamespace cloc smodul) acc (modref.NestedTyconRef smodul) smodul) @@ -1087,7 +1087,7 @@ let rec AddStorageForNonLocalModuleOrNamespaceRef amap g cloc acc (modref:Module acc /// Determine how all the F#-declared top level values, functions and members are represented, for an external assembly. -let AddStorageForExternalCcu amap g eenv (ccu:CcuThunk) = +let AddStorageForExternalCcu amap g eenv (ccu: CcuThunk) = if not ccu.IsFSharp then eenv else let cloc = CompLocForCcu ccu let eenv = @@ -1105,7 +1105,7 @@ let AddStorageForExternalCcu amap g eenv (ccu:CcuThunk) = eenv /// Record how all the top level F#-declared values, functions and members are represented, for a local module or namespace. -let rec AddBindingsForLocalModuleType allocVal cloc eenv (mty:ModuleOrNamespaceType) = +let rec AddBindingsForLocalModuleType allocVal cloc eenv (mty: ModuleOrNamespaceType) = let eenv = List.fold (fun eenv submodul -> AddBindingsForLocalModuleType allocVal (CompLocForSubModuleOrNamespace cloc submodul) eenv submodul.ModuleOrNamespaceType) eenv mty.ModuleAndNamespaceDefinitions let eenv = Seq.fold (fun eenv v -> allocVal cloc v eenv) eenv mty.AllValsAndMembers eenv @@ -1115,7 +1115,7 @@ let AddExternalCcusToIlxGenEnv amap g eenv ccus = List.fold (AddStorageForExternalCcu amap g) eenv ccus /// Record how all the unrealized abstract slots are represented, for a type definition. -let AddBindingsForTycon allocVal (cloc:CompileLocation) (tycon:Tycon) eenv = +let AddBindingsForTycon allocVal (cloc: CompileLocation) (tycon: Tycon) eenv = let unrealizedSlots = if tycon.IsFSharpObjectModelTycon then tycon.FSharpObjectModelTypeInfo.fsobjmodel_vslots @@ -1123,7 +1123,7 @@ let AddBindingsForTycon allocVal (cloc:CompileLocation) (tycon:Tycon) eenv = (eenv, unrealizedSlots) ||> List.fold (fun eenv vref -> allocVal cloc vref.Deref eenv) /// Record how constructs are represented, for a sequence of definitions in a module or namespace fragment. -let rec AddBindingsForModuleDefs allocVal (cloc:CompileLocation) eenv mdefs = +let rec AddBindingsForModuleDefs allocVal (cloc: CompileLocation) eenv mdefs = List.fold (AddBindingsForModuleDef allocVal cloc) eenv mdefs /// Record how constructs are represented, for a module or namespace fragment definition. @@ -1164,7 +1164,7 @@ and AddBindingsForModuleTopVals _g allocVal _cloc eenv vs = /// into the stored results for the whole CCU. /// isIncrementalFragment = true --> "typed input" /// isIncrementalFragment = false --> "#load" -let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (amap:ImportMap, isIncrementalFragment, g, ccu, fragName, intraAssemblyInfo, eenv, typedImplFiles) = +let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (amap: ImportMap, isIncrementalFragment, g, ccu, fragName, intraAssemblyInfo, eenv, typedImplFiles) = let cloc = CompLocForFragment fragName ccu let allocVal = ComputeAndAddStorageForLocalTopVal (amap, g, intraAssemblyInfo, true, NoShadowLocal) (eenv, typedImplFiles) ||> List.fold (fun eenv (TImplFile(qname, _, mexpr, _, _, _)) -> @@ -1180,7 +1180,7 @@ let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (amap:ImportMap, isIncrementa //-------------------------------------------------------------------------- /// Generate IL debuging information. -let GenILSourceMarker (g: TcGlobals) (m:range) = +let GenILSourceMarker (g: TcGlobals) (m: range) = ILSourceMarker.Create(document=g.memoize_file m.FileIndex, line=m.StartLine, /// NOTE: .NET && VS measure first column as column 1 @@ -1226,7 +1226,7 @@ let MergePropertyPair m (pd: ILPropertyDef) (pdef: ILPropertyDef) = type PropKey = PropKey of string * ILTypes * ILThisConvention -let AddPropertyDefToHash (m:range) (ht:Dictionary) (pdef: ILPropertyDef) = +let AddPropertyDefToHash (m: range) (ht: Dictionary) (pdef: ILPropertyDef) = let nm = PropKey(pdef.Name, pdef.Args, pdef.CallingConv) match ht.TryGetValue(nm) with | true, (idx, pd) -> @@ -1249,7 +1249,7 @@ let MergePropertyDefs m ilPropertyDefs = type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = let gmethods = new ResizeArray(0) let gfields = new ResizeArray(0) - let gproperties : Dictionary = new Dictionary<_, _>(3, HashIdentity.Structural) + let gproperties: Dictionary = new Dictionary<_, _>(3, HashIdentity.Structural) let gevents = new ResizeArray(0) let gnested = new TypeDefsBuilder() @@ -1293,7 +1293,7 @@ type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = and TypeDefsBuilder() = - let tdefs : Internal.Utilities.Collections.HashMultiMap = HashMultiMap(0, HashIdentity.Structural) + let tdefs: Internal.Utilities.Collections.HashMultiMap = HashMultiMap(0, HashIdentity.Structural) let mutable countDown = System.Int32.MaxValue member b.Close() = @@ -1317,12 +1317,12 @@ and TypeDefsBuilder() = with :? KeyNotFoundException -> failwith ("FindTypeDefBuilder: " + nm + " not found") member b.FindNestedTypeDefsBuilder(path) = - List.fold (fun (acc:TypeDefsBuilder) x -> acc.FindTypeDefBuilder(x).NestedTypeDefs) b path + List.fold (fun (acc: TypeDefsBuilder) x -> acc.FindTypeDefBuilder(x).NestedTypeDefs) b path - member b.FindNestedTypeDefBuilder(tref:ILTypeRef) = + member b.FindNestedTypeDefBuilder(tref: ILTypeRef) = b.FindNestedTypeDefsBuilder(tref.Enclosing).FindTypeDefBuilder(tref.Name) - member b.AddTypeDef(tdef:ILTypeDef, eliminateIfEmpty, addAtEnd, tdefDiscards) = + member b.AddTypeDef(tdef: ILTypeDef, eliminateIfEmpty, addAtEnd, tdefDiscards) = let idx = if addAtEnd then (countDown <- countDown - 1; countDown) else tdefs.Count tdefs.Add (tdef.Name, (idx, (new TypeDefBuilder(tdef, tdefDiscards), eliminateIfEmpty))) @@ -1331,11 +1331,11 @@ type AnonTypeGenerationTable() = member __.Table = dict /// Assembly generation buffers -type AssemblyBuilder(cenv:cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf = +type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf = // The Abstract IL table of types let gtdefs= new TypeDefsBuilder() // The definitions of top level values, as quotations. - let mutable reflectedDefinitions : Dictionary = Dictionary(HashIdentity.Reference) + let mutable reflectedDefinitions: Dictionary = Dictionary(HashIdentity.Reference) let mutable extraBindingsToGenerate = [] // A memoization table for generating value types for big constant arrays @@ -1474,10 +1474,10 @@ type AssemblyBuilder(cenv:cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf (ilCtorRef, ilMethodRefs, ilTy) - let mutable explicitEntryPointInfo : ILTypeRef option = None + let mutable explicitEntryPointInfo: ILTypeRef option = None /// static init fields on script modules. - let mutable scriptInitFspecs : (ILFieldSpec * range) list = [] + let mutable scriptInitFspecs: (ILFieldSpec * range) list = [] member mgbuf.AddScriptInitFieldSpec(fieldSpec, range) = scriptInitFspecs <- (fieldSpec, range) :: scriptInitFspecs @@ -1489,7 +1489,7 @@ type AssemblyBuilder(cenv:cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf match explicitEntryPointInfo with | Some tref -> let IntializeCompiledScript(fspec, m) = - mgbuf.AddExplicitInitToSpecificMethodDef((fun (md:ILMethodDef) -> 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 +1500,7 @@ type AssemblyBuilder(cenv:cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf let cloc = CompLocForPrivateImplementationDetails cloc rawDataValueTypeGenerator.Apply((cloc, size)) - member mgbuf.GenerateAnonType(genToStringMethod, anonInfo:AnonRecdTypeInfo) = + member mgbuf.GenerateAnonType(genToStringMethod, anonInfo: AnonRecdTypeInfo) = let isStruct = evalAnonInfoIsStruct anonInfo let key = anonInfo.Stamp match anonTypeTable.Table.TryGetValue key with @@ -1510,7 +1510,7 @@ type AssemblyBuilder(cenv:cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf anonTypeTable.Table.[key] <- info info - member mgbuf.LookupAnonType(anonInfo:AnonRecdTypeInfo) = + member mgbuf.LookupAnonType(anonInfo: AnonRecdTypeInfo) = match anonTypeTable.Table.TryGetValue anonInfo.Stamp with | true, res -> res | _ -> failwithf "the anonymous record %A has not been generated in the pre-phase of generating this module" anonInfo.ILTypeRef @@ -1520,13 +1520,13 @@ type AssemblyBuilder(cenv:cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf extraBindingsToGenerate <- [] result - member mgbuf.AddTypeDef(tref:ILTypeRef, tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) = + member mgbuf.AddTypeDef(tref: ILTypeRef, tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) = gtdefs.FindNestedTypeDefsBuilder(tref.Enclosing).AddTypeDef(tdef, eliminateIfEmpty, addAtEnd, tdefDiscards) - member mgbuf.GetCurrentFields(tref:ILTypeRef) = + member mgbuf.GetCurrentFields(tref: ILTypeRef) = gtdefs.FindNestedTypeDefBuilder(tref).GetCurrentFields() - member mgbuf.AddReflectedDefinition(vspec : Tast.Val, expr) = + member mgbuf.AddReflectedDefinition(vspec: Tast.Val, expr) = // preserve order by storing index of item let n = reflectedDefinitions.Count reflectedDefinitions.Add(vspec, (vspec.CompiledName, n, expr)) @@ -1536,7 +1536,7 @@ type AssemblyBuilder(cenv:cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf | true, (name, n, expr) when name <> newName -> reflectedDefinitions.[vspec] <- (newName, n, expr) | _ -> () - member mgbuf.AddMethodDef(tref:ILTypeRef, ilMethodDef) = + member mgbuf.AddMethodDef(tref: ILTypeRef, ilMethodDef) = gtdefs.FindNestedTypeDefBuilder(tref).AddMethodDef(ilMethodDef) if ilMethodDef.IsEntryPoint then explicitEntryPointInfo <- Some(tref) @@ -1576,12 +1576,12 @@ type AssemblyBuilder(cenv:cenv, anonTypeTable: AnonTypeGenerationTable) as mgbuf /// Used for the few times we have to flush the IL evaluation stack and to compute maxStack. type Pushes = ILType list type Pops = int -let pop (i:int) : Pops = i -let Push tys : Pushes = tys +let pop (i: int) : Pops = i +let Push tys: Pushes = tys let Push0 = Push [] -let FeeFee (cenv:cenv) = (if cenv.opts.testFlagEmitFeeFeeAs100001 then 100001 else 0x00feefee) -let FeeFeeInstr (cenv:cenv) doc = +let FeeFee (cenv: cenv) = (if cenv.opts.testFlagEmitFeeFeeAs100001 then 100001 else 0x00feefee) +let FeeFeeInstr (cenv: cenv) doc = I_seqpoint (ILSourceMarker.Create(document = doc, line = FeeFee cenv, column = 0, @@ -1589,10 +1589,10 @@ let FeeFeeInstr (cenv:cenv) doc = endColumn = 0)) /// Buffers for IL code generation -type CodeGenBuffer(m:range, +type CodeGenBuffer(m: range, mgbuf: AssemblyBuilder, methodName, - alreadyUsedArgs:int) = + alreadyUsedArgs: int) = let locals = new ResizeArray<((string * (Mark * Mark)) list * ILType * bool)>(10) let codebuf = new ResizeArray(200) @@ -1606,8 +1606,8 @@ type CodeGenBuffer(m:range, let mutable hasSequencePoints = false let mutable anyDocument = None // we collect an arbitrary document in order to emit the header FeeFee if needed - let codeLabelToPC : Dictionary = new Dictionary<_, _>(10) - let codeLabelToCodeLabel : Dictionary = new Dictionary<_, _>(10) + let codeLabelToPC: Dictionary = new Dictionary<_, _>(10) + let codeLabelToCodeLabel: Dictionary = new Dictionary<_, _>(10) let rec lab2pc n lbl = if n = System.Int32.MaxValue then error(InternalError("recursive label graph", m)) @@ -1629,7 +1629,7 @@ type CodeGenBuffer(m:range, nstack <- nstack + 1 maxStack <- Operators.max maxStack nstack - member cgbuf.DoPops (n:Pops) = + member cgbuf.DoPops (n: Pops) = for i = 0 to n - 1 do match stack with | [] -> @@ -1787,14 +1787,14 @@ type CodeGenBuffer(m:range, (ResizeArray.toList locals, maxStack, codeLabels, instrs, ResizeArray.toList exnSpecs, hasSequencePoints) module CG = - let EmitInstr (cgbuf:CodeGenBuffer) pops pushes i = cgbuf.EmitInstr(pops, pushes, i) - let EmitInstrs (cgbuf:CodeGenBuffer) pops pushes is = cgbuf.EmitInstrs(pops, pushes, is) - let EmitSeqPoint (cgbuf:CodeGenBuffer) src = cgbuf.EmitSeqPoint(src) - let GenerateDelayMark (cgbuf:CodeGenBuffer) nm = cgbuf.GenerateDelayMark(nm) - let SetMark (cgbuf:CodeGenBuffer) m1 m2 = cgbuf.SetMark(m1, m2) - let SetMarkToHere (cgbuf:CodeGenBuffer) m1 = cgbuf.SetMarkToHere(m1) - let SetStack (cgbuf:CodeGenBuffer) s = cgbuf.SetStack(s) - let GenerateMark (cgbuf:CodeGenBuffer) s = cgbuf.Mark(s) + let EmitInstr (cgbuf: CodeGenBuffer) pops pushes i = cgbuf.EmitInstr(pops, pushes, i) + let EmitInstrs (cgbuf: CodeGenBuffer) pops pushes is = cgbuf.EmitInstrs(pops, pushes, is) + let EmitSeqPoint (cgbuf: CodeGenBuffer) src = cgbuf.EmitSeqPoint(src) + let GenerateDelayMark (cgbuf: CodeGenBuffer) nm = cgbuf.GenerateDelayMark(nm) + let SetMark (cgbuf: CodeGenBuffer) m1 m2 = cgbuf.SetMark(m1, m2) + let SetMarkToHere (cgbuf: CodeGenBuffer) m1 = cgbuf.SetMarkToHere(m1) + let SetStack (cgbuf: CodeGenBuffer) s = cgbuf.SetStack(s) + let GenerateMark (cgbuf: CodeGenBuffer) s = cgbuf.Mark(s) open CG @@ -1806,7 +1806,7 @@ open CG let GenString cenv cgbuf s = CG.EmitInstrs cgbuf (pop 0) (Push [cenv.g.ilg.typ_String]) [ I_ldstr s ] -let GenConstArray cenv (cgbuf:CodeGenBuffer) eenv ilElementType (data:'a[]) (write : ByteBuffer -> 'a -> unit) = +let GenConstArray cenv (cgbuf: CodeGenBuffer) eenv ilElementType (data:'a[]) (write: ByteBuffer -> 'a -> unit) = let buf = ByteBuffer.Create data.Length data |> Array.iter (write buf) let bytes = buf.Close() @@ -1880,7 +1880,7 @@ let CodeGenThen cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, c let locals, maxStack, lab2pc, code, exnSpecs, hasSequencePoints = cgbuf.Close() - let localDebugSpecs : ILLocalDebugInfo list = + let localDebugSpecs: ILLocalDebugInfo list = locals |> List.mapi (fun i (nms, _, _isFixed) -> List.map (fun nm -> (i, nm)) nms) |> List.concat @@ -1939,7 +1939,7 @@ let StartLocalScope nm cgbuf = let endScope = CG.GenerateDelayMark cgbuf ("end_" + nm) startScope, endScope -let LocalScope nm cgbuf (f : (Mark * Mark) -> 'a) : 'a = +let LocalScope nm cgbuf (f: (Mark * Mark) -> 'a) : 'a = let _, endScope as scopeMarks = StartLocalScope nm cgbuf let res = f scopeMarks CG.SetMarkToHere cgbuf endScope @@ -2125,7 +2125,7 @@ let DoesGenExprStartWithSequencePoint g sp expr = // Generate expressions //------------------------------------------------------------------------- -let rec GenExpr (cenv:cenv) (cgbuf:CodeGenBuffer) eenv sp expr sequel = +let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = let expr = stripExpr expr @@ -2183,10 +2183,10 @@ let rec GenExpr (cenv:cenv) (cgbuf:CodeGenBuffer) eenv sp expr sequel = ) -> // application of local type functions with type parameters = measure types and body = local value - inine the body GenExpr cenv cgbuf eenv sp v sequel - | Expr.App(f,fty,tyargs,args,m) -> - GenApp cenv cgbuf eenv (f,fty,tyargs,args,m) sequel - | Expr.Val(v,_,m) -> - GenGetVal cenv cgbuf eenv (v,m) sequel + | Expr.App(f ,fty, tyargs, args, m) -> + GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel + | Expr.Val(v, _, m) -> + GenGetVal cenv cgbuf eenv (v, m) sequel // Most generation of linear expressions is implemented routinely using tailcalls and the correct sequels. // This is because the element of expansion happens to be the final thing generated in most cases. However @@ -2194,70 +2194,70 @@ let rec GenExpr (cenv:cenv) (cgbuf:CodeGenBuffer) eenv sp expr sequel = | LinearOpExpr _ -> GenLinearExpr cenv cgbuf eenv expr sequel id |> ignore - | Expr.Op(op,tyargs,args,m) -> - match op,args,tyargs with - | TOp.ExnConstr(c),_,_ -> - GenAllocExn cenv cgbuf eenv (c,args,m) sequel - | TOp.UnionCase(c),_,_ -> - GenAllocUnionCase cenv cgbuf eenv (c,tyargs,args,m) sequel - | TOp.Recd(isCtor,tycon),_,_ -> - GenAllocRecd cenv cgbuf eenv isCtor (tycon,tyargs,args,m) sequel - | TOp.AnonRecd(anonInfo),_,_ -> - GenAllocAnonRecd cenv cgbuf eenv (anonInfo,tyargs,args,m) sequel - | TOp.AnonRecdGet (anonInfo,n),[e],_ -> - GenGetAnonRecdField cenv cgbuf eenv (anonInfo,e,tyargs,n,m) sequel - | TOp.TupleFieldGet (tupInfo,n),[e],_ -> - GenGetTupleField cenv cgbuf eenv (tupInfo,e,tyargs,n,m) sequel - | TOp.ExnFieldGet(ecref,n),[e],_ -> - GenGetExnField cenv cgbuf eenv (e,ecref,n,m) sequel - | TOp.UnionCaseFieldGet(ucref,n),[e],_ -> - GenGetUnionCaseField cenv cgbuf eenv (e,ucref,tyargs,n,m) sequel - | TOp.UnionCaseFieldGetAddr(ucref,n,_readonly),[e],_ -> - GenGetUnionCaseFieldAddr cenv cgbuf eenv (e,ucref,tyargs,n,m) sequel - | TOp.UnionCaseTagGet ucref,[e],_ -> - GenGetUnionCaseTag cenv cgbuf eenv (e,ucref,tyargs,m) sequel - | TOp.UnionCaseProof ucref,[e],_ -> - GenUnionCaseProof cenv cgbuf eenv (e,ucref,tyargs,m) sequel - | TOp.ExnFieldSet(ecref,n),[e;e2],_ -> - GenSetExnField cenv cgbuf eenv (e,ecref,n,e2,m) sequel - | TOp.UnionCaseFieldSet(ucref,n),[e;e2],_ -> - GenSetUnionCaseField cenv cgbuf eenv (e,ucref,tyargs,n,e2,m) sequel - | TOp.ValFieldGet f,[e],_ -> - GenGetRecdField cenv cgbuf eenv (e,f,tyargs,m) sequel - | TOp.ValFieldGet f,[],_ -> - GenGetStaticField cenv cgbuf eenv (f,tyargs,m) sequel - | TOp.ValFieldGetAddr (f, _readonly),[e],_ -> - GenGetRecdFieldAddr cenv cgbuf eenv (e,f,tyargs,m) sequel - | TOp.ValFieldGetAddr (f, _readonly),[],_ -> - GenGetStaticFieldAddr cenv cgbuf eenv (f,tyargs,m) sequel - | TOp.ValFieldSet f,[e1;e2],_ -> - GenSetRecdField cenv cgbuf eenv (e1,f,tyargs,e2,m) sequel - | TOp.ValFieldSet f,[e2],_ -> - GenSetStaticField cenv cgbuf eenv (f,tyargs,e2,m) sequel - | TOp.Tuple tupInfo,_,_ -> - GenAllocTuple cenv cgbuf eenv (tupInfo,args,tyargs,m) sequel - | TOp.ILAsm(code,returnTys),_,_ -> - GenAsmCode cenv cgbuf eenv (code,tyargs,args,returnTys,m) sequel - | TOp.While (sp,_),[Expr.Lambda(_,_,_,[_],e1,_,_);Expr.Lambda(_,_,_,[_],e2,_,_)],[] -> - GenWhileLoop cenv cgbuf eenv (sp,e1,e2,m) sequel - | TOp.For(spStart,dir),[Expr.Lambda(_,_,_,[_],e1,_,_);Expr.Lambda(_,_,_,[_],e2,_,_);Expr.Lambda(_,_,_,[v],e3,_,_)],[] -> - GenForLoop cenv cgbuf eenv (spStart,v,e1,dir,e2,e3,m) sequel - | TOp.TryFinally(spTry,spFinally),[Expr.Lambda(_,_,_,[_],e1,_,_); Expr.Lambda(_,_,_,[_],e2,_,_)],[resty] -> - GenTryFinally cenv cgbuf eenv (e1,e2,m,resty,spTry,spFinally) sequel - | TOp.TryCatch(spTry,spWith),[Expr.Lambda(_,_,_,[_],e1,_,_); Expr.Lambda(_,_,_,[vf],ef,_,_);Expr.Lambda(_,_,_,[vh],eh,_,_)],[resty] -> - GenTryCatch cenv cgbuf eenv (e1,vf,ef,vh,eh,m,resty,spTry,spWith) sequel - | TOp.ILCall(virt,_,valu,newobj,valUseFlags,_,isDllImport,ilMethRef,enclArgTys,methArgTys,returnTys),args,[] -> - GenILCall cenv cgbuf eenv (virt,valu,newobj,valUseFlags,isDllImport,ilMethRef,enclArgTys,methArgTys,args,returnTys,m) sequel - | TOp.RefAddrGet _readonly,[e],[ty] -> GenGetAddrOfRefCellField cenv cgbuf eenv (e,ty,m) sequel - | TOp.Coerce,[e],[tgty;srcty] -> GenCoerce cenv cgbuf eenv (e,tgty,m,srcty) sequel - | TOp.Reraise,[],[rtnty] -> GenReraise cenv cgbuf eenv (rtnty,m) sequel - | TOp.TraitCall(ss),args,[] -> GenTraitCall cenv cgbuf eenv (ss,args, m) expr sequel - | TOp.LValueOp(LSet,v),[e],[] -> GenSetVal cenv cgbuf eenv (v,e,m) sequel - | TOp.LValueOp(LByrefGet,v),[],[] -> GenGetByref cenv cgbuf eenv (v,m) sequel - | TOp.LValueOp(LByrefSet,v),[e],[] -> GenSetByref cenv cgbuf eenv (v,e,m) sequel - | TOp.LValueOp(LAddrOf _,v),[],[] -> GenGetValAddr cenv cgbuf eenv (v,m) sequel - | TOp.Array,elems,[elemTy] -> GenNewArray cenv cgbuf eenv (elems,elemTy,m) sequel - | TOp.Bytes bytes,[],[] -> + | Expr.Op(op, tyargs, args, m) -> + match op, args, tyargs with + | TOp.ExnConstr(c), _, _ -> + GenAllocExn cenv cgbuf eenv (c, args, m) sequel + | TOp.UnionCase(c), _, _ -> + GenAllocUnionCase cenv cgbuf eenv (c, tyargs, args, m) sequel + | TOp.Recd(isCtor, tycon), _, _ -> + GenAllocRecd cenv cgbuf eenv isCtor (tycon, tyargs, args, m) sequel + | TOp.AnonRecd(anonInfo), _, _ -> + GenAllocAnonRecd cenv cgbuf eenv (anonInfo, tyargs, args, m) sequel + | TOp.AnonRecdGet (anonInfo, n), [e], _ -> + GenGetAnonRecdField cenv cgbuf eenv (anonInfo, e, tyargs, n, m) sequel + | TOp.TupleFieldGet (tupInfo, n), [e], _ -> + GenGetTupleField cenv cgbuf eenv (tupInfo, e, tyargs, n, m) sequel + | TOp.ExnFieldGet(ecref, n), [e], _ -> + GenGetExnField cenv cgbuf eenv (e, ecref, n, m) sequel + | TOp.UnionCaseFieldGet(ucref, n), [e], _ -> + GenGetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel + | TOp.UnionCaseFieldGetAddr(ucref, n, _readonly), [e], _ -> + GenGetUnionCaseFieldAddr cenv cgbuf eenv (e, ucref, tyargs, n, m) sequel + | TOp.UnionCaseTagGet ucref, [e], _ -> + GenGetUnionCaseTag cenv cgbuf eenv (e, ucref, tyargs, m) sequel + | TOp.UnionCaseProof ucref, [e], _ -> + GenUnionCaseProof cenv cgbuf eenv (e, ucref, tyargs, m) sequel + | TOp.ExnFieldSet(ecref, n), [e;e2], _ -> + GenSetExnField cenv cgbuf eenv (e, ecref, n, e2, m) sequel + | TOp.UnionCaseFieldSet(ucref, n), [e;e2], _ -> + GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel + | TOp.ValFieldGet f, [e], _ -> + GenGetRecdField cenv cgbuf eenv (e, f, tyargs, m) sequel + | TOp.ValFieldGet f, [], _ -> + GenGetStaticField cenv cgbuf eenv (f, tyargs, m) sequel + | TOp.ValFieldGetAddr (f, _readonly), [e], _ -> + GenGetRecdFieldAddr cenv cgbuf eenv (e, f, tyargs, m) sequel + | TOp.ValFieldGetAddr (f, _readonly), [], _ -> + GenGetStaticFieldAddr cenv cgbuf eenv (f, tyargs, m) sequel + | TOp.ValFieldSet f, [e1;e2], _ -> + GenSetRecdField cenv cgbuf eenv (e1, f, tyargs, e2, m) sequel + | TOp.ValFieldSet f, [e2], _ -> + GenSetStaticField cenv cgbuf eenv (f, tyargs, e2, m) sequel + | TOp.Tuple tupInfo, _, _ -> + GenAllocTuple cenv cgbuf eenv (tupInfo, args, tyargs, m) sequel + | TOp.ILAsm(code, returnTys), _, _ -> + GenAsmCode cenv cgbuf eenv (code, tyargs, args, returnTys, m) sequel + | TOp.While (sp, _), [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _)], [] -> + GenWhileLoop cenv cgbuf eenv (sp, e1, e2, m) sequel + | TOp.For(spStart, dir), [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _);Expr.Lambda(_, _, _, [v], e3, _, _)], [] -> + GenForLoop cenv cgbuf eenv (spStart, v, e1, dir, e2, e3, m) sequel + | TOp.TryFinally(spTry, spFinally), [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)], [resty] -> + GenTryFinally cenv cgbuf eenv (e1, e2, m, resty, spTry, spFinally) sequel + | TOp.TryCatch(spTry, spWith), [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [vf], ef, _, _);Expr.Lambda(_, _, _, [vh], eh, _, _)], [resty] -> + GenTryCatch cenv cgbuf eenv (e1, vf, ef, vh, eh, m, resty, spTry, spWith) sequel + | TOp.ILCall(virt, _, valu, newobj, valUseFlags, _, isDllImport, ilMethRef, enclArgTys, methArgTys, returnTys), args, [] -> + GenILCall cenv cgbuf eenv (virt, valu, newobj, valUseFlags, isDllImport, ilMethRef, enclArgTys, methArgTys, args, returnTys, m) sequel + | TOp.RefAddrGet _readonly, [e], [ty] -> GenGetAddrOfRefCellField cenv cgbuf eenv (e, ty, m) sequel + | TOp.Coerce, [e], [tgty;srcty] -> GenCoerce cenv cgbuf eenv (e, tgty, m, srcty) sequel + | TOp.Reraise, [], [rtnty] -> GenReraise cenv cgbuf eenv (rtnty, m) sequel + | TOp.TraitCall(ss), args, [] -> GenTraitCall cenv cgbuf eenv (ss, args, m) expr sequel + | TOp.LValueOp(LSet, v), [e], [] -> GenSetVal cenv cgbuf eenv (v, e, m) sequel + | TOp.LValueOp(LByrefGet, v), [], [] -> GenGetByref cenv cgbuf eenv (v, m) sequel + | TOp.LValueOp(LByrefSet, v), [e], [] -> GenSetByref cenv cgbuf eenv (v, e, m) sequel + | TOp.LValueOp(LAddrOf _, v), [], [] -> GenGetValAddr cenv cgbuf eenv (v, m) sequel + | TOp.Array, elems, [elemTy] -> GenNewArray cenv cgbuf eenv (elems, elemTy, m) sequel + | TOp.Bytes bytes, [], [] -> if cenv.opts.emitConstantArraysUsingStaticDataBlobs then GenConstArray cenv cgbuf eenv cenv.g.ilg.typ_Byte bytes (fun buf b -> buf.EmitByte b) GenSequel cenv eenv.cloc cgbuf sequel @@ -2464,7 +2464,7 @@ and GenAllocTuple cenv cgbuf eenv (tupInfo, args, argtys, m) sequel = and GenGetTupleField cenv cgbuf eenv (tupInfo, e, tys, n, m) sequel = let tupInfo = evalTupInfoIsStruct tupInfo - let rec getCompiledTupleItem g (e, tys:TTypes, n, m) = + let rec getCompiledTupleItem g (e, tys: TTypes, n, m) = let ar = tys.Length if ar <= 0 then failwith "getCompiledTupleItem" elif ar < maxTuple then @@ -2779,7 +2779,7 @@ and GenSetStaticField cenv cgbuf eenv (f, tyargs, e2, m) sequel = and mk_field_pops isStatic n = if isStatic then pop n else pop (n+1) -and GenFieldGet isStatic cenv cgbuf eenv (rfref:RecdFieldRef, tyargs, m) = +and GenFieldGet isStatic cenv cgbuf eenv (rfref: RecdFieldRef, tyargs, m) = let fspec = GenRecdFieldRef m cenv eenv.tyenv rfref tyargs let vol = if rfref.RecdField.IsVolatile then Volatile else Nonvolatile if useGenuineField rfref.Tycon rfref.RecdField || entityRefInThisAssembly cenv.g.compilingFslib rfref.TyconRef then @@ -2790,7 +2790,7 @@ and GenFieldGet isStatic cenv cgbuf eenv (rfref:RecdFieldRef, tyargs, m) = let mspec = mkILMethSpecInTy (fspec.DeclaringType, cconv, "get_" + rfref.RecdField.rfield_id.idText, [], fspec.FormalType, []) CG.EmitInstr cgbuf (mk_field_pops isStatic 0) (Push [fspec.ActualType]) (mkNormalCall mspec) -and GenFieldStore isStatic cenv cgbuf eenv (rfref:RecdFieldRef, tyargs, m) sequel = +and GenFieldStore isStatic cenv cgbuf eenv (rfref: RecdFieldRef, tyargs, m) sequel = let fspec = GenRecdFieldRef m cenv eenv.tyenv rfref tyargs let fld = rfref.RecdField if fld.IsMutable && not (useGenuineField rfref.Tycon fld) then @@ -3108,7 +3108,7 @@ and GenNamedLocalTyFuncCall cenv (cgbuf: CodeGenBuffer) eenv ty cloinfo tyargs m let ilTyArgs = tyargs |> GenTypeArgs cenv.amap m eenv.tyenv - let _, (ilContractMethTyargs: ILGenericParameterDefs), (ilContractCloTySpec:ILTypeSpec), ilContractFormalRetTy = + let _, (ilContractMethTyargs: ILGenericParameterDefs), (ilContractCloTySpec: ILTypeSpec), ilContractFormalRetTy = GenNamedLocalTypeFuncContractInfo cenv eenv m cloinfo let ilContractTy = mkILBoxedTy ilContractCloTySpec.TypeRef ilContractClassTyargs @@ -3211,7 +3211,7 @@ and GenTry cenv cgbuf eenv scopeMarks (e1, m, resty, spTry) = let tryMarks = (startTryMark.CodeLabel, endTryMark.CodeLabel) whereToSave, eenvinner, stack, tryMarks, afterHandler, ilResultTy -and GenTryCatch cenv cgbuf eenv (e1, vf:Val, ef, vh:Val, eh, m, resty, spTry, spWith) sequel = +and GenTryCatch cenv cgbuf eenv (e1, vf: Val, ef, vh: Val, eh, m, resty, spTry, spWith) sequel = // Save the stack - gross because IL flushes the stack at the exn. handler // note: eenvinner notes spill vars are live LocalScope "trystack" cgbuf (fun scopeMarks -> @@ -3677,7 +3677,7 @@ and GenQuotation cenv cgbuf eenv (ast, conv, m, ety) sequel = // Generate calls to IL methods //-------------------------------------------------------------------------- -and GenILCall cenv cgbuf eenv (virt, valu, newobj, valUseFlags, isDllImport, ilMethRef:ILMethodRef, enclArgTys, methArgTys, argExprs, returnTys, m) sequel = +and GenILCall cenv cgbuf eenv (virt, valu, newobj, valUseFlags, isDllImport, ilMethRef: ILMethodRef, enclArgTys, methArgTys, argExprs, returnTys, m) sequel = let hasByrefArg = ilMethRef.ArgTypes |> List.exists IsILTypeByref let isSuperInit = match valUseFlags with CtorValUsedAsSuperInit -> true | _ -> false let isBaseCall = match valUseFlags with VSlotDirectCall -> true | _ -> false @@ -3775,13 +3775,13 @@ and GenGetValAddr cenv cgbuf eenv (v: ValRef, m) sequel = GenSequel cenv eenv.cloc cgbuf sequel -and GenGetByref cenv cgbuf eenv (v:ValRef, m) sequel = +and GenGetByref cenv cgbuf eenv (v: ValRef, m) sequel = GenGetLocalVRef cenv cgbuf eenv m v None let ilty = GenType cenv.amap m eenv.tyenv (destByrefTy cenv.g v.Type) CG.EmitInstrs cgbuf (pop 1) (Push [ilty]) [ mkNormalLdobj ilty ] GenSequel cenv eenv.cloc cgbuf sequel -and GenSetByref cenv cgbuf eenv (v:ValRef, e, m) sequel = +and GenSetByref cenv cgbuf eenv (v: ValRef, e, m) sequel = GenGetLocalVRef cenv cgbuf eenv m v None GenExpr cenv cgbuf eenv SPSuppress e Continue let ilty = GenType cenv.amap m eenv.tyenv (destByrefTy cenv.g v.Type) @@ -3828,7 +3828,7 @@ and GenDefaultValue cenv cgbuf eenv (ty, m) = // Generate generic parameters //-------------------------------------------------------------------------- -and GenGenericParam cenv eenv (tp:Typar) = +and GenGenericParam cenv eenv (tp: Typar) = let subTypeConstraints = tp.Constraints |> List.choose (function | TyparConstraint.CoercesTo(ty, _) -> Some(ty) | _ -> None) @@ -3958,16 +3958,16 @@ and bindBaseOrThisVarOpt cenv eenv baseValOpt = | None -> eenv | Some basev -> AddStorageForVal cenv.g (basev, notlazy (Arg 0)) eenv -and fixupVirtualSlotFlags (mdef:ILMethodDef) = +and fixupVirtualSlotFlags (mdef: ILMethodDef) = mdef.WithHideBySig() -and renameMethodDef nameOfOverridingMethod (mdef : ILMethodDef) = +and renameMethodDef nameOfOverridingMethod (mdef: ILMethodDef) = mdef.With(name=nameOfOverridingMethod) -and fixupMethodImplFlags (mdef:ILMethodDef) = +and fixupMethodImplFlags (mdef: ILMethodDef) = mdef.WithAccess(ILMemberAccess.Private).WithHideBySig().WithFinal(true).WithNewSlot -and GenObjectMethod cenv eenvinner (cgbuf:CodeGenBuffer) useMethodImpl tmethod = +and GenObjectMethod cenv eenvinner (cgbuf: CodeGenBuffer) useMethodImpl tmethod = // Check if we're compiling the property as a .NET event let (TObjExprMethod(slotsig, attribs, methTyparsOfOverridingMethod, methodParams, methodBodyExpr, m)) = tmethod @@ -4055,9 +4055,9 @@ and GenObjectExpr cenv cgbuf eenvouter expr (baseType, baseValOpt, basecall, ove and GenSequenceExpr cenv - (cgbuf:CodeGenBuffer) + (cgbuf: CodeGenBuffer) eenvouter - (nextEnumeratorValRef:ValRef, pcvref:ValRef, currvref:ValRef, stateVars, generateNextExpr, closeExpr, checkCloseExpr:Expr, seqElemTy, m) sequel = + (nextEnumeratorValRef: ValRef, pcvref: ValRef, currvref: ValRef, stateVars, generateNextExpr, closeExpr, checkCloseExpr: Expr, seqElemTy, m) sequel = let stateVars = [ pcvref; currvref ] @ stateVars let stateVarsSet = stateVars |> List.map (fun vref -> vref.Deref) |> Zset.ofList valOrder @@ -4067,7 +4067,7 @@ and GenSequenceExpr eenvouter |> AddStorageForLocalVals cenv.g (stateVars |> List.map (fun v -> v.Deref, Local(0, false, None))) // Get the free variables. Make a lambda to pretend that the 'nextEnumeratorValRef' is bound (it is an argument to GenerateNext) - let (cloAttribs, _, _, cloFreeTyvars, cloFreeVars, ilCloTypeRef:ILTypeRef, ilCloFreeVars, eenvinner) = + let (cloAttribs, _, _, cloFreeTyvars, cloFreeVars, ilCloTypeRef: ILTypeRef, ilCloFreeVars, eenvinner) = GetIlxClosureFreeVars cenv m None eenvouter [] (mkLambda m nextEnumeratorValRef.Deref (generateNextExpr, cenv.g.int32_ty)) let ilCloSeqElemTy = GenType cenv.amap m eenvinner.tyenv seqElemTy @@ -4154,7 +4154,7 @@ and GenSequenceExpr /// Generate the class for a closure type definition -and GenClosureTypeDefs cenv (tref:ILTypeRef, ilGenParams, attrs, ilCloFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, ext, ilIntfTys) = +and GenClosureTypeDefs cenv (tref: ILTypeRef, ilGenParams, attrs, ilCloFreeVars, ilCloLambdas, ilCtorBody, mdefs, mimpls, ext, ilIntfTys) = let cloInfo = { cloFreeVars=ilCloFreeVars @@ -4190,7 +4190,7 @@ and GenClosureTypeDefs cenv (tref:ILTypeRef, ilGenParams, attrs, ilCloFreeVars, and GenGenericParams cenv eenv tps = tps |> DropErasedTypars |> List.map (GenGenericParam cenv eenv) -and GenGenericArgs m (tyenv:TypeReprEnv) tps = +and GenGenericArgs m (tyenv: TypeReprEnv) tps = tps |> DropErasedTypars |> List.map (fun c -> (mkILTyvarTy tyenv.[c, m])) /// Generate the closure class for a function @@ -4212,7 +4212,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr if isLocalTypeFunc then // Work out the contract type and generate a class with an abstract method for this type - let (ilContractGenericParams, ilContractMethTyargs, ilContractTySpec:ILTypeSpec, ilContractFormalRetTy) = GenNamedLocalTypeFuncContractInfo cenv eenv m cloinfo + let (ilContractGenericParams, ilContractMethTyargs, ilContractTySpec: ILTypeSpec, ilContractFormalRetTy) = GenNamedLocalTypeFuncContractInfo cenv eenv m cloinfo let ilContractTypeRef = ilContractTySpec.TypeRef let ilContractTy = mkILFormalBoxedTy ilContractTypeRef ilContractGenericParams let ilContractCtor = mkILNonGenericEmptyCtor None cenv.g.ilg.typ_Object @@ -4261,7 +4261,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr | _ -> failwith "GenLambda: not a lambda" -and GenLambdaVal cenv (cgbuf:CodeGenBuffer) eenv (cloinfo, m) = +and GenLambdaVal cenv (cgbuf: CodeGenBuffer) eenv (cloinfo, m) = GenGetLocalVals cenv cgbuf eenv m cloinfo.cloFreeVars CG.EmitInstr cgbuf (pop cloinfo.cloILFreeVars.Length) @@ -4273,10 +4273,10 @@ and GenLambda cenv cgbuf eenv isLocalTypeFunc selfv expr sequel = GenLambdaVal cenv cgbuf eenv (cloinfo, m) GenSequel cenv eenv.cloc cgbuf sequel -and GenTypeOfVal cenv eenv (v:Val) = +and GenTypeOfVal cenv eenv (v: Val) = GenType cenv.amap v.Range eenv.tyenv v.Type -and GenFreevar cenv m eenvouter tyenvinner (fv:Val) = +and GenFreevar cenv m eenvouter tyenvinner (fv: Val) = match StorageForVal m fv eenvouter with // Local type functions | Local(_, _, Some _) | Env(_, _, _, Some _) -> cenv.g.ilg.typ_Object @@ -4329,7 +4329,7 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = | _ -> true) // The general shape is: - // {LAM . expr }[free-typars] : overall-type[contract-typars] + // {LAM . expr }[free-typars]: overall-type[contract-typars] // Then // internal-typars = free-typars - contract-typars // @@ -4409,7 +4409,7 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = let (cloAttribs, cloInternalFreeTyvars, cloContractFreeTyvars, _, cloFreeVars, ilCloTypeRef, ilCloFreeVars, eenvinner) = GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr // Put the type and value arguments into the environment - let rec getClosureArgs eenv ntmargs tvsl (vs:Val list) = + let rec getClosureArgs eenv ntmargs tvsl (vs: Val list) = match tvsl, vs with | tvs :: rest, _ -> let eenv = AddTyparsToEnv tvs eenv @@ -4437,7 +4437,7 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = let ilReturnTy = GenType cenv.amap m eenvinner.tyenv returnTy // The general shape is: - // {LAM . expr }[free-typars] : overall-type[contract-typars] + // {LAM . expr }[free-typars]: overall-type[contract-typars] // Then // internal-typars = free-typars - contract-typars // @@ -4515,7 +4515,7 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = // Named local type functions //-------------------------------------------------------------------------- -and IsNamedLocalTypeFuncVal g (v:Val) expr = +and IsNamedLocalTypeFuncVal g (v: Val) expr = not v.IsCompiledAsTopLevel && IsGenericValWithGenericContraints g v && (match stripExpr expr with Expr.TyLambda _ -> true | _ -> false) @@ -4758,7 +4758,7 @@ and GetTarget (targets:_[]) n = and GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx targets repeatSP targetInfos sequel = let (TTarget(vs, successExpr, spTarget)) = GetTarget targets targetIdx match TryFindTargetInfo targetInfos targetIdx with - | Some (_, targetMarkAfterBinds:Mark, eenvAtTarget, _, _, _, _, _, _, _) -> + | Some (_, targetMarkAfterBinds: Mark, eenvAtTarget, _, _, _, _, _, _, _) -> // If not binding anything we can go directly to the targetMarkAfterBinds point // This is useful to avoid lots of branches e.g. in match A | B | C -> e @@ -5020,14 +5020,14 @@ and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester eenv successTree GenDecisionTreeAndTargetsInner cenv cgbuf (Some failure) stackAtTargets eenv failureTree targets repeatSP targetInfos sequel /// Generate fixups for letrec bindings -and GenLetRecFixup cenv cgbuf eenv (ilxCloSpec:IlxClosureSpec, e, ilField:ILFieldSpec, e2, _m) = +and GenLetRecFixup cenv cgbuf eenv (ilxCloSpec: IlxClosureSpec, e, ilField: ILFieldSpec, e2, _m) = GenExpr cenv cgbuf eenv SPSuppress e Continue CG.EmitInstrs cgbuf (pop 0) Push0 [ I_castclass ilxCloSpec.ILType ] GenExpr cenv cgbuf eenv SPSuppress e2 Continue CG.EmitInstrs cgbuf (pop 2) Push0 [ mkNormalStfld (mkILFieldSpec(ilField.FieldRef, ilxCloSpec.ILType)) ] /// Generate letrec bindings -and GenLetRecBindings cenv (cgbuf:CodeGenBuffer) eenv (allBinds: Bindings, m) = +and GenLetRecBindings cenv (cgbuf: CodeGenBuffer) eenv (allBinds: Bindings, m) = // Fix up recursion for non-toplevel recursive bindings let bindsPossiblyRequiringFixup = allBinds |> List.filter (fun b -> @@ -5061,7 +5061,7 @@ and GenLetRecBindings cenv (cgbuf:CodeGenBuffer) eenv (allBinds: Bindings, m) = let fixups = ref [] let recursiveVars = Zset.addList (bindsPossiblyRequiringFixup |> List.map (fun v -> v.Var)) (Zset.empty valOrder) let _ = - (recursiveVars, bindsPossiblyRequiringFixup) ||> List.fold (fun forwardReferenceSet (bind:Binding) -> + (recursiveVars, bindsPossiblyRequiringFixup) ||> List.fold (fun forwardReferenceSet (bind: Binding) -> // Compute fixups bind.Expr |> IterateRecursiveFixups cenv.g (Some bind.Var) (computeFixupsForOneRecursiveVar bind.Var forwardReferenceSet fixups) @@ -5073,7 +5073,7 @@ and GenLetRecBindings cenv (cgbuf:CodeGenBuffer) eenv (allBinds: Bindings, m) = // Generate the actual bindings let _ = - (recursiveVars, allBinds) ||> List.fold (fun forwardReferenceSet (bind:Binding) -> + (recursiveVars, allBinds) ||> List.fold (fun forwardReferenceSet (bind: Binding) -> GenBinding cenv cgbuf eenv bind // Record the variable as defined let forwardReferenceSet = Zset.remove bind.Var forwardReferenceSet @@ -5190,7 +5190,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s | StaticField (fspec, vref, hasLiteralAttr, ilTyForProperty, ilPropName, fty, ilGetterMethRef, ilSetterMethRef, optShadowLocal) -> let mut = vspec.IsMutable - let canTarget(targets, goal : System.AttributeTargets) = + let canTarget(targets, goal: System.AttributeTargets) = match targets with | None -> true | Some tgts -> 0 <> int(tgts &&& goal) @@ -5428,7 +5428,7 @@ and GenParamAttribs cenv paramTy attribs = inFlag, outFlag, optionalFlag, defaultValue, Marshal, attribs /// Generate IL parameters -and GenParams cenv eenv (mspec:ILMethodSpec) (attribs:ArgReprInfo list) methodArgTys (implValsOpt: Val list option) = +and GenParams cenv eenv (mspec: ILMethodSpec) (attribs: ArgReprInfo list) methodArgTys (implValsOpt: Val list option) = let ilArgTys = mspec.FormalArgTypes let argInfosAndTypes = if List.length attribs = List.length ilArgTys then List.zip ilArgTys attribs @@ -5467,7 +5467,7 @@ and GenParams cenv eenv (mspec:ILMethodSpec) (attribs:ArgReprInfo list) methodAr | Some attr -> ilAttribs @ [attr] | None -> ilAttribs - let param : ILParameter = + let param: ILParameter = { Name=nmOpt Type= ilArgTy Default=defaultParamValue @@ -5482,7 +5482,7 @@ and GenParams cenv eenv (mspec:ILMethodSpec) (attribs:ArgReprInfo list) methodAr |> fst /// Generate IL method return information -and GenReturnInfo cenv eenv ilRetTy (retInfo : ArgReprInfo) : ILReturn = +and GenReturnInfo cenv eenv ilRetTy (retInfo: ArgReprInfo) : ILReturn = let marshal, attribs = GenMarshal cenv retInfo.Attribs { Type=ilRetTy Marshal=marshal @@ -5504,7 +5504,7 @@ and GenPropertyForMethodDef compileAsInstance tref mdef (v: Val) (memberInfo: Va customAttrs = ilAttrs) /// Generate an ILEventDef for a [] member -and GenEventForProperty cenv eenvForMeth (mspec:ILMethodSpec) (v:Val) ilAttrsThatGoOnPrimaryItem m returnTy = +and GenEventForProperty cenv eenvForMeth (mspec: ILMethodSpec) (v: Val) ilAttrsThatGoOnPrimaryItem m returnTy = let evname = v.PropertyName let delegateTy = Infos.FindDelegateTypeOfPropertyEvent cenv.g cenv.amap evname m returnTy let ilDelegateTy = GenType cenv.amap m eenvForMeth.tyenv delegateTy @@ -5520,7 +5520,7 @@ and GenEventForProperty cenv eenvForMeth (mspec:ILMethodSpec) (v:Val) ilAttrsTha otherMethods= [], customAttrs = mkILCustomAttrs ilAttrsThatGoOnPrimaryItem) -and ComputeFlagFixupsForMemberBinding cenv (v:Val, memberInfo:ValMemberInfo) = +and ComputeFlagFixupsForMemberBinding cenv (v: Val, memberInfo: ValMemberInfo) = if isNil memberInfo.ImplementedSlotSigs then [fixupVirtualSlotFlags] else @@ -5556,7 +5556,7 @@ and ComputeFlagFixupsForMemberBinding cenv (v:Val, memberInfo:ValMemberInfo) = else fixupVirtualSlotFlags >> renameMethodDef nameOfOverridingMethod) -and ComputeMethodImplAttribs cenv (_v:Val) attrs = +and ComputeMethodImplAttribs cenv (_v: Val) attrs = let implflags = match TryFindFSharpAttribute cenv.g cenv.g.attrib_MethodImplAttribute attrs with | Some (Attrib(_, _, [ AttribInt32Arg flags ], _, _, _, _)) -> flags @@ -5585,7 +5585,7 @@ and ComputeMethodImplAttribs cenv (_v:Val) attrs = and GenMethodForBinding cenv cgbuf eenv - (v:Val, mspec, access, paramInfos, retInfo) + (v: Val, mspec, access, paramInfos, retInfo) (topValInfo, ctorThisValOpt, baseValOpt, tps, methodVars, methodArgTys, body, returnTy) = let m = v.Range @@ -5688,7 +5688,7 @@ and GenMethodForBinding let methName = mspec.Name let tref = mspec.MethodRef.DeclaringTypeRef - let EmitTheMethodDef (mdef:ILMethodDef) = + let EmitTheMethodDef (mdef: ILMethodDef) = // Does the function have an explicit [] attribute? let isExplicitEntryPoint = HasFSharpAttribute cenv.g cenv.g.attrib_EntryPointAttribute attrs @@ -5857,15 +5857,15 @@ and GenSetVal cenv cgbuf eenv (vref, e, m) sequel = GenSetStorage vref.Range cgbuf storage GenUnitThenSequel cenv eenv m eenv.cloc cgbuf sequel -and GenGetValRefAndSequel cenv cgbuf eenv m (v:ValRef) fetchSequel = +and GenGetValRefAndSequel cenv cgbuf eenv m (v: ValRef) fetchSequel = let ty = v.Type GenGetStorageAndSequel cenv cgbuf eenv m (ty, GenType cenv.amap m eenv.tyenv ty) (StorageForValRef m v eenv) fetchSequel -and GenGetVal cenv cgbuf eenv (v:ValRef, m) sequel = +and GenGetVal cenv cgbuf eenv (v: ValRef, m) sequel = GenGetValRefAndSequel cenv cgbuf eenv m v None GenSequel cenv eenv.cloc cgbuf sequel -and GenBindingRhs cenv cgbuf eenv sp (vspec:Val) e = +and GenBindingRhs cenv cgbuf eenv sp (vspec: Val) e = match e with | Expr.TyLambda _ | Expr.Lambda _ -> let isLocalTypeFunc = IsNamedLocalTypeFuncVal cenv.g vspec e @@ -5996,13 +5996,13 @@ and GenGetStorageAndSequel cenv cgbuf eenv m (ty, ilTy) storage storeSequel = and GenGetLocalVals cenv cgbuf eenvouter m fvs = List.iter (fun v -> GenGetLocalVal cenv cgbuf eenvouter m v None) fvs -and GenGetLocalVal cenv cgbuf eenv m (vspec:Val) fetchSequel = +and GenGetLocalVal cenv cgbuf eenv m (vspec: Val) fetchSequel = GenGetStorageAndSequel cenv cgbuf eenv m (vspec.Type, GenTypeOfVal cenv eenv vspec) (StorageForVal m vspec eenv) fetchSequel -and GenGetLocalVRef cenv cgbuf eenv m (vref:ValRef) fetchSequel = +and GenGetLocalVRef cenv cgbuf eenv m (vref: ValRef) fetchSequel = GenGetStorageAndSequel cenv cgbuf eenv m (vref.Type, GenTypeOfVal cenv eenv vref.Deref) (StorageForValRef m vref eenv) fetchSequel -and GenStoreVal cgbuf eenv m (vspec:Val) = +and GenStoreVal cgbuf eenv m (vspec: Val) = GenSetStorage vspec.Range cgbuf (StorageForVal m vspec eenv) /// Allocate IL locals @@ -6123,7 +6123,7 @@ and EmitRestoreStack cgbuf (savedStack, savedStackLocals) = //GenAttr: custom attribute generation //------------------------------------------------------------------------- -and GenAttribArg amap g eenv x (ilArgTy:ILType) = +and GenAttribArg amap g eenv x (ilArgTy: ILType) = match x, ilArgTy with @@ -6224,7 +6224,7 @@ and GenAttr amap g eenv (Attrib(_, k, args, props, _, _, _)) = and GenAttrs cenv eenv attrs = List.map (GenAttr cenv.amap cenv.g eenv) attrs -and GenCompilationArgumentCountsAttr cenv (v:Val) = +and GenCompilationArgumentCountsAttr cenv (v: Val) = [ match v.ValReprInfo with | Some(tvi) when v.IsMemberOrModuleBinding -> let arities = if ValSpecIsCompiledAsInstance cenv.g v then List.tail tvi.AritiesOfArgs else tvi.AritiesOfArgs @@ -6234,7 +6234,7 @@ and GenCompilationArgumentCountsAttr cenv (v:Val) = () ] // Create a permission set for a list of security attributes -and CreatePermissionSets cenv eenv (securityAttributes : Attrib list) = +and CreatePermissionSets cenv eenv (securityAttributes: Attrib list) = [for ((Attrib(tcref, _, actions, _, _, _, _)) as attr) in securityAttributes do let action = match actions with | [AttribInt32Arg act] -> act | _ -> failwith "internal error: unrecognized security action" let secaction = (List.assoc action (Lazy.force ILSecurityActionRevMap)) @@ -6291,7 +6291,7 @@ and GenModuleExpr cenv cgbuf qname lazyInitInfo eenv x = and GenModuleDefs cenv cgbuf qname lazyInitInfo eenv mdefs = mdefs |> List.iter (GenModuleDef cenv cgbuf qname lazyInitInfo eenv) -and GenModuleDef cenv (cgbuf:CodeGenBuffer) qname lazyInitInfo eenv x = +and GenModuleDef cenv (cgbuf: CodeGenBuffer) qname lazyInitInfo eenv x = match x with | TMDefRec(_isRec, tycons, mbinds, m) -> tycons |> List.iter (fun tc -> @@ -6314,7 +6314,7 @@ and GenModuleDef cenv (cgbuf:CodeGenBuffer) qname lazyInitInfo eenv x = // Generate a module binding -and GenModuleBinding cenv (cgbuf:CodeGenBuffer) (qname:QualifiedNameOfFile) lazyInitInfo eenv m x = +and GenModuleBinding cenv (cgbuf: CodeGenBuffer) (qname: QualifiedNameOfFile) lazyInitInfo eenv m x = match x with | ModuleOrNamespaceBinding.Binding bind -> GenLetRecBindings cenv cgbuf eenv ([bind], m) @@ -6436,7 +6436,7 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, // well for the bindings earlier in the file containing the entrypoint. match mgbuf.GetExplicitEntryPointInfo() with - // Final file, explicit entry point : place the code in a .cctor, and add code to main that forces the .cctor (if topCode has initialization effect). + // Final file, explicit entry point: place the code in a .cctor, and add code to main that forces the .cctor (if topCode has initialization effect). | Some tref -> if doesSomething then lazyInitInfo.Add (fun fspec feefee seqpt -> @@ -6465,7 +6465,7 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, mgbuf.AddMethodDef(initClassTy.TypeRef, ilMainMethodDef) - // Library file : generate an optional .cctor if topCode has initialization effect + // Library file: generate an optional .cctor if topCode has initialization effect | None -> if doesSomething then @@ -6507,14 +6507,14 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, eenvafter -and GenForceWholeFileInitializationAsPartOfCCtor cenv (mgbuf:AssemblyBuilder) (lazyInitInfo: ResizeArray<_>) tref m = +and GenForceWholeFileInitializationAsPartOfCCtor cenv (mgbuf: AssemblyBuilder) (lazyInitInfo: ResizeArray<_>) tref m = // Authoring a .cctor with effects forces the cctor for the 'initialization' module by doing a dummy store & load of a field // Doing both a store and load keeps FxCop happier because it thinks the field is useful lazyInitInfo.Add (fun fspec feefee seqpt -> mgbuf.AddExplicitInitToSpecificMethodDef((fun md -> md.Name = ".cctor"), tref, fspec, GenPossibleILSourceMarker cenv m, feefee, seqpt)) /// Generate an Equals method. -and GenEqualsOverrideCallingIComparable cenv (tcref:TyconRef, ilThisTy, _ilThatTy) = +and GenEqualsOverrideCallingIComparable cenv (tcref: TyconRef, ilThisTy, _ilThatTy) = let mspec = mkILNonGenericInstanceMethSpecInTy (cenv.g.iltyp_IComparable, "CompareTo", [cenv.g.ilg.typ_Object], cenv.g.ilg.typ_Int32) mkILNonGenericVirtualMethod @@ -6539,7 +6539,7 @@ and GenFieldInit m c = | ConstToILFieldInit fieldInit -> fieldInit | _ -> error(Error(FSComp.SR.ilTypeCannotBeUsedForLiteralField(), m)) -and GenAbstractBinding cenv eenv tref (vref:ValRef) = +and GenAbstractBinding cenv eenv tref (vref: ValRef) = assert(vref.IsMember) let m = vref.Range let memberInfo = Option.get vref.MemberInfo @@ -6631,7 +6631,7 @@ and GenToStringMethod cenv eenv ilThisTy m = yield mdef | _ -> () ] -and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = +and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let tcref = mkLocalTyconRef tycon if tycon.IsTypeAbbrev then () else match tycon.TypeReprInfo with @@ -6921,7 +6921,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = yield ilMethodDef.WithSpecialName if generateDebugDisplayAttribute then - let (|Lazy|) (x:Lazy<_>) = x.Force() + let (|Lazy|) (x: Lazy<_>) = x.Force() match (eenv.valsInScope.TryFind cenv.g.sprintf_vref.Deref, eenv.valsInScope.TryFind cenv.g.new_format_vref.Deref) with | Some(Lazy(Method(_, _, sprintfMethSpec, _, _, _, _))), Some(Lazy(Method(_, _, newFormatMethSpec, _, _, _, _))) -> @@ -7227,7 +7227,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon:Tycon) = /// Generate the type for an F# exception declaration. -and GenExnDef cenv mgbuf eenv m (exnc:Tycon) = +and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = let exncref = mkLocalEntityRef exnc match exnc.ExceptionInfo with | TExnAbbrevRepr _ | TExnAsmRepr _ | TExnNone -> () @@ -7368,7 +7368,7 @@ let CodegenAssembly cenv eenv mgbuf fileImpls = // structures representing the contents of the module. //------------------------------------------------------------------------- -let GetEmptyIlxGenEnv (ilg : ILGlobals) ccu = +let GetEmptyIlxGenEnv (ilg: ILGlobals) ccu = let thisCompLoc = CompLocForCcu ccu { tyenv=TypeReprEnv.Empty cloc = thisCompLoc @@ -7383,10 +7383,10 @@ let GetEmptyIlxGenEnv (ilg : ILGlobals) ccu = type IlxGenResults = { ilTypeDefs: ILTypeDef list - ilAssemAttrs : ILAttribute list + ilAssemAttrs: ILAttribute list ilNetModuleAttrs: ILAttribute list - topAssemblyAttrs : Attribs - permissionSets : ILSecurityDecl list + topAssemblyAttrs: Attribs + permissionSets: ILSecurityDecl list quotationResourceInfo: (ILTypeRef list * byte[]) list } @@ -7469,10 +7469,10 @@ open System.Reflection /// The lookup* functions are the conversions available from ilreflect. type ExecutionContext = - { LookupFieldRef : (ILFieldRef -> FieldInfo) - LookupMethodRef : (ILMethodRef -> MethodInfo) - LookupTypeRef : (ILTypeRef -> Type) - LookupType : (ILType -> Type) } + { LookupFieldRef: (ILFieldRef -> FieldInfo) + LookupMethodRef: (ILMethodRef -> MethodInfo) + LookupTypeRef: (ILTypeRef -> Type) + LookupType: (ILType -> Type) } // A helper to generate a default value for any System.Type. I couldn't find a System.Reflection // method to do this. @@ -7487,9 +7487,9 @@ let defaultOf = /// Top-level val bindings are stored (for example) in static fields. /// In the FSI case, these fields are be created and initialised, so we can recover the object. /// IlxGen knows how v was stored, and then ilreflect knows how this storage was generated. -/// IlxGen converts (v:Tast.Val) to AbsIL datastructures. +/// IlxGen converts (v: Tast.Val) to AbsIL datastructures. /// Ilreflect converts from AbsIL datastructures to emitted Type, FieldInfo, MethodInfo etc. -let LookupGeneratedValue (amap:ImportMap) (ctxt: ExecutionContext) eenv (v:Val) = +let LookupGeneratedValue (amap: ImportMap) (ctxt: ExecutionContext) eenv (v: Val) = try // Convert the v.Type into a System.Type according to ilxgen and ilreflect. let objTyp() = @@ -7502,14 +7502,14 @@ let LookupGeneratedValue (amap:ImportMap) (ctxt: ExecutionContext) eenv (v:Val) if hasLiteralAttr then let staticTy = ctxt.LookupTypeRef fspec.DeclaringTypeRef // Checked: This FieldInfo (FieldBuilder) supports GetValue(). - staticTy.GetField(fspec.Name).GetValue(null:obj) + staticTy.GetField(fspec.Name).GetValue(null: obj) else let staticTy = ctxt.LookupTypeRef ilContainerTy.TypeRef // We can't call .Invoke on the ILMethodRef's MethodInfo, // because it is the MethodBuilder and that does not support Invoke. // Rather, we look for the getter MethodInfo from the built type and .Invoke on that. let methInfo = staticTy.GetMethod(ilGetterMethRef.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) - methInfo.Invoke((null:obj), (null:obj[])) + methInfo.Invoke((null: obj), (null: obj[])) Some (obj, objTyp()) | StaticProperty (ilGetterMethSpec, _) -> @@ -7519,7 +7519,7 @@ let LookupGeneratedValue (amap:ImportMap) (ctxt: ExecutionContext) eenv (v:Val) // because it is the MethodBuilder and that does not support Invoke. // Rather, we look for the getter MethodInfo from the built type and .Invoke on that. let methInfo = staticTy.GetMethod(ilGetterMethSpec.Name, BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic) - methInfo.Invoke((null:obj), (null:obj[])) + methInfo.Invoke((null: obj), (null: obj[])) Some (obj, objTyp()) | Null -> @@ -7536,7 +7536,7 @@ let LookupGeneratedValue (amap:ImportMap) (ctxt: ExecutionContext) eenv (v:Val) None // Invoke the set_Foo method for a declaration with a default/null value. Used to release storage in fsi.exe -let ClearGeneratedValue (ctxt: ExecutionContext) (_g:TcGlobals) eenv (v:Val) = +let ClearGeneratedValue (ctxt: ExecutionContext) (_g: TcGlobals) eenv (v: Val) = try match StorageForVal v.Range v eenv with | StaticField (fspec, _, hasLiteralAttr, _, _, _, _ilGetterMethRef, ilSetterMethRef, _) -> @@ -7556,7 +7556,7 @@ let ClearGeneratedValue (ctxt: ExecutionContext) (_g:TcGlobals) eenv (v:Val) = /// The published API from the ILX code generator -type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal : ConstraintSolver.TcValF, ccu: Tast.CcuThunk) = +type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: ConstraintSolver.TcValF, ccu: Tast.CcuThunk) = // The incremental state held by the ILX code generator let mutable ilxGenEnv = GetEmptyIlxGenEnv tcGlobals.ilg ccu @@ -7575,7 +7575,7 @@ type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal : Constra /// Generate ILX code for an assembly fragment member __.GenerateCode (codeGenOpts, typedAssembly, assemAttribs, moduleAttribs) = - let cenv : cenv = + let cenv: cenv = { g=tcGlobals TcVal = tcVal viewCcu = ccu diff --git a/src/fsharp/InfoReader.fs b/src/fsharp/InfoReader.fs index baa7419119c..1c5525722e0 100644 --- a/src/fsharp/InfoReader.fs +++ b/src/fsharp/InfoReader.fs @@ -20,8 +20,8 @@ open FSharp.Compiler.Tastops open FSharp.Compiler.TcGlobals /// Use the given function to select some of the member values from the members of an F# type -let private SelectImmediateMemberVals g optFilter f (tcref:TyconRef) = - let chooser (vref:ValRef) = +let private SelectImmediateMemberVals g optFilter f (tcref: TyconRef) = + let chooser (vref: ValRef) = match vref.MemberInfo with // The 'when' condition is a workaround for the fact that values providing // override and interface implementations are published in inferred module types @@ -38,10 +38,10 @@ let private SelectImmediateMemberVals g optFilter f (tcref:TyconRef) = | Some nm -> tcref.MembersOfFSharpTyconByName |> NameMultiMap.find nm |> List.choose chooser /// Check whether a name matches an optional filter -let private checkFilter optFilter (nm:string) = match optFilter with None -> true | Some n2 -> nm = n2 +let private checkFilter optFilter (nm: string) = match optFilter with None -> true | Some n2 -> nm = n2 /// Try to select an F# value when querying members, and if so return a MethInfo that wraps the F# value. -let TrySelectMemberVal g optFilter ty pri _membInfo (vref:ValRef) = +let TrySelectMemberVal g optFilter ty pri _membInfo (vref: ValRef) = if checkFilter optFilter vref.LogicalName then Some(FSMeth(g, ty, vref, pri)) else @@ -98,7 +98,7 @@ type PropertyCollector(g, amap, m, ty, optFilter, ad) = let hashIdentity = HashIdentity.FromFunctions - (fun (pinfo:PropInfo) -> hash pinfo.PropertyName) + (fun (pinfo: PropInfo) -> hash pinfo.PropertyName) (fun pinfo1 pinfo2 -> pinfo1.IsStatic = pinfo2.IsStatic && PropInfosEquivByNameAndPartialSig EraseNone g amap m pinfo1 pinfo2 && @@ -119,7 +119,7 @@ type PropertyCollector(g, amap, m, ty, optFilter, ad) = | _ -> props.[pinfo] <- pinfo - member x.Collect(membInfo:ValMemberInfo, vref:ValRef) = + member x.Collect(membInfo: ValMemberInfo, vref: ValRef) = match membInfo.MemberFlags.MemberKind with | MemberKind.PropertyGet -> let pinfo = FSProp(g, ty, Some vref, None) @@ -261,7 +261,7 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = infos /// Make a reference to a record or class field - let MakeRecdFieldInfo g ty (tcref:TyconRef) fspec = + let MakeRecdFieldInfo g ty (tcref: TyconRef) fspec = RecdFieldInfo(argsOfAppTy g ty, tcref.MakeNestedRecdFieldRef fspec) /// Get the F#-declared record fields or class 'val' fields of a type @@ -341,7 +341,7 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = // Only cache closed, monomorphic types (closed = all members for the type // have been processed). Generic type instantiations could be processed if we had // a decent hash function for these. - canMemoize=(fun (_flags, (_:range), ty) -> + canMemoize=(fun (_flags, (_: range), ty) -> match stripTyEqns g ty with | TType_app(tcref, []) -> tcref.TypeContents.tcaug_closed | _ -> false), @@ -443,7 +443,7 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = /// Get the declared constructors of any F# type -let rec GetIntrinsicConstructorInfosOfTypeAux (infoReader:InfoReader) m origTy metadataTy = +let rec GetIntrinsicConstructorInfosOfTypeAux (infoReader: InfoReader) m origTy metadataTy = protectAssemblyExploration [] (fun () -> let g = infoReader.g let amap = infoReader.amap @@ -545,7 +545,7 @@ let private FilterItemsInSubTypesBasedOnItemsInSuperTypes nmf keepTest itemLists /// Add all the items to the IndexedList, preferring the ones in the sub-types. let private FilterItemsInSuperTypesBasedOnItemsInSubTypes nmf keepTest itemLists = - let rec loop itemLists (indexedItemsInSubTypes:IndexedList<_>) = + let rec loop itemLists (indexedItemsInSubTypes: IndexedList<_>) = match itemLists with | [] -> List.rev indexedItemsInSubTypes.Items | items :: itemsInSuperTypes -> @@ -613,7 +613,7 @@ let private FilterOverrides findFlag (isVirt:'a->bool, isNewSlot, isDefiniteOver // // type PD() = // inherit PC() - // override this.M(x:int) = () + // override this.M(x: int) = () |> FilterItemsInSuperTypesBasedOnItemsInSubTypes nmf (fun item1 superTypeItems -> not (isNewSlot item1 && @@ -625,7 +625,7 @@ let private FilterOverrides findFlag (isVirt:'a->bool, isNewSlot, isDefiniteOver let private FilterOverridesOfMethInfos findFlag g amap m minfos = minfos |> FilterOverrides findFlag - ((fun (minfo:MethInfo) -> minfo.IsVirtual), + ((fun (minfo: MethInfo) -> minfo.IsVirtual), (fun minfo -> minfo.IsNewSlot), (fun minfo -> minfo.IsDefiniteFSharpOverride), (fun minfo -> minfo.IsFinal), @@ -636,7 +636,7 @@ let private FilterOverridesOfMethInfos findFlag g amap m minfos = let private FilterOverridesOfPropInfos findFlag g amap m props = props |> FilterOverrides findFlag - ((fun (pinfo:PropInfo) -> pinfo.IsVirtualProperty), + ((fun (pinfo: PropInfo) -> pinfo.IsVirtualProperty), (fun pinfo -> pinfo.IsNewSlot), (fun pinfo -> pinfo.IsDefiniteFSharpOverride), (fun _ -> false), @@ -644,7 +644,7 @@ let private FilterOverridesOfPropInfos findFlag g amap m props = (fun pinfo -> pinfo.PropertyName)) /// Exclude methods from super types which have the same signature as a method in a more specific type. -let ExcludeHiddenOfMethInfos g amap m (minfos:MethInfo list list) = +let ExcludeHiddenOfMethInfos g amap m (minfos: MethInfo list list) = minfos |> ExcludeItemsInSuperTypesBasedOnEquivTestWithItemsInSubTypes (fun minfo -> minfo.LogicalName) @@ -658,16 +658,16 @@ let ExcludeHiddenOfMethInfos g amap m (minfos:MethInfo list list) = /// Exclude properties from super types which have the same name as a property in a more specific type. let ExcludeHiddenOfPropInfos g amap m pinfos = pinfos - |> ExcludeItemsInSuperTypesBasedOnEquivTestWithItemsInSubTypes (fun (pinfo:PropInfo) -> pinfo.PropertyName) (PropInfosEquivByNameAndPartialSig EraseNone g amap m) + |> ExcludeItemsInSuperTypesBasedOnEquivTestWithItemsInSubTypes (fun (pinfo: PropInfo) -> pinfo.PropertyName) (PropInfosEquivByNameAndPartialSig EraseNone g amap m) |> List.concat /// Get the sets of intrinsic methods in the hierarchy (not including extension methods) -let GetIntrinsicMethInfoSetsOfType (infoReader:InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = +let GetIntrinsicMethInfoSetsOfType (infoReader: InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = infoReader.GetRawIntrinsicMethodSetsOfType(optFilter, ad, allowMultiIntfInst, m, ty) |> FilterOverridesOfMethInfos findFlag infoReader.g infoReader.amap m /// Get the sets intrinsic properties in the hierarchy (not including extension properties) -let GetIntrinsicPropInfoSetsOfType (infoReader:InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = +let GetIntrinsicPropInfoSetsOfType (infoReader: InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = infoReader.GetRawIntrinsicPropertySetsOfType(optFilter, ad, allowMultiIntfInst, m, ty) |> FilterOverridesOfPropInfos findFlag infoReader.g infoReader.amap m @@ -680,7 +680,7 @@ let GetIntrinsicPropInfosOfType infoReader (optFilter, ad, allowMultiIntfInst) GetIntrinsicPropInfoSetsOfType infoReader (optFilter, ad, allowMultiIntfInst) findFlag m ty |> List.concat /// Perform type-directed name resolution of a particular named member in an F# type -let TryFindIntrinsicNamedItemOfType (infoReader:InfoReader) (nm, ad) findFlag m ty = +let TryFindIntrinsicNamedItemOfType (infoReader: InfoReader) (nm, ad) findFlag m ty = match infoReader.TryFindNamedItemOfType(nm, ad, m, ty) with | Some item -> match item with @@ -713,7 +713,7 @@ type SigOfFunctionForDelegate = SigOfFunctionForDelegate of MethInfo * TType lis /// Given a delegate type work out the minfo, argument types, return type /// and F# function type by looking at the Invoke signature of the delegate. -let GetSigOfFunctionForDelegate (infoReader:InfoReader) delty m ad = +let GetSigOfFunctionForDelegate (infoReader: InfoReader) delty m ad = let g = infoReader.g let amap = infoReader.amap let invokeMethInfo = @@ -737,7 +737,7 @@ let GetSigOfFunctionForDelegate (infoReader:InfoReader) delty m ad = SigOfFunctionForDelegate(invokeMethInfo, compiledViewOfDelArgTys, delRetTy, fty) /// Try and interpret a delegate type as a "standard" .NET delegate type associated with an event, with a "sender" parameter. -let TryDestStandardDelegateType (infoReader:InfoReader) m ad delTy = +let TryDestStandardDelegateType (infoReader: InfoReader) m ad delTy = let g = infoReader.g let (SigOfFunctionForDelegate(_, compiledViewOfDelArgTys, delRetTy, _)) = GetSigOfFunctionForDelegate infoReader delTy m ad match compiledViewOfDelArgTys with @@ -760,14 +760,14 @@ let TryDestStandardDelegateType (infoReader:InfoReader) m ad delTy = /// that do not use any additional information, the .NET Framework has /// already defined an appropriate delegate type: EventHandler. /// (from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vcwlkEventsTutorial.asp) -let IsStandardEventInfo (infoReader:InfoReader) m ad (einfo:EventInfo) = +let IsStandardEventInfo (infoReader: InfoReader) m ad (einfo: EventInfo) = let dty = einfo.GetDelegateType(infoReader.amap, m) match TryDestStandardDelegateType infoReader m ad dty with | Some _ -> true | None -> false /// Get the (perhaps tupled) argument type accepted by an event -let ArgsTypOfEventInfo (infoReader:InfoReader) m ad (einfo:EventInfo) = +let ArgsTypOfEventInfo (infoReader: InfoReader) m ad (einfo: EventInfo) = let amap = infoReader.amap let dty = einfo.GetDelegateType(amap, m) match TryDestStandardDelegateType infoReader m ad dty with @@ -776,7 +776,7 @@ let ArgsTypOfEventInfo (infoReader:InfoReader) m ad (einfo:EventInfo) = /// Get the type of the event when looked at as if it is a property /// Used when displaying the property in Intellisense -let PropTypOfEventInfo (infoReader:InfoReader) m ad (einfo:EventInfo) = +let PropTypOfEventInfo (infoReader: InfoReader) m ad (einfo: EventInfo) = let g = infoReader.g let amap = infoReader.amap let delTy = einfo.GetDelegateType(amap, m) diff --git a/src/fsharp/InnerLambdasToTopLevelFuncs.fs b/src/fsharp/InnerLambdasToTopLevelFuncs.fs index e25d1b4d11b..d66610c3c10 100644 --- a/src/fsharp/InnerLambdasToTopLevelFuncs.fs +++ b/src/fsharp/InnerLambdasToTopLevelFuncs.fs @@ -73,7 +73,7 @@ let showTyparSet tps = showL (commaListL (List.map typarL (Zset.elements tps))) // CLEANUP NOTE: don't like the look of this function - this distinction // should never be needed -let isDelayedRepr (f:Val) e = +let isDelayedRepr (f: Val) e = let _tps, vss, _b, _rty = stripTopLambda (e, f.Type) List.length vss>0 @@ -89,7 +89,7 @@ let mkLocalNameTypeArity compgen m name ty topValInfo = // DEFN: An f is TLR with arity wf if // (a) it's repr is "LAM tps. lam x1...xN. body" and have N<=wf (i.e. have enough args) // (b) it has no free tps -// (c) for g:freevars(repr), both +// (c) for g: freevars(repr), both // (1) g is TLR with arity wg, and // (2) g occurs in arity-met occurrence. // (d) if N=0, then further require that body be a TLR-constant. @@ -132,7 +132,7 @@ let mkLocalNameTypeArity compgen m name ty topValInfo = //------------------------------------------------------------------------- let GetValsBoundUnderMustInline xinfo = - let accRejectFrom (v:Val) repr rejectS = + let accRejectFrom (v: Val) repr rejectS = if v.InlineInfo = ValInline.PseudoVal then Zset.union (GetValsBoundInExpr repr) rejectS else rejectS @@ -144,7 +144,7 @@ let GetValsBoundUnderMustInline xinfo = // pass1: IsRefusedTLR //------------------------------------------------------------------------- -let IsRefusedTLR g (f:Val) = +let IsRefusedTLR g (f: Val) = let mutableVal = f.IsMutable // things marked ValInline.Never are special let dllImportStubOrOtherNeverInline = (f.InlineInfo = ValInline.Never) @@ -156,12 +156,12 @@ let IsRefusedTLR g (f:Val) = let refuseTest = alreadyChosen || mutableVal || byrefVal || specialVal || dllImportStubOrOtherNeverInline refuseTest -let IsMandatoryTopLevel (f:Val) = +let IsMandatoryTopLevel (f: Val) = let specialVal = f.MemberInfo.IsSome let isModulBinding = f.IsMemberOrModuleBinding specialVal || isModulBinding -let IsMandatoryNonTopLevel g (f:Val) = +let IsMandatoryNonTopLevel g (f: Val) = let byrefVal = isByrefLikeTy g f.Range f.Type byrefVal @@ -329,10 +329,14 @@ let reqdItemOrder = /// The reqdTypars are the free reqdTypars of the defns, and those required by any direct TLR arity-met calls. /// The reqdItems are the ids/subEnvs required from calls to freeVars. type ReqdItemsForDefn = - { reqdTypars : Zset - reqdItems : Zset - m : Range.range } + { + reqdTypars: Zset + reqdItems: Zset + m: Range.range + } + member env.ReqdSubEnvs = [ for x in env.reqdItems do match x with | ReqdSubEnv f -> yield f | ReqdVal _ -> () ] + member env.ReqdVals = [ for x in env.reqdItems do match x with | ReqdSubEnv _ -> () | ReqdVal v -> yield v ] member env.Extend (typars, items) = @@ -359,13 +363,11 @@ type ReqdItemsForDefn = type Generators = Zset /// check a named function value applied to sufficient arguments -let IsArityMet (vref:ValRef) wf (tys: TypeInst) args = +let IsArityMet (vref: ValRef) wf (tys: TypeInst) args = (tys.Length = vref.Typars.Length) && (wf <= List.length args) - module Pass2_DetermineReqdItems = - // IMPLEMENTATION PLAN: // // fold over expr. @@ -414,11 +416,12 @@ module Pass2_DetermineReqdItems = /// /// recShortCalls to f will require a binding for f in terms of fHat within the fHatBody. type state = - { stack : (BindingGroupSharingSameReqdItems * Generators * ReqdItemsForDefn) list - reqdItemsMap : Zmap - fclassM : Zmap - revDeclist : BindingGroupSharingSameReqdItems list - recShortCallS : Zset + { + stack: (BindingGroupSharingSameReqdItems * Generators * ReqdItemsForDefn) list + reqdItemsMap: Zmap + fclassM: Zmap + revDeclist: BindingGroupSharingSameReqdItems list + recShortCallS: Zset } let state0 = @@ -453,7 +456,7 @@ module Pass2_DetermineReqdItems = /// Log requirements for gv in the relevant stack frames let LogRequiredFrom gv items state = - let logIntoFrame (fclass, reqdVals0:Zset, env: ReqdItemsForDefn) = + let logIntoFrame (fclass, reqdVals0: Zset, env: ReqdItemsForDefn) = let env = if reqdVals0.Contains gv then env.Extend ([], items) @@ -483,7 +486,7 @@ module Pass2_DetermineReqdItems = /// On intercepted nodes, must recurseF fold to collect from subexpressions. let ExprEnvIntercept (tlrS, arityM) recurseF noInterceptF z expr = - let accInstance z (fvref:ValRef, tps, args) = + let accInstance z (fvref: ValRef, tps, args) = let f = fvref.Deref match Zmap.tryFind f arityM with @@ -649,14 +652,18 @@ module Pass2_DetermineReqdItems = /// provided it is fixed up via a copyExpr call on the final expr. type PackedReqdItems = - { /// The actual typars - ep_etps : Typars - /// The actual env carrier values - ep_aenvs : Val list - /// Sequentially define the aenvs in terms of the fvs - ep_pack : Bindings - /// Sequentially define the fvs in terms of the aenvs - ep_unpack : Bindings + { + /// The actual typars + ep_etps: Typars + + /// The actual env carrier values + ep_aenvs: Val list + + /// Sequentially define the aenvs in terms of the fvs + ep_pack: Bindings + + /// Sequentially define the fvs in terms of the aenvs + ep_unpack: Bindings } @@ -686,7 +693,7 @@ exception AbortTLR of Range.range /// aenvFor(v) = aenvi where (v, aenvi) in cmap. let FlatEnvPacks g fclassM topValS declist (reqdItemsMap: Zmap) = let fclassOf f = Zmap.force f fclassM ("fclassM", nameOfVal) - let packEnv carrierMaps (fc:BindingGroupSharingSameReqdItems) = + let packEnv carrierMaps (fc: BindingGroupSharingSameReqdItems) = if verboseTLR then dprintf "\ntlr: packEnv fc=%A\n" fc let env = Zmap.force fc reqdItemsMap ("packEnv", string) @@ -825,7 +832,7 @@ let MakeSimpleArityInfo tps n = ValReprInfo (ValReprInfo.InferTyparInfo tps, Lis let CreateNewValuesForTLR g tlrS arityM fclassM envPackM = if verboseTLR then dprintf "CreateNewValuesForTLR------\n" - let createFHat (f:Val) = + let createFHat (f: Val) = let wf = Zmap.force f arityM ("createFHat - wf", (fun v -> showL (valL v))) let fc = Zmap.force f fclassM ("createFHat - fc", nameOfVal) let envp = Zmap.force fc envPackM ("CreateNewValuesForTLR - envp", string) @@ -856,16 +863,16 @@ let CreateNewValuesForTLR g tlrS arityM fclassM envPackM = module Pass4_RewriteAssembly = [] type RewriteContext = - { ccu : CcuThunk - g : TcGlobals - tlrS : Zset - topValS : Zset - arityM : Zmap - fclassM : Zmap - recShortCallS : Zset - envPackM : Zmap + { ccu: CcuThunk + g: TcGlobals + tlrS: Zset + topValS: Zset + arityM: Zmap + fclassM: Zmap + recShortCallS: Zset + envPackM: Zmap /// The mapping from 'f' values to 'fHat' values - fHatM : Zmap + fHatM: Zmap } @@ -890,15 +897,16 @@ module Pass4_RewriteAssembly = type RewriteState = { rws_mustinline: bool /// counts level of enclosing "lambdas" - rws_innerLevel : int + rws_innerLevel: int /// collected preDecs (fringe is in-order) - rws_preDecs : Tree + rws_preDecs: Tree } let rewriteState0 = {rws_mustinline=false;rws_innerLevel=0;rws_preDecs=emptyTR} // move in/out of lambdas (or lambda containing construct) let EnterInner z = {z with rws_innerLevel = z.rws_innerLevel + 1} + let ExitInner z = {z with rws_innerLevel = z.rws_innerLevel - 1} let EnterMustInline b z f = @@ -920,6 +928,7 @@ module Pass4_RewriteAssembly = /// pop and set preDecs as "LiftedDeclaration tree" let PopPreDecs z = {z with rws_preDecs=emptyTR}, z.rws_preDecs + let SetPreDecs z pdt = {z with rws_preDecs=pdt} /// collect Top* repr bindings - if needed... @@ -964,7 +973,7 @@ module Pass4_RewriteAssembly = // To // let f vss = fHat f_freeVars vss // let fHat f_freeVars vss = f_body[, f_freeVars] - let TransTLRBindings penv (binds:Bindings) = + let TransTLRBindings penv (binds: Bindings) = if isNil binds then List.empty, List.empty else let fc = BindingGroupSharingSameReqdItems binds let envp = Zmap.force fc penv.envPackM ("TransTLRBindings", string) @@ -986,7 +995,7 @@ module Pass4_RewriteAssembly = aenvExprs @ vsExprs, m), rty) fBind - let fHatNewBinding (shortRecBinds:Bindings) (TBind(f, b, letSeqPtOpt)) = + let fHatNewBinding (shortRecBinds: Bindings) (TBind(f, b, letSeqPtOpt)) = let wf = Zmap.force f penv.arityM ("fHatNewBinding - arityM", nameOfVal) let fHat = Zmap.force f penv.fHatM ("fHatNewBinding - fHatM", nameOfVal) // Take off the variables @@ -1016,7 +1025,7 @@ module Pass4_RewriteAssembly = | None -> List.empty // no env for this mutual binding | Some envp -> envp.ep_pack // environment pack bindings - let TransBindings xisRec penv (binds:Bindings) = + let TransBindings xisRec penv (binds: Bindings) = let tlrBs, nonTlrBs = binds |> List.partition (fun b -> Zset.contains b.Var penv.tlrS) let fclass = BindingGroupSharingSameReqdItems tlrBs // Trans each TLR f binding into fHat and f rebind @@ -1026,7 +1035,7 @@ module Pass4_RewriteAssembly = // QUERY: we repeat this logic in LowerCallsAndSeqs. Do we really need to do this here? // QUERY: yes and no - if we don't, we have an unrealizable term, and many decisions must // QUERY: correlate with LowerCallsAndSeqs. - let forceTopBindToHaveArity (bind:Binding) = + let forceTopBindToHaveArity (bind: Binding) = if penv.topValS.Contains(bind.Var) then ConvertBind penv.g bind else bind @@ -1048,7 +1057,7 @@ module Pass4_RewriteAssembly = // Is it a val app, where the val f is TLR with arity wf? // CLEANUP NOTE: should be using a mkApps to make all applications match fx with - | Expr.Val (fvref:ValRef, _, m) when + | Expr.Val (fvref: ValRef, _, m) when (Zset.contains fvref.Deref penv.tlrS) && (let wf = Zmap.force fvref.Deref penv.arityM ("TransApp - wf", nameOfVal) IsArityMet fvref wf tys args) -> @@ -1076,7 +1085,7 @@ module Pass4_RewriteAssembly = /// At applications, fixup calls if they are arity-met instances of TLR. /// At free vals, fixup 0-call if it is an arity-met constant. /// Other cases rewrite structurally. - let rec TransExpr (penv: RewriteContext) (z:RewriteState) expr : Expr * RewriteState = + let rec TransExpr (penv: RewriteContext) (z: RewriteState) expr: Expr * RewriteState = match expr with // Use TransLinearExpr with a rebuild-continuation for some forms to avoid stack overflows on large terms @@ -1113,7 +1122,7 @@ module Pass4_RewriteAssembly = | Expr.Obj (_, ty, basev, basecall, overrides, iimpls, m) -> let basecall, z = TransExpr penv z basecall let overrides, z = List.mapFold (TransMethod penv) z overrides - let (iimpls:(TType*ObjExprMethod list)list), (z:RewriteState) = + let (iimpls:(TType*ObjExprMethod list)list), (z: RewriteState) = List.mapFold (fun z (tType, objExprs) -> let objExprs', z' = List.mapFold (TransMethod penv) z objExprs (tType, objExprs'), z') z iimpls @@ -1230,7 +1239,7 @@ module Pass4_RewriteAssembly = // not a linear expression contf (TransExpr penv z expr) - and TransMethod penv (z:RewriteState) (TObjExprMethod(slotsig, attribs, tps, vs, e, m)) = + and TransMethod penv (z: RewriteState) (TObjExprMethod(slotsig, attribs, tps, vs, e, m)) = let z = EnterInner z let e, z = TransExpr penv z e let z = ExitInner z @@ -1241,7 +1250,7 @@ module Pass4_RewriteAssembly = let z, e = EnterMustInline mustInline z (fun z -> TransExpr penv z e) TBind (v, e, letSeqPtOpt), z - and TransDecisionTree penv z x : DecisionTree * RewriteState = + and TransDecisionTree penv z x: DecisionTree * RewriteState = match x with | TDSuccess (es, n) -> let es, z = List.mapFold (TransExpr penv) z es @@ -1275,7 +1284,7 @@ module Pass4_RewriteAssembly = ModuleOrNamespaceExprWithSig(mty, def, m), z and TransModuleDefs penv z x = List.mapFold (TransModuleDef penv) z x - and TransModuleDef penv (z: RewriteState) x : ModuleOrNamespaceExpr * RewriteState = + and TransModuleDef penv (z: RewriteState) x: ModuleOrNamespaceExpr * RewriteState = match x with | TMDefRec(isRec, tycons, mbinds, m) -> let mbinds, z = TransModuleBindings penv z mbinds @@ -1332,7 +1341,7 @@ let MakeTLRDecisions ccu g expr = // pass4: rewrite if verboseTLR then dprintf "TransExpr(rw)------\n" let expr, _ = - let penv : Pass4_RewriteAssembly.RewriteContext = + let penv: Pass4_RewriteAssembly.RewriteContext = {ccu=ccu; g=g; tlrS=tlrS; topValS=topValS; arityM=arityM; fclassM=fclassM; recShortCallS=recShortCallS; envPackM=envPackM; fHatM=fHatM} let z = Pass4_RewriteAssembly.rewriteState0 Pass4_RewriteAssembly.TransImplFile penv z expr diff --git a/src/fsharp/LexFilter.fs b/src/fsharp/LexFilter.fs index 0c78c7c0e1c..279376b3d62 100755 --- a/src/fsharp/LexFilter.fs +++ b/src/fsharp/LexFilter.fs @@ -17,13 +17,13 @@ open FSharp.Compiler.Lexhelp let debug = false -let stringOfPos (p:Position) = sprintf "(%d:%d)" p.OriginalLine p.Column -let outputPos os (p:Position) = Printf.fprintf os "(%d:%d)" p.OriginalLine p.Column +let stringOfPos (p: Position) = sprintf "(%d:%d)" p.OriginalLine p.Column +let outputPos os (p: Position) = Printf.fprintf os "(%d:%d)" p.OriginalLine p.Column /// Used for warning strings, which should display columns as 1-based and display /// the lines after taking '# line' directives into account (i.e. do not use /// p.OriginalLine) -let warningStringOfPos (p:Position) = sprintf "(%d:%d)" p.Line (p.Column + 1) +let warningStringOfPos (p: Position) = sprintf "(%d:%d)" p.Line (p.Column + 1) type Context = // Position is position of keyword. @@ -441,7 +441,7 @@ type TokenTup = // Strip a bunch of leading '>' of a token, at the end of a typar application // Note: this is used in the 'service.fs' to do limited postprocessing -let (|TyparsCloseOp|_|) (txt:string) = +let (|TyparsCloseOp|_|) (txt: string) = let angles = txt |> Seq.takeWhile (fun c -> c = '>') |> Seq.toList let afterAngles = txt |> Seq.skipWhile (fun c -> c = '>') |> Seq.toList if List.isEmpty angles then None else @@ -498,7 +498,7 @@ type PositionWithColumn = //---------------------------------------------------------------------------- // build a LexFilter //--------------------------------------------------------------------------*) -type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, lexbuf: UnicodeLexing.Lexbuf) = +type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, lexbuf: UnicodeLexing.Lexbuf) = //---------------------------------------------------------------------------- // Part I. Building a new lex stream from an old @@ -531,12 +531,12 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, let getLexbufState() = new LexbufState(lexbuf.StartPos, lexbuf.EndPos, lexbuf.IsPastEndOfStream) - let setLexbufState (p:LexbufState) = + let setLexbufState (p: LexbufState) = lexbuf.StartPos <- p.StartPos lexbuf.EndPos <- p.EndPos lexbuf.IsPastEndOfStream <- p.PastEOF - let startPosOfTokenTup (tokenTup:TokenTup) = + let startPosOfTokenTup (tokenTup: TokenTup) = match tokenTup.Token with // EOF token is processed as if on column -1 // This forces the closure of all contexts. @@ -604,7 +604,7 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, offsideStack <- (CtxtSeqBlock(FirstInSeqBlock, startPosOfTokenTup initialLookaheadTokenTup, NoAddBlockEnd)) :: offsideStack initialLookaheadTokenTup - let warn (s:TokenTup) msg = + let warn (s: TokenTup) msg = warning(Lexhelp.IndentationProblem(msg, mkSynRange (startPosOfTokenTup s) s.LexbufState.EndPos)) // 'query { join x in ys ... }' @@ -629,7 +629,7 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, // Undentation rules //-------------------------------------------------------------------------- - let pushCtxt tokenTup (newCtxt:Context) = + let pushCtxt tokenTup (newCtxt: Context) = let rec unindentationLimit strict stack = match newCtxt, stack with | _, [] -> PositionWithColumn(newCtxt.StartPos, -1) @@ -839,12 +839,12 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, // Adjacency precedence rule //-------------------------------------------------------------------------- - let isAdjacent (leftTokenTup:TokenTup) rightTokenTup = + let isAdjacent (leftTokenTup: TokenTup) rightTokenTup = let lparenStartPos = startPosOfTokenTup rightTokenTup let tokenEndPos = leftTokenTup.LexbufState.EndPos (tokenEndPos = lparenStartPos) - let nextTokenIsAdjacentLParenOrLBrack (tokenTup:TokenTup) = + let nextTokenIsAdjacentLParenOrLBrack (tokenTup: TokenTup) = let lookaheadTokenTup = peekNextTokenTup() match lookaheadTokenTup.Token with | (LPAREN | LBRACK) -> @@ -856,7 +856,7 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, let lookaheadTokenTup = peekNextTokenTup() isAdjacent firstTokenTup lookaheadTokenTup - let peekAdjacentTypars indentation (tokenTup:TokenTup) = + let peekAdjacentTypars indentation (tokenTup: TokenTup) = let lookaheadTokenTup = peekNextTokenTup() match lookaheadTokenTup.Token with | INFIX_COMPARE_OP " @@ -987,7 +987,7 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, // End actions //-------------------------------------------------------------------------- - let returnToken (tokenLexbufState:LexbufState) tok = + let returnToken (tokenLexbufState: LexbufState) tok = setLexbufState(tokenLexbufState) prevWasAtomicEnd <- isAtomicExprEndToken(tok) tok @@ -2123,7 +2123,7 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, | _ -> returnToken tokenLexbufState token - and rulesForBothSoftWhiteAndHardWhite(tokenTup:TokenTup) = + and rulesForBothSoftWhiteAndHardWhite(tokenTup: TokenTup) = match tokenTup.Token with // Insert HIGH_PRECEDENCE_PAREN_APP if needed | IDENT _ when (nextTokenIsAdjacentLParenOrLBrack tokenTup).IsSome -> @@ -2216,7 +2216,7 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, false and pushCtxtSeqBlock(addBlockBegin, addBlockEnd) = pushCtxtSeqBlockAt (peekNextTokenTup(), addBlockBegin, addBlockEnd) - and pushCtxtSeqBlockAt(p:TokenTup, addBlockBegin, addBlockEnd) = + and pushCtxtSeqBlockAt(p: TokenTup, addBlockBegin, addBlockEnd) = if addBlockBegin then if debug then dprintf "--> insert OBLOCKBEGIN \n" delayToken(p.UseLocation(OBLOCKBEGIN)) @@ -2246,7 +2246,7 @@ type LexFilterImpl (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, // LexFilterImpl does the majority of the work for offsides rules and other magic. // LexFilter just wraps it with light post-processing that introduces a few more 'coming soon' symbols, to // make it easier for the parser to 'look ahead' and safely shift tokens in a number of recovery scenarios. -type LexFilter (lightSyntaxStatus:LightSyntaxStatus, compilingFsLib, lexer, lexbuf: UnicodeLexing.Lexbuf) = +type LexFilter (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, lexbuf: UnicodeLexing.Lexbuf) = let inner = new LexFilterImpl (lightSyntaxStatus, compilingFsLib, lexer, lexbuf) // We don't interact with lexbuf state at all, any inserted tokens have same state/location as the real one read, so diff --git a/src/fsharp/MethodCalls.fs b/src/fsharp/MethodCalls.fs index e754ce22d09..0744fd720b9 100644 --- a/src/fsharp/MethodCalls.fs +++ b/src/fsharp/MethodCalls.fs @@ -122,7 +122,7 @@ type CallerNamedArg<'T> = // The function AdjustCalledArgType detects this and refuses to apply the default byref-to-ref transformation. // // The function AdjustCalledArgType also adjusts for optional arguments. -let AdjustCalledArgType (infoReader:InfoReader) isConstraint (calledArg: CalledArg) (callerArg: CallerArg<_>) = +let AdjustCalledArgType (infoReader: InfoReader) isConstraint (calledArg: CalledArg) (callerArg: CallerArg<_>) = let g = infoReader.g // #424218 - when overload resolution is part of constraint solving - do not perform type-directed conversions let calledArgTy = calledArg.CalledArgumentType @@ -207,7 +207,7 @@ type CalledMethArgSet<'T> = member x.NumUnnamedCalledArgs = x.UnnamedCalledArgs.Length -let MakeCalledArgs amap m (minfo:MethInfo) minst = +let MakeCalledArgs amap m (minfo: MethInfo) minst = // Mark up the arguments with their position, so we can sort them back into order later let paramDatas = minfo.GetParamDatas(amap, m, minst) paramDatas |> List.mapiSquared (fun i j (ParamData(isParamArrayArg, isInArg, isOutArg, optArgInfo, callerInfoFlags, nmOpt, reflArgInfo, typeOfCalledArg)) -> @@ -226,19 +226,19 @@ let MakeCalledArgs amap m (minfo:MethInfo) minst = /// The constructor takes all the information about the caller and called side of a method, match up named arguments, property setters etc., /// and returns a CalledMeth object for further analysis. type CalledMeth<'T> - (infoReader:InfoReader, + (infoReader: InfoReader, nameEnv: NameResolutionEnv option, isCheckingAttributeCall, freshenMethInfo, // a function to help generate fresh type variables the property setters methods in generic classes m, ad, // the access domain of the place where the call is taking place - minfo:MethInfo, // the method we're attempting to call + minfo: MethInfo, // the method we're attempting to call calledTyArgs, // the 'called type arguments', i.e. the fresh generic instantiation of the method we're attempting to call callerTyArgs: TType list, // the 'caller type arguments', i.e. user-given generic instantiation of the method we're attempting to call pinfoOpt: PropInfo option, // the property related to the method we're attempting to call, if any callerObjArgTys: TType list, // the types of the actual object argument, if any curriedCallerArgs: (CallerArg<'T> list * CallerNamedArg<'T> list) list, // the data about any arguments supplied by the caller - allowParamArgs:bool, // do we allow the use of a param args method in its "expanded" form? + allowParamArgs: bool, // do we allow the use of a param args method in its "expanded" form? allowOutAndOptArgs: bool, // do we allow the use of the transformation that converts out arguments as tuple returns? tyargsOpt : TType option) // method parameters = @@ -424,7 +424,7 @@ type CalledMeth<'T> /// unnamed called out args: return these as part of the return tuple member x.UnnamedCalledOutArgs = unnamedCalledOutArgs - static member GetMethod (x:CalledMeth<'T>) = x.Method + static member GetMethod (x: CalledMeth<'T>) = x.Method member x.NumArgSets = x.ArgSets.Length @@ -512,7 +512,7 @@ let InferLambdaArgsForLambdaPropagation origRhsExpr = | _ -> 0 loop origRhsExpr -let ExamineArgumentForLambdaPropagation (infoReader:InfoReader) (arg: AssignedCalledArg) = +let ExamineArgumentForLambdaPropagation (infoReader: InfoReader) (arg: AssignedCalledArg) = let g = infoReader.g // Find the explicit lambda arguments of the caller. Ignore parentheses. let argExpr = match arg.CallerArg.Expr with SynExpr.Paren(x, _, _, _) -> x | x -> x @@ -531,7 +531,7 @@ let ExamineArgumentForLambdaPropagation (infoReader:InfoReader) (arg: AssignedCa NoInfo // not a function type on the called side - no information else CalledArgMatchesType(adjustedCalledArgTy) // not a lambda on the caller side - push information from caller to called -let ExamineMethodForLambdaPropagation (x:CalledMeth) = +let ExamineMethodForLambdaPropagation (x: CalledMeth) = let unnamedInfo = x.AssignedUnnamedArgs |> List.mapSquared (ExamineArgumentForLambdaPropagation x.infoReader) let namedInfo = x.AssignedNamedArgs |> List.mapSquared (fun arg -> (arg.NamedArgIdOpt.Value, ExamineArgumentForLambdaPropagation x.infoReader arg)) if unnamedInfo |> List.existsSquared (function CallerLambdaHasArgTypes _ -> true | _ -> false) || @@ -553,7 +553,7 @@ let IsBaseCall objArgs = /// Compute whether we insert a 'coerce' on the 'this' pointer for an object model call /// For example, when calling an interface method on a struct, or a method on a constrained /// variable type. -let ComputeConstrainedCallInfo g amap m (objArgs, minfo:MethInfo) = +let ComputeConstrainedCallInfo g amap m (objArgs, minfo: MethInfo) = match objArgs with | [objArgExpr] when not minfo.IsExtensionMember -> let methObjTy = minfo.ApparentEnclosingType @@ -576,7 +576,7 @@ let ComputeConstrainedCallInfo g amap m (objArgs, minfo:MethInfo) = /// Adjust the 'this' pointer before making a call /// Take the address of a struct, and coerce to an interface/base/constraint type if necessary -let TakeObjAddrForMethodCall g amap (minfo:MethInfo) isMutable m objArgs f = +let TakeObjAddrForMethodCall g amap (minfo: MethInfo) isMutable m objArgs f = let ccallInfo = ComputeConstrainedCallInfo g amap m (objArgs, minfo) let wrap, objArgs = @@ -622,7 +622,7 @@ let TakeObjAddrForMethodCall g amap (minfo:MethInfo) isMutable m objArgs f = /// Build an expression node that is a call to a .NET method. -let BuildILMethInfoCall g amap m isProp (minfo:ILMethInfo) valUseFlags minst direct args = +let BuildILMethInfoCall g amap m isProp (minfo: ILMethInfo) valUseFlags minst direct args = let valu = isStructTy g minfo.ApparentEnclosingType let ctor = minfo.IsConstructor if minfo.IsClassConstructor then @@ -676,7 +676,7 @@ let BuildFSharpMethodApp g m (vref: ValRef) vexp vexprty (args: Exprs) = retTy /// Build a call to an F# method. -let BuildFSharpMethodCall g m (ty, vref:ValRef) valUseFlags minst args = +let BuildFSharpMethodCall g m (ty, vref: ValRef) valUseFlags minst args = let vexp = Expr.Val (vref, valUseFlags, m) let vexpty = vref.Type let tpsorig, tau = vref.TypeScheme @@ -716,7 +716,7 @@ let MakeMethInfoCall amap m minfo minst args = #if !NO_EXTENSIONTYPING // This imports a provided method, and checks if it is a known compiler intrinsic like "1 + 2" -let TryImportProvidedMethodBaseAsLibraryIntrinsic (amap:Import.ImportMap, m:range, mbase: Tainted) = +let TryImportProvidedMethodBaseAsLibraryIntrinsic (amap: Import.ImportMap, m: range, mbase: Tainted) = let methodName = mbase.PUntaint((fun x -> x.Name), m) let declaringType = Import.ImportProvidedType amap m (mbase.PApply((fun x -> x.DeclaringType), m)) if isAppTy amap.g declaringType then @@ -829,7 +829,7 @@ let BuildMethodCall tcVal g amap isMutable m isProp minfo valUseFlags minst objA //------------------------------------------------------------------------- /// Implements the elaborated form of adhoc conversions from functions to delegates at member callsites -let BuildNewDelegateExpr (eventInfoOpt:EventInfo option, g, amap, delegateTy, invokeMethInfo:MethInfo, delArgTys, f, fty, m) = +let BuildNewDelegateExpr (eventInfoOpt: EventInfo option, g, amap, delegateTy, invokeMethInfo: MethInfo, delArgTys, f, fty, m) = let slotsig = invokeMethInfo.GetSlotSig(amap, m) let delArgVals, expr = let topValInfo = ValReprInfo([], List.replicate (max 1 (List.length delArgTys)) ValReprInfo.unnamedTopArg, ValReprInfo.unnamedRetVal) @@ -926,7 +926,7 @@ module ProvidedMethodCalls = /// back to System.Type. However, there is currently no way to get from an arbitrary F# TType (even the TType for /// System.Object) to a System.Type to give to the type provider. let eraseSystemType (amap, m, inputType) = - let rec loop (st:Tainted) = + let rec loop (st: Tainted) = if st.PUntaint((fun st -> st.IsGenericParameter), m) then st elif st.PUntaint((fun st -> st.IsArray), m) then let et = st.PApply((fun st -> st.GetElementType()), m) @@ -971,11 +971,11 @@ module ProvidedMethodCalls = st loop inputType - let convertProvidedExpressionToExprAndWitness tcVal (thisArg:Expr option, - allArgs:Exprs, - paramVars:Tainted[], + let convertProvidedExpressionToExprAndWitness tcVal (thisArg: Expr option, + allArgs: Exprs, + paramVars: Tainted[], g, amap, mut, isProp, isSuperInit, m, - expr:Tainted) = + expr: Tainted) = let varConv = // note: using paramVars.Length as assumed initial size, but this might not // be the optimal value; this wasn't checked before obsoleting Dictionary.ofList @@ -983,7 +983,7 @@ module ProvidedMethodCalls = for v, e in Seq.zip (paramVars |> Seq.map (fun x -> x.PUntaint(id, m))) (Option.toList thisArg @ allArgs) do dict.Add(v, (None, e)) dict - let rec exprToExprAndWitness top (ea:Tainted) = + let rec exprToExprAndWitness top (ea: Tainted) = let fail() = error(Error(FSComp.SR.etUnsupportedProvidedExpression(ea.PUntaint((fun etree -> etree.UnderlyingExpressionString), m)), m)) match ea with | Tainted.Null -> error(Error(FSComp.SR.etNullProvidedExpression(ea.TypeProviderDesignation), m)) @@ -1172,7 +1172,7 @@ module ProvidedMethodCalls = fail() - and ctorCallToExpr (ne:Tainted<_>) = + and ctorCallToExpr (ne: Tainted<_>) = let (ctor, args) = ne.PApply2(id, m) let targetMethInfo = ProvidedMeth(amap, ctor.PApply((fun ne -> upcast ne), m), None, m) let objArgs = [] @@ -1180,7 +1180,7 @@ module ProvidedMethodCalls = let callExpr = BuildMethodCall tcVal g amap Mutates.PossiblyMutates m false targetMethInfo isSuperInit [] objArgs arguments callExpr - and addVar (v:Tainted) = + and addVar (v: Tainted) = let nm = v.PUntaint ((fun v -> v.Name), m) let mut = v.PUntaint ((fun v -> v.IsMutable), m) let vRaw = v.PUntaint (id, m) @@ -1189,11 +1189,11 @@ module ProvidedMethodCalls = varConv.[vRaw] <- (Some vT, vTe) vT - and removeVar (v:Tainted) = + and removeVar (v: Tainted) = let vRaw = v.PUntaint (id, m) varConv.Remove vRaw |> ignore - and methodCallToExpr top _origExpr (mce:Tainted<_>) = + and methodCallToExpr top _origExpr (mce: Tainted<_>) = let (objOpt, meth, args) = mce.PApply3(id, m) let targetMethInfo = ProvidedMeth(amap, meth.PApply((fun mce -> upcast mce), m), None, m) let objArgs = @@ -1215,7 +1215,7 @@ module ProvidedMethodCalls = let callExpr = BuildMethodCall tcVal g amap mut m isProp targetMethInfo isSuperInit replacementGenericArguments objArgs arguments Some meth, callExpr - and varToExpr (pe:Tainted) = + and varToExpr (pe: Tainted) = // sub in the appropriate argument // REVIEW: "thisArg" pointer should be first, if present let vRaw = pe.PUntaint(id, m) @@ -1233,7 +1233,7 @@ module ProvidedMethodCalls = // fill in parameter holes in the expression - let TranslateInvokerExpressionForProvidedMethodCall tcVal (g, amap, mut, isProp, isSuperInit, mi:Tainted, objArgs, allArgs, m) = + let TranslateInvokerExpressionForProvidedMethodCall tcVal (g, amap, mut, isProp, isSuperInit, mi: Tainted, objArgs, allArgs, m) = let parameters = mi.PApplyArray((fun mi -> mi.GetParameters()), "GetParameters", m) let paramTys = @@ -1262,7 +1262,7 @@ module ProvidedMethodCalls = convertProvidedExpressionToExprAndWitness tcVal (thisArg, allArgs, paramVars, g, amap, mut, isProp, isSuperInit, m, ea) - let BuildInvokerExpressionForProvidedMethodCall tcVal (g, amap, mi:Tainted, objArgs, mut, isProp, isSuperInit, allArgs, m) = + let BuildInvokerExpressionForProvidedMethodCall tcVal (g, amap, mi: Tainted, objArgs, mut, isProp, isSuperInit, allArgs, m) = try let methInfoOpt, (expr, retTy) = TranslateInvokerExpressionForProvidedMethodCall tcVal (g, amap, mut, isProp, isSuperInit, mi, objArgs, allArgs, m) @@ -1278,17 +1278,17 @@ module ProvidedMethodCalls = -let RecdFieldInstanceChecks g amap ad m (rfinfo:RecdFieldInfo) = +let RecdFieldInstanceChecks g amap ad m (rfinfo: RecdFieldInfo) = if rfinfo.IsStatic then error (Error (FSComp.SR.tcStaticFieldUsedWhenInstanceFieldExpected(), m)) CheckRecdFieldInfoAttributes g rfinfo m |> CommitOperationResult CheckRecdFieldInfoAccessible amap m ad rfinfo -let ILFieldInstanceChecks g amap ad m (finfo :ILFieldInfo) = +let ILFieldInstanceChecks g amap ad m (finfo : ILFieldInfo) = if finfo.IsStatic then error (Error (FSComp.SR.tcStaticFieldUsedWhenInstanceFieldExpected(), m)) CheckILFieldInfoAccessible g amap m ad finfo CheckILFieldAttributes g finfo m -let MethInfoChecks g amap isInstance tyargsOpt objArgs ad m (minfo:MethInfo) = +let MethInfoChecks g amap isInstance tyargsOpt objArgs ad m (minfo: MethInfo) = if minfo.IsInstance <> isInstance then if isInstance then error (Error (FSComp.SR.csMethodIsNotAnInstanceMethod(minfo.LogicalName), m)) @@ -1324,6 +1324,6 @@ let MethInfoChecks g amap isInstance tyargsOpt objArgs ad m (minfo:MethInfo) = exception FieldNotMutable of DisplayEnv * Tast.RecdFieldRef * range -let CheckRecdFieldMutation m denv (rfinfo:RecdFieldInfo) = +let CheckRecdFieldMutation m denv (rfinfo: RecdFieldInfo) = if not rfinfo.RecdField.IsMutable then error (FieldNotMutable(denv, rfinfo.RecdFieldRef, m)) diff --git a/src/fsharp/MethodOverrides.fs b/src/fsharp/MethodOverrides.fs index a58ecf2ce64..eda26ec3bd0 100644 --- a/src/fsharp/MethodOverrides.fs +++ b/src/fsharp/MethodOverrides.fs @@ -78,7 +78,7 @@ module DispatchSlotChecking = let FormatMethInfoSig g amap m denv d = bufs (fun buf -> PrintMethInfoSigToBuffer g amap m denv buf d) /// Get the override info for an existing (inherited) method being used to implement a dispatch slot. - let GetInheritedMemberOverrideInfo g amap m parentType (minfo:MethInfo) = + let GetInheritedMemberOverrideInfo g amap m parentType (minfo: MethInfo) = let nm = minfo.LogicalName let (CompiledSig (argTys, retTy, fmtps, ttpinst)) = CompiledSigOfMeth g amap m minfo @@ -86,7 +86,7 @@ module DispatchSlotChecking = Override(parentType, minfo.ApparentEnclosingTyconRef, mkSynId m nm, (fmtps, ttpinst), argTys, retTy, isFakeEventProperty, false) /// Get the override info for a value being used to implement a dispatch slot. - let GetTypeMemberOverrideInfo g reqdTy (overrideBy:ValRef) = + let GetTypeMemberOverrideInfo g reqdTy (overrideBy: ValRef) = let _, argInfos, retTy, _ = GetTypeOfMemberInMemberForm g overrideBy let nm = overrideBy.LogicalName @@ -124,7 +124,7 @@ module DispatchSlotChecking = Override(implKind, overrideBy.MemberApparentEntity, mkSynId overrideBy.Range nm, (memberMethodTypars, memberToParentInst), argTys, retTy, isFakeEventProperty, overrideBy.IsCompilerGenerated) /// Get the override information for an object expression method being used to implement dispatch slots - let GetObjectExprOverrideInfo g amap (implty, id:Ident, memberFlags, ty, arityInfo, bindingAttribs, rhsExpr) = + let GetObjectExprOverrideInfo g amap (implty, id: Ident, memberFlags, ty, arityInfo, bindingAttribs, rhsExpr) = // Dissect the type let tps, argInfos, retTy, _ = GetMemberTypeInMemberForm g memberFlags arityInfo ty id.idRange let argTys = argInfos |> List.mapSquared fst @@ -150,11 +150,11 @@ module DispatchSlotChecking = error(InternalError("Unexpected shape for object expression override", id.idRange)) /// Check if an override matches a dispatch slot by name - let IsNameMatch (dispatchSlot:MethInfo) (overrideBy: OverrideInfo) = + let IsNameMatch (dispatchSlot: MethInfo) (overrideBy: OverrideInfo) = (overrideBy.LogicalName = dispatchSlot.LogicalName) /// Check if an override matches a dispatch slot by name - let IsImplMatch g (dispatchSlot:MethInfo) (overrideBy: OverrideInfo) = + let IsImplMatch g (dispatchSlot: MethInfo) (overrideBy: OverrideInfo) = // If the override is listed as only relevant to one type, and we're matching it against an abstract slot of an interface type, // then check that interface type is the right type. match overrideBy.CanImplement with @@ -165,10 +165,10 @@ module DispatchSlotChecking = /// Check if the kinds of type parameters match between a dispatch slot and an override. let IsTyparKindMatch (CompiledSig(_, _, fvmtps, _)) (Override(_, _, _, (mtps, _), _, _, _, _)) = - List.lengthsEqAndForall2 (fun (tp1:Typar) (tp2:Typar) -> tp1.Kind = tp2.Kind) mtps fvmtps + List.lengthsEqAndForall2 (fun (tp1: Typar) (tp2: Typar) -> tp1.Kind = tp2.Kind) mtps fvmtps /// Check if an override is a partial match for the requirements for a dispatch slot - let IsPartialMatch g (dispatchSlot:MethInfo) compiledSig (Override(_, _, _, (mtps, _), argTys, _retTy, _, _) as overrideBy) = + let IsPartialMatch g (dispatchSlot: MethInfo) compiledSig (Override(_, _, _, (mtps, _), argTys, _retTy, _, _) as overrideBy) = IsNameMatch dispatchSlot overrideBy && let (CompiledSig (vargtys, _, fvmtps, _)) = compiledSig mtps.Length = fvmtps.Length && @@ -246,12 +246,12 @@ module DispatchSlotChecking = /// Check all dispatch slots are implemented by some override. let CheckDispatchSlotsAreImplemented (denv, g, amap, m, - nenv, sink:TcResultsSink, + nenv, sink: TcResultsSink, isOverallTyAbstract, reqdTy, - dispatchSlots:RequiredSlot list, - availPriorOverrides:OverrideInfo list, - overrides:OverrideInfo list) = + dispatchSlots: RequiredSlot list, + availPriorOverrides: OverrideInfo list, + overrides: OverrideInfo list) = let isReqdTyInterface = isInterfaceTy g reqdTy let showMissingMethodsAndRaiseErrors = (isReqdTyInterface || not isOverallTyAbstract) @@ -388,7 +388,7 @@ module DispatchSlotChecking = /// allReqdTys = {C;I2;I3} /// /// allReqdTys can include one class/record/union type. - let GetSlotImplSets (infoReader:InfoReader) denv isObjExpr allReqdTys = + let GetSlotImplSets (infoReader: InfoReader) denv isObjExpr allReqdTys = let g = infoReader.g let amap = infoReader.amap @@ -457,7 +457,7 @@ module DispatchSlotChecking = isImpliedInterfaceTable.ContainsKey (tcrefOfAppTy g ty) && impliedTys |> List.exists (TypesFeasiblyEquiv 0 g amap reqdTyRange ty) - //let isSlotImpl (minfo:MethInfo) = + //let isSlotImpl (minfo: MethInfo) = // not minfo.IsAbstract && minfo.IsVirtual // Compute the abstract slots that require implementations @@ -505,7 +505,7 @@ module DispatchSlotChecking = yield GetInheritedMemberOverrideInfo g amap reqdTyRange CanImplementAnyClassHierarchySlot minfo ] // We also collect up the properties. This is used for abstract slot inference when overriding properties - let isRelevantRequiredProperty (x:PropInfo) = + let isRelevantRequiredProperty (x: PropInfo) = (x.IsVirtualProperty && not (isInterfaceTy g reqdTy)) || isImpliedInterfaceType x.ApparentEnclosingType @@ -519,7 +519,7 @@ module DispatchSlotChecking = /// Check that a type definition implements all its required interfaces after processing all declarations /// within a file. - let CheckImplementationRelationAtEndOfInferenceScope (infoReader :InfoReader, denv, nenv, sink, tycon:Tycon, isImplementation) = + let CheckImplementationRelationAtEndOfInferenceScope (infoReader : InfoReader, denv, nenv, sink, tycon: Tycon, isImplementation) = let g = infoReader.g let amap = infoReader.amap @@ -547,7 +547,7 @@ module DispatchSlotChecking = overrideBy.IsVirtualMember && // exclude non virtual (e.g. keep override/default). [4469] not overrideBy.IsDispatchSlotMember) - let mustOverrideSomething reqdTy (overrideBy:ValRef) = + let mustOverrideSomething reqdTy (overrideBy: ValRef) = let memberInfo = overrideBy.MemberInfo.Value not (overrideBy.IsFSharpEventProperty(g)) && memberInfo.MemberFlags.IsOverrideOrExplicitImpl && @@ -641,7 +641,7 @@ module DispatchSlotChecking = /// "Type Completion" inference and a few other checks at the end of the inference scope -let FinalTypeDefinitionChecksAtEndOfInferenceScope (infoReader:InfoReader, nenv, sink, isImplementation, denv) (tycon:Tycon) = +let FinalTypeDefinitionChecksAtEndOfInferenceScope (infoReader: InfoReader, nenv, sink, isImplementation, denv) (tycon: Tycon) = let g = infoReader.g let amap = infoReader.amap @@ -702,7 +702,7 @@ let FinalTypeDefinitionChecksAtEndOfInferenceScope (infoReader:InfoReader, nenv, /// Get the methods relevant to determining if a uniquely-identified-override exists based on the syntactic information /// at the member signature prior to type inference. This is used to pre-assign type information if it does -let GetAbstractMethInfosForSynMethodDecl(infoReader:InfoReader, ad, memberName:Ident, bindm, typToSearchForAbstractMembers, valSynData) = +let GetAbstractMethInfosForSynMethodDecl(infoReader: InfoReader, ad, memberName: Ident, bindm, typToSearchForAbstractMembers, valSynData) = let minfos = match typToSearchForAbstractMembers with | _, Some(SlotImplSet(_, dispatchSlotsKeyed, _, _)) -> @@ -717,7 +717,7 @@ let GetAbstractMethInfosForSynMethodDecl(infoReader:InfoReader, ad, memberName:I /// Get the properties relevant to determining if a uniquely-identified-override exists based on the syntactic information /// at the member signature prior to type inference. This is used to pre-assign type information if it does -let GetAbstractPropInfosForSynPropertyDecl(infoReader:InfoReader, ad, memberName:Ident, bindm, typToSearchForAbstractMembers, _k, _valSynData) = +let GetAbstractPropInfosForSynPropertyDecl(infoReader: InfoReader, ad, memberName: Ident, bindm, typToSearchForAbstractMembers, _k, _valSynData) = let pinfos = match typToSearchForAbstractMembers with | _, Some(SlotImplSet(_, _, _, reqdProps)) -> diff --git a/src/fsharp/NameResolution.fs b/src/fsharp/NameResolution.fs index b598a46266a..bca1d50d60c 100644 --- a/src/fsharp/NameResolution.fs +++ b/src/fsharp/NameResolution.fs @@ -30,7 +30,7 @@ open FSharp.Compiler.ExtensionTyping #endif /// An object that captures the logical context for name resolution. -type NameResolver(g:TcGlobals, +type NameResolver(g: TcGlobals, amap: Import.ImportMap, infoReader: InfoReader, instantiationGenerator: (range -> Typars -> TypeInst)) = @@ -54,20 +54,20 @@ type NameResolver(g:TcGlobals, //------------------------------------------------------------------------- /// Get references to all the union cases in the type definition -let UnionCaseRefsInTycon (modref: ModuleOrNamespaceRef) (tycon:Tycon) = +let UnionCaseRefsInTycon (modref: ModuleOrNamespaceRef) (tycon: Tycon) = tycon.UnionCasesAsList |> List.map (mkModuleUnionCaseRef modref tycon) /// Get references to all the union cases defined in the module -let UnionCaseRefsInModuleOrNamespace (modref:ModuleOrNamespaceRef) = +let UnionCaseRefsInModuleOrNamespace (modref: ModuleOrNamespaceRef) = [ for x in modref.ModuleOrNamespaceType.AllEntities do yield! UnionCaseRefsInTycon modref x ] /// Try to find a type with a union case of the given name -let TryFindTypeWithUnionCase (modref:ModuleOrNamespaceRef) (id: Ident) = +let TryFindTypeWithUnionCase (modref: ModuleOrNamespaceRef) (id: Ident) = modref.ModuleOrNamespaceType.AllEntities |> QueueList.tryFind (fun tycon -> tycon.GetUnionCaseByName id.idText |> Option.isSome) /// Try to find a type with a record field of the given name -let TryFindTypeWithRecdField (modref:ModuleOrNamespaceRef) (id: Ident) = +let TryFindTypeWithRecdField (modref: ModuleOrNamespaceRef) (id: Ident) = modref.ModuleOrNamespaceType.AllEntities |> QueueList.tryFind (fun tycon -> tycon.GetFieldByName id.idText |> Option.isSome) @@ -100,7 +100,7 @@ let ActivePatternElemsOfVal modref vspec = /// Get the active pattern elements defined in a module, if any. Cache in the slot in the module type. -let ActivePatternElemsOfModuleOrNamespace (modref:ModuleOrNamespaceRef) : NameMap = +let ActivePatternElemsOfModuleOrNamespace (modref: ModuleOrNamespaceRef) : NameMap = let mtyp = modref.ModuleOrNamespaceType cacheOptRef mtyp.ActivePatternElemRefLookupTable (fun () -> mtyp.AllValsAndMembers @@ -214,11 +214,11 @@ type Item = /// Represents the potential resolution of an unqualified name to a type. | UnqualifiedType of TyconRef list - static member MakeMethGroup (nm, minfos:MethInfo list) = + static member MakeMethGroup (nm, minfos: MethInfo list) = let minfos = minfos |> List.sortBy (fun minfo -> minfo.NumArgs |> List.sum) Item.MethodGroup (nm, minfos, None) - static member MakeCtorGroup (nm, minfos:MethInfo list) = + static member MakeCtorGroup (nm, minfos: MethInfo list) = let minfos = minfos |> List.sortBy (fun minfo -> minfo.NumArgs |> List.sum) Item.CtorGroup (nm, minfos) @@ -260,12 +260,12 @@ let valRefHash (vref: ValRef) = /// Pairs an Item with a TyparInst showing how generic type variables of the item are instantiated at /// a particular usage point. type ItemWithInst = - { Item : Item + { Item: Item TyparInst: TyparInst } let ItemWithNoInst item = ({ Item = item; TyparInst = emptyTyparInst } : ItemWithInst) -let (|ItemWithInst|) (x:ItemWithInst) = (x.Item, x.TyparInst) +let (|ItemWithInst|) (x: ItemWithInst) = (x.Item, x.TyparInst) /// Represents a record field resolution and the information if the usage is deprecated. type FieldResolution = FieldResolution of RecdFieldRef * bool @@ -421,7 +421,7 @@ type NameResolutionEnv = let NextExtensionMethodPriority() = uint64 (newStamp()) /// Get the info for all the .NET-style extension members listed as static members in the type. -let private GetCSharpStyleIndexedExtensionMembersForTyconRef (amap:Import.ImportMap) m (tcrefOfStaticClass:TyconRef) = +let private GetCSharpStyleIndexedExtensionMembersForTyconRef (amap: Import.ImportMap) m (tcrefOfStaticClass: TyconRef) = let g = amap.g // Type must be non-generic and have 'Extension' attribute if isNil(tcrefOfStaticClass.Typars(m)) && TyconRefHasAttribute g m g.attrib_ExtensionAttribute tcrefOfStaticClass then @@ -503,7 +503,7 @@ type BulkAdd = Yes | No /// bulkAddMode: true when adding the values from the 'open' of a namespace /// or module, when we collapse the value table down to a dictionary. -let AddValRefsToItems (bulkAddMode: BulkAdd) (eUnqualifiedItems: LayeredMap<_, _>) (vrefs:ValRef[]) = +let AddValRefsToItems (bulkAddMode: BulkAdd) (eUnqualifiedItems: LayeredMap<_, _>) (vrefs: ValRef[]) = // Object model members are not added to the unqualified name resolution environment let vrefs = vrefs |> Array.filter (fun vref -> not vref.IsMember) @@ -518,7 +518,7 @@ let AddValRefsToItems (bulkAddMode: BulkAdd) (eUnqualifiedItems: LayeredMap<_, _ eUnqualifiedItems.Add (vref.LogicalName, Item.Value vref) /// Add an F# value to the table of available extension members, if necessary, as an FSharp-style extension member -let AddValRefToExtensionMembers pri (eIndexedExtensionMembers: TyconRefMultiMap<_>) (vref:ValRef) = +let AddValRefToExtensionMembers pri (eIndexedExtensionMembers: TyconRefMultiMap<_>) (vref: ValRef) = if vref.IsMember && vref.IsExtensionMember then eIndexedExtensionMembers.Add (vref.MemberApparentEntity, FSExtMem (vref, pri)) else @@ -534,7 +534,7 @@ let AddFakeNameToNameEnv nm nenv item = {nenv with eUnqualifiedItems = nenv.eUnqualifiedItems.Add (nm, item) } /// Add an F# value to the table of available active patterns -let AddValRefsToActivePatternsNameEnv ePatItems (vref:ValRef) = +let AddValRefsToActivePatternsNameEnv ePatItems (vref: ValRef) = let ePatItems = (ActivePatternElemsOfValRef vref, ePatItems) ||> List.foldBack (fun apref tab -> @@ -557,7 +557,7 @@ let AddValRefsToNameEnvWithPriority bulkAddMode pri nenv (vrefs: ValRef []) = ePatItems = (nenv.ePatItems, vrefs) ||> Array.fold AddValRefsToActivePatternsNameEnv } /// Add a single F# value to the environment. -let AddValRefToNameEnv nenv (vref:ValRef) = +let AddValRefToNameEnv nenv (vref: ValRef) = let pri = NextExtensionMethodPriority() { nenv with eUnqualifiedItems = @@ -579,7 +579,7 @@ let AddActivePatternResultTagsToNameEnv (apinfo: PrettyNaming.ActivePatternInfo) ||> List.foldBack (fun (j, nm) acc -> acc.Add(nm, Item.ActivePatternResult(apinfo, ty, j, m))) } /// Generalize a union case, from Cons --> List.Cons -let GeneralizeUnionCaseRef (ucref:UnionCaseRef) = +let GeneralizeUnionCaseRef (ucref: UnionCaseRef) = UnionCaseInfo (fst (generalizeTyconRef ucref.TyconRef), ucref) @@ -595,7 +595,7 @@ let AddTyconsByDemangledNameAndArity (bulkAddMode: BulkAdd) (tcrefs: TyconRef[]) | BulkAdd.No -> (tab, entries) ||> Array.fold (fun tab (KeyValue(k, v)) -> tab.Add(k, v)) /// Add type definitions to the sub-table of the environment indexed by access name -let AddTyconByAccessNames bulkAddMode (tcrefs:TyconRef[]) (tab: LayeredMultiMap) = +let AddTyconByAccessNames bulkAddMode (tcrefs: TyconRef[]) (tab: LayeredMultiMap) = if tcrefs.Length = 0 then tab else let entries = tcrefs @@ -606,16 +606,16 @@ let AddTyconByAccessNames bulkAddMode (tcrefs:TyconRef[]) (tab: LayeredMultiMap< | BulkAdd.No -> (tab, entries) ||> Array.fold (fun tab (KeyValue(k, v)) -> tab.Add (k, v)) /// Add a record field to the corresponding sub-table of the name resolution environment -let AddRecdField (rfref:RecdFieldRef) tab = NameMultiMap.add rfref.FieldName rfref tab +let AddRecdField (rfref: RecdFieldRef) tab = NameMultiMap.add rfref.FieldName rfref tab /// Add a set of union cases to the corresponding sub-table of the environment -let AddUnionCases1 (tab:Map<_, _>) (ucrefs:UnionCaseRef list) = +let AddUnionCases1 (tab: Map<_, _>) (ucrefs: UnionCaseRef list) = (tab, ucrefs) ||> List.fold (fun acc ucref -> let item = Item.UnionCase(GeneralizeUnionCaseRef ucref, false) acc.Add (ucref.CaseName, item)) /// Add a set of union cases to the corresponding sub-table of the environment -let AddUnionCases2 bulkAddMode (eUnqualifiedItems: LayeredMap<_, _>) (ucrefs :UnionCaseRef list) = +let AddUnionCases2 bulkAddMode (eUnqualifiedItems: LayeredMap<_, _>) (ucrefs: UnionCaseRef list) = match bulkAddMode with | BulkAdd.Yes -> let items = @@ -630,7 +630,7 @@ let AddUnionCases2 bulkAddMode (eUnqualifiedItems: LayeredMap<_, _>) (ucrefs :Un acc.Add (ucref.CaseName, item)) /// Add any implied contents of a type definition to the environment. -let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g:TcGlobals) amap m nenv (tcref:TyconRef) = +let private AddPartsOfTyconRefToNameEnv bulkAddMode ownDefinition (g: TcGlobals) amap m nenv (tcref: TyconRef) = let isIL = tcref.IsILTycon let ucrefs = if isIL then [] else tcref.UnionCasesAsList |> List.map tcref.MakeNestedUnionCaseRef @@ -719,7 +719,7 @@ let AddTyconRefsToNameEnv bulkAddMode ownDefinition g amap m root nenv tcrefs = AddTyconByAccessNames bulkAddMode tcrefs nenv.eTyconsByAccessNames } /// Add an F# exception definition to the name resolution environment -let AddExceptionDeclsToNameEnv bulkAddMode nenv (ecref:TyconRef) = +let AddExceptionDeclsToNameEnv bulkAddMode nenv (ecref: TyconRef) = assert ecref.IsExceptionDecl let item = Item.ExnCase ecref {nenv with @@ -733,7 +733,7 @@ let AddExceptionDeclsToNameEnv bulkAddMode nenv (ecref:TyconRef) = ePatItems = nenv.ePatItems.Add (ecref.LogicalName, item) } /// Add a module abbreviation to the name resolution environment -let AddModuleAbbrevToNameEnv (id:Ident) nenv modrefs = +let AddModuleAbbrevToNameEnv (id: Ident) nenv modrefs = {nenv with eModulesAndNamespaces = let add old nw = nw @ old @@ -778,7 +778,7 @@ let rec AddModuleOrNamespaceRefsToNameEnv g amap m root ad nenv (modrefs: Module nenv /// Add the contents of a module or namespace to the name resolution environment -and AddModuleOrNamespaceContentsToNameEnv (g:TcGlobals) amap (ad:AccessorDomain) m root nenv (modref:ModuleOrNamespaceRef) = +and AddModuleOrNamespaceContentsToNameEnv (g: TcGlobals) amap (ad: AccessorDomain) m root nenv (modref: ModuleOrNamespaceRef) = let pri = NextExtensionMethodPriority() let mty = modref.ModuleOrNamespaceType @@ -820,7 +820,7 @@ and AddModulesAndNamespacesContentsToNameEnv g amap ad m root nenv modrefs = (modrefs, nenv) ||> List.foldBack (fun modref acc -> AddModuleOrNamespaceContentsToNameEnv g amap ad m root acc modref) /// Add a single modules or namespace to the name resolution environment -let AddModuleOrNamespaceRefToNameEnv g amap m root ad nenv (modref:EntityRef) = +let AddModuleOrNamespaceRefToNameEnv g amap m root ad nenv (modref: EntityRef) = AddModuleOrNamespaceRefsToNameEnv g amap m root ad nenv [modref] @@ -834,7 +834,7 @@ type CheckForDuplicateTyparFlag = let AddDeclaredTyparsToNameEnv check nenv typars = let typarmap = List.foldBack - (fun (tp:Typar) sofar -> + (fun (tp: Typar) sofar -> match check with | CheckForDuplicateTypars -> if Map.containsKey tp.Name sofar then @@ -851,14 +851,14 @@ let AddDeclaredTyparsToNameEnv check nenv typars = /// Convert a reference to a named type into a type that includes /// a fresh set of inference type variables for the type parameters of the union type. -let FreshenTycon (ncenv: NameResolver) m (tcref:TyconRef) = +let FreshenTycon (ncenv: NameResolver) m (tcref: TyconRef) = let tinst = ncenv.InstantiationGenerator m (tcref.Typars m) let improvedTy = ncenv.g.decompileType tcref tinst improvedTy /// Convert a reference to a union case into a UnionCaseInfo that includes /// a fresh set of inference type variables for the type parameters of the union type. -let FreshenUnionCaseRef (ncenv: NameResolver) m (ucref:UnionCaseRef) = +let FreshenUnionCaseRef (ncenv: NameResolver) m (ucref: UnionCaseRef) = let tinst = ncenv.InstantiationGenerator m (ucref.TyconRef.Typars m) UnionCaseInfo(tinst, ucref) @@ -1007,7 +1007,7 @@ type TypeNameResolutionInfo = /// Qualified lookups of type names where the number of generic arguments is known /// from context, e.g. Module.Type. The full names suh as ``List`1`` can /// be used to qualify access if needed -let LookupTypeNameInEntityHaveArity nm (staticResInfo: TypeNameResolutionStaticArgsInfo) (mty:ModuleOrNamespaceType) = +let LookupTypeNameInEntityHaveArity nm (staticResInfo: TypeNameResolutionStaticArgsInfo) (mty: ModuleOrNamespaceType) = let attempt1 = mty.TypesByMangledName.TryFind (staticResInfo.MangledNameForType nm) match attempt1 with | None -> mty.TypesByMangledName.TryFind nm @@ -1015,7 +1015,7 @@ let LookupTypeNameInEntityHaveArity nm (staticResInfo: TypeNameResolutionStaticA /// Unqualified lookups of type names where the number of generic arguments is known /// from context, e.g. List. Rebindings due to 'open' may have rebound identifiers. -let LookupTypeNameInEnvHaveArity fq nm numTyArgs (nenv:NameResolutionEnv) = +let LookupTypeNameInEnvHaveArity fq nm numTyArgs (nenv: NameResolutionEnv) = let key = match TryDemangleGenericNameAndPos nm with | ValueSome pos -> DecodeGenericTypeName pos nm @@ -1060,7 +1060,7 @@ let LookupTypeNameInEnvNoArity fq nm (nenv: NameResolutionEnv) = LookupTypeNameNoArity nm (nenv.TyconsByDemangledNameAndArity fq) (nenv.TyconsByAccessNames fq) /// Qualified lookup of type names in an entity -let LookupTypeNameInEntityNoArity m nm (mtyp:ModuleOrNamespaceType) = +let LookupTypeNameInEntityNoArity m nm (mtyp: ModuleOrNamespaceType) = LookupTypeNameNoArity nm (mtyp.TypesByDemangledNameAndArity m) mtyp.TypesByAccessNames /// Qualified lookup of type names in an entity where we may know a generic argument count @@ -1094,7 +1094,7 @@ let CheckForDirectReferenceToGeneratedType (tcref: TyconRef, genOk, m) = /// This adds a new entity for a lazily discovered provided type into the TAST structure. -let AddEntityForProvidedType (amap: Import.ImportMap, modref: ModuleOrNamespaceRef, resolutionEnvironment, st:Tainted, m) = +let AddEntityForProvidedType (amap: Import.ImportMap, modref: ModuleOrNamespaceRef, resolutionEnvironment, st: Tainted, m) = let importProvidedType t = Import.ImportProvidedType amap m t let isSuppressRelocate = amap.g.isInteractive || st.PUntaint((fun st -> st.IsSuppressRelocate), m) let tycon = Construct.NewProvidedTycon(resolutionEnvironment, st, importProvidedType, isSuppressRelocate, m) @@ -1137,7 +1137,7 @@ let ResolveProvidedTypeNameInEntity (amap, m, typeName, modref: ModuleOrNamespac #endif /// Lookup a type name in an entity. -let LookupTypeNameInEntityMaybeHaveArity (amap, m, ad, nm, staticResInfo:TypeNameResolutionStaticArgsInfo, modref: ModuleOrNamespaceRef) = +let LookupTypeNameInEntityMaybeHaveArity (amap, m, ad, nm, staticResInfo: TypeNameResolutionStaticArgsInfo, modref: ModuleOrNamespaceRef) = let mtyp = modref.ModuleOrNamespaceType let tcrefs = match staticResInfo with @@ -1164,13 +1164,13 @@ let LookupTypeNameInEntityMaybeHaveArity (amap, m, ad, nm, staticResInfo:TypeNam /// /// Handle the .NET/C# business where nested generic types implicitly accumulate the type parameters /// from their enclosing types. -let MakeNestedType (ncenv:NameResolver) (tinst:TType list) m (tcrefNested:TyconRef) = +let MakeNestedType (ncenv: NameResolver) (tinst: TType list) m (tcrefNested: TyconRef) = let tps = List.drop tinst.Length (tcrefNested.Typars m) let tinstNested = ncenv.InstantiationGenerator m tps mkAppTy tcrefNested (tinst @ tinstNested) /// Get all the accessible nested types of an existing type. -let GetNestedTypesOfType (ad, ncenv:NameResolver, optFilter, staticResInfo, checkForGenerated, m) ty = +let GetNestedTypesOfType (ad, ncenv: NameResolver, optFilter, staticResInfo, checkForGenerated, m) ty = let g = ncenv.g ncenv.InfoReader.GetPrimaryTypeHierachy(AllowMultiIntfInstantiations.Yes, m, ty) |> List.collect (fun ty -> match ty with @@ -1256,48 +1256,48 @@ type FormatStringCheckContext = /// An abstract type for reporting the results of name resolution and type checking. type ITypecheckResultsSink = - abstract NotifyEnvWithScope : range * NameResolutionEnv * AccessorDomain -> unit - abstract NotifyExprHasType : pos * TType * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range -> unit - abstract NotifyNameResolution : pos * Item * Item * TyparInst * ItemOccurence * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range * bool -> unit - abstract NotifyFormatSpecifierLocation : range * int -> unit - abstract NotifyOpenDeclaration : OpenDeclaration -> unit - abstract CurrentSource : string option - abstract FormatStringCheckContext : FormatStringCheckContext option - -let (|ValRefOfProp|_|) (pi : PropInfo) = pi.ArbitraryValRef -let (|ValRefOfMeth|_|) (mi : MethInfo) = mi.ArbitraryValRef -let (|ValRefOfEvent|_|) (evt : EventInfo) = evt.ArbitraryValRef - -let rec (|RecordFieldUse|_|) (item : Item) = + abstract NotifyEnvWithScope: range * NameResolutionEnv * AccessorDomain -> unit + abstract NotifyExprHasType: pos * TType * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range -> unit + abstract NotifyNameResolution: pos * Item * Item * TyparInst * ItemOccurence * Tastops.DisplayEnv * NameResolutionEnv * AccessorDomain * range * bool -> unit + abstract NotifyFormatSpecifierLocation: range * int -> unit + abstract NotifyOpenDeclaration: OpenDeclaration -> unit + abstract CurrentSource: string option + abstract FormatStringCheckContext: FormatStringCheckContext option + +let (|ValRefOfProp|_|) (pi: PropInfo) = pi.ArbitraryValRef +let (|ValRefOfMeth|_|) (mi: MethInfo) = mi.ArbitraryValRef +let (|ValRefOfEvent|_|) (evt: EventInfo) = evt.ArbitraryValRef + +let rec (|RecordFieldUse|_|) (item: Item) = match item with | Item.RecdField(RecdFieldInfo(_, RFRef(tcref, name))) -> Some (name, tcref) | Item.SetterArg(_, RecordFieldUse(f)) -> Some(f) | _ -> None -let rec (|ILFieldUse|_|) (item : Item) = +let rec (|ILFieldUse|_|) (item: Item) = match item with | Item.ILField(finfo) -> Some(finfo) | Item.SetterArg(_, ILFieldUse(f)) -> Some(f) | _ -> None -let rec (|PropertyUse|_|) (item : Item) = +let rec (|PropertyUse|_|) (item: Item) = match item with | Item.Property(_, pinfo::_) -> Some(pinfo) | Item.SetterArg(_, PropertyUse(pinfo)) -> Some(pinfo) | _ -> None -let rec (|FSharpPropertyUse|_|) (item : Item) = +let rec (|FSharpPropertyUse|_|) (item: Item) = match item with | Item.Property(_, [ValRefOfProp vref]) -> Some(vref) | Item.SetterArg(_, FSharpPropertyUse(propDef)) -> Some(propDef) | _ -> None -let (|MethodUse|_|) (item : Item) = +let (|MethodUse|_|) (item: Item) = match item with | Item.MethodGroup(_, [minfo], _) -> Some(minfo) | _ -> None -let (|FSharpMethodUse|_|) (item : Item) = +let (|FSharpMethodUse|_|) (item: Item) = match item with | Item.MethodGroup(_, [ValRefOfMeth vref], _) -> Some(vref) | Item.Value(vref) when vref.IsMember -> Some(vref) @@ -1316,22 +1316,22 @@ let (|EntityUse|_|) (item: Item) = | _ -> None | _ -> None -let (|EventUse|_|) (item : Item) = +let (|EventUse|_|) (item: Item) = match item with | Item.Event(einfo) -> Some einfo | _ -> None -let (|FSharpEventUse|_|) (item : Item) = +let (|FSharpEventUse|_|) (item: Item) = match item with | Item.Event(ValRefOfEvent vref) -> Some vref | _ -> None -let (|UnionCaseUse|_|) (item : Item) = +let (|UnionCaseUse|_|) (item: Item) = match item with | Item.UnionCase(UnionCaseInfo(_, u1), _) -> Some u1 | _ -> None -let (|ValUse|_|) (item:Item) = +let (|ValUse|_|) (item: Item) = match item with | Item.Value vref | FSharpPropertyUse vref @@ -1340,16 +1340,16 @@ let (|ValUse|_|) (item:Item) = | Item.CustomBuilder(_, vref) -> Some vref | _ -> None -let (|ActivePatternCaseUse|_|) (item:Item) = +let (|ActivePatternCaseUse|_|) (item: Item) = match item with | Item.ActivePatternCase(APElemRef(_, vref, idx)) -> Some (vref.SigRange, vref.DefinitionRange, idx) | Item.ActivePatternResult(ap, _, idx, _) -> Some (ap.Range, ap.Range, idx) | _ -> None -let tyconRefDefnHash (_g: TcGlobals) (eref1:EntityRef) = +let tyconRefDefnHash (_g: TcGlobals) (eref1: EntityRef) = hash eref1.LogicalName -let tyconRefDefnEq g (eref1:EntityRef) (eref2: EntityRef) = +let tyconRefDefnEq g (eref1: EntityRef) (eref2: EntityRef) = tyconRefEq g eref1 eref2 || // Signature items considered equal to implementation items @@ -1357,10 +1357,10 @@ let tyconRefDefnEq g (eref1:EntityRef) (eref2: EntityRef) = (eref1.DefinitionRange = eref2.DefinitionRange || eref1.SigRange = eref2.SigRange) && eref1.LogicalName = eref2.LogicalName -let valRefDefnHash (_g: TcGlobals) (vref1:ValRef) = +let valRefDefnHash (_g: TcGlobals) (vref1: ValRef) = hash vref1.DisplayName -let valRefDefnEq g (vref1:ValRef) (vref2: ValRef) = +let valRefDefnEq g (vref1: ValRef) (vref2: ValRef) = valRefEq g vref1 vref2 || // Signature items considered equal to implementation items @@ -1368,10 +1368,10 @@ let valRefDefnEq g (vref1:ValRef) (vref2: ValRef) = (vref1.DefinitionRange = vref2.DefinitionRange || vref1.SigRange = vref2.SigRange) && vref1.LogicalName = vref2.LogicalName -let unionCaseRefDefnEq g (uc1:UnionCaseRef) (uc2: UnionCaseRef) = +let unionCaseRefDefnEq g (uc1: UnionCaseRef) (uc2: UnionCaseRef) = uc1.CaseName = uc2.CaseName && tyconRefDefnEq g uc1.TyconRef uc2.TyconRef -/// Given the Item 'orig' - returns function 'other : Item -> bool', that will yield true if other and orig represents the same item and false - otherwise +/// Given the Item 'orig' - returns function 'other: Item -> bool', that will yield true if other and orig represents the same item and false - otherwise let ItemsAreEffectivelyEqual g orig other = match orig, other with | EntityUse ty1, EntityUse ty2 -> @@ -1438,7 +1438,7 @@ let ItemsAreEffectivelyEqual g orig other = | _ -> false -/// Given the Item 'orig' - returns function 'other : Item -> bool', that will yield true if other and orig represents the same item and false - otherwise +/// Given the Item 'orig' - returns function 'other: Item -> bool', that will yield true if other and orig represents the same item and false - otherwise let ItemsAreEffectivelyEqualHash (g: TcGlobals) orig = match orig with | EntityUse tcref -> tyconRefDefnHash g tcref @@ -1456,7 +1456,7 @@ let ItemsAreEffectivelyEqualHash (g: TcGlobals) orig = | _ -> 389329 [] -type CapturedNameResolution(p:pos, i:Item, tpinst, io:ItemOccurence, de:DisplayEnv, nre:NameResolutionEnv, ad:AccessorDomain, m:range) = +type CapturedNameResolution(p: pos, i: Item, tpinst, io: ItemOccurence, de: DisplayEnv, nre: NameResolutionEnv, ad: AccessorDomain, m: range) = member this.Pos = p member this.Item = i member this.ItemWithInst = ({ Item = i; TyparInst = tpinst } : ItemWithInst) @@ -1470,10 +1470,10 @@ type CapturedNameResolution(p:pos, i:Item, tpinst, io:ItemOccurence, de:DisplayE /// Represents container for all name resolutions that were met so far when typechecking some particular file type TcResolutions - (capturedEnvs : ResizeArray, - capturedExprTypes : ResizeArray, - capturedNameResolutions : ResizeArray, - capturedMethodGroupResolutions : ResizeArray) = + (capturedEnvs: ResizeArray, + capturedExprTypes: ResizeArray, + capturedNameResolutions: ResizeArray, + capturedMethodGroupResolutions: ResizeArray) = static let empty = TcResolutions(ResizeArray(0), ResizeArray(0), ResizeArray(0), ResizeArray(0)) @@ -1496,7 +1496,7 @@ type TcSymbolUseData = /// This is a memory-critical data structure - allocations of this data structure and its immediate contents /// is one of the highest memory long-lived data structures in typical uses of IDEs. Not many of these objects /// are allocated (one per file), but they are large because the allUsesOfAllSymbols array is large. -type TcSymbolUses(g, capturedNameResolutions : ResizeArray, formatSpecifierLocations: (range * int)[]) = +type TcSymbolUses(g, capturedNameResolutions: ResizeArray, formatSpecifierLocations: (range * int)[]) = // Make sure we only capture the information we really need to report symbol uses let allUsesOfSymbols = @@ -1529,7 +1529,7 @@ type TcResultsSinkImpl(g, ?source: string) = let capturedNameResolutionIdentifiers = new System.Collections.Generic.HashSet ( { new IEqualityComparer<_> with - member __.GetHashCode((p:pos, i)) = p.Line + 101 * p.Column + hash i + member __.GetHashCode((p: pos, i)) = p.Line + 101 * p.Column + hash i member __.Equals((p1, i1), (p2, i2)) = posEq p1 p2 && i1 = i2 } ) let capturedModulesAndNamespaces = @@ -1540,7 +1540,7 @@ type TcResultsSinkImpl(g, ?source: string) = let capturedMethodGroupResolutions = ResizeArray<_>() let capturedOpenDeclarations = ResizeArray() - let allowedRange (m:range) = not m.IsSynthetic + let allowedRange (m: range) = not m.IsSynthetic let formatStringCheckContext = lazy @@ -1617,47 +1617,47 @@ type TcResultsSinkImpl(g, ?source: string) = /// An abstract type for reporting the results of name resolution and type checking, and which allows /// temporary suspension and/or redirection of reporting. type TcResultsSink = - { mutable CurrentSink : ITypecheckResultsSink option } + { mutable CurrentSink: ITypecheckResultsSink option } static member NoSink = { CurrentSink = None } static member WithSink sink = { CurrentSink = Some sink } /// Temporarily redirect reporting of name resolution and type checking results -let WithNewTypecheckResultsSink (newSink : ITypecheckResultsSink, sink:TcResultsSink) = +let WithNewTypecheckResultsSink (newSink: ITypecheckResultsSink, sink: TcResultsSink) = let old = sink.CurrentSink sink.CurrentSink <- Some newSink { new System.IDisposable with member x.Dispose() = sink.CurrentSink <- old } /// Temporarily suspend reporting of name resolution and type checking results -let TemporarilySuspendReportingTypecheckResultsToSink (sink:TcResultsSink) = +let TemporarilySuspendReportingTypecheckResultsToSink (sink: TcResultsSink) = let old = sink.CurrentSink sink.CurrentSink <- None { new System.IDisposable with member x.Dispose() = sink.CurrentSink <- old } /// Report the active name resolution environment for a specific source range -let CallEnvSink (sink:TcResultsSink) (scopem, nenv, ad) = +let CallEnvSink (sink: TcResultsSink) (scopem, nenv, ad) = match sink.CurrentSink with | None -> () | Some sink -> sink.NotifyEnvWithScope(scopem, nenv, ad) /// Report a specific name resolution at a source range -let CallNameResolutionSink (sink:TcResultsSink) (m:range, nenv, item, itemMethodGroup, tpinst, occurenceType, denv, ad) = +let CallNameResolutionSink (sink: TcResultsSink) (m: range, nenv, item, itemMethodGroup, tpinst, occurenceType, denv, ad) = match sink.CurrentSink with | None -> () | Some sink -> sink.NotifyNameResolution(m.End, item, itemMethodGroup, tpinst, occurenceType, denv, nenv, ad, m, false) -let CallNameResolutionSinkReplacing (sink:TcResultsSink) (m:range, nenv, item, itemMethodGroup, tpinst, occurenceType, denv, ad) = +let CallNameResolutionSinkReplacing (sink: TcResultsSink) (m: range, nenv, item, itemMethodGroup, tpinst, occurenceType, denv, ad) = match sink.CurrentSink with | None -> () | Some sink -> sink.NotifyNameResolution(m.End, item, itemMethodGroup, tpinst, occurenceType, denv, nenv, ad, m, true) /// Report a specific expression typing at a source range -let CallExprHasTypeSink (sink:TcResultsSink) (m:range, nenv, ty, denv, ad) = +let CallExprHasTypeSink (sink: TcResultsSink) (m: range, nenv, ty, denv, ad) = match sink.CurrentSink with | None -> () | Some sink -> sink.NotifyExprHasType(m.End, ty, denv, nenv, ad, m) -let CallOpenDeclarationSink (sink:TcResultsSink) (openDeclaration: OpenDeclaration) = +let CallOpenDeclarationSink (sink: TcResultsSink) (openDeclaration: OpenDeclaration) = match sink.CurrentSink with | None -> () | Some sink -> sink.NotifyOpenDeclaration(openDeclaration) @@ -1736,7 +1736,7 @@ type ResolutionInfo = | ResolutionInfo of (*entityPath, reversed*)(range * EntityRef) list * (*warnings/errors*)(ResultTyparChecker -> unit) static member SendEntityPathToSink(sink, ncenv: NameResolver, nenv, occ, ad, ResolutionInfo(entityPath, warnings), typarChecker) = - entityPath |> List.iter (fun (m, eref:EntityRef) -> + entityPath |> List.iter (fun (m, eref: EntityRef) -> CheckEntityAttributes ncenv.g eref m |> CommitOperationResult CheckTyconAccessible ncenv.amap m ad eref |> ignore let item = @@ -1773,8 +1773,8 @@ type ResolutionInfo = let CheckForTypeLegitimacyAndMultipleGenericTypeAmbiguities (tcrefs:(ResolutionInfo * TyconRef) list, - typeNameResInfo:TypeNameResolutionInfo, - genOk:PermitDirectReferenceToGeneratedType, + typeNameResInfo: TypeNameResolutionInfo, + genOk: PermitDirectReferenceToGeneratedType, m) = let tcrefs = @@ -1825,7 +1825,7 @@ let CheckForTypeLegitimacyAndMultipleGenericTypeAmbiguities //------------------------------------------------------------------------- /// Perform name resolution for an identifier which must resolve to be a namespace or module. -let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQualified (nenv:NameResolutionEnv) ad (id:Ident) (rest:Ident list) isOpenDecl = +let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQualified (nenv: NameResolutionEnv) ad (id: Ident) (rest: Ident list) isOpenDecl = if first && id.idText = MangledGlobalName then match rest with | [] -> @@ -1845,7 +1845,7 @@ let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQu UndefinedName(0, FSComp.SR.undefinedNameNamespaceOrModule, id, suggestModulesAndNamespaces)) let mutable moduleNotFoundErrorCache = None - let moduleNotFound (modref: ModuleOrNamespaceRef) (mty:ModuleOrNamespaceType) (id:Ident) depth = + let moduleNotFound (modref: ModuleOrNamespaceRef) (mty: ModuleOrNamespaceType) (id: Ident) depth = match moduleNotFoundErrorCache with | Some (oldId, error) when oldId = id.idRange -> error | _ -> @@ -1867,7 +1867,7 @@ let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQu match moduleOrNamespaces.TryGetValue id.idText with | true, modrefs -> /// Look through the sub-namespaces and/or modules - let rec look depth (modref: ModuleOrNamespaceRef) (mty:ModuleOrNamespaceType) (lid:Ident list) = + let rec look depth (modref: ModuleOrNamespaceRef) (mty: ModuleOrNamespaceType) (lid: Ident list) = match lid with | [] -> success (depth, modref, mty) | id :: rest -> @@ -1891,7 +1891,7 @@ let rec ResolveLongIndentAsModuleOrNamespace sink atMostOne amap m first fullyQu | _ -> raze (namespaceNotFound.Force()) -let ResolveLongIndentAsModuleOrNamespaceThen sink atMostOne amap m fullyQualified (nenv:NameResolutionEnv) ad id rest isOpenDecl f = +let ResolveLongIndentAsModuleOrNamespaceThen sink atMostOne amap m fullyQualified (nenv: NameResolutionEnv) ad id rest isOpenDecl f = match ResolveLongIndentAsModuleOrNamespace sink ResultCollectionSettings.AllResults amap m true fullyQualified nenv ad id [] isOpenDecl with | Result modrefs -> match rest with @@ -1907,7 +1907,7 @@ let ResolveLongIndentAsModuleOrNamespaceThen sink atMostOne amap m fullyQualifie // Bind name used in "new Foo.Bar(...)" constructs //------------------------------------------------------------------------- -let private ResolveObjectConstructorPrim (ncenv:NameResolver) edenv resInfo m ad ty = +let private ResolveObjectConstructorPrim (ncenv: NameResolver) edenv resInfo m ad ty = let g = ncenv.g let amap = ncenv.amap if isDelegateTy g ty then @@ -1933,15 +1933,15 @@ let private ResolveObjectConstructorPrim (ncenv:NameResolver) edenv resInfo m ad success (resInfo, Item.MakeCtorGroup ((tcrefOfAppTy g metadataTy).LogicalName, (defaultStructCtorInfo@ctorInfos))) /// Perform name resolution for an identifier which must resolve to be an object constructor. -let ResolveObjectConstructor (ncenv:NameResolver) edenv m ad ty = - ResolveObjectConstructorPrim (ncenv:NameResolver) edenv [] m ad ty |?> (fun (_resInfo, item) -> item) +let ResolveObjectConstructor (ncenv: NameResolver) edenv m ad ty = + ResolveObjectConstructorPrim (ncenv: NameResolver) edenv [] m ad ty |?> (fun (_resInfo, item) -> item) //------------------------------------------------------------------------- // Bind the "." notation (member lookup or lookup in a type) //------------------------------------------------------------------------- /// Query the declared properties of a type (including inherited properties) -let IntrinsicPropInfosOfTypeInScope (infoReader:InfoReader) (optFilter, ad) findFlag m ty = +let IntrinsicPropInfosOfTypeInScope (infoReader: InfoReader) (optFilter, ad) findFlag m ty = let g = infoReader.g let amap = infoReader.amap let pinfos = GetIntrinsicPropInfoSetsOfType infoReader (optFilter, ad, AllowMultiIntfInstantiations.Yes) findFlag m ty @@ -1949,7 +1949,7 @@ let IntrinsicPropInfosOfTypeInScope (infoReader:InfoReader) (optFilter, ad) find pinfos /// Select from a list of extension properties -let SelectPropInfosFromExtMembers (infoReader:InfoReader, ad, optFilter) declaringTy m extMemInfos = +let SelectPropInfosFromExtMembers (infoReader: InfoReader, ad, optFilter) declaringTy m extMemInfos = let g = infoReader.g let amap = infoReader.amap // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers, hence setify. @@ -1968,7 +1968,7 @@ let SelectPropInfosFromExtMembers (infoReader:InfoReader, ad, optFilter) declari propCollector.Close() /// Query the available extension properties of a type (including extension properties for inherited types) -let ExtensionPropInfosOfTypeInScope (infoReader:InfoReader) (nenv: NameResolutionEnv) (optFilter, ad) m ty = +let ExtensionPropInfosOfTypeInScope (infoReader: InfoReader) (nenv: NameResolutionEnv) (optFilter, ad) m ty = let g = infoReader.g let extMemsFromHierarchy = @@ -1989,7 +1989,7 @@ let AllPropInfosOfTypeInScope infoReader nenv (optFilter, ad) findFlag m ty = @ ExtensionPropInfosOfTypeInScope infoReader nenv (optFilter, ad) m ty /// Get the available methods of a type (both declared and inherited) -let IntrinsicMethInfosOfType (infoReader:InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = +let IntrinsicMethInfosOfType (infoReader: InfoReader) (optFilter, ad, allowMultiIntfInst) findFlag m ty = let g = infoReader.g let amap = infoReader.amap let minfos = GetIntrinsicMethInfoSetsOfType infoReader (optFilter, ad, allowMultiIntfInst) findFlag m ty @@ -1997,7 +1997,7 @@ let IntrinsicMethInfosOfType (infoReader:InfoReader) (optFilter, ad, allowMultiI minfos /// Select from a list of extension methods -let SelectMethInfosFromExtMembers (infoReader:InfoReader) optFilter apparentTy m extMemInfos = +let SelectMethInfosFromExtMembers (infoReader: InfoReader) optFilter apparentTy m extMemInfos = let g = infoReader.g // NOTE: multiple "open"'s push multiple duplicate values into eIndexedExtensionMembers let seen = HashSet(ExtensionMember.Comparer g) @@ -2031,7 +2031,7 @@ let SelectMethInfosFromExtMembers (infoReader:InfoReader) optFilter apparentTy m ] /// Query the available extension properties of a methods (including extension methods for inherited types) -let ExtensionMethInfosOfTypeInScope (infoReader:InfoReader) (nenv: NameResolutionEnv) optFilter m ty = +let ExtensionMethInfosOfTypeInScope (infoReader: InfoReader) (nenv: NameResolutionEnv) optFilter m ty = let extMemsDangling = SelectMethInfosFromExtMembers infoReader optFilter ty m nenv.eUnindexedExtensionMembers let extMemsFromHierarchy = infoReader.GetEntireTypeHierachy(AllowMultiIntfInstantiations.Yes, m, ty) |> List.collect (fun ty -> @@ -2081,7 +2081,7 @@ let TryFindAnonRecdFieldOfType g typ nm = | None -> None | ValueNone -> None -let CoreDisplayName(pinfo:PropInfo) = +let CoreDisplayName(pinfo: PropInfo) = match pinfo with | FSProp(_, _, _, Some set) -> set.CoreDisplayName | FSProp(_, _, Some get, _) -> get.CoreDisplayName @@ -2091,7 +2091,7 @@ let CoreDisplayName(pinfo:PropInfo) = | ProvidedProp(_, pi, m) -> pi.PUntaint((fun pi -> pi.Name), m) #endif -let DecodeFSharpEvent (pinfos:PropInfo list) ad g (ncenv:NameResolver) m = +let DecodeFSharpEvent (pinfos: PropInfo list) ad g (ncenv: NameResolver) m = match pinfos with | [pinfo] when pinfo.IsFSharpEventProperty -> let nm = CoreDisplayName(pinfo) @@ -2122,7 +2122,7 @@ let GetRecordLabelsForType g nenv ty = // REVIEW: this shows up on performance logs. Consider for example endless resolutions of "List.map" to // the empty set of results, or "x.Length" for a list or array type. This indicates it could be worth adding a cache here. -let rec ResolveLongIdentInTypePrim (ncenv:NameResolver) nenv lookupKind (resInfo:ResolutionInfo) depth m ad (id:Ident) (rest:Ident list) findFlag (typeNameResInfo: TypeNameResolutionInfo) ty = +let rec ResolveLongIdentInTypePrim (ncenv: NameResolver) nenv lookupKind (resInfo: ResolutionInfo) depth m ad (id: Ident) (rest: Ident list) findFlag (typeNameResInfo: TypeNameResolutionInfo) ty = let g = ncenv.g let m = unionRanges m id.idRange let nm = id.idText // used to filter the searches of the tables @@ -2254,7 +2254,7 @@ let rec ResolveLongIdentInTypePrim (ncenv:NameResolver) nenv lookupKind (resInfo raze (UndefinedName (depth, FSComp.SR.undefinedNameFieldConstructorOrMember, id, suggestMembers)) -and ResolveLongIdentInNestedTypes (ncenv:NameResolver) nenv lookupKind resInfo depth id m ad (id2:Ident) (rest:Ident list) findFlag typeNameResInfo tys = +and ResolveLongIdentInNestedTypes (ncenv: NameResolver) nenv lookupKind resInfo depth id m ad (id2: Ident) (rest: Ident list) findFlag typeNameResInfo tys = tys |> CollectAtMostOneResult (fun ty -> let resInfo = if isAppTy ncenv.g ty then resInfo.AddEntity(id.idRange, tcrefOfAppTy ncenv.g ty) else resInfo @@ -2264,14 +2264,14 @@ and ResolveLongIdentInNestedTypes (ncenv:NameResolver) nenv lookupKind resInfo d /// Resolve a long identifier using type-qualified name resolution. let ResolveLongIdentInType sink ncenv nenv lookupKind m ad id findFlag typeNameResInfo ty = let resInfo, item, rest = - ResolveLongIdentInTypePrim (ncenv:NameResolver) nenv lookupKind ResolutionInfo.Empty 0 m ad id [] findFlag typeNameResInfo ty + ResolveLongIdentInTypePrim (ncenv: NameResolver) nenv lookupKind ResolutionInfo.Empty 0 m ad id [] findFlag typeNameResInfo ty |> AtMostOneResult m |> ForceRaise ResolutionInfo.SendEntityPathToSink (sink, ncenv, nenv, ItemOccurence.UseInType, ad, resInfo, ResultTyparChecker(fun () -> CheckAllTyparsInferrable ncenv.amap m item)) item, rest -let private ResolveLongIdentInTyconRef (ncenv:NameResolver) nenv lookupKind resInfo depth m ad id rest typeNameResInfo tcref = +let private ResolveLongIdentInTyconRef (ncenv: NameResolver) nenv lookupKind resInfo depth m ad id rest typeNameResInfo tcref = #if !NO_EXTENSIONTYPING // No dotting through type generators to get to a member! CheckForDirectReferenceToGeneratedType (tcref, PermitDirectReferenceToGeneratedType.No, m) @@ -2279,8 +2279,8 @@ let private ResolveLongIdentInTyconRef (ncenv:NameResolver) nenv lookupKind resI let ty = FreshenTycon ncenv m tcref ty |> ResolveLongIdentInTypePrim ncenv nenv lookupKind resInfo depth m ad id rest IgnoreOverrides typeNameResInfo -let private ResolveLongIdentInTyconRefs atMostOne (ncenv:NameResolver) nenv lookupKind depth m ad id rest typeNameResInfo idRange tcrefs = - tcrefs |> CollectResults2 atMostOne (fun (resInfo:ResolutionInfo, tcref) -> +let private ResolveLongIdentInTyconRefs atMostOne (ncenv: NameResolver) nenv lookupKind depth m ad id rest typeNameResInfo idRange tcrefs = + tcrefs |> CollectResults2 atMostOne (fun (resInfo: ResolutionInfo, tcref) -> let resInfo = resInfo.AddEntity(idRange, tcref) tcref |> ResolveLongIdentInTyconRef ncenv nenv lookupKind resInfo depth m ad id rest typeNameResInfo |> AtMostOneResult m) @@ -2292,7 +2292,7 @@ let (|AccessibleEntityRef|_|) amap m ad (modref: ModuleOrNamespaceRef) mspec = let eref = modref.NestedTyconRef mspec if IsEntityAccessible amap m ad eref then Some eref else None -let rec ResolveExprLongIdentInModuleOrNamespace (ncenv:NameResolver) nenv (typeNameResInfo: TypeNameResolutionInfo) ad resInfo depth m modref (mty:ModuleOrNamespaceType) (id:Ident) (rest :Ident list) = +let rec ResolveExprLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv (typeNameResInfo: TypeNameResolutionInfo) ad resInfo depth m modref (mty: ModuleOrNamespaceType) (id: Ident) (rest: Ident list) = // resInfo records the modules or namespaces actually relevant to a resolution let m = unionRanges m id.idRange match mty.AllValsByLogicalName.TryGetValue id.idText with @@ -2407,7 +2407,7 @@ let rec ResolveExprLongIdentInModuleOrNamespace (ncenv:NameResolver) nenv (typeN /// An identifier has resolved to a type name in an expression (corresponding to one or more TyconRefs). /// Return either a set of constructors (later refined by overload resolution), or a set of TyconRefs. -let ChooseTyconRefInExpr (ncenv:NameResolver, m, ad, nenv, id:Ident, typeNameResInfo:TypeNameResolutionInfo, resInfo:ResolutionInfo, tcrefs) = +let ChooseTyconRefInExpr (ncenv: NameResolver, m, ad, nenv, id: Ident, typeNameResInfo: TypeNameResolutionInfo, resInfo: ResolutionInfo, tcrefs) = let tcrefs = tcrefs |> List.map (fun tcref -> (resInfo, tcref)) let tcrefs = CheckForTypeLegitimacyAndMultipleGenericTypeAmbiguities (tcrefs, typeNameResInfo, PermitDirectReferenceToGeneratedType.No, m) match typeNameResInfo.ResolutionFlag with @@ -2423,7 +2423,7 @@ let ChooseTyconRefInExpr (ncenv:NameResolver, m, ad, nenv, id:Ident, typeNameRes /// Resolve F# "A.B.C" syntax in expressions /// Not all of the sequence will necessarily be swallowed, i.e. we return some identifiers /// that may represent further actions, e.g. further lookups. -let rec ResolveExprLongIdentPrim sink (ncenv:NameResolver) first fullyQualified m ad nenv (typeNameResInfo:TypeNameResolutionInfo) (id:Ident) (rest:Ident list) isOpenDecl = +let rec ResolveExprLongIdentPrim sink (ncenv: NameResolver) first fullyQualified m ad nenv (typeNameResInfo: TypeNameResolutionInfo) (id: Ident) (rest: Ident list) isOpenDecl = let resInfo = ResolutionInfo.Empty if first && id.idText = MangledGlobalName then match rest with @@ -2624,7 +2624,7 @@ let rec ResolveExprLongIdentPrim sink (ncenv:NameResolver) first fullyQualified ResolutionInfo.SendEntityPathToSink(sink, ncenv, nenv, ItemOccurence.Use, ad, resInfo, ResultTyparChecker(fun () -> CheckAllTyparsInferrable ncenv.amap m item)) item, rest -let ResolveExprLongIdent sink (ncenv:NameResolver) m ad nenv typeNameResInfo lid = +let ResolveExprLongIdent sink (ncenv: NameResolver) m ad nenv typeNameResInfo lid = match lid with | [] -> error (Error(FSComp.SR.nrInvalidExpression(textOfLid lid), m)) | id::rest -> ResolveExprLongIdentPrim sink ncenv true OpenQualified m ad nenv typeNameResInfo id rest false @@ -2633,7 +2633,7 @@ let ResolveExprLongIdent sink (ncenv:NameResolver) m ad nenv typeNameResInfo lid // Resolve F#/IL "." syntax in patterns //------------------------------------------------------------------------- -let rec ResolvePatternLongIdentInModuleOrNamespace (ncenv:NameResolver) nenv numTyArgsOpt ad resInfo depth m modref (mty:ModuleOrNamespaceType) (id:Ident) (rest: Ident list) = +let rec ResolvePatternLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv numTyArgsOpt ad resInfo depth m modref (mty: ModuleOrNamespaceType) (id: Ident) (rest: Ident list) = let m = unionRanges m id.idRange match TryFindTypeWithUnionCase modref id with | Some tycon when IsTyconReprAccessible ncenv.amap m ad (modref.NestedTyconRef tycon) -> @@ -2665,7 +2665,7 @@ let rec ResolvePatternLongIdentInModuleOrNamespace (ncenv:NameResolver) nenv num match rest with | id2::rest2 -> let tcrefs = tcrefs.Force() - ResolveLongIdentInTyconRefs ResultCollectionSettings.AtMostOneResult (ncenv:NameResolver) nenv LookupKind.Pattern (depth+1) m ad id2 rest2 numTyArgsOpt id.idRange tcrefs + ResolveLongIdentInTyconRefs ResultCollectionSettings.AtMostOneResult (ncenv: NameResolver) nenv LookupKind.Pattern (depth+1) m ad id2 rest2 numTyArgsOpt id.idRange tcrefs | _ -> NoResultsOrUsefulErrors @@ -2718,7 +2718,7 @@ exception UpperCaseIdentifierInPattern of range type WarnOnUpperFlag = WarnOnUpperCase | AllIdsOK // Long ID in a pattern -let rec ResolvePatternLongIdentPrim sink (ncenv:NameResolver) fullyQualified warnOnUpper newDef m ad nenv numTyArgsOpt (id:Ident) (rest:Ident list) = +let rec ResolvePatternLongIdentPrim sink (ncenv: NameResolver) fullyQualified warnOnUpper newDef m ad nenv numTyArgsOpt (id: Ident) (rest: Ident list) = if id.idText = MangledGlobalName then match rest with | [] -> @@ -2774,7 +2774,7 @@ let rec ResolvePatternLongIdentPrim sink (ncenv:NameResolver) fullyQualified war | element :: _ -> error(Error(FSComp.SR.nrIsNotConstructorOrLiteral(), element.idRange)) /// Resolve a long identifier when used in a pattern. -let ResolvePatternLongIdent sink (ncenv:NameResolver) warnOnUpper newDef m ad nenv numTyArgsOpt (lid:Ident list) = +let ResolvePatternLongIdent sink (ncenv: NameResolver) warnOnUpper newDef m ad nenv numTyArgsOpt (lid: Ident list) = match lid with | [] -> error(Error(FSComp.SR.nrUnexpectedEmptyLongId(), m)) | id::rest -> ResolvePatternLongIdentPrim sink ncenv OpenQualified warnOnUpper newDef m ad nenv numTyArgsOpt id rest @@ -2790,14 +2790,14 @@ let ResolvePatternLongIdent sink (ncenv:NameResolver) warnOnUpper newDef m ad ne // // X.ListEnumerator // does not resolve // -let ResolveNestedTypeThroughAbbreviation (ncenv:NameResolver) (tcref: TyconRef) m = +let ResolveNestedTypeThroughAbbreviation (ncenv: NameResolver) (tcref: TyconRef) m = if tcref.IsTypeAbbrev && tcref.Typars(m).IsEmpty && isAppTy ncenv.g tcref.TypeAbbrev.Value && isNil (argsOfAppTy ncenv.g tcref.TypeAbbrev.Value) then tcrefOfAppTy ncenv.g tcref.TypeAbbrev.Value else tcref /// Resolve a long identifier representing a type name -let rec ResolveTypeLongIdentInTyconRefPrim (ncenv:NameResolver) (typeNameResInfo:TypeNameResolutionInfo) ad resInfo genOk depth m (tcref: TyconRef) (id:Ident) (rest: Ident list) = +let rec ResolveTypeLongIdentInTyconRefPrim (ncenv: NameResolver) (typeNameResInfo: TypeNameResolutionInfo) ad resInfo genOk depth m (tcref: TyconRef) (id: Ident) (rest: Ident list) = let tcref = ResolveNestedTypeThroughAbbreviation ncenv tcref m match rest with | [] -> @@ -2843,7 +2843,7 @@ let rec ResolveTypeLongIdentInTyconRefPrim (ncenv:NameResolver) (typeNameResInfo AtMostOneResult m tyconSearch /// Resolve a long identifier representing a type name and report the result -let ResolveTypeLongIdentInTyconRef sink (ncenv:NameResolver) nenv typeNameResInfo ad m tcref (lid: Ident list) = +let ResolveTypeLongIdentInTyconRef sink (ncenv: NameResolver) nenv typeNameResInfo ad m tcref (lid: Ident list) = let resInfo, tcref = match lid with | [] -> @@ -2856,7 +2856,7 @@ let ResolveTypeLongIdentInTyconRef sink (ncenv:NameResolver) nenv typeNameResInf tcref /// Create an UndefinedName error with details -let SuggestTypeLongIdentInModuleOrNamespace depth (modref:ModuleOrNamespaceRef) amap ad m (id:Ident) = +let SuggestTypeLongIdentInModuleOrNamespace depth (modref: ModuleOrNamespaceRef) amap ad m (id: Ident) = let suggestPossibleTypes() = modref.ModuleOrNamespaceType.AllEntities |> Seq.filter (fun e -> IsEntityAccessible amap m ad (modref.NestedTyconRef e)) @@ -2867,7 +2867,7 @@ let SuggestTypeLongIdentInModuleOrNamespace depth (modref:ModuleOrNamespaceRef) UndefinedName(depth, errorTextF, id, suggestPossibleTypes) /// Resolve a long identifier representing a type in a module or namespace -let rec private ResolveTypeLongIdentInModuleOrNamespace sink nenv (ncenv:NameResolver) (typeNameResInfo: TypeNameResolutionInfo) ad genOk (resInfo:ResolutionInfo) depth m modref _mty (id:Ident) (rest: Ident list) = +let rec private ResolveTypeLongIdentInModuleOrNamespace sink nenv (ncenv: NameResolver) (typeNameResInfo: TypeNameResolutionInfo) ad genOk (resInfo: ResolutionInfo) depth m modref _mty (id: Ident) (rest: Ident list) = match rest with | [] -> // On all paths except error reporting we have isSome(staticResInfo), hence get at most one result back @@ -2907,7 +2907,7 @@ let rec private ResolveTypeLongIdentInModuleOrNamespace sink nenv (ncenv:NameRes AddResults tyconSearch modulSearch /// Resolve a long identifier representing a type -let rec ResolveTypeLongIdentPrim sink (ncenv:NameResolver) occurence first fullyQualified m nenv ad (id:Ident) (rest: Ident list) (staticResInfo: TypeNameResolutionStaticArgsInfo) genOk = +let rec ResolveTypeLongIdentPrim sink (ncenv: NameResolver) occurence first fullyQualified m nenv ad (id: Ident) (rest: Ident list) (staticResInfo: TypeNameResolutionStaticArgsInfo) genOk = let typeNameResInfo = TypeNameResolutionInfo.ResolveToTypeRefs staticResInfo if first && id.idText = MangledGlobalName then match rest with @@ -2992,7 +2992,7 @@ let rec ResolveTypeLongIdentPrim sink (ncenv:NameResolver) occurence first fully /// Resolve a long identifier representing a type and report it -let ResolveTypeLongIdent sink (ncenv:NameResolver) occurence fullyQualified nenv ad (lid: Ident list) staticResInfo genOk = +let ResolveTypeLongIdent sink (ncenv: NameResolver) occurence fullyQualified nenv ad (lid: Ident list) staticResInfo genOk = let m = rangeOfLid lid let res = match lid with @@ -3015,7 +3015,7 @@ let ResolveTypeLongIdent sink (ncenv:NameResolver) occurence fullyQualified nenv //------------------------------------------------------------------------- /// Resolve a long identifier representing a record field in a module or namespace -let rec ResolveFieldInModuleOrNamespace (ncenv:NameResolver) nenv ad (resInfo:ResolutionInfo) depth m (modref: ModuleOrNamespaceRef) _mty (id:Ident) (rest: Ident list) = +let rec ResolveFieldInModuleOrNamespace (ncenv: NameResolver) nenv ad (resInfo: ResolutionInfo) depth m (modref: ModuleOrNamespaceRef) _mty (id: Ident) (rest: Ident list) = let typeNameResInfo = TypeNameResolutionInfo.Default let m = unionRanges m id.idRange // search for module-qualified names, e.g. { Microsoft.FSharp.Core.contents = 1 } @@ -3056,7 +3056,7 @@ let rec ResolveFieldInModuleOrNamespace (ncenv:NameResolver) nenv ad (resInfo:Re |> AtMostOneResult m /// Suggest other labels of the same record -let SuggestOtherLabelsOfSameRecordType g (nenv:NameResolutionEnv) ty (id:Ident) (allFields:Ident list) = +let SuggestOtherLabelsOfSameRecordType g (nenv: NameResolutionEnv) ty (id: Ident) (allFields: Ident list) = let labelsOfPossibleRecord = GetRecordLabelsForType g nenv ty let givenFields = @@ -3067,7 +3067,7 @@ let SuggestOtherLabelsOfSameRecordType g (nenv:NameResolutionEnv) ty (id:Ident) labelsOfPossibleRecord.ExceptWith givenFields labelsOfPossibleRecord -let SuggestLabelsOfRelatedRecords g (nenv:NameResolutionEnv) (id:Ident) (allFields:Ident list) = +let SuggestLabelsOfRelatedRecords g (nenv: NameResolutionEnv) (id: Ident) (allFields: Ident list) = let suggestLabels() = let givenFields = allFields |> List.map (fun fld -> fld.idText) |> List.filter ((<>) id.idText) |> HashSet let fullyQualfied = @@ -3119,7 +3119,7 @@ let SuggestLabelsOfRelatedRecords g (nenv:NameResolutionEnv) (id:Ident) (allFiel UndefinedName(0, FSComp.SR.undefinedNameRecordLabel, id, suggestLabels) /// Resolve a long identifier representing a record field -let ResolveFieldPrim sink (ncenv:NameResolver) nenv ad ty (mp, id:Ident) allFields = +let ResolveFieldPrim sink (ncenv: NameResolver) nenv ad ty (mp, id: Ident) allFields = let typeNameResInfo = TypeNameResolutionInfo.Default let g = ncenv.g let m = id.idRange @@ -3194,7 +3194,7 @@ let ResolveField sink ncenv nenv ad ty (mp, id) allFields = rfref) /// Generate a new reference to a record field with a fresh type instantiation -let FreshenRecdFieldRef (ncenv:NameResolver) m (rfref:RecdFieldRef) = +let FreshenRecdFieldRef (ncenv: NameResolver) m (rfref: RecdFieldRef) = Item.RecdField(RecdFieldInfo(ncenv.InstantiationGenerator m (rfref.Tycon.Typars m), rfref)) @@ -3207,7 +3207,7 @@ let FreshenRecdFieldRef (ncenv:NameResolver) m (rfref:RecdFieldRef) = /// determine any valid members // // QUERY (instantiationGenerator cleanup): it would be really nice not to flow instantiationGenerator to here. -let private ResolveExprDotLongIdent (ncenv:NameResolver) m ad nenv ty (id:Ident) rest findFlag = +let private ResolveExprDotLongIdent (ncenv: NameResolver) m ad nenv ty (id: Ident) rest findFlag = let typeNameResInfo = TypeNameResolutionInfo.Default let adhoctDotSearchAccessible = AtMostOneResult m (ResolveLongIdentInTypePrim ncenv nenv LookupKind.Expr ResolutionInfo.Empty 1 m ad id rest findFlag typeNameResInfo ty) match adhoctDotSearchAccessible with @@ -3247,7 +3247,7 @@ let ComputeItemRange wholem (lid: Ident list) rest = /// Filters method groups that will be sent to Visual Studio IntelliSense /// to include only static/instance members -let FilterMethodGroups (ncenv:NameResolver) itemRange item staticOnly = +let FilterMethodGroups (ncenv: NameResolver) itemRange item staticOnly = match item with | Item.MethodGroup(nm, minfos, orig) -> let minfos = minfos |> List.filter (fun minfo -> @@ -3279,7 +3279,7 @@ type AfterResolution = /// Resolve a long identifier occurring in an expression position. /// /// Called for 'TypeName.Bar' - for VS IntelliSense, we can filter out instance members from method groups -let ResolveLongIdentAsExprAndComputeRange (sink:TcResultsSink) (ncenv:NameResolver) wholem ad nenv typeNameResInfo lid = +let ResolveLongIdentAsExprAndComputeRange (sink: TcResultsSink) (ncenv: NameResolver) wholem ad nenv typeNameResInfo lid = let item1, rest = ResolveExprLongIdent sink ncenv wholem ad nenv typeNameResInfo lid let itemRange = ComputeItemRange wholem lid rest @@ -3340,7 +3340,7 @@ let (|NonOverridable|_|) namedItem = /// Called for 'expression.Bar' - for VS IntelliSense, we can filter out static members from method groups /// Also called for 'GenericType.Bar' - for VS IntelliSense, we can filter out non-static members from method groups -let ResolveExprDotLongIdentAndComputeRange (sink:TcResultsSink) (ncenv:NameResolver) wholem ad nenv ty lid findFlag thisIsActuallyATyAppNotAnExpr = +let ResolveExprDotLongIdentAndComputeRange (sink: TcResultsSink) (ncenv: NameResolver) wholem ad nenv ty lid findFlag thisIsActuallyATyAppNotAnExpr = let resolveExpr findFlag = let resInfo, item, rest = match lid with @@ -3408,13 +3408,13 @@ let ResolveExprDotLongIdentAndComputeRange (sink:TcResultsSink) (ncenv:NameResol //------------------------------------------------------------------------- /// A generator of type instantiations used when no more specific type instantiation is known. -let FakeInstantiationGenerator (_m:range) gps = List.map mkTyparTy gps +let FakeInstantiationGenerator (_m: range) gps = List.map mkTyparTy gps // note: using local refs is ok since it is only used by VS let ItemForModuleOrNamespaceRef v = Item.ModuleOrNamespaces [v] -let ItemForPropInfo (pinfo:PropInfo) = Item.Property (pinfo.PropertyName, [pinfo]) +let ItemForPropInfo (pinfo: PropInfo) = Item.Property (pinfo.PropertyName, [pinfo]) -let IsTyconUnseenObsoleteSpec ad g amap m (x:TyconRef) allowObsolete = +let IsTyconUnseenObsoleteSpec ad g amap m (x: TyconRef) allowObsolete = not (IsEntityAccessible amap m ad x) || ((not allowObsolete) && (if x.IsILTycon then @@ -3422,15 +3422,15 @@ let IsTyconUnseenObsoleteSpec ad g amap m (x:TyconRef) allowObsolete = else CheckFSharpAttributesForUnseen g x.Attribs m)) -let IsTyconUnseen ad g amap m (x:TyconRef) = IsTyconUnseenObsoleteSpec ad g amap m x false +let IsTyconUnseen ad g amap m (x: TyconRef) = IsTyconUnseenObsoleteSpec ad g amap m x false -let IsValUnseen ad g m (v:ValRef) = +let IsValUnseen ad g m (v: ValRef) = v.IsCompilerGenerated || v.Deref.IsClassConstructor || not (IsValAccessible ad v) || CheckFSharpAttributesForUnseen g v.Attribs m -let IsUnionCaseUnseen ad g amap m (ucref:UnionCaseRef) = +let IsUnionCaseUnseen ad g amap m (ucref: UnionCaseRef) = not (IsUnionCaseAccessible amap m ad ucref) || IsTyconUnseen ad g amap m ucref.TyconRef || CheckFSharpAttributesForUnseen g ucref.Attribs m @@ -3442,7 +3442,7 @@ let ItemIsUnseen ad g amap m item = | Item.ExnCase x -> IsTyconUnseen ad g amap m x | _ -> false -let ItemOfTyconRef ncenv m (x:TyconRef) = +let ItemOfTyconRef ncenv m (x: TyconRef) = Item.Types (x.DisplayName, [FreshenTycon ncenv m x]) let ItemOfTy g x = @@ -3452,7 +3452,7 @@ let ItemOfTy g x = // Filter out 'PrivateImplementationDetail' classes let IsInterestingModuleName nm = not (System.String.IsNullOrEmpty nm) && nm.[0] <> '<' -let rec PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThen f plid (modref:ModuleOrNamespaceRef) = +let rec PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThen f plid (modref: ModuleOrNamespaceRef) = let mty = modref.ModuleOrNamespaceType match plid with | [] -> f modref @@ -3461,7 +3461,7 @@ let rec PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThen f plid (m | true, mty -> PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThen f rest (modref.NestedTyconRef mty) | _ -> [] -let PartialResolveLongIndentAsModuleOrNamespaceThen (nenv:NameResolutionEnv) plid f = +let PartialResolveLongIndentAsModuleOrNamespaceThen (nenv: NameResolutionEnv) plid f = match plid with | id:: rest -> match nenv.eModulesAndNamespaces.TryGetValue id with @@ -3559,7 +3559,7 @@ let ResolveCompletionsInType (ncenv: NameResolver) nenv (completionTargets: Reso pinfosIncludingUnseen |> List.filter (fun x -> not (PropInfoIsUnseen m x)) - let minfoFilter (suppressedMethNames:Zset<_>) (minfo:MethInfo) = + let minfoFilter (suppressedMethNames: Zset<_>) (minfo: MethInfo) = let isApplicableMeth = match completionTargets with | ResolveCompletionTargets.All x -> x @@ -3670,7 +3670,7 @@ let ResolveCompletionsInType (ncenv: NameResolver) nenv (completionTargets: Reso [] // Partition methods into overload sets - let rec partitionl (l:MethInfo list) acc = + let rec partitionl (l: MethInfo list) acc = match l with | [] -> acc | h::t -> @@ -3716,7 +3716,7 @@ let rec ResolvePartialLongIdentInType (ncenv: NameResolver) nenv isApplicableMet (rfinfos |> List.collect (fun x -> x.FieldType |> ResolvePartialLongIdentInType ncenv nenv isApplicableMeth m ad false rest)) @ // e.g. .. - let FullTypeOfPinfo(pinfo:PropInfo) = + let FullTypeOfPinfo(pinfo: PropInfo) = let rty = pinfo.GetPropertyType(amap, m) let rty = if pinfo.IsIndexer then mkRefTupledTy g (pinfo.GetParamTypes(amap, m)) --> rty else rty rty @@ -3748,7 +3748,7 @@ let rec ResolvePartialLongIdentInType (ncenv: NameResolver) nenv isApplicableMet IsILFieldInfoAccessible g amap m ad x) |> List.collect (fun x -> x.FieldType(amap, m) |> ResolvePartialLongIdentInType ncenv nenv isApplicableMeth m ad false rest)) -let InfosForTyconConstructors (ncenv:NameResolver) m ad (tcref:TyconRef) = +let InfosForTyconConstructors (ncenv: NameResolver) m ad (tcref: TyconRef) = let g = ncenv.g let amap = ncenv.amap // Don't show constructors for type abbreviations. See FSharp 1.0 bug 2881 @@ -3775,7 +3775,7 @@ let InfosForTyconConstructors (ncenv:NameResolver) m ad (tcref:TyconRef) = /// import.fs creates somewhat fake modules for nested members of types (so that /// types never contain other types) -let inline notFakeContainerModule (tyconNames:HashSet<_>) nm = +let inline notFakeContainerModule (tyconNames: HashSet<_>) nm = not (tyconNames.Contains nm) let getFakeContainerModulesFromTycons (tycons:#seq) = @@ -3793,7 +3793,7 @@ let getFakeContainerModulesFromTyconRefs (tyconRefs:#seq) = hashSet /// Check is a namespace or module contains something accessible -let rec private EntityRefContainsSomethingAccessible (ncenv: NameResolver) m ad (modref:ModuleOrNamespaceRef) = +let rec private EntityRefContainsSomethingAccessible (ncenv: NameResolver) m ad (modref: ModuleOrNamespaceRef) = let g = ncenv.g let mty = modref.ModuleOrNamespaceType @@ -3827,7 +3827,7 @@ let rec private EntityRefContainsSomethingAccessible (ncenv: NameResolver) m ad let submodref = modref.NestedTyconRef submod EntityRefContainsSomethingAccessible ncenv m ad submodref)) -let rec ResolvePartialLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv isApplicableMeth m ad (modref:ModuleOrNamespaceRef) plid allowObsolete = +let rec ResolvePartialLongIdentInModuleOrNamespace (ncenv: NameResolver) nenv isApplicableMeth m ad (modref: ModuleOrNamespaceRef) plid allowObsolete = let g = ncenv.g let mty = modref.ModuleOrNamespaceType @@ -3920,7 +3920,7 @@ let TryToResolveLongIdentAsType (ncenv: NameResolver) (nenv: NameResolutionEnv) // Look for values called 'id' that accept the dot-notation let ty = match nenv.eUnqualifiedItems.TryGetValue id with - // v.lookup : member of a value + // v.lookup: member of a value | true, v -> match v with | Item.Value x -> @@ -3933,7 +3933,7 @@ let TryToResolveLongIdentAsType (ncenv: NameResolver) (nenv: NameResolutionEnv) match ty with | Some _ -> ty | _ -> - // type.lookup : lookup a static something in a type + // type.lookup: lookup a static something in a type LookupTypeNameInEnvNoArity OpenQualified id nenv |> List.tryHead |> Option.map (fun tcref -> @@ -3943,7 +3943,7 @@ let TryToResolveLongIdentAsType (ncenv: NameResolver) (nenv: NameResolutionEnv) /// allowObsolete - specifies whether we should return obsolete types & modules /// as (no other obsolete items are returned) -let rec ResolvePartialLongIdentPrim (ncenv: NameResolver) (nenv: NameResolutionEnv) isApplicableMeth fullyQualified m ad plid allowObsolete : Item list = +let rec ResolvePartialLongIdentPrim (ncenv: NameResolver) (nenv: NameResolutionEnv) isApplicableMeth fullyQualified m ad plid allowObsolete: Item list = let g = ncenv.g match plid with @@ -4019,7 +4019,7 @@ let rec ResolvePartialLongIdentPrim (ncenv: NameResolver) (nenv: NameResolutionE // Look for values called 'id' that accept the dot-notation let values, isItemVal = (match nenv.eUnqualifiedItems.TryGetValue id with - // v.lookup : member of a value + // v.lookup: member of a value | true, v -> match v with | Item.Value x -> @@ -4031,7 +4031,7 @@ let rec ResolvePartialLongIdentPrim (ncenv: NameResolver) (nenv: NameResolutionE let staticSometingInType = [ if not isItemVal then - // type.lookup : lookup a static something in a type + // type.lookup: lookup a static something in a type for tcref in LookupTypeNameInEnvNoArity OpenQualified id nenv do let tcref = ResolveNestedTypeThroughAbbreviation ncenv tcref m let ty = FreshenTycon ncenv m tcref @@ -4044,7 +4044,7 @@ let ResolvePartialLongIdent ncenv nenv isApplicableMeth m ad plid allowObsolete ResolvePartialLongIdentPrim ncenv nenv (ResolveCompletionTargets.All isApplicableMeth) OpenQualified m ad plid allowObsolete // REVIEW: has much in common with ResolvePartialLongIdentInModuleOrNamespace - probably they should be united -let rec ResolvePartialLongIdentInModuleOrNamespaceForRecordFields (ncenv: NameResolver) nenv m ad (modref:ModuleOrNamespaceRef) plid allowObsolete = +let rec ResolvePartialLongIdentInModuleOrNamespaceForRecordFields (ncenv: NameResolver) nenv m ad (modref: ModuleOrNamespaceRef) plid allowObsolete = let g = ncenv.g let mty = modref.ModuleOrNamespaceType @@ -4117,7 +4117,7 @@ let rec ResolvePartialLongIdentInModuleOrNamespaceForRecordFields (ncenv: NameRe /// allowObsolete - specifies whether we should return obsolete types & modules /// as (no other obsolete items are returned) -let rec ResolvePartialLongIdentToClassOrRecdFields (ncenv: NameResolver) (nenv: NameResolutionEnv) m ad plid (allowObsolete : bool) = +let rec ResolvePartialLongIdentToClassOrRecdFields (ncenv: NameResolver) (nenv: NameResolutionEnv) m ad plid (allowObsolete: bool) = ResolvePartialLongIdentToClassOrRecdFieldsImpl ncenv nenv OpenQualified m ad plid allowObsolete and ResolvePartialLongIdentToClassOrRecdFieldsImpl (ncenv: NameResolver) (nenv: NameResolutionEnv) fullyQualified m ad plid allowObsolete = @@ -4271,7 +4271,7 @@ let ResolveCompletionsInTypeForItem (ncenv: NameResolver) nenv m ad statics ty ( pinfosIncludingUnseen |> List.filter (fun x -> not (PropInfoIsUnseen m x)) - let minfoFilter (suppressedMethNames:Zset<_>) (minfo: MethInfo) = + let minfoFilter (suppressedMethNames: Zset<_>) (minfo: MethInfo) = // Only show the Finalize, MemberwiseClose etc. methods on System.Object for values whose static type really is // System.Object. Few of these are typically used from F#. // @@ -4367,7 +4367,7 @@ let ResolveCompletionsInTypeForItem (ncenv: NameResolver) nenv m ad statics ty ( minfos // Partition methods into overload sets - let rec partitionl (l:MethInfo list) acc = + let rec partitionl (l: MethInfo list) acc = match l with | [] -> acc | h::t -> @@ -4527,7 +4527,7 @@ let rec PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThenLazy f pli PartialResolveLookupInModuleOrNamespaceAsModuleOrNamespaceThenLazy f rest (modref.NestedTyconRef mty) | _ -> Seq.empty -let PartialResolveLongIndentAsModuleOrNamespaceThenLazy (nenv:NameResolutionEnv) plid f = +let PartialResolveLongIndentAsModuleOrNamespaceThenLazy (nenv: NameResolutionEnv) plid f = seq { match plid with | id :: rest -> @@ -4614,7 +4614,7 @@ let rec GetCompletionForItem (ncenv: NameResolver) (nenv: NameResolutionEnv) m a let ty = if x.BaseOrThisInfo = CtorThisVal && isRefCellTy g ty then destRefCellTy g ty else ty yield! ResolvePartialLongIdentInTypeForItem ncenv nenv m ad false rest item ty | _ -> - // type.lookup : lookup a static something in a type + // type.lookup: lookup a static something in a type for tcref in LookupTypeNameInEnvNoArity OpenQualified id nenv do let tcref = ResolveNestedTypeThroughAbbreviation ncenv tcref m let ty = FreshenTycon ncenv m tcref diff --git a/src/fsharp/NicePrint.fs b/src/fsharp/NicePrint.fs index 5cd213918c4..fdd35321e45 100755 --- a/src/fsharp/NicePrint.fs +++ b/src/fsharp/NicePrint.fs @@ -63,7 +63,7 @@ module internal PrintUtilities = | (x:: rest) -> [ resultFunction x (layoutFunction x -- leftL (tagText (match rest.Length with 1 -> FSComp.SR.nicePrintOtherOverloads1() | n -> FSComp.SR.nicePrintOtherOverloadsN(n)))) ] | _ -> [] - let layoutTyconRefImpl isAttribute (denv: DisplayEnv) (tcref:TyconRef) = + let layoutTyconRefImpl isAttribute (denv: DisplayEnv) (tcref: TyconRef) = let demangled = let name = if denv.includeStaticParametersInTypeNames then @@ -90,7 +90,7 @@ module internal PrintUtilities = else path |> List.map (fun s -> let i = s.IndexOf(',') - if i <> -1 then s.Substring(0,i)+"<...>" // apparently has static params, shorten + if i <> -1 then s.Substring(0, i)+"<...>" // apparently has static params, shorten else s) let pathText = trimPathByDisplayEnv denv path if pathText = "" then tyconTextL else leftL (tagUnknownEntity pathText) ^^ tyconTextL @@ -101,7 +101,7 @@ module internal PrintUtilities = module private PrintIL = - let fullySplitILTypeRef (tref:ILTypeRef) = + let fullySplitILTypeRef (tref: ILTypeRef) = (List.collect IL.splitNamespace (tref.Enclosing @ [PrettyNaming.DemangleGenericTypeName tref.Name])) let layoutILTypeRefName denv path = @@ -126,7 +126,7 @@ module private PrintIL = | [ "System"; "UIntPtr" ] -> ["unativeint" ] | [ "System"; "Boolean"] -> ["bool"] | _ -> path - let p2,n = List.frontAndBack path + let p2, n = List.frontAndBack path let tagged = if n = "obj" || n = "string" then tagClass n else tagStruct n if denv.shortTypeNames then wordL tagged @@ -217,9 +217,9 @@ module private PrintIL = // Layout an unnamed argument | _, None, _ -> LeftL.colon // Layout a named argument - | true, Some nm,_ -> + | true, Some nm, _ -> layoutBuiltinAttribute denv denv.g.attrib_ParamArrayAttribute ^^ wordL (tagParameter nm) ^^ SepL.colon - | false, Some nm,_ -> leftL (tagParameter nm) ^^ SepL.colon + | false, Some nm, _ -> leftL (tagParameter nm) ^^ SepL.colon preL ^^ (layoutILType denv ilTyparSubst p.Type) @@ -285,13 +285,13 @@ module private PrintIL = let name = adjustILName p.Name let nameL = wordL (tagProperty name) - let layoutGetterType (getterRef:ILMethodRef) = + let layoutGetterType (getterRef: ILMethodRef) = if isNil getterRef.ArgTypes then layoutILType denv ilTyparSubst getterRef.ReturnType else layoutILCallingSignature denv ilTyparSubst None getterRef.CallingSignature - let layoutSetterType (setterRef:ILMethodRef) = + let layoutSetterType (setterRef: ILMethodRef) = let argTypes = setterRef.ArgTypes if isNil argTypes then emptyL // shouldn't happen @@ -308,7 +308,7 @@ module private PrintIL = let specGetSetL = match p.GetMethod, p.SetMethod with - | None,None + | None, None | Some _, None -> emptyL | None, Some _ -> WordL.keywordWith ^^ WordL.keywordSet | Some _, Some _ -> WordL.keywordWith ^^ WordL.keywordGet ^^ RightL.comma ^^ WordL.keywordSet @@ -359,7 +359,7 @@ module private PrintIL = // filtering methods for hiding things we oughtn't show let isStaticILProperty (p: ILPropertyDef) = - match p.GetMethod,p.SetMethod with + match p.GetMethod, p.SetMethod with | Some getter, _ -> getter.CallingSignature.CallingConv.IsStatic | None, Some setter -> setter.CallingSignature.CallingConv.IsStatic | None, None -> true @@ -441,7 +441,7 @@ module private PrintIL = if isShowBase baseName then yield WordL.keywordInherit ^^ baseName ] - let memberBlockLs (fieldDefs:ILFieldDefs, methodDefs:ILMethodDefs, propertyDefs:ILPropertyDefs, eventDefs:ILEventDefs) = + let memberBlockLs (fieldDefs: ILFieldDefs, methodDefs: ILMethodDefs, propertyDefs: ILPropertyDefs, eventDefs: ILEventDefs) = let ctors = methodDefs.AsList |> List.filter isPublicILCtor @@ -470,7 +470,7 @@ module private PrintIL = |> List.map (fun md -> (md.Name, md.Parameters.Length), md) // collect into overload groups |> List.groupBy (fst >> fst) - |> List.collect (fun (_,group) -> group |> List.sortBy fst |> shrinkOverloads (snd >> layoutILMethodDef denv ilTyparSubst typeDef.Name) (fun x xL -> (fst x,xL))) + |> List.collect (fun (_, group) -> group |> List.sortBy fst |> shrinkOverloads (snd >> layoutILMethodDef denv ilTyparSubst typeDef.Name) (fun x xL -> (fst x, xL))) let members = (props @ meths) @@ -553,12 +553,12 @@ module private PrintTypes = | Const.IntPtr x -> (x |> string)+"n" |> tagNumericLiteral | Const.UIntPtr x -> (x |> string)+"un" |> tagNumericLiteral | Const.Single d -> - ((let s = d.ToString("g12",System.Globalization.CultureInfo.InvariantCulture) + ((let s = d.ToString("g12", System.Globalization.CultureInfo.InvariantCulture) if String.forall (fun c -> System.Char.IsDigit(c) || c = '-') s then s + ".0" else s) + "f") |> tagNumericLiteral | Const.Double d -> - let s = d.ToString("g12",System.Globalization.CultureInfo.InvariantCulture) + let s = d.ToString("g12", System.Globalization.CultureInfo.InvariantCulture) (if String.forall (fun c -> System.Char.IsDigit(c) || c = '-') s then s + ".0" else s) |> tagNumericLiteral @@ -570,20 +570,20 @@ module private PrintTypes = | Const.Zero -> tagKeyword(if isRefTy g ty then "null" else "default") wordL str - let layoutAccessibility (denv:DisplayEnv) accessibility itemL = + let layoutAccessibility (denv: DisplayEnv) accessibility itemL = let isInternalCompPath x = match x with - | CompPath(ILScopeRef.Local,[]) -> true + | CompPath(ILScopeRef.Local, []) -> true | _ -> false let (|Public|Internal|Private|) (TAccess p) = match p with | [] -> Public | _ when List.forall isInternalCompPath p -> Internal | _ -> Private - match denv.contextAccessibility,accessibility with - | Public,Internal -> WordL.keywordInternal ++ itemL // print modifier, since more specific than context - | Public,Private -> WordL.keywordPrivate ++ itemL // print modifier, since more specific than context - | Internal,Private -> WordL.keywordPrivate ++ itemL // print modifier, since more specific than context + match denv.contextAccessibility, accessibility with + | Public, Internal -> WordL.keywordInternal ++ itemL // print modifier, since more specific than context + | Public, Private -> WordL.keywordPrivate ++ itemL // print modifier, since more specific than context + | Internal, Private -> WordL.keywordPrivate ++ itemL // print modifier, since more specific than context | _ -> itemL /// Layout a reference to a type @@ -616,13 +616,13 @@ module private PrintTypes = /// See also dataExprL - there is overlap between these that should be removed let rec private layoutAttribArg denv arg = match arg with - | Expr.Const(c,_,ty) -> + | Expr.Const(c, _, ty) -> if isEnumTy denv.g ty then WordL.keywordEnum ^^ angleL (layoutType denv ty) ^^ bracketL (layoutConst denv.g ty c) else layoutConst denv.g ty c - | Expr.Op (TOp.Array,[_elemTy],args,_) -> + | Expr.Op (TOp.Array, [_elemTy], args, _) -> LeftL.leftBracketBar ^^ semiListL (List.map (layoutAttribArg denv) args) ^^ RightL.rightBracketBar // Detect 'typeof' calls @@ -633,7 +633,7 @@ module private PrintTypes = | TypeDefOfExpr denv.g ty -> LeftL.keywordTypedefof ^^ wordL (tagPunctuation "<") ^^ layoutType denv ty ^^ rightL (tagPunctuation ">") - | Expr.Op (TOp.Coerce,[tgTy;_],[arg2],_) -> + | Expr.Op (TOp.Coerce, [tgTy;_], [arg2], _) -> leftL (tagPunctuation "(") ^^ layoutAttribArg denv arg2 ^^ wordL (tagPunctuation ":>") ^^ layoutType denv tgTy ^^ rightL (tagPunctuation ")") | AttribBitwiseOrExpr denv.g (arg1, arg2) -> @@ -648,12 +648,12 @@ module private PrintTypes = /// Layout arguments of an attribute 'arg1, ..., argN' and private layoutAttribArgs denv args = - sepListL (rightL (tagPunctuation ",")) (List.map (fun (AttribExpr(e1,_)) -> layoutAttribArg denv e1) args) + sepListL (rightL (tagPunctuation ",")) (List.map (fun (AttribExpr(e1, _)) -> layoutAttribArg denv e1) args) /// Layout an attribute 'Type(arg1, ..., argN)' // // REVIEW: we are ignoring "props" here - and layoutAttrib denv (Attrib(_,k,args,_props,_,_,_)) = + and layoutAttrib denv (Attrib(_, k, args, _props, _, _, _)) = let argsL = bracketL (layoutAttribArgs denv args) match k with | ILAttrib ilMethRef -> @@ -668,7 +668,7 @@ module private PrintTypes = PrintIL.layoutILTypeRef denv tref ++ argsL | FSAttrib vref -> // REVIEW: this is not trimming "Attribute" - let _,_,rty,_ = GetTypeOfMemberInMemberForm denv.g vref + let _, _, rty, _ = GetTypeOfMemberInMemberForm denv.g vref let rty = GetFSharpViewOfReturnType denv.g rty let tcref = tcrefOfAppTy denv.g rty layoutTyconRef denv tcref ++ argsL @@ -689,14 +689,14 @@ module private PrintTypes = | ILAttribElem.UInt64 x -> wordL (tagNumericLiteral ((x |> string)+"UL")) | ILAttribElem.Single x -> let str = - let s = x.ToString("g12",System.Globalization.CultureInfo.InvariantCulture) + let s = x.ToString("g12", System.Globalization.CultureInfo.InvariantCulture) (if String.forall (fun c -> System.Char.IsDigit(c) || c = '-') s then s + ".0" else s) + "f" wordL (tagNumericLiteral str) | ILAttribElem.Double x -> let str = - let s = x.ToString("g12",System.Globalization.CultureInfo.InvariantCulture) + let s = x.ToString("g12", System.Globalization.CultureInfo.InvariantCulture) if String.forall (fun c -> System.Char.IsDigit(c) || c = '-') s then s + ".0" else s @@ -747,7 +747,7 @@ module private PrintTypes = | [], TyparKind.Type -> restL | _, _ -> squareAngleL (sepListL (rightL (tagPunctuation ";")) ((match kind with TyparKind.Type -> [] | TyparKind.Measure -> [wordL (tagText "Measure")]) @ List.map (layoutAttrib denv) attrs)) ^^ restL - and private layoutTyparRef denv (typar:Typar) = + and private layoutTyparRef denv (typar: Typar) = wordL (tagTypeParameter (sprintf "%s%s%s" @@ -764,7 +764,7 @@ module private PrintTypes = /// ('a :> Type) - inplace coercion constraint not singleton. /// ('a.opM: S->T) - inplace operator constraint. /// - and private layoutTyparRefWithInfo denv (env:SimplifyTypes.TypeSimplificationInfo) (typar:Typar) = + and private layoutTyparRefWithInfo denv (env: SimplifyTypes.TypeSimplificationInfo) (typar: Typar) = let varL = layoutTyparRef denv typar let varL = if denv.showAttributes then layoutTyparAttribs denv typar.Kind typar.Attribs varL else varL @@ -786,10 +786,10 @@ module private PrintTypes = // So we normalize the constraints to eliminate duplicate member constraints let cxs = cxs - |> ListSet.setify (fun (_,cx1) (_,cx2) -> - match cx1,cx2 with - | TyparConstraint.MayResolveMember(traitInfo1,_), - TyparConstraint.MayResolveMember(traitInfo2,_) -> traitsAEquiv denv.g TypeEquivEnv.Empty traitInfo1 traitInfo2 + |> ListSet.setify (fun (_, cx1) (_, cx2) -> + match cx1, cx2 with + | TyparConstraint.MayResolveMember(traitInfo1, _), + TyparConstraint.MayResolveMember(traitInfo2, _) -> traitsAEquiv denv.g TypeEquivEnv.Empty traitInfo1 traitInfo2 | _ -> false) let cxsL = List.collect (layoutConstraintWithInfo denv env) cxs @@ -804,17 +804,17 @@ module private PrintTypes = wordL (tagKeyword "when") ^^ sepListL (wordL (tagKeyword "and")) cxsL /// Layout constraints, taking TypeSimplificationInfo into account - and private layoutConstraintWithInfo denv env (tp,tpc) = + and private layoutConstraintWithInfo denv env (tp, tpc) = let longConstraintPrefix l = layoutTyparRefWithInfo denv env tp ^^ WordL.colon ^^ l match tpc with - | TyparConstraint.CoercesTo(tpct,_) -> + | TyparConstraint.CoercesTo(tpct, _) -> [layoutTyparRefWithInfo denv env tp ^^ wordL (tagOperator ":>") --- layoutTypeWithInfo denv env tpct] - | TyparConstraint.MayResolveMember(traitInfo,_) -> + | TyparConstraint.MayResolveMember(traitInfo, _) -> [layoutTraitWithInfo denv env traitInfo] - | TyparConstraint.DefaultsTo(_,ty,_) -> + | TyparConstraint.DefaultsTo(_, ty, _) -> if denv.showTyparDefaultConstraints then [wordL (tagKeyword "default") ^^ layoutTyparRefWithInfo denv env tp ^^ WordL.colon ^^ layoutTypeWithInfo denv env ty] else [] - | TyparConstraint.IsEnum(ty,_) -> + | TyparConstraint.IsEnum(ty, _) -> if denv.shortConstraints then [wordL (tagKeyword "enum")] else @@ -829,7 +829,7 @@ module private PrintTypes = [wordL (tagKeyword "equality")] else [wordL (tagKeyword "equality") |> longConstraintPrefix] - | TyparConstraint.IsDelegate(aty,bty,_) -> + | TyparConstraint.IsDelegate(aty, bty, _) -> if denv.shortConstraints then [WordL.keywordDelegate] else @@ -851,7 +851,7 @@ module private PrintTypes = [wordL (tagText "reference type")] else [(wordL (tagKeyword "not") ^^ wordL(tagKeyword "struct")) |> longConstraintPrefix] - | TyparConstraint.SimpleChoice(tys,_) -> + | TyparConstraint.SimpleChoice(tys, _) -> [bracketL (sepListL (sepL (tagPunctuation "|")) (List.map (layoutTypeWithInfo denv env) tys)) |> longConstraintPrefix] | TyparConstraint.RequiresDefaultConstructor _ -> if denv.shortConstraints then @@ -864,7 +864,7 @@ module private PrintTypes = WordL.arrow ^^ (layoutTyparRefWithInfo denv env tp)) |> longConstraintPrefix] - and private layoutTraitWithInfo denv env (TTrait(tys,nm,memFlags,argtys,rty,_)) = + and private layoutTraitWithInfo denv env (TTrait(tys, nm, memFlags, argtys, rty, _)) = let nm = DemangleOperatorName nm if denv.shortConstraints then WordL.keywordMember ^^ wordL (tagMember nm) @@ -883,23 +883,23 @@ module private PrintTypes = /// Layout a unit expression and private layoutMeasure denv unt = - let sortVars vs = vs |> List.sortBy (fun (v:Typar,_) -> v.DisplayName) - let sortCons cs = cs |> List.sortBy (fun (c:TyconRef,_) -> c.DisplayName) - let negvs,posvs = ListMeasureVarOccsWithNonZeroExponents unt |> sortVars |> List.partition (fun (_,e) -> SignRational e < 0) - let negcs,poscs = ListMeasureConOccsWithNonZeroExponents denv.g false unt |> sortCons |> List.partition (fun (_,e) -> SignRational e < 0) + let sortVars vs = vs |> List.sortBy (fun (v: Typar, _) -> v.DisplayName) + let sortCons cs = cs |> List.sortBy (fun (c: TyconRef, _) -> c.DisplayName) + let negvs, posvs = ListMeasureVarOccsWithNonZeroExponents unt |> sortVars |> List.partition (fun (_, e) -> SignRational e < 0) + let negcs, poscs = ListMeasureConOccsWithNonZeroExponents denv.g false unt |> sortCons |> List.partition (fun (_, e) -> SignRational e < 0) let unparL uv = layoutTyparRef denv uv let unconL tc = layoutTyconRef denv tc let rationalL e = wordL (tagNumericLiteral (RationalToString e)) let measureToPowerL x e = if e = OneRational then x else x -- wordL (tagPunctuation "^") -- rationalL e - let prefix = spaceListL (List.map (fun (v,e) -> measureToPowerL (unparL v) e) posvs @ - List.map (fun (c,e) -> measureToPowerL (unconL c) e) poscs) - let postfix = spaceListL (List.map (fun (v,e) -> measureToPowerL (unparL v) (NegRational e)) negvs @ - List.map (fun (c,e) -> measureToPowerL (unconL c) (NegRational e)) negcs) - match (negvs,negcs) with - | [],[] -> (match posvs,poscs with [],[] -> wordL (tagNumericLiteral "1") | _ -> prefix) + let prefix = spaceListL (List.map (fun (v, e) -> measureToPowerL (unparL v) e) posvs @ + List.map (fun (c, e) -> measureToPowerL (unconL c) e) poscs) + let postfix = spaceListL (List.map (fun (v, e) -> measureToPowerL (unparL v) (NegRational e)) negvs @ + List.map (fun (c, e) -> measureToPowerL (unconL c) (NegRational e)) negcs) + match (negvs, negcs) with + | [], [] -> (match posvs, poscs with [], [] -> wordL (tagNumericLiteral "1") | _ -> prefix) | _ -> prefix ^^ sepL (tagPunctuation "/") ^^ (if List.length negvs + List.length negcs > 1 then sepL (tagPunctuation "(") ^^ postfix ^^ sepL (tagPunctuation ")") else postfix) - /// Layout type arguments, either NAME or (ty,...,ty) NAME *) + /// Layout type arguments, either NAME or (ty, ..., ty) NAME *) and private layoutTypeAppWithInfoAndPrec denv env tcL prec prefix args = if prefix then match args with @@ -917,31 +917,31 @@ module private PrintTypes = match stripTyparEqns ty with - // Always prefer to format 'byref' as 'inref' + // Always prefer to format 'byref' as 'inref' | ty when isInByrefTy denv.g ty && (match ty with TType_app (tc, _) when denv.g.inref_tcr.CanDeref && tyconRefEq denv.g tc denv.g.byref2_tcr -> true | _ -> false) -> layoutTypeWithInfoAndPrec denv env prec (mkInByrefTy denv.g (destByrefTy denv.g ty)) - // Always prefer to format 'byref' as 'outref' + // Always prefer to format 'byref' as 'outref' | ty when isOutByrefTy denv.g ty && (match ty with TType_app (tc, _) when denv.g.outref_tcr.CanDeref && tyconRefEq denv.g tc denv.g.byref2_tcr -> true | _ -> false) -> layoutTypeWithInfoAndPrec denv env prec (mkOutByrefTy denv.g (destByrefTy denv.g ty)) - // Always prefer to format 'byref' as 'byref' + // Always prefer to format 'byref' as 'byref' | ty when isByrefTy denv.g ty && (match ty with TType_app (tc, _) when denv.g.byref_tcr.CanDeref && tyconRefEq denv.g tc denv.g.byref2_tcr -> true | _ -> false) -> layoutTypeWithInfoAndPrec denv env prec (mkByrefTy denv.g (destByrefTy denv.g ty)) // Always prefer 'float' to 'float<1>' - | TType_app (tc,args) when tc.IsMeasureableReprTycon && List.forall (isDimensionless denv.g) args -> + | TType_app (tc, args) when tc.IsMeasureableReprTycon && List.forall (isDimensionless denv.g) args -> layoutTypeWithInfoAndPrec denv env prec (reduceTyconRefMeasureableOrProvided denv.g tc args) // Layout a type application - | TType_app (tc,args) -> + | TType_app (tc, args) -> layoutTypeAppWithInfoAndPrec denv env (layoutTyconRef denv tc) prec tc.IsPrefixDisplay args - | TType_ucase (UCRef(tc,_),args) -> + | TType_ucase (UCRef(tc, _), args) -> layoutTypeAppWithInfoAndPrec denv env (layoutTyconRef denv tc) prec tc.IsPrefixDisplay args // Layout a tuple type - | TType_anon (anonInfo,tys) -> + | TType_anon (anonInfo, tys) -> let core = sepListL (wordL (tagPunctuation ";")) (List.map2 (fun nm ty -> wordL (tagField nm) ^^ wordL (tagPunctuation ":") ^^ layoutTypeWithInfoAndPrec denv env prec ty) (Array.toList anonInfo.SortedNames) tys) if evalAnonInfoIsStruct anonInfo then WordL.keywordStruct --- braceBarL core @@ -949,14 +949,14 @@ module private PrintTypes = braceBarL core // Layout a tuple type - | TType_tuple (tupInfo,t) -> + | TType_tuple (tupInfo, t) -> if evalTupInfoIsStruct tupInfo then WordL.keywordStruct --- bracketL (layoutTypesWithInfoAndPrec denv env 2 (wordL (tagPunctuation "*")) t) else bracketIfL (prec <= 2) (layoutTypesWithInfoAndPrec denv env 2 (wordL (tagPunctuation "*")) t) // Layout a first-class generic type. - | TType_forall (tps,tau) -> + | TType_forall (tps, tau) -> let tauL = layoutTypeWithInfoAndPrec denv env prec tau match tps with | [] -> tauL @@ -967,7 +967,7 @@ module private PrintTypes = | TType_fun _ -> let rec loop soFarL ty = match stripTyparEqns ty with - | TType_fun (dty,rty) -> loop (soFarL --- (layoutTypeWithInfoAndPrec denv env 4 dty ^^ wordL (tagPunctuation "->"))) rty + | TType_fun (dty, rty) -> loop (soFarL --- (layoutTypeWithInfoAndPrec denv env 4 dty ^^ wordL (tagPunctuation "->"))) rty | rty -> soFarL --- layoutTypeWithInfoAndPrec denv env 5 rty bracketIfL (prec <= 4) (loop emptyL ty) @@ -998,7 +998,7 @@ module private PrintTypes = | _ -> // Format each argument, including its name and type - let argL (ty,argInfo: ArgReprInfo) = + let argL (ty, argInfo: ArgReprInfo) = // Detect an optional argument let isOptionalArg = HasFSharpAttribute denv.g denv.g.attrib_OptionalArgumentAttribute argInfo.Attribs @@ -1008,10 +1008,10 @@ module private PrintTypes = | Some(id), true, _, ValueSome ty -> leftL (tagPunctuation "?") ^^ sepL (tagParameter id.idText) ^^ SepL.colon ^^ layoutTypeWithInfoAndPrec denv env 2 ty // Layout an unnamed argument - | None, _,_, _ -> + | None, _, _, _ -> layoutTypeWithInfoAndPrec denv env 2 ty // Layout a named argument - | Some id,_,isParamArray,_ -> + | Some id, _, isParamArray, _ -> let prefix = if isParamArray then layoutBuiltinAttribute denv denv.g.attrib_ParamArrayAttribute ^^ leftL (tagParameter id.idText) @@ -1031,12 +1031,12 @@ module private PrintTypes = /// Layout type parameters let layoutTyparDecls denv nmL prefix (typars: Typars) = let env = SimplifyTypes.typeSimplificationInfo0 - let tpcs = typars |> List.collect (fun tp -> List.map (fun tpc -> tp,tpc) tp.Constraints) - match typars,tpcs with - | [],[] -> + let tpcs = typars |> List.collect (fun tp -> List.map (fun tpc -> tp, tpc) tp.Constraints) + match typars, tpcs with + | [], [] -> nmL - | [h],[] when not prefix -> + | [h], [] when not prefix -> layoutTyparRefWithInfo denv env h --- nmL | _ -> @@ -1064,13 +1064,13 @@ module private PrintTypes = // Oddly this is called in multiple places with argInfos=[] and denv.useColonForReturnType=true, as a complex // way of giving give ": ty" let prettyLayoutOfUncurriedSig denv typarInst argInfos retTy = - let (prettyTyparInst, prettyArgInfos,prettyRetTy),cxs = PrettyTypes.PrettifyInstAndUncurriedSig denv.g (typarInst, argInfos, retTy) + let (prettyTyparInst, prettyArgInfos, prettyRetTy), cxs = PrettyTypes.PrettifyInstAndUncurriedSig denv.g (typarInst, argInfos, retTy) prettyTyparInst, prettyLayoutOfTopTypeInfoAux denv [prettyArgInfos] prettyRetTy cxs let prettyLayoutOfCurriedMemberSig denv typarInst argInfos retTy parentTyparTys = - let (prettyTyparInst, parentTyparTys,argInfos,retTy),cxs = PrettyTypes.PrettifyInstAndCurriedSig denv.g (typarInst, parentTyparTys, argInfos, retTy) + let (prettyTyparInst, parentTyparTys, argInfos, retTy), cxs = PrettyTypes.PrettifyInstAndCurriedSig denv.g (typarInst, parentTyparTys, argInfos, retTy) // Filter out the parent typars, which don't get shown in the member signature - let cxs = cxs |> List.filter (fun (tp,_) -> not (parentTyparTys |> List.exists (fun ty -> match tryDestTyparTy denv.g ty with ValueSome destTypar -> typarEq tp destTypar | _ -> false))) + let cxs = cxs |> List.filter (fun (tp, _) -> not (parentTyparTys |> List.exists (fun ty -> match tryDestTyparTy denv.g ty with ValueSome destTypar -> typarEq tp destTypar | _ -> false))) prettyTyparInst, prettyLayoutOfTopTypeInfoAux denv argInfos retTy cxs // Layout: type spec - class, datatype, record, abbrev @@ -1081,7 +1081,7 @@ module private PrintTypes = PrettyTypes.NewPrettyTypars memberToParentInst methTypars methTyparNames let retTy = instType allTyparInst retTy - let argInfos = argInfos |> List.map (fun infos -> if isNil infos then [(denv.g.unit_ty,ValReprInfo.unnamedTopArg1)] else infos |> List.map (map1Of2 (instType allTyparInst))) + let argInfos = argInfos |> List.map (fun infos -> if isNil infos then [(denv.g.unit_ty, ValReprInfo.unnamedTopArg1)] else infos |> List.map (map1Of2 (instType allTyparInst))) // Also format dummy types corresponding to any type variables on the container to make sure they // aren't chosen as names for displayed variables. @@ -1093,7 +1093,7 @@ module private PrintTypes = let prettyLayoutOfMemberType denv v typarInst argInfos retTy = match PartitionValRefTypars denv.g v with - | Some(_,_,memberMethodTypars,memberToParentInst,_) -> + | Some(_, _, memberMethodTypars, memberToParentInst, _) -> prettyLayoutOfMemberSigCore denv memberToParentInst (typarInst, memberMethodTypars, argInfos, retTy) | None -> let prettyTyparInst, layout = prettyLayoutOfUncurriedSig denv typarInst (List.concat argInfos) retTy @@ -1108,13 +1108,13 @@ module private PrintTypes = nameL ^^ wordL (tagPunctuation ":") ^^ tauL let prettyLayoutOfType denv ty = - let ty,cxs = PrettyTypes.PrettifyType denv.g ty + let ty, cxs = PrettyTypes.PrettifyType denv.g ty let env = SimplifyTypes.CollectInfo true [ty] cxs let cxsL = layoutConstraintsWithInfo denv env env.postfixConstraints layoutTypeWithInfoAndPrec denv env 2 ty --- cxsL let prettyLayoutOfTypeNoConstraints denv ty = - let ty,_cxs = PrettyTypes.PrettifyType denv.g ty + let ty, _cxs = PrettyTypes.PrettifyType denv.g ty layoutTypeWithInfoAndPrec denv SimplifyTypes.typeSimplificationInfo0 5 ty let layoutAssemblyName _denv (ty: TType) = @@ -1123,11 +1123,11 @@ module private PrintTypes = /// Printing TAST objects module private PrintTastMemberOrVals = open PrintTypes - let private prettyLayoutOfMember denv typarInst (v:Val) = + let private prettyLayoutOfMember denv typarInst (v: Val) = let v = mkLocalValRef v let membInfo = Option.get v.MemberInfo let stat = PrintTypes.layoutMemberFlags membInfo.MemberFlags - let _tps,argInfos,rty,_ = GetTypeOfMemberInFSharpForm denv.g v + let _tps, argInfos, rty, _ = GetTypeOfMemberInFSharpForm denv.g v let mkNameL niceMethodTypars tagFunction name = let nameL = @@ -1143,7 +1143,7 @@ module private PrintTastMemberOrVals = match membInfo.MemberFlags.MemberKind with | MemberKind.Member -> - let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty + let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty let nameL = mkNameL niceMethodTypars tagMember v.LogicalName let resL = stat --- (nameL ^^ WordL.colon ^^ tauL) prettyTyparInst, resL @@ -1158,38 +1158,38 @@ module private PrintTastMemberOrVals = | MemberKind.PropertyGet -> if isNil argInfos then // use error recovery because intellisense on an incomplete file will show this - errorR(Error(FSComp.SR.tastInvalidFormForPropertyGetter(),v.Id.idRange)) + errorR(Error(FSComp.SR.tastInvalidFormForPropertyGetter(), v.Id.idRange)) let nameL = mkNameL [] tagProperty v.CoreDisplayName let resL = stat --- nameL --- (WordL.keywordWith ^^ WordL.keywordGet) emptyTyparInst, resL else let argInfos = match argInfos with - | [[(ty,_)]] when isUnitTy denv.g ty -> [] + | [[(ty, _)]] when isUnitTy denv.g ty -> [] | _ -> argInfos - let prettyTyparInst, niceMethodTypars,tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty + let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst argInfos rty let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName let resL = stat --- (nameL ^^ WordL.colon ^^ (if isNil argInfos then tauL else tauL --- (WordL.keywordWith ^^ WordL.keywordGet))) prettyTyparInst, resL | MemberKind.PropertySet -> if argInfos.Length <> 1 || isNil argInfos.Head then // use error recovery because intellisense on an incomplete file will show this - errorR(Error(FSComp.SR.tastInvalidFormForPropertySetter(),v.Id.idRange)) + errorR(Error(FSComp.SR.tastInvalidFormForPropertySetter(), v.Id.idRange)) let nameL = mkNameL [] tagProperty v.CoreDisplayName let resL = stat --- nameL --- (WordL.keywordWith ^^ WordL.keywordSet) emptyTyparInst, resL else - let argInfos,valueInfo = List.frontAndBack argInfos.Head + let argInfos, valueInfo = List.frontAndBack argInfos.Head let prettyTyparInst, niceMethodTypars, tauL = prettyLayoutOfMemberType denv v typarInst (if isNil argInfos then [] else [argInfos]) (fst valueInfo) let nameL = mkNameL niceMethodTypars tagProperty v.CoreDisplayName let resL = stat --- (nameL ^^ wordL (tagPunctuation ":") ^^ (tauL --- (WordL.keywordWith ^^ WordL.keywordSet))) prettyTyparInst, resL - let private layoutNonMemberVal denv (tps,v:Val,tau,cxs) = + let private layoutNonMemberVal denv (tps, v: Val, tau, cxs) = let env = SimplifyTypes.CollectInfo true [tau] cxs let cxs = env.postfixConstraints - let argInfos,rty = GetTopTauTypeInFSharpForm denv.g (arityOfVal v).ArgInfos tau v.Range + let argInfos, rty = GetTopTauTypeInFSharpForm denv.g (arityOfVal v).ArgInfos tau v.Range let nameL = (if v.IsModuleBinding then tagModuleBinding else tagUnknownEntity) v.DisplayName |> mkNav v.DefinitionRange @@ -1217,17 +1217,17 @@ module private PrintTastMemberOrVals = | None -> valAndTypeL | Some rhsL -> (valAndTypeL ++ wordL (tagPunctuation"=")) --- rhsL - let prettyLayoutOfValOrMember denv typarInst (v:Val) = + let prettyLayoutOfValOrMember denv typarInst (v: Val) = let prettyTyparInst, vL = match v.MemberInfo with | None -> - let tps,tau = v.TypeScheme + let tps, tau = v.TypeScheme // adjust the type in case this is the 'this' pointer stored in a reference cell let tau = StripSelfRefCell(denv.g, v.BaseOrThisInfo, tau) - let (prettyTyparInst, prettyTypars, prettyTauTy),cxs = PrettyTypes.PrettifyInstAndTyparsAndType denv.g (typarInst,tps,tau) - let resL = layoutNonMemberVal denv (prettyTypars,v,prettyTauTy,cxs) + let (prettyTyparInst, prettyTypars, prettyTauTy), cxs = PrettyTypes.PrettifyInstAndTyparsAndType denv.g (typarInst, tps, tau) + let resL = layoutNonMemberVal denv (prettyTypars, v, prettyTauTy, cxs) prettyTyparInst, resL | Some _ -> prettyLayoutOfMember denv typarInst v @@ -1267,15 +1267,15 @@ module InfoMemberPrinting = RightL.colon ^^ PrintTypes.layoutType denv pty // Layout an unnamed argument - | _, None, _,_ -> + | _, None, _, _ -> PrintTypes.layoutType denv pty // Layout a named argument - | true, Some nm,_,_ -> + | true, Some nm, _, _ -> layoutBuiltinAttribute denv denv.g.attrib_ParamArrayAttribute ^^ wordL (tagParameter nm.idText) ^^ RightL.colon ^^ PrintTypes.layoutType denv pty - | false, Some nm,_,_ -> + | false, Some nm, _, _ -> wordL (tagParameter nm.idText) ^^ RightL.colon ^^ PrintTypes.layoutType denv pty @@ -1285,9 +1285,9 @@ module InfoMemberPrinting = /// Format a method info using "F# style". // // That is, this style: - // new: argName1:argType1 * ... * argNameN:argTypeN -> retType - // Method: argName1:argType1 * ... * argNameN:argTypeN -> retType - let private layoutMethInfoFSharpStyleCore amap m denv (minfo:MethInfo) minst = + // new: argName1: argType1 * ... * argNameN: argTypeN -> retType + // Method: argName1: argType1 * ... * argNameN: argTypeN -> retType + let private layoutMethInfoFSharpStyleCore amap m denv (minfo: MethInfo) minst = let layout = if not minfo.IsConstructor && not minfo.IsInstance then WordL.keywordStatic else emptyL @@ -1316,9 +1316,9 @@ module InfoMemberPrinting = /// Format a method info using "half C# style". // // That is, this style: - // Container(argName1:argType1, ..., argNameN:argTypeN) : retType - // Container.Method(argName1:argType1, ..., argNameN:argTypeN) : retType - let private layoutMethInfoCSharpStyle amap m denv (minfo:MethInfo) minst = + // Container(argName1: argType1, ..., argNameN: argTypeN) : retType + // Container.Method(argName1: argType1, ..., argNameN: argTypeN) : retType + let private layoutMethInfoCSharpStyle amap m denv (minfo: MethInfo) minst = let retTy = if minfo.IsConstructor then minfo.ApparentEnclosingType else minfo.GetFSharpReturnTy(amap, m, minst) let layout = if minfo.IsExtensionMember then @@ -1346,7 +1346,7 @@ module InfoMemberPrinting = // Prettify this baby - let prettifyILMethInfo (amap:Import.ImportMap) m (minfo:MethInfo) typarInst ilMethInfo = + let prettifyILMethInfo (amap: Import.ImportMap) m (minfo: MethInfo) typarInst ilMethInfo = let (ILMethInfo(_, apparentTy, dty, mdef, _)) = ilMethInfo let (prettyTyparInst, prettyTys), _ = PrettyTypes.PrettifyInstAndTypes amap.g (typarInst, (apparentTy :: minfo.FormalMethodInst)) let prettyApparentTy, prettyFormalMethInst = List.headAndTail prettyTys @@ -1365,28 +1365,28 @@ module InfoMemberPrinting = // // For F# members: // new: unit -> retType - // new: argName1:argType1 * ... * argNameN:argTypeN -> retType + // new: argName1: argType1 * ... * argNameN: argTypeN -> retType // Container.Method: unit -> retType - // Container.Method: argName1:argType1 * ... * argNameN:argTypeN -> retType + // Container.Method: argName1: argType1 * ... * argNameN: argTypeN -> retType // // For F# extension members: - // ApparentContainer.Method: argName1:argType1 * ... * argNameN:argTypeN -> retType + // ApparentContainer.Method: argName1: argType1 * ... * argNameN: argTypeN -> retType // // For C# and provided members: - // Container(argName1:argType1, ..., argNameN:argTypeN) : retType - // Container.Method(argName1:argType1, ..., argNameN:argTypeN) : retType + // Container(argName1: argType1, ..., argNameN: argTypeN) : retType + // Container.Method(argName1: argType1, ..., argNameN: argTypeN) : retType // // For C# extension members: - // ApparentContainer.Method(argName1:argType1, ..., argNameN:argTypeN) : retType + // ApparentContainer.Method(argName1: argType1, ..., argNameN: argTypeN) : retType let prettyLayoutOfMethInfoFreeStyle (amap: Import.ImportMap) m denv typarInst methInfo = match methInfo with | DefaultStructCtor _ -> let prettyTyparInst, _ = PrettyTypes.PrettifyInst amap.g typarInst prettyTyparInst, PrintTypes.layoutTyconRef denv methInfo.ApparentEnclosingTyconRef ^^ wordL (tagPunctuation "()") - | FSMeth(_,_,vref,_) -> + | FSMeth(_, _, vref, _) -> let prettyTyparInst, resL = PrintTastMemberOrVals.prettyLayoutOfValOrMember { denv with showMemberContainers=true } typarInst vref.Deref prettyTyparInst, resL - | ILMeth(_,ilminfo,_) -> + | ILMeth(_, ilminfo, _) -> let prettyTyparInst, prettyMethInfo, minst = prettifyILMethInfo amap m methInfo typarInst ilminfo let resL = layoutMethInfoCSharpStyle amap m denv prettyMethInfo minst prettyTyparInst, resL @@ -1397,7 +1397,7 @@ module InfoMemberPrinting = #endif let prettyLayoutOfPropInfoFreeStyle g amap m denv (pinfo: PropInfo) = - let rty = pinfo.GetPropertyType(amap,m) + let rty = pinfo.GetPropertyType(amap, m) let rty = if pinfo.IsIndexer then mkRefTupledTy g (pinfo.GetParamTypes(amap, m)) --> rty else rty let rty, _ = PrettyTypes.PrettifyType g rty let tagProp = @@ -1426,13 +1426,13 @@ module InfoMemberPrinting = module private TastDefinitionPrinting = open PrintTypes - let layoutExtensionMember denv (v:Val) = + let layoutExtensionMember denv (v: Val) = let tycon = v.MemberApparentEntity.Deref let nameL = tagMethod tycon.DisplayName |> mkNav v.DefinitionRange |> wordL let nameL = layoutAccessibility denv tycon.Accessibility nameL // "type-accessibility" let tps = match PartitionValTyparsForApparentEnclosingType denv.g v with - | Some(_,memberParentTypars,_,_,_) -> memberParentTypars + | Some(_, memberParentTypars, _, _, _) -> memberParentTypars | None -> [] let lhsL = WordL.keywordType ^^ layoutTyparDecls denv nameL tycon.IsPrefixDisplay tps let memberL = PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv v @@ -1441,7 +1441,7 @@ module private TastDefinitionPrinting = let layoutExtensionMembers denv vs = aboveListL (List.map (layoutExtensionMember denv) vs) - let layoutRecdField addAccess denv (fld:RecdField) = + let layoutRecdField addAccess denv (fld: RecdField) = let lhs = tagRecordField fld.Name |> mkNav fld.DefinitionRange @@ -1468,7 +1468,7 @@ module private TastDefinitionPrinting = let isGenerated = if isUnionCase then isGeneratedUnionCaseField else isGeneratedExceptionField sepListL (wordL (tagPunctuation "*")) (List.mapi (layoutUnionOrExceptionField denv isGenerated) fields) - let layoutUnionCase denv prefixL (ucase:UnionCase) = + let layoutUnionCase denv prefixL (ucase: UnionCase) = let nmL = DemangleOperatorNameAsLayout (tagUnionCase >> mkNav ucase.DefinitionRange) ucase.Id.idText //let nmL = layoutAccessibility denv ucase.Accessibility nmL match ucase.RecdFields with @@ -1501,48 +1501,48 @@ module private TastDefinitionPrinting = let private layoutILFieldInfo denv amap m (e: ILFieldInfo) = let staticL = if e.IsStatic then WordL.keywordStatic else emptyL let nameL = wordL (tagField (adjustILName e.FieldName)) - let typL = layoutType denv (e.FieldType(amap,m)) + let typL = layoutType denv (e.FieldType(amap, m)) staticL ^^ WordL.keywordVal ^^ nameL ^^ WordL.colon ^^ typL let private layoutEventInfo denv amap m (e: EventInfo) = let staticL = if e.IsStatic then WordL.keywordStatic else emptyL let nameL = wordL (tagEvent (adjustILName e.EventName)) - let typL = layoutType denv (e.GetDelegateType(amap,m)) + let typL = layoutType denv (e.GetDelegateType(amap, m)) staticL ^^ WordL.keywordEvent ^^ nameL ^^ WordL.colon ^^ typL let private layoutPropInfo denv amap m (p: PropInfo) = let staticL = if p.IsStatic then WordL.keywordStatic else emptyL let nameL = wordL (tagProperty (adjustILName p.PropertyName)) - let typL = layoutType denv (p.GetPropertyType(amap,m)) // shouldn't happen + let typL = layoutType denv (p.GetPropertyType(amap, m)) // shouldn't happen let specGetSetL = match p.HasGetter, p.HasSetter with - | false,false | true,false -> emptyL + | false, false | true, false -> emptyL | false, true -> WordL.keywordWith ^^ WordL.keywordSet | true, true -> WordL.keywordWith ^^ WordL.keywordGet^^ SepL.comma ^^ WordL.keywordSet staticL ^^ WordL.keywordMember ^^ nameL ^^ WordL.colon ^^ typL ^^ specGetSetL /// Another re-implementation of type printing, this time based off provided info objects. - let layoutProvidedTycon (denv:DisplayEnv) (infoReader:InfoReader) ad m start lhsL ty = + let layoutProvidedTycon (denv: DisplayEnv) (infoReader: InfoReader) ad m start lhsL ty = let g = denv.g let tcref = tcrefOfAppTy g ty if isEnumTy g ty then let fieldLs = - infoReader.GetILFieldInfosOfType (None,ad,m,ty) + infoReader.GetILFieldInfosOfType (None, ad, m, ty) |> List.filter (fun x -> x.FieldName <> "value__") |> List.map (fun x -> PrintIL.layoutILEnumDefParts x.FieldName x.LiteralValue) |> aboveListL (lhsL ^^ WordL.equals) @@-- fieldLs else let amap = infoReader.amap - let sortKey (v:MethInfo) = - (not v.IsConstructor, - not v.IsInstance, // instance first - v.DisplayName, // sort by name - List.sum v.NumArgs , // sort by #curried + let sortKey (v: MethInfo) = + (not v.IsConstructor, + not v.IsInstance, // instance first + v.DisplayName, // sort by name + List.sum v.NumArgs , // sort by #curried v.NumArgs.Length) // sort by arity let shouldShow (valRef: ValRef option) = @@ -1557,7 +1557,7 @@ module private TastDefinitionPrinting = |> List.filter (fun v -> shouldShow v.ArbitraryValRef) let meths = - GetImmediateIntrinsicMethInfosOfType (None,ad) g amap m ty + GetImmediateIntrinsicMethInfosOfType (None, ad) g amap m ty |> List.filter (fun v -> shouldShow v.ArbitraryValRef) let iimplsLs = @@ -1567,11 +1567,11 @@ module private TastDefinitionPrinting = GetImmediateInterfacesOfType SkipUnrefInterfaces.Yes g amap m ty |> List.map (fun ity -> wordL (tagKeyword (if isInterfaceTy g ty then "inherit" else "interface")) --- layoutType denv ity) let props = - GetIntrinsicPropInfosOfType infoReader (None,ad,AllowMultiIntfInstantiations.Yes) PreferOverrides m ty + GetIntrinsicPropInfosOfType infoReader (None, ad, AllowMultiIntfInstantiations.Yes) PreferOverrides m ty |> List.filter (fun v -> shouldShow v.ArbitraryValRef) let events = - infoReader.GetEventInfosOfType(None,ad,m,ty) + infoReader.GetEventInfosOfType(None, ad, m, ty) |> List.filter (fun v -> shouldShow v.ArbitraryValRef) let impliedNames = @@ -1592,20 +1592,20 @@ module private TastDefinitionPrinting = meths |> List.filter (fun md -> not (impliedNames.Contains md.DisplayName)) |> List.groupBy (fun md -> md.DisplayName) - |> List.collect (fun (_,group) -> shrinkOverloads (InfoMemberPrinting.layoutMethInfoFSharpStyle amap m denv) (fun x xL -> (sortKey x, xL)) group) + |> List.collect (fun (_, group) -> shrinkOverloads (InfoMemberPrinting.layoutMethInfoFSharpStyle amap m denv) (fun x xL -> (sortKey x, xL)) group) let fieldLs = - infoReader.GetILFieldInfosOfType (None,ad,m,ty) - |> List.map (fun x -> (true,x.IsStatic,x.FieldName,0,0),layoutILFieldInfo denv amap m x) + infoReader.GetILFieldInfosOfType (None, ad, m, ty) + |> List.map (fun x -> (true, x.IsStatic, x.FieldName, 0, 0), layoutILFieldInfo denv amap m x) let propLs = props - |> List.map (fun x -> (true,x.IsStatic,x.PropertyName,0,0),layoutPropInfo denv amap m x) + |> List.map (fun x -> (true, x.IsStatic, x.PropertyName, 0, 0), layoutPropInfo denv amap m x) let eventLs = events - |> List.map (fun x -> (true,x.IsStatic,x.EventName,0,0), layoutEventInfo denv amap m x) + |> List.map (fun x -> (true, x.IsStatic, x.EventName, 0, 0), layoutEventInfo denv amap m x) let membLs = (methLs @ fieldLs @ propLs @ eventLs) |> List.sortBy fst |> List.map snd @@ -1645,9 +1645,9 @@ module private TastDefinitionPrinting = (lhsL ^^ WordL.equals) @@-- rhsL #endif - let layoutTycon (denv:DisplayEnv) (infoReader:InfoReader) ad m simplified typewordL (tycon:Tycon) = + let layoutTycon (denv: DisplayEnv) (infoReader: InfoReader) ad m simplified typewordL (tycon: Tycon) = let g = denv.g - let _,ty = generalizeTyconRef (mkLocalTyconRef tycon) + let _, ty = generalizeTyconRef (mkLocalTyconRef tycon) let start, name = let n = tycon.DisplayName if isStructTy g ty then Some "struct", tagStruct n @@ -1670,14 +1670,14 @@ module private TastDefinitionPrinting = #else ignore (infoReader, ad, m) #endif - let memberImplementLs,memberCtorLs,memberInstanceLs,memberStaticLs = + let memberImplementLs, memberCtorLs, memberInstanceLs, memberStaticLs = let adhoc = tycon.MembersOfFSharpTyconSorted |> List.filter (fun v -> not v.IsDispatchSlot) |> List.filter (fun v -> not v.Deref.IsClassConstructor) |> List.filter (fun v -> match v.MemberInfo.Value.ImplementedSlotSigs with - | TSlotSig(_,oty,_,_,_,_) :: _ -> + | TSlotSig(_, oty, _, _, _, _) :: _ -> // Don't print overrides in HTML docs denv.showOverrides && // Don't print individual methods forming interface implementations - these are currently never exported @@ -1686,23 +1686,23 @@ module private TastDefinitionPrinting = |> List.filter (fun v -> denv.showObsoleteMembers || not (CheckFSharpAttributesForObsolete denv.g v.Attribs)) |> List.filter (fun v -> denv.showHiddenMembers || not (CheckFSharpAttributesForHidden denv.g v.Attribs)) // sort - let sortKey (v:ValRef) = - (not v.IsConstructor, // constructors before others - v.Id.idText, // sort by name - (if v.IsCompiledAsTopLevel then v.ValReprInfo.Value.NumCurriedArgs else 0), // sort by #curried + let sortKey (v: ValRef) = + (not v.IsConstructor, // constructors before others + v.Id.idText, // sort by name + (if v.IsCompiledAsTopLevel then v.ValReprInfo.Value.NumCurriedArgs else 0), // sort by #curried (if v.IsCompiledAsTopLevel then v.ValReprInfo.Value.AritiesOfArgs else [])) // sort by arity let adhoc = adhoc |> List.sortBy sortKey let iimpls = match tycon.TypeReprInfo with | TFSharpObjectRepr r when (match r.fsobjmodel_kind with TTyconInterface -> true | _ -> false) -> [] | _ -> tycon.ImmediateInterfacesOfFSharpTycon - let iimpls = iimpls |> List.filter (fun (_,compgen,_) -> not compgen) + let iimpls = iimpls |> List.filter (fun (_, compgen, _) -> not compgen) // if TTyconInterface, the iimpls should be printed as inherited interfaces - let iimplsLs = iimpls |> List.map (fun (ty,_,_) -> wordL (tagKeyword "interface") --- layoutType denv ty) + let iimplsLs = iimpls |> List.map (fun (ty, _, _) -> wordL (tagKeyword "interface") --- layoutType denv ty) let adhocCtorsLs = adhoc |> List.filter (fun v -> v.IsConstructor) |> List.map (fun vref -> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv vref.Deref) let adhocInstanceLs = adhoc |> List.filter (fun v -> not v.IsConstructor && v.IsInstanceMember) |> List.map (fun vref -> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv vref.Deref) let adhocStaticLs = adhoc |> List.filter (fun v -> not v.IsConstructor && not v.IsInstanceMember) |> List.map (fun vref -> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv vref.Deref) - iimplsLs,adhocCtorsLs,adhocInstanceLs,adhocStaticLs + iimplsLs, adhocCtorsLs, adhocInstanceLs, adhocStaticLs let memberLs = memberImplementLs @ memberCtorLs @ memberInstanceLs @ memberStaticLs let addMembersAsWithEnd reprL = if isNil memberLs then reprL @@ -1732,7 +1732,7 @@ module private TastDefinitionPrinting = | TFSharpObjectRepr r -> match r.fsobjmodel_kind with - | TTyconDelegate (TSlotSig(_,_, _,_,paraml, rty)) -> + | TTyconDelegate (TSlotSig(_, _, _, _, paraml, rty)) -> let rty = GetFSharpViewOfReturnType denv.g rty Some (WordL.keywordDelegate ^^ WordL.keywordOf --- layoutTopType denv SimplifyTypes.typeSimplificationInfo0 (paraml |> List.mapSquared (fun sp -> (sp.Type, ValReprInfo.unnamedTopArg1))) rty []) | _ -> @@ -1751,11 +1751,11 @@ module private TastDefinitionPrinting = | _ -> let inherits = match r.fsobjmodel_kind, tycon.TypeContents.tcaug_super with - | TTyconClass,Some super -> [wordL (tagKeyword "inherit") ^^ (layoutType denv super)] - | TTyconInterface,_ -> + | TTyconClass, Some super -> [wordL (tagKeyword "inherit") ^^ (layoutType denv super)] + | TTyconInterface, _ -> tycon.ImmediateInterfacesOfFSharpTycon - |> List.filter (fun (_,compgen,_) -> not compgen) - |> List.map (fun (ity,_,_) -> wordL (tagKeyword "inherit") ^^ (layoutType denv ity)) + |> List.filter (fun (_, compgen, _) -> not compgen) + |> List.map (fun (ity, _, _) -> wordL (tagKeyword "inherit") ^^ (layoutType denv ity)) | _ -> [] let vsprs = tycon.MembersOfFSharpTyconSorted @@ -1810,7 +1810,7 @@ module private TastDefinitionPrinting = layoutAttribs denv ty tycon.TypeOrMeasureKind tycon.Attribs reprL // Layout: exception definition - let layoutExnDefn denv (exnc:Entity) = + let layoutExnDefn denv (exnc: Entity) = let nm = exnc.LogicalName let nmL = wordL (tagClass nm) let nmL = layoutAccessibility denv exnc.TypeReprAccessibility nmL @@ -1829,7 +1829,7 @@ module private TastDefinitionPrinting = // Layout: module spec - let layoutTyconDefns denv infoReader ad m (tycons:Tycon list) = + let layoutTyconDefns denv infoReader ad m (tycons: Tycon list) = match tycons with | [] -> emptyL | [h] when h.IsExceptionDecl -> layoutExnDefn denv h @@ -1849,8 +1849,8 @@ module private InferredSigPrinting = let rec isConcreteNamespace x = match x with - | TMDefRec(_,tycons,mbinds,_) -> - not (isNil tycons) || (mbinds |> List.exists (function ModuleOrNamespaceBinding.Binding _ -> true | ModuleOrNamespaceBinding.Module(x,_) -> not x.IsNamespace)) + | TMDefRec(_, tycons, mbinds, _) -> + not (isNil tycons) || (mbinds |> List.exists (function ModuleOrNamespaceBinding.Binding _ -> true | ModuleOrNamespaceBinding.Module(x, _) -> not x.IsNamespace)) | TMDefLet _ -> true | TMDefDo _ -> true | TMDefs defs -> defs |> List.exists isConcreteNamespace @@ -1863,11 +1863,11 @@ module private InferredSigPrinting = and imdefsL denv x = aboveListL (x |> List.map (imdefL denv)) and imdefL denv x = - let filterVal (v:Val) = not v.IsCompilerGenerated && Option.isNone v.MemberInfo - let filterExtMem (v:Val) = v.IsExtensionMember + let filterVal (v: Val) = not v.IsCompilerGenerated && Option.isNone v.MemberInfo + let filterExtMem (v: Val) = v.IsExtensionMember match x with - | TMDefRec(_,tycons,mbinds,_) -> + | TMDefRec(_, tycons, mbinds, _) -> TastDefinitionPrinting.layoutTyconDefns denv infoReader ad m tycons @@ (mbinds |> List.choose (function ModuleOrNamespaceBinding.Binding bind -> Some bind | _ -> None) @@ -1883,11 +1883,11 @@ module private InferredSigPrinting = |> aboveListL) @@ (mbinds - |> List.choose (function ModuleOrNamespaceBinding.Module (mspec,def) -> Some (mspec,def) | _ -> None) + |> List.choose (function ModuleOrNamespaceBinding.Module (mspec, def) -> Some (mspec, def) | _ -> None) |> List.map (imbindL denv) |> aboveListL) - | TMDefLet(bind,_) -> + | TMDefLet(bind, _) -> ([bind.Var] |> List.filter filterVal |> List.map (PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv) @@ -1922,7 +1922,7 @@ module private InferredSigPrinting = let denv = denv.AddAccessibility mspec.Accessibility let basic = imdefL denv def // Check if its an outer module or a nested module - if (outerPath |> List.forall (fun (_,istype) -> istype = Namespace) ) then + if (outerPath |> List.forall (fun (_, istype) -> istype = Namespace) ) then // OK, this is an outer module if showHeader then // OK, we're not in F# Interactive @@ -1953,33 +1953,33 @@ module private PrintData = and private dataExprWrapL denv isAtomic expr = match expr with - | Expr.Const (c,_,ty) -> + | Expr.Const (c, _, ty) -> if isEnumTy denv.g ty then wordL (tagKeyword "enum") ^^ angleL (layoutType denv ty) ^^ bracketL (layoutConst denv.g ty c) else layoutConst denv.g ty c - | Expr.Val (v,_,_) -> wordL (tagLocal v.DisplayName) + | Expr.Val (v, _, _) -> wordL (tagLocal v.DisplayName) | Expr.Link rX -> dataExprWrapL denv isAtomic (!rX) - | Expr.Op (TOp.UnionCase(c),_,args,_) -> + | Expr.Op (TOp.UnionCase(c), _, args, _) -> if denv.g.unionCaseRefEq c denv.g.nil_ucref then wordL (tagPunctuation "[]") elif denv.g.unionCaseRefEq c denv.g.cons_ucref then - let rec strip = function (Expr.Op (TOp.UnionCase _,_,[h;t],_)) -> h::strip t | _ -> [] + let rec strip = function (Expr.Op (TOp.UnionCase _, _, [h;t], _)) -> h::strip t | _ -> [] listL (dataExprL denv) (strip expr) elif isNil args then wordL (tagUnionCase c.CaseName) else (wordL (tagUnionCase c.CaseName) ++ bracketL (commaListL (dataExprsL denv args))) - | Expr.Op (TOp.ExnConstr(c),_,args,_) -> (wordL (tagMethod c.LogicalName) ++ bracketL (commaListL (dataExprsL denv args))) - | Expr.Op (TOp.Tuple _,_,xs,_) -> tupleL (dataExprsL denv xs) - | Expr.Op (TOp.Recd (_,tc),_,xs,_) -> + | Expr.Op (TOp.ExnConstr(c), _, args, _) -> (wordL (tagMethod c.LogicalName) ++ bracketL (commaListL (dataExprsL denv args))) + | Expr.Op (TOp.Tuple _, _, xs, _) -> tupleL (dataExprsL denv xs) + | Expr.Op (TOp.Recd (_, tc), _, xs, _) -> let fields = tc.TrueInstanceFieldsAsList let lay fs x = (wordL (tagRecordField fs.rfield_id.idText) ^^ sepL (tagPunctuation "=")) --- (dataExprL denv x) leftL (tagPunctuation "{") ^^ semiListL (List.map2 lay fields xs) ^^ rightL (tagPunctuation "}") | Expr.Op (TOp.ValFieldGet (RecdFieldRef.RFRef (tcref, name)), _, _, _) -> (layoutTyconRef denv tcref) ^^ sepL (tagPunctuation ".") ^^ wordL (tagField name) - | Expr.Op (TOp.Array,[_],xs,_) -> leftL (tagPunctuation "[|") ^^ semiListL (dataExprsL denv xs) ^^ RightL.rightBracketBar + | Expr.Op (TOp.Array, [_], xs, _) -> leftL (tagPunctuation "[|") ^^ semiListL (dataExprsL denv xs) ^^ RightL.rightBracketBar | _ -> wordL (tagPunctuation "?") and private dataExprsL denv xs = List.map (dataExprL denv) xs @@ -2046,13 +2046,13 @@ let prettyLayoutOfInstAndSig denv x = PrintTypes.prettyLayoutOfInstAndSig denv x /// If the output text is different without showing constraints and/or imperative type variable /// annotations and/or fully qualifying paths then don't show them! let minimalStringsOfTwoTypes denv t1 t2= - let (t1,t2),tpcs = PrettyTypes.PrettifyTypePair denv.g (t1,t2) + let (t1, t2), tpcs = PrettyTypes.PrettifyTypePair denv.g (t1, t2) // try denv + no type annotations let attempt1 = let denv = { denv with showImperativeTyparAnnotations=false; showConstraintTyparAnnotations=false } let min1 = stringOfTy denv t1 let min2 = stringOfTy denv t2 - if min1 <> min2 then Some (min1,min2,"") else None + if min1 <> min2 then Some (min1, min2, "") else None match attempt1 with | Some res -> res | None -> @@ -2061,7 +2061,7 @@ let minimalStringsOfTwoTypes denv t1 t2= let denv = { denv with showImperativeTyparAnnotations=false; showConstraintTyparAnnotations=false }.SetOpenPaths [] let min1 = stringOfTy denv t1 let min2 = stringOfTy denv t2 - if min1 <> min2 then Some (min1,min2,"") else None + if min1 <> min2 then Some (min1, min2, "") else None // try denv match attempt2 with | Some res -> res @@ -2069,7 +2069,7 @@ let minimalStringsOfTwoTypes denv t1 t2= let attempt3 = let min1 = stringOfTy denv t1 let min2 = stringOfTy denv t2 - if min1 <> min2 then Some (min1,min2,stringOfTyparConstraints denv tpcs) else None + if min1 <> min2 then Some (min1, min2, stringOfTyparConstraints denv tpcs) else None match attempt3 with | Some res -> res | None -> @@ -2079,7 +2079,7 @@ let minimalStringsOfTwoTypes denv t1 t2= let denv = { denv with includeStaticParametersInTypeNames=true } let min1 = stringOfTy denv t1 let min2 = stringOfTy denv t2 - if min1 <> min2 then Some (min1,min2,stringOfTyparConstraints denv tpcs) else None + if min1 <> min2 then Some (min1, min2, stringOfTyparConstraints denv tpcs) else None match attempt4 with | Some res -> res | None -> @@ -2091,7 +2091,7 @@ let minimalStringsOfTwoTypes denv t1 t2= let assemblyName = PrintTypes.layoutAssemblyName denv t |> function | null | "" -> "" | name -> sprintf " (%s)" name sprintf "%s%s" (stringOfTy denv t1) assemblyName - (makeName t1,makeName t2,stringOfTyparConstraints denv tpcs) + (makeName t1, makeName t2, stringOfTyparConstraints denv tpcs) // Note: Always show imperative annotations when comparing value signatures @@ -2100,12 +2100,12 @@ let minimalStringsOfTwoValues denv v1 v2= let min1 = bufs (fun buf -> outputQualifiedValOrMember denvMin buf v1) let min2 = bufs (fun buf -> outputQualifiedValOrMember denvMin buf v2) if min1 <> min2 then - (min1,min2) + (min1, min2) else let denvMax = { denv with showImperativeTyparAnnotations=true; showConstraintTyparAnnotations=true } let max1 = bufs (fun buf -> outputQualifiedValOrMember denvMax buf v1) let max2 = bufs (fun buf -> outputQualifiedValOrMember denvMax buf v2) - max1,max2 + max1, max2 let minimalStringOfType denv ty = let ty, _cxs = PrettyTypes.PrettifyType denv.g ty diff --git a/src/fsharp/Optimizer.fs b/src/fsharp/Optimizer.fs index 51c74b2ae35..ae818cb9e84 100644 --- a/src/fsharp/Optimizer.fs +++ b/src/fsharp/Optimizer.fs @@ -132,7 +132,7 @@ type ValInfos(entries) = let valInfoTable = lazy (let t = ValHash.Create () - for (vref:ValRef, x) in entries do + for (vref: ValRef, x) in entries do t.Add (vref.Deref, (vref, x)) t) @@ -153,9 +153,9 @@ type ValInfos(entries) = member x.Filter f = ValInfos(Seq.filter f x.Entries) - member x.TryFind (v:ValRef) = valInfoTable.Force().TryFind v.Deref + member x.TryFind (v: ValRef) = valInfoTable.Force().TryFind v.Deref - member x.TryFindForFslib (v:ValRef) = valInfosForFslib.Force().TryGetValue(v.Deref.GetLinkagePartialKey()) + member x.TryFindForFslib (v: ValRef) = valInfosForFslib.Force().TryGetValue(v.Deref.GetLinkagePartialKey()) type ModuleInfo = { ValInfos: ValInfos @@ -186,12 +186,12 @@ let rec exprValueInfoL g exprVal = and exprValueInfosL g vinfos = commaListL (List.map (exprValueInfoL g) (Array.toList vinfos)) -and moduleInfoL g (x:LazyModuleInfo) = +and moduleInfoL g (x: LazyModuleInfo) = let x = x.Force() braceL ((wordL (tagText "Modules: ") @@ (x.ModuleOrNamespaceInfos |> namemapL (fun nm x -> wordL (tagText nm) ^^ moduleInfoL g x) ) ) @@ (wordL (tagText "Values:") @@ (x.ValInfos.Entries |> seqL (fun (vref, x) -> valRefL vref ^^ valInfoL g x) ))) -and valInfoL g (x:ValInfo) = +and valInfoL g (x: ValInfo) = braceL ((wordL (tagText "ValExprInfo: ") @@ exprValueInfoL g x.ValExprInfo) @@ (wordL (tagText "ValMakesNoCriticalTailcalls:") @@ wordL (tagText (if x.ValMakesNoCriticalTailcalls then "true" else "false")))) #endif @@ -426,12 +426,12 @@ let rec IsPartialExprVal x = | ValValue (_, a) | SizeValue(_, a) -> IsPartialExprVal a -let CheckInlineValueIsComplete (v:Val) res = +let CheckInlineValueIsComplete (v: Val) res = if v.MustInline && IsPartialExprVal res then errorR(Error(FSComp.SR.optValueMarkedInlineButIncomplete(v.DisplayName), v.Range)) //System.Diagnostics.Debug.Assert(false, sprintf "Break for incomplete inline value %s" v.DisplayName) -let check (vref: ValRef) (res:ValInfo) = +let check (vref: ValRef) (res: ValInfo) = CheckInlineValueIsComplete vref.Deref res.ValExprInfo (vref, res) @@ -462,7 +462,7 @@ let FindOrCreateGlobalModuleInfo n (ss: LayeredMap<_, _>) = | Some res -> res | None -> EmptyModuleInfo -let rec BindValueInSubModuleFSharpCore (mp:string[]) i (v:Val) vval ss = +let rec BindValueInSubModuleFSharpCore (mp: string[]) i (v: Val) vval ss = if i < mp.Length then {ss with ModuleOrNamespaceInfos = BindValueInModuleForFslib mp.[i] mp (i+1) v vval ss.ModuleOrNamespaceInfos } else @@ -482,10 +482,10 @@ let BindValueForFslib (nlvref : NonLocalValOrMemberRef) v vval env = let UnknownValInfo = { ValExprInfo=UnknownValue; ValMakesNoCriticalTailcalls=false } -let mkValInfo info (v:Val) = { ValExprInfo=info.Info; ValMakesNoCriticalTailcalls= v.MakesNoCriticalTailcalls } +let mkValInfo info (v: Val) = { ValExprInfo=info.Info; ValMakesNoCriticalTailcalls= v.MakesNoCriticalTailcalls } (* Bind a value *) -let BindInternalLocalVal cenv (v:Val) vval env = +let BindInternalLocalVal cenv (v: Val) vval env = let vval = if v.IsMutable then UnknownValInfo else vval #if CHECKED #else @@ -496,7 +496,7 @@ let BindInternalLocalVal cenv (v:Val) vval env = cenv.localInternalVals.[v.Stamp] <- vval env -let BindExternalLocalVal cenv (v:Val) vval env = +let BindExternalLocalVal cenv (v: Val) vval env = #if CHECKED CheckInlineValueIsComplete v vval #endif @@ -527,11 +527,11 @@ let BindExternalLocalVal cenv (v:Val) vval env = else env env -let rec BindValsInModuleOrNamespace cenv (mval:LazyModuleInfo) env = +let rec BindValsInModuleOrNamespace cenv (mval: LazyModuleInfo) env = let mval = mval.Force() // do all the sub modules let env = (mval.ModuleOrNamespaceInfos, env) ||> NameMap.foldBackRange (BindValsInModuleOrNamespace cenv) - let env = (env, mval.ValInfos.Entries) ||> Seq.fold (fun env (v:ValRef, vval) -> BindExternalLocalVal cenv v.Deref vval env) + let env = (env, mval.ValInfos.Entries) ||> Seq.fold (fun env (v: ValRef, vval) -> BindExternalLocalVal cenv v.Deref vval env) env let inline BindInternalValToUnknown cenv v env = @@ -553,7 +553,7 @@ let inline BindInternalValsToUnknown cenv vs env = let BindTypeVar tyv typeinfo env = { env with typarInfos= (tyv, typeinfo)::env.typarInfos } -let BindTypeVarsToUnknown (tps:Typar list) env = +let BindTypeVarsToUnknown (tps: Typar list) env = if isNil tps then env else // The optimizer doesn't use the type values it could track. // However here we mutate to provide better names for generalized type parameters @@ -564,11 +564,11 @@ let BindTypeVarsToUnknown (tps:Typar list) env = tp.typar_id <- ident (nm, tp.Range)) List.fold (fun sofar arg -> BindTypeVar arg UnknownTypeValue sofar) env tps -let BindCcu (ccu:Tast.CcuThunk) mval env (_g:TcGlobals) = +let BindCcu (ccu: Tast.CcuThunk) mval env (_g: TcGlobals) = { env with globalModuleInfos=env.globalModuleInfos.Add(ccu.AssemblyName, mval) } /// Lookup information about values -let GetInfoForLocalValue cenv env (v:Val) m = +let GetInfoForLocalValue cenv env (v: Val) m = // Abstract slots do not have values if v.IsDispatchSlot then UnknownValInfo else @@ -585,7 +585,7 @@ let GetInfoForLocalValue cenv env (v:Val) m = #endif UnknownValInfo -let TryGetInfoForCcu env (ccu:CcuThunk) = env.globalModuleInfos.TryFind(ccu.AssemblyName) +let TryGetInfoForCcu env (ccu: CcuThunk) = env.globalModuleInfos.TryFind(ccu.AssemblyName) let TryGetInfoForEntity sv n = match sv.ModuleOrNamespaceInfos.TryFind n with @@ -603,7 +603,7 @@ let TryGetInfoForNonLocalEntityRef env (nleref: NonLocalEntityRef) = | Some ccuinfo -> TryGetInfoForPath (ccuinfo.Force()) nleref.Path 0 | None -> None -let GetInfoForNonLocalVal cenv env (vref:ValRef) = +let GetInfoForNonLocalVal cenv env (vref: ValRef) = if vref.IsDispatchSlot then UnknownValInfo // REVIEW: optionally turn x-module on/off on per-module basis or @@ -628,7 +628,7 @@ let GetInfoForNonLocalVal cenv env (vref:ValRef) = else UnknownValInfo -let GetInfoForVal cenv env m (vref:ValRef) = +let GetInfoForVal cenv env m (vref: ValRef) = let res = if vref.IsLocalRef then GetInfoForLocalValue cenv env vref.binding m @@ -1107,7 +1107,7 @@ let AbstractLazyModulInfoByHiding isAssemblyBoundary mhi = |> Seq.filter (fun (vref, _) -> not (hiddenVal vref.Deref)) |> Seq.map (fun (vref, e) -> check (* "its implementation uses a binding hidden by a signature" m *) vref (abstractValInfo e) )) } - and abstractLazyModulInfo (ss:LazyModuleInfo) = + and abstractLazyModulInfo (ss: LazyModuleInfo) = ss.Force() |> abstractModulInfo |> notlazy abstractLazyModulInfo @@ -1115,7 +1115,7 @@ let AbstractLazyModulInfoByHiding isAssemblyBoundary mhi = /// Hide all information except what we need for "must inline". We always save this optimization information let AbstractOptimizationInfoToEssentials = - let rec abstractModulInfo (ss:ModuleInfo) = + let rec abstractModulInfo (ss: ModuleInfo) = { ModuleOrNamespaceInfos = NameMap.map (Lazy.force >> abstractModulInfo >> notlazy) ss.ModuleOrNamespaceInfos ValInfos = ss.ValInfos.Filter (fun (v, _) -> v.MustInline) } @@ -1124,7 +1124,7 @@ let AbstractOptimizationInfoToEssentials = abstractLazyModulInfo /// Hide information because of a "let ... in ..." or "let rec ... in ... " -let AbstractExprInfoByVars (boundVars:Val list, boundTyVars) ivalue = +let AbstractExprInfoByVars (boundVars: Val list, boundTyVars) ivalue = // Module and member bindings can be skipped when checking abstraction, since abstraction of these values has already been done when // we hit the end of the module and called AbstractLazyModulInfoByHiding. If we don't skip these then we end up quadtratically retraversing // the inferred optimization data, i.e. at each binding all the way up a sequences of 'lets' in a module. @@ -1300,7 +1300,7 @@ let IsDiscardableEffectExpr expr = | _ -> false /// Checks is a value binding is non-discardable -let ValueIsUsedOrHasEffect cenv fvs (b:Binding, binfo) = +let ValueIsUsedOrHasEffect cenv fvs (b: Binding, binfo) = let v = b.Var not (cenv.settings.EliminateUnusedBindings()) || Option.isSome v.MemberInfo || @@ -1572,7 +1572,7 @@ let ExpandStructuralBindingRaw cenv expr = expr (* avoid re-expanding when recursion hits original binding *) else let argTys = destRefTupleTy cenv.g v.Type - let argBind i (arg:Expr) argTy = + let argBind i (arg: Expr) argTy = let name = v.LogicalName + "_" + string i let v, ve = mkCompGenLocal arg.Range name argTy ve, mkCompGenBind v arg @@ -1627,7 +1627,7 @@ let (|AnyInstanceMethodApp|_|) e = | Expr.App(Expr.Val (vref, _, _), _, tyargs, [obj; MaybeRefTupled args], _) -> Some (vref, tyargs, obj, args) | _ -> None -let (|InstanceMethodApp|_|) g (expectedValRef:ValRef) e = +let (|InstanceMethodApp|_|) g (expectedValRef: ValRef) e = match e with | AnyInstanceMethodApp (vref, tyargs, obj, args) when valRefEq g vref expectedValRef -> Some (tyargs, obj, args) | _ -> None @@ -1742,7 +1742,7 @@ let rec tryRewriteToSeqCombinators g (e: Expr) = /// /// We check if the combinators are marked with tag IEnumerable - if do, we optimize the "Run" and quotation away, since RunQueryAsEnumerable simply performs /// an eval. -let TryDetectQueryQuoteAndRun cenv (expr:Expr) = +let TryDetectQueryQuoteAndRun cenv (expr: Expr) = let g = cenv.g match expr with | QueryRun g (bodyOfRun, reqdResultInfo) -> @@ -1757,7 +1757,7 @@ let TryDetectQueryQuoteAndRun cenv (expr:Expr) = // When we find the 'core' of the query expression, then if that is using IEnumerable execution, // try to rewrite the core into combinators approximating the compiled form of seq { ... }, which in turn // are eligible for state-machine representation. If that fails, we still rewrite to combinator form. - let rec loopOuter (e:Expr) = + let rec loopOuter (e: Expr) = match e with | QueryFor g (qTy, _, resultElemTy, _, _) @@ -1820,7 +1820,7 @@ let IsSystemStringConcatArray (methRef: ILMethodRef) = methRef.ArgTypes.Length = 1 && methRef.ArgTypes.Head.BasicQualifiedName = "System.String[]" /// Optimize/analyze an expression -let rec OptimizeExpr cenv (env:IncrementalOptimizationEnv) expr = +let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = // Eliminate subsumption coercions for functions. This must be done post-typechecking because we need // complete inference types. @@ -2435,7 +2435,7 @@ and TryOptimizeValInfo cenv env m vinfo = if vinfo.HasEffect then None else TryOptimizeVal cenv env (false, vinfo.Info , m) /// Add 'v1 = v2' information into the information stored about a value -and AddValEqualityInfo g m (v:ValRef) info = +and AddValEqualityInfo g m (v: ValRef) info = // ValValue is information that v = v2, where v2 does not change // So we can't record this information for mutable values. An exception can be made // for "outArg" values arising from method calls since they are only temporarily mutable @@ -2446,7 +2446,7 @@ and AddValEqualityInfo g m (v:ValRef) info = {info with Info= MakeValueInfoForValue g m v info.Info} /// Optimize/analyze a use of a value -and OptimizeVal cenv env expr (v:ValRef, m) = +and OptimizeVal cenv env expr (v: ValRef, m) = let valInfoForVal = GetInfoForVal cenv env m v match TryOptimizeVal cenv env (v.MustInline, valInfoForVal.ValExprInfo, m) with @@ -2494,7 +2494,7 @@ and CanDevirtualizeApplication cenv v vref ty args = // Hence we have to actually have the object argument available to us, && (not (isStructTy cenv.g ty) || not (isNil args)) -and TakeAddressOfStructArgumentIfNeeded cenv (vref:ValRef) ty args m = +and TakeAddressOfStructArgumentIfNeeded cenv (vref: ValRef) ty args m = if vref.IsInstanceMember && isStructTy cenv.g ty then match args with | objArg::rest -> @@ -2510,7 +2510,7 @@ and TakeAddressOfStructArgumentIfNeeded cenv (vref:ValRef) ty args m = else id, args -and DevirtualizeApplication cenv env (vref:ValRef) ty tyargs args m = +and DevirtualizeApplication cenv env (vref: ValRef) ty tyargs args m = let wrap, args = TakeAddressOfStructArgumentIfNeeded cenv vref ty args m let transformedExpr = wrap (MakeApplicationAndBetaReduce cenv.g (exprForValRef m vref, vref.Type, (if isNil tyargs then [] else [tyargs]), args, m)) OptimizeExpr cenv env transformedExpr @@ -2522,8 +2522,8 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = // to be augmented with a visible comparison value. // // e.g rewrite - // 'LanguagePrimitives.HashCompare.GenericComparisonIntrinsic (x:C) (y:C)' - // --> 'x.CompareTo(y:C)' where this is a direct call to the implementation of CompareTo, i.e. + // 'LanguagePrimitives.HashCompare.GenericComparisonIntrinsic (x: C) (y: C)' + // --> 'x.CompareTo(y: C)' where this is a direct call to the implementation of CompareTo, i.e. // C::CompareTo(C) // not C::CompareTo(obj) // @@ -2965,7 +2965,7 @@ and OptimizeExprThenConsiderSplit cenv env e = ConsiderSplitToMethod true cenv.settings.veryBigExprSize cenv env (eR, einfo) /// Decide whether to List.unzip a sub-expression into a new method -and ComputeSplitToMethodCondition flag threshold cenv env (e:Expr, einfo) = +and ComputeSplitToMethodCondition flag threshold cenv env (e: Expr, einfo) = flag && // REVIEW: The method splitting optimization is completely disabled if we are not taking tailcalls. // REVIEW: This should only apply to methods that actually make self-tailcalls (tested further below). @@ -3270,7 +3270,7 @@ and OptimizeModuleExpr cenv env x = // // It may be wise to move to a non-mutating implementation at some point here. Copying expressions is // probably more costly than copying specs anyway. - let rec elimModTy (mtyp:ModuleOrNamespaceType) = + let rec elimModTy (mtyp: ModuleOrNamespaceType) = let mty = new ModuleOrNamespaceType(kind=mtyp.ModuleOrNamespaceKind, vals= (mtyp.AllValsAndMembers |> QueueList.filter (Zset.memberOf deadSet >> not)), @@ -3278,7 +3278,7 @@ and OptimizeModuleExpr cenv env x = mtyp.ModuleAndNamespaceDefinitions |> List.iter elimModSpec mty - and elimModSpec (mspec:ModuleOrNamespace) = + and elimModSpec (mspec: ModuleOrNamespace) = let mtyp = elimModTy mspec.ModuleOrNamespaceType mspec.entity_modul_contents <- MaybeLazy.Strict mtyp @@ -3309,7 +3309,7 @@ and OptimizeModuleExpr cenv env x = ModuleOrNamespaceExprWithSig(mty, def, m), info -and mkValBind (bind:Binding) info = +and mkValBind (bind: Binding) info = (mkLocalValRef bind.Var, info) and OptimizeModuleDef cenv (env, bindInfosColl) x = @@ -3435,7 +3435,7 @@ let rec p_ExprValueInfo x st = | SizeValue (_adepth, a) -> p_ExprValueInfo a st -and p_ValInfo (v:ValInfo) st = +and p_ValInfo (v: ValInfo) st = p_ExprValueInfo v.ValExprInfo st p_bool v.ValMakesNoCriticalTailcalls st diff --git a/src/fsharp/PatternMatchCompilation.fs b/src/fsharp/PatternMatchCompilation.fs index f2284068c06..ee310acddfb 100644 --- a/src/fsharp/PatternMatchCompilation.fs +++ b/src/fsharp/PatternMatchCompilation.fs @@ -836,7 +836,7 @@ let CompilePatternBasic // The main recursive loop of the pattern match compiler let rec InvestigateFrontiers refuted frontiers = match frontiers with - | [] -> failwith "CompilePattern:compile - empty clauses: at least the final clause should always succeed" + | [] -> failwith "CompilePattern: compile - empty clauses: at least the final clause should always succeed" | (Frontier (i, active, valMap)) :: rest -> // Check to see if we've got a succeeding clause. There may still be a 'when' condition for the clause @@ -1315,7 +1315,7 @@ let CompilePatternBasic dtree, targets -let isPartialOrWhenClause (c:TypedMatchClause) = isPatternPartial c.Pattern || c.GuardExpr.IsSome +let isPartialOrWhenClause (c: TypedMatchClause) = isPatternPartial c.Pattern || c.GuardExpr.IsSome let rec CompilePattern g denv amap exprm matchm warnOnUnused actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) (clausesL: TypedMatchClause list) inputTy resultTy = diff --git a/src/fsharp/PostInferenceChecks.fs b/src/fsharp/PostInferenceChecks.fs index f691f4f0b9e..a91473b6880 100644 --- a/src/fsharp/PostInferenceChecks.fs +++ b/src/fsharp/PostInferenceChecks.fs @@ -95,12 +95,12 @@ type env = /// Are we in an app expression (Expr.App)? isInAppExpr: bool } -let BindTypar env (tp:Typar) = +let BindTypar env (tp: Typar) = { env with boundTyparNames = tp.Name :: env.boundTyparNames boundTypars = env.boundTypars.Add (tp, ()) } -let BindTypars g env (tps:Typar list) = +let BindTypars g env (tps: Typar list) = let tps = NormalizeDeclaredTyparsForEquiRecursiveInference g tps if isNil tps then env else // Here we mutate to provide better names for generalized type parameters @@ -198,7 +198,7 @@ type cenv = isInternalTestSpanStackReferring: bool // outputs mutable usesQuotations : bool - mutable entryPointGiven:bool } + mutable entryPointGiven: bool } /// Check if the value is an argument of a function let IsValArgument env (v: Val) = @@ -262,10 +262,10 @@ let GetLimitValByRef cenv env m v = { scope = scope; flags = flags } -let LimitVal cenv (v:Val) limit = +let LimitVal cenv (v: Val) limit = cenv.limitVals.[v.Stamp] <- limit -let BindVal cenv env (v:Val) = +let BindVal cenv env (v: Val) = //printfn "binding %s..." v.DisplayName let alreadyDone = cenv.boundVals.ContainsKey v.Stamp cenv.boundVals.[v.Stamp] <- 1 @@ -439,7 +439,7 @@ let AccessInternalsVisibleToAsInternal thisCompPath internalsVisibleToPaths acce accessSubstPaths (thisCompPath, internalsVisibleToPath) access) -let CheckTypeForAccess (cenv:cenv) env objName valAcc m ty = +let CheckTypeForAccess (cenv: cenv) env objName valAcc m ty = if cenv.reportErrors then let visitType ty = @@ -455,7 +455,7 @@ let CheckTypeForAccess (cenv:cenv) env objName valAcc m ty = CheckTypeDeep cenv (visitType, None, None, None, None) cenv.g env false ty -let WarnOnWrongTypeForAccess (cenv:cenv) env objName valAcc m ty = +let WarnOnWrongTypeForAccess (cenv: cenv) env objName valAcc m ty = if cenv.reportErrors then let visitType ty = @@ -533,7 +533,7 @@ let mkArgsPermit n = else PermitByRefExpr.YesTupleOfArgs n /// Work out what byref-values are allowed at input positions to named F# functions or members -let mkArgsForAppliedVal isBaseCall (vref:ValRef) argsl = +let mkArgsForAppliedVal isBaseCall (vref: ValRef) argsl = match vref.ValReprInfo with | Some topValInfo -> let argArities = topValInfo.AritiesOfArgs @@ -557,7 +557,7 @@ let rec mkArgsForAppliedExpr isBaseCall argsl x = | _ -> [] /// Check types occurring in the TAST. -let CheckTypeAux permitByRefLike (cenv:cenv) env m ty onInnerByrefError = +let CheckTypeAux permitByRefLike (cenv: cenv) env m ty onInnerByrefError = if cenv.reportErrors then let visitTyar (env, tp) = if not (env.boundTypars.ContainsKey tp) then @@ -609,13 +609,13 @@ let CheckType permitByRefLike cenv env m ty = /// Check types occurring in TAST (like CheckType) and additionally reject any byrefs. /// The additional byref checks are to catch "byref instantiations" - one place were byref are not permitted. -let CheckTypeNoByrefs (cenv:cenv) env m ty = CheckType PermitByRefType.None cenv env m ty +let CheckTypeNoByrefs (cenv: cenv) env m ty = CheckType PermitByRefType.None cenv env m ty /// Check types occurring in TAST but allow a Span or similar -let CheckTypePermitSpanLike (cenv:cenv) env m ty = CheckType PermitByRefType.SpanLike cenv env m ty +let CheckTypePermitSpanLike (cenv: cenv) env m ty = CheckType PermitByRefType.SpanLike cenv env m ty /// Check types occurring in TAST but allow all byrefs. Only used on internally-generated types -let CheckTypePermitAllByrefs (cenv:cenv) env m ty = CheckType PermitByRefType.All cenv env m ty +let CheckTypePermitAllByrefs (cenv: cenv) env m ty = CheckType PermitByRefType.All cenv env m ty /// Check types ocurring in TAST but disallow inner types to be byref or byref-like types. let CheckTypeNoInnerByrefs cenv env m ty = CheckType PermitByRefType.NoInnerByRefLike cenv env m ty @@ -635,7 +635,7 @@ let (|OptionalCoerce|) = function | x -> x /// Check an expression doesn't contain a 'reraise' -let CheckNoReraise cenv freesOpt (body:Expr) = +let CheckNoReraise cenv freesOpt (body: Expr) = if cenv.reportErrors then // Avoid recomputing the free variables let fvs = match freesOpt with None -> freeInExpr CollectLocals body | Some fvs -> fvs @@ -668,7 +668,7 @@ let rec CheckExprNoByrefs cenv env expr = CheckExpr cenv env expr PermitByRefExpr.No |> ignore /// Check a value -and CheckValRef (cenv:cenv) (env:env) v m (context: PermitByRefExpr) = +and CheckValRef (cenv: cenv) (env: env) v m (context: PermitByRefExpr) = if cenv.reportErrors then if isSpliceOperator cenv.g v && not env.quote then errorR(Error(FSComp.SR.chkSplicingOnlyInQuotations(), m)) @@ -736,7 +736,7 @@ and CheckValUse (cenv: cenv) (env: env) (vref: ValRef, vFlags, m) (context: Perm limit /// Check an expression, given information about the position of the expression -and CheckForOverAppliedExceptionRaisingPrimitive (cenv:cenv) expr = +and CheckForOverAppliedExceptionRaisingPrimitive (cenv: cenv) expr = let g = cenv.g let expr = stripExpr expr @@ -863,7 +863,7 @@ and CheckCallWithReceiver cenv env m returnTy args contexts context = limitArgs CheckCallLimitArgs cenv env m returnTy limitArgs context -and CheckExprLinear (cenv:cenv) (env:env) expr (context:PermitByRefExpr) (contf : Limit -> Limit) = +and CheckExprLinear (cenv: cenv) (env: env) expr (context: PermitByRefExpr) (contf : Limit -> Limit) = match expr with | Expr.Sequential (e1, e2, NormalSeq, _, _) -> CheckExprNoByrefs cenv env e1 @@ -903,7 +903,7 @@ and CheckExprLinear (cenv:cenv) (env:env) expr (context:PermitByRefExpr) (contf contf (CheckExpr cenv env expr context) /// Check an expression, given information about the position of the expression -and CheckExpr (cenv:cenv) (env:env) origExpr (context:PermitByRefExpr) : Limit = +and CheckExpr (cenv: cenv) (env: env) origExpr (context: PermitByRefExpr) : Limit = let g = cenv.g let origExpr = stripExpr origExpr @@ -1626,7 +1626,7 @@ and CheckValInfo cenv env (ValReprInfo(_, args, ret)) = and CheckArgInfo cenv env (argInfo : ArgReprInfo) = CheckAttribs cenv env argInfo.Attribs -and CheckValSpecAux permitByRefLike cenv env (v:Val) onInnerByrefError = +and CheckValSpecAux permitByRefLike cenv env (v: Val) onInnerByrefError = v.Attribs |> CheckAttribs cenv env v.ValReprInfo |> Option.iter (CheckValInfo cenv env) CheckTypeAux permitByRefLike cenv env v.Range v.Type onInnerByrefError @@ -1880,7 +1880,7 @@ let CheckModuleBindings cenv env binds = // check tycons //-------------------------------------------------------------------------- -let CheckRecdField isUnion cenv env (tycon:Tycon) (rfield:RecdField) = +let CheckRecdField isUnion cenv env (tycon: Tycon) (rfield: RecdField) = let g = cenv.g let tcref = mkLocalTyconRef tycon let m = rfield.Range @@ -1905,7 +1905,7 @@ let CheckRecdField isUnion cenv env (tycon:Tycon) (rfield:RecdField) = CheckAttribs cenv env rfield.PropertyAttribs CheckAttribs cenv env rfield.FieldAttribs -let CheckEntityDefn cenv env (tycon:Entity) = +let CheckEntityDefn cenv env (tycon: Entity) = #if !NO_EXTENSIONTYPING if not tycon.IsProvidedGeneratedTycon then #endif @@ -1935,7 +1935,7 @@ let CheckEntityDefn cenv env (tycon:Entity) = | None -> [] let namesOfMethodsThatMayDifferOnlyInReturnType = ["op_Explicit";"op_Implicit"] (* hardwired *) - let methodUniquenessIncludesReturnType (minfo:MethInfo) = List.contains minfo.LogicalName namesOfMethodsThatMayDifferOnlyInReturnType + let methodUniquenessIncludesReturnType (minfo: MethInfo) = List.contains minfo.LogicalName namesOfMethodsThatMayDifferOnlyInReturnType let MethInfosEquivWrtUniqueness eraseFlag m minfo minfo2 = if methodUniquenessIncludesReturnType minfo then MethInfosEquivByNameAndSig eraseFlag true g cenv.amap m minfo minfo2 @@ -1947,7 +1947,7 @@ let CheckEntityDefn cenv env (tycon:Entity) = let immediateProps = GetImmediateIntrinsicPropInfosOfType (None, AccessibleFromSomewhere) g cenv.amap m ty - let getHash (hash:Dictionary) nm = + let getHash (hash: Dictionary) nm = match hash.TryGetValue(nm) with | true, h -> h | _ -> [] @@ -1978,9 +1978,9 @@ let CheckEntityDefn cenv env (tycon:Entity) = let m = (match minfo.ArbitraryValRef with None -> m | Some vref -> vref.DefinitionRange) let others = getOtherMethods minfo // abstract/default pairs of duplicate methods are OK - let IsAbstractDefaultPair (x:MethInfo) (y:MethInfo) = + let IsAbstractDefaultPair (x: MethInfo) (y: MethInfo) = x.IsDispatchSlot && y.IsDefiniteFSharpOverride - let IsAbstractDefaultPair2 (minfo:MethInfo) (minfo2:MethInfo) = + let IsAbstractDefaultPair2 (minfo: MethInfo) (minfo2: MethInfo) = IsAbstractDefaultPair minfo minfo2 || IsAbstractDefaultPair minfo2 minfo let checkForDup erasureFlag (minfo2: MethInfo) = not (IsAbstractDefaultPair2 minfo minfo2) @@ -2047,7 +2047,7 @@ let CheckEntityDefn cenv env (tycon:Entity) = let checkForDup erasureFlag pinfo2 = // abstract/default pairs of duplicate properties are OK - let IsAbstractDefaultPair (x:PropInfo) (y:PropInfo) = + let IsAbstractDefaultPair (x: PropInfo) (y: PropInfo) = x.IsDispatchSlot && y.IsDefiniteFSharpOverride not (IsAbstractDefaultPair pinfo pinfo2 || IsAbstractDefaultPair pinfo2 pinfo) @@ -2092,7 +2092,7 @@ let CheckEntityDefn cenv env (tycon:Entity) = let nm = minfo.LogicalName let m = (match minfo.ArbitraryValRef with None -> m | Some vref -> vref.DefinitionRange) let parentMethsOfSameName = getHash hashOfAllVirtualMethsInParent nm - let checkForDup erasureFlag (minfo2:MethInfo) = minfo2.IsDispatchSlot && MethInfosEquivByNameAndSig erasureFlag true g cenv.amap m minfo minfo2 + let checkForDup erasureFlag (minfo2: MethInfo) = minfo2.IsDispatchSlot && MethInfosEquivByNameAndSig erasureFlag true g cenv.amap m minfo minfo2 match parentMethsOfSameName |> List.tryFind (checkForDup EraseAll) with | None -> () | Some minfo -> @@ -2256,7 +2256,7 @@ and CheckModuleSpec cenv env x = let env = { env with reflect = env.reflect || HasFSharpAttribute cenv.g cenv.g.attrib_ReflectedDefinitionAttribute mspec.Attribs } CheckDefnInModule cenv env rhs -let CheckTopImpl (g, amap, reportErrors, infoReader, internalsVisibleToPaths, viewCcu, denv , mexpr, extraAttribs, (isLastCompiland:bool*bool), isInternalTestSpanStackReferring) = +let CheckTopImpl (g, amap, reportErrors, infoReader, internalsVisibleToPaths, viewCcu, denv , mexpr, extraAttribs, (isLastCompiland: bool*bool), isInternalTestSpanStackReferring) = let cenv = { g =g reportErrors=reportErrors diff --git a/src/fsharp/PrettyNaming.fs b/src/fsharp/PrettyNaming.fs index 3935542a046..4c11b9054d3 100755 --- a/src/fsharp/PrettyNaming.fs +++ b/src/fsharp/PrettyNaming.fs @@ -59,8 +59,8 @@ module public FSharp.Compiler.PrettyNaming ("&&", "op_BooleanAnd") ("||", "op_BooleanOr") ("<=", "op_LessThanOrEqual") - ("=","op_Equality") - ("<>","op_Inequality") + ("=", "op_Equality") + ("<>", "op_Inequality") (">=", "op_GreaterThanOrEqual") ("<", "op_LessThan") (">", "op_GreaterThan") @@ -119,7 +119,7 @@ module public FSharp.Compiler.PrettyNaming /// The set of characters usable in custom operators. let private opCharSet = let t = new HashSet<_>() - for (c,_) in opCharTranslateTable do + for (c, _) in opCharTranslateTable do t.Add(c) |> ignore t @@ -139,7 +139,7 @@ module public FSharp.Compiler.PrettyNaming // there is single operator containing a space - range operator with step: `.. ..` name = ".. .." || name |> Seq.forall (fun c -> c <> ' ' && opCharSet.Contains c) - let IsMangledOpName (n:string) = + let IsMangledOpName (n: string) = n.StartsWithOrdinal(opNamePrefix) /// Compiles a custom operator into a mangled operator name. @@ -167,7 +167,7 @@ module public FSharp.Compiler.PrettyNaming fun opp -> // Has this operator already been compiled? - compiledOperators.GetOrAdd(opp, fun (op:string) -> + compiledOperators.GetOrAdd(opp, fun (op: string) -> let opLength = op.Length let sb = new Text.StringBuilder (opNamePrefix, opNamePrefix.Length + (opLength * maxOperatorNameLength)) for i = 0 to opLength - 1 do @@ -281,7 +281,7 @@ module public FSharp.Compiler.PrettyNaming let standardOps = let ops = Dictionary (opNameTable.Length, StringComparer.Ordinal) for x, y in opNameTable do - ops.Add(y,x) + ops.Add(y, x) ops fun opName -> @@ -459,18 +459,18 @@ module public FSharp.Compiler.PrettyNaming let [] private compilerGeneratedMarkerChar = '@' - let IsCompilerGeneratedName (nm:string) = + let IsCompilerGeneratedName (nm: string) = nm.IndexOf compilerGeneratedMarkerChar <> -1 let CompilerGeneratedName nm = if IsCompilerGeneratedName nm then nm else nm+compilerGeneratedMarker - let GetBasicNameOfPossibleCompilerGeneratedName (name:string) = + let GetBasicNameOfPossibleCompilerGeneratedName (name: string) = match name.IndexOf(compilerGeneratedMarker, StringComparison.Ordinal) with | -1 | 0 -> name | n -> name.[0..n-1] - let CompilerGeneratedNameSuffix (basicName:string) suffix = + let CompilerGeneratedNameSuffix (basicName: string) suffix = basicName+compilerGeneratedMarker+suffix @@ -480,7 +480,7 @@ module public FSharp.Compiler.PrettyNaming let [] private mangledGenericTypeNameSym = '`' - let TryDemangleGenericNameAndPos (n:string) = + let TryDemangleGenericNameAndPos (n: string) = (* check what comes after the symbol is a number *) let pos = n.LastIndexOf mangledGenericTypeNameSym if pos = -1 then ValueNone else @@ -498,20 +498,20 @@ module public FSharp.Compiler.PrettyNaming type NameArityPair = NameArityPair of string * int - let DecodeGenericTypeName pos (mangledName:string) = - let res = mangledName.Substring(0,pos) - let num = mangledName.Substring(pos+1,mangledName.Length - pos - 1) + let DecodeGenericTypeName pos (mangledName: string) = + let res = mangledName.Substring(0, pos) + let num = mangledName.Substring(pos+1, mangledName.Length - pos - 1) NameArityPair(res, int32 num) - let DemangleGenericTypeNameWithPos pos (mangledName:string) = - mangledName.Substring(0,pos) + let DemangleGenericTypeNameWithPos pos (mangledName: string) = + mangledName.Substring(0, pos) - let DemangleGenericTypeName (mangledName:string) = + let DemangleGenericTypeName (mangledName: string) = match TryDemangleGenericNameAndPos mangledName with | ValueSome pos -> DemangleGenericTypeNameWithPos pos mangledName | _ -> mangledName - let private chopStringTo (s:string) (c:char) = + let private chopStringTo (s: string) (c: char) = match s.IndexOf c with | -1 -> s | idx -> @@ -547,7 +547,7 @@ module public FSharp.Compiler.PrettyNaming /// Return a string array delimited by the given separator. /// Note that a quoted string is not going to be mangled into pieces. let inline private isNotQuotedQuotation (text: string) n = n > 0 && text.[n-1] <> '\\' - let private splitAroundQuotation (text:string) (separator:char) = + let private splitAroundQuotation (text: string) (separator: char) = let length = text.Length let result = ResizeArray() let mutable insideQuotation = false @@ -574,7 +574,7 @@ module public FSharp.Compiler.PrettyNaming /// Return a string array delimited by the given separator up to the maximum number. /// Note that a quoted string is not going to be mangled into pieces. - let private splitAroundQuotationWithCount (text:string) (separator:char) (count:int)= + let private splitAroundQuotationWithCount (text: string) (separator: char) (count: int)= if count <= 1 then [| text |] else let mangledText = splitAroundQuotation text separator match mangledText.Length > count with @@ -588,7 +588,7 @@ module public FSharp.Compiler.PrettyNaming let IllegalCharactersInTypeAndNamespaceNames = [| '.'; '+'; '$'; '&'; '['; ']'; '/'; '\\'; '*'; '\"'; '`' |] /// Determines if the specified name is a valid name for an active pattern. - let IsActivePatternName (nm:string) = + let IsActivePatternName (nm: string) = let nameLen = nm.Length // The name must start and end with '|' (nm.IndexOf '|' = 0) && @@ -612,19 +612,19 @@ module public FSharp.Compiler.PrettyNaming type ActivePatternInfo = | APInfo of bool * (string * Range.range) list * Range.range - member x.IsTotal = let (APInfo(p,_,_)) = x in p + member x.IsTotal = let (APInfo(p, _, _)) = x in p - member x.ActiveTags = let (APInfo(_,tags,_)) = x in List.map fst tags + member x.ActiveTags = let (APInfo(_, tags, _)) = x in List.map fst tags - member x.ActiveTagsWithRanges = let (APInfo(_,tags,_)) = x in tags + member x.ActiveTagsWithRanges = let (APInfo(_, tags, _)) = x in tags - member x.Range = let (APInfo(_,_,m)) = x in m + member x.Range = let (APInfo(_, _, m)) = x in m - let ActivePatternInfoOfValName nm (m:Range.range) = + let ActivePatternInfoOfValName nm (m: Range.range) = // Note: The approximate range calculations in this code assume the name is of the form "(|A|B|)" not "(| A | B |)" // The ranges are used for IDE refactoring support etc. If names of the second type are used, // renaming may be inaccurate/buggy. However names of the first form are dominant in F# code. - let rec loop (nm:string) (mp:Range.range) = + let rec loop (nm: string) (mp: Range.range) = let n = nm.IndexOf '|' if n > 0 then let m1 = Range.mkRange mp.FileName mp.Start (Range.mkPos mp.StartLine (mp.StartColumn + n)) @@ -638,31 +638,31 @@ module public FSharp.Compiler.PrettyNaming // Skip the '|' at each end when recovering ranges let m0 = Range.mkRange m.FileName (Range.mkPos m.StartLine (m.StartColumn + 1)) (Range.mkPos m.EndLine (m.EndColumn - 1)) let names = loop nm.[1..nm.Length-2] m0 - let resH,resT = List.frontAndBack names - Some(if fst resT = "_" then APInfo(false,resH,m) else APInfo(true,names,m)) + let resH, resT = List.frontAndBack names + Some(if fst resT = "_" then APInfo(false, resH, m) else APInfo(true, names, m)) else None - let private mangleStaticStringArg (nm:string,v:string) = + let private mangleStaticStringArg (nm: string, v: string) = nm + "=" + "\"" + v.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"" - let private tryDemangleStaticStringArg (mangledText:string) = + let private tryDemangleStaticStringArg (mangledText: string) = match splitAroundQuotationWithCount mangledText '=' 2 with | [| nm; v |] -> if v.Length >= 2 then - Some(nm,v.[1..v.Length-2].Replace("\\\\","\\").Replace("\\\"","\"")) + Some(nm, v.[1..v.Length-2].Replace("\\\\", "\\").Replace("\\\"", "\"")) else - Some(nm,v) + Some(nm, v) | _ -> None exception InvalidMangledStaticArg of string /// Demangle the static parameters - let demangleProvidedTypeName (typeLogicalName:string) = + let demangleProvidedTypeName (typeLogicalName: string) = if typeLogicalName.Contains "," then let pieces = splitAroundQuotation typeLogicalName ',' match pieces with - | [| x; "" |] -> x, [| |] + | [| x; "" |] -> x, [| |] | _ -> let argNamesAndValues = pieces.[1..] |> Array.choose tryDemangleStaticStringArg if argNamesAndValues.Length = (pieces.Length - 1) then @@ -688,7 +688,7 @@ module public FSharp.Compiler.PrettyNaming /// Mangle the static parameters for a provided type or method let computeMangledNameWithoutDefaultArgValues(nm, staticArgs, defaultArgValues) = let nonDefaultArgs = - (staticArgs,defaultArgValues) + (staticArgs, defaultArgValues) ||> Array.zip |> Array.choose (fun (staticArg, (defaultArgName, defaultArgValue)) -> let actualArgValue = string staticArg diff --git a/src/fsharp/QuotationTranslator.fs b/src/fsharp/QuotationTranslator.fs index 6deca36555e..bd157c6ecc2 100644 --- a/src/fsharp/QuotationTranslator.fs +++ b/src/fsharp/QuotationTranslator.fs @@ -97,14 +97,14 @@ type QuotationTranslationEnv = isinstVals = ValMap<_>.Empty substVals = ValMap<_>.Empty } - member env.BindTypar (v:Typar) = + member env.BindTypar (v: Typar) = let idx = env.tyvs.Count { env with tyvs = env.tyvs.Add(v.Stamp, idx ) } member env.BindTypars vs = (env, vs) ||> List.fold (fun env v -> env.BindTypar v) // fold left-to-right because indexes are left-to-right -let BindFormalTypars (env:QuotationTranslationEnv) vs = +let BindFormalTypars (env: QuotationTranslationEnv) vs = { env with tyvs = Map.empty }.BindTypars vs let BindVal env v = @@ -285,7 +285,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. ConvExpr cenv env (MakeApplicationAndBetaReduce cenv.g (expr, exprty, [tyargs], curriedArgs, m)) else // Too many arguments? Chop - let (curriedArgs:Expr list ), laterArgs = List.splitAt nCurriedArgInfos curriedArgs + let (curriedArgs: Expr list ), laterArgs = List.splitAt nCurriedArgInfos curriedArgs let callR = // We now have the right number of arguments, w.r.t. currying and tupling. @@ -322,7 +322,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. ConvModuleValueApp cenv env m vref tyargs untupledCurriedArgs match curriedArgs, curriedArgInfos with // static member and module value unit argument elimination - | [arg:Expr], [[]] -> + | [arg: Expr], [[]] -> // we got here if quotation is represents a call with unit argument // let f () = () // <@ f @> // => (\arg -> f arg) => arg is Expr.Val - no-effects, first case @@ -732,10 +732,10 @@ and ConvObjectModelCallCore cenv env m (isPropGet, isPropSet, isNewObj, parentTy numGenericArgs = numGenericArgs } QP.mkMethodCall(methR, tyargsR, callArgsR) -and ConvModuleValueApp cenv env m (vref:ValRef) tyargs (args: Expr list list) = +and ConvModuleValueApp cenv env m (vref: ValRef) tyargs (args: Expr list list) = EmitDebugInfoIfNecessary cenv env m (ConvModuleValueAppCore cenv env m vref tyargs args) -and ConvModuleValueAppCore cenv env m (vref:ValRef) tyargs (args: Expr list list) = +and ConvModuleValueAppCore cenv env m (vref: ValRef) tyargs (args: Expr list list) = match vref.DeclaringEntity with | ParentNone -> failwith "ConvModuleValueApp" | Parent(tcref) -> @@ -749,10 +749,10 @@ and ConvModuleValueAppCore cenv env m (vref:ValRef) tyargs (args: Expr list list and ConvExprs cenv env args = List.map (ConvExpr cenv env) args -and ConvValRef holeOk cenv env m (vref:ValRef) tyargs = +and ConvValRef holeOk cenv env m (vref: ValRef) tyargs = EmitDebugInfoIfNecessary cenv env m (ConvValRefCore holeOk cenv env m vref tyargs) -and private ConvValRefCore holeOk cenv env m (vref:ValRef) tyargs = +and private ConvValRefCore holeOk cenv env m (vref: ValRef) tyargs = let v = vref.Deref if env.isinstVals.ContainsVal v then let (ty, e) = env.isinstVals.[v] @@ -777,7 +777,7 @@ and private ConvValRefCore holeOk cenv env m (vref:ValRef) tyargs = | Parent _ -> ConvModuleValueApp cenv env m vref tyargs [] -and ConvUnionCaseRef cenv (ucref:UnionCaseRef) m = +and ConvUnionCaseRef cenv (ucref: UnionCaseRef) m = let ucgtypR = ConvTyconRef cenv ucref.TyconRef m let nm = if cenv.g.unionCaseRefEq ucref cenv.g.cons_ucref then "Cons" @@ -785,7 +785,7 @@ and ConvUnionCaseRef cenv (ucref:UnionCaseRef) m = else ucref.CaseName (ucgtypR, nm) -and ConvRecdFieldRef cenv (rfref:RecdFieldRef) m = +and ConvRecdFieldRef cenv (rfref: RecdFieldRef) m = let typR = ConvTyconRef cenv rfref.TyconRef m let nm = if useGenuineField rfref.TyconRef.Deref rfref.RecdField then @@ -794,11 +794,11 @@ and ConvRecdFieldRef cenv (rfref:RecdFieldRef) m = rfref.FieldName (typR, nm) -and ConvVal cenv env (v:Val) = +and ConvVal cenv env (v: Val) = let tyR = ConvType cenv env v.Range v.Type QP.freshVar (v.CompiledName, tyR, v.IsMutable) -and ConvTyparRef cenv env m (tp:Typar) = +and ConvTyparRef cenv env m (tp: Typar) = match env.tyvs.TryFind tp.Stamp with | Some x -> x | None -> @@ -944,7 +944,7 @@ and ConvDecisionTree cenv env tgs typR x = // Check if this is an provider-generated assembly that will be statically linked -and IsILTypeRefStaticLinkLocal cenv m (tr:ILTypeRef) = +and IsILTypeRefStaticLinkLocal cenv m (tr: ILTypeRef) = ignore cenv; ignore m match tr.Scope with #if !NO_EXTENSIONTYPING @@ -964,14 +964,14 @@ and IsILTypeRefStaticLinkLocal cenv m (tr:ILTypeRef) = | _ -> false // Adjust for static linking information, then convert -and ConvILTypeRefUnadjusted cenv m (tr:ILTypeRef) = +and ConvILTypeRefUnadjusted cenv m (tr: ILTypeRef) = let trefAdjusted = if IsILTypeRefStaticLinkLocal cenv m tr then ILTypeRef.Create(ILScopeRef.Local, tr.Enclosing, tr.Name) else tr ConvILTypeRef cenv trefAdjusted -and ConvILTypeRef cenv (tr:ILTypeRef) = +and ConvILTypeRef cenv (tr: ILTypeRef) = match cenv.quotationFormat with | QuotationSerializationFormat.FSharp_40_Plus -> let idx = @@ -1007,14 +1007,14 @@ and ConvILType cenv env m ty = #if !NO_EXTENSIONTYPING -and TryElimErasableTyconRef cenv m (tcref:TyconRef) = +and TryElimErasableTyconRef cenv m (tcref: TyconRef) = match tcref.TypeReprInfo with // Get the base type | TProvidedTypeExtensionPoint info when info.IsErased -> Some (info.BaseTypeForErased (m, cenv.g.obj_ty)) | _ -> None #endif -and ConvTyconRef cenv (tcref:TyconRef) m = +and ConvTyconRef cenv (tcref: TyconRef) m = #if !NO_EXTENSIONTYPING match TryElimErasableTyconRef cenv m tcref with | Some baseTy -> ConvTyconRef cenv (tcrefOfAppTy cenv.g baseTy) m @@ -1052,7 +1052,7 @@ let ConvExprPublic cenv env e = astExpr -let ConvMethodBase cenv env (methName, v:Val) = +let ConvMethodBase cenv env (methName, v: Val) = let m = v.Range let parentTyconR = ConvTyconRef cenv v.TopValDeclaringEntity m diff --git a/src/fsharp/SignatureConformance.fs b/src/fsharp/SignatureConformance.fs index a162a951595..b22de20da1b 100644 --- a/src/fsharp/SignatureConformance.fs +++ b/src/fsharp/SignatureConformance.fs @@ -49,7 +49,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = // b. If an attribute is found in ASig that has the same attribute type, then a warning is given and the attribute in the implementation is ignored // c. Otherwise, the attribute in the implementation is kept // (c) The attributes appearing in the compiled element are the compiled forms of the attributes from the signature and the kept attributes from the implementation - let checkAttribs _aenv (implAttribs:Attribs) (sigAttribs:Attribs) fixup = + let checkAttribs _aenv (implAttribs: Attribs) (sigAttribs: Attribs) fixup = // Remap the signature attributes to make them look as if they were declared in // the implementation. This allows us to compare them and propagate them to the implementation @@ -107,7 +107,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = fixup (sigAttribs @ keptImplAttribs) true - let rec checkTypars m (aenv: TypeEquivEnv) (implTypars:Typars) (sigTypars:Typars) = + let rec checkTypars m (aenv: TypeEquivEnv) (implTypars: Typars) (sigTypars: Typars) = if implTypars.Length <> sigTypars.Length then errorR (Error(FSComp.SR.typrelSigImplNotCompatibleParamCountsDiffer(), m)) false @@ -149,7 +149,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = true) && (not checkingSig || checkAttribs aenv implTypar.Attribs sigTypar.Attribs (fun attribs -> implTypar.SetAttribs attribs))) - and checkTypeDef (aenv: TypeEquivEnv) (implTycon:Tycon) (sigTycon:Tycon) = + and checkTypeDef (aenv: TypeEquivEnv) (implTycon: Tycon) (sigTycon: Tycon) = let m = implTycon.Range // Propagate defn location information from implementation to signature . @@ -294,7 +294,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = implVal.SetValReprInfo (Some (ValReprInfo (sigTyparNames, implArgInfos, implRetInfo))) res - and checkVal implModRef (aenv:TypeEquivEnv) (implVal:Val) (sigVal:Val) = + and checkVal implModRef (aenv: TypeEquivEnv) (implVal: Val) (sigVal: Val) = // Propagate defn location information from implementation to signature . sigVal.SetOtherRange (implVal.Range, true) @@ -408,7 +408,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = // sig for err then checkRecordFieldsForExn. // ------------------------------------------------------------------------------- - and checkRecordFields m aenv (implTycon:Tycon) (implFields:TyconRecdFields) (sigFields:TyconRecdFields) = + and checkRecordFields m aenv (implTycon: Tycon) (implFields: TyconRecdFields) (sigFields: TyconRecdFields) = let implFields = implFields.TrueFieldsAsList let sigFields = sigFields.TrueFieldsAsList let m1 = implFields |> NameMap.ofKeyedList (fun rfld -> rfld.Name) @@ -426,7 +426,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = then true else (errorR(Error (FSComp.SR.DefinitionsInSigAndImplNotCompatibleFieldOrderDiffer(implTycon.TypeOrMeasureKind.ToString(), implTycon.DisplayName), m)); false)) - and checkRecordFieldsForExn _g _denv err aenv (implFields:TyconRecdFields) (sigFields:TyconRecdFields) = + and checkRecordFieldsForExn _g _denv err aenv (implFields: TyconRecdFields) (sigFields: TyconRecdFields) = let implFields = implFields.TrueFieldsAsList let sigFields = sigFields.TrueFieldsAsList let m1 = implFields |> NameMap.ofKeyedList (fun rfld -> rfld.Name) @@ -439,9 +439,9 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = then true else (errorR(err (FSComp.SR.ExceptionDefsNotCompatibleFieldOrderDiffers)); false)) - and checkVirtualSlots denv m (implTycon:Tycon) implAbstractSlots sigAbstractSlots = - let m1 = NameMap.ofKeyedList (fun (v:ValRef) -> v.DisplayName) implAbstractSlots - let m2 = NameMap.ofKeyedList (fun (v:ValRef) -> v.DisplayName) sigAbstractSlots + and checkVirtualSlots denv m (implTycon: Tycon) implAbstractSlots sigAbstractSlots = + let m1 = NameMap.ofKeyedList (fun (v: ValRef) -> v.DisplayName) implAbstractSlots + let m2 = NameMap.ofKeyedList (fun (v: ValRef) -> v.DisplayName) sigAbstractSlots (m1, m2) ||> NameMap.suball2 (fun _s vref -> let kindText = implTycon.TypeOrMeasureKind.ToString() let valText = NicePrint.stringValOrMember denv vref.Deref @@ -452,7 +452,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = let valText = NicePrint.stringValOrMember denv vref.Deref errorR(Error (FSComp.SR.DefinitionsInSigAndImplNotCompatibleAbstractMemberMissingInSig(kindText, implTycon.DisplayName, valText), m)); false) (fun _x _y -> true) - and checkClassFields isStruct m aenv (implTycon:Tycon) (implFields:TyconRecdFields) (sigFields:TyconRecdFields) = + and checkClassFields isStruct m aenv (implTycon: Tycon) (implFields: TyconRecdFields) (sigFields: TyconRecdFields) = let implFields = implFields.TrueFieldsAsList let sigFields = sigFields.TrueFieldsAsList let m1 = implFields |> NameMap.ofKeyedList (fun rfld -> rfld.Name) @@ -468,7 +468,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = true) - and checkTypeRepr m aenv (implTycon:Tycon) sigTypeRepr = + and checkTypeRepr m aenv (implTycon: Tycon) sigTypeRepr = let reportNiceError k s1 s2 = let aset = NameSet.ofList s1 let fset = NameSet.ofList s2 @@ -545,7 +545,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = | TNoRepr, _ -> (errorR (Error(FSComp.SR.DefinitionsInSigAndImplNotCompatibleRepresentationsDiffer(implTycon.TypeOrMeasureKind.ToString(), implTycon.DisplayName), m)); false) | _, _ -> (errorR (Error(FSComp.SR.DefinitionsInSigAndImplNotCompatibleRepresentationsDiffer(implTycon.TypeOrMeasureKind.ToString(), implTycon.DisplayName), m)); false) - and checkTypeAbbrev m aenv (implTycon:Tycon) (sigTycon:Tycon) = + and checkTypeAbbrev m aenv (implTycon: Tycon) (sigTycon: Tycon) = let kind1 = implTycon.TypeOrMeasureKind let kind2 = sigTycon.TypeOrMeasureKind if kind1 <> kind2 then (errorR (Error (FSComp.SR.DefinitionsInSigAndImplNotCompatibleSignatureDeclaresDiffer(implTycon.TypeOrMeasureKind.ToString(), implTycon.DisplayName, kind2.ToString(), kind1.ToString()), m)); false) @@ -562,7 +562,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = | Some _, None -> (errorR (Error (FSComp.SR.DefinitionsInSigAndImplNotCompatibleAbbreviationHiddenBySig(implTycon.TypeOrMeasureKind.ToString(), implTycon.DisplayName), m)); false) | None, Some _ -> (errorR (Error (FSComp.SR.DefinitionsInSigAndImplNotCompatibleSigHasAbbreviation(implTycon.TypeOrMeasureKind.ToString(), implTycon.DisplayName), m)); false) - and checkModuleOrNamespaceContents m aenv (implModRef:ModuleOrNamespaceRef) (signModType:ModuleOrNamespaceType) = + and checkModuleOrNamespaceContents m aenv (implModRef: ModuleOrNamespaceRef) (signModType: ModuleOrNamespaceType) = let implModType = implModRef.ModuleOrNamespaceType (if implModType.ModuleOrNamespaceKind <> signModType.ModuleOrNamespaceKind then errorR(Error(FSComp.SR.typrelModuleNamespaceAttributesDifferInSigAndImpl(), m))) @@ -578,7 +578,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = (fun s fx -> errorR(RequiredButNotSpecified(denv, implModRef, (if fx.IsModule then "module" else "namespace"), (fun os -> Printf.bprintf os "%s" s), m)); false) (fun x1 x2 -> checkModuleOrNamespace aenv (mkLocalModRef x1) x2) && - let sigValHadNoMatchingImplementation (fx:Val) (_closeActualVal: Val option) = + let sigValHadNoMatchingImplementation (fx: Val) (_closeActualVal: Val option) = errorR(RequiredButNotSpecified(denv, implModRef, "value", (fun os -> (* In the case of missing members show the full required enclosing type and signature *) if fx.IsMember then @@ -586,7 +586,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = else Printf.bprintf os "%s" fx.DisplayName), m)) - let valuesPartiallyMatch (av:Val) (fv:Val) = + let valuesPartiallyMatch (av: Val) (fv: Val) = let akey = av.GetLinkagePartialKey() let fkey = fv.GetLinkagePartialKey() (akey.MemberParentMangledName = fkey.MemberParentMangledName) && @@ -595,7 +595,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = (implModType.AllValsAndMembersByLogicalNameUncached, signModType.AllValsAndMembersByLogicalNameUncached) ||> NameMap.suball2 - (fun _s (fxs:Val list) -> sigValHadNoMatchingImplementation fxs.Head None; false) + (fun _s (fxs: Val list) -> sigValHadNoMatchingImplementation fxs.Head None; false) (fun avs fvs -> match avs, fvs with | [], _ | _, [] -> failwith "unreachable" @@ -637,7 +637,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = checkModuleOrNamespaceContents implModRef.Range aenv implModRef sigModRef.ModuleOrNamespaceType && checkAttribs aenv implModRef.Attribs sigModRef.Attribs implModRef.Deref.SetAttribs - member __.CheckSignature aenv (implModRef:ModuleOrNamespaceRef) (signModType:ModuleOrNamespaceType) = + member __.CheckSignature aenv (implModRef: ModuleOrNamespaceRef) (signModType: ModuleOrNamespaceType) = checkModuleOrNamespaceContents implModRef.Range aenv implModRef signModType member __.CheckTypars m aenv (implTypars: Typars) (signTypars: Typars) = @@ -645,7 +645,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = /// Check the names add up between a signature and its implementation. We check this first. -let rec CheckNamesOfModuleOrNamespaceContents denv (implModRef:ModuleOrNamespaceRef) (signModType:ModuleOrNamespaceType) = +let rec CheckNamesOfModuleOrNamespaceContents denv (implModRef: ModuleOrNamespaceRef) (signModType: ModuleOrNamespaceType) = let m = implModRef.Range let implModType = implModRef.ModuleOrNamespaceType NameMap.suball2 @@ -657,11 +657,11 @@ let rec CheckNamesOfModuleOrNamespaceContents denv (implModRef:ModuleOrNamespace (implModType.ModulesAndNamespacesByDemangledName, signModType.ModulesAndNamespacesByDemangledName ) ||> NameMap.suball2 (fun s fx -> errorR(RequiredButNotSpecified(denv, implModRef, (if fx.IsModule then "module" else "namespace"), (fun os -> Printf.bprintf os "%s" s), m)); false) - (fun x1 (x2:ModuleOrNamespace) -> CheckNamesOfModuleOrNamespace denv (mkLocalModRef x1) x2.ModuleOrNamespaceType) && + (fun x1 (x2: ModuleOrNamespace) -> CheckNamesOfModuleOrNamespace denv (mkLocalModRef x1) x2.ModuleOrNamespaceType) && (implModType.AllValsAndMembersByLogicalNameUncached , signModType.AllValsAndMembersByLogicalNameUncached) ||> NameMap.suball2 - (fun _s (fxs:Val list) -> + (fun _s (fxs: Val list) -> let fx = fxs.Head errorR(RequiredButNotSpecified(denv, implModRef, "value", (fun os -> // In the case of missing members show the full required enclosing type and signature @@ -672,6 +672,6 @@ let rec CheckNamesOfModuleOrNamespaceContents denv (implModRef:ModuleOrNamespace (fun _ _ -> true) -and CheckNamesOfModuleOrNamespace denv (implModRef:ModuleOrNamespaceRef) signModType = +and CheckNamesOfModuleOrNamespace denv (implModRef: ModuleOrNamespaceRef) signModType = CheckNamesOfModuleOrNamespaceContents denv implModRef signModType diff --git a/src/fsharp/TastOps.fs b/src/fsharp/TastOps.fs index 21b82215eda..dbf8371c537 100644 --- a/src/fsharp/TastOps.fs +++ b/src/fsharp/TastOps.fs @@ -51,7 +51,7 @@ type TyparMap<'T> = let (TPMap m) = tm TPMap (m.Add(v.Stamp, x)) - static member Empty : TyparMap<'T> = TPMap Map.empty + static member Empty: TyparMap<'T> = TPMap Map.empty [] type TyconRefMap<'T>(imap: StampMap<'T>) = @@ -62,7 +62,7 @@ type TyconRefMap<'T>(imap: StampMap<'T>) = member m.Remove (v: TyconRef) = TyconRefMap (imap.Remove v.Stamp) member m.IsEmpty = imap.IsEmpty - static member Empty : TyconRefMap<'T> = TyconRefMap Map.empty + static member Empty: TyconRefMap<'T> = TyconRefMap Map.empty static member OfList vs = (vs, TyconRefMap<'T>.Empty) ||> List.foldBack (fun (x, y) acc -> acc.Add x y) [] @@ -70,7 +70,7 @@ type TyconRefMap<'T>(imap: StampMap<'T>) = type ValMap<'T>(imap: StampMap<'T>) = member m.Contents = imap - member m.Item with get (v:Val) = imap.[v.Stamp] + member m.Item with get (v: Val) = imap.[v.Stamp] member m.TryFind (v: Val) = imap.TryFind v.Stamp member m.ContainsVal (v: Val) = imap.ContainsKey v.Stamp member m.Add (v: Val) x = ValMap (imap.Add(v.Stamp, x)) @@ -88,14 +88,14 @@ type TyparInst = (Typar * TType) list type TyconRefRemap = TyconRefMap type ValRemap = ValMap -let emptyTyconRefRemap : TyconRefRemap = TyconRefMap<_>.Empty -let emptyTyparInst = ([] : TyparInst) +let emptyTyconRefRemap: TyconRefRemap = TyconRefMap<_>.Empty +let emptyTyparInst = ([]: TyparInst) [] type Remap = - { tpinst : TyparInst + { tpinst: TyparInst valRemap: ValRemap - tyconRefRemap : TyconRefRemap + tyconRefRemap: TyconRefRemap removeTraitSolutions: bool } let emptyRemap = @@ -122,17 +122,17 @@ let isRemapEmpty remap = let rec instTyparRef tpinst ty tp = match tpinst with | [] -> ty - | (tp', ty')::t -> + | (tp', ty'):: t -> if typarEq tp tp' then ty' else instTyparRef t ty tp -let instMeasureTyparRef tpinst unt (tp:Typar) = +let instMeasureTyparRef tpinst unt (tp: Typar) = match tp.Kind with | TyparKind.Measure -> let rec loop tpinst = match tpinst with | [] -> unt - | (tp', ty')::t -> + | (tp', ty'):: t -> if typarEq tp tp' then match ty' with | TType_measure unt -> unt @@ -155,12 +155,12 @@ let mkTyparInst (typars: Typars) tyargs = if List.length typars <> List.length tyargs then failwith ("mkTyparInst: invalid type" + (sprintf " %d <> %d" (List.length typars) (List.length tyargs))) #endif - (List.zip typars tyargs : TyparInst) + (List.zip typars tyargs: TyparInst) let generalizeTypar tp = mkTyparTy tp let generalizeTypars tps = List.map generalizeTypar tps -let rec remapTypeAux (tyenv : Remap) (ty:TType) = +let rec remapTypeAux (tyenv: Remap) (ty: TType) = let ty = stripTyparEqns ty match ty with | TType_var tp as ty -> instTyparRef tyenv.tpinst ty tp @@ -320,7 +320,7 @@ and remapValLinkage tyenv (vlink: ValLinkageFullKey) = if tyOpt === tyOpt' then vlink else ValLinkageFullKey(vlink.PartialKey, tyOpt') -and remapNonLocalValRef tyenv (nlvref:NonLocalValOrMemberRef) = +and remapNonLocalValRef tyenv (nlvref: NonLocalValOrMemberRef) = let eref = nlvref.EnclosingEntity let eref' = remapTyconRef tyenv.tyconRefRemap eref let vlink = nlvref.ItemKey @@ -392,21 +392,21 @@ let mkTyparToTyparRenaming tpsOrig tps = let tinst = generalizeTypars tps mkTyparInst tpsOrig tinst, tinst -let mkTyconInst (tycon:Tycon) tinst = mkTyparInst tycon.TyparsNoRange tinst -let mkTyconRefInst (tcref:TyconRef) tinst = mkTyconInst tcref.Deref tinst +let mkTyconInst (tycon: Tycon) tinst = mkTyparInst tycon.TyparsNoRange tinst +let mkTyconRefInst (tcref: TyconRef) tinst = mkTyconInst tcref.Deref tinst //--------------------------------------------------------------------------- // Basic equalites //--------------------------------------------------------------------------- -let tyconRefEq (g:TcGlobals) tcref1 tcref2 = primEntityRefEq g.compilingFslib g.fslibCcu tcref1 tcref2 -let valRefEq (g:TcGlobals) vref1 vref2 = primValRefEq g.compilingFslib g.fslibCcu vref1 vref2 +let tyconRefEq (g: TcGlobals) tcref1 tcref2 = primEntityRefEq g.compilingFslib g.fslibCcu tcref1 tcref2 +let valRefEq (g: TcGlobals) vref1 vref2 = primValRefEq g.compilingFslib g.fslibCcu vref1 vref2 //--------------------------------------------------------------------------- // Remove inference equations and abbreviations from units //--------------------------------------------------------------------------- -let reduceTyconRefAbbrevMeasureable (tcref:TyconRef) = +let reduceTyconRefAbbrevMeasureable (tcref: TyconRef) = let abbrev = tcref.TypeAbbrev match abbrev with | Some (TType_measure ms) -> ms @@ -456,7 +456,7 @@ let rec MeasureVarExponent tp unt = let ListMeasureVarOccs unt = let rec gather acc unt = match stripUnitEqnsFromMeasure unt with - | Measure.Var tp -> if List.exists (typarEq tp) acc then acc else tp::acc + | Measure.Var tp -> if List.exists (typarEq tp) acc then acc else tp:: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.RationalPower(unt', _) -> gather acc unt' | Measure.Inv unt' -> gather acc unt' @@ -471,7 +471,7 @@ let ListMeasureVarOccsWithNonZeroExponents untexpr = if List.exists (fun (tp', _) -> typarEq tp tp') acc then acc else let e = MeasureVarExponent tp untexpr - if e = ZeroRational then acc else (tp, e)::acc + if e = ZeroRational then acc else (tp, e):: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.Inv unt' -> gather acc unt' | Measure.RationalPower(unt', _) -> gather acc unt' @@ -485,7 +485,7 @@ let ListMeasureConOccsWithNonZeroExponents g eraseAbbrevs untexpr = | Measure.Con c -> if List.exists (fun (c', _) -> tyconRefEq g c c') acc then acc else let e = MeasureExprConExponent g eraseAbbrevs c untexpr - if e = ZeroRational then acc else (c, e)::acc + if e = ZeroRational then acc else (c, e):: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.Inv unt' -> gather acc unt' | Measure.RationalPower(unt', _) -> gather acc unt' @@ -497,7 +497,7 @@ let ListMeasureConOccsWithNonZeroExponents g eraseAbbrevs untexpr = let ListMeasureConOccsAfterRemapping g r unt = let rec gather acc unt = match stripUnitEqnsFromMeasure unt with - | Measure.Con c -> if List.exists (tyconRefEq g (r c)) acc then acc else r c::acc + | Measure.Con c -> if List.exists (tyconRefEq g (r c)) acc then acc else r c:: acc | Measure.Prod(unt1, unt2) -> gather (gather acc unt1) unt2 | Measure.RationalPower(unt', _) -> gather acc unt' | Measure.Inv unt' -> gather acc unt' @@ -521,7 +521,7 @@ let MeasureProdOpt m1 m2 = let ProdMeasures ms = match ms with | [] -> Measure.One - | m::ms -> List.foldBack MeasureProdOpt ms m + | m:: ms -> List.foldBack MeasureProdOpt ms m let isDimensionless g tyarg = match stripTyparEqns tyarg with @@ -568,21 +568,21 @@ let tryNormalizeMeasureInType g ty = // Some basic type builders //--------------------------------------------------------------------------- -let mkNativePtrTy (g:TcGlobals) ty = +let mkNativePtrTy (g: TcGlobals) ty = assert g.nativeptr_tcr.CanDeref // this should always be available, but check anyway TType_app (g.nativeptr_tcr, [ty]) -let mkByrefTy (g:TcGlobals) ty = +let mkByrefTy (g: TcGlobals) ty = assert g.byref_tcr.CanDeref // this should always be available, but check anyway TType_app (g.byref_tcr, [ty]) -let mkInByrefTy (g:TcGlobals) ty = +let mkInByrefTy (g: TcGlobals) ty = if g.inref_tcr.CanDeref then // If not using sufficient FSharp.Core, then inref = byref, see RFC FS-1053.md TType_app (g.inref_tcr, [ty]) else mkByrefTy g ty -let mkOutByrefTy (g:TcGlobals) ty = +let mkOutByrefTy (g: TcGlobals) ty = if g.outref_tcr.CanDeref then // If not using sufficient FSharp.Core, then outref = byref, see RFC FS-1053.md TType_app (g.outref_tcr, [ty]) else @@ -594,21 +594,21 @@ let mkByrefTyWithFlag g readonly ty = else mkByrefTy g ty -let mkByref2Ty (g:TcGlobals) ty1 ty2 = +let mkByref2Ty (g: TcGlobals) ty1 ty2 = assert g.byref2_tcr.CanDeref // check we are using sufficient FSharp.Core, caller should check this TType_app (g.byref2_tcr, [ty1; ty2]) -let mkVoidPtrTy (g:TcGlobals) = +let mkVoidPtrTy (g: TcGlobals) = assert g.voidptr_tcr.CanDeref // check we are using sufficient FSharp.Core , caller should check this TType_app (g.voidptr_tcr, []) -let mkByrefTyWithInference (g:TcGlobals) ty1 ty2 = +let mkByrefTyWithInference (g: TcGlobals) ty1 ty2 = if g.byref2_tcr.CanDeref then // If not using sufficient FSharp.Core, then inref = byref, see RFC FS-1053.md TType_app (g.byref2_tcr, [ty1; ty2]) else TType_app (g.byref_tcr, [ty1]) -let mkArrayTy (g:TcGlobals) rank ty m = +let mkArrayTy (g: TcGlobals) rank ty m = if rank < 1 || rank > 32 then errorR(Error(FSComp.SR.tastopsMaxArrayThirtyTwo(rank), m)) TType_app (g.il_arr_tcr_map.[3], [ty]) @@ -640,7 +640,7 @@ let isCompiledTupleTyconRef g tcref = tyconRefEq g g.struct_tuple7_tcr tcref || tyconRefEq g g.struct_tuple8_tcr tcref -let mkCompiledTupleTyconRef (g:TcGlobals) isStruct n = +let mkCompiledTupleTyconRef (g: TcGlobals) isStruct n = if n = 1 then (if isStruct then g.struct_tuple1_tcr else g.ref_tuple1_tcr) elif n = 2 then (if isStruct then g.struct_tuple2_tcr else g.ref_tuple2_tcr) elif n = 3 then (if isStruct then g.struct_tuple3_tcr else g.ref_tuple3_tcr) @@ -685,17 +685,17 @@ let applyTyconAbbrev abbrevTy tycon tyargs = if isNil tyargs then abbrevTy else instType (mkTyconInst tycon tyargs) abbrevTy -let reduceTyconAbbrev (tycon:Tycon) tyargs = +let reduceTyconAbbrev (tycon: Tycon) tyargs = let abbrev = tycon.TypeAbbrev match abbrev with | None -> invalidArg "tycon" "this type definition is not an abbreviation" | Some abbrevTy -> applyTyconAbbrev abbrevTy tycon tyargs -let reduceTyconRefAbbrev (tcref:TyconRef) tyargs = +let reduceTyconRefAbbrev (tcref: TyconRef) tyargs = reduceTyconAbbrev tcref.Deref tyargs -let reduceTyconMeasureableOrProvided (g:TcGlobals) (tycon:Tycon) tyargs = +let reduceTyconMeasureableOrProvided (g: TcGlobals) (tycon: Tycon) tyargs = #if NO_EXTENSIONTYPING ignore g // otherwise g would be unused #endif @@ -708,7 +708,7 @@ let reduceTyconMeasureableOrProvided (g:TcGlobals) (tycon:Tycon) tyargs = #endif | _ -> invalidArg "tc" "this type definition is not a refinement" -let reduceTyconRefMeasureableOrProvided (g:TcGlobals) (tcref:TyconRef) tyargs = +let reduceTyconRefMeasureableOrProvided (g: TcGlobals) (tcref: TyconRef) tyargs = reduceTyconMeasureableOrProvided g tcref.Deref tyargs let rec stripTyEqnsA g canShortcut ty = @@ -748,7 +748,7 @@ let evalAnonInfoIsStruct (anonInfo: AnonRecdTypeInfo) = /// and measureable types (float<_>). /// It also optionally erases all "compilation representations", i.e. function and /// tuple types, and also "nativeptr<'T> --> System.IntPtr" -let rec stripTyEqnsAndErase eraseFuncAndTuple (g:TcGlobals) ty = +let rec stripTyEqnsAndErase eraseFuncAndTuple (g: TcGlobals) ty = let ty = stripTyEqns g ty match ty with | TType_app (tcref, args) -> @@ -774,7 +774,7 @@ let stripTyEqnsWrtErasure erasureFlag g ty = | EraseMeasures -> stripTyEqnsAndErase false g ty | _ -> stripTyEqns g ty -let rec stripExnEqns (eref:TyconRef) = +let rec stripExnEqns (eref: TyconRef) = let exnc = eref.Deref match exnc.ExceptionInfo with | TExnAbbrevRepr eref -> stripExnEqns eref @@ -945,7 +945,7 @@ and typarConstraintsAEquivAux erasureFlag g aenv tpc1 tpc2 = | TyparConstraint.RequiresDefaultConstructor _, TyparConstraint.RequiresDefaultConstructor _ -> true | _ -> false -and typarConstraintSetsAEquivAux erasureFlag g aenv (tp1:Typar) (tp2:Typar) = +and typarConstraintSetsAEquivAux erasureFlag g aenv (tp1: Typar) (tp2: Typar) = tp1.StaticReq = tp2.StaticReq && ListSet.equals (typarConstraintsAEquivAux erasureFlag g aenv) tp1.Constraints tp2.Constraints @@ -1100,12 +1100,12 @@ let mkLambdaTy tps tys rty = mkForallTyIfNeeded tps (mkIteratedFunTy tys rty) /// the library arising from env.fs. Part of this means that we have to be able to resolve these /// references. This function artificially forces the existence of a module or namespace at a /// particular point in order to do this. -let ensureCcuHasModuleOrNamespaceAtPath (ccu:CcuThunk) path (CompPath(_, cpath)) xml = +let ensureCcuHasModuleOrNamespaceAtPath (ccu: CcuThunk) path (CompPath(_, cpath)) xml = let scoref = ccu.ILScopeRef - let rec loop prior_cpath (path:Ident list) cpath (modul:ModuleOrNamespace) = + let rec loop prior_cpath (path: Ident list) cpath (modul: ModuleOrNamespace) = let mtype = modul.ModuleOrNamespaceType match path, cpath with - | (hpath::tpath), ((_, mkind)::tcpath) -> + | (hpath:: tpath), ((_, mkind):: tcpath) -> let modName = hpath.idText if not (Map.containsKey modName mtype.AllEntitiesByCompiledAndLogicalMangledNames) then let smodul = NewModuleOrNamespace (Some(CompPath(scoref, prior_cpath))) taccessPublic hpath xml [] (MaybeLazy.Strict (NewEmptyModuleOrNamespaceType mkind)) @@ -1204,7 +1204,7 @@ let mkTypeChoose m vs b = match vs with [] -> b | _ -> Expr.TyChoose (vs, b, m) let mkObjExpr (ty, basev, basecall, overrides, iimpls, m) = Expr.Obj (newUnique(), ty, basev, basecall, overrides, iimpls, m) -let mkLambdas m tps (vs:Val list) (b, rty) = +let mkLambdas m tps (vs: Val list) (b, rty) = mkTypeLambda m tps (List.foldBack (fun v (e, ty) -> mkLambda m v (e, ty), v.Type --> ty) vs (b, rty)) let mkMultiLambdasCore m vsl (b, rty) = @@ -1220,7 +1220,7 @@ let mkMemberLambdas m tps ctorThisValOpt baseValOpt vsl (b, rty) = | _ -> match vsl with | [] -> error(InternalError("mk_basev_multi_lambdas_core: can't attach a basev to a non-lambda expression", m)) - | h::t -> + | h:: t -> let b, rty = mkMultiLambdasCore m t (b, rty) (rebuildLambda m ctorThisValOpt baseValOpt h (b, rty), (typeOfLambdaArg m h --> rty)) mkTypeLambda m tps expr @@ -1297,8 +1297,8 @@ let isBeingGeneralized tp typeScheme = // Build conditional expressions... //------------------------------------------------------------------------- -let mkLazyAnd (g:TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty e1 e2 (Expr.Const(Const.Bool false, m, g.bool_ty)) -let mkLazyOr (g:TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty e1 (Expr.Const(Const.Bool true, m, g.bool_ty)) e2 +let mkLazyAnd (g: TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty e1 e2 (Expr.Const(Const.Bool false, m, g.bool_ty)) +let mkLazyOr (g: TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.bool_ty e1 (Expr.Const(Const.Bool true, m, g.bool_ty)) e2 let mkCoerceExpr(e, to_ty, m, from_ty) = Expr.Op (TOp.Coerce, [to_ty;from_ty], [e], m) @@ -1323,7 +1323,7 @@ let mkRecdFieldSetViaExprAddr (e1, fref, tinst, e2, m) = Expr.Op (TOp.ValFieldS let mkUnionCaseTagGetViaExprAddr (e1, cref, tinst, m) = Expr.Op (TOp.UnionCaseTagGet(cref), tinst, [e1], m) /// Make a 'TOp.UnionCaseProof' expression, which proves a union value is over a particular case (used only for ref-unions, not struct-unions) -let mkUnionCaseProof (e1, cref:UnionCaseRef, tinst, m) = if cref.Tycon.IsStructOrEnumTycon then e1 else Expr.Op (TOp.UnionCaseProof(cref), tinst, [e1], m) +let mkUnionCaseProof (e1, cref: UnionCaseRef, tinst, m) = if cref.Tycon.IsStructOrEnumTycon then e1 else Expr.Op (TOp.UnionCaseProof(cref), tinst, [e1], m) /// Build a 'TOp.UnionCaseFieldGet' expression for something we've already determined to be a particular union case. For ref-unions, /// the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, @@ -1345,20 +1345,20 @@ let mkUnionCaseFieldSet (e1, cref, tinst, j, e2, m) = Expr.Op (TOp.Union let mkExnCaseFieldGet (e1, ecref, j, m) = Expr.Op (TOp.ExnFieldGet(ecref, j), [], [e1], m) let mkExnCaseFieldSet (e1, ecref, j, e2, m) = Expr.Op (TOp.ExnFieldSet(ecref, j), [], [e1;e2], m) -let mkDummyLambda (g:TcGlobals) (e:Expr, ety) = +let mkDummyLambda (g: TcGlobals) (e: Expr, ety) = let m = e.Range mkLambda m (fst (mkCompGenLocal m "unitVar" g.unit_ty)) (e, ety) -let mkWhile (g:TcGlobals) (spWhile, marker, e1, e2, m) = +let mkWhile (g: TcGlobals) (spWhile, marker, e1, e2, m) = Expr.Op (TOp.While (spWhile, marker), [] , [mkDummyLambda g (e1, g.bool_ty);mkDummyLambda g (e2, g.unit_ty)], m) -let mkFor (g:TcGlobals) (spFor, v, e1, dir, e2, e3:Expr, m) = +let mkFor (g: TcGlobals) (spFor, v, e1, dir, e2, e3: Expr, m) = Expr.Op (TOp.For (spFor, dir) , [] , [mkDummyLambda g (e1, g.int_ty) ;mkDummyLambda g (e2, g.int_ty);mkLambda e3.Range v (e3, g.unit_ty)], m) -let mkTryWith g (e1, vf, ef:Expr, vh, eh:Expr, m, ty, spTry, spWith) = +let mkTryWith g (e1, vf, ef: Expr, vh, eh: Expr, m, ty, spTry, spWith) = Expr.Op (TOp.TryCatch(spTry, spWith), [ty], [mkDummyLambda g (e1, ty);mkLambda ef.Range vf (ef, ty);mkLambda eh.Range vh (eh, ty)], m) -let mkTryFinally (g:TcGlobals) (e1, e2, m, ty, spTry, spFinally) = +let mkTryFinally (g: TcGlobals) (e1, e2, m, ty, spTry, spFinally) = Expr.Op (TOp.TryFinally(spTry, spFinally), [ty], [mkDummyLambda g (e1, ty);mkDummyLambda g (e2, g.unit_ty)], m) let mkDefault (m, ty) = Expr.Const(Const.Zero, m, ty) @@ -1380,13 +1380,13 @@ type ValHash<'T> = let (ValHash t) = ht t.Values :> seq<'T> - member ht.TryFind (v:Val) = + member ht.TryFind (v: Val) = let (ValHash t) = ht match t.TryGetValue v.Stamp with | true, v -> Some v | _ -> None - member ht.Add (v:Val, x) = + member ht.Add (v: Val, x) = let (ValHash t) = ht t.[v.Stamp] <- x @@ -1403,7 +1403,7 @@ type ValMultiMap<'T>(contents: StampMap<'T list>) = | Some vals -> vals | _ -> [] - member m.Add (v:Val, x) = ValMultiMap<'T>(contents.Add (v.Stamp, x :: m.Find v)) + member m.Add (v: Val, x) = ValMultiMap<'T>(contents.Add (v.Stamp, x :: m.Find v)) member m.Remove (v: Val) = ValMultiMap<'T>(contents.Remove v.Stamp) @@ -1428,13 +1428,13 @@ type TyconRefMultiMap<'T>(contents: TyconRefMap<'T list>) = //-------------------------------------------------------------------------- /// Try to create a EntityRef suitable for accessing the given Entity from another assembly -let tryRescopeEntity viewedCcu (entity:Entity) : ValueOption = +let tryRescopeEntity viewedCcu (entity: Entity) : ValueOption = match entity.PublicPath with | Some pubpath -> ValueSome (ERefNonLocal (rescopePubPath viewedCcu pubpath)) | None -> ValueNone /// Try to create a ValRef suitable for accessing the given Val from another assembly -let tryRescopeVal viewedCcu (entityRemap:Remap) (vspec:Val) : ValueOption = +let tryRescopeVal viewedCcu (entityRemap: Remap) (vspec: Val) : ValueOption = match vspec.PublicPath with | Some (ValPubPath(p, fullLinkageKey)) -> // The type information in the val linkage doesn't need to keep any information to trait solutions. @@ -1456,15 +1456,15 @@ let tryRescopeVal viewedCcu (entityRemap:Remap) (vspec:Val) : ValueOption actualTysOfRecdFields inst +let actualTysOfInstanceRecdFields inst (tcref: TyconRef) = tcref.AllInstanceFieldsAsList |> actualTysOfRecdFields inst -let actualTysOfUnionCaseFields inst (x:UnionCaseRef) = actualTysOfRecdFields inst x.AllFieldsAsList +let actualTysOfUnionCaseFields inst (x: UnionCaseRef) = actualTysOfRecdFields inst x.AllFieldsAsList -let actualResultTyOfUnionCase tinst (x:UnionCaseRef) = +let actualResultTyOfUnionCase tinst (x: UnionCaseRef) = instType (mkTyconRefInst x.TyconRef tinst) x.ReturnType let recdFieldsOfExnDefRef x = (stripExnEqns x).TrueInstanceFieldsAsList @@ -1474,13 +1474,13 @@ let recdFieldTysOfExnDefRef x = actualTysOfRecdFields [] (recdFieldsOfExnDefRef let recdFieldTyOfExnDefRefByIdx x j = actualTyOfRecdField [] (recdFieldOfExnDefRefByIdx x j) -let actualTyOfRecdFieldForTycon tycon tinst (fspec:RecdField) = +let actualTyOfRecdFieldForTycon tycon tinst (fspec: RecdField) = instType (mkTyconInst tycon tinst) fspec.FormalType -let actualTyOfRecdFieldRef (fref:RecdFieldRef) tinst = +let actualTyOfRecdFieldRef (fref: RecdFieldRef) tinst = actualTyOfRecdFieldForTycon fref.Tycon tinst fref.RecdField -let actualTyOfUnionFieldRef (fref:UnionCaseRef) n tinst = +let actualTyOfUnionFieldRef (fref: UnionCaseRef) n tinst = actualTyOfRecdFieldForTycon fref.Tycon tinst (fref.FieldByIndex(n)) @@ -1502,7 +1502,7 @@ let rec stripFunTy g ty = if isFunTy g ty then let (d, r) = destFunTy g ty let more, rty = stripFunTy g r - d::more, rty + d:: more, rty else [], ty let applyForallTy g ty tyargs = @@ -1530,7 +1530,7 @@ let rec stripFunTyN g n ty = assert (n >= 0) if n > 0 && isFunTy g ty then let (d, r) = destFunTy g ty - let more, rty = stripFunTyN g (n-1) r in d::more, rty + let more, rty = stripFunTyN g (n-1) r in d:: more, rty else [], ty @@ -1571,7 +1571,7 @@ let GetTopValTypeInFSharpForm g (ValReprInfo(_, argInfos, retInfo) as topValInfo let curriedArgTys, returnTy = GetTopTauTypeInFSharpForm g argInfos tau m tps, curriedArgTys, returnTy, retInfo -let IsCompiledAsStaticProperty g (v:Val) = +let IsCompiledAsStaticProperty g (v: Val) = match v.ValReprInfo with | Some valReprInfoValue -> match GetTopValTypeInFSharpForm g valReprInfoValue v.Type v.Range with @@ -1579,18 +1579,18 @@ let IsCompiledAsStaticProperty g (v:Val) = | _ -> false | _ -> false -let IsCompiledAsStaticPropertyWithField g (v:Val) = +let IsCompiledAsStaticPropertyWithField g (v: Val) = (not v.IsCompiledAsStaticPropertyWithoutField && IsCompiledAsStaticProperty g v) //------------------------------------------------------------------------- // Multi-dimensional array types... //------------------------------------------------------------------------- -let isArrayTyconRef (g:TcGlobals) tcref = +let isArrayTyconRef (g: TcGlobals) tcref = g.il_arr_tcr_map |> Array.exists (tyconRefEq g tcref) -let rankOfArrayTyconRef (g:TcGlobals) tcref = +let rankOfArrayTyconRef (g: TcGlobals) tcref = match g.il_arr_tcr_map |> Array.tryFindIndex (tyconRefEq g tcref) with | Some idx -> idx + 1 @@ -1601,12 +1601,12 @@ let rankOfArrayTyconRef (g:TcGlobals) tcref = // Misc functions on F# types //------------------------------------------------------------------------- -let destArrayTy (g:TcGlobals) ty = +let destArrayTy (g: TcGlobals) ty = match tryAppTy g ty with | ValueSome (tcref, [ty]) when isArrayTyconRef g tcref -> ty | _ -> failwith "destArrayTy" -let destListTy (g:TcGlobals) ty = +let destListTy (g: TcGlobals) ty = match tryAppTy g ty with | ValueSome (tcref, [ty]) when tyconRefEq g tcref g.list_tcr_canon -> ty | _ -> failwith "destListTy" @@ -1655,7 +1655,7 @@ type TypeDefMetadata = | ProvidedTypeMetadata of TProvidedTypeInfo #endif -let metadataOfTycon (tycon:Tycon) = +let metadataOfTycon (tycon: Tycon) = #if !NO_EXTENSIONTYPING match tycon.TypeReprInfo with | TProvidedTypeExtensionPoint info -> ProvidedTypeMetadata info @@ -1688,7 +1688,7 @@ let isILReferenceTy g ty = | ILTypeMetadata (TILObjectReprData(_, _, td)) -> not td.IsStructOrEnum | FSharpOrArrayOrByrefOrTupleOrExnTypeMetadata -> isArrayTy g ty -let isILInterfaceTycon (tycon:Tycon) = +let isILInterfaceTycon (tycon: Tycon) = match metadataOfTycon tycon with #if !NO_EXTENSIONTYPING | ProvidedTypeMetadata info -> info.IsInterface @@ -1839,7 +1839,7 @@ let returnTyOfMethod g (TObjExprMethod((TSlotSig(_, parentTy, _, _, _, _) as ss) actualReturnTyOfSlotSig tinst methTyInst ss /// Is the type 'abstract' in C#-speak -let isAbstractTycon (tycon:Tycon) = +let isAbstractTycon (tycon: Tycon) = if tycon.IsFSharpObjectModelTycon then not tycon.IsFSharpDelegateTycon && tycon.TypeContents.tcaug_abstract @@ -1850,18 +1850,18 @@ let isAbstractTycon (tycon:Tycon) = // Determine if a member/Val/ValRef is an explicit impl //--------------------------------------------------------------------------- -let MemberIsExplicitImpl g (membInfo:ValMemberInfo) = +let MemberIsExplicitImpl g (membInfo: ValMemberInfo) = membInfo.MemberFlags.IsOverrideOrExplicitImpl && match membInfo.ImplementedSlotSigs with | [] -> false | slotsigs -> slotsigs |> List.forall (fun slotsig -> isInterfaceTy g slotsig.ImplementedType) -let ValIsExplicitImpl g (v:Val) = +let ValIsExplicitImpl g (v: Val) = match v.MemberInfo with | Some membInfo -> MemberIsExplicitImpl g membInfo | _ -> false -let ValRefIsExplicitImpl g (vref:ValRef) = ValIsExplicitImpl g vref.Deref +let ValRefIsExplicitImpl g (vref: ValRef) = ValIsExplicitImpl g vref.Deref //--------------------------------------------------------------------------- // Find all type variables in a type, apart from those that have had @@ -1894,7 +1894,7 @@ let unionFreeTycons s1 s2 = let typarOrder = { new System.Collections.Generic.IComparer with - member x.Compare (v1:Typar, v2:Typar) = compare v1.Stamp v2.Stamp } + member x.Compare (v1: Typar, v2: Typar) = compare v1.Stamp v2.Stamp } let emptyFreeTypars = Zset.empty typarOrder let unionFreeTypars s1 s2 = @@ -1925,9 +1925,9 @@ type FreeVarOptions = includeLocalTycons: bool includeTypars: bool includeLocalTyconReprs: bool - includeRecdFields : bool - includeUnionCases : bool - includeLocals : bool } + includeRecdFields: bool + includeUnionCases: bool + includeLocals: bool } let CollectAllNoCaching = { canCache = false @@ -2000,15 +2000,15 @@ let accFreeLocalTycon opts x acc = if Zset.contains x acc.FreeTycons then acc else { acc with FreeTycons = Zset.add x acc.FreeTycons } -let accFreeTycon opts (tcref:TyconRef) acc = +let accFreeTycon opts (tcref: TyconRef) acc = if not opts.includeLocalTycons then acc elif tcref.IsLocalRef then accFreeLocalTycon opts tcref.PrivateTarget acc else acc let rec boundTypars opts tps acc = - // Bound type vars form a recursively-referential set due to constraints, e.g. A : I, B : I + // Bound type vars form a recursively-referential set due to constraints, e.g. A: I, B: I // So collect up free vars in all constraints first, then bind all variables - let acc = List.foldBack (fun (tp:Typar) acc -> accFreeInTyparConstraints opts tp.Constraints acc) tps acc + let acc = List.foldBack (fun (tp: Typar) acc -> accFreeInTyparConstraints opts tp.Constraints acc) tps acc List.foldBack (fun tp acc -> { acc with FreeTypars = Zset.remove tp acc.FreeTypars}) tps acc and accFreeInTyparConstraints opts cxs acc = @@ -2056,14 +2056,14 @@ and accFreeLocalValInTraitSln _opts v fvs = if Zset.contains v fvs.FreeTraitSolutions then fvs else { fvs with FreeTraitSolutions = Zset.add v fvs.FreeTraitSolutions} -and accFreeValRefInTraitSln opts (vref:ValRef) fvs = +and accFreeValRefInTraitSln opts (vref: ValRef) fvs = if vref.IsLocalRef then accFreeLocalValInTraitSln opts vref.PrivateTarget fvs else // non-local values do not contain free variables fvs -and accFreeTyparRef opts (tp:Typar) acc = +and accFreeTyparRef opts (tp: Typar) acc = if not opts.includeTypars then acc else if Zset.contains tp acc.FreeTypars then acc else @@ -2096,16 +2096,16 @@ and accFreeInTypes opts tys acc = | h :: t -> accFreeInTypes opts t (accFreeInType opts h acc) and freeInType opts ty = accFreeInType opts ty emptyFreeTyvars -and accFreeInVal opts (v:Val) acc = accFreeInType opts v.val_type acc +and accFreeInVal opts (v: Val) acc = accFreeInType opts v.val_type acc let freeInTypes opts tys = accFreeInTypes opts tys emptyFreeTyvars let freeInVal opts v = accFreeInVal opts v emptyFreeTyvars let freeInTyparConstraints opts v = accFreeInTyparConstraints opts v emptyFreeTyvars let accFreeInTypars opts tps acc = List.foldBack (accFreeTyparRef opts) tps acc -let rec addFreeInModuleTy (mtyp:ModuleOrNamespaceType) acc = +let rec addFreeInModuleTy (mtyp: ModuleOrNamespaceType) acc = QueueList.foldBack (typeOfVal >> accFreeInType CollectAllNoCaching) mtyp.AllValsAndMembers - (QueueList.foldBack (fun (mspec:ModuleOrNamespace) acc -> addFreeInModuleTy mspec.ModuleOrNamespaceType acc) mtyp.AllEntities acc) + (QueueList.foldBack (fun (mspec: ModuleOrNamespace) acc -> addFreeInModuleTy mspec.ModuleOrNamespaceType acc) mtyp.AllEntities acc) let freeInModuleTy mtyp = addFreeInModuleTy mtyp emptyFreeTyvars @@ -2121,9 +2121,9 @@ let emptyFreeTyparsLeftToRight = [] let unionFreeTyparsLeftToRight fvs1 fvs2 = ListSet.unionFavourRight typarEq fvs1 fvs2 let rec boundTyparsLeftToRight g cxFlag thruFlag acc tps = - // Bound type vars form a recursively-referential set due to constraints, e.g. A : I, B : I + // Bound type vars form a recursively-referential set due to constraints, e.g. A: I, B: I // So collect up free vars in all constraints first, then bind all variables - List.fold (fun acc (tp:Typar) -> accFreeInTyparConstraintsLeftToRight g cxFlag thruFlag acc tp.Constraints) tps acc + List.fold (fun acc (tp: Typar) -> accFreeInTyparConstraintsLeftToRight g cxFlag thruFlag acc tp.Constraints) tps acc and accFreeInTyparConstraintsLeftToRight g cxFlag thruFlag acc cxs = List.fold (accFreeInTyparConstraintLeftToRight g cxFlag thruFlag) acc cxs @@ -2156,7 +2156,7 @@ and accFreeInTraitLeftToRight g cxFlag thruFlag acc (TTrait(tys, _, _, argtys, r let acc = Option.fold (accFreeInTypeLeftToRight g cxFlag thruFlag) acc rty acc -and accFreeTyparRefLeftToRight g cxFlag thruFlag acc (tp:Typar) = +and accFreeTyparRefLeftToRight g cxFlag thruFlag acc (tp: Typar) = if ListSet.contains typarEq tp acc then acc else @@ -2208,9 +2208,9 @@ let freeInTypesLeftToRight g thruFlag ty = let freeInTypesLeftToRightSkippingConstraints g ty = accFreeInTypesLeftToRight g false true emptyFreeTyparsLeftToRight ty |> List.rev -let valOfBind (b:Binding) = b.Var +let valOfBind (b: Binding) = b.Var -let valsOfBinds (binds:Bindings) = binds |> List.map (fun b -> b.Var) +let valsOfBinds (binds: Bindings) = binds |> List.map (fun b -> b.Var) //-------------------------------------------------------------------------- // Values representing member functions on F# types @@ -2227,7 +2227,7 @@ let GetMemberTypeInFSharpForm g memberFlags arities ty m = | [] -> errorR(InternalError("value does not have a valid member type", m)) argInfos - | _::t -> t + | _:: t -> t else argInfos tps, argInfos, rty, retInfo @@ -2239,7 +2239,7 @@ let checkMemberVal membInfo arity m = | _, None -> error(InternalError("checkMemberVal - no arity", m)) | Some membInfo, Some arity -> (membInfo, arity) -let checkMemberValRef (vref:ValRef) = +let checkMemberValRef (vref: ValRef) = checkMemberVal vref.MemberInfo vref.ValReprInfo vref.Range let GetTopValTypeInCompiledForm g topValInfo ty m = @@ -2286,16 +2286,16 @@ let GetMemberTypeInMemberForm g memberFlags topValInfo ty m = let rty = if isUnitTy g rty then None else Some rty (tps, paramArgInfos, rty, retInfo) -let GetTypeOfMemberInMemberForm g (vref:ValRef) = +let GetTypeOfMemberInMemberForm g (vref: ValRef) = //assert (not vref.IsExtensionMember) let membInfo, topValInfo = checkMemberValRef vref GetMemberTypeInMemberForm g membInfo.MemberFlags topValInfo vref.Type vref.Range -let GetTypeOfMemberInFSharpForm g (vref:ValRef) = +let GetTypeOfMemberInFSharpForm g (vref: ValRef) = let membInfo, topValInfo = checkMemberValRef vref GetMemberTypeInFSharpForm g membInfo.MemberFlags topValInfo vref.Type vref.Range -let PartitionValTyparsForApparentEnclosingType g (v:Val) = +let PartitionValTyparsForApparentEnclosingType g (v: Val) = match v.ValReprInfo with | None -> error(InternalError("PartitionValTypars: not a top value", v.Range)) | Some arities -> @@ -2311,7 +2311,7 @@ let PartitionValTyparsForApparentEnclosingType g (v:Val) = /// Match up the type variables on an member value with the type /// variables on the apparent enclosing type -let PartitionValTypars g (v:Val) = +let PartitionValTypars g (v: Val) = match v.ValReprInfo with | None -> error(InternalError("PartitionValTypars: not a top value", v.Range)) | Some arities -> @@ -2324,7 +2324,7 @@ let PartitionValTypars g (v:Val) = let PartitionValRefTypars g (vref: ValRef) = PartitionValTypars g vref.Deref /// Get the arguments for an F# value that represents an object model method -let ArgInfosOfMemberVal g (v:Val) = +let ArgInfosOfMemberVal g (v: Val) = let membInfo, topValInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range let _, arginfos, _, _ = GetMemberTypeInMemberForm g membInfo.MemberFlags topValInfo v.Type v.Range arginfos @@ -2332,7 +2332,7 @@ let ArgInfosOfMemberVal g (v:Val) = let ArgInfosOfMember g (vref: ValRef) = ArgInfosOfMemberVal g vref.Deref -let GetFSharpViewOfReturnType (g:TcGlobals) retTy = +let GetFSharpViewOfReturnType (g: TcGlobals) retTy = match retTy with | None -> g.unit_ty | Some retTy -> retTy @@ -2340,7 +2340,7 @@ let GetFSharpViewOfReturnType (g:TcGlobals) retTy = /// Get the property "type" (getter return type) for an F# value that represents a getter or setter /// of an object model property. -let ReturnTypeOfPropertyVal g (v:Val) = +let ReturnTypeOfPropertyVal g (v: Val) = let membInfo, topValInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range match membInfo.MemberFlags.MemberKind with | MemberKind.PropertySet -> @@ -2357,7 +2357,7 @@ let ReturnTypeOfPropertyVal g (v:Val) = /// Get the property arguments for an F# value that represents a getter or setter /// of an object model property. -let ArgInfosOfPropertyVal g (v:Val) = +let ArgInfosOfPropertyVal g (v: Val) = let membInfo, topValInfo = checkMemberVal v.MemberInfo v.ValReprInfo v.Range match membInfo.MemberFlags.MemberKind with | MemberKind.PropertyGet -> @@ -2375,7 +2375,7 @@ let ArgInfosOfPropertyVal g (v:Val) = // Generalize type constructors to types //--------------------------------------------------------------------------- -let generalTyconRefInst (tc:TyconRef) = generalizeTypars tc.TyparsNoRange +let generalTyconRefInst (tc: TyconRef) = generalizeTypars tc.TyparsNoRange let generalizeTyconRef tc = let tinst = generalTyconRefInst tc @@ -2395,7 +2395,7 @@ let prefixOfStaticReq s = | NoStaticReq -> "'" | HeadTypeStaticReq -> " ^" -let prefixOfRigidTypar (typar:Typar) = +let prefixOfRigidTypar (typar: Typar) = if (typar.Rigidity <> TyparRigidity.Rigid) then "_" else "" //--------------------------------------------------------------------------- @@ -2405,7 +2405,7 @@ let prefixOfRigidTypar (typar:Typar) = type TyparConstraintsWithTypars = (Typar * TyparConstraint) list module PrettyTypes = - let newPrettyTypar (tp:Typar) nm = + let newPrettyTypar (tp: Typar) nm = NewTypar (tp.Kind, tp.Rigidity, Typar(ident(nm, tp.Range), tp.StaticReq, false), false, TyparDynamicReq.Yes, [], false, false) let NewPrettyTypars renaming tps names = @@ -2419,25 +2419,25 @@ module PrettyTypes = // We choose names for unit-of-measure from 'u'..'z' // If we run off the end of these ranges, we use 'aX' for positive integer X or 'uX' for positive integer X // Finally, we skip any names already in use - let NeedsPrettyTyparName (tp:Typar) = + let NeedsPrettyTyparName (tp: Typar) = tp.IsCompilerGenerated && tp.ILName.IsNone && (tp.typar_id.idText = unassignedTyparName) let PrettyTyparNames pred alreadyInUse tps = - let rec choose (tps:Typar list) (typeIndex, measureIndex) acc = + let rec choose (tps: Typar list) (typeIndex, measureIndex) acc = match tps with | [] -> List.rev acc - | tp::tps -> + | tp:: tps -> // Use a particular name, possibly after incrementing indexes let useThisName (nm, typeIndex, measureIndex) = - choose tps (typeIndex, measureIndex) (nm::acc) + choose tps (typeIndex, measureIndex) (nm:: acc) // Give up, try again with incremented indexes let tryAgain (typeIndex, measureIndex) = - choose (tp::tps) (typeIndex, measureIndex) acc + choose (tp:: tps) (typeIndex, measureIndex) acc let tryName (nm, typeIndex, measureIndex) f = if List.contains nm alreadyInUse then @@ -2638,28 +2638,28 @@ module SimplifyTypes = [] type DisplayEnv = - { includeStaticParametersInTypeNames : bool - openTopPathsSorted : Lazy - openTopPathsRaw : string list list - shortTypeNames : bool - suppressNestedTypes : bool - maxMembers : int option - showObsoleteMembers : bool - showHiddenMembers : bool - showTyparBinding : bool - showImperativeTyparAnnotations : bool - suppressInlineKeyword : bool - suppressMutableKeyword : bool - showMemberContainers : bool - shortConstraints : bool - useColonForReturnType : bool - showAttributes : bool - showOverrides : bool - showConstraintTyparAnnotations : bool - abbreviateAdditionalConstraints : bool - showTyparDefaultConstraints : bool - g : TcGlobals - contextAccessibility : Accessibility + { includeStaticParametersInTypeNames: bool + openTopPathsSorted: Lazy + openTopPathsRaw: string list list + shortTypeNames: bool + suppressNestedTypes: bool + maxMembers: int option + showObsoleteMembers: bool + showHiddenMembers: bool + showTyparBinding: bool + showImperativeTyparAnnotations: bool + suppressInlineKeyword: bool + suppressMutableKeyword: bool + showMemberContainers: bool + shortConstraints: bool + useColonForReturnType: bool + showAttributes: bool + showOverrides: bool + showConstraintTyparAnnotations: bool + abbreviateAdditionalConstraints: bool + showTyparDefaultConstraints: bool + g: TcGlobals + contextAccessibility: Accessibility generatedValueLayout : (Val -> layout option) } member x.SetOpenPaths(paths) = @@ -2781,7 +2781,7 @@ let fullNameOfParentOfValRef vref = | None -> ValueNone | Some (ValPubPath(pp, _)) -> ValueSome(fullNameOfPubPath pp) | VRefNonLocal nlr -> - ValueSome (fullNameOfEntityRef (fun (x:EntityRef) -> x.DemangledModuleOrNamespaceName) nlr.EnclosingEntity) + ValueSome (fullNameOfEntityRef (fun (x: EntityRef) -> x.DemangledModuleOrNamespaceName) nlr.EnclosingEntity) let fullNameOfParentOfValRefAsLayout vref = match vref with @@ -2790,25 +2790,25 @@ let fullNameOfParentOfValRefAsLayout vref = | None -> ValueNone | Some (ValPubPath(pp, _)) -> ValueSome(fullNameOfPubPathAsLayout pp) | VRefNonLocal nlr -> - ValueSome (fullNameOfEntityRefAsLayout (fun (x:EntityRef) -> x.DemangledModuleOrNamespaceName) nlr.EnclosingEntity) + ValueSome (fullNameOfEntityRefAsLayout (fun (x: EntityRef) -> x.DemangledModuleOrNamespaceName) nlr.EnclosingEntity) let fullDisplayTextOfParentOfModRef r = fullNameOfParentOfEntityRef r -let fullDisplayTextOfModRef r = fullNameOfEntityRef (fun (x:EntityRef) -> x.DemangledModuleOrNamespaceName) r -let fullDisplayTextOfTyconRefAsLayout r = fullNameOfEntityRefAsLayout (fun (tc:TyconRef) -> tc.DisplayNameWithStaticParametersAndUnderscoreTypars) r -let fullDisplayTextOfExnRef r = fullNameOfEntityRef (fun (tc:TyconRef) -> tc.DisplayNameWithStaticParametersAndUnderscoreTypars) r -let fullDisplayTextOfExnRefAsLayout r = fullNameOfEntityRefAsLayout (fun (tc:TyconRef) -> tc.DisplayNameWithStaticParametersAndUnderscoreTypars) r +let fullDisplayTextOfModRef r = fullNameOfEntityRef (fun (x: EntityRef) -> x.DemangledModuleOrNamespaceName) r +let fullDisplayTextOfTyconRefAsLayout r = fullNameOfEntityRefAsLayout (fun (tc: TyconRef) -> tc.DisplayNameWithStaticParametersAndUnderscoreTypars) r +let fullDisplayTextOfExnRef r = fullNameOfEntityRef (fun (tc: TyconRef) -> tc.DisplayNameWithStaticParametersAndUnderscoreTypars) r +let fullDisplayTextOfExnRefAsLayout r = fullNameOfEntityRefAsLayout (fun (tc: TyconRef) -> tc.DisplayNameWithStaticParametersAndUnderscoreTypars) r -let fullDisplayTextOfUnionCaseRef (ucref:UnionCaseRef) = fullDisplayTextOfTyconRef ucref.TyconRef +.+ ucref.CaseName -let fullDisplayTextOfRecdFieldRef (rfref:RecdFieldRef) = fullDisplayTextOfTyconRef rfref.TyconRef +.+ rfref.FieldName +let fullDisplayTextOfUnionCaseRef (ucref: UnionCaseRef) = fullDisplayTextOfTyconRef ucref.TyconRef +.+ ucref.CaseName +let fullDisplayTextOfRecdFieldRef (rfref: RecdFieldRef) = fullDisplayTextOfTyconRef rfref.TyconRef +.+ rfref.FieldName -let fullDisplayTextOfValRef (vref:ValRef) = +let fullDisplayTextOfValRef (vref: ValRef) = match fullNameOfParentOfValRef vref with | ValueNone -> vref.DisplayName | ValueSome pathText -> pathText +.+ vref.DisplayName -let fullDisplayTextOfValRefAsLayout (vref:ValRef) = +let fullDisplayTextOfValRefAsLayout (vref: ValRef) = let n = match vref.MemberInfo with | None -> @@ -2829,7 +2829,7 @@ let fullDisplayTextOfValRefAsLayout (vref:ValRef) = //pathText +.+ vref.DisplayName -let fullMangledPathToTyconRef (tcref:TyconRef) = +let fullMangledPathToTyconRef (tcref: TyconRef) = match tcref with | ERefLocal _ -> (match tcref.PublicPath with None -> [| |] | Some pp -> pp.EnclosingPath) | ERefNonLocal nlr -> nlr.EnclosingMangledPath @@ -2840,13 +2840,13 @@ let qualifiedMangledNameOfTyconRef tcref nm = let rec firstEq p1 p2 = match p1 with | [] -> true - | h1::t1 -> + | h1:: t1 -> match p2 with - | h2::t2 -> h1 = h2 && firstEq t1 t2 + | h2:: t2 -> h1 = h2 && firstEq t1 t2 | _ -> false let rec firstRem p1 p2 = - match p1 with [] -> p2 | _::t1 -> firstRem t1 (List.tail p2) + match p1 with [] -> p2 | _:: t1 -> firstRem t1 (List.tail p2) let trimPathByDisplayEnv denv path = let findOpenedNamespace openedPath = @@ -2861,7 +2861,7 @@ let trimPathByDisplayEnv denv path = | None -> if isNil path then "" else textOfPath path + "." -let superOfTycon (g:TcGlobals) (tycon:Tycon) = +let superOfTycon (g: TcGlobals) (tycon: Tycon) = match tycon.TypeContents.tcaug_super with | None -> g.obj_ty | Some ty -> ty @@ -2871,12 +2871,12 @@ let superOfTycon (g:TcGlobals) (tycon:Tycon) = //---------------------------------------------------------------------------- // AbsIL view of attributes (we read these from .NET binaries) -let isILAttribByName (tencl:string list, tname: string) (attr: ILAttribute) = +let isILAttribByName (tencl: string list, tname: string) (attr: ILAttribute) = (attr.Method.DeclaringType.TypeSpec.Name = tname) && (attr.Method.DeclaringType.TypeSpec.Enclosing = tencl) // AbsIL view of attributes (we read these from .NET binaries). The comparison is done by name. -let isILAttrib (tref:ILTypeRef) (attr: ILAttribute) = +let isILAttrib (tref: ILTypeRef) (attr: ILAttribute) = isILAttribByName (tref.Enclosing, tref.Name) attr // REVIEW: consider supporting querying on Abstract IL custom attributes. @@ -2886,7 +2886,7 @@ let isILAttrib (tref:ILTypeRef) (attr: ILAttribute) = let HasILAttribute tref (attrs: ILAttributes) = attrs.AsArray |> Array.exists (isILAttrib tref) -let TryDecodeILAttribute (g:TcGlobals) tref (attrs: ILAttributes) = +let TryDecodeILAttribute (g: TcGlobals) tref (attrs: ILAttributes) = attrs.AsArray |> Array.tryPick (fun x -> if isILAttrib tref x then Some(decodeILAttribData g.ilg x) else None) // F# view of attributes (these get converted to AbsIL attributes in ilxgen) @@ -2938,7 +2938,7 @@ let TryFindILAttributeOpt attr attrs = /// provided attributes. // // This is used for AttributeUsageAttribute, DefaultMemberAttribute and ConditionalAttribute (on attribute types) -let TryBindTyconRefAttribute g (m:range) (AttribInfo (atref, _) as args) (tcref:TyconRef) f1 f2 f3 = +let TryBindTyconRefAttribute g (m: range) (AttribInfo (atref, _) as args) (tcref: TyconRef) f1 f2 f3 = ignore m; ignore f3 match metadataOfTycon tcref.Deref with #if !NO_EXTENSIONTYPING @@ -3057,22 +3057,22 @@ let destRefCellTy g ty = | TType_app(tcref, [x]) when tyconRefEq g g.refcell_tcr_canon tcref -> x | _ -> failwith "destRefCellTy: not a ref type" -let StripSelfRefCell(g:TcGlobals, baseOrThisInfo:ValBaseOrThisInfo, tau: TType) : TType = +let StripSelfRefCell(g: TcGlobals, baseOrThisInfo: ValBaseOrThisInfo, tau: TType) : TType = if baseOrThisInfo = CtorThisVal && isRefCellTy g tau then destRefCellTy g tau else tau -let mkRefCellTy (g:TcGlobals) ty = TType_app(g.refcell_tcr_nice, [ty]) +let mkRefCellTy (g: TcGlobals) ty = TType_app(g.refcell_tcr_nice, [ty]) -let mkLazyTy (g:TcGlobals) ty = TType_app(g.lazy_tcr_nice, [ty]) +let mkLazyTy (g: TcGlobals) ty = TType_app(g.lazy_tcr_nice, [ty]) -let mkPrintfFormatTy (g:TcGlobals) aty bty cty dty ety = TType_app(g.format_tcr, [aty;bty;cty;dty; ety]) +let mkPrintfFormatTy (g: TcGlobals) aty bty cty dty ety = TType_app(g.format_tcr, [aty;bty;cty;dty; ety]) -let mkOptionTy (g:TcGlobals) ty = TType_app (g.option_tcr_nice, [ty]) +let mkOptionTy (g: TcGlobals) ty = TType_app (g.option_tcr_nice, [ty]) -let mkListTy (g:TcGlobals) ty = TType_app (g.list_tcr_nice, [ty]) +let mkListTy (g: TcGlobals) ty = TType_app (g.list_tcr_nice, [ty]) -let isOptionTy (g:TcGlobals) ty = +let isOptionTy (g: TcGlobals) ty = match tryDestAppTy g ty with | ValueNone -> false | ValueSome tcref -> tyconRefEq g g.option_tcr_canon tcref @@ -3102,8 +3102,8 @@ let destLinqExpressionTy g ty = | Some ty -> ty | None -> failwith "destLinqExpressionTy: not an expression type" -let mkNoneCase (g:TcGlobals) = mkUnionCaseRef g.option_tcr_canon "None" -let mkSomeCase (g:TcGlobals) = mkUnionCaseRef g.option_tcr_canon "Some" +let mkNoneCase (g: TcGlobals) = mkUnionCaseRef g.option_tcr_canon "None" +let mkSomeCase (g: TcGlobals) = mkUnionCaseRef g.option_tcr_canon "Some" type ValRef with member vref.IsDispatchSlot = @@ -3206,9 +3206,9 @@ module DebugPrint = let boolL = function true -> WordL.keywordTrue | false -> WordL.keywordFalse - let intL (n:int) = wordL (tagNumericLiteral (string n )) + let intL (n: int) = wordL (tagNumericLiteral (string n )) - let int64L (n:int64) = wordL (tagNumericLiteral (string n )) + let int64L (n: int64) = wordL (tagNumericLiteral (string n )) let jlistL xL xmap = QueueList.foldBack (fun x z -> z @@ xL x) xmap emptyL @@ -3238,7 +3238,7 @@ module DebugPrint = let stampL _n w = w - let layoutTyconRef (tc:TyconRef) = + let layoutTyconRef (tc: TyconRef) = wordL (tagText tc.DisplayNameWithStaticParameters) |> stampL tc.Stamp let rec auxTypeL env ty = auxTypeWrapL env false ty @@ -3283,7 +3283,7 @@ module DebugPrint = let sortCons (cs:(TyconRef * Rational) list) = cs |> List.sortBy (fun (c, _) -> c.DisplayName) let negvs, posvs = ListMeasureVarOccsWithNonZeroExponents unt |> sortVars |> List.partition (fun (_, e) -> SignRational e < 0) let negcs, poscs = ListMeasureConOccsWithNonZeroExponents g false unt |> sortCons |> List.partition (fun (_, e) -> SignRational e < 0) - let unparL (uv:Typar) = wordL (tagText ("'" + uv.DisplayName)) + let unparL (uv: Typar) = wordL (tagText ("'" + uv.DisplayName)) let unconL tc = layoutTyconRef tc let rationalL e = wordL (tagText(RationalToString e)) let measureToPowerL x e = if e = OneRational then x else x -- wordL (tagText "^") -- rationalL e @@ -3304,14 +3304,14 @@ module DebugPrint = wordL(tagText "") #endif - and auxTyparWrapL (env:SimplifyTypes.TypeSimplificationInfo) isAtomic (typar:Typar) = + and auxTyparWrapL (env: SimplifyTypes.TypeSimplificationInfo) isAtomic (typar: Typar) = let wrap x = bracketIfL isAtomic x in // wrap iff require atomic expr // There are several cases for pprinting of typar. // // 'a - is multiple occurrence. // #Type - inplace coercion constraint and singleton // ('a :> Type) - inplace coercion constraint not singleton - // ('a.opM : S->T) - inplace operator constraint + // ('a.opM: S->T) - inplace operator constraint let tpL = wordL (tagText (prefixOfStaticReq typar.StaticReq + prefixOfRigidTypar typar @@ -3453,7 +3453,7 @@ module DebugPrint = (if outFlag then wordL(tagText "[out]") else emptyL) ^^ (if inFlag then wordL(tagText "[opt]") else emptyL) - let slotSigL (slotsig:SlotSig) = + let slotSigL (slotsig: SlotSig) = #if DEBUG let (TSlotSig(nm, ty, tps1, tps2, pms, rty)) = slotsig match !global_g with @@ -3469,7 +3469,7 @@ module DebugPrint = wordL(tagText "slotsig") #endif - let rec memberL (v:Val) (membInfo:ValMemberInfo) = + let rec memberL (v: Val) (membInfo: ValMemberInfo) = aboveListL [ wordL(tagText "compiled_name! = ") ^^ wordL (tagText v.CompiledName) wordL(tagText "membInfo-slotsig! = ") ^^ listL slotSigL membInfo.ImplementedSlotSigs ] @@ -3483,11 +3483,11 @@ module DebugPrint = match v.MemberInfo with None -> () | Some mem_info -> yield wordL(tagText "!") ^^ memberL v mem_info match v.ValReprInfo with None -> () | Some arity_info -> yield wordL(tagText "#") ^^ arityInfoL arity_info] - let unionCaseRefL (ucr:UnionCaseRef) = wordL (tagText ucr.CaseName) + let unionCaseRefL (ucr: UnionCaseRef) = wordL (tagText ucr.CaseName) - let recdFieldRefL (rfref:RecdFieldRef) = wordL (tagText rfref.FieldName) + let recdFieldRefL (rfref: RecdFieldRef) = wordL (tagText rfref.FieldName) - let identL (id:Ident) = wordL (tagText id.idText) + let identL (id: Ident) = wordL (tagText id.idText) // Note: We need nice printing of constants in order to print literals and attributes let constL c = @@ -3521,7 +3521,7 @@ module DebugPrint = | Const.Zero -> "default" wordL (tagText str) - let rec tyconL (tycon:Tycon) = + let rec tyconL (tycon: Tycon) = if tycon.IsModuleOrNamespace then entityL tycon else let lhsL = wordL (tagText (match tycon.TypeOrMeasureKind with TyparKind.Measure -> "[] type" | TyparKind.Type -> "type")) ^^ wordL (tagText tycon.DisplayName) ^^ layoutTyparDecls tycon.TyparsNoRange @@ -3558,12 +3558,12 @@ module DebugPrint = let prefixL = if not (isNilOrSingleton ucases) then wordL(tagText "|") else emptyL List.map (ucaseL prefixL) ucases - let layoutRecdField (fld:RecdField) = + let layoutRecdField (fld: RecdField) = let lhs = wordL (tagText fld.Name) let lhs = if fld.IsMutable then wordL(tagText "mutable") --- lhs else lhs (lhs ^^ rightL(tagText ":")) --- typeL fld.FormalType - let tyconReprL (repr, tycon:Tycon) = + let tyconReprL (repr, tycon: Tycon) = match repr with | TRecdRepr _ -> tycon.TrueFieldsAsList |> List.map (fun fld -> layoutRecdField fld ^^ rightL(tagText ";")) |> aboveListL @@ -3804,17 +3804,17 @@ module DebugPrint = | ModuleOrNamespaceBinding.Module(mspec, rhs) -> (wordL (tagText (if mspec.IsNamespace then "namespace" else "module")) ^^ (wordL (tagText mspec.DemangledModuleOrNamespaceName) |> stampL mspec.Stamp)) @@-- mdefL rhs - and entityTypeL (mtyp:ModuleOrNamespaceType) = + and entityTypeL (mtyp: ModuleOrNamespaceType) = aboveListL [jlistL typeOfValL mtyp.AllValsAndMembers jlistL tyconL mtyp.AllEntities;] - and entityL (ms:ModuleOrNamespace) = + and entityL (ms: ModuleOrNamespace) = let header = wordL(tagText "module") ^^ (wordL (tagText ms.DemangledModuleOrNamespaceName) |> stampL ms.Stamp) ^^ wordL(tagText ":") let footer = wordL(tagText "end") let body = entityTypeL ms.ModuleOrNamespaceType (header @@-- body) @@ footer - and ccuL (ccu:CcuThunk) = entityL ccu.Contents + and ccuL (ccu: CcuThunk) = entityL ccu.Contents and decisionTreeL x = match x with @@ -3874,7 +3874,7 @@ let wrapModuleOrNamespaceTypeInNamespace id cpath mtyp = let mspec = wrapModuleOrNamespaceType id cpath mtyp NewModuleOrNamespaceType Namespace [ mspec ] [], mspec -let wrapModuleOrNamespaceExprInNamespace (id :Ident) cpath mexpr = +let wrapModuleOrNamespaceExprInNamespace (id: Ident) cpath mexpr = let mspec = wrapModuleOrNamespaceType id cpath (NewEmptyModuleOrNamespaceType Namespace) TMDefRec (false, [], [ModuleOrNamespaceBinding.Module(mspec, mexpr)], id.idRange) @@ -3920,7 +3920,7 @@ let mkRepackageRemapping mrpi = // Compute instances of the above for mty -> mty //-------------------------------------------------------------------------- -let accEntityRemap (msigty:ModuleOrNamespaceType) (entity:Entity) (mrpi, mhi) = +let accEntityRemap (msigty: ModuleOrNamespaceType) (entity: Entity) (mrpi, mhi) = let sigtyconOpt = (NameMap.tryFind entity.LogicalName msigty.AllEntitiesByCompiledAndLogicalMangledNames) match sigtyconOpt with | None -> @@ -3964,7 +3964,7 @@ let accEntityRemap (msigty:ModuleOrNamespaceType) (entity:Entity) (mrpi, mhi) = mhi (mrpi, mhi) -let accSubEntityRemap (msigty:ModuleOrNamespaceType) (entity:Entity) (mrpi, mhi) = +let accSubEntityRemap (msigty: ModuleOrNamespaceType) (entity: Entity) (mrpi, mhi) = let sigtyconOpt = (NameMap.tryFind entity.LogicalName msigty.AllEntitiesByCompiledAndLogicalMangledNames) match sigtyconOpt with | None -> @@ -3978,11 +3978,11 @@ let accSubEntityRemap (msigty:ModuleOrNamespaceType) (entity:Entity) (mrpi, mhi) let mrpi = { mrpi with RepackagedEntities = ((tcref, sigtcref) :: mrpi.RepackagedEntities) } (mrpi, mhi) -let valLinkageAEquiv g aenv (v1:Val) (v2:Val) = +let valLinkageAEquiv g aenv (v1: Val) (v2: Val) = (v1.GetLinkagePartialKey() = v2.GetLinkagePartialKey()) && (if v1.IsMember && v2.IsMember then typeAEquivAux EraseAll g aenv v1.Type v2.Type else true) -let accValRemap g aenv (msigty:ModuleOrNamespaceType) (implVal:Val) (mrpi, mhi) = +let accValRemap g aenv (msigty: ModuleOrNamespaceType) (implVal: Val) (mrpi, mhi) = let implValKey = implVal.GetLinkagePartialKey() let sigValOpt = msigty.AllValsAndMembersByPartialLinkageKey @@ -3995,22 +3995,22 @@ let accValRemap g aenv (msigty:ModuleOrNamespaceType) (implVal:Val) (mrpi, mhi) if verbose then dprintf "accValRemap, hide = %s#%d\n" implVal.LogicalName implVal.Stamp let mhi = { mhi with HiddenVals = Zset.add implVal mhi.HiddenVals } (mrpi, mhi) - | Some (sigVal:Val) -> + | Some (sigVal: Val) -> // The value is in the signature. Add the repackage entry. let mrpi = { mrpi with RepackagedVals = (vref, mkLocalValRef sigVal) :: mrpi.RepackagedVals } (mrpi, mhi) -let getCorrespondingSigTy nm (msigty:ModuleOrNamespaceType) = +let getCorrespondingSigTy nm (msigty: ModuleOrNamespaceType) = match NameMap.tryFind nm msigty.AllEntitiesByCompiledAndLogicalMangledNames with | None -> NewEmptyModuleOrNamespaceType ModuleOrType | Some sigsubmodul -> sigsubmodul.ModuleOrNamespaceType -let rec accEntityRemapFromModuleOrNamespaceType (mty:ModuleOrNamespaceType) (msigty:ModuleOrNamespaceType) acc = +let rec accEntityRemapFromModuleOrNamespaceType (mty: ModuleOrNamespaceType) (msigty: ModuleOrNamespaceType) acc = let acc = (mty.AllEntities, acc) ||> QueueList.foldBack (fun e acc -> accEntityRemapFromModuleOrNamespaceType e.ModuleOrNamespaceType (getCorrespondingSigTy e.LogicalName msigty) acc) let acc = (mty.AllEntities, acc) ||> QueueList.foldBack (accEntityRemap msigty) acc -let rec accValRemapFromModuleOrNamespaceType g aenv (mty:ModuleOrNamespaceType) msigty acc = +let rec accValRemapFromModuleOrNamespaceType g aenv (mty: ModuleOrNamespaceType) msigty acc = let acc = (mty.AllEntities, acc) ||> QueueList.foldBack (fun e acc -> accValRemapFromModuleOrNamespaceType g aenv e.ModuleOrNamespaceType (getCorrespondingSigTy e.LogicalName msigty) acc) let acc = (mty.AllValsAndMembers, acc) ||> QueueList.foldBack (accValRemap g aenv msigty) acc @@ -4029,7 +4029,7 @@ let ComputeRemappingFromInferredSignatureToExplicitSignature g mty msigty = /// At TMDefRec nodes abstract (virtual) vslots are effectively binders, even /// though they are tucked away inside the tycon. This helper function extracts the /// virtual slots to aid with finding this babies. -let abstractSlotValsOfTycons (tycons:Tycon list) = +let abstractSlotValsOfTycons (tycons: Tycon list) = tycons |> List.collect (fun tycon -> if tycon.IsFSharpObjectModelTycon then tycon.FSharpObjectModelTypeInfo.fsobjmodel_vslots else []) |> List.map (fun v -> v.Deref) @@ -4088,7 +4088,7 @@ let ComputeRemappingFromImplementationToSignature g mdef msigty = // Compute instances of the above for the assembly boundary //-------------------------------------------------------------------------- -let accTyconHidingInfoAtAssemblyBoundary (tycon:Tycon) mhi = +let accTyconHidingInfoAtAssemblyBoundary (tycon: Tycon) mhi = if not (canAccessFromEverywhere tycon.Accessibility) then // The type constructor is not public, hence hidden at the assembly boundary. { mhi with HiddenTycons = Zset.add tycon mhi.HiddenTycons } @@ -4114,7 +4114,7 @@ let accTyconHidingInfoAtAssemblyBoundary (tycon:Tycon) mhi = // Collect up the values hidden at the assembly boundary. This is used by IsHiddenVal to // determine if something is considered hidden. This is used in turn to eliminate optimization // information at the assembly boundary and to decide to label things as "internal". -let accValHidingInfoAtAssemblyBoundary (vspec:Val) mhi = +let accValHidingInfoAtAssemblyBoundary (vspec: Val) mhi = if // anything labelled "internal" or more restrictive is considered to be hidden at the assembly boundary not (canAccessFromEverywhere vspec.Accessibility) || // compiler generated members for class function 'let' bindings are considered to be hidden at the assembly boundary @@ -4127,7 +4127,7 @@ let accValHidingInfoAtAssemblyBoundary (vspec:Val) mhi = mhi let rec accModuleOrNamespaceHidingInfoAtAssemblyBoundary mty acc = - let acc = QueueList.foldBack (fun (e:Entity) acc -> accModuleOrNamespaceHidingInfoAtAssemblyBoundary e.ModuleOrNamespaceType acc) mty.AllEntities acc + let acc = QueueList.foldBack (fun (e: Entity) acc -> accModuleOrNamespaceHidingInfoAtAssemblyBoundary e.ModuleOrNamespaceType acc) mty.AllEntities acc let acc = QueueList.foldBack accTyconHidingInfoAtAssemblyBoundary mty.AllEntities acc let acc = QueueList.foldBack accValHidingInfoAtAssemblyBoundary mty.AllValsAndMembers acc acc @@ -4168,7 +4168,7 @@ let IsHiddenRecdField mrmi x = IsHidden (fun mhi -> mhi.HiddenRecdFields) (fun r let foldModuleOrNamespaceTy ft fv mty acc = let rec go mty acc = - let acc = QueueList.foldBack (fun (e:Entity) acc -> go e.ModuleOrNamespaceType acc) mty.AllEntities acc + let acc = QueueList.foldBack (fun (e: Entity) acc -> go e.ModuleOrNamespaceType acc) mty.AllEntities acc let acc = QueueList.foldBack ft mty.AllEntities acc let acc = QueueList.foldBack fv mty.AllValsAndMembers acc acc @@ -4181,10 +4181,10 @@ let allEntitiesOfModuleOrNamespaceTy m = foldModuleOrNamespaceTy (fun ft acc -> // Free variables in terms. Are all constructs public accessible? //--------------------------------------------------------------------------- -let isPublicVal (lv:Val) = (lv.Accessibility = taccessPublic) -let isPublicUnionCase (ucr:UnionCaseRef) = (ucr.UnionCase.Accessibility = taccessPublic) -let isPublicRecdField (rfr:RecdFieldRef) = (rfr.RecdField.Accessibility = taccessPublic) -let isPublicTycon (tcref:Tycon) = (tcref.Accessibility = taccessPublic) +let isPublicVal (lv: Val) = (lv.Accessibility = taccessPublic) +let isPublicUnionCase (ucr: UnionCaseRef) = (ucr.UnionCase.Accessibility = taccessPublic) +let isPublicRecdField (rfr: RecdFieldRef) = (rfr.RecdField.Accessibility = taccessPublic) +let isPublicTycon (tcref: Tycon) = (tcref.Accessibility = taccessPublic) let freeVarsAllPublic fvs = // Are any non-public items used in the expr (which corresponded to the fvs)? @@ -4255,7 +4255,7 @@ let unionFreeVars fvs1 fvs2 = FreeRecdFields = unionFreeRecdFields fvs1.FreeRecdFields fvs2.FreeRecdFields FreeUnionCases = unionFreeUnionCases fvs1.FreeUnionCases fvs2.FreeUnionCases } -let inline accFreeTyvars (opts:FreeVarOptions) f v acc = +let inline accFreeTyvars (opts: FreeVarOptions) f v acc = if not opts.collectInTypes then acc else let ftyvs = acc.FreeTyvars let ftyvs' = f opts v ftyvs @@ -4291,19 +4291,19 @@ let accUsesRethrow flg fvs = let boundLocalVals opts vs fvs = List.foldBack (boundLocalVal opts) vs fvs -let bindLhs opts (bind:Binding) fvs = boundLocalVal opts bind.Var fvs +let bindLhs opts (bind: Binding) fvs = boundLocalVal opts bind.Var fvs let freeVarsCacheCompute opts cache f = if opts.canCache then cached cache f else f() let rec accBindRhs opts (TBind(_, repr, _)) acc = accFreeInExpr opts repr acc -and accFreeInSwitchCases opts csl dflt (acc:FreeVars) = +and accFreeInSwitchCases opts csl dflt (acc: FreeVars) = Option.foldBack (accFreeInDecisionTree opts) dflt (List.foldBack (accFreeInSwitchCase opts) csl acc) and accFreeInSwitchCase opts (TCase(discrim, dtree)) acc = accFreeInDecisionTree opts dtree (accFreeInTest opts discrim acc) -and accFreeInTest (opts:FreeVarOptions) discrim acc = +and accFreeInTest (opts: FreeVarOptions) discrim acc = match discrim with | DecisionTreeTest.UnionCase(ucref, tinst) -> accFreeUnionCaseRef opts ucref (accFreeVarsInTys opts tinst acc) | DecisionTreeTest.ArrayLength(_, ty) -> accFreeVarsInTy opts ty acc @@ -4315,7 +4315,7 @@ and accFreeInTest (opts:FreeVarOptions) discrim acc = (accFreeVarsInTys opts tys (Option.foldBack (fun (vref, tinst) acc -> accFreeValRef opts vref (accFreeVarsInTys opts tinst acc)) activePatIdentity acc)) -and accFreeInDecisionTree opts x (acc : FreeVars) = +and accFreeInDecisionTree opts x (acc: FreeVars) = match x with | TDSwitch(e1, csl, dflt, _) -> accFreeInExpr opts e1 (accFreeInSwitchCases opts csl dflt acc) | TDSuccess (es, _) -> accFreeInFlatExprs opts es acc @@ -4346,7 +4346,7 @@ and accLocalTyconRepr opts b fvs = if Zset.contains b fvs.FreeLocalTyconReprs then fvs else { fvs with FreeLocalTyconReprs = Zset.add b fvs.FreeLocalTyconReprs } -and accUsedRecdOrUnionTyconRepr opts (tc:Tycon) fvs = +and accUsedRecdOrUnionTyconRepr opts (tc: Tycon) fvs = if match tc.TypeReprInfo with TFSharpObjectRepr _ | TRecdRepr _ | TUnionRepr _ -> true | _ -> false then accLocalTyconRepr opts tc fvs else fvs @@ -4368,7 +4368,7 @@ and accFreeRecdFieldRef opts rfref fvs = { fvs with FreeRecdFields = Zset.add rfref fvs.FreeRecdFields } and accFreeExnRef _exnc fvs = fvs // Note: this exnc (TyconRef) should be collected the surround types, e.g. tinst of Expr.Op -and accFreeValRef opts (vref:ValRef) fvs = +and accFreeValRef opts (vref: ValRef) fvs = match vref.IsLocalRef with | true -> accFreeLocalVal opts vref.PrivateTarget fvs // non-local values do not contain free variables @@ -4384,12 +4384,12 @@ and accFreeInMethods opts methods acc = and accFreeInInterfaceImpl opts (ty, overrides) acc = accFreeVarsInTy opts ty (accFreeInMethods opts overrides acc) -and accFreeInExpr (opts:FreeVarOptions) x acc = +and accFreeInExpr (opts: FreeVarOptions) x acc = match x with | Expr.Let _ -> accFreeInExprLinear opts x acc (fun e -> e) | _ -> accFreeInExprNonLinear opts x acc -and accFreeInExprLinear (opts:FreeVarOptions) x acc contf = +and accFreeInExprLinear (opts: FreeVarOptions) x acc contf = // for nested let-bindings, we need to continue after the whole let-binding is processed match x with | Expr.Let (bind, e, _, cache) -> @@ -4566,7 +4566,7 @@ and accFreeInTargets opts targets acc = and accFreeInTarget opts (TTarget(vs, expr, _)) acc = List.foldBack (boundLocalVal opts) vs (accFreeInExpr opts expr acc) -and accFreeInFlatExprs opts (exprs:Exprs) acc = List.foldBack (accFreeInExpr opts) exprs acc +and accFreeInFlatExprs opts (exprs: Exprs) acc = List.foldBack (accFreeInExpr opts) exprs acc and accFreeInExprs opts (exprs: Exprs) acc = match exprs with @@ -4574,7 +4574,7 @@ and accFreeInExprs opts (exprs: Exprs) acc = | [h]-> // tailcall - e.g. Cons(x, Cons(x2, .......Cons(x1000000, Nil))) and [| x1; .... ; x1000000 |] accFreeInExpr opts h acc - | h::t -> + | h:: t -> let acc = accFreeInExpr opts h acc accFreeInExprs opts t acc @@ -4686,11 +4686,11 @@ let InferArityOfExpr g allowTypeDirectedDetupling ty partialArgAttribsL retAttri let attribs = if partialAttribs.Length = tys.Length then partialAttribs else tys |> List.map (fun _ -> []) - (ids, attribs) ||> List.map2 (fun id attribs -> { Name = id; Attribs = attribs } : ArgReprInfo )) - let retInfo : ArgReprInfo = { Attribs = retAttribs; Name = None } + (ids, attribs) ||> List.map2 (fun id attribs -> { Name = id; Attribs = attribs }: ArgReprInfo )) + let retInfo: ArgReprInfo = { Attribs = retAttribs; Name = None } ValReprInfo (ValReprInfo.InferTyparInfo tps, curriedArgInfos, retInfo) -let InferArityOfExprBinding g allowTypeDirectedDetupling (v:Val) expr = +let InferArityOfExprBinding g allowTypeDirectedDetupling (v: Val) expr = match v.ValReprInfo with | Some info -> info | None -> InferArityOfExpr g allowTypeDirectedDetupling v.Type [] [] expr @@ -4731,7 +4731,7 @@ let underlyingTypeOfEnumTy (g: TcGlobals) ty = | None -> error(InternalError("no 'value__' field found for enumeration type " + tycon.LogicalName, tycon.Range)) // CLEANUP NOTE: Get rid of this mutation. -let setValHasNoArity (f:Val) = +let setValHasNoArity (f: Val) = f.SetValReprInfo None; f //-------------------------------------------------------------------------- @@ -4785,7 +4785,7 @@ let decideStaticOptimizationConstraint g c = let rec DecideStaticOptimizations g cs = match cs with | [] -> StaticOptimizationAnswer.Yes - | h::t -> + | h:: t -> let d = decideStaticOptimizationConstraint g h if d = StaticOptimizationAnswer.No then StaticOptimizationAnswer.No elif d = StaticOptimizationAnswer.Yes then DecideStaticOptimizations g t @@ -4817,13 +4817,13 @@ let markAsCompGen compgen d = | _ -> false { d with val_flags= d.val_flags.SetIsCompilerGenerated(d.val_flags.IsCompilerGenerated || compgen) } -let bindLocalVal (v:Val) (v':Val) tmenv = +let bindLocalVal (v: Val) (v': Val) tmenv = { tmenv with valRemap=tmenv.valRemap.Add v (mkLocalValRef v') } let bindLocalVals vs vs' tmenv = { tmenv with valRemap= (vs, vs', tmenv.valRemap) |||> List.foldBack2 (fun v v' acc -> acc.Add v (mkLocalValRef v') ) } -let bindTycon (tc:Tycon) (tc':Tycon) tyenv = +let bindTycon (tc: Tycon) (tc': Tycon) tyenv = { tyenv with tyconRefRemap=tyenv.tyconRefRemap.Add (mkLocalTyconRef tc) (mkLocalTyconRef tc') } let bindTycons tcs tcs' tyenv = @@ -4855,7 +4855,7 @@ and remapAttribs g tmenv xs = List.map (remapAttrib g tmenv) xs and remapPossibleForallTy g tmenv ty = remapTypeFull (remapAttribs g tmenv) tmenv ty -and remapArgData g tmenv (argInfo : ArgReprInfo) : ArgReprInfo = +and remapArgData g tmenv (argInfo: ArgReprInfo) : ArgReprInfo = { Attribs = remapAttribs g tmenv argInfo.Attribs; Name = argInfo.Name } and remapValReprInfo g tmenv (ValReprInfo(tpNames, arginfosl, retInfo)) = @@ -4886,17 +4886,17 @@ and remapParentRef tyenv p = | ParentNone -> ParentNone | Parent x -> Parent (x |> remapTyconRef tyenv.tyconRefRemap) -and mapImmediateValsAndTycons ft fv (x:ModuleOrNamespaceType) = +and mapImmediateValsAndTycons ft fv (x: ModuleOrNamespaceType) = let vals = x.AllValsAndMembers |> QueueList.map fv let tycons = x.AllEntities |> QueueList.map ft new ModuleOrNamespaceType(x.ModuleOrNamespaceKind, vals, tycons) -and copyVal compgen (v:Val) = +and copyVal compgen (v: Val) = match compgen with | OnlyCloneExprVals when v.IsMemberOrModuleBinding -> v | _ -> v |> NewModifiedVal id -and fixupValData g compgen tmenv (v2:Val) = +and fixupValData g compgen tmenv (v2: Val) = // only fixup if we copy the value match compgen with | OnlyCloneExprVals when v2.IsMemberOrModuleBinding -> () @@ -4917,7 +4917,7 @@ and copyAndRemapAndBindVal g compgen tmenv v = fixupValData g compgen tmenvinner v2 v2, tmenvinner -and remapExpr (g: TcGlobals) (compgen:ValCopyFlag) (tmenv:Remap) expr = +and remapExpr (g: TcGlobals) (compgen: ValCopyFlag) (tmenv: Remap) expr = match expr with // Handle the linear cases for arbitrary-sized inputs @@ -5126,7 +5126,7 @@ and remapDecisionTree g compgen tmenv x = let bind', tmenvinner = copyAndRemapAndBindBinding g compgen tmenv bind TDBind (bind', remapDecisionTree g compgen tmenvinner rest) -and copyAndRemapAndBindBinding g compgen tmenv (bind:Binding) = +and copyAndRemapAndBindBinding g compgen tmenv (bind: Binding) = let v = bind.Var let v', tmenv = copyAndRemapAndBindVal g compgen tmenv v remapAndRenameBind g compgen tmenv bind v' , tmenv @@ -5155,16 +5155,16 @@ and remapRecdField g tmenv x = rfield_pattribs = x.rfield_pattribs |> remapAttribs g tmenv rfield_fattribs = x.rfield_fattribs |> remapAttribs g tmenv } -and remapRecdFields g tmenv (x:TyconRecdFields) = +and remapRecdFields g tmenv (x: TyconRecdFields) = x.AllFieldsAsList |> List.map (remapRecdField g tmenv) |> MakeRecdFieldsTable -and remapUnionCase g tmenv (x:UnionCase) = +and remapUnionCase g tmenv (x: UnionCase) = { x with FieldTable = x.FieldTable |> remapRecdFields g tmenv ReturnType = x.ReturnType |> remapType tmenv Attribs = x.Attribs |> remapAttribs g tmenv } -and remapUnionCases g tmenv (x:TyconUnionData) = +and remapUnionCases g tmenv (x: TyconUnionData) = x.UnionCasesAsList |> List.map (remapUnionCase g tmenv) |> MakeUnionCases and remapFsObjData g tmenv x = @@ -5200,7 +5200,7 @@ and remapTyconRepr g tmenv repr = | TAsmRepr _ -> repr | TMeasureableRepr x -> TMeasureableRepr (remapType tmenv x) -and remapTyconAug tmenv (x:TyconAugmentation) = +and remapTyconAug tmenv (x: TyconAugmentation) = { x with tcaug_equals = x.tcaug_equals |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) tcaug_compare = x.tcaug_compare |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) @@ -5254,7 +5254,7 @@ and renameVal tmenv x = | Some v -> v.Deref | None -> x -and copyTycon compgen (tycon:Tycon) = +and copyTycon compgen (tycon: Tycon) = match compgen with | OnlyCloneExprVals -> tycon | _ -> NewClonedTycon tycon @@ -5271,7 +5271,7 @@ and copyAndRemapAndBindTyconsAndVals g compgen tmenv tycons vs = // "if a type constructor is hidden then all its inner values and inner type constructors must also be hidden" // Hence we can just lookup the inner tycon/value mappings in the tables. - let lookupVal (v:Val) = + let lookupVal (v: Val) = let vref = try let res = tmenvinner.valRemap.[v] @@ -5309,7 +5309,7 @@ and copyAndRemapAndBindTyconsAndVals g compgen tmenv tycons vs = tycons', vs', tmenvinner -and allTyconsOfTycon (tycon:Tycon) = +and allTyconsOfTycon (tycon: Tycon) = seq { yield tycon for nestedTycon in tycon.ModuleOrNamespaceType.AllEntities do yield! allTyconsOfTycon nestedTycon } @@ -5503,11 +5503,11 @@ and remarkBind m (TBind(v, repr, _)) = // Mutability analysis //-------------------------------------------------------------------------- -let isRecdOrStructFieldDefinitelyMutable (f:RecdField) = not f.IsStatic && f.IsMutable +let isRecdOrStructFieldDefinitelyMutable (f: RecdField) = not f.IsStatic && f.IsMutable -let isUnionCaseDefinitelyMutable (uc:UnionCase) = uc.FieldTable.FieldsByIndex |> Array.exists isRecdOrStructFieldDefinitelyMutable +let isUnionCaseDefinitelyMutable (uc: UnionCase) = uc.FieldTable.FieldsByIndex |> Array.exists isRecdOrStructFieldDefinitelyMutable -let isUnionCaseRefDefinitelyMutable (uc:UnionCaseRef) = uc.UnionCase |> isUnionCaseDefinitelyMutable +let isUnionCaseRefDefinitelyMutable (uc: UnionCaseRef) = uc.UnionCase |> isUnionCaseDefinitelyMutable /// This is an incomplete check for .NET struct types. Returning 'false' doesn't mean the thing is immutable. let isRecdOrUnionOrStructTyconRefDefinitelyMutable (tcref: TyconRef) = @@ -5524,7 +5524,7 @@ let isRecdOrUnionOrStructTyconRefDefinitelyMutable (tcref: TyconRef) = // Although from the pure F# perspective exception values cannot be changed, the .NET // implementation of exception objects attaches a whole bunch of stack information to // each raised object. Hence we treat exception objects as if they have identity -let isExnDefinitelyMutable (_ecref:TyconRef) = true +let isExnDefinitelyMutable (_ecref: TyconRef) = true // Some of the implementations of library functions on lists use mutation on the tail // of the cons cell. These cells are always private, i.e. not accessible by any other @@ -5532,7 +5532,7 @@ let isExnDefinitelyMutable (_ecref:TyconRef) = true // However, within the implementation code reads of the tail cell must in theory be treated // with caution. Hence we are conservative and within FSharp.Core we don't treat list // reads as if they were pure. -let isUnionCaseFieldMutable (g: TcGlobals) (ucref:UnionCaseRef) n = +let isUnionCaseFieldMutable (g: TcGlobals) (ucref: UnionCaseRef) n = (g.compilingFslib && tyconRefEq g ucref.TyconRef g.list_tcr_canon && n = 1) || (ucref.FieldByIndex n).IsMutable @@ -5540,7 +5540,7 @@ let isExnFieldMutable ecref n = if n < 0 || n >= List.length (recdFieldsOfExnDefRef ecref) then errorR(InternalError(sprintf "isExnFieldMutable, exnc = %s, n = %d" ecref.LogicalName n, ecref.Range)) (recdFieldOfExnDefRefByIdx ecref n).IsMutable -let useGenuineField (tycon:Tycon) (f:RecdField) = +let useGenuineField (tycon: Tycon) (f: RecdField) = Option.isSome f.LiteralValue || tycon.IsEnumTycon || f.rfield_secret || (not f.IsStatic && f.rfield_mutable && not tycon.IsRecordTycon) let ComputeFieldName tycon f = @@ -5555,17 +5555,17 @@ let isQuotedExprTy g ty = match tryAppTy g ty with ValueSome (tcref, _) -> tycon let destQuotedExprTy g ty = match tryAppTy g ty with ValueSome (_, [ty]) -> ty | _ -> failwith "destQuotedExprTy" -let mkQuotedExprTy (g:TcGlobals) ty = TType_app(g.expr_tcr, [ty]) +let mkQuotedExprTy (g: TcGlobals) ty = TType_app(g.expr_tcr, [ty]) -let mkRawQuotedExprTy (g:TcGlobals) = TType_app(g.raw_expr_tcr, []) +let mkRawQuotedExprTy (g: TcGlobals) = TType_app(g.raw_expr_tcr, []) -let mkAnyTupledTy (g:TcGlobals) tupInfo tys = +let mkAnyTupledTy (g: TcGlobals) tupInfo tys = match tys with | [] -> g.unit_ty | [h] -> h | _ -> TType_tuple(tupInfo, tys) -let mkAnyAnonRecdTy (_g:TcGlobals) anonInfo tys = +let mkAnyAnonRecdTy (_g: TcGlobals) anonInfo tys = TType_anon(anonInfo, tys) let mkRefTupledTy g tys = mkAnyTupledTy g tupInfoRef tys @@ -5574,9 +5574,9 @@ let mkRefTupledVarsTy g vs = mkRefTupledTy g (typesOfVals vs) let mkMethodTy g argtys rty = mkIteratedFunTy (List.map (mkRefTupledTy g) argtys) rty -let mkArrayType (g:TcGlobals) ty = TType_app (g.array_tcr_nice, [ty]) +let mkArrayType (g: TcGlobals) ty = TType_app (g.array_tcr_nice, [ty]) -let mkByteArrayTy (g:TcGlobals) = mkArrayType g g.byte_ty +let mkByteArrayTy (g: TcGlobals) = mkArrayType g g.byte_ty //-------------------------------------------------------------------------- // tyOfExpr @@ -5703,9 +5703,9 @@ let mkTyAppExpr m (f, fty) tyargs = match tyargs with [] -> f | _ -> primMkApp ( let rec accTargetsOfDecisionTree tree acc = match tree with | TDSwitch (_, cases, dflt, _) -> - List.foldBack (fun (c:DecisionTreeCase) -> accTargetsOfDecisionTree c.CaseTree) cases + List.foldBack (fun (c: DecisionTreeCase) -> accTargetsOfDecisionTree c.CaseTree) cases (Option.foldBack accTargetsOfDecisionTree dflt acc) - | TDSuccess (_, i) -> i::acc + | TDSuccess (_, i) -> i:: acc | TDBind (_, rest) -> accTargetsOfDecisionTree rest acc let rec mapTargetsOfDecisionTree f tree = @@ -5772,7 +5772,7 @@ let foldLinearBindingTargetsOfMatch tree (targets: _[]) = | TDSuccess (es, i) -> branchesToTargets.[i] <- (List.rev accBinds, es) :: branchesToTargets.[i] | TDBind (bind, rest) -> - accumulateTipsOfDecisionTree (bind::accBinds) rest + accumulateTipsOfDecisionTree (bind:: accBinds) rest // Compute the targets that can only be reached one way accumulateTipsOfDecisionTree [] tree @@ -5894,7 +5894,7 @@ let CanTakeAddressOf g m ty mut = // // We only do this for true local or closure fields because we can't take addresses of immutable static // fields across assemblies. -let CanTakeAddressOfImmutableVal (g: TcGlobals) m (vref:ValRef) mut = +let CanTakeAddressOfImmutableVal (g: TcGlobals) m (vref: ValRef) mut = // We can take the address of values of struct type if the operation doesn't mutate // and the value is a true local or closure field. not vref.IsMutable && @@ -5905,15 +5905,15 @@ let CanTakeAddressOfImmutableVal (g: TcGlobals) m (vref:ValRef) mut = // We always generate a static property but there is no field to take an address of CanTakeAddressOf g m vref.Type mut -let MustTakeAddressOfVal (g:TcGlobals) (vref:ValRef) = +let MustTakeAddressOfVal (g: TcGlobals) (vref: ValRef) = vref.IsMutable && // We can only take the address of mutable values in the same assembly valRefInThisAssembly g.compilingFslib vref -let MustTakeAddressOfByrefGet (g:TcGlobals) (vref:ValRef) = +let MustTakeAddressOfByrefGet (g: TcGlobals) (vref: ValRef) = isByrefTy g vref.Type && not (isInByrefTy g vref.Type) -let CanTakeAddressOfByrefGet (g:TcGlobals) (vref:ValRef) mut = +let CanTakeAddressOfByrefGet (g: TcGlobals) (vref: ValRef) mut = isInByrefTy g vref.Type && CanTakeAddressOf g vref.Range (destByrefTy g vref.Type) mut @@ -5924,13 +5924,13 @@ let MustTakeAddressOfRecdField (rfref: RecdField) = let MustTakeAddressOfRecdFieldRef (rfref: RecdFieldRef) = MustTakeAddressOfRecdField rfref.RecdField -let CanTakeAddressOfRecdFieldRef (g:TcGlobals) m (rfref: RecdFieldRef) tinst mut = +let CanTakeAddressOfRecdFieldRef (g: TcGlobals) m (rfref: RecdFieldRef) tinst mut = // We only do this if the field is defined in this assembly because we can't take addresses across assemblies for immutable fields entityRefInThisAssembly g.compilingFslib rfref.TyconRef && not rfref.RecdField.IsMutable && CanTakeAddressOf g m (actualTyOfRecdFieldRef rfref tinst) mut -let CanTakeAddressOfUnionFieldRef (g:TcGlobals) m (uref: UnionCaseRef) cidx tinst mut = +let CanTakeAddressOfUnionFieldRef (g: TcGlobals) m (uref: UnionCaseRef) cidx tinst mut = // We only do this if the field is defined in this assembly because we can't take addresses across assemblies for immutable fields entityRefInThisAssembly g.compilingFslib uref.TyconRef && let rfref = uref.FieldByIndex cidx @@ -6010,7 +6010,7 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress None, mkArrayElemAddress g (readonly, ilInstrReadOnlyAnnotation, isNativePtr, shape, elemTy, [aexpr; nexpr], m), readonly, writeonly // LVALUE of "e.[n1, n2]", "e.[n1, n2, n3]", "e.[n1, n2, n3, n4]" where e is an array of structs - | Expr.App(Expr.Val(vref, _, _), _, [elemTy], (aexpr::args), _) + | Expr.App(Expr.Val(vref, _, _), _, [elemTy], (aexpr:: args), _) when (valRefEq g vref g.array2D_get_vref || valRefEq g vref g.array3D_get_vref || valRefEq g vref g.array4D_get_vref) -> let readonly = false // array address is never forced to be readonly @@ -6022,7 +6022,7 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress | Some(vf) -> valRefEq g vf g.addrof2_vref | _ -> false - None, mkArrayElemAddress g (readonly, ilInstrReadOnlyAnnotation, isNativePtr, shape, elemTy, (aexpr::args), m), readonly, writeonly + None, mkArrayElemAddress g (readonly, ilInstrReadOnlyAnnotation, isNativePtr, shape, elemTy, (aexpr:: args), m), readonly, writeonly // LVALUE: "&meth(args)" where meth has a byref or inref return. Includes "&span.[idx]". | Expr.Let(TBind(vref, e, _), Expr.Op(TOp.LValueOp (LByrefGet, vref2), _, _, _), _, _) @@ -6091,16 +6091,16 @@ let mkTupleFieldGet g (tupInfo, e, tinst, i, m) = let wrap, e', _readonly, _writeonly = mkExprAddrOfExpr g (evalTupInfoIsStruct tupInfo) false NeverMutates e None m wrap (mkTupleFieldGetViaExprAddr(tupInfo, e', tinst, i, m)) -let mkAnonRecdFieldGet g (anonInfo:AnonRecdTypeInfo, e, tinst, i, m) = +let mkAnonRecdFieldGet g (anonInfo: AnonRecdTypeInfo, e, tinst, i, m) = let wrap, e', _readonly, _writeonly = mkExprAddrOfExpr g (evalAnonInfoIsStruct anonInfo) false NeverMutates e None m wrap (mkAnonRecdFieldGetViaExprAddr(anonInfo, e', tinst, i, m)) -let mkRecdFieldGet g (e, fref:RecdFieldRef, tinst, m) = +let mkRecdFieldGet g (e, fref: RecdFieldRef, tinst, m) = assert (not (isByrefTy g (tyOfExpr g e))) let wrap, e', _readonly, _writeonly = mkExprAddrOfExpr g fref.Tycon.IsStructOrEnumTycon false NeverMutates e None m wrap (mkRecdFieldGetViaExprAddr(e', fref, tinst, m)) -let mkUnionCaseFieldGetUnproven g (e, cref:UnionCaseRef, tinst, j, m) = +let mkUnionCaseFieldGetUnproven g (e, cref: UnionCaseRef, tinst, j, m) = assert (not (isByrefTy g (tyOfExpr g e))) let wrap, e', _readonly, _writeonly = mkExprAddrOfExpr g cref.Tycon.IsStructOrEnumTycon false NeverMutates e None m wrap (mkUnionCaseFieldGetUnprovenViaExprAddr (e', cref, tinst, j, m)) @@ -6127,7 +6127,7 @@ let mkArray (argty, args, m) = Expr.Op(TOp.Array, [argty], args, m) // somehow appears twice on the right. //--------------------------------------------------------------------------- -let rec IterateRecursiveFixups g (selfv : Val option) rvs ((access : Expr), set) exprToFix = +let rec IterateRecursiveFixups g (selfv: Val option) rvs ((access: Expr), set) exprToFix = let exprToFix = stripExpr exprToFix match exprToFix with | Expr.Const _ -> () @@ -6210,7 +6210,7 @@ let ExprFolder0 = /// Adapted from usage info folding. /// Collecting from exprs at moment. /// To collect ids etc some additional folding needed, over formals etc. -type ExprFolders<'State> (folders : ExprFolder<'State>) = +type ExprFolders<'State> (folders: ExprFolder<'State>) = let mutable exprFClosure = Unchecked.defaultof<'State -> Expr -> 'State> // prevent reallocation of closure let mutable exprNoInterceptFClosure = Unchecked.defaultof<'State -> Expr -> 'State> // prevent reallocation of closure @@ -6291,7 +6291,7 @@ type ExprFolders<'State> (folders : ExprFolder<'State>) = let z = folders.recBindingsIntercept z binds List.fold (bindF dtree) z binds - and bindF dtree z (bind:Binding) = + and bindF dtree z (bind: Binding) = let z = folders.valBindingSiteIntercept z (dtree, bind.Var) exprF z bind.Expr @@ -6372,21 +6372,21 @@ let ExprStats x = // //------------------------------------------------------------------------- -let mkString (g:TcGlobals) m n = Expr.Const(Const.String n, m, g.string_ty) +let mkString (g: TcGlobals) m n = Expr.Const(Const.String n, m, g.string_ty) -let mkBool (g:TcGlobals) m b = Expr.Const(Const.Bool b, m, g.bool_ty) +let mkBool (g: TcGlobals) m b = Expr.Const(Const.Bool b, m, g.bool_ty) -let mkByte (g:TcGlobals) m b = Expr.Const(Const.Byte b, m, g.byte_ty) +let mkByte (g: TcGlobals) m b = Expr.Const(Const.Byte b, m, g.byte_ty) -let mkUInt16 (g:TcGlobals) m b = Expr.Const(Const.UInt16 b, m, g.uint16_ty) +let mkUInt16 (g: TcGlobals) m b = Expr.Const(Const.UInt16 b, m, g.uint16_ty) let mkTrue g m = mkBool g m true let mkFalse g m = mkBool g m false -let mkUnit (g:TcGlobals) m = Expr.Const(Const.Unit, m, g.unit_ty) +let mkUnit (g: TcGlobals) m = Expr.Const(Const.Unit, m, g.unit_ty) -let mkInt32 (g:TcGlobals) m n = Expr.Const(Const.Int32 n, m, g.int32_ty) +let mkInt32 (g: TcGlobals) m n = Expr.Const(Const.Int32 n, m, g.int32_ty) let mkInt g m n = mkInt32 g m (n) @@ -6412,13 +6412,13 @@ let destIDelegateEventType g ty = | _ -> failwith "destIDelegateEventType: internal error" else failwith "destIDelegateEventType: not an IDelegateEvent type" -let mkIEventType (g:TcGlobals) ty1 ty2 = TType_app (g.fslib_IEvent2_tcr, [ty1;ty2]) +let mkIEventType (g: TcGlobals) ty1 ty2 = TType_app (g.fslib_IEvent2_tcr, [ty1;ty2]) -let mkIObservableType (g:TcGlobals) ty1 = TType_app (g.tcref_IObservable, [ty1]) +let mkIObservableType (g: TcGlobals) ty1 = TType_app (g.tcref_IObservable, [ty1]) -let mkIObserverType (g:TcGlobals) ty1 = TType_app (g.tcref_IObserver, [ty1]) +let mkIObserverType (g: TcGlobals) ty1 = TType_app (g.tcref_IObserver, [ty1]) -let mkRefCellContentsRef (g:TcGlobals) = mkRecdFieldRef g.refcell_tcr_canon "contents" +let mkRefCellContentsRef (g: TcGlobals) = mkRecdFieldRef g.refcell_tcr_canon "contents" let mkSequential spSeq m e1 e2 = Expr.Sequential(e1, e2, NormalSeq, spSeq, m) @@ -6427,7 +6427,7 @@ let mkCompGenSequential m e1 e2 = mkSequential SuppressSequencePointOnExprOfSequ let rec mkSequentials spSeq g m es = match es with | [e] -> e - | e::es -> mkSequential spSeq m e (mkSequentials spSeq g m es) + | e:: es -> mkSequential spSeq m e (mkSequentials spSeq g m es) | [] -> mkUnit g m let mkGetArg0 m ty = mkAsmExpr( [ mkLdarg0 ], [], [], [ty], m) @@ -6448,13 +6448,13 @@ let mkRefTupledNoTypes g m args = mkRefTupled g m args (List.map (tyOfExpr g) ar let mkRefTupledVars g m vs = mkRefTupled g m (List.map (exprForVal m) vs) (typesOfVals vs) -let mkAnonRecd (_g:TcGlobals) m anonInfo es tys = Expr.Op (TOp.AnonRecd (anonInfo),tys,es,m) +let mkAnonRecd (_g: TcGlobals) m anonInfo es tys = Expr.Op (TOp.AnonRecd (anonInfo),tys,es,m) //-------------------------------------------------------------------------- // Permute expressions //-------------------------------------------------------------------------- -let inversePerm (sigma:int array) = +let inversePerm (sigma: int array) = let n = sigma.Length let invSigma = Array.create n -1 for i = 0 to n-1 do @@ -6463,7 +6463,7 @@ let inversePerm (sigma:int array) = invSigma.[sigma_i] <- i invSigma -let permute (sigma:int[]) (data:'T[]) = +let permute (sigma: int[]) (data:'T[]) = let n = sigma.Length let invSigma = inversePerm sigma Array.init n (fun i -> data.[invSigma.[i]]) @@ -6487,12 +6487,12 @@ let liftAllBefore sigma = /// Put record field assignments in order. // -let permuteExprList (sigma:int[]) (exprs: Expr list) (ty: TType list) (names:string list) = +let permuteExprList (sigma: int[]) (exprs: Expr list) (ty: TType list) (names: string list) = let ty, names = (Array.ofList ty, Array.ofList names) let liftLim = liftAllBefore sigma - let rewrite rbinds (i, expri:Expr) = + let rewrite rbinds (i, expri: Expr) = if i < liftLim then let tmpvi, tmpei = mkCompGenLocal expri.Range names.[i] ty.[i] let bindi = mkCompGenBind tmpvi expri @@ -6510,7 +6510,7 @@ let permuteExprList (sigma:int[]) (exprs: Expr list) (ty: TType list) (names:str /// let sigma = Array.map #Index () /// However the presence of static fields means .Index may index into a non-compact set of instance field indexes. /// We still need to sort by index. -let mkRecordExpr g (lnk, tcref, tinst, rfrefs:RecdFieldRef list, args, m) = +let mkRecordExpr g (lnk, tcref, tinst, rfrefs: RecdFieldRef list, args, m) = // Remove any abbreviations let tcref, tinst = destAppTy g (mkAppTy tcref tinst) @@ -6537,9 +6537,9 @@ let mkRefCellGet g m ty e = mkRecdFieldGetViaExprAddr (e, mkRefCellContentsRef g let mkRefCellSet g m ty e1 e2 = mkRecdFieldSetViaExprAddr (e1, mkRefCellContentsRef g, [ty], e2, m) -let mkNil (g:TcGlobals) m ty = mkUnionCaseExpr (g.nil_ucref, [ty], [], m) +let mkNil (g: TcGlobals) m ty = mkUnionCaseExpr (g.nil_ucref, [ty], [], m) -let mkCons (g:TcGlobals) ty h t = mkUnionCaseExpr (g.cons_ucref, [ty], [h;t], unionRanges h.Range t.Range) +let mkCons (g: TcGlobals) ty h t = mkUnionCaseExpr (g.cons_ucref, [ty], [h;t], unionRanges h.Range t.Range) let mkCompGenLocalAndInvisbleBind g nm m e = let locv, loce = mkCompGenLocal m nm (tyOfExpr g e) @@ -6591,169 +6591,169 @@ let typedExprForIntrinsic _g m (IntrinsicValRef(_, _, _, ty, _) as i) = let vref = ValRefForIntrinsic i exprForValRef m vref, ty -let mkCallGetGenericComparer (g:TcGlobals) m = typedExprForIntrinsic g m g.get_generic_comparer_info |> fst +let mkCallGetGenericComparer (g: TcGlobals) m = typedExprForIntrinsic g m g.get_generic_comparer_info |> fst -let mkCallGetGenericEREqualityComparer (g:TcGlobals) m = typedExprForIntrinsic g m g.get_generic_er_equality_comparer_info |> fst +let mkCallGetGenericEREqualityComparer (g: TcGlobals) m = typedExprForIntrinsic g m g.get_generic_er_equality_comparer_info |> fst -let mkCallGetGenericPEREqualityComparer (g:TcGlobals) m = typedExprForIntrinsic g m g.get_generic_per_equality_comparer_info |> fst +let mkCallGetGenericPEREqualityComparer (g: TcGlobals) m = typedExprForIntrinsic g m g.get_generic_per_equality_comparer_info |> fst -let mkCallUnbox (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unbox_info, [[ty]], [ e1 ], m) +let mkCallUnbox (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unbox_info, [[ty]], [ e1 ], m) -let mkCallUnboxFast (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unbox_fast_info, [[ty]], [ e1 ], m) +let mkCallUnboxFast (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unbox_fast_info, [[ty]], [ e1 ], m) -let mkCallTypeTest (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.istype_info, [[ty]], [ e1 ], m) +let mkCallTypeTest (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.istype_info, [[ty]], [ e1 ], m) -let mkCallTypeOf (g:TcGlobals) m ty = mkApps g (typedExprForIntrinsic g m g.typeof_info, [[ty]], [ ], m) +let mkCallTypeOf (g: TcGlobals) m ty = mkApps g (typedExprForIntrinsic g m g.typeof_info, [[ty]], [ ], m) -let mkCallTypeDefOf (g:TcGlobals) m ty = mkApps g (typedExprForIntrinsic g m g.typedefof_info, [[ty]], [ ], m) +let mkCallTypeDefOf (g: TcGlobals) m ty = mkApps g (typedExprForIntrinsic g m g.typedefof_info, [[ty]], [ ], m) -let mkCallDispose (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.dispose_info, [[ty]], [ e1 ], m) +let mkCallDispose (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.dispose_info, [[ty]], [ e1 ], m) -let mkCallSeq (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.seq_info, [[ty]], [ e1 ], m) +let mkCallSeq (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.seq_info, [[ty]], [ e1 ], m) -let mkCallCreateInstance (g:TcGlobals) m ty = mkApps g (typedExprForIntrinsic g m g.create_instance_info, [[ty]], [ mkUnit g m ], m) +let mkCallCreateInstance (g: TcGlobals) m ty = mkApps g (typedExprForIntrinsic g m g.create_instance_info, [[ty]], [ mkUnit g m ], m) -let mkCallGetQuerySourceAsEnumerable (g:TcGlobals) m ty1 ty2 e1 = mkApps g (typedExprForIntrinsic g m g.query_source_as_enum_info, [[ty1;ty2]], [ e1; mkUnit g m ], m) +let mkCallGetQuerySourceAsEnumerable (g: TcGlobals) m ty1 ty2 e1 = mkApps g (typedExprForIntrinsic g m g.query_source_as_enum_info, [[ty1;ty2]], [ e1; mkUnit g m ], m) -let mkCallNewQuerySource (g:TcGlobals) m ty1 ty2 e1 = mkApps g (typedExprForIntrinsic g m g.new_query_source_info, [[ty1;ty2]], [ e1 ], m) +let mkCallNewQuerySource (g: TcGlobals) m ty1 ty2 e1 = mkApps g (typedExprForIntrinsic g m g.new_query_source_info, [[ty1;ty2]], [ e1 ], m) -let mkCallCreateEvent (g:TcGlobals) m ty1 ty2 e1 e2 e3 = mkApps g (typedExprForIntrinsic g m g.create_event_info, [[ty1;ty2]], [ e1;e2;e3 ], m) +let mkCallCreateEvent (g: TcGlobals) m ty1 ty2 e1 e2 e3 = mkApps g (typedExprForIntrinsic g m g.create_event_info, [[ty1;ty2]], [ e1;e2;e3 ], m) -let mkCallGenericComparisonWithComparerOuter (g:TcGlobals) m ty comp e1 e2 = mkApps g (typedExprForIntrinsic g m g.generic_comparison_withc_outer_info, [[ty]], [ comp;e1;e2 ], m) +let mkCallGenericComparisonWithComparerOuter (g: TcGlobals) m ty comp e1 e2 = mkApps g (typedExprForIntrinsic g m g.generic_comparison_withc_outer_info, [[ty]], [ comp;e1;e2 ], m) -let mkCallGenericEqualityEROuter (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.generic_equality_er_outer_info, [[ty]], [ e1;e2 ], m) +let mkCallGenericEqualityEROuter (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.generic_equality_er_outer_info, [[ty]], [ e1;e2 ], m) -let mkCallGenericEqualityWithComparerOuter (g:TcGlobals) m ty comp e1 e2 = mkApps g (typedExprForIntrinsic g m g.generic_equality_withc_outer_info, [[ty]], [comp;e1;e2], m) +let mkCallGenericEqualityWithComparerOuter (g: TcGlobals) m ty comp e1 e2 = mkApps g (typedExprForIntrinsic g m g.generic_equality_withc_outer_info, [[ty]], [comp;e1;e2], m) -let mkCallGenericHashWithComparerOuter (g:TcGlobals) m ty comp e1 = mkApps g (typedExprForIntrinsic g m g.generic_hash_withc_outer_info, [[ty]], [comp;e1], m) +let mkCallGenericHashWithComparerOuter (g: TcGlobals) m ty comp e1 = mkApps g (typedExprForIntrinsic g m g.generic_hash_withc_outer_info, [[ty]], [comp;e1], m) -let mkCallEqualsOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.equals_operator_info, [[ty]], [ e1;e2 ], m) +let mkCallEqualsOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.equals_operator_info, [[ty]], [ e1;e2 ], m) -let mkCallNotEqualsOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.not_equals_operator, [[ty]], [ e1;e2 ], m) +let mkCallNotEqualsOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.not_equals_operator, [[ty]], [ e1;e2 ], m) -let mkCallLessThanOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.less_than_operator, [[ty]], [ e1;e2 ], m) +let mkCallLessThanOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.less_than_operator, [[ty]], [ e1;e2 ], m) -let mkCallLessThanOrEqualsOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.less_than_or_equals_operator, [[ty]], [ e1;e2 ], m) +let mkCallLessThanOrEqualsOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.less_than_or_equals_operator, [[ty]], [ e1;e2 ], m) -let mkCallGreaterThanOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.greater_than_operator, [[ty]], [ e1;e2 ], m) +let mkCallGreaterThanOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.greater_than_operator, [[ty]], [ e1;e2 ], m) -let mkCallGreaterThanOrEqualsOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.greater_than_or_equals_operator, [[ty]], [ e1;e2 ], m) +let mkCallGreaterThanOrEqualsOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.greater_than_or_equals_operator, [[ty]], [ e1;e2 ], m) -let mkCallAdditionOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_addition_info, [[ty; ty; ty]], [e1;e2], m) +let mkCallAdditionOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_addition_info, [[ty; ty; ty]], [e1;e2], m) -let mkCallSubtractionOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_subtraction_info, [[ty; ty; ty]], [e1;e2], m) +let mkCallSubtractionOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_subtraction_info, [[ty; ty; ty]], [e1;e2], m) -let mkCallMultiplyOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_multiply_info, [[ty; ty; ty]], [e1;e2], m) +let mkCallMultiplyOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_multiply_info, [[ty; ty; ty]], [e1;e2], m) -let mkCallDivisionOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_division_info, [[ty; ty; ty]], [e1;e2], m) +let mkCallDivisionOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_division_info, [[ty; ty; ty]], [e1;e2], m) -let mkCallModulusOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_modulus_info, [[ty; ty; ty]], [e1;e2], m) +let mkCallModulusOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.unchecked_modulus_info, [[ty; ty; ty]], [e1;e2], m) -let mkCallBitwiseAndOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_and_info, [[ty]], [e1;e2], m) +let mkCallBitwiseAndOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_and_info, [[ty]], [e1;e2], m) -let mkCallBitwiseOrOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_or_info, [[ty]], [e1;e2], m) +let mkCallBitwiseOrOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_or_info, [[ty]], [e1;e2], m) -let mkCallBitwiseXorOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_xor_info, [[ty]], [e1;e2], m) +let mkCallBitwiseXorOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_xor_info, [[ty]], [e1;e2], m) -let mkCallShiftLeftOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_shift_left_info, [[ty]], [e1;e2], m) +let mkCallShiftLeftOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_shift_left_info, [[ty]], [e1;e2], m) -let mkCallShiftRightOperator (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_shift_right_info, [[ty]], [e1;e2], m) +let mkCallShiftRightOperator (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.bitwise_shift_right_info, [[ty]], [e1;e2], m) -let mkCallUnaryNegOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unchecked_unary_minus_info, [[ty]], [e1], m) +let mkCallUnaryNegOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unchecked_unary_minus_info, [[ty]], [e1], m) -let mkCallUnaryNotOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.bitwise_unary_not_info, [[ty]], [e1], m) +let mkCallUnaryNotOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.bitwise_unary_not_info, [[ty]], [e1], m) -let mkCallAdditionChecked (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.checked_addition_info, [[ty; ty; ty]], [e1;e2], m) +let mkCallAdditionChecked (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.checked_addition_info, [[ty; ty; ty]], [e1;e2], m) -let mkCallSubtractionChecked (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.checked_subtraction_info, [[ty; ty; ty]], [e1;e2], m) +let mkCallSubtractionChecked (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.checked_subtraction_info, [[ty; ty; ty]], [e1;e2], m) -let mkCallMultiplyChecked (g:TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.checked_multiply_info, [[ty; ty; ty]], [e1;e2], m) +let mkCallMultiplyChecked (g: TcGlobals) m ty e1 e2 = mkApps g (typedExprForIntrinsic g m g.checked_multiply_info, [[ty; ty; ty]], [e1;e2], m) -let mkCallUnaryNegChecked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.checked_unary_minus_info, [[ty]], [e1], m) +let mkCallUnaryNegChecked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.checked_unary_minus_info, [[ty]], [e1], m) -let mkCallToByteChecked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.byte_checked_info, [[ty]], [e1], m) +let mkCallToByteChecked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.byte_checked_info, [[ty]], [e1], m) -let mkCallToSByteChecked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.sbyte_checked_info, [[ty]], [e1], m) +let mkCallToSByteChecked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.sbyte_checked_info, [[ty]], [e1], m) -let mkCallToInt16Checked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int16_checked_info, [[ty]], [e1], m) +let mkCallToInt16Checked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int16_checked_info, [[ty]], [e1], m) -let mkCallToUInt16Checked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint16_checked_info, [[ty]], [e1], m) +let mkCallToUInt16Checked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint16_checked_info, [[ty]], [e1], m) -let mkCallToIntChecked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int_checked_info, [[ty]], [e1], m) +let mkCallToIntChecked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int_checked_info, [[ty]], [e1], m) -let mkCallToInt32Checked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int32_checked_info, [[ty]], [e1], m) +let mkCallToInt32Checked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int32_checked_info, [[ty]], [e1], m) -let mkCallToUInt32Checked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint32_checked_info, [[ty]], [e1], m) +let mkCallToUInt32Checked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint32_checked_info, [[ty]], [e1], m) -let mkCallToInt64Checked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int64_checked_info, [[ty]], [e1], m) +let mkCallToInt64Checked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int64_checked_info, [[ty]], [e1], m) -let mkCallToUInt64Checked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint64_checked_info, [[ty]], [e1], m) +let mkCallToUInt64Checked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint64_checked_info, [[ty]], [e1], m) -let mkCallToIntPtrChecked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.nativeint_checked_info, [[ty]], [e1], m) +let mkCallToIntPtrChecked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.nativeint_checked_info, [[ty]], [e1], m) -let mkCallToUIntPtrChecked (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unativeint_checked_info, [[ty]], [e1], m) +let mkCallToUIntPtrChecked (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unativeint_checked_info, [[ty]], [e1], m) -let mkCallToByteOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.byte_operator_info, [[ty]], [e1], m) +let mkCallToByteOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.byte_operator_info, [[ty]], [e1], m) -let mkCallToSByteOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.sbyte_operator_info, [[ty]], [e1], m) +let mkCallToSByteOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.sbyte_operator_info, [[ty]], [e1], m) -let mkCallToInt16Operator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int16_operator_info, [[ty]], [e1], m) +let mkCallToInt16Operator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int16_operator_info, [[ty]], [e1], m) -let mkCallToUInt16Operator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint16_operator_info, [[ty]], [e1], m) +let mkCallToUInt16Operator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint16_operator_info, [[ty]], [e1], m) -let mkCallToIntOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int_operator_info, [[ty]], [e1], m) +let mkCallToIntOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int_operator_info, [[ty]], [e1], m) -let mkCallToInt32Operator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int32_operator_info, [[ty]], [e1], m) +let mkCallToInt32Operator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int32_operator_info, [[ty]], [e1], m) -let mkCallToUInt32Operator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint32_operator_info, [[ty]], [e1], m) +let mkCallToUInt32Operator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint32_operator_info, [[ty]], [e1], m) -let mkCallToInt64Operator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int64_operator_info, [[ty]], [e1], m) +let mkCallToInt64Operator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.int64_operator_info, [[ty]], [e1], m) -let mkCallToUInt64Operator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint64_operator_info, [[ty]], [e1], m) +let mkCallToUInt64Operator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.uint64_operator_info, [[ty]], [e1], m) -let mkCallToSingleOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.float32_operator_info, [[ty]], [e1], m) +let mkCallToSingleOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.float32_operator_info, [[ty]], [e1], m) -let mkCallToDoubleOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.float_operator_info, [[ty]], [e1], m) +let mkCallToDoubleOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.float_operator_info, [[ty]], [e1], m) -let mkCallToIntPtrOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.nativeint_operator_info, [[ty]], [e1], m) +let mkCallToIntPtrOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.nativeint_operator_info, [[ty]], [e1], m) -let mkCallToUIntPtrOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unativeint_operator_info, [[ty]], [e1], m) +let mkCallToUIntPtrOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.unativeint_operator_info, [[ty]], [e1], m) -let mkCallToCharOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.char_operator_info, [[ty]], [e1], m) +let mkCallToCharOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.char_operator_info, [[ty]], [e1], m) -let mkCallToEnumOperator (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.enum_operator_info, [[ty]], [e1], m) +let mkCallToEnumOperator (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.enum_operator_info, [[ty]], [e1], m) -let mkCallArrayLength (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.array_length_info, [[ty]], [e1], m) +let mkCallArrayLength (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.array_length_info, [[ty]], [e1], m) -let mkCallArrayGet (g:TcGlobals) m ty e1 idx1 = mkApps g (typedExprForIntrinsic g m g.array_get_info, [[ty]], [ e1 ; idx1 ], m) +let mkCallArrayGet (g: TcGlobals) m ty e1 idx1 = mkApps g (typedExprForIntrinsic g m g.array_get_info, [[ty]], [ e1 ; idx1 ], m) -let mkCallArray2DGet (g:TcGlobals) m ty e1 idx1 idx2 = mkApps g (typedExprForIntrinsic g m g.array2D_get_info, [[ty]], [ e1 ; idx1; idx2 ], m) +let mkCallArray2DGet (g: TcGlobals) m ty e1 idx1 idx2 = mkApps g (typedExprForIntrinsic g m g.array2D_get_info, [[ty]], [ e1 ; idx1; idx2 ], m) -let mkCallArray3DGet (g:TcGlobals) m ty e1 idx1 idx2 idx3 = mkApps g (typedExprForIntrinsic g m g.array3D_get_info, [[ty]], [ e1 ; idx1; idx2; idx3 ], m) +let mkCallArray3DGet (g: TcGlobals) m ty e1 idx1 idx2 idx3 = mkApps g (typedExprForIntrinsic g m g.array3D_get_info, [[ty]], [ e1 ; idx1; idx2; idx3 ], m) -let mkCallArray4DGet (g:TcGlobals) m ty e1 idx1 idx2 idx3 idx4 = mkApps g (typedExprForIntrinsic g m g.array4D_get_info, [[ty]], [ e1 ; idx1; idx2; idx3; idx4 ], m) +let mkCallArray4DGet (g: TcGlobals) m ty e1 idx1 idx2 idx3 idx4 = mkApps g (typedExprForIntrinsic g m g.array4D_get_info, [[ty]], [ e1 ; idx1; idx2; idx3; idx4 ], m) -let mkCallArraySet (g:TcGlobals) m ty e1 idx1 v = mkApps g (typedExprForIntrinsic g m g.array_set_info, [[ty]], [ e1 ; idx1; v ], m) +let mkCallArraySet (g: TcGlobals) m ty e1 idx1 v = mkApps g (typedExprForIntrinsic g m g.array_set_info, [[ty]], [ e1 ; idx1; v ], m) -let mkCallArray2DSet (g:TcGlobals) m ty e1 idx1 idx2 v = mkApps g (typedExprForIntrinsic g m g.array2D_set_info, [[ty]], [ e1 ; idx1; idx2; v ], m) +let mkCallArray2DSet (g: TcGlobals) m ty e1 idx1 idx2 v = mkApps g (typedExprForIntrinsic g m g.array2D_set_info, [[ty]], [ e1 ; idx1; idx2; v ], m) -let mkCallArray3DSet (g:TcGlobals) m ty e1 idx1 idx2 idx3 v = mkApps g (typedExprForIntrinsic g m g.array3D_set_info, [[ty]], [ e1 ; idx1; idx2; idx3; v ], m) +let mkCallArray3DSet (g: TcGlobals) m ty e1 idx1 idx2 idx3 v = mkApps g (typedExprForIntrinsic g m g.array3D_set_info, [[ty]], [ e1 ; idx1; idx2; idx3; v ], m) -let mkCallArray4DSet (g:TcGlobals) m ty e1 idx1 idx2 idx3 idx4 v = mkApps g (typedExprForIntrinsic g m g.array4D_set_info, [[ty]], [ e1 ; idx1; idx2; idx3; idx4; v ], m) +let mkCallArray4DSet (g: TcGlobals) m ty e1 idx1 idx2 idx3 idx4 v = mkApps g (typedExprForIntrinsic g m g.array4D_set_info, [[ty]], [ e1 ; idx1; idx2; idx3; idx4; v ], m) -let mkCallHash (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.hash_info, [[ty]], [ e1 ], m) +let mkCallHash (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.hash_info, [[ty]], [ e1 ], m) -let mkCallBox (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.box_info, [[ty]], [ e1 ], m) +let mkCallBox (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.box_info, [[ty]], [ e1 ], m) -let mkCallIsNull (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.isnull_info, [[ty]], [ e1 ], m) +let mkCallIsNull (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.isnull_info, [[ty]], [ e1 ], m) -let mkCallIsNotNull (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.isnotnull_info, [[ty]], [ e1 ], m) +let mkCallIsNotNull (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.isnotnull_info, [[ty]], [ e1 ], m) -let mkCallRaise (g:TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.raise_info, [[ty]], [ e1 ], m) +let mkCallRaise (g: TcGlobals) m ty e1 = mkApps g (typedExprForIntrinsic g m g.raise_info, [[ty]], [ e1 ], m) -let mkCallNewDecimal (g:TcGlobals) m (e1, e2, e3, e4, e5) = mkApps g (typedExprForIntrinsic g m g.new_decimal_info, [], [ e1;e2;e3;e4;e5 ], m) +let mkCallNewDecimal (g: TcGlobals) m (e1, e2, e3, e4, e5) = mkApps g (typedExprForIntrinsic g m g.new_decimal_info, [], [ e1;e2;e3;e4;e5 ], m) -let mkCallNewFormat (g:TcGlobals) m aty bty cty dty ety e1 = mkApps g (typedExprForIntrinsic g m g.new_format_info, [[aty;bty;cty;dty;ety]], [ e1 ], m) +let mkCallNewFormat (g: TcGlobals) m aty bty cty dty ety e1 = mkApps g (typedExprForIntrinsic g m g.new_format_info, [[aty;bty;cty;dty;ety]], [ e1 ], m) let TryEliminateDesugaredConstants g m c = match c with @@ -6767,9 +6767,9 @@ let TryEliminateDesugaredConstants g m c = | _ -> None -let mkSeqTy (g:TcGlobals) ty = mkAppTy g.seq_tcr [ty] +let mkSeqTy (g: TcGlobals) ty = mkAppTy g.seq_tcr [ty] -let mkIEnumeratorTy (g:TcGlobals) ty = mkAppTy g.tcref_System_Collections_Generic_IEnumerator [ty] +let mkIEnumeratorTy (g: TcGlobals) ty = mkAppTy g.tcref_System_Collections_Generic_IEnumerator [ty] let mkCallSeqCollect g m alphaTy betaTy arg1 arg2 = let enumty2 = try rangeOfFunTy g (tyOfExpr g arg1) with _ -> (* defensive programming *) (mkSeqTy g betaTy) @@ -6822,7 +6822,7 @@ let mkCallDeserializeQuotationFSharp40Plus g m e1 e2 e3 e4 e5 = let mkCallCastQuotation g m ty e1 = mkApps g (typedExprForIntrinsic g m g.cast_quotation_info, [[ty]], [ e1 ], m) -let mkCallLiftValueWithName (g:TcGlobals) m ty nm e1 = +let mkCallLiftValueWithName (g: TcGlobals) m ty nm e1 = let vref = ValRefForIntrinsic g.lift_value_with_name_info // Use "Expr.ValueWithName" if it exists in FSharp.Core match vref.TryDeref with @@ -6891,26 +6891,26 @@ let mkStaticCall_String_Concat_Array g m arg = // Hence each of the following are marked with places where they are generated. // Generated by the optimizer and the encoding of 'for' loops -let mkDecr (g:TcGlobals) m e = mkAsmExpr([ IL.AI_sub ], [], [e; mkOne g m], [g.int_ty], m) +let mkDecr (g: TcGlobals) m e = mkAsmExpr([ IL.AI_sub ], [], [e; mkOne g m], [g.int_ty], m) -let mkIncr (g:TcGlobals) m e = mkAsmExpr([ IL.AI_add ], [], [mkOne g m; e], [g.int_ty], m) +let mkIncr (g: TcGlobals) m e = mkAsmExpr([ IL.AI_add ], [], [mkOne g m; e], [g.int_ty], m) // Generated by the pattern match compiler and the optimizer for // 1. array patterns // 2. optimizations associated with getting 'for' loops into the shape expected by the JIT. // // NOTE: The conv.i4 assumes that int_ty is int32. Note: ldlen returns native UNSIGNED int -let mkLdlen (g:TcGlobals) m arre = mkAsmExpr ([ IL.I_ldlen; (IL.AI_conv IL.DT_I4) ], [], [ arre ], [ g.int_ty ], m) +let mkLdlen (g: TcGlobals) m arre = mkAsmExpr ([ IL.I_ldlen; (IL.AI_conv IL.DT_I4) ], [], [ arre ], [ g.int_ty ], m) -let mkLdelem (_g:TcGlobals) m ty arre idxe = mkAsmExpr ([ IL.I_ldelem_any (ILArrayShape.SingleDimensional, mkILTyvarTy 0us) ], [ty], [ arre;idxe ], [ ty ], m) +let mkLdelem (_g: TcGlobals) m ty arre idxe = mkAsmExpr ([ IL.I_ldelem_any (ILArrayShape.SingleDimensional, mkILTyvarTy 0us) ], [ty], [ arre;idxe ], [ ty ], m) // This is generated in equality/compare/hash augmentations and in the pattern match compiler. // It is understood by the quotation processor and turned into "Equality" nodes. // // Note: this is IL assembly code, don't go inserting this in expressions which will be exposed via quotations -let mkILAsmCeq (g:TcGlobals) m e1 e2 = mkAsmExpr ([ IL.AI_ceq ], [], [e1; e2], [g.bool_ty], m) +let mkILAsmCeq (g: TcGlobals) m e1 e2 = mkAsmExpr ([ IL.AI_ceq ], [], [e1; e2], [g.bool_ty], m) -let mkILAsmClt (g:TcGlobals) m e1 e2 = mkAsmExpr ([ IL.AI_clt ], [], [e1; e2], [g.bool_ty], m) +let mkILAsmClt (g: TcGlobals) m e1 e2 = mkAsmExpr ([ IL.AI_clt ], [], [e1; e2], [g.bool_ty], m) // This is generated in the initialization of the "ctorv" field in the typechecker's compilation of // an implicit class construction. @@ -6925,7 +6925,7 @@ let destThrow = function let isThrow x = Option.isSome (destThrow x) // reraise - parsed as library call - internally represented as op form. -let mkReraiseLibCall (g:TcGlobals) ty m = let ve, vt = typedExprForIntrinsic g m g.reraise_info in Expr.App(ve, vt, [ty], [mkUnit g m], m) +let mkReraiseLibCall (g: TcGlobals) ty m = let ve, vt = typedExprForIntrinsic g m g.reraise_info in Expr.App(ve, vt, [ty], [mkUnit g m], m) let mkReraise m returnTy = Expr.Op (TOp.Reraise, [returnTy], [], m) (* could suppress unitArg *) @@ -6938,12 +6938,12 @@ let tnameCompilationArgumentCountsAttr = FSharpLib.Core + ".CompilationArgumentC let tnameCompilationMappingAttr = FSharpLib.Core + ".CompilationMappingAttribute" let tnameSourceConstructFlags = FSharpLib.Core + ".SourceConstructFlags" -let tref_CompilationArgumentCountsAttr (g:TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, tnameCompilationArgumentCountsAttr) -let tref_CompilationMappingAttr (g:TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, tnameCompilationMappingAttr) -let tref_CompilationSourceNameAttr (g:TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, tnameCompilationSourceNameAttr) -let tref_SourceConstructFlags (g:TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, tnameSourceConstructFlags) +let tref_CompilationArgumentCountsAttr (g: TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, tnameCompilationArgumentCountsAttr) +let tref_CompilationMappingAttr (g: TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, tnameCompilationMappingAttr) +let tref_CompilationSourceNameAttr (g: TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, tnameCompilationSourceNameAttr) +let tref_SourceConstructFlags (g: TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, tnameSourceConstructFlags) -let mkCompilationMappingAttrPrim (g:TcGlobals) k nums = +let mkCompilationMappingAttrPrim (g: TcGlobals) k nums = mkILCustomAttribute g.ilg (tref_CompilationMappingAttr g, ((mkILNonGenericValueTy (tref_SourceConstructFlags g)) :: (nums |> List.map (fun _ -> g.ilg.typ_Int32))), ((k :: nums) |> List.map (fun n -> ILAttribElem.Int32(n))), @@ -6955,17 +6955,17 @@ let mkCompilationMappingAttrWithSeqNum g kind seqNum = mkCompilationMappingAttrP let mkCompilationMappingAttrWithVariantNumAndSeqNum g kind varNum seqNum = mkCompilationMappingAttrPrim g kind [varNum;seqNum] -let mkCompilationArgumentCountsAttr (g:TcGlobals) nums = +let mkCompilationArgumentCountsAttr (g: TcGlobals) nums = mkILCustomAttribute g.ilg (tref_CompilationArgumentCountsAttr g, [ mkILArr1DTy g.ilg.typ_Int32 ], [ILAttribElem.Array (g.ilg.typ_Int32, List.map (fun n -> ILAttribElem.Int32(n)) nums)], []) -let mkCompilationSourceNameAttr (g:TcGlobals) n = +let mkCompilationSourceNameAttr (g: TcGlobals) n = mkILCustomAttribute g.ilg (tref_CompilationSourceNameAttr g, [ g.ilg.typ_String ], [ILAttribElem.String(Some n)], []) -let mkCompilationMappingAttrForQuotationResource (g:TcGlobals) (nm, tys: ILTypeRef list) = +let mkCompilationMappingAttrForQuotationResource (g: TcGlobals) (nm, tys: ILTypeRef list) = mkILCustomAttribute g.ilg (tref_CompilationMappingAttr g, [ g.ilg.typ_String; mkILArr1DTy g.ilg.typ_Type ], [ ILAttribElem.String (Some nm); ILAttribElem.Array (g.ilg.typ_Type, [ for ty in tys -> ILAttribElem.TypeRef (Some ty) ]) ], @@ -6977,10 +6977,10 @@ let mkCompilationMappingAttrForQuotationResource (g:TcGlobals) (nm, tys: ILTypeR #if !NO_EXTENSIONTYPING -let isTypeProviderAssemblyAttr (cattr:ILAttribute) = +let isTypeProviderAssemblyAttr (cattr: ILAttribute) = cattr.Method.DeclaringType.BasicQualifiedName = typeof.FullName -let TryDecodeTypeProviderAssemblyAttr ilg (cattr:ILAttribute) = +let TryDecodeTypeProviderAssemblyAttr ilg (cattr: ILAttribute) = if isTypeProviderAssemblyAttr cattr then let parms, _args = decodeILAttribData ilg cattr match parms with // The first parameter to the attribute is the name of the assembly with the compiler extensions. @@ -7003,7 +7003,7 @@ let tnames_SignatureDataVersionAttr = splitILTypeName tname_SignatureDataVersion let tref_SignatureDataVersionAttr () = mkILTyRef(IlxSettings.ilxFsharpCoreLibScopeRef (), tname_SignatureDataVersionAttr) -let mkSignatureDataVersionAttr (g:TcGlobals) ((v1, v2, v3, _) : ILVersionInfo) = +let mkSignatureDataVersionAttr (g: TcGlobals) ((v1, v2, v3, _) : ILVersionInfo) = mkILCustomAttribute g.ilg (tref_SignatureDataVersionAttr(), [g.ilg.typ_Int32;g.ilg.typ_Int32;g.ilg.typ_Int32], @@ -7015,7 +7015,7 @@ let tname_AutoOpenAttr = FSharpLib.Core + ".AutoOpenAttribute" let IsSignatureDataVersionAttr cattr = isILAttribByName ([], tname_SignatureDataVersionAttr) cattr -let TryFindAutoOpenAttr (ilg : IL.ILGlobals) cattr = +let TryFindAutoOpenAttr (ilg: IL.ILGlobals) cattr = if isILAttribByName ([], tname_AutoOpenAttr) cattr then match decodeILAttribData ilg cattr with | [ILAttribElem.String s], _ -> s @@ -7048,7 +7048,7 @@ let IsMatchingSignatureDataVersionAttr ilg ((v1, v2, v3, _) : ILVersionInfo) ca warning(Failure(FSComp.SR.tastUnexpectedDecodeOfInterfaceDataVersionAttribute())) false -let mkCompilerGeneratedAttr (g:TcGlobals) n = +let mkCompilerGeneratedAttr (g: TcGlobals) n = mkILCustomAttribute g.ilg (tref_CompilationMappingAttr g, [mkILNonGenericValueTy (tref_SourceConstructFlags g)], [ILAttribElem.Int32(n)], []) //-------------------------------------------------------------------------- @@ -7070,7 +7070,7 @@ let untupledToRefTupled g vs = // The required tupled-arity (arity) can either be 1 // or N, and likewise for the tuple-arity of the input lambda, i.e. either 1 or N // where the N's will be identical. -let AdjustArityOfLambdaBody g arity (vs:Val list) body = +let AdjustArityOfLambdaBody g arity (vs: Val list) body = let nvs = vs.Length if not (nvs = arity || nvs = 1 || arity = 1) then failwith ("lengths don't add up") if arity = 0 then @@ -7122,7 +7122,7 @@ let MultiLambdaToTupledLambdaIfNeeded g (vs, arg) body = // expressions). //------------------------------------------------------------------------ -let rec MakeApplicationAndBetaReduceAux g (f, fty, tyargsl : TType list list, argsl: Expr list, m) = +let rec MakeApplicationAndBetaReduceAux g (f, fty, tyargsl: TType list list, argsl: Expr list, m) = match f with | Expr.Let(bind, body, mlet, _) -> // Lift bindings out, i.e. (let x = e in f) y --> let x = e in f y @@ -7183,7 +7183,7 @@ let MakeApplicationAndBetaReduce g (f, fty, tyargsl, argl, m) = let MakeArgsForTopArgs _g m argtysl tpenv = argtysl |> List.mapi (fun i argtys -> - argtys |> List.mapi (fun j (argty, argInfo : ArgReprInfo) -> + argtys |> List.mapi (fun j (argty, argInfo: ArgReprInfo) -> let ty = instType tpenv argty let nm = match argInfo.Name with @@ -7191,7 +7191,7 @@ let MakeArgsForTopArgs _g m argtysl tpenv = | Some id -> id.idText fst (mkCompGenLocal m nm ty))) -let AdjustValForExpectedArity g m (vref:ValRef) flags topValInfo = +let AdjustValForExpectedArity g m (vref: ValRef) flags topValInfo = let tps, argtysl, rty, _ = GetTopValTypeInFSharpForm g topValInfo vref.Type m let tps' = copyTypars tps @@ -7282,7 +7282,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex // Use the nice names for a function of known arity and name. Note that 'nice' here also // carries a semantic meaning. For a function with top-info, - // let f (x:A) (y:A) (z:A) = ... + // let f (x: A) (y: A) (z: A) = ... // we know there are no side effects on the application of 'f' to 1, 2 args. This greatly simplifies // the closure built for // f b1 b2 @@ -7338,7 +7338,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex /// Given an argument variable of tuple type that has been evaluated and stored in the /// given variable, where the tuple type that satisfies the input argument types, /// coerce it to a tuple that satisfies the matching coerced argument type(s). - let CoerceBoundTuple tupleVar argTys (actualTys : TType list) = + let CoerceBoundTuple tupleVar argTys (actualTys: TType list) = assert (actualTys.Length > 1) mkRefTupled g appm @@ -7364,7 +7364,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex if buildingLambdas then // Evaluate the user-supplied tuple-valued argument expression, inject the coercions and build an explicit tuple // Assign the argument to make sure it is only run once - // f ~~> : B -> int + // f ~~>: B -> int // f ~~> : (B * B) -> int // // for @@ -7420,7 +7420,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex let N = argTys.Length let (cloVar, exprForOtherArgs, _) = List.foldBack - (fun (i, inpArgTy, actualArgTys) (cloVar:Val, res, resTy) -> + (fun (i, inpArgTy, actualArgTys) (cloVar: Val, res, resTy) -> let inpArgTys = match actualArgTys with @@ -7490,7 +7490,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex // If no trailing args then we can skip introducing the dummy variable // This corresponds to - // let f (x:A) = 1 + // let f (x: A) = 1 // // f ~~> type B -> int // @@ -7551,7 +7551,7 @@ let NormalizeAndAdjustPossibleSubsumptionExprs g inputExpr = let etaExpandTypeLambda g m tps (tm, ty) = if isNil tps then tm else mkTypeLambda m tps (mkApps g ((tm, ty), [(List.map mkTyparTy tps)], [], m), ty) -let AdjustValToTopVal (tmp:Val) parent valData = +let AdjustValToTopVal (tmp: Val) parent valData = tmp.SetValReprInfo (Some valData) tmp.SetDeclaringEntity parent tmp.SetIsMemberOrModuleBinding() @@ -7622,7 +7622,7 @@ let LinearizeTopMatch g parent = function let commaEncs strs = String.concat "," strs let angleEnc str = "{" + str + "}" -let ticksAndArgCountTextOfTyconRef (tcref:TyconRef) = +let ticksAndArgCountTextOfTyconRef (tcref: TyconRef) = // Generic type names are (name + "`" + digits) where name does not contain "`". let path = Array.toList (fullMangledPathToTyconRef tcref) @ [tcref.CompiledName] textOfPath path @@ -7704,7 +7704,7 @@ let XmlDocArgsEnc g (gtpsType, gtpsMethod) argTs = if isNil argTs then "" else "(" + String.concat "," (List.map (typeEnc g (gtpsType, gtpsMethod)) argTs) + ")" -let buildAccessPath (cp : CompilationPath option) = +let buildAccessPath (cp: CompilationPath option) = match cp with | Some(cp) -> let ap = cp.AccessPath |> List.map fst |> List.toArray @@ -7712,7 +7712,7 @@ let buildAccessPath (cp : CompilationPath option) = | None -> "Extension Type" let prependPath path name = if path = "" then name else path + "." + name -let XmlDocSigOfVal g path (v:Val) = +let XmlDocSigOfVal g path (v: Val) = let parentTypars, methTypars, argInfos, prefix, path, name = // CLEANUP: this is one of several code paths that treat module values and members @@ -7764,7 +7764,7 @@ let XmlDocSigOfTycon = BuildXmlDocSig "T:" let XmlDocSigOfSubModul = BuildXmlDocSig "T:" -let XmlDocSigOfEntity (eref:EntityRef) = +let XmlDocSigOfEntity (eref: EntityRef) = XmlDocSigOfTycon [(buildAccessPath eref.CompilationPathOpt); eref.Deref.CompiledName] //-------------------------------------------------------------------------- @@ -7783,10 +7783,10 @@ let HasUseNullAsTrueValueAttribute g attribs = | Some(flags) -> ((flags &&& enum_CompilationRepresentationAttribute_PermitNull) <> 0) | _ -> false -let TyconHasUseNullAsTrueValueAttribute g (tycon:Tycon) = HasUseNullAsTrueValueAttribute g tycon.Attribs +let TyconHasUseNullAsTrueValueAttribute g (tycon: Tycon) = HasUseNullAsTrueValueAttribute g tycon.Attribs // WARNING: this must match optimizeAlternativeToNull in ilx/cu_erase.fs -let CanHaveUseNullAsTrueValueAttribute (_g:TcGlobals) (tycon:Tycon) = +let CanHaveUseNullAsTrueValueAttribute (_g: TcGlobals) (tycon: Tycon) = (tycon.IsUnionTycon && let ucs = tycon.UnionCasesArray (ucs.Length = 0 || @@ -7794,7 +7794,7 @@ let CanHaveUseNullAsTrueValueAttribute (_g:TcGlobals) (tycon:Tycon) = ucs |> Array.exists (fun uc -> not uc.IsNullary)))) // WARNING: this must match optimizeAlternativeToNull in ilx/cu_erase.fs -let IsUnionTypeWithNullAsTrueValue (g:TcGlobals) (tycon:Tycon) = +let IsUnionTypeWithNullAsTrueValue (g: TcGlobals) (tycon: Tycon) = (tycon.IsUnionTycon && let ucs = tycon.UnionCasesArray (ucs.Length = 0 || @@ -7939,9 +7939,9 @@ let mkNullTest g m e1 e2 e3 = let dtree = TDSwitch(e1, [TCase(DecisionTreeTest.IsNull, tg3)], Some tg2, m) let expr = mbuilder.Close(dtree, m, tyOfExpr g e2) expr -let mkNonNullTest (g:TcGlobals) m e = mkAsmExpr ([ IL.AI_ldnull ; IL.AI_cgt_un ], [], [e], [g.bool_ty], m) +let mkNonNullTest (g: TcGlobals) m e = mkAsmExpr ([ IL.AI_ldnull ; IL.AI_cgt_un ], [], [e], [g.bool_ty], m) let mkNonNullCond g m ty e1 e2 e3 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m ty (mkNonNullTest g m e1) e2 e3 -let mkIfThen (g:TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.unit_ty e1 e2 (mkUnit g m) +let mkIfThen (g: TcGlobals) m e1 e2 = mkCond NoSequencePointAtStickyBinding SuppressSequencePointAtTarget m g.unit_ty e1 e2 (mkUnit g m) let ModuleNameIsMangled g attrs = @@ -7952,7 +7952,7 @@ let ModuleNameIsMangled g attrs = let CompileAsEvent g attrs = HasFSharpAttribute g g.attrib_CLIEventAttribute attrs -let MemberIsCompiledAsInstance g parent isExtensionMember (membInfo:ValMemberInfo) attrs = +let MemberIsCompiledAsInstance g parent isExtensionMember (membInfo: ValMemberInfo) attrs = // All extension members are compiled as static members if isExtensionMember then false // Anything implementing a dispatch slot is compiled as an instance member @@ -7997,7 +7997,7 @@ let isComInteropTy g ty = | None -> false | Some attr -> TryFindFSharpBoolAttribute g attr tcref.Attribs = Some(true) -let ValSpecIsCompiledAsInstance g (v:Val) = +let ValSpecIsCompiledAsInstance g (v: Val) = match v.MemberInfo with | Some(membInfo) -> // Note it doesn't matter if we pass 'v.TopValDeclaringEntity' or 'v.MemberApparentEntity' here. @@ -8013,7 +8013,7 @@ let ValRefIsCompiledAsInstanceMember g (vref: ValRef) = ValSpecIsCompiledAsInsta // Crack information about an F# object model call //--------------------------------------------------------------------------- -let GetMemberCallInfo g (vref:ValRef, vFlags) = +let GetMemberCallInfo g (vref: ValRef, vFlags) = match vref.MemberInfo with | Some(membInfo) when not vref.IsExtensionMember -> let numEnclTypeArgs = vref.MemberApparentEntity.TyparsNoRange.Length @@ -8038,7 +8038,7 @@ let GetMemberCallInfo g (vref:ValRef, vFlags) = //--------------------------------------------------------------------------- -let TryGetActivePatternInfo (vref:ValRef) = +let TryGetActivePatternInfo (vref: ValRef) = // First is an optimization to prevent calls to CoreDisplayName, which calls DemangleOperatorName let logicalName = vref.LogicalName if logicalName.Length = 0 || logicalName.[0] <> '|' then @@ -8056,7 +8056,7 @@ type ActivePatternElemRef with if n < 0 || n >= List.length nms then error(InternalError("name_of_apref: index out of range for active pattern reference", vref.Range)) List.item n nms -let mkChoiceTyconRef (g:TcGlobals) m n = +let mkChoiceTyconRef (g: TcGlobals) m n = match n with | 0 | 1 -> error(InternalError("mkChoiceTyconRef", m)) | 2 -> g.choice2_tcr @@ -8067,7 +8067,7 @@ let mkChoiceTyconRef (g:TcGlobals) m n = | 7 -> g.choice7_tcr | _ -> error(Error(FSComp.SR.tastActivePatternsLimitedToSeven(), m)) -let mkChoiceTy (g:TcGlobals) m tinst = +let mkChoiceTy (g: TcGlobals) m tinst = match List.length tinst with | 0 -> g.unit_ty | 1 -> List.head tinst @@ -8092,7 +8092,7 @@ type PrettyNaming.ActivePatternInfo with // check if an active pattern takes type parameters only bound by the return types, // not by their argument types. -let doesActivePatternHaveFreeTypars g (v:ValRef) = +let doesActivePatternHaveFreeTypars g (v: ValRef) = let vty = v.TauType let vtps = v.Typars |> Zset.ofList typarOrder if not (isFunTy g v.TauType) then @@ -8308,9 +8308,9 @@ and RewriteImplFile env mv = mapTImplFile (rewriteModuleOrNamespaceExpr env) mv // accessed via non local references. //-------------------------------------------------------------------------- -let MakeExportRemapping viewedCcu (mspec:ModuleOrNamespace) = +let MakeExportRemapping viewedCcu (mspec: ModuleOrNamespace) = - let accEntityRemap (entity:Entity) acc = + let accEntityRemap (entity: Entity) acc = match tryRescopeEntity viewedCcu entity with | ValueSome eref -> addTyconRefRemap (mkLocalTyconRef entity) eref acc @@ -8320,7 +8320,7 @@ let MakeExportRemapping viewedCcu (mspec:ModuleOrNamespace) = else error(InternalError("Unexpected entity without a pubpath when remapping assembly data", entity.Range)) - let accValRemap (vspec:Val) acc = + let accValRemap (vspec: Val) acc = // The acc contains the entity remappings match tryRescopeVal viewedCcu acc vspec with | ValueSome vref -> @@ -8391,7 +8391,7 @@ let isCompiledConstraint cx = // Is a value a first-class polymorphic value with .NET constraints? // Used to turn off TLR and method splitting -let IsGenericValWithGenericContraints g (v:Val) = +let IsGenericValWithGenericContraints g (v: Val) = isForallTy g v.Type && v.Type |> destForallTy g |> fst |> List.exists (fun tp -> List.exists isCompiledConstraint tp.Constraints) @@ -8430,7 +8430,7 @@ type EntityRef with member tcref.HasOverride g nm argtys = tcref.Deref.HasOverride g nm argtys member tcref.HasMember g nm argtys = tcref.Deref.HasMember g nm argtys -let mkFastForLoop g (spLet, m, idv:Val, start, dir, finish, body) = +let mkFastForLoop g (spLet, m, idv: Val, start, dir, finish, body) = let dir = if dir then FSharpForLoopUp else FSharpForLoopDown mkFor g (spLet, idv, start, dir, finish, body, m) @@ -8496,7 +8496,7 @@ let IsSimpleSyntacticConstantExpr g inputExpr = checkExpr Set.empty inputExpr -let EvalArithBinOp (opInt8, opInt16, opInt32, opInt64, opUInt8, opUInt16, opUInt32, opUInt64) (arg1:Expr) (arg2:Expr) = +let EvalArithBinOp (opInt8, opInt16, opInt32, opInt64, opUInt8, opUInt16, opUInt32, opUInt64) (arg1: Expr) (arg2: Expr) = // At compile-time we check arithmetic let m = unionRanges arg1.Range arg2.Range try @@ -8613,7 +8613,7 @@ let EvalLiteralExprOrAttribArg g x = // // This is the right abstraction for viewing member types, but the implementation // below is a little ugly. -let GetTypeOfIntrinsicMemberInCompiledForm g (vref:ValRef) = +let GetTypeOfIntrinsicMemberInCompiledForm g (vref: ValRef) = assert (not vref.IsExtensionMember) let membInfo, topValInfo = checkMemberValRef vref let tps, argInfos, rty, retInfo = GetTypeOfMemberInMemberForm g vref @@ -8626,7 +8626,7 @@ let GetTypeOfIntrinsicMemberInCompiledForm g (vref:ValRef) = | [] -> errorR(InternalError("value does not have a valid member type", vref.Range)) argInfos - | h::_ -> h ::argInfos + | h::_ -> h :: argInfos else argInfos tps, argInfos, rty, retInfo @@ -8662,13 +8662,13 @@ let rec mkCompiledTuple g isStruct (argtys, args, m) = let argtysAB = argtysA @ [ty8] (mkCompiledTupleTyconRef g isStruct (List.length argtysAB), argtysAB, argsA @ [v8], m) -let mkILMethodSpecForTupleItem (_g : TcGlobals) (ty:ILType) n = +let mkILMethodSpecForTupleItem (_g: TcGlobals) (ty: ILType) n = mkILNonGenericInstanceMethSpecInTy(ty, (if n < goodTupleFields then "get_Item"+(n+1).ToString() else "get_Rest"), [], mkILTyvarTy (uint16 n)) -let mkILFieldSpecForTupleItem (ty:ILType) n = +let mkILFieldSpecForTupleItem (ty: ILType) n = mkILFieldSpecInTy (ty, (if n < goodTupleFields then "Item"+(n+1).ToString() else "Rest"), mkILTyvarTy (uint16 n)) -let mkGetTupleItemN g m n (ty:ILType) isStruct te retty = +let mkGetTupleItemN g m n (ty: ILType) isStruct te retty = if isStruct then mkAsmExpr([mkNormalLdfld (mkILFieldSpecForTupleItem ty n) ], [], [te], [retty], m) else @@ -8836,7 +8836,7 @@ let (|InnerExprPat|) expr = stripExpr expr /// is to eliminate variables of static type "unit". These is a /// utility function related to this. -let BindUnitVars g (mvs:Val list, paramInfos:ArgReprInfo list, body) = +let BindUnitVars g (mvs: Val list, paramInfos: ArgReprInfo list, body) = match mvs, paramInfos with | [v], [] -> assert isUnitTy g v.Type diff --git a/src/fsharp/TastPickle.fs b/src/fsharp/TastPickle.fs index 9d00cf4d4aa..95f471c6fd4 100755 --- a/src/fsharp/TastPickle.fs +++ b/src/fsharp/TastPickle.fs @@ -197,65 +197,65 @@ let p_used_space1 f st = // leave more space p_space 1 space st -let p_bytes (s:byte[]) st = +let p_bytes (s: byte[]) st = let len = s.Length p_int32 (len) st st.os.EmitBytes s -let p_prim_string (s:string) st = +let p_prim_string (s: string) st = let bytes = Encoding.UTF8.GetBytes s let len = bytes.Length p_int32 (len) st st.os.EmitBytes bytes let p_int c st = p_int32 c st -let p_int8 (i:sbyte) st = p_int32 (int32 i) st -let p_uint8 (i:byte) st = p_byte (int i) st -let p_int16 (i:int16) st = p_int32 (int32 i) st -let p_uint16 (x:uint16) st = p_int32 (int32 x) st -let p_uint32 (x:uint32) st = p_int32 (int32 x) st -let p_int64 (i:int64) st = +let p_int8 (i: sbyte) st = p_int32 (int32 i) st +let p_uint8 (i: byte) st = p_byte (int i) st +let p_int16 (i: int16) st = p_int32 (int32 i) st +let p_uint16 (x: uint16) st = p_int32 (int32 x) st +let p_uint32 (x: uint32) st = p_int32 (int32 x) st +let p_int64 (i: int64) st = p_int32 (int32 (i &&& 0xFFFFFFFFL)) st p_int32 (int32 (i >>> 32)) st -let p_uint64 (x:uint64) st = p_int64 (int64 x) st +let p_uint64 (x: uint64) st = p_int64 (int64 x) st -let bits_of_float32 (x:float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) -let bits_of_float (x:float) = System.BitConverter.DoubleToInt64Bits(x) +let bits_of_float32 (x: float32) = System.BitConverter.ToInt32(System.BitConverter.GetBytes(x), 0) +let bits_of_float (x: float) = System.BitConverter.DoubleToInt64Bits(x) let p_single i st = p_int32 (bits_of_float32 i) st let p_double i st = p_int64 (bits_of_float i) st let p_ieee64 i st = p_int64 (bits_of_float i) st let p_char i st = p_uint16 (uint16 (int32 i)) st -let inline p_tup2 p1 p2 (a, b) (st:WriterState) = +let inline p_tup2 p1 p2 (a, b) (st: WriterState) = (p1 a st : unit); (p2 b st : unit) -let inline p_tup3 p1 p2 p3 (a, b, c) (st:WriterState) = +let inline p_tup3 p1 p2 p3 (a, b, c) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit) -let inline p_tup4 p1 p2 p3 p4 (a, b, c, d) (st:WriterState) = +let inline p_tup4 p1 p2 p3 p4 (a, b, c, d) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit) -let inline p_tup5 p1 p2 p3 p4 p5 (a, b, c, d, e) (st:WriterState) = +let inline p_tup5 p1 p2 p3 p4 p5 (a, b, c, d, e) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit) -let inline p_tup6 p1 p2 p3 p4 p5 p6 (a, b, c, d, e, f) (st:WriterState) = +let inline p_tup6 p1 p2 p3 p4 p5 p6 (a, b, c, d, e, f) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit) -let inline p_tup7 p1 p2 p3 p4 p5 p6 p7 (a, b, c, d, e, f, x7) (st:WriterState) = +let inline p_tup7 p1 p2 p3 p4 p5 p6 p7 (a, b, c, d, e, f, x7) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit) -let inline p_tup8 p1 p2 p3 p4 p5 p6 p7 p8 (a, b, c, d, e, f, x7, x8) (st:WriterState) = +let inline p_tup8 p1 p2 p3 p4 p5 p6 p7 p8 (a, b, c, d, e, f, x7, x8) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit); (p8 x8 st : unit) -let inline p_tup9 p1 p2 p3 p4 p5 p6 p7 p8 p9 (a, b, c, d, e, f, x7, x8, x9) (st:WriterState) = +let inline p_tup9 p1 p2 p3 p4 p5 p6 p7 p8 p9 (a, b, c, d, e, f, x7, x8, x9) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit); (p8 x8 st : unit); (p9 x9 st : unit) -let inline p_tup10 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 (a, b, c, d, e, f, x7, x8, x9, x10) (st:WriterState) = +let inline p_tup10 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 (a, b, c, d, e, f, x7, x8, x9, x10) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit); (p8 x8 st : unit); (p9 x9 st : unit); (p10 x10 st : unit) -let inline p_tup11 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 (a, b, c, d, e, f, x7, x8, x9, x10, x11) (st:WriterState) = +let inline p_tup11 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 (a, b, c, d, e, f, x7, x8, x9, x10, x11) (st: WriterState) = (p1 a st : unit); (p2 b st : unit); (p3 c st : unit); (p4 d st : unit); (p5 e st : unit); (p6 f st : unit); (p7 x7 st : unit); (p8 x8 st : unit); (p9 x9 st : unit); (p10 x10 st : unit); (p11 x11 st : unit) let u_byte st = int (st.is.ReadByte()) @@ -304,8 +304,8 @@ let u_int64 st = b1 ||| (b2 <<< 32) let u_uint64 st = uint64 (u_int64 st) -let float32_of_bits (x:int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) -let float_of_bits (x:int64) = System.BitConverter.Int64BitsToDouble(x) +let float32_of_bits (x: int32) = System.BitConverter.ToSingle(System.BitConverter.GetBytes(x), 0) +let float_of_bits (x: int64) = System.BitConverter.Int64BitsToDouble(x) let u_single st = float32_of_bits (u_int32 st) let u_double st = float_of_bits (u_int64 st) @@ -332,15 +332,15 @@ let u_used_space1 f st = warning(Error(FSComp.SR.pickleUnexpectedNonZero st.ifile, range0)); None -let inline u_tup2 p1 p2 (st:ReaderState) = let a = p1 st in let b = p2 st in (a, b) +let inline u_tup2 p1 p2 (st: ReaderState) = let a = p1 st in let b = p2 st in (a, b) -let inline u_tup3 p1 p2 p3 (st:ReaderState) = +let inline u_tup3 p1 p2 p3 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in (a, b, c) -let inline u_tup4 p1 p2 p3 p4 (st:ReaderState) = +let inline u_tup4 p1 p2 p3 p4 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in (a, b, c, d) -let inline u_tup5 p1 p2 p3 p4 p5 (st:ReaderState) = +let inline u_tup5 p1 p2 p3 p4 p5 (st: ReaderState) = let a = p1 st let b = p2 st let c = p3 st @@ -348,61 +348,61 @@ let inline u_tup5 p1 p2 p3 p4 p5 (st:ReaderState) = let e = p5 st (a, b, c, d, e) -let inline u_tup6 p1 p2 p3 p4 p5 p6 (st:ReaderState) = +let inline u_tup6 p1 p2 p3 p4 p5 p6 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in (a, b, c, d, e, f) -let inline u_tup7 p1 p2 p3 p4 p5 p6 p7 (st:ReaderState) = +let inline u_tup7 p1 p2 p3 p4 p5 p6 p7 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in (a, b, c, d, e, f, x7) -let inline u_tup8 p1 p2 p3 p4 p5 p6 p7 p8 (st:ReaderState) = +let inline u_tup8 p1 p2 p3 p4 p5 p6 p7 p8 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in (a, b, c, d, e, f, x7, x8) -let inline u_tup9 p1 p2 p3 p4 p5 p6 p7 p8 p9 (st:ReaderState) = +let inline u_tup9 p1 p2 p3 p4 p5 p6 p7 p8 p9 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in (a, b, c, d, e, f, x7, x8, x9) -let inline u_tup10 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 (st:ReaderState) = +let inline u_tup10 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in (a, b, c, d, e, f, x7, x8, x9, x10) -let inline u_tup11 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 (st:ReaderState) = +let inline u_tup11 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11) -let inline u_tup12 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 (st:ReaderState) = +let inline u_tup12 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12) -let inline u_tup13 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 (st:ReaderState) = +let inline u_tup13 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12, x13) -let inline u_tup14 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 (st:ReaderState) = +let inline u_tup14 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in let x14 = p14 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12, x13, x14) -let inline u_tup15 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 (st:ReaderState) = +let inline u_tup15 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in let x14 = p14 st in let x15 = p15 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12, x13, x14, x15) -let inline u_tup16 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 (st:ReaderState) = +let inline u_tup16 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in let x14 = p14 st in let x15 = p15 st in let x16 = p16 st in (a, b, c, d, e, f, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16) -let inline u_tup17 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 p17 (st:ReaderState) = +let inline u_tup17 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 p17 (st: ReaderState) = let a = p1 st in let b = p2 st in let c = p3 st in let d = p4 st in let e = p5 st in let f = p6 st in let x7 = p7 st in let x8 = p8 st in let x9 = p9 st in let x10 = p10 st in let x11 = p11 st in let x12 = p12 st in let x13 = p13 st in @@ -417,7 +417,7 @@ let inline u_tup17 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 p17 (s // exception Nope // ctxt is for debugging -let p_osgn_ref (_ctxt:string) (outMap : NodeOutTable<_, _>) x st = +let p_osgn_ref (_ctxt: string) (outMap : NodeOutTable<_, _>) x st = let idx = outMap.Table.FindOrAdd (outMap.NodeStamp x) //if ((idx = 0) && outMap.Name = "oentities") then // let msg = @@ -635,7 +635,7 @@ let u_option f st = // Boobytrap an OSGN node with a force of a lazy load of a bunch of pickled data #if LAZY_UNPICKLE -let wire (x:osgn<_>) (res:Lazy<_>) = +let wire (x: osgn<_>) (res: Lazy<_>) = x.osgnTripWire <- Some(fun () -> res.Force() |> ignore) #endif @@ -698,7 +698,7 @@ let p_ints = p_list p_int // CCU References // A huge number of these occur in pickled F# data, so make them unique -let encode_ccuref ccuTab (x:CcuThunk) = encode_uniq ccuTab x.AssemblyName +let encode_ccuref ccuTab (x: CcuThunk) = encode_uniq ccuTab x.AssemblyName let decode_ccuref x = x let lookup_ccuref st ccuTab x = lookup_uniq st ccuTab x let u_encoded_ccuref st = @@ -768,10 +768,10 @@ let pickleObjWithDanglingCcus inMem file g scope p x = { os = ByteBuffer.Create 100000 oscope=scope occus= Table<_>.Create "occus" - oentities=NodeOutTable<_, _>.Create((fun (tc:Tycon) -> tc.Stamp), (fun tc -> tc.LogicalName), (fun tc -> tc.Range), (fun osgn -> osgn), "otycons") - otypars=NodeOutTable<_, _>.Create((fun (tp:Typar) -> tp.Stamp), (fun tp -> tp.DisplayName), (fun tp -> tp.Range), (fun osgn -> osgn), "otypars") - ovals=NodeOutTable<_, _>.Create((fun (v:Val) -> v.Stamp), (fun v -> v.LogicalName), (fun v -> v.Range), (fun osgn -> osgn), "ovals") - oanoninfos=NodeOutTable<_, _>.Create((fun (v:AnonRecdTypeInfo) -> v.Stamp), (fun v -> string v.Stamp), (fun _ -> range0), id, "oanoninfos") + oentities=NodeOutTable<_, _>.Create((fun (tc: Tycon) -> tc.Stamp), (fun tc -> tc.LogicalName), (fun tc -> tc.Range), (fun osgn -> osgn), "otycons") + otypars=NodeOutTable<_, _>.Create((fun (tp: Typar) -> tp.Stamp), (fun tp -> tp.DisplayName), (fun tp -> tp.Range), (fun osgn -> osgn), "otypars") + ovals=NodeOutTable<_, _>.Create((fun (v: Val) -> v.Stamp), (fun v -> v.LogicalName), (fun v -> v.Range), (fun osgn -> osgn), "ovals") + oanoninfos=NodeOutTable<_, _>.Create((fun (v: AnonRecdTypeInfo) -> v.Stamp), (fun v -> string v.Stamp), (fun _ -> range0), id, "oanoninfos") ostrings=Table<_>.Create "ostrings" onlerefs=Table<_>.Create "onlerefs" opubpaths=Table<_>.Create "opubpaths" @@ -792,10 +792,10 @@ let pickleObjWithDanglingCcus inMem file g scope p x = { os = ByteBuffer.Create 100000 oscope=scope occus= Table<_>.Create "occus (fake)" - oentities=NodeOutTable<_, _>.Create((fun (tc:Tycon) -> tc.Stamp), (fun tc -> tc.LogicalName), (fun tc -> tc.Range), (fun osgn -> osgn), "otycons") - otypars=NodeOutTable<_, _>.Create((fun (tp:Typar) -> tp.Stamp), (fun tp -> tp.DisplayName), (fun tp -> tp.Range), (fun osgn -> osgn), "otypars") - ovals=NodeOutTable<_, _>.Create((fun (v:Val) -> v.Stamp), (fun v -> v.LogicalName), (fun v -> v.Range), (fun osgn -> osgn), "ovals") - oanoninfos=NodeOutTable<_, _>.Create((fun (v:AnonRecdTypeInfo) -> v.Stamp), (fun v -> string v.Stamp), (fun _ -> range0), id, "oanoninfos") + oentities=NodeOutTable<_, _>.Create((fun (tc: Tycon) -> tc.Stamp), (fun tc -> tc.LogicalName), (fun tc -> tc.Range), (fun osgn -> osgn), "otycons") + otypars=NodeOutTable<_, _>.Create((fun (tp: Typar) -> tp.Stamp), (fun tp -> tp.DisplayName), (fun tp -> tp.Range), (fun osgn -> osgn), "otypars") + ovals=NodeOutTable<_, _>.Create((fun (v: Val) -> v.Stamp), (fun v -> v.LogicalName), (fun v -> v.Range), (fun osgn -> osgn), "ovals") + oanoninfos=NodeOutTable<_, _>.Create((fun (v: AnonRecdTypeInfo) -> v.Stamp), (fun v -> string v.Stamp), (fun _ -> range0), id, "oanoninfos") ostrings=Table<_>.Create "ostrings (fake)" opubpaths=Table<_>.Create "opubpaths (fake)" onlerefs=Table<_>.Create "onlerefs (fake)" @@ -821,7 +821,7 @@ let pickleObjWithDanglingCcus inMem file g scope p x = st2.os.Close() phase2bytes -let check (ilscope:ILScopeRef) (inMap : NodeInTable<_, _>) = +let check (ilscope: ILScopeRef) (inMap : NodeInTable<_, _>) = for i = 0 to inMap.Count - 1 do let n = inMap.Get i if not (inMap.IsLinked n) then @@ -831,7 +831,7 @@ let check (ilscope:ILScopeRef) (inMap : NodeInTable<_, _>) = // an identical copy of the source for the DLL containing the data being unpickled. A message will // then be printed indicating the name of the item. -let unpickleObjWithDanglingCcus file ilscope (iILModule:ILModuleDef option) u (phase2bytes:byte[]) = +let unpickleObjWithDanglingCcus file ilscope (iILModule: ILModuleDef option) u (phase2bytes: byte[]) = let st2 = { is = ByteStream.FromBytes (phase2bytes, 0, phase2bytes.Length) iilscope= ilscope @@ -905,10 +905,10 @@ let p_ILPublicKey x st = let p_ILVersion x st = p_tup4 p_uint16 p_uint16 p_uint16 p_uint16 x st -let p_ILModuleRef (x:ILModuleRef) st = +let p_ILModuleRef (x: ILModuleRef) st = p_tup3 p_string p_bool (p_option p_bytes) (x.Name, x.HasMetadata, x.Hash) st -let p_ILAssemblyRef (x:ILAssemblyRef) st = +let p_ILAssemblyRef (x: ILAssemblyRef) st = p_byte 0 st // leave a dummy tag to make room for future encodings of assembly refs p_tup6 p_string (p_option p_bytes) (p_option p_ILPublicKey) p_bool (p_option p_ILVersion) (p_option p_string) ( x.Name, x.Hash, x.PublicKey, x.Retargetable, x.Version, x.Locale) st @@ -989,9 +989,9 @@ and p_ILCallConv (Callconv(x, y)) st = p_tup2 p_ILHasThis p_ILBasicCallConv (x, and p_ILCallSig x st = p_tup3 p_ILCallConv p_ILTypes p_ILType (x.CallingConv, x.ArgTypes, x.ReturnType) st -and p_ILTypeRef (x:ILTypeRef) st = p_tup3 p_ILScopeRef p_strings p_string (x.Scope, x.Enclosing, x.Name) st +and p_ILTypeRef (x: ILTypeRef) st = p_tup3 p_ILScopeRef p_strings p_string (x.Scope, x.Enclosing, x.Name) st -and p_ILTypeSpec (a:ILTypeSpec) st = p_tup2 p_ILTypeRef p_ILTypes (a.TypeRef, a.GenericArgs) st +and p_ILTypeSpec (a: ILTypeSpec) st = p_tup2 p_ILTypeRef p_ILTypes (a.TypeRef, a.GenericArgs) st let u_ILBasicCallConv st = match u_byte st with @@ -1326,7 +1326,7 @@ let u_xmldoc st = XmlDoc (u_array u_string st) let p_local_item_ref ctxt tab st = p_osgn_ref ctxt tab st -let p_tcref ctxt (x:EntityRef) st = +let p_tcref ctxt (x: EntityRef) st = match x with | ERefLocal x -> p_byte 0 st; p_local_item_ref ctxt st.oentities x st | ERefNonLocal x -> p_byte 1 st; p_nleref x st @@ -1365,7 +1365,7 @@ let checkForInRefStructThisArg st ty = let _, tauTy = tryDestForallTy g ty isFunTy g tauTy && isFunTy g (rangeOfFunTy g tauTy) && isInByrefTy g (domainOfFunTy g tauTy) -let p_nonlocal_val_ref (nlv:NonLocalValOrMemberRef) st = +let p_nonlocal_val_ref (nlv: NonLocalValOrMemberRef) st = let a = nlv.EnclosingEntity let key = nlv.ItemKey let pkey = key.PartialKey @@ -1625,7 +1625,7 @@ let u_tyar_constraint st = let u_tyar_constraints = (u_list_revi u_tyar_constraint) -let p_tyar_spec_data (x:Typar) st = +let p_tyar_spec_data (x: Typar) st = p_tup5 p_ident p_attribs @@ -1634,7 +1634,7 @@ let p_tyar_spec_data (x:Typar) st = p_xmldoc (x.typar_id, x.Attribs, int64 x.typar_flags.PickledBits, x.Constraints, x.XmlDoc) st -let p_tyar_spec (x:Typar) st = +let p_tyar_spec (x: Typar) st = //Disabled, workaround for bug 2721: if x.Rigidity <> TyparRigidity.Rigid then warning(Error(sprintf "p_tyar_spec: typar#%d is not rigid" x.Stamp, x.Range)) if x.IsFromError then warning(Error((0, "p_tyar_spec: from error"), x.Range)) p_osgn_decl st.otypars p_tyar_spec_data x st @@ -1724,7 +1724,7 @@ let fill_u_Exprs, u_Exprs = u_hole() let fill_u_constraints, u_constraints = u_hole() let fill_u_Vals, u_Vals = u_hole() -let p_ArgReprInfo (x:ArgReprInfo) st = +let p_ArgReprInfo (x: ArgReprInfo) st = p_attribs x.Attribs st p_option p_ident x.Name st @@ -1847,7 +1847,7 @@ and p_recdfield_spec x st = and p_rfield_table x st = p_array p_recdfield_spec (x.FieldsByIndex) st -and p_entity_spec_data (x:Entity) st = +and p_entity_spec_data (x: Entity) st = p_tyar_specs (x.entity_typars.Force(x.entity_range)) st p_string x.entity_logical_name st p_option p_string x.EntityCompiledName st @@ -1920,7 +1920,7 @@ and p_attrib_expr (AttribExpr(e1, e2)) st = and p_attrib_arg (AttribNamedArg(a, b, c, d)) st = p_tup4 p_string p_ty p_bool p_attrib_expr (a, b, c, d) st -and p_member_info (x:ValMemberInfo) st = +and p_member_info (x: ValMemberInfo) st = p_tup4 (p_tcref "member_info") p_MemberFlags (p_list p_slotsig) p_bool (x.ApparentEnclosingEntity, x.MemberFlags, x.ImplementedSlotSigs, x.IsImplemented) st @@ -2012,7 +2012,7 @@ and u_tycon_repr st = | None -> TNoRepr | Some iILModule -> try - let rec find acc enclosingTypeNames (tdefs:ILTypeDefs) = + let rec find acc enclosingTypeNames (tdefs: ILTypeDefs) = match enclosingTypeNames with | [] -> List.rev acc, tdefs.FindByName iltref.Name | h::t -> let nestedTypeDef = tdefs.FindByName h diff --git a/src/fsharp/TypeChecker.fs b/src/fsharp/TypeChecker.fs index e9a57aa3ae5..d85cf3e5e63 100755 --- a/src/fsharp/TypeChecker.fs +++ b/src/fsharp/TypeChecker.fs @@ -130,7 +130,7 @@ type CtorInfo = /// declarations because it refers to type inference variables. As type inference progresses /// these type inference variables may get solved. [] -type UngeneralizableItem(computeFreeTyvars : (unit -> FreeTyvars)) = +type UngeneralizableItem(computeFreeTyvars: (unit -> FreeTyvars)) = // Flag is for: have we determined that this item definitely has // no free type inference variables? This implies that @@ -164,7 +164,7 @@ type UngeneralizableItem(computeFreeTyvars : (unit -> FreeTyvars)) = [] type TcEnv = { /// Name resolution information - eNameResEnv : NameResolutionEnv + eNameResEnv: NameResolutionEnv /// The list of items in the environment that may contain free inference /// variables (which may not be generalized). The relevant types may @@ -200,16 +200,16 @@ type TcEnv = eModuleOrNamespaceTypeAccumulator: ModuleOrNamespaceType ref /// Context information for type checker - eContextInfo : ContextInfo + eContextInfo: ContextInfo /// Here Some tcref indicates we can access protected members in all super types eFamilyType: TyconRef option // Information to enforce special restrictions on valid expressions // for .NET constructors. - eCtorInfo : CtorInfo option + eCtorInfo: CtorInfo option - eCallerMemberName : string option + eCallerMemberName: string option } member tenv.DisplayEnv = tenv.eNameResEnv.DisplayEnv @@ -301,7 +301,7 @@ let AddValListToNameEnv vs nenv = List.foldBack (fun v nenv -> AddValRefToNameEnv nenv (mkLocalValRef v)) vs nenv /// Adjust the TcEnv to make more things 'InternalsVisibleTo' -let addInternalsAccessibility env (ccu:CcuThunk) = +let addInternalsAccessibility env (ccu: CcuThunk) = let compPath = CompPath (ccu.ILScopeRef, []) let eInternalsVisibleCompPaths = compPath :: env.eInternalsVisibleCompPaths { env with @@ -309,13 +309,13 @@ let addInternalsAccessibility env (ccu:CcuThunk) = eInternalsVisibleCompPaths = compPath :: env.eInternalsVisibleCompPaths } /// Add a local value to TcEnv -let AddLocalValPrimitive (v:Val) env = +let AddLocalValPrimitive (v: Val) env = { env with eNameResEnv = AddValRefToNameEnv env.eNameResEnv (mkLocalValRef v) eUngeneralizableItems = addFreeItemOfTy v.Type env.eUngeneralizableItems } /// Add a table of local values to TcEnv -let AddLocalValMap tcSink scopem (vals:Val NameMap) env = +let AddLocalValMap tcSink scopem (vals: Val NameMap) env = let env = if vals.IsEmpty then env @@ -327,7 +327,7 @@ let AddLocalValMap tcSink scopem (vals:Val NameMap) env = env /// Add a list of local values to TcEnv and report them to the sink -let AddLocalVals tcSink scopem (vals:Val list) env = +let AddLocalVals tcSink scopem (vals: Val list) env = let env = if isNil vals then env @@ -347,7 +347,7 @@ let AddLocalVal tcSink scopem v env = env /// Add an exception definition to TcEnv and report it to the sink -let AddLocalExnDefnAndReport tcSink scopem env (exnc:Tycon) = +let AddLocalExnDefnAndReport tcSink scopem env (exnc: Tycon) = let env = { env with eNameResEnv = AddExceptionDeclsToNameEnv BulkAdd.No env.eNameResEnv (mkLocalEntityRef exnc) } // Also make VisualStudio think there is an identifier in scope at the range of the identifier text of its binding location CallEnvSink tcSink (exnc.Range, env.NameEnv, env.eAccessRights) @@ -385,7 +385,7 @@ let AddRootModuleOrNamespaceRefs g amap m env modrefs = { env with eNameResEnv = AddModuleOrNamespaceRefsToNameEnv g amap m true env.eAccessRights env.eNameResEnv modrefs } /// Adjust the TcEnv to account for a new referenced assembly -let AddNonLocalCcu g amap scopem env assemblyName (ccu:CcuThunk, internalsVisibleToAttributes) = +let AddNonLocalCcu g amap scopem env assemblyName (ccu: CcuThunk, internalsVisibleToAttributes) = let internalsVisible = internalsVisibleToAttributes @@ -410,7 +410,7 @@ let AddNonLocalCcu g amap scopem env assemblyName (ccu:CcuThunk, internalsVisib env /// Adjust the TcEnv to account for a fully processed "namespace" declaration in thie file -let AddLocalRootModuleOrNamespace tcSink g amap scopem env (mtyp:ModuleOrNamespaceType) = +let AddLocalRootModuleOrNamespace tcSink g amap scopem env (mtyp: ModuleOrNamespaceType) = // Compute the top-rooted module or namespace references let modrefs = mtyp.ModuleAndNamespaceDefinitions |> List.map mkLocalModRef // Compute the top-rooted type definitions @@ -434,14 +434,14 @@ let AddModuleAbbreviationAndReport tcSink scopem id modrefs env = env /// Add a "module X = ..." definition to the TcEnv -let AddLocalSubModule g amap m env (modul:ModuleOrNamespace) = +let AddLocalSubModule g amap m env (modul: ModuleOrNamespace) = let env = { env with eNameResEnv = AddModuleOrNamespaceRefToNameEnv g amap m false env.eAccessRights env.eNameResEnv (mkLocalModRef modul) eUngeneralizableItems = addFreeItemOfModuleTy modul.ModuleOrNamespaceType env.eUngeneralizableItems } env /// Add a "module X = ..." definition to the TcEnv and report it to the sink -let AddLocalSubModuleAndReport tcSink scopem g amap m env (modul:ModuleOrNamespace) = +let AddLocalSubModuleAndReport tcSink scopem g amap m env (modul: ModuleOrNamespace) = let env = AddLocalSubModule g amap m env modul CallEnvSink tcSink (scopem, env.NameEnv, env.eAccessRights) env @@ -581,7 +581,7 @@ let MakeInnerEnvForTyconRef env tcref isExtrinsicExtension = eAccessPath = eAccessPath } /// Make an environment suitable for processing inside a member definition -let MakeInnerEnvForMember env (v:Val) = +let MakeInnerEnvForMember env (v: Val) = match v.MemberInfo with | None -> env | Some _ -> MakeInnerEnvForTyconRef env v.MemberApparentEntity v.IsExtensionMember @@ -606,7 +606,7 @@ let LocateEnv ccu env enclosingNamespacePath = env /// Given an inferred module type, place that inside a namespace path implied by a "namespace X.Y.Z" definition -let BuildRootModuleType enclosingNamespacePath (cpath:CompilationPath) mtyp = +let BuildRootModuleType enclosingNamespacePath (cpath: CompilationPath) mtyp = (enclosingNamespacePath, (cpath, (mtyp, []))) ||> List.foldBack (fun id (cpath, (mtyp, mspecs)) -> let a, b = wrapModuleOrNamespaceTypeInNamespace id cpath.ParentCompPath mtyp @@ -614,13 +614,13 @@ let BuildRootModuleType enclosingNamespacePath (cpath:CompilationPath) mtyp = |> fun (_, (mtyp, mspecs)) -> mtyp, List.rev mspecs /// Given a resulting module expression, place that inside a namespace path implied by a "namespace X.Y.Z" definition -let BuildRootModuleExpr enclosingNamespacePath (cpath:CompilationPath) mexpr = +let BuildRootModuleExpr enclosingNamespacePath (cpath: CompilationPath) mexpr = (enclosingNamespacePath, (cpath, mexpr)) ||> List.foldBack (fun id (cpath, mexpr) -> (cpath.ParentCompPath, wrapModuleOrNamespaceExprInNamespace id cpath.ParentCompPath mexpr)) |> snd /// Try to take the "FSINNN" prefix off a namespace path -let TryStripPrefixPath (g:TcGlobals) (enclosingNamespacePath: Ident list) = +let TryStripPrefixPath (g: TcGlobals) (enclosingNamespacePath: Ident list) = match enclosingNamespacePath with | p::rest when g.isInteractive && @@ -708,7 +708,7 @@ let UnifyRefTupleType contextInfo cenv denv m ty ps = ptys /// Allow the inference of structness from the known type, e.g. -/// let (x : struct (int * int)) = (3,4) +/// let (x: struct (int * int)) = (3,4) let UnifyTupleTypeAndInferCharacteristics contextInfo cenv denv m knownTy isExplicitStruct ps = let tupInfo, ptys = if isAnyTupleTy cenv.g knownTy then @@ -815,7 +815,7 @@ let ReportImplicitlyIgnoredBoolExpression denv m ty expr = extractNext inner | expr -> checkExpr m expr -let UnifyUnitType cenv (env:TcEnv) m ty expr = +let UnifyUnitType cenv (env: TcEnv) m ty expr = let denv = env.DisplayEnv if AddCxTypeEqualsTypeUndoIfFailed denv cenv.css m ty cenv.g.unit_ty then true @@ -856,7 +856,7 @@ module AttributeTargets = let ModuleDecl = AttributeTargets.Class let Top = AttributeTargets.Assembly ||| AttributeTargets.Module ||| AttributeTargets.Method -let ForNewConstructors tcSink (env:TcEnv) mObjTy methodName meths = +let ForNewConstructors tcSink (env: TcEnv) mObjTy methodName meths = let origItem = Item.CtorGroup(methodName, meths) let callSink (item, minst) = CallNameResolutionSink tcSink (mObjTy, env.NameEnv, item, origItem, minst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) let sendToSink minst refinedMeths = callSink (Item.CtorGroup(methodName, refinedMeths), minst) @@ -941,7 +941,7 @@ let TcConst cenv ty m env c = | SynConst.Bytes _ -> error (InternalError(FSComp.SR.tcUnexpectedConstByteArray(), m)) /// Convert an Abstract IL ILFieldInit value read from .NET metadata to a TAST constant -let TcFieldInit (_m:range) lit = PatternMatchCompilation.ilFieldToTastConst lit +let TcFieldInit (_m: range) lit = PatternMatchCompilation.ilFieldToTastConst lit //------------------------------------------------------------------------- // Arities. These serve two roles in the system: @@ -1002,7 +1002,7 @@ let TranslatePartialArity tps (PartialValReprInfo (argsData, retData)) = // Members //------------------------------------------------------------------------- -let ComputeLogicalName (id:Ident) memberFlags = +let ComputeLogicalName (id: Ident) memberFlags = match memberFlags.MemberKind with | MemberKind.ClassConstructor -> ".cctor" | MemberKind.Constructor -> ".ctor" @@ -1023,7 +1023,7 @@ type ValMemberInfoTransient = ValMemberInfoTransient of ValMemberInfo * string * let MakeMemberDataAndMangledNameForMemberVal(g, tcref, isExtrinsic, attrs, optImplSlotTys, memberFlags, valSynData, id, isCompGen) = let logicalName = ComputeLogicalName id memberFlags let optIntfSlotTys = if optImplSlotTys |> List.forall (isInterfaceTy g) then optImplSlotTys else [] - let memberInfo : ValMemberInfo = + let memberInfo: ValMemberInfo = { ApparentEnclosingEntity=tcref MemberFlags=memberFlags IsImplemented=false @@ -1302,11 +1302,11 @@ let PublishTypeDefn cenv env tycon = UpdateAccModuleOrNamespaceType cenv env (fun _ mty -> mty.AddEntity tycon) -let PublishValueDefnPrim cenv env (vspec:Val) = +let PublishValueDefnPrim cenv env (vspec: Val) = UpdateAccModuleOrNamespaceType cenv env (fun _ mty -> mty.AddVal vspec) -let PublishValueDefn cenv env declKind (vspec:Val) = +let PublishValueDefn cenv env declKind (vspec: Val) = if (declKind = ModuleOrMemberBinding) && ((GetCurrAccumulatedModuleOrNamespaceType env).ModuleOrNamespaceKind = Namespace) && (Option.isNone vspec.MemberInfo) then @@ -1371,7 +1371,7 @@ let ComputeAccessAndCompPath env declKindOpt m vis overrideVis actualParent = let cpath = if accessModPermitted then Some env.eCompPath else None vis, cpath -let CheckForAbnormalOperatorNames cenv (idRange:range) coreDisplayName (memberInfoOpt: ValMemberInfo option) = +let CheckForAbnormalOperatorNames cenv (idRange: range) coreDisplayName (memberInfoOpt: ValMemberInfo option) = if (idRange.EndColumn - idRange.StartColumn <= 5) && not cenv.g.compilingFslib then @@ -1538,14 +1538,14 @@ let MakeAndPublishVal cenv env (altActualParent, inSig, declKind, vrec, vscheme, let MakeAndPublishVals cenv env (altActualParent, inSig, declKind, vrec, valSchemes, attrs, doc, konst) = Map.foldBack - (fun name (valscheme:ValScheme) values -> + (fun name (valscheme: ValScheme) values -> Map.add name (MakeAndPublishVal cenv env (altActualParent, inSig, declKind, vrec, valscheme, attrs, doc, konst, false), valscheme.TypeScheme) values) valSchemes Map.empty let MakeAndPublishBaseVal cenv env baseIdOpt ty = baseIdOpt - |> Option.map (fun (id:Ident) -> + |> Option.map (fun (id: Ident) -> let valscheme = ValScheme(id, NonGenericTypeScheme(ty), None, None, false, ValInline.Never, BaseVal, None, false, false, false, false) MakeAndPublishVal cenv env (ParentNone, false, ExpressionBinding, ValNotInRecScope, valscheme, [], XmlDoc.Empty, None, false)) @@ -1594,7 +1594,7 @@ let MakeAndPublishSafeThisVal cenv env (thisIdOpt: Ident option) thisTy = /// Fixup the type instantiation at recursive references. Used after the bindings have been /// checked. The fixups are applied by using mutation. -let AdjustAndForgetUsesOfRecValue cenv (vrefTgt: ValRef) (valScheme : ValScheme) = +let AdjustAndForgetUsesOfRecValue cenv (vrefTgt: ValRef) (valScheme: ValScheme) = let (TypeScheme(generalizedTypars, _)) = valScheme.TypeScheme let fty = GeneralizedTypeForTypeScheme valScheme.TypeScheme let lvrefTgt = vrefTgt.Deref @@ -1624,7 +1624,7 @@ let AdjustAndForgetUsesOfRecValue cenv (vrefTgt: ValRef) (valScheme : ValScheme) /// Set the properties of recursive values that are only fully known after inference is complete -let AdjustRecType _cenv (vspec:Val) (ValScheme(_, typeScheme, topValData, _, _, _, _, _, _, _, _, _)) = +let AdjustRecType _cenv (vspec: Val) (ValScheme(_, typeScheme, topValData, _, _, _, _, _, _, _, _, _)) = let fty = GeneralizedTypeForTypeScheme typeScheme vspec.SetType fty vspec.SetValReprInfo topValData @@ -1677,7 +1677,7 @@ let ChooseCanonicalValSchemeAfterInference g denv valscheme m = let PlaceTyparsInDeclarationOrder declaredTypars generalizedTypars = declaredTypars @ (generalizedTypars |> List.filter (fun tp -> not (ListSet.contains typarEq tp declaredTypars))) -let SetTyparRigid _g denv m (tp:Typar) = +let SetTyparRigid _g denv m (tp: Typar) = match tp.Solution with | None -> () | Some ty -> @@ -1733,7 +1733,7 @@ let DontGeneralizeVals types = let InferGenericArityFromTyScheme (TypeScheme(generalizedTypars, _)) partialValReprInfo = TranslatePartialArity generalizedTypars partialValReprInfo -let ComputeIsTyFunc(id:Ident, hasDeclaredTypars, arityInfo:ValReprInfo option) = +let ComputeIsTyFunc(id: Ident, hasDeclaredTypars, arityInfo: ValReprInfo option) = hasDeclaredTypars && (match arityInfo with | None -> error(Error(FSComp.SR.tcExplicitTypeParameterInvalid(), id.idRange)) @@ -1751,32 +1751,32 @@ let UseSyntacticArity declKind typeScheme partialValReprInfo = // // For example // let f (a, b) c = 1 // gets arity [2;1] -// let f (a:int*int) = 1 // gets arity [2], based on type +// let f (a: int*int) = 1 // gets arity [2], based on type // let f () = 1 // gets arity [0] -// let f = (fun (x:int) (y:int) -> 1) // gets arity [1;1] -// let f = (fun (x:int*int) y -> 1) // gets arity [2;1] +// let f = (fun (x: int) (y: int) -> 1) // gets arity [1;1] +// let f = (fun (x: int*int) y -> 1) // gets arity [2;1] // // Some of this arity inference is purely syntax directed and done in InferSynValData in ast.fs // Some is done by InferArityOfExpr. // // However, there are some corner cases in this specification. In particular, consider // let f () () = 1 // [0;1] or [0;0]? Answer: [0;1] -// let f (a:unit) = 1 // [0] or [1]? Answer: [1] +// let f (a: unit) = 1 // [0] or [1]? Answer: [1] // let f = (fun () -> 1) // [0] or [1]? Answer: [0] -// let f = (fun (a:unit) -> 1) // [0] or [1]? Answer: [1] +// let f = (fun (a: unit) -> 1) // [0] or [1]? Answer: [1] // // The particular choice of [1] for -// let f (a:unit) = 1 +// let f (a: unit) = 1 // is intended to give a disambiguating form for members that override methods taking a single argument // instantiated to type "unit", e.g. // type Base<'a> = -// abstract M : 'a -> unit +// abstract M: 'a -> unit // // { new Base with -// member x.M(v:int) = () } +// member x.M(v: int) = () } // // { new Base with -// member x.M(v:unit) = () } +// member x.M(v: unit) = () } // let CombineSyntacticAndInferredArities g declKind rhsExpr prelimScheme = let (PrelimValScheme2(_, typeScheme, partialValReprInfoOpt, memberInfoOpt, isMutable, _, _, ArgAndRetAttribs(argAttribs, retAttribs), _, _, _)) = prelimScheme @@ -1904,7 +1904,7 @@ let MakeAndPublishSimpleVals cenv env m names mergeNamesInOneNameresEnv = // to C<_> occurs then generate C for a fresh type inference variable ?ty. //------------------------------------------------------------------------- -let FreshenTyconRef m rigid (tcref:TyconRef) declaredTyconTypars = +let FreshenTyconRef m rigid (tcref: TyconRef) declaredTyconTypars = let tpsorig = declaredTyconTypars let tps = copyTypars tpsorig if rigid <> TyparRigidity.Rigid then @@ -1923,7 +1923,7 @@ let FreshenPossibleForallTy g m rigid ty = let tps, renaming, tinst = CopyAndFixupTypars m rigid tpsorig tpsorig, tps, tinst, instType renaming tau -let infoOfTyconRef m (tcref:TyconRef) = +let infoOfTyconRef m (tcref: TyconRef) = let tps, renaming, tinst = FreshenTypeInst m (tcref.Typars m) tps, renaming, tinst, TType_app (tcref, tinst) @@ -2073,19 +2073,19 @@ let TcUnionCaseOrExnField cenv (env: TcEnv) ty1 m c n funcs = mkf, ty2 //------------------------------------------------------------------------- -// Environment of explicit type parameters, e.g. 'a in "(x : 'a)" +// Environment of explicit type parameters, e.g. 'a in "(x: 'a)" //------------------------------------------------------------------------- type SyntacticUnscopedTyparEnv = UnscopedTyparEnv of NameMap -let emptyUnscopedTyparEnv : SyntacticUnscopedTyparEnv = UnscopedTyparEnv Map.empty +let emptyUnscopedTyparEnv: SyntacticUnscopedTyparEnv = UnscopedTyparEnv Map.empty let AddUnscopedTypar n p (UnscopedTyparEnv tab) = UnscopedTyparEnv (Map.add n p tab) let TryFindUnscopedTypar n (UnscopedTyparEnv tab) = Map.tryFind n tab let HideUnscopedTypars typars (UnscopedTyparEnv tab) = - UnscopedTyparEnv (List.fold (fun acc (tp:Typar) -> Map.remove tp.Name acc) tab typars) + UnscopedTyparEnv (List.fold (fun acc (tp: Typar) -> Map.remove tp.Name acc) tab typars) //------------------------------------------------------------------------- // Helpers for generalizing type variables @@ -2188,7 +2188,7 @@ module GeneralizationHelpers = /// For non-generalized type variables be careful to iteratively knock out /// both the typars and any typars free in the constraints of the typars /// into the set that are considered free in the environment. - let rec TrimUngeneralizableTypars genConstrainedTyparFlag inlineFlag (generalizedTypars:Typar list) freeInEnv = + let rec TrimUngeneralizableTypars genConstrainedTyparFlag inlineFlag (generalizedTypars: Typar list) freeInEnv = // Do not generalize type variables with a static requirement unless function is marked 'inline' let generalizedTypars, ungeneralizableTypars1 = if inlineFlag = ValInline.PseudoVal then generalizedTypars, [] @@ -2221,7 +2221,7 @@ module GeneralizationHelpers = TrimUngeneralizableTypars genConstrainedTyparFlag inlineFlag generalizedTypars freeInEnv /// Condense type variables in positive position - let CondenseTypars (cenv, denv:DisplayEnv, generalizedTypars: Typars, tauTy, m) = + let CondenseTypars (cenv, denv: DisplayEnv, generalizedTypars: Typars, tauTy, m) = // The type of the value is ty11 * ... * ty1N -> ... -> tyM1 * ... * tyMM -> retTy // This is computed REGARDLESS of the arity of the expression. @@ -2232,7 +2232,7 @@ module GeneralizationHelpers = let returnTypeFreeTypars = freeInTypeLeftToRight cenv.g false retTy let allUntupledArgTysWithFreeVars = allUntupledArgTys |> List.map (fun ty -> (ty, freeInTypeLeftToRight cenv.g false ty)) - let relevantUniqueSubtypeConstraint (tp:Typar) = + let relevantUniqueSubtypeConstraint (tp: Typar) = // Find a single subtype constraint match tp.Constraints |> List.partition (function (TyparConstraint.CoercesTo _) -> true | _ -> false) with | [TyparConstraint.CoercesTo(cxty, _)], others -> @@ -2255,7 +2255,7 @@ module GeneralizationHelpers = | None -> [] | _ -> []) - let IsCondensationTypar (tp:Typar) = + let IsCondensationTypar (tp: Typar) = // A condensation typar may not a user-generated type variable nor has it been unified with any user type variable (tp.DynamicReq = TyparDynamicReq.No) && // A condensation typar must have a single constraint "'a :> A" @@ -2284,9 +2284,9 @@ module GeneralizationHelpers = |> RaiseOperationResult let ComputeAndGeneralizeGenericTypars (cenv, - denv:DisplayEnv, + denv: DisplayEnv, m, - freeInEnv:FreeTypars, + freeInEnv: FreeTypars, canInferTypars, genConstrainedTyparFlag, inlineFlag, @@ -2317,7 +2317,7 @@ module GeneralizationHelpers = if canInferTypars then generalizedTypars else generalizedTypars |> List.filter (fun tp -> ListSet.contains typarEq tp allDeclaredTypars) - let allConstraints = List.collect (fun (tp:Typar) -> tp.Constraints) generalizedTypars + let allConstraints = List.collect (fun (tp: Typar) -> tp.Constraints) generalizedTypars let generalizedTypars = ConstraintSolver.SimplifyMeasuresInTypeScheme cenv.g resultFirst generalizedTypars tauTy allConstraints // Generalization turns inference type variables into rigid, quantified type variables, @@ -2434,7 +2434,7 @@ let ComputeInlineFlag memFlagsOption isInline isMutable m = type NormalizedBindingRhs = | NormalizedBindingRhs of SynSimplePats list * SynBindingReturnInfo option * SynExpr -let PushOnePatternToRhs (cenv:cenv) isMember p (NormalizedBindingRhs(spatsL, rtyOpt, rhsExpr)) = +let PushOnePatternToRhs (cenv: cenv) isMember p (NormalizedBindingRhs(spatsL, rtyOpt, rhsExpr)) = let spats, rhsExpr = PushPatternToExpr cenv.synArgNameGenerator isMember p rhsExpr NormalizedBindingRhs(spats::spatsL, rtyOpt, rhsExpr) @@ -2469,7 +2469,7 @@ type IsObjExprBinding = module BindingNormalization = /// Push a bunch of pats at once. They may contain patterns, e.g. let f (A x) (B y) = ... /// In this case the semantics is let f a b = let A x = a in let B y = b - let private PushMultiplePatternsToRhs (cenv:cenv) isMember ps (NormalizedBindingRhs(spatsL, rtyOpt, rhsExpr)) = + let private PushMultiplePatternsToRhs (cenv: cenv) isMember ps (NormalizedBindingRhs(spatsL, rtyOpt, rhsExpr)) = let spatsL2, rhsExpr = PushCurriedPatternsToExpr cenv.synArgNameGenerator rhsExpr.Range isMember ps rhsExpr NormalizedBindingRhs(spatsL2@spatsL, rtyOpt, rhsExpr) @@ -2503,7 +2503,7 @@ module BindingNormalization = typars) | _ -> MakeNormalizedStaticOrValBinding cenv ValOrMemberBinding id vis typars args rhsExpr valSynData - let private NormalizeInstanceMemberBinding cenv memberFlags valSynData thisId memberId (toolId:Ident option) vis typars args m rhsExpr = + let private NormalizeInstanceMemberBinding cenv memberFlags valSynData thisId memberId (toolId: Ident option) vis typars args m rhsExpr = let (SynValData(_, valSynInfo, thisIdOpt)) = valSynData if not memberFlags.IsInstance then // static method with adhoc "this" argument @@ -2701,7 +2701,7 @@ let FreshenObjectArgType cenv m rigid tcref isExtrinsic declaredTyconTypars = // static member B2() = C.A() // // At this point during type inference, the return type of C.A() is '?X' // // After type inference, the return type of C.A() is 'int' -// member this.C() = (x : 'T) +// member this.C() = (x: 'T) // // At this point during type inference the type of 'x' is inferred to be 'T' // // Here "A" is generalized too early. @@ -2711,7 +2711,7 @@ let FreshenObjectArgType cenv m rigid tcref isExtrinsic declaredTyconTypars = // be accepted). As a result, we deal with this unsoundness by an adhoc post-type-checking // consistency check for recursive uses of "A" with explicit instantiations within the recursive // scope of "A". -let TcValEarlyGeneralizationConsistencyCheck cenv (env:TcEnv) (v:Val, vrec, tinst, vty, tau, m) = +let TcValEarlyGeneralizationConsistencyCheck cenv (env: TcEnv) (v: Val, vrec, tinst, vty, tau, m) = match vrec with | ValInRecScope isComplete when isComplete && not (isNil tinst) -> //printfn "pushing post-inference check for '%s', vty = '%s'" v.DisplayName (DebugPrint.showType vty) @@ -2743,7 +2743,7 @@ let TcValEarlyGeneralizationConsistencyCheck cenv (env:TcEnv) (v:Val, vrec, tins /// | CtorValUsedAsSuperInit "inherit Panel()" /// | CtorValUsedAsSelfInit "new() = new OwnType(3)" /// | VSlotDirectCall "base.OnClick(eventArgs)" -let TcVal checkAttributes cenv env tpenv (vref:ValRef) optInst optAfterResolution m = +let TcVal checkAttributes cenv env tpenv (vref: ValRef) optInst optAfterResolution m = let (tpsorig, _, _, _, tinst, _) as res = let v = vref.Deref let vrec = v.RecursiveValInfo @@ -2799,13 +2799,13 @@ let TcVal checkAttributes cenv env tpenv (vref:ValRef) optInst optAfterResolutio // If we have got an explicit instantiation then use that | Some(vrefFlags, checkTys) -> - let checkInst (tinst:TypeInst) = + let checkInst (tinst: TypeInst) = if not v.IsMember && not v.PermitsExplicitTypeInstantiation && not (List.isEmpty tinst) && not (List.isEmpty v.Typars) then warning(Error(FSComp.SR.tcDoesNotAllowExplicitTypeArguments(v.DisplayName), m)) match vrec with | ValInRecScope false -> let tpsorig, tau = vref.TypeScheme - let (tinst:TypeInst), tpenv = checkTys tpenv (tpsorig |> List.map (fun tp -> tp.Kind)) + let (tinst: TypeInst), tpenv = checkTys tpenv (tpsorig |> List.map (fun tp -> tp.Kind)) checkInst tinst if tpsorig.Length <> tinst.Length then error(Error(FSComp.SR.tcTypeParameterArityMismatch(tpsorig.Length, tinst.Length), m)) let tau2 = instType (mkTyparInst tpsorig tinst) tau @@ -2817,7 +2817,7 @@ let TcVal checkAttributes cenv env tpenv (vref:ValRef) optInst optAfterResolutio | ValNotInRecScope -> let tpsorig, tps, tptys, tau = FreshenPossibleForallTy cenv.g m TyparRigidity.Flexible vty //dprintfn "After Freshen: tau = %s" (Layout.showL (typeL tau)) - let (tinst:TypeInst), tpenv = checkTys tpenv (tps |> List.map (fun tp -> tp.Kind)) + let (tinst: TypeInst), tpenv = checkTys tpenv (tps |> List.map (fun tp -> tp.Kind)) checkInst tinst //dprintfn "After Check: tau = %s" (Layout.showL (typeL tau)) if tptys.Length <> tinst.Length then error(Error(FSComp.SR.tcTypeParameterArityMismatch(tps.Length, tinst.Length), m)) @@ -2845,7 +2845,7 @@ let TcVal checkAttributes cenv env tpenv (vref:ValRef) optInst optAfterResolutio /// simplified version of TcVal used in calls to BuildMethodCall (typrelns.fs) /// this function is used on typechecking step for making calls to provided methods and on optimization step (for the same purpose). -let LightweightTcValForUsingInBuildMethodCall g (vref:ValRef) vrefFlags (vrefTypeInst : TTypes) m = +let LightweightTcValForUsingInBuildMethodCall g (vref: ValRef) vrefFlags (vrefTypeInst: TTypes) m = let v = vref.Deref let vty = vref.Type // byref-typed values get dereferenced @@ -2931,9 +2931,9 @@ let MakeApplicableExprNoFlex cenv expr = /// /// For 'obj' this is because introducing this flexibility would NOT be the reverse of condensation, /// since we don't condense -/// f : 'a -> unit +/// f: 'a -> unit /// to -/// f : obj -> unit +/// f: obj -> unit /// /// We represent the flexibility in the TAST by leaving a function-to-function coercion node in the tree /// This "special" node is immediately eliminated by the use of IteratedFlexibleAdjustArityOfLambdaBody as soon as we @@ -3040,11 +3040,11 @@ let BuildPossiblyConditionalMethodCall cenv env isMutable m isProp minfo valUseF BuildMethodCall tcVal cenv.g cenv.amap isMutable m isProp minfo valUseFlags minst objArgs args -let TryFindIntrinsicOrExtensionMethInfo (cenv:cenv) (env: TcEnv) m ad nm ty = +let TryFindIntrinsicOrExtensionMethInfo (cenv: cenv) (env: TcEnv) m ad nm ty = AllMethInfosOfTypeInScope cenv.infoReader env.NameEnv (Some(nm), ad) IgnoreOverrides m ty /// Build the 'test and dispose' part of a 'use' statement -let BuildDisposableCleanup cenv env m (v:Val) = +let BuildDisposableCleanup cenv env m (v: Val) = v.SetHasBeenReferenced() let ad = env.eAccessRights let disposeMethod = @@ -3080,7 +3080,7 @@ let BuildOffsetToStringData cenv env m = let offsetExpr, _ = BuildPossiblyConditionalMethodCall cenv env NeverMutates m false offsetToStringDataMethod NormalValUse [] [] [] offsetExpr -let BuildILFieldGet g amap m objExpr (finfo:ILFieldInfo) = +let BuildILFieldGet g amap m objExpr (finfo: ILFieldInfo) = let fref = finfo.ILFieldRef let isValueType = finfo.IsValueType let valu = if isValueType then AsValue else AsObject @@ -3106,7 +3106,7 @@ let BuildILFieldGet g amap m objExpr (finfo:ILFieldInfo) = // Add an I_nop if this is an initonly field to make sure we never recognize it as an lvalue. See mkExprAddrOfExpr. wrap (mkAsmExpr (([ mkNormalLdfld fspec ] @ (if finfo.IsInitOnly then [ AI_nop ] else [])), tinst, [objExpr], [fieldType], m)) -let BuildILFieldSet g m objExpr (finfo:ILFieldInfo) argExpr = +let BuildILFieldSet g m objExpr (finfo: ILFieldInfo) argExpr = let fref = finfo.ILFieldRef let isValueType = finfo.IsValueType let valu = if isValueType then AsValue else AsObject @@ -3119,7 +3119,7 @@ let BuildILFieldSet g m objExpr (finfo:ILFieldInfo) argExpr = let wrap, objExpr, _readonly, _writeonly = mkExprAddrOfExpr g isValueType false DefinitelyMutates objExpr None m wrap (mkAsmExpr ([ mkNormalStfld fspec ], tinst, [objExpr; argExpr], [], m)) -let BuildILStaticFieldSet m (finfo:ILFieldInfo) argExpr = +let BuildILStaticFieldSet m (finfo: ILFieldInfo) argExpr = let fref = finfo.ILFieldRef let isValueType = finfo.IsValueType let valu = if isValueType then AsValue else AsObject @@ -3131,7 +3131,7 @@ let BuildILStaticFieldSet m (finfo:ILFieldInfo) argExpr = if finfo.IsInitOnly then error (Error (FSComp.SR.tcFieldIsReadonly(), m)) mkAsmExpr ([ mkNormalStsfld fspec ], tinst, [argExpr], [], m) -let BuildRecdFieldSet g m objExpr (rfinfo:RecdFieldInfo) argExpr = +let BuildRecdFieldSet g m objExpr (rfinfo: RecdFieldInfo) argExpr = let tgtTy = rfinfo.DeclaringType let valu = isStructTy g tgtTy let objExpr = if valu then objExpr else mkCoerceExpr(objExpr, tgtTy, m, tyOfExpr g objExpr) @@ -3154,7 +3154,7 @@ let (|SimpleEqualsExpr|_|) e = // For join clauses that join on nullable, we syntactically insert the creation of nullable values on the appropriate side of the condition, // then pull the syntax apart again -let (|JoinRelation|_|) cenv env (e:SynExpr) = +let (|JoinRelation|_|) cenv env (e: SynExpr) = let m = e.Range let ad = env.eAccessRights @@ -3264,7 +3264,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr // Ensure there are no curried arguments, and indeed no arguments at all - let hasArgs (minfo:MethInfo) minst = + let hasArgs (minfo: MethInfo) minst = match minfo.GetParamTypes(cenv.amap, m, minst) with | [[]] -> false | _ -> true @@ -3307,11 +3307,11 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr if isObjTy cenv.g enumElemTy then // Look for an 'Item' property, or a set of these with consistent return types - let allEquivReturnTypes (minfo:MethInfo) (others:MethInfo list) = + let allEquivReturnTypes (minfo: MethInfo) (others: MethInfo list) = let returnTy = minfo.GetFSharpReturnTy(cenv.amap, m, []) others |> List.forall (fun other -> typeEquiv cenv.g (other.GetFSharpReturnTy(cenv.amap, m, [])) returnTy) - let isInt32OrObjectIndexer (minfo:MethInfo) = + let isInt32OrObjectIndexer (minfo: MethInfo) = match minfo.GetParamTypes(cenv.amap, m, []) with | [[ty]] -> // e.g. MatchCollection @@ -3405,7 +3405,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr // Used inside sequence expressions -let ConvertArbitraryExprToEnumerable cenv ty (env: TcEnv) (expr:Expr) = +let ConvertArbitraryExprToEnumerable cenv ty (env: TcEnv) (expr: Expr) = let m = expr.Range let enumElemTy = NewInferenceType () if AddCxTypeMustSubsumeTypeUndoIfFailed env.DisplayEnv cenv.css m ( mkSeqTy cenv.g enumElemTy) ty then @@ -3469,7 +3469,7 @@ let mkSeqFinally cenv env m genTy e1 e2 = let mkSeqExprMatchClauses (pat', vspecs) innerExpr = [TClause(pat', None, TTarget(vspecs, innerExpr, SequencePointAtTarget), pat'.Range) ] -let compileSeqExprMatchClauses cenv env inputExprMark (pat:Pattern, vspecs) innerExpr inputExprOpt bindPatTy genInnerTy = +let compileSeqExprMatchClauses cenv env inputExprMark (pat: Pattern, vspecs) innerExpr inputExprOpt bindPatTy genInnerTy = let patMark = pat.Range let tclauses = mkSeqExprMatchClauses (pat, vspecs) innerExpr CompilePatternForMatchClauses cenv env inputExprMark patMark false ThrowIncompleteMatchException inputExprOpt bindPatTy genInnerTy tclauses @@ -3480,7 +3480,7 @@ let elimFastIntegerForLoop (spBind, id, start, dir, finish, innerExpr, m) = else mkSynTrifix m ".. .." start (SynExpr.Const(SynConst.Int32 -1, start.Range)) finish SynExpr.ForEach (spBind, SeqExprOnly false, true, mkSynPatVar None id, pseudoEnumExpr, innerExpr, m) -let (|ExprAsPat|_|) (f:SynExpr) = +let (|ExprAsPat|_|) (f: SynExpr) = match f with | SingleIdent v1 | SynExprParen(SingleIdent v1, _, _, _) -> Some (mkSynPatVar None v1) | SynExprParen(SynExpr.Tuple (false, elems, _, _), _, _, _) -> @@ -3692,7 +3692,7 @@ type InitializationGraphAnalysisState = | DefinitelyLazy type PreInitializationGraphEliminationBinding = - { FixupPoints : RecursiveUseFixupPoints + { FixupPoints: RecursiveUseFixupPoints Binding: Tast.Binding } @@ -3703,7 +3703,7 @@ let EliminateInitializationGraphs (getLetBinds: 'LetDataIn list -> PreInitializationGraphEliminationBinding list) (morphLetBinds: (PreInitializationGraphEliminationBinding list -> Binding list) -> 'LetDataIn list -> Binding list) g mustHaveArity denv - (fixupsAndBindingsWithoutLaziness : MutRecShape<_, _, _, _, _> list) bindsm = + (fixupsAndBindingsWithoutLaziness: MutRecShape<_, _, _, _, _> list) bindsm = let recursiveVals = let hash = ValHash.Create() @@ -3747,7 +3747,7 @@ let EliminateInitializationGraphs // // This is a design decision (See bug 6496), so that generalized recursive bindings such as // let rec x = x - // are analyzed. Although we give type "x : 'T" to these, from the users point of view + // are analyzed. Although we give type "x: 'T" to these, from the users point of view // any use of "x" will result in an infinite recursion. Type instantiation is implicit in F# // because of type inference, which makes it reasonable to check generic bindings strictly. | Expr.TyLambda (_, _, b, _, _) -> CheckExpr st b @@ -3888,20 +3888,20 @@ let EliminateInitializationGraphs if newTopBinds.Count = 0 then res else MutRecShape.Lets (List.concat newTopBinds) :: res else - let noMorph (pgrbinds : PreInitializationGraphEliminationBinding list) = pgrbinds |> List.map (fun pgrbind -> pgrbind.Binding) + let noMorph (pgrbinds: PreInitializationGraphEliminationBinding list) = pgrbinds |> List.map (fun pgrbind -> pgrbind.Binding) fixupsAndBindingsWithoutLaziness |> MutRecShapes.map (morphTyconBinds noMorph) (morphLetBinds noMorph) id //------------------------------------------------------------------------- // Check the shape of an object constructor and rewrite calls //------------------------------------------------------------------------- -let CheckAndRewriteObjectCtor g env (ctorLambaExpr:Expr) = +let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = let m = ctorLambaExpr.Range let tps, vsl, body, returnTy = stripTopLambda (ctorLambaExpr, tyOfExpr g ctorLambaExpr) // Rewrite legitimate self-construction calls to CtorValUsedAsSelfInit - let error (expr:Expr) = + let error (expr: Expr) = errorR(Error(FSComp.SR.tcInvalidObjectConstructionExpression(), expr.Range)) expr @@ -3931,7 +3931,7 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr:Expr) = recdExpr - let rec checkAndRewrite (expr:Expr) = + let rec checkAndRewrite (expr: Expr) = match expr with // = { fields } // The constructor ends in an object initialization expression - good @@ -3970,7 +3970,7 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr:Expr) = expr // Type applications are ok, e.g. - // type C<'a>(x:int) = + // type C<'a>(x: int) = // new() = C<'a>(3) | Expr.App(f, fty, tyargs, [], m) -> let f = checkAndRewriteCtorUsage f @@ -4206,19 +4206,19 @@ type RecursiveBindingInfo = member x.DeclKind = let (RBInfo(_, _, _, _, _, _, _, _, _, _, _, _, _, declKind)) = x in declKind type PreCheckingRecursiveBinding = - { SyntacticBinding : NormalizedBinding - RecBindingInfo : RecursiveBindingInfo } + { SyntacticBinding: NormalizedBinding + RecBindingInfo: RecursiveBindingInfo } type PreGeneralizationRecursiveBinding = - { ExtraGeneralizableTypars : Typars + { ExtraGeneralizableTypars: Typars CheckedBinding: CheckedBindingInfo - RecBindingInfo : RecursiveBindingInfo } + RecBindingInfo: RecursiveBindingInfo } type PostGeneralizationRecursiveBinding = - { ValScheme : ValScheme + { ValScheme: ValScheme CheckedBinding: CheckedBindingInfo - RecBindingInfo : RecursiveBindingInfo } + RecBindingInfo: RecursiveBindingInfo } member x.GeneralizedTypars = x.ValScheme.GeneralizedTypars type PostBindCtorThisVarRefCellRecursiveBinding = @@ -4235,7 +4235,7 @@ let CanInferExtraGeneralizedTyparsForRecBinding (pgrbind: PreGeneralizationRecur /// Get the "this" variable from an instance member binding -let GetInstanceMemberThisVariable (v:Val, x) = +let GetInstanceMemberThisVariable (v: Val, x) = // Skip over LAM tps. Choose 'a. if v.IsInstanceMember then let rec firstArg e = @@ -4380,7 +4380,7 @@ and TcValSpec cenv env declKind newOk containerInfo memFlagsOpt thisTyOpt tpenv // Treat constraints at the "end" of the type as if they are declared. // This is by far the most convenient place to locate the constraints. // e.g. - // val FastGenericComparer<'T> : IComparer<'T> when 'T : comparison + // val FastGenericComparer<'T>: IComparer<'T> when 'T: comparison let tpenv = match ty with | SynType.WithGlobalConstraints(_, wcs, _) -> @@ -4431,7 +4431,7 @@ and TcValSpec cenv env declKind newOk containerInfo memFlagsOpt thisTyOpt tpenv else ty', valSynInfo - let reallyGenerateOneMember(id:Ident, valSynInfo, ty', memberFlags) = + let reallyGenerateOneMember(id: Ident, valSynInfo, ty', memberFlags) = let (PartialValReprInfo(argsData, _)) as partialValReprInfo = TranslateTopValSynInfo id.idRange (TcAttributes cenv env) valSynInfo @@ -4503,8 +4503,8 @@ and TcValSpec cenv env declKind newOk containerInfo memFlagsOpt thisTyOpt tpenv /// If optKind=Some kind, then this is the kind we're expecting (we're in *analysis* mode) /// If optKind=None, we need to determine the kind (we're in *synthesis* mode) /// -and TcTyparOrMeasurePar optKind cenv (env:TcEnv) newOk tpenv (Typar(id, _, _) as tp) = - let checkRes (res:Typar) = +and TcTyparOrMeasurePar optKind cenv (env: TcEnv) newOk tpenv (Typar(id, _, _) as tp) = + let checkRes (res: Typar) = match optKind, res.Kind with | Some TyparKind.Measure, TyparKind.Type -> error (Error(FSComp.SR.tcExpectedUnitOfMeasureMarkWithAttribute(), id.idRange)); res, tpenv | Some TyparKind.Type, TyparKind.Measure -> error (Error(FSComp.SR.tcExpectedTypeParameter(), id.idRange)); res, tpenv @@ -4573,7 +4573,7 @@ and TcTyparDecls cenv env synTypars = List.map (TcTyparDecl cenv env) synTypars /// If optKind=Some kind, then this is the kind we're expecting (we're in *analysis* mode) /// If optKind=None, we need to determine the kind (we're in *synthesis* mode) /// -and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv:SyntacticUnscopedTyparEnv) ty = +and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscopedTyparEnv) ty = match ty with | SynType.LongIdent(LongIdentWithDots([], _)) -> @@ -4679,7 +4679,7 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv:SyntacticUnscoped // _ types | SynType.Anon m -> - let tp:Typar = TcAnonTypeOrMeasure optKind cenv TyparRigidity.Anon TyparDynamicReq.No newOk m + let tp: Typar = TcAnonTypeOrMeasure optKind cenv TyparRigidity.Anon TyparDynamicReq.No newOk m match tp.Kind with | TyparKind.Measure -> TType_measure (Measure.Var tp), tpenv | TyparKind.Type -> mkTyparTy tp, tpenv @@ -4747,10 +4747,10 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv:SyntacticUnscoped errorR(Error(FSComp.SR.tcIllegalSyntaxInTypeExpression(), m)) NewErrorType (), tpenv -and TcType cenv newOk checkCxs occ env (tpenv:SyntacticUnscopedTyparEnv) ty = +and TcType cenv newOk checkCxs occ env (tpenv: SyntacticUnscopedTyparEnv) ty = TcTypeOrMeasure (Some TyparKind.Type) cenv newOk checkCxs occ env tpenv ty -and TcMeasure cenv newOk checkCxs occ env (tpenv:SyntacticUnscopedTyparEnv) ty m = +and TcMeasure cenv newOk checkCxs occ env (tpenv: SyntacticUnscopedTyparEnv) ty m = match ty with | SynType.Anon m -> error(Error(FSComp.SR.tcAnonymousUnitsOfMeasureCannotBeNested(), m)) @@ -4782,7 +4782,7 @@ and TcTypesAsTuple cenv newOk checkCxs occ env tpenv args m = ty::tys, tpenv // Type-check a list of measures separated by juxtaposition, * or / -and TcMeasuresAsTuple cenv newOk checkCxs occ env (tpenv:SyntacticUnscopedTyparEnv) args m = +and TcMeasuresAsTuple cenv newOk checkCxs occ env (tpenv: SyntacticUnscopedTyparEnv) args m = let rec gather args tpenv isquot acc = match args with | [] -> acc, tpenv @@ -4808,7 +4808,7 @@ and TcTyparConstraints cenv newOk checkCxs occ env tpenv wcs = tpenv #if !NO_EXTENSIONTYPING -and TcStaticConstantParameter cenv (env:TcEnv) tpenv kind (v:SynType) idOpt container = +and TcStaticConstantParameter cenv (env: TcEnv) tpenv kind (v: SynType) idOpt container = let fail() = error(Error(FSComp.SR.etInvalidStaticArgument(NicePrint.minimalStringOfType env.DisplayEnv kind), v.Range)) let record ttype = match idOpt with @@ -4821,20 +4821,20 @@ and TcStaticConstantParameter cenv (env:TcEnv) tpenv kind (v:SynType) idOpt cont | SynType.StaticConstant(sc, _) -> let v = match sc with - | SynConst.Byte n when typeEquiv cenv.g cenv.g.byte_ty kind -> record(cenv.g.byte_ty); box (n:byte) - | SynConst.Int16 n when typeEquiv cenv.g cenv.g.int16_ty kind -> record(cenv.g.int16_ty); box (n:int16) - | SynConst.Int32 n when typeEquiv cenv.g cenv.g.int32_ty kind -> record(cenv.g.int32_ty); box (n:int) - | SynConst.Int64 n when typeEquiv cenv.g cenv.g.int64_ty kind -> record(cenv.g.int64_ty); box (n:int64) - | SynConst.SByte n when typeEquiv cenv.g cenv.g.sbyte_ty kind -> record(cenv.g.sbyte_ty); box (n:sbyte) - | SynConst.UInt16 n when typeEquiv cenv.g cenv.g.uint16_ty kind -> record(cenv.g.uint16_ty); box (n:uint16) - | SynConst.UInt32 n when typeEquiv cenv.g cenv.g.uint32_ty kind -> record(cenv.g.uint32_ty); box (n:uint32) - | SynConst.UInt64 n when typeEquiv cenv.g cenv.g.uint64_ty kind -> record(cenv.g.uint64_ty); box (n:uint64) - | SynConst.Decimal n when typeEquiv cenv.g cenv.g.decimal_ty kind -> record(cenv.g.decimal_ty); box (n:decimal) - | SynConst.Single n when typeEquiv cenv.g cenv.g.float32_ty kind -> record(cenv.g.float32_ty); box (n:single) - | SynConst.Double n when typeEquiv cenv.g cenv.g.float_ty kind -> record(cenv.g.float_ty); box (n:double) - | SynConst.Char n when typeEquiv cenv.g cenv.g.char_ty kind -> record(cenv.g.char_ty); box (n:char) - | SynConst.String (s, _) when s <> null && typeEquiv cenv.g cenv.g.string_ty kind -> record(cenv.g.string_ty); box (s:string) - | SynConst.Bool b when typeEquiv cenv.g cenv.g.bool_ty kind -> record(cenv.g.bool_ty); box (b:bool) + | SynConst.Byte n when typeEquiv cenv.g cenv.g.byte_ty kind -> record(cenv.g.byte_ty); box (n: byte) + | SynConst.Int16 n when typeEquiv cenv.g cenv.g.int16_ty kind -> record(cenv.g.int16_ty); box (n: int16) + | SynConst.Int32 n when typeEquiv cenv.g cenv.g.int32_ty kind -> record(cenv.g.int32_ty); box (n: int) + | SynConst.Int64 n when typeEquiv cenv.g cenv.g.int64_ty kind -> record(cenv.g.int64_ty); box (n: int64) + | SynConst.SByte n when typeEquiv cenv.g cenv.g.sbyte_ty kind -> record(cenv.g.sbyte_ty); box (n: sbyte) + | SynConst.UInt16 n when typeEquiv cenv.g cenv.g.uint16_ty kind -> record(cenv.g.uint16_ty); box (n: uint16) + | SynConst.UInt32 n when typeEquiv cenv.g cenv.g.uint32_ty kind -> record(cenv.g.uint32_ty); box (n: uint32) + | SynConst.UInt64 n when typeEquiv cenv.g cenv.g.uint64_ty kind -> record(cenv.g.uint64_ty); box (n: uint64) + | SynConst.Decimal n when typeEquiv cenv.g cenv.g.decimal_ty kind -> record(cenv.g.decimal_ty); box (n: decimal) + | SynConst.Single n when typeEquiv cenv.g cenv.g.float32_ty kind -> record(cenv.g.float32_ty); box (n: single) + | SynConst.Double n when typeEquiv cenv.g cenv.g.float_ty kind -> record(cenv.g.float_ty); box (n: double) + | SynConst.Char n when typeEquiv cenv.g cenv.g.char_ty kind -> record(cenv.g.char_ty); box (n: char) + | SynConst.String (s, _) when s <> null && typeEquiv cenv.g cenv.g.string_ty kind -> record(cenv.g.string_ty); box (s: string) + | SynConst.Bool b when typeEquiv cenv.g cenv.g.bool_ty kind -> record(cenv.g.bool_ty); box (b: bool) | _ -> fail() v, tpenv | SynType.StaticConstantExpr(e, _ ) -> @@ -4849,21 +4849,21 @@ and TcStaticConstantParameter cenv (env:TcEnv) tpenv kind (v:SynType) idOpt cont // Check we have a residue constant. We know the type was correct because we checked the expression with this type. | Expr.Const(c, _, _) -> match c with - | Const.Byte n -> record(cenv.g.byte_ty); box (n:byte) - | Const.Int16 n -> record(cenv.g.int16_ty); box (n:int16) - | Const.Int32 n -> record(cenv.g.int32_ty); box (n:int) - | Const.Int64 n -> record(cenv.g.int64_ty); box (n:int64) - | Const.SByte n -> record(cenv.g.sbyte_ty); box (n:sbyte) - | Const.UInt16 n -> record(cenv.g.uint16_ty); box (n:uint16) - | Const.UInt32 n -> record(cenv.g.uint32_ty); box (n:uint32) - | Const.UInt64 n -> record(cenv.g.uint64_ty); box (n:uint64) - | Const.Decimal n -> record(cenv.g.decimal_ty); box (n:decimal) - | Const.Single n -> record(cenv.g.float32_ty); box (n:single) - | Const.Double n -> record(cenv.g.float_ty); box (n:double) - | Const.Char n -> record(cenv.g.char_ty); box (n:char) + | Const.Byte n -> record(cenv.g.byte_ty); box (n: byte) + | Const.Int16 n -> record(cenv.g.int16_ty); box (n: int16) + | Const.Int32 n -> record(cenv.g.int32_ty); box (n: int) + | Const.Int64 n -> record(cenv.g.int64_ty); box (n: int64) + | Const.SByte n -> record(cenv.g.sbyte_ty); box (n: sbyte) + | Const.UInt16 n -> record(cenv.g.uint16_ty); box (n: uint16) + | Const.UInt32 n -> record(cenv.g.uint32_ty); box (n: uint32) + | Const.UInt64 n -> record(cenv.g.uint64_ty); box (n: uint64) + | Const.Decimal n -> record(cenv.g.decimal_ty); box (n: decimal) + | Const.Single n -> record(cenv.g.float32_ty); box (n: single) + | Const.Double n -> record(cenv.g.float_ty); box (n: double) + | Const.Char n -> record(cenv.g.char_ty); box (n: char) | Const.String null -> fail() - | Const.String s -> record(cenv.g.string_ty); box (s:string) - | Const.Bool b -> record(cenv.g.bool_ty); box (b:bool) + | Const.String s -> record(cenv.g.string_ty); box (s: string) + | Const.Bool b -> record(cenv.g.bool_ty); box (b: bool) | _ -> fail() | _ -> error(Error(FSComp.SR.tcInvalidConstantExpression(), v.Range)) v, tpenv' @@ -4925,7 +4925,7 @@ and CrackStaticConstantArgs cenv env tpenv (staticParameters: Tainted info.ProvidedType @@ -5053,7 +5053,7 @@ and TcNestedTypeApplication cenv newOk checkCxs occ env tpenv mWholeTypeApp ty t | _ -> error(InternalError("TcNestedTypeApplication: expected type application", mWholeTypeApp)) -and TryAdjustHiddenVarNameToCompGenName cenv env (id:Ident) altNameRefCellOpt = +and TryAdjustHiddenVarNameToCompGenName cenv env (id: Ident) altNameRefCellOpt = match altNameRefCellOpt with | Some ({contents = Undecided altId } as altNameRefCell) -> match ResolvePatternLongIdent cenv.tcSink cenv.nameResolver AllIdsOK false id.idRange env.eAccessRights env.eNameResEnv TypeNameResolutionInfo.Default [id] with @@ -5094,7 +5094,7 @@ and TcSimplePat optArgsOK checkCxs cenv ty env (tpenv, names, takenNames) p = TcSimplePat optArgsOK checkCxs cenv ty env (tpenv, names, takenNames) p // raise an error if any optional args precede any non-optional args -and ValidateOptArgOrder (spats : SynSimplePats) = +and ValidateOptArgOrder (spats: SynSimplePats) = let rec getPats spats = match spats with @@ -5115,7 +5115,7 @@ and ValidateOptArgOrder (spats : SynSimplePats) = /// Bind the patterns used in argument position for a function, method or lambda. -and TcSimplePats cenv optArgsOK checkCxs ty env (tpenv, names, takenNames:Set<_>) p = +and TcSimplePats cenv optArgsOK checkCxs ty env (tpenv, names, takenNames: Set<_>) p = // validate optional argument declaration ValidateOptArgOrder p @@ -5158,7 +5158,7 @@ and TcSimplePatsOfUnknownType cenv optArgsOK checkCxs env tpenv spats = let argty = NewInferenceType () TcSimplePats cenv optArgsOK checkCxs argty env (tpenv, NameMap.empty, Set.empty) spats -and TcPatBindingName cenv env id ty isMemberThis vis1 topValData (inlineFlag, declaredTypars, argAttribs, isMutable, vis2, compgen) (names, takenNames:Set) = +and TcPatBindingName cenv env id ty isMemberThis vis1 topValData (inlineFlag, declaredTypars, argAttribs, isMutable, vis2, compgen) (names, takenNames: Set) = let vis = if Option.isSome vis1 then vis1 else vis2 if takenNames.Contains id.idText then errorR (VarBoundTwice id) let compgen = compgen || IsCompilerGeneratedName id.idText @@ -5188,7 +5188,7 @@ and TcPatBindingName cenv env id ty isMemberThis vis1 topValData (inlineFlag, de PBind(vspec, typeScheme)), names, takenNames -and TcPatAndRecover warnOnUpper cenv (env:TcEnv) topValInfo vFlags (tpenv, names, takenNames) ty (pat:SynPat) = +and TcPatAndRecover warnOnUpper cenv (env: TcEnv) topValInfo vFlags (tpenv, names, takenNames) ty (pat: SynPat) = try TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty pat with e -> @@ -5219,7 +5219,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p error(Error(FSComp.SR.tcInvalidNonPrimitiveLiteralInPatternMatch(), m)) | _ -> let c' = TcConst cenv ty m env c - (fun (_:TcPatPhase2Input) -> TPat_const(c', m)), (tpenv, names, takenNames) + (fun (_: TcPatPhase2Input) -> TPat_const(c', m)), (tpenv, names, takenNames) | SynPat.Wild m -> (fun _ -> TPat_wild m), (tpenv, names, takenNames) @@ -5372,7 +5372,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p | SynConstructorArgs.Pats args -> args | SynConstructorArgs.NamePatPairs (pairs, m) -> // rewrite patterns from the form (name-N = pat-N...) to (..._, pat-N, _...) - // so type T = Case of name : int * value : int + // so type T = Case of name: int * value: int // | Case(value = v) // will become // | Case(_, v) @@ -5723,7 +5723,7 @@ and CheckSuperInit cenv objTy m = // TcExprUndelayed //------------------------------------------------------------------------- -and TcExprUndelayedNoType cenv env tpenv synExpr : Expr * TType * _ = +and TcExprUndelayedNoType cenv env tpenv synExpr: Expr * TType * _ = let overallTy = NewInferenceType () let expr, tpenv = TcExprUndelayed cenv overallTy env tpenv synExpr expr, overallTy, tpenv @@ -5765,7 +5765,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = // (fun anonArg -> let[spMatch] anonVal = anonArg in pat1 -> expr1 ... | patN -> exprN) // // Note the presence of the "let" is visible in quotations regardless of the presence of sequence points, so - // <@ function x -> (x:int) @> + // <@ function x -> (x: int) @> // is // Lambda (_arg2, Let (x, _arg2, x)) @@ -5784,7 +5784,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = | SynExpr.Fixed (_, m) -> error(Error(FSComp.SR.tcFixedNotAllowed(), m)) - // e : ty + // e: ty | SynExpr.Typed (synBodyExpr, synType, m) -> let tgtTy, tpenv = TcTypeAndRecover cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synType UnifyTypes cenv env m overallTy tgtTy @@ -5876,7 +5876,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = else { env with eContextInfo = ContextInfo.CollectionElement (isArray, m) } - let args', tpenv = List.mapFold (fun tpenv (x:SynExpr) -> TcExprFlex cenv flex false argty (getInitEnv x.Range) tpenv x) tpenv args + let args', tpenv = List.mapFold (fun tpenv (x: SynExpr) -> TcExprFlex cenv flex false argty (getInitEnv x.Range) tpenv x) tpenv args let expr = if isArray then Expr.Op(TOp.Array, [argty], args', m) @@ -6497,13 +6497,13 @@ and GetNameAndArityOfObjExprBinding _cenv _env b = lookPat pat -and FreshenObjExprAbstractSlot cenv (env: TcEnv) (implty:TType) virtNameAndArityPairs (bind, bindAttribs, bindName, absSlots:(_ * MethInfo) list) = +and FreshenObjExprAbstractSlot cenv (env: TcEnv) (implty: TType) virtNameAndArityPairs (bind, bindAttribs, bindName, absSlots:(_ * MethInfo) list) = let (NormalizedBinding (_, _, _, _, _, _, synTyparDecls, _, _, _, mBinding, _)) = bind match absSlots with | [] when not (CompileAsEvent cenv.g bindAttribs) -> let absSlotsByName = List.filter (fst >> fst >> (=) bindName) virtNameAndArityPairs let getSignature absSlot = (NicePrint.stringOfMethInfo cenv.amap mBinding env.DisplayEnv absSlot).Replace("abstract ", "") - let getDetails (absSlot:MethInfo) = + let getDetails (absSlot: MethInfo) = if absSlot.GetParamTypes(cenv.amap, mBinding, []) |> List.existsSquared (isAnyTupleTy cenv.g) then FSComp.SR.tupleRequiredInAbstractMethod() else "" @@ -6531,9 +6531,9 @@ and FreshenObjExprAbstractSlot cenv (env: TcEnv) (implty:TType) virtNameAndArity errorR(ErrorWithSuggestions(FSComp.SR.tcMemberFoundIsNotAbstractOrVirtual(tcref.DisplayName, bindName), mBinding, bindName, suggestVirtualMembers)) else errorR(ErrorWithSuggestions(FSComp.SR.tcNoAbstractOrVirtualMemberFound(bindName), mBinding, bindName, suggestVirtualMembers)) - | [(_, absSlot:MethInfo)] -> + | [(_, absSlot: MethInfo)] -> errorR(Error(FSComp.SR.tcArgumentArityMismatch(bindName, List.sum absSlot.NumArgs, arity, getSignature absSlot, getDetails absSlot), mBinding)) - | (_, absSlot:MethInfo) :: _ -> + | (_, absSlot: MethInfo) :: _ -> errorR(Error(FSComp.SR.tcArgumentArityMismatchOneOverload(bindName, List.sum absSlot.NumArgs, arity, getSignature absSlot, getDetails absSlot), mBinding)) None @@ -6668,7 +6668,7 @@ and ComputeObjectExprOverrides cenv (env: TcEnv) tpenv impls = // Convert the syntactic info to actual info let overrides = - (overrides, bindNameAndSynInfoPairs) ||> List.map2 (fun (id:Ident, memberFlags, ty, bindingAttribs, bindingBody) (_, valSynData) -> + (overrides, bindNameAndSynInfoPairs) ||> List.map2 (fun (id: Ident, memberFlags, ty, bindingAttribs, bindingBody) (_, valSynData) -> let partialValInfo = TranslateTopValSynInfo id.idRange (TcAttributes cenv env) valSynData let tps, _ = tryDestForallTy cenv.g ty let valInfo = TranslatePartialArity tps partialValInfo @@ -6911,7 +6911,7 @@ and TcConstExpr cenv overallTy env m tpenv c = //------------------------------------------------------------------------- // Check an 'assert(x)' expression. -and TcAssertExpr cenv overallTy env (m:range) tpenv x = +and TcAssertExpr cenv overallTy env (m: range) tpenv x = let synm = m.MakeSynthetic() // Mark as synthetic so the language service won't pick it up. let callDiagnosticsExpr = SynExpr.App(ExprAtomicFlag.Atomic, false, mkSynLidGet synm ["System";"Diagnostics";"Debug"] "Assert", // wrap an extra parentheses so 'assert(x=1) isn't considered a named argument to a method call @@ -7232,7 +7232,7 @@ and TcQuotationExpr cenv overallTy env tpenv (_oper, raw, ast, isFromQueryExpres and TcComputationOrSequenceExpression cenv (env: TcEnv) overallTy m interpValOpt tpenv comp = match interpValOpt with - | Some (interpExpr:Expr, builderTy) -> + | Some (interpExpr: Expr, builderTy) -> TcComputationExpression cenv env overallTy m interpExpr builderTy tpenv comp | None -> TcSequenceExpression cenv env tpenv comp overallTy m @@ -7261,7 +7261,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | _ -> false /// Make a builder.Method(...) call - let mkSynCall nm (m:range) args = + let mkSynCall nm (m: range) args = let m = m.MakeSynthetic() // Mark as synthetic so the language service won't pick it up. let args = match args with @@ -7305,7 +7305,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv (function (Attrib(_, _, _, ExtractAttribNamedArg "JoinConditionWord" (AttribStringArg s), _, _, _)) -> Some s | _ -> None) IgnoreAttribute // We do not respect this attribute for provided methods - let flagSearch (propName:string) = + let flagSearch (propName: string) = TryBindMethInfoAttribute cenv.g mBuilderVal cenv.g.attrib_CustomOperationAttribute methInfo IgnoreAttribute // We do not respect this attribute for IL methods (function (Attrib(_, _, _, ExtractAttribNamedArg propName (AttribBoolArg b), _, _, _)) -> Some b | _ -> None) @@ -7335,7 +7335,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv /// Decide if the identifier represents a use of a custom query operator - let tryGetDataForCustomOperation (nm:Ident) = + let tryGetDataForCustomOperation (nm: Ident) = match customOperationMethodsIndexedByKeyword.TryGetValue nm.idText with | true, [opData] -> let (opName, maintainsVarSpaceUsingBind, maintainsVarSpace, _allowInto, isLikeZip, isLikeJoin, isLikeGroupJoin, _joinConditionWord, methInfo) = opData @@ -7354,37 +7354,37 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let isCustomOperation nm = tryGetDataForCustomOperation nm |> Option.isSome // Check for the MaintainsVariableSpace on custom operation - let customOperationMaintainsVarSpace (nm:Ident) = + let customOperationMaintainsVarSpace (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false | Some (_nm, _maintainsVarSpaceUsingBind, maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> maintainsVarSpace - let customOperationMaintainsVarSpaceUsingBind (nm:Ident) = + let customOperationMaintainsVarSpaceUsingBind (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false | Some (_nm, maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> maintainsVarSpaceUsingBind - let customOperationIsLikeZip (nm:Ident) = + let customOperationIsLikeZip (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeZip - let customOperationIsLikeJoin (nm:Ident) = + let customOperationIsLikeJoin (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeJoin - let customOperationIsLikeGroupJoin (nm:Ident) = + let customOperationIsLikeGroupJoin (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeGroupJoin - let customOperationJoinConditionWord (nm:Ident) = + let customOperationJoinConditionWord (nm: Ident) = match tryGetDataForCustomOperation nm with | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, Some joinConditionWord, _methInfo) -> joinConditionWord | _ -> "on" - let customOperationAllowsInto (nm:Ident) = + let customOperationAllowsInto (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> allowInto @@ -7417,7 +7417,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv CallEnvSink cenv.tcSink (comp.Range, env.NameEnv, ad) // Check for the [] attribute on an argument position - let tryGetArgInfosForCustomOperator (nm:Ident) = + let tryGetArgInfosForCustomOperator (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> None | Some (_nm, __maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, methInfo) -> @@ -7428,13 +7428,13 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | _ -> None | _ -> None - let expectedArgCountForCustomOperator (nm:Ident) = + let expectedArgCountForCustomOperator (nm: Ident) = match tryGetArgInfosForCustomOperator nm with | None -> 0 | Some argInfos -> max (argInfos.Length - 1) 0 // drop the computation context argument // Check for the [] attribute on an argument position - let isCustomOperationProjectionParameter i (nm:Ident) = + let isCustomOperationProjectionParameter i (nm: Ident) = match tryGetArgInfosForCustomOperator nm with | None -> false | Some argInfos -> @@ -7454,13 +7454,13 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | _ -> None // e1 in e2 ('in' is parsed as 'JOIN_IN') - let (|InExpr|_|) (e:SynExpr) = + let (|InExpr|_|) (e: SynExpr) = match e with | SynExpr.JoinIn(e1, _, e2, mApp) -> Some (e1, e2, mApp) | _ -> None // e1 on e2 (note: 'on' is the 'JoinConditionWord') - let (|OnExpr|_|) nm (e:SynExpr) = + let (|OnExpr|_|) nm (e: SynExpr) = match tryGetDataForCustomOperation nm with | None -> None | Some _ -> @@ -7472,7 +7472,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | _ -> None // e1 into e2 - let (|IntoSuffix|_|) (e:SynExpr) = + let (|IntoSuffix|_|) (e: SynExpr) = match e with | SynExpr.App(_, _, SynExpr.App(_, _, x, SingleIdent nm2, _), ExprAsPat intoPat, _) when nm2.idText = CustomOperations.Into -> Some (x, nm2.idRange, intoPat) @@ -7481,7 +7481,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let arbPat (m: range) = mkSynPatVar None (mkSynId (m.MakeSynthetic()) "_missingVar") - let MatchIntoSuffixOrRecover alreadyGivenError (nm:Ident) (e:SynExpr) = + let MatchIntoSuffixOrRecover alreadyGivenError (nm: Ident) (e: SynExpr) = match e with | IntoSuffix (x, intoWordRange, intoPat) -> // record the "into" as a custom operation for colorization @@ -7493,7 +7493,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv errorR(Error(FSComp.SR.tcOperatorIncorrectSyntax(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) (e, arbPat e.Range, true) - let MatchOnExprOrRecover alreadyGivenError nm (onExpr:SynExpr) = + let MatchOnExprOrRecover alreadyGivenError nm (onExpr: SynExpr) = match onExpr with | OnExpr nm (innerSource, SynExprParen(keySelectors, _, _, _)) -> (innerSource, keySelectors) @@ -7519,12 +7519,12 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv None // JoinOrGroupJoinOp customOperationIsLikeJoin - let (|JoinOp|_|) (e:SynExpr) = JoinOrGroupJoinOp customOperationIsLikeJoin e - let (|GroupJoinOp|_|) (e:SynExpr) = JoinOrGroupJoinOp customOperationIsLikeGroupJoin e + let (|JoinOp|_|) (e: SynExpr) = JoinOrGroupJoinOp customOperationIsLikeJoin e + let (|GroupJoinOp|_|) (e: SynExpr) = JoinOrGroupJoinOp customOperationIsLikeGroupJoin e let arbKeySelectors m = mkSynBifix m "=" (arbExpr("_keySelectors", m)) (arbExpr("_keySelector2", m)) - let (|JoinExpr|_|) (e:SynExpr) = + let (|JoinExpr|_|) (e: SynExpr) = match e with | InExpr (JoinOp(nm, innerSourcePat, _, alreadyGivenError), onExpr, mJoinCore) -> let (innerSource, keySelectors) = MatchOnExprOrRecover alreadyGivenError nm onExpr @@ -7535,7 +7535,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv Some (nm, innerSourcePat, arbExpr("_innerSource", e.Range), arbKeySelectors e.Range, mJoinCore) | _ -> None - let (|GroupJoinExpr|_|) (e:SynExpr) = + let (|GroupJoinExpr|_|) (e: SynExpr) = match e with | InExpr (GroupJoinOp (nm, innerSourcePat, _, alreadyGivenError), intoExpr, mGroupJoinCore) -> let onExpr, intoPat, alreadyGivenError = MatchIntoSuffixOrRecover alreadyGivenError nm intoExpr @@ -7549,7 +7549,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv None - let (|JoinOrGroupJoinOrZipClause|_|) (e:SynExpr) = + let (|JoinOrGroupJoinOrZipClause|_|) (e: SynExpr) = match e with // join innerSourcePat in innerSource on (keySelector1 = keySelector2) @@ -7933,7 +7933,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let isYield = not (customOperationMaintainsVarSpaceUsingBind nm) translatedCtxt (transNoQueryOps (SynExpr.YieldOrReturn((isYield, false), varSpaceExpr, mClause))) - let rec consumeClauses (varSpace:LazyWithContext<_, _>) dataCompPrior compClausesExpr lastUsesBind = + let rec consumeClauses (varSpace: LazyWithContext<_, _>) dataCompPrior compClausesExpr lastUsesBind = // Substitute 'yield ' into the context @@ -8295,7 +8295,7 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = // Allow subsumption at 'yield' if the element type is nominal prior to the analysis of the body of the sequence expression let flex = not (isTyparTy cenv.g genEnumElemTy) - let mkDelayedExpr (coreExpr:Expr) = + let mkDelayedExpr (coreExpr: Expr) = let m = coreExpr.Range let overallTy = tyOfExpr cenv.g coreExpr mkSeqDelay cenv env m overallTy coreExpr @@ -8541,14 +8541,14 @@ and Propagate cenv overallTy env tpenv (expr: ApplicableExpr) exprty delayed = propagate false delayed expr.Range exprty -and PropagateThenTcDelayed cenv overallTy env tpenv mExpr expr exprty (atomicFlag:ExprAtomicFlag) delayed = +and PropagateThenTcDelayed cenv overallTy env tpenv mExpr expr exprty (atomicFlag: ExprAtomicFlag) delayed = Propagate cenv overallTy env tpenv expr exprty delayed TcDelayed cenv overallTy env tpenv mExpr expr exprty atomicFlag delayed /// Typecheck "expr ... " constructs where "..." is a sequence of applications, /// type applications and dot-notation projections. -and TcDelayed cenv overallTy env tpenv mExpr expr exprty (atomicFlag:ExprAtomicFlag) delayed = +and TcDelayed cenv overallTy env tpenv mExpr expr exprty (atomicFlag: ExprAtomicFlag) delayed = // OK, we've typechecked the thing on the left of the delayed lookup chain. // We can now record for posterity the type of this expression and the location of the expression. @@ -8634,7 +8634,7 @@ and TcFunctionApplicationThen cenv overallTy env tpenv mExprAndArg expr exprty ( error (NotAFunction(denv, overallTy, mFunExpr, mArg)) //------------------------------------------------------------------------- -// TcLongIdentThen : Typecheck "A.B.C.E.F ... " constructs +// TcLongIdentThen: Typecheck "A.B.C.E.F ... " constructs //------------------------------------------------------------------------- and TcLongIdentThen cenv overallTy env tpenv (LongIdentWithDots(longId, _)) delayed = @@ -9397,7 +9397,7 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela | (Item.FakeInterfaceCtor _ | Item.DelegateCtor _) -> error (Error (FSComp.SR.tcConstructorsCannotBeFirstClassValues(), mItem)) | _ -> error (Error (FSComp.SR.tcSyntaxFormUsedOnlyWithRecordLabelsPropertiesAndFields(), mItem)) -and TcEventValueThen cenv overallTy env tpenv mItem mExprAndItem objDetails (einfo:EventInfo) delayed = +and TcEventValueThen cenv overallTy env tpenv mItem mExprAndItem objDetails (einfo: EventInfo) delayed = // Instance IL event (fake up event-as-value) let nm = einfo.EventName let ad = env.eAccessRights @@ -9514,7 +9514,7 @@ and TcMethodApplication mMethExpr // range of the entire method expression mItem methodName - (objTyOpt : TType option) + (objTyOpt: TType option) ad mut isProp @@ -9622,7 +9622,7 @@ and TcMethodApplication let unnamedCurriedCallerArgs = unnamedCurriedCallerArgs |> List.mapSquared MakeUnnamedCallerArgInfo let namedCurriedCallerArgs = namedCurriedCallerArgs |> List.mapSquared (fun (isOpt, nm, x) -> let ty = GetNewInferenceTypeForMethodArg cenv env tpenv x - // #435263 : compiler crash with .net optional parameters and F# optional syntax + // #435263: compiler crash with .net optional parameters and F# optional syntax // named optional arguments should always have option type let ty = if isOpt then mkOptionTy denv.g ty else ty nm, isOpt, x, ty, x.Range @@ -9631,17 +9631,17 @@ and TcMethodApplication (Some (unnamedCurriedCallerArgs, namedCurriedCallerArgs), None, exprTy) - let CalledMethHasSingleArgumentGroupOfThisLength n (calledMeth:MethInfo) = + let CalledMethHasSingleArgumentGroupOfThisLength n (calledMeth: MethInfo) = let curriedMethodArgAttribs = calledMeth.GetParamAttribs(cenv.amap, mItem) curriedMethodArgAttribs.Length = 1 && curriedMethodArgAttribs.Head.Length = n - let GenerateMatchingSimpleArgumentTypes (calledMeth:MethInfo) = + let GenerateMatchingSimpleArgumentTypes (calledMeth: MethInfo) = let curriedMethodArgAttribs = calledMeth.GetParamAttribs(cenv.amap, mItem) curriedMethodArgAttribs |> List.map (List.filter isSimpleFormalArg >> NewInferenceTypes) - let UnifyMatchingSimpleArgumentTypes exprTy (calledMeth:MethInfo) = + let UnifyMatchingSimpleArgumentTypes exprTy (calledMeth: MethInfo) = let curriedArgTys = GenerateMatchingSimpleArgumentTypes calledMeth let returnTy = (exprTy, curriedArgTys) ||> List.fold (fun exprTy argTys -> @@ -9806,7 +9806,7 @@ and TcMethodApplication let callerArgs = List.zip unnamedCurriedCallerArgs namedCurriedCallerArgs let postArgumentTypeCheckingCalledMethGroup = - preArgumentTypeCheckingCalledMethGroup |> List.map (fun (minfo:MethInfo, minst, pinfoOpt, usesParamArrayConversion) -> + preArgumentTypeCheckingCalledMethGroup |> List.map (fun (minfo: MethInfo, minst, pinfoOpt, usesParamArrayConversion) -> let callerTyArgs = match tyargsOpt with | Some tyargs -> minfo.AdjustUserTypeInstForFSharpStyleIndexedExtensionMembers(tyargs) @@ -10389,7 +10389,7 @@ and TcNewDelegateThen cenv overallTy env tpenv mDelTy mExprAndArg delegateTy arg error(Error(FSComp.SR.tcDelegateConstructorMustBePassed(), mExprAndArg)) -and bindLetRec (binds:Bindings) m e = +and bindLetRec (binds: Bindings) m e = if isNil binds then e else @@ -10477,7 +10477,7 @@ and TcAndPatternCompileMatchClauses mExpr matchm actionOnFailure cenv inputExprO let matchVal, expr = CompilePatternForMatchClauses cenv env mExpr matchm true actionOnFailure inputExprOpt inputTy resultTy clauses matchVal, expr, tpenv -and TcMatchPattern cenv inputTy env tpenv (pat:SynPat, optWhenExpr) = +and TcMatchPattern cenv inputTy env tpenv (pat: SynPat, optWhenExpr) = let m = pat.Range let patf', (tpenv, names, _) = TcPat WarnOnUpperCase cenv env None (ValInline.Optional, permitInferTypars, noArgOrRetAttribs, false, None, false) (tpenv, Map.empty, Set.empty) inputTy pat let envinner, values, vspecMap = MakeAndPublishSimpleVals cenv env m names false @@ -10516,7 +10516,7 @@ and TcStaticOptimizationConstraint cenv env tpenv c = TTyconIsStruct(mkTyparTy tp'), tpenv /// Emit a conv.i instruction -and mkConvToNativeInt (g:TcGlobals) e m = Expr.Op (TOp.ILAsm ([ AI_conv ILBasicType.DT_I], [ g.nativeint_ty ]), [], [e], m) +and mkConvToNativeInt (g: TcGlobals) e m = Expr.Op (TOp.ILAsm ([ AI_conv ILBasicType.DT_I], [ g.nativeint_ty ]), [], [e], m) /// Fix up the r.h.s. of a 'use x = fixed expr' and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBinding) = @@ -10546,7 +10546,7 @@ and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBindi let charPtrTy = mkNativePtrTy cenv.g cenv.g.char_ty UnifyTypes cenv env mBinding charPtrTy overallPatTy // - // let ptr : nativeptr = + // let ptr: nativeptr = // let pinned s = str // (nativeptr)s + get_OffsettoStringData() @@ -10563,11 +10563,11 @@ and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBindi let elemPtrTy = mkNativePtrTy cenv.g elemTy UnifyTypes cenv env mBinding elemPtrTy overallPatTy - // let ptr : nativeptr = - // let tmpArray : elem[] = arr + // let ptr: nativeptr = + // let tmpArray: elem[] = arr // if nonNull tmpArray then // if tmpArray.Length <> 0 then - // let pinned tmpArrayByref : byref = &arr.[0] + // let pinned tmpArrayByref: byref = &arr.[0] // (nativeint) tmpArrayByref // else // (nativeint) 0 @@ -10593,7 +10593,7 @@ and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBindi /// Binding checking code, for all bindings including let bindings, let-rec bindings, member bindings and object-expression bindings and -and TcNormalizedBinding declKind (cenv:cenv) env tpenv overallTy safeThisValOpt safeInitInfo (enclosingDeclaredTypars, (ExplicitTyparInfo(_, declaredTypars, _) as flex)) bind = +and TcNormalizedBinding declKind (cenv: cenv) env tpenv overallTy safeThisValOpt safeInitInfo (enclosingDeclaredTypars, (ExplicitTyparInfo(_, declaredTypars, _) as flex)) bind = let envinner = AddDeclaredTypars NoCheckForDuplicateTypars (enclosingDeclaredTypars@declaredTypars) env match bind with @@ -11170,7 +11170,7 @@ and CheckMemberFlags optIntfSlotTy newslotsOK overridesOK memberFlags m = /// the _body_ of the binding. For example, in a letrec we may assume this knowledge /// for each binding in the letrec prior to any type inference. This might, for example, /// tell us the type of the arguments to a recursive function. -and ApplyTypesFromArgumentPatterns (cenv, env, optArgsOK, ty, m, tpenv, NormalizedBindingRhs (pushedPats, retInfoOpt, e), memberFlagsOpt:MemberFlags option) = +and ApplyTypesFromArgumentPatterns (cenv, env, optArgsOK, ty, m, tpenv, NormalizedBindingRhs (pushedPats, retInfoOpt, e), memberFlagsOpt: MemberFlags option) = match pushedPats with | [] -> match retInfoOpt with @@ -11202,7 +11202,7 @@ and ComputeIsComplete enclosingDeclaredTypars declaredTypars ty = /// Determine if a uniquely-identified-abstract-slot exists for an override member (or interface member implementation) based on the information available /// at the syntactic definition of the member (i.e. prior to type inference). If so, we know the expected signature of the override, and the full slotsig /// it implements. Apply the inferred slotsig. -and ApplyAbstractSlotInference (cenv:cenv) (envinner:TcEnv) (bindingTy, m, synTyparDecls, declaredTypars, memberId, tcrefObjTy, renaming, _objTy, optIntfSlotTy, valSynData, memberFlags, attribs) = +and ApplyAbstractSlotInference (cenv: cenv) (envinner: TcEnv) (bindingTy, m, synTyparDecls, declaredTypars, memberId, tcrefObjTy, renaming, _objTy, optIntfSlotTy, valSynData, memberFlags, attribs) = let ad = envinner.eAccessRights let typToSearchForAbstractMembers = @@ -11375,7 +11375,7 @@ and AnalyzeRecursiveStaticMemberOrValDecl tpenv, declKind, newslotsOK, overridesOK, tcrefContainerInfo, vis1, - id:Ident, vis2, declaredTypars, + id: Ident, vis2, declaredTypars, memberFlagsOpt, thisIdOpt, bindingAttribs, valSynInfo, ty, bindingRhs, mBinding, flex) = @@ -11446,8 +11446,8 @@ and AnalyzeRecursiveStaticMemberOrValDecl and AnalyzeRecursiveInstanceMemberDecl (cenv, envinner: TcEnv, tpenv, declKind, synTyparDecls, valSynInfo, - flex:ExplicitTyparInfo, newslotsOK, overridesOK, vis1, thisId, - memberId:Ident, toolId:Ident option, bindingAttribs, vis2, + flex: ExplicitTyparInfo, newslotsOK, overridesOK, vis1, thisId, + memberId: Ident, toolId: Ident option, bindingAttribs, vis2, tcrefContainerInfo, memberFlagsOpt, ty, bindingRhs, mBinding) = let vis = CombineVisibilityAttribs vis1 vis2 mBinding @@ -11560,7 +11560,7 @@ and AnalyzeRecursiveDecl (cenv, envinner, tpenv, declKind, synTyparDecls, declar /// and overrides). At this point we perform override inference, to infer /// which method we are overriding, in order to add constraints to the /// implementation of the method. -and AnalyzeAndMakeAndPublishRecursiveValue overridesOK isGeneratedEventVal cenv (env:TcEnv) (tpenv, recBindIdx) (NormalizedRecBindingDefn(containerInfo, newslotsOK, declKind, binding)) = +and AnalyzeAndMakeAndPublishRecursiveValue overridesOK isGeneratedEventVal cenv (env: TcEnv) (tpenv, recBindIdx) (NormalizedRecBindingDefn(containerInfo, newslotsOK, declKind, binding)) = // Pull apart the inputs let (NormalizedBinding(vis1, bindingKind, isInline, isMutable, bindingSynAttribs, bindingXmlDoc, synTyparDecls, valSynData, declPattern, bindingRhs, mBinding, spBind)) = binding @@ -11648,7 +11648,7 @@ and AnalyzeAndMakeAndPublishRecursiveValue overridesOK isGeneratedEventVal cenv let recBindIdx = recBindIdx + 1 // Done - add the declared name to the List.map and return the bundle for use by TcLetrec - let primaryBinding : PreCheckingRecursiveBinding = + let primaryBinding: PreCheckingRecursiveBinding = { SyntacticBinding = revisedBinding RecBindingInfo = rbinfo } @@ -11671,13 +11671,13 @@ and TcLetrecBinding // The state of the left-to-right iteration through the bindings (envNonRec: TcEnv, - generalizedRecBinds : PostGeneralizationRecursiveBinding list, + generalizedRecBinds: PostGeneralizationRecursiveBinding list, preGeneralizationRecBinds: PreGeneralizationRecursiveBinding list, tpenv, - uncheckedRecBindsTable : Map) + uncheckedRecBindsTable: Map) // This is the actual binding to check - (rbind : PreCheckingRecursiveBinding) = + (rbind: PreCheckingRecursiveBinding) = let (RBInfo(_, _, enclosingDeclaredTypars, _, vspec, flex, _, _, baseValOpt, safeThisValOpt, safeInitInfo, _, tau, declKind)) = rbind.RecBindingInfo @@ -11696,15 +11696,15 @@ and TcLetrecBinding // // Example 1: - // let f() = g() f : unit -> ?b - // and g() = 1 f : unit -> int, can generalize (though now monomorphic) + // let f() = g() f: unit -> ?b + // and g() = 1 f: unit -> int, can generalize (though now monomorphic) // Example 2: - // let f() = g() f : unit -> ?b - // and g() = [] f : unit -> ?c list, can generalize + // let f() = g() f: unit -> ?b + // and g() = [] f: unit -> ?c list, can generalize // Example 3: - // let f() = [] f : unit -> ?b, can generalize immediately + // let f() = [] f: unit -> ?b, can generalize immediately // and g() = [] let envRec = Option.foldBack (AddLocalVal cenv.tcSink scopem) baseValOpt envRec let envRec = Option.foldBack (AddLocalVal cenv.tcSink scopem) safeThisValOpt envRec @@ -11754,10 +11754,10 @@ and TcLetrecBinding and TcIncrementalLetRecGeneralization cenv scopem // The state of the left-to-right iteration through the bindings (envNonRec: TcEnv, - generalizedRecBinds : PostGeneralizationRecursiveBinding list, + generalizedRecBinds: PostGeneralizationRecursiveBinding list, preGeneralizationRecBinds: PreGeneralizationRecursiveBinding list, tpenv, - uncheckedRecBindsTable : Map) = + uncheckedRecBindsTable: Map) = let denv = envNonRec.DisplayEnv // recompute the free-in-environment in case any type variables have been instantiated @@ -11925,7 +11925,7 @@ and TcIncrementalLetRecGeneralization cenv scopem //------------------------------------------------------------------------- /// Compute the type variables which may be generalized and perform the generalization -and TcLetrecComputeAndGeneralizeGenericTyparsForBinding cenv denv freeInEnv (pgrbind : PreGeneralizationRecursiveBinding) = +and TcLetrecComputeAndGeneralizeGenericTyparsForBinding cenv denv freeInEnv (pgrbind: PreGeneralizationRecursiveBinding) = let freeInEnv = Zset.diff freeInEnv (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.ExtraGeneralizableTypars)) @@ -11956,7 +11956,7 @@ and TcLetrecComputeAndGeneralizeGenericTyparsForBinding cenv denv freeInEnv (pgr generalizedTypars /// Compute the type variables which may have member constraints that need to be canonicalized prior to generalization -and TcLetrecComputeSupportForBinding cenv (pgrbind : PreGeneralizationRecursiveBinding) = +and TcLetrecComputeSupportForBinding cenv (pgrbind: PreGeneralizationRecursiveBinding) = let rbinfo = pgrbind.RecBindingInfo let allDeclaredTypars = rbinfo.EnclosingDeclaredTypars @ rbinfo.DeclaredTypars let maxInferredTypars = freeInTypeLeftToRight cenv.g false rbinfo.Val.TauType @@ -11967,7 +11967,7 @@ and TcLetrecComputeSupportForBinding cenv (pgrbind : PreGeneralizationRecursiveB //------------------------------------------------------------------------ // Generalise generalizedTypars from checkedBind. -and TcLetrecGeneralizeBinding cenv denv generalizedTypars (pgrbind : PreGeneralizationRecursiveBinding) : PostGeneralizationRecursiveBinding = +and TcLetrecGeneralizeBinding cenv denv generalizedTypars (pgrbind: PreGeneralizationRecursiveBinding) : PostGeneralizationRecursiveBinding = let (RBInfo(_, _, enclosingDeclaredTypars, _, vspec, flex, partialValReprInfo, memberInfoOpt, _, _, _, vis, _, declKind)) = pgrbind.RecBindingInfo let (CheckedBindingInfo(inlineFlag, _, _, _, _, _, expr, argAttribs, _, _, _, compgen, _, isFixed)) = pgrbind.CheckedBinding @@ -11991,12 +11991,12 @@ and TcLetrecGeneralizeBinding cenv denv generalizedTypars (pgrbind : PreGenerali and TcLetrecComputeCtorSafeThisValBind cenv safeThisValOpt = match safeThisValOpt with | None -> None - | Some (v:Val) -> + | Some (v: Val) -> let m = v.Range let ty = destRefCellTy cenv.g v.Type Some (mkCompGenBind v (mkRefCell cenv.g m ty (mkNull m ty))) -and MakeCheckSafeInitField g tinst thisValOpt rfref reqExpr (expr:Expr) = +and MakeCheckSafeInitField g tinst thisValOpt rfref reqExpr (expr: Expr) = let m = expr.Range let availExpr = match thisValOpt with @@ -12072,7 +12072,7 @@ and TcLetrecAdjustMemberForSpecialVals cenv (pgrbind: PostGeneralizationRecursiv { ValScheme = pgrbind.ValScheme Binding = TBind(vspec, expr, spBind) } -and FixupLetrecBind cenv denv generalizedTyparsForRecursiveBlock (bind : PostBindCtorThisVarRefCellRecursiveBinding) = +and FixupLetrecBind cenv denv generalizedTyparsForRecursiveBlock (bind: PostBindCtorThisVarRefCellRecursiveBinding) = let (TBind(vspec, expr, spBind)) = bind.Binding // Check coherence of generalization of variables for memberInfo members in generic classes @@ -12230,12 +12230,12 @@ let TcAndPublishValSpec (cenv, env, containerInfo: ContainerInfo, declKind, memF exception NotUpperCaseConstructor of range -let CheckNamespaceModuleOrTypeName (g:TcGlobals) (id:Ident) = +let CheckNamespaceModuleOrTypeName (g: TcGlobals) (id: Ident) = // type names '[]' etc. are used in fslib if not g.compilingFslib && id.idText.IndexOfAny(IllegalCharactersInTypeAndNamespaceNames) <> -1 then errorR(Error(FSComp.SR.tcInvalidNamespaceModuleTypeUnionName(), id.idRange)) -let CheckDuplicates (idf : _ -> Ident) k elems = +let CheckDuplicates (idf: _ -> Ident) k elems = elems |> List.iteri (fun i uc1 -> elems |> List.iteri (fun j uc2 -> let id1 = (idf uc1) @@ -12318,7 +12318,7 @@ module TcRecdUnionAndEnumDeclarations = begin if not (String.isUpper name) && name <> opNameCons && name <> opNameNil then errorR(NotUpperCaseConstructor(id.idRange)) - let ValidateFieldNames (synFields : SynField list, tastFields : RecdField list) = + let ValidateFieldNames (synFields: SynField list, tastFields: RecdField list) = let seen = Dictionary() for (sf, f) in List.zip synFields tastFields do let mutable synField = Unchecked.defaultof<_> @@ -12366,7 +12366,7 @@ module TcRecdUnionAndEnumDeclarations = begin NewUnionCase id rfields recordTy attrs (xmldoc.ToXmlDoc()) vis - let TcUnionCaseDecls cenv env parent (thisTy : TType) tpenv unionCases = + let TcUnionCaseDecls cenv env parent (thisTy: TType) tpenv unionCases = let unionCases' = unionCases |> List.map (TcUnionCaseDecl cenv env parent thisTy tpenv) unionCases' |> CheckDuplicates (fun uc -> uc.Id) "union case" @@ -12394,7 +12394,7 @@ end // Bind elements of classes //------------------------------------------------------------------------- -let PublishInterface cenv denv (tcref:TyconRef) m compgen ty' = +let PublishInterface cenv denv (tcref: TyconRef) m compgen ty' = if not (isInterfaceTy cenv.g ty') then errorR(Error(FSComp.SR.tcTypeIsNotInterfaceType1(NicePrint.minimalStringOfType denv ty'), m)) let tcaug = tcref.TypeContents if tcref.HasInterface cenv.g ty' then @@ -12422,7 +12422,7 @@ let TcTyconMemberSpecs cenv env containerInfo declKind tpenv (augSpfn: SynMember // Bind 'open' declarations //------------------------------------------------------------------------- -let TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap (longId : Ident list) = +let TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap (longId: Ident list) = let ad = env.eAccessRights match longId with | [] -> Result [] @@ -12432,7 +12432,7 @@ let TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap (longId : Ident l | Result res -> Result res | Exception err -> raze err -let TcOpenDecl tcSink (g:TcGlobals) amap m scopem env (longId : Ident list) = +let TcOpenDecl tcSink (g: TcGlobals) amap m scopem env (longId: Ident list) = let modrefs = ForceRaise (TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap longId) // validate opened namespace names @@ -12499,33 +12499,45 @@ module IncrClassChecking = /// Typechecked info for implicit constructor and it's arguments type IncrClassCtorLhs = - {/// The TyconRef for the type being defined - TyconRef : TyconRef - /// The type parameters allocated for the implicit instance constructor. - /// These may be equated with other (WillBeRigid) type parameters through equirecursive inference, and so - /// should always be renormalized/canonicalized when used. - InstanceCtorDeclaredTypars : Typars - /// The value representing the static implicit constructor. - /// Lazy to ensure the static ctor value is only published if needed. - StaticCtorValInfo : Lazy<(Val list * Val * ValScheme)> - /// The value representing the implicit constructor. - InstanceCtorVal : Val - /// The type of the implicit constructor, representing as a ValScheme. - InstanceCtorValScheme : ValScheme - /// The values representing the arguments to the implicit constructor. - InstanceCtorArgs : Val list - /// The reference cell holding the 'this' parameter within the implicit constructor so it can be referenced in the - /// arguments passed to the base constructor - InstanceCtorSafeThisValOpt : Val option - /// Data indicating if safe-initialization checks need to be inserted for this type. - InstanceCtorSafeInitInfo : SafeInitData - /// The value representing the 'base' variable within the implicit instance constructor. - InstanceCtorBaseValOpt : Val option - /// The value representing the 'this' variable within the implicit instance constructor. - InstanceCtorThisVal : Val - /// The name generator used to generate the names of fields etc. within the type. - NameGenerator : NiceNameGenerator + { + /// The TyconRef for the type being defined + TyconRef: TyconRef + + /// The type parameters allocated for the implicit instance constructor. + /// These may be equated with other (WillBeRigid) type parameters through equirecursive inference, and so + /// should always be renormalized/canonicalized when used. + InstanceCtorDeclaredTypars: Typars + + /// The value representing the static implicit constructor. + /// Lazy to ensure the static ctor value is only published if needed. + StaticCtorValInfo: Lazy<(Val list * Val * ValScheme)> + + /// The value representing the implicit constructor. + InstanceCtorVal: Val + + /// The type of the implicit constructor, representing as a ValScheme. + InstanceCtorValScheme: ValScheme + + /// The values representing the arguments to the implicit constructor. + InstanceCtorArgs: Val list + + /// The reference cell holding the 'this' parameter within the implicit constructor so it can be referenced in the + /// arguments passed to the base constructor + InstanceCtorSafeThisValOpt: Val option + + /// Data indicating if safe-initialization checks need to be inserted for this type. + InstanceCtorSafeInitInfo: SafeInitData + + /// The value representing the 'base' variable within the implicit instance constructor. + InstanceCtorBaseValOpt: Val option + + /// The value representing the 'this' variable within the implicit instance constructor. + InstanceCtorThisVal: Val + + /// The name generator used to generate the names of fields etc. within the type. + NameGenerator: NiceNameGenerator } + /// Get the type parameters of the implicit constructor, after taking equi-recursive inference into account. member ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv denv m = let ctorDeclaredTypars = ctorInfo.InstanceCtorDeclaredTypars @@ -12534,7 +12546,7 @@ module IncrClassChecking = /// Check and elaborate the "left hand side" of the implicit class construction /// syntax. - let TcImplictCtorLhs_Phase2A(cenv, env, tpenv, tcref:TyconRef, vis, attrs, spats, thisIdOpt, baseValOpt: Val option, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy) = + let TcImplictCtorLhs_Phase2A(cenv, env, tpenv, tcref: TyconRef, vis, attrs, spats, thisIdOpt, baseValOpt: Val option, safeInitInfo, m, copyOfTyconTypars, objTy, thisTy) = let baseValOpt = match GetSuperTypeOfType cenv.g cenv.amap m objTy with @@ -12632,7 +12644,7 @@ module IncrClassChecking = /// The "v" is the local typed w.r.t. tyvars of the implicit ctor. /// The formalTyparInst does the formal-typars/implicit-ctor-typars subst. /// Field specifications added to a tcref must be in terms of the tcrefs formal typars. - let private MakeIncrClassField(g, cpath, formalTyparInst:TyparInst, v:Val, isStatic, rfref:RecdFieldRef) = + let private MakeIncrClassField(g, cpath, formalTyparInst: TyparInst, v: Val, isStatic, rfref: RecdFieldRef) = let name = rfref.FieldName let id = ident (name, v.Range) let ty = v.Type |> instType formalTyparInst @@ -12655,12 +12667,12 @@ module IncrClassChecking = /// type defined with implicit class construction. type IncrClassReprInfo = { /// Indicates the set of field names taken within one incremental class - TakenFieldNames:Set - RepInfoTcGlobals:TcGlobals + TakenFieldNames: Set + RepInfoTcGlobals: TcGlobals /// vals mapped to representations - ValReprs : Zmap + ValReprs: Zmap /// vals represented as fields or members from this point on - ValsWithRepresentation : Zset } + ValsWithRepresentation: Zset } static member Empty(g, names) = { TakenFieldNames=Set.ofList names @@ -12669,12 +12681,12 @@ module IncrClassChecking = ValsWithRepresentation = Zset.empty valOrder } /// Find the representation of a value - member localRep.LookupRepr (v:Val) = + member localRep.LookupRepr (v: Val) = match Zmap.tryFind v localRep.ValReprs with | None -> error(InternalError("LookupRepr: failed to find representation for value", v.Range)) | Some res -> res - static member IsMethodRepr cenv (bind:Binding) = + static member IsMethodRepr cenv (bind: Binding) = let v = bind.Var // unit fields are not stored, just run rhs for effects if isUnitTy cenv.g v.Type then @@ -12686,13 +12698,13 @@ module IncrClassChecking = /// Choose how a binding is represented member localRep.ChooseRepresentation (cenv, env: TcEnv, isStatic, isCtorArg, - ctorInfo:IncrClassCtorLhs, + ctorInfo: IncrClassCtorLhs, /// The vars forced to be fields due to static member bindings, instance initialization expressions or instance member bindings - staticForcedFieldVars:FreeLocals, + staticForcedFieldVars: FreeLocals, /// The vars forced to be fields due to instance member bindings - instanceForcedFieldVars:FreeLocals, + instanceForcedFieldVars: FreeLocals, takenFieldNames: Set, - bind:Binding) = + bind: Binding) = let g = cenv.g let v = bind.Var let relevantForcedFieldVars = (if isStatic then staticForcedFieldVars else instanceForcedFieldVars) @@ -12777,7 +12789,7 @@ module IncrClassChecking = repr, takenFieldNames /// Extend the known local representations by choosing a representation for a binding - member localRep.ChooseAndAddRepresentation(cenv, env: TcEnv, isStatic, isCtorArg, ctorInfo:IncrClassCtorLhs, staticForcedFieldVars:FreeLocals, instanceForcedFieldVars: FreeLocals, bind:Binding) = + member localRep.ChooseAndAddRepresentation(cenv, env: TcEnv, isStatic, isCtorArg, ctorInfo: IncrClassCtorLhs, staticForcedFieldVars: FreeLocals, instanceForcedFieldVars: FreeLocals, bind: Binding) = let v = bind.Var let repr, takenFieldNames = localRep.ChooseRepresentation (cenv, env, isStatic, isCtorArg, ctorInfo, staticForcedFieldVars, instanceForcedFieldVars, localRep.TakenFieldNames, bind ) // OK, representation chosen, now add it @@ -12785,18 +12797,18 @@ module IncrClassChecking = TakenFieldNames=takenFieldNames ValReprs = Zmap.add v repr localRep.ValReprs} - member localRep.ValNowWithRepresentation (v:Val) = + member localRep.ValNowWithRepresentation (v: Val) = {localRep with ValsWithRepresentation = Zset.add v localRep.ValsWithRepresentation} - member localRep.IsValWithRepresentation (v:Val) = + member localRep.IsValWithRepresentation (v: Val) = localRep.ValsWithRepresentation.Contains(v) - member localRep.IsValRepresentedAsLocalVar (v:Val) = + member localRep.IsValRepresentedAsLocalVar (v: Val) = match localRep.LookupRepr v with | InVar false -> true | _ -> false - member localRep.IsValRepresentedAsMethod (v:Val) = + member localRep.IsValRepresentedAsMethod (v: Val) = localRep.IsValWithRepresentation(v) && match localRep.LookupRepr(v) with | InMethod _ -> true @@ -12865,7 +12877,7 @@ module IncrClassChecking = /// Mutate a type definition by adding fields /// Used as part of processing "let" bindings in a type definition. - member localRep.PublishIncrClassFields (cenv, denv, cpath, ctorInfo:IncrClassCtorLhs, safeStaticInitInfo) = + member localRep.PublishIncrClassFields (cenv, denv, cpath, ctorInfo: IncrClassCtorLhs, safeStaticInitInfo) = let tcref = ctorInfo.TyconRef let rfspecs = [ for KeyValue(v, repr) in localRep.ValReprs do @@ -12899,7 +12911,7 @@ module IncrClassChecking = /// Fix up the references to the locals, e.g. /// v -> this.fieldv /// f x -> this.method x - member localRep.FixupIncrClassExprPhase2C cenv thisValOpt safeStaticInitInfo (thisTyInst:TypeInst) expr = + member localRep.FixupIncrClassExprPhase2C cenv thisValOpt safeStaticInitInfo (thisTyInst: TypeInst) expr = // fixup: intercept and expr rewrite let FixupExprNode rw e = //dprintfn "Fixup %s" (showL (exprL e)) @@ -12954,17 +12966,17 @@ module IncrClassChecking = (cenv, env: TcEnv, /// The lhs information about the implicit constructor - ctorInfo:IncrClassCtorLhs, + ctorInfo: IncrClassCtorLhs, /// The call to the super class constructor inheritsExpr, /// Should we place a sequence point at the 'inheritedTys call? inheritsIsVisible, /// The declarations - decs : IncrClassConstructionBindingsPhase2C list, - memberBinds : Binding list, + decs: IncrClassConstructionBindingsPhase2C list, + memberBinds: Binding list, /// Record any unconstrained type parameters generalized for the outer members as "free choices" in the let bindings generalizedTyparsForRecursiveBlock, - safeStaticInitInfo : SafeInitData) = + safeStaticInitInfo: SafeInitData) = let denv = env.DisplayEnv @@ -12985,14 +12997,14 @@ module IncrClassChecking = let accFreeInExpr acc expr = unionFreeVars acc (freeInExpr CollectLocalsNoCaching expr) - let accFreeInBinding acc (bind:Binding) = + let accFreeInBinding acc (bind: Binding) = accFreeInExpr acc bind.Expr - let accFreeInBindings acc (binds:Binding list) = + let accFreeInBindings acc (binds: Binding list) = (acc, binds) ||> List.fold accFreeInBinding // Find all the variables used in any method. These become fields. - // staticForcedFieldVars:FreeLocals: the vars forced to be fields due to static member bindings, instance initialization expressions or instance member bindings + // staticForcedFieldVars: FreeLocals: the vars forced to be fields due to static member bindings, instance initialization expressions or instance member bindings // instanceForcedFieldVars: FreeLocals: the vars forced to be fields due to instance member bindings let staticForcedFieldVars, instanceForcedFieldVars = @@ -13038,7 +13050,7 @@ module IncrClassChecking = // Compute the implicit construction side effects of single // 'let' or 'let rec' binding in the implicit class construction sequence - let TransBind (reps:IncrClassReprInfo) (TBind(v, rhsExpr, spBind)) = + let TransBind (reps: IncrClassReprInfo) (TBind(v, rhsExpr, spBind)) = if v.MustInline then error(Error(FSComp.SR.tcLocalClassBindingsCannotBeInline(), v.Range)) let rhsExpr = reps.FixupIncrClassExprPhase2C cenv (Some thisVal) safeStaticInitInfo thisTyInst rhsExpr @@ -13106,7 +13118,7 @@ module IncrClassChecking = /// Work out the implicit construction side effects of a 'let', 'let rec' or 'do' /// binding in the implicit class construction sequence - let TransTrueDec isCtorArg (reps:IncrClassReprInfo) dec = + let TransTrueDec isCtorArg (reps: IncrClassReprInfo) dec = match dec with | (IncrClassBindingGroup(binds, isStatic, isRec)) -> let actions, reps, methodBinds = @@ -13140,7 +13152,7 @@ module IncrClassChecking = /// Work out the implicit construction side effects of each declaration /// in the implicit class construction sequence - let TransDec (reps:IncrClassReprInfo) dec = + let TransDec (reps: IncrClassReprInfo) dec = match dec with // The call to the base class constructor is done so we can set the ref cell | Phase2CCtorJustAfterSuperInit -> @@ -13358,7 +13370,7 @@ module MutRecBindingChecking = // Phase2A: create member prelimRecValues for "recursive" items, i.e. ctor val and member vals // Phase2A: also processes their arg patterns - collecting type assertions - let TcMutRecBindings_Phase2A_CreateRecursiveValuesAndCheckArgumentPatterns cenv tpenv (envMutRec, mutRecDefns : MutRecDefnsPhase2Info) = + let TcMutRecBindings_Phase2A_CreateRecursiveValuesAndCheckArgumentPatterns cenv tpenv (envMutRec, mutRecDefns: MutRecDefnsPhase2Info) = // The basic iteration over the declarations in a single type definition // State: @@ -13538,7 +13550,7 @@ module MutRecBindingChecking = /// Phase2B: check each of the bindings, convert from ast to tast and collects type assertions. /// Also generalize incrementally. - let TcMutRecBindings_Phase2B_TypeCheckAndIncrementalGeneralization cenv tpenv envInitial (envMutRec, defnsAs:MutRecDefnsPhase2AData, uncheckedRecBinds: PreCheckingRecursiveBinding list, scopem) : MutRecDefnsPhase2BData * _ * _ = + let TcMutRecBindings_Phase2B_TypeCheckAndIncrementalGeneralization cenv tpenv envInitial (envMutRec, defnsAs: MutRecDefnsPhase2AData, uncheckedRecBinds: PreCheckingRecursiveBinding list, scopem) : MutRecDefnsPhase2BData * _ * _ = let (defnsBs: MutRecDefnsPhase2BData), (tpenv, generalizedRecBinds, preGeneralizationRecBinds, _, _) = @@ -13551,7 +13563,7 @@ module MutRecBindingChecking = // consider // // type A<'T>() = - // let someFuncValue : 'A = A<'T>.Meth2() + // let someFuncValue: 'A = A<'T>.Meth2() // static member Meth2() = A<'T>.Meth2() // and B<'T>() = // static member Meth1() = A<'T>.Meth2() @@ -13812,7 +13824,7 @@ module MutRecBindingChecking = // there are some minor concerns about performance w.r.t. these static bindings: // // set.fs (also map.fs) - // static let empty : Set<'T> = + // static let empty: Set<'T> = // let comparer = LanguagePrimitives.FastGenericComparer<'T> // new Set<'T>(comparer, SetEmpty) // @@ -13935,7 +13947,7 @@ module MutRecBindingChecking = tyconOpt, memberBindsWithFixups, []) /// Check a "module X = A.B.C" module abbreviation declaration - let TcModuleAbbrevDecl (cenv:cenv) scopem env (id, p, m) = + let TcModuleAbbrevDecl (cenv: cenv) scopem env (id, p, m) = let ad = env.eAccessRights let resolved = match p with @@ -13978,7 +13990,7 @@ module MutRecBindingChecking = let moduleAbbrevs = decls |> List.choose (function MutRecShape.ModuleAbbrev (MutRecDataForModuleAbbrev (id, mp, m)) -> Some (id, mp, m) | _ -> None) let opens = decls |> List.choose (function MutRecShape.Open (MutRecDataForOpen (mp, m)) -> Some (mp, m) | _ -> None) let lets = decls |> List.collect (function MutRecShape.Lets binds -> getVals binds | _ -> []) - let exns = tycons |> List.filter (fun (tycon:Tycon) -> tycon.IsExceptionDecl) + let exns = tycons |> List.filter (fun (tycon: Tycon) -> tycon.IsExceptionDecl) // Add the type definitions, exceptions, modules and "open" declarations. // The order here is sensitive. The things added first will be resolved in an environment @@ -14111,7 +14123,7 @@ module MutRecBindingChecking = let unsolvedTypars = freeInTypesLeftToRight g true allTypes //printfn "unsolvedTypars.Length = %d" unsolvedTypars.Length //for x in unsolvedTypars do - // printfn "unsolvedTypar : %s #%d" x.DisplayName x.Stamp + // printfn "unsolvedTypar: %s #%d" x.DisplayName x.Stamp let unsolvedTyparsInvolvingGeneralizedVariables = unsolvedTypars |> List.filter (fun tp -> let freeInTypar = (freeInType CollectAllNoCaching (mkTyparTy tp)).FreeTypars @@ -14121,11 +14133,11 @@ module MutRecBindingChecking = freeInTypar.Exists(fun otherTypar -> genSet.Contains otherTypar)) //printfn "unsolvedTyparsInvolvingGeneralizedVariables.Length = %d" unsolvedTyparsInvolvingGeneralizedVariables.Length //for x in unsolvedTypars do - // printfn "unsolvedTyparsInvolvingGeneralizedVariable : %s #%d" x.DisplayName x.Stamp + // printfn "unsolvedTyparsInvolvingGeneralizedVariable: %s #%d" x.DisplayName x.Stamp unsolvedTyparsInvolvingGeneralizedVariables for tp in unsolvedTyparsForRecursiveBlockInvolvingGeneralizedVariables do - //printfn "solving unsolvedTyparsInvolvingGeneralizedVariable : %s #%d" tp.DisplayName tp.Stamp + //printfn "solving unsolvedTyparsInvolvingGeneralizedVariable: %s #%d" tp.DisplayName tp.Stamp if (tp.Rigidity <> TyparRigidity.Rigid) && not tp.IsSolved then ConstraintSolver.ChooseTyparSolutionAndSolve cenv.css denv tp @@ -14236,7 +14248,7 @@ let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: | _ -> error(Error(FSComp.SR.tcDeclarationElementNotPermittedInAugmentation(), mem.Range)))) - let binds : MutRecDefnsPhase2Info = + let binds: MutRecDefnsPhase2Info = (envMutRec, mutRecDefns) ||> MutRecShapes.mapTyconsWithEnv (fun envForDecls tyconData -> let (MutRecDefnsPhase2DataForTycon(tyconOpt, _, declKind, tcref, _, _, declaredTyconTypars, _, _, _, fixupFinalAttrs)) = tyconData let obinds = tyconBindingsOfTypeDefn tyconData @@ -14261,7 +14273,7 @@ module AddAugmentationDeclarations = | ValueSome tcref2 when tyconRefEq g tcref2 tcref -> true | _ -> false) - let AddGenericCompareDeclarations cenv (env: TcEnv) (scSet:Set) (tycon:Tycon) = + let AddGenericCompareDeclarations cenv (env: TcEnv) (scSet: Set) (tycon: Tycon) = if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithCompare cenv.g tycon && scSet.Contains tycon.Stamp then let tcref = mkLocalTyconRef tycon let tcaug = tycon.TypeContents @@ -14298,7 +14310,7 @@ module AddAugmentationDeclarations = - let AddGenericEqualityWithComparerDeclarations cenv (env: TcEnv) (seSet:Set) (tycon:Tycon) = + let AddGenericEqualityWithComparerDeclarations cenv (env: TcEnv) (seSet: Set) (tycon: Tycon) = if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithEquals cenv.g tycon && seSet.Contains tycon.Stamp then let tcref = mkLocalTyconRef tycon let tcaug = tycon.TypeContents @@ -14317,19 +14329,19 @@ module AddAugmentationDeclarations = PublishValueDefn cenv env ModuleOrMemberBinding evspec3 - let AddGenericCompareBindings cenv (tycon:Tycon) = + let AddGenericCompareBindings cenv (tycon: Tycon) = if (* AugmentWithHashCompare.TyconIsCandidateForAugmentationWithCompare cenv.g tycon && *) Option.isSome tycon.GeneratedCompareToValues then AugmentWithHashCompare.MakeBindingsForCompareAugmentation cenv.g tycon else [] - let AddGenericCompareWithComparerBindings cenv (tycon:Tycon) = + let AddGenericCompareWithComparerBindings cenv (tycon: Tycon) = if (* AugmentWithHashCompare.TyconIsCandidateForAugmentationWithCompare cenv.g tycon && *) Option.isSome tycon.GeneratedCompareToWithComparerValues then (AugmentWithHashCompare.MakeBindingsForCompareWithComparerAugmentation cenv.g tycon) else [] - let AddGenericEqualityWithComparerBindings cenv (tycon:Tycon) = + let AddGenericEqualityWithComparerBindings cenv (tycon: Tycon) = if AugmentWithHashCompare.TyconIsCandidateForAugmentationWithEquals cenv.g tycon && Option.isSome tycon.GeneratedHashAndEqualsWithComparerValues then (AugmentWithHashCompare.MakeBindingsForEqualityWithComparerAugmentation cenv.g tycon) else @@ -14384,7 +14396,7 @@ module TyconConstraintInference = let InferSetOfTyconsSupportingComparable cenv (denv: DisplayEnv) tyconsWithStructuralTypes = let g = cenv.g - let tab = tyconsWithStructuralTypes |> List.map (fun (tycon:Tycon, structuralTypes) -> tycon.Stamp, (tycon, structuralTypes)) |> Map.ofList + let tab = tyconsWithStructuralTypes |> List.map (fun (tycon: Tycon, structuralTypes) -> tycon.Stamp, (tycon, structuralTypes)) |> Map.ofList // Initially, assume the equality relation is available for all structural type definitions let initialAssumedTycons = @@ -14397,7 +14409,7 @@ module TyconConstraintInference = // Repeatedly eliminate structural type definitions whose structural component types no longer support // comparison. On the way record type variables which are support the comparison relation. - let rec loop (assumedTycons : Set) (assumedTypars: Set) = + let rec loop (assumedTycons: Set) (assumedTypars: Set) = let assumedTyparsAcc = ref assumedTypars // Checks if a field type supports the 'comparison' constraint based on the assumptions about the type constructors @@ -14528,12 +14540,12 @@ module TyconConstraintInference = // Repeatedly eliminate structural type definitions whose structural component types no longer support // equality. On the way add type variables which are support the equality relation - let rec loop (assumedTycons : Set) (assumedTypars: Set) = + let rec loop (assumedTycons: Set) (assumedTypars: Set) = let assumedTyparsAcc = ref assumedTypars // Checks if a field type supports the 'equality' constraint based on the assumptions about the type constructors // and type parameters. - let rec checkIfFieldTypeSupportsEquality (tycon:Tycon) (ty: TType) = + let rec checkIfFieldTypeSupportsEquality (tycon: Tycon) (ty: TType) = match tryDestTyparTy cenv.g ty with | ValueSome tp -> // Look for an explicit 'equality' constraint @@ -14782,7 +14794,7 @@ module TcExceptionDeclarations = module EstablishTypeDefinitionCores = /// Compute the mangled name of a type definition. 'doErase' is true for all type definitions except type abbreviations. - let private ComputeTyconName (longPath: Ident list, doErase:bool, typars: Typars) = + let private ComputeTyconName (longPath: Ident list, doErase: bool, typars: Typars) = if longPath.Length <> 1 then error(Error(FSComp.SR.tcInvalidTypeExtension(), longPath.Head.idRange)) let id = longPath.Head let erasedArity = @@ -14826,7 +14838,7 @@ module EstablishTypeDefinitionCores = k - let private (|TyconCoreAbbrevThatIsReallyAUnion|_|) (hasMeasureAttr, envinner, id:Ident) synTyconRepr = + let private (|TyconCoreAbbrevThatIsReallyAUnion|_|) (hasMeasureAttr, envinner, id: Ident) synTyconRepr = match synTyconRepr with | SynTypeDefnSimpleRepr.TypeAbbrev(_, SynType.LongIdent(LongIdentWithDots([unionCaseName], _)), m) when @@ -14971,7 +14983,7 @@ module EstablishTypeDefinitionCores = // Establish the visibility of the representation, e.g. // type R = - // private { f:int } + // private { f: int } // member x.P = x.f + x.f let synVisOfRepr = match synTyconRepr with @@ -15002,7 +15014,7 @@ module EstablishTypeDefinitionCores = /// /// synTyconInfo: Syntactic AST for the name, attributes etc. of the type constructor /// synTyconRepr: Syntactic AST for the RHS of the type definition - let private TcTyconDefnCore_Phase1B_EstablishBasicKind cenv inSig envinner (MutRecDefnsPhase1DataForTycon(synTyconInfo, synTyconRepr, _, _, _, _)) (tycon:Tycon) = + let private TcTyconDefnCore_Phase1B_EstablishBasicKind cenv inSig envinner (MutRecDefnsPhase1DataForTycon(synTyconInfo, synTyconRepr, _, _, _, _)) (tycon: Tycon) = let (ComponentInfo(synAttrs, typars, _, _, _, _, _, _)) = synTyconInfo let m = tycon.Range let id = tycon.Id @@ -15108,7 +15120,7 @@ module EstablishTypeDefinitionCores = | _ -> None /// Check whether 'type X = ABC<...>' is a generative provided type definition - let private TcTyconDefnCore_TryAsGenerateDeclaration cenv envinner tpenv (tycon:Tycon, rhsType) = + let private TcTyconDefnCore_TryAsGenerateDeclaration cenv envinner tpenv (tycon: Tycon, rhsType) = let tcref = mkLocalTyconRef tycon match TcTyconDefnCore_GetGenerateDeclaration_Rhs rhsType with @@ -15141,7 +15153,7 @@ module EstablishTypeDefinitionCores = /// Check and establish a 'type X = ABC<...>' provided type definition - let private TcTyconDefnCore_Phase1C_EstablishDeclarationForGeneratedSetOfTypes cenv inSig (tycon:Tycon, rhsType:SynType, tcrefForContainer:TyconRef, theRootType:Tainted, checkTypeName, args, m) = + let private TcTyconDefnCore_Phase1C_EstablishDeclarationForGeneratedSetOfTypes cenv inSig (tycon: Tycon, rhsType: SynType, tcrefForContainer: TyconRef, theRootType: Tainted, checkTypeName, args, m) = // Explanation: We are definitely on the compilation thread here, we just have not propagated the token this far. let ctok = AssumeCompilationThreadWithoutEvidence() @@ -15277,7 +15289,7 @@ module EstablishTypeDefinitionCores = /// Establish any type abbreviations /// /// e.g. for - /// type B<'a when 'a : C> = DDD of C + /// type B<'a when 'a: C> = DDD of C /// and C = B /// /// we establish @@ -15298,7 +15310,7 @@ module EstablishTypeDefinitionCores = // such as 'isRefTupleTy' will return reliable results, e.g. isRefTupleTy on the /// TAST type for 'PairOfInts' will report 'true' // - let private TcTyconDefnCore_Phase1C_Phase1E_EstablishAbbreviations cenv envinner inSig tpenv pass (MutRecDefnsPhase1DataForTycon(_, synTyconRepr, _, _, _, _)) (tycon:Tycon) (attrs:Attribs) = + let private TcTyconDefnCore_Phase1C_Phase1E_EstablishAbbreviations cenv envinner inSig tpenv pass (MutRecDefnsPhase1DataForTycon(_, synTyconRepr, _, _, _, _)) (tycon: Tycon) (attrs: Attribs) = let m = tycon.Range let checkCxs = if (pass = SecondPass) then CheckCxs else NoCheckCxs let firstPass = (pass = FirstPass) @@ -15358,7 +15370,7 @@ module EstablishTypeDefinitionCores = // Third phase: check and publish the supr types. Run twice, once before constraints are established // and once after - let private TcTyconDefnCore_Phase1D_Phase1F_EstablishSuperTypesAndInterfaceTypes cenv tpenv inSig pass (envMutRec, mutRecDefns:MutRecShape<(_ * (Tycon * (Attribs * _)) option), _, _, _, _> list) = + let private TcTyconDefnCore_Phase1D_Phase1F_EstablishSuperTypesAndInterfaceTypes cenv tpenv inSig pass (envMutRec, mutRecDefns: MutRecShape<(_ * (Tycon * (Attribs * _)) option), _, _, _, _> list) = let checkCxs = if (pass = SecondPass) then CheckCxs else NoCheckCxs let firstPass = (pass = FirstPass) @@ -15467,7 +15479,7 @@ module EstablishTypeDefinitionCores = with e -> errorRecovery e m)) /// Establish the fields, dispatch slots and union cases of a type - let private TcTyconDefnCore_Phase1G_EstablishRepresentation cenv envinner tpenv inSig (MutRecDefnsPhase1DataForTycon(_, synTyconRepr, _, _, _, _)) (tycon:Tycon) (attrs:Attribs) = + let private TcTyconDefnCore_Phase1G_EstablishRepresentation cenv envinner tpenv inSig (MutRecDefnsPhase1DataForTycon(_, synTyconRepr, _, _, _, _)) (tycon: Tycon) (attrs: Attribs) = let m = tycon.Range try let id = tycon.Id @@ -15538,7 +15550,7 @@ module EstablishTypeDefinitionCores = let noSealedAttributeCheck(k) = if hasSealedAttr = Some(true) then errorR (Error(k(), m)) - let noFieldsCheck(fields':RecdField list) = + let noFieldsCheck(fields': RecdField list) = match fields' with | (rf :: _) -> errorR (Error(FSComp.SR.tcInterfaceTypesAndDelegatesCannotContainFields(), rf.Range)) | _ -> () @@ -15550,7 +15562,7 @@ module EstablishTypeDefinitionCores = // Notify the Language Service about field names in record/class declaration let ad = envinner.eAccessRights - let writeFakeRecordFieldsToSink (fields:RecdField list) = + let writeFakeRecordFieldsToSink (fields: RecdField list) = let nenv = envinner.NameEnv // Record fields should be visible from IntelliSense, so add fake names for them (similarly to "let a = ..") for fspec in fields do @@ -15769,7 +15781,7 @@ module EstablishTypeDefinitionCores = let slots = fst (TcAndPublishValSpec (cenv, envinner, containerInfo, ModuleOrMemberBinding, Some memberFlags, tpenv, valSpfn)) // Multiple slots may be returned, e.g. for - // abstract P : int with get, set + // abstract P: int with get, set for slot in slots do yield mkLocalValRef slot ] @@ -15826,7 +15838,7 @@ module EstablishTypeDefinitionCores = /// Check that a set of type definitions is free of cycles in abbreviations let private TcTyconDefnCore_CheckForCyclicAbbreviations tycons = - let edgesFrom (tycon:Tycon) = + let edgesFrom (tycon: Tycon) = let rec accInAbbrevType ty acc = match stripTyparEqns ty with @@ -15902,15 +15914,15 @@ module EstablishTypeDefinitionCores = // // BEGIN: EARLIER COMMENT // Of course structs are not allowed to contain instance fields of their own type: - // type S = struct { field x : S } + // type S = struct { field x: S } // // In addition, see bug 3429. In the .NET IL structs are allowed to contain // static fields of their exact generic type, e.g. - // type S = struct { static field x : S } - // type S = struct { static field x : S } + // type S = struct { static field x: S } + // type S = struct { static field x: S } // but not - // type S = struct { static field x : S } - // type S = struct { static field x : S } + // type S = struct { static field x: S } + // type S = struct { static field x: S } // etc. // // Ideally structs would allow static fields of any type. However @@ -15919,7 +15931,7 @@ module EstablishTypeDefinitionCores = // END: EARLIER COMMENT // edgesFrom tycon collects (tycon, tycon2) edges, for edges as described above. - let edgesFrom (tycon:Tycon) = + let edgesFrom (tycon: Tycon) = // Record edge (tycon, tycon2), only when tycon2 is an "initial" tycon. let insertEdgeToTycon tycon2 acc = if ListSet.contains (===) tycon2 tycons && // note: only add if tycon2 is initial @@ -15935,7 +15947,7 @@ module EstablishTypeDefinitionCores = acc // collect edges from an a struct field (which is struct-contained in tycon) - let rec accStructField (structTycon:Tycon) structTyInst (fspec:RecdField) (doneTypes, acc) = + let rec accStructField (structTycon: Tycon) structTyInst (fspec: RecdField) (doneTypes, acc) = let fieldTy = actualTyOfRecdFieldForTycon structTycon structTyInst fspec accStructFieldType structTycon structTyInst fspec fieldTy (doneTypes, acc) @@ -15970,7 +15982,7 @@ module EstablishTypeDefinitionCores = doneTypes, acc // collect edges from the fields of a given struct type. - and accStructFields includeStaticFields ty (structTycon:Tycon) tinst (doneTypes, acc) = + and accStructFields includeStaticFields ty (structTycon: Tycon) tinst (doneTypes, acc) = if List.exists (typeEquiv cenv.g ty) doneTypes then // This type (type instance) has been seen before, so no need to collect the same edges again (and avoid loops!) doneTypes, acc @@ -16021,7 +16033,7 @@ module EstablishTypeDefinitionCores = let TcMutRecDefns_CheckExplicitConstraints cenv tpenv m checkCxs envMutRecPrelim withEnvs = (envMutRecPrelim, withEnvs) ||> MutRecShapes.iterTyconsWithEnv (fun envForDecls (origInfo, tyconOpt) -> match origInfo, tyconOpt with - | (typeDefCore, _, _), Some (tycon:Tycon) -> + | (typeDefCore, _, _), Some (tycon: Tycon) -> let (MutRecDefnsPhase1DataForTycon(synTyconInfo, _, _, _, _, _)) = typeDefCore let (ComponentInfo(_, _, synTyconConstraints, _, _, _, _, _)) = synTyconInfo let envForTycon = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars(m)) envForDecls @@ -16032,7 +16044,7 @@ module EstablishTypeDefinitionCores = | _ -> ()) - let TcMutRecDefns_Phase1 mkLetInfo cenv envInitial parent typeNames inSig tpenv m scopem mutRecNSInfo (mutRecDefns:MutRecShapes) = + let TcMutRecDefns_Phase1 mkLetInfo cenv envInitial parent typeNames inSig tpenv m scopem mutRecNSInfo (mutRecDefns: MutRecShapes) = // Phase1A - build Entity for type definitions, exception definitions and module definitions. // Also for abbreviations of any of these. Augmentations are skipped in this phase. @@ -16190,7 +16202,7 @@ module TcDeclarations = /// Given a type definition, compute whether its members form an extension of an existing type, and if so if it is an /// intrinsic or extrinsic extension - let private ComputeTyconDeclKind tyconOpt isAtOriginalTyconDefn cenv envForDecls inSig m (synTypars:SynTyparDecl list) synTyparCxs longPath = + let private ComputeTyconDeclKind tyconOpt isAtOriginalTyconDefn cenv envForDecls inSig m (synTypars: SynTyparDecl list) synTyparCxs longPath = let ad = envForDecls.eAccessRights let tcref = @@ -16660,7 +16672,7 @@ module TcDeclarations = /// Bind a collection of mutually recursive declarations in a signature file - let TcMutRecSignatureDecls cenv envInitial parent typeNames tpenv m scopem mutRecNSInfo (mutRecSigs:MutRecSigsInitialData) = + let TcMutRecSignatureDecls cenv envInitial parent typeNames tpenv m scopem mutRecNSInfo (mutRecSigs: MutRecSigsInitialData) = let mutRecSigsAfterSplit = mutRecSigs |> MutRecShapes.mapTycons SplitTyconSignature let _tycons, envMutRec, mutRecDefnsAfterCore = EstablishTypeDefinitionCores.TcMutRecDefns_Phase1 (fun containerInfo valDecl -> (containerInfo, valDecl)) cenv envInitial parent typeNames true tpenv m scopem mutRecNSInfo mutRecSigsAfterSplit @@ -16693,7 +16705,7 @@ module TcDeclarations = // Bind module types //------------------------------------------------------------------------- -let rec TcSignatureElementNonMutRec cenv parent typeNames endm (env: TcEnv) synSigDecl : Eventually = +let rec TcSignatureElementNonMutRec cenv parent typeNames endm (env: TcEnv) synSigDecl: Eventually = eventually { try match synSigDecl with @@ -16868,7 +16880,7 @@ and TcSignatureElementsMutRec cenv parent typeNames endm mutRecNSInfo envInitial let scopem = (defs, endm) ||> List.foldBack (fun h m -> unionRanges h.Range m) let mutRecDefns = - let rec loop isNamespace defs : MutRecSigsInitialData = + let rec loop isNamespace defs: MutRecSigsInitialData = ((true, true), defs) ||> List.collectFold (fun (openOk, moduleAbbrevOk) def -> match def with | SynModuleSigDecl.Types (typeSpecs, _) -> @@ -16915,7 +16927,7 @@ and TcSignatureElementsMutRec cenv parent typeNames endm mutRecNSInfo envInitial -and TcModuleOrNamespaceSignatureElementsNonMutRec cenv parent env (id, modKind, defs, m:range, xml) = +and TcModuleOrNamespaceSignatureElementsNonMutRec cenv parent env (id, modKind, defs, m: range, xml) = eventually { let endm = m.EndRange // use end of range for errors @@ -16963,7 +16975,7 @@ let TcMutRecDefnsEscapeCheck (binds: MutRecShapes<_, _, _, _, _>) env = // ignore solitary '()' expressions and 'do ()' bindings, since these are allowed in namespaces // for the purposes of attaching attributes to an assembly, e.g. // namespace A.B.C -// [] +// [] // do() let CheckLetOrDoInNamespace binds m = @@ -16976,7 +16988,7 @@ let CheckLetOrDoInNamespace binds m = error(NumberedError(FSComp.SR.tcNamespaceCannotContainValues(), binds.Head.RangeOfHeadPat)) /// The non-mutually recursive case for a declaration -let rec TcModuleOrNamespaceElementNonMutRec (cenv:cenv) parent typeNames scopem env synDecl = +let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem env synDecl = eventually { cenv.synArgNameGenerator.Reset() let tpenv = emptyUnscopedTyparEnv @@ -17182,7 +17194,7 @@ and TcModuleOrNamespaceElementsMutRec cenv parent typeNames endm envInitial mutR let scopem = (defs, endm) ||> List.foldBack (fun h m -> unionRanges h.Range m) let (mutRecDefns, (_, _, synAttrs)) = - let rec loop isNamespace attrs defs : (MutRecDefnsInitialData * _) = + let rec loop isNamespace attrs defs: (MutRecDefnsInitialData * _) = ((true, true, attrs), defs) ||> List.collectFold (fun (openOk, moduleAbbrevOk, attrs) def -> match ElimModuleDoBinding def with @@ -17348,7 +17360,7 @@ type ConditionalDefines = type TopAttribs = { mainMethodAttrs: Attribs netModuleAttrs: Attribs - assemblyAttrs : Attribs } + assemblyAttrs: Attribs } let EmptyTopAttrs = { mainMethodAttrs=[] @@ -17360,7 +17372,7 @@ let CombineTopAttrs topAttrs1 topAttrs2 = netModuleAttrs = topAttrs1.netModuleAttrs @ topAttrs2.netModuleAttrs assemblyAttrs = topAttrs1.assemblyAttrs @ topAttrs2.assemblyAttrs } -let rec IterTyconsOfModuleOrNamespaceType f (mty:ModuleOrNamespaceType) = +let rec IterTyconsOfModuleOrNamespaceType f (mty: ModuleOrNamespaceType) = mty.AllEntities |> QueueList.iter (fun tycon -> f tycon) mty.ModuleAndNamespaceDefinitions |> List.iter (fun v -> IterTyconsOfModuleOrNamespaceType f v.ModuleOrNamespaceType) @@ -17403,7 +17415,7 @@ let ApplyDefaults cenv g denvAtEnd m mexpr extraAttribs = let CheckValueRestriction denvAtEnd rootSigOpt implFileTypePriorToSig m = if Option.isNone rootSigOpt then - let rec check (mty:ModuleOrNamespaceType) = + let rec check (mty: ModuleOrNamespaceType) = for v in mty.AllValsAndMembers do let ftyvs = (freeInVal CollectTyparsNoCaching v).FreeTypars |> Zset.elements if (not v.IsCompilerGenerated && @@ -17470,7 +17482,7 @@ let TypeCheckOneImplFile // checkForErrors: A function to help us stop reporting cascading errors (g, niceNameGen, amap, topCcu, checkForErrors, conditionalDefines, tcSink, isInternalTestSpanStackReferring) env - (rootSigOpt : ModuleOrNamespaceType option) + (rootSigOpt: ModuleOrNamespaceType option) (ParsedImplFileInput(_, isScript, qualNameOfFile, scopedPragmas, _, implFileFrags, isLastCompiland)) = eventually { diff --git a/src/fsharp/TypeRelations.fs b/src/fsharp/TypeRelations.fs index 5b633acb50d..2d07a2b4177 100755 --- a/src/fsharp/TypeRelations.fs +++ b/src/fsharp/TypeRelations.fs @@ -13,11 +13,7 @@ open FSharp.Compiler.TcGlobals open FSharp.Compiler.Infos open FSharp.Compiler.PrettyNaming -//------------------------------------------------------------------------- -// a :> b without coercion based on finalized (no type variable) types -//------------------------------------------------------------------------- - - +/// Implements a :> b without coercion based on finalized (no type variable) types // QUERY: This relation is approximate and not part of the language specification. // // Some appropriate uses: @@ -34,15 +30,15 @@ let rec TypeDefinitelySubsumesTypeNoCoercion ndeep g amap m ty1 ty2 = else let ty1 = stripTyEqns g ty1 let ty2 = stripTyEqns g ty2 - match ty1,ty2 with - | TType_app (tc1,l1) ,TType_app (tc2,l2) when tyconRefEq g tc1 tc2 -> + match ty1, ty2 with + | TType_app (tc1, l1) , TType_app (tc2, l2) when tyconRefEq g tc1 tc2 -> List.lengthsEqAndForall2 (typeEquiv g) l1 l2 - | TType_ucase (tc1,l1) ,TType_ucase (tc2,l2) when g.unionCaseRefEq tc1 tc2 -> + | TType_ucase (tc1, l1) , TType_ucase (tc2, l2) when g.unionCaseRefEq tc1 tc2 -> List.lengthsEqAndForall2 (typeEquiv g) l1 l2 - | TType_tuple (tupInfo1,l1) ,TType_tuple (tupInfo2,l2) -> + | TType_tuple (tupInfo1, l1) , TType_tuple (tupInfo2, l2) -> evalTupInfoIsStruct tupInfo1 = evalTupInfoIsStruct tupInfo2 && List.lengthsEqAndForall2 (typeEquiv g) l1 l2 - | TType_fun (d1,r1) ,TType_fun (d2,r2) -> + | TType_fun (d1, r1) , TType_fun (d2, r2) -> typeEquiv g d1 d2 && typeEquiv g r1 r2 | TType_measure measure1, TType_measure measure2 -> measureEquiv g measure1 measure2 @@ -69,16 +65,16 @@ let rec TypesFeasiblyEquiv ndeep g amap m ty1 ty2 = if ndeep > 100 then error(InternalError("recursive class hierarchy (detected in TypeFeasiblySubsumesType), ty1 = " + (DebugPrint.showType ty1), m)); let ty1 = stripTyEqns g ty1 let ty2 = stripTyEqns g ty2 - match ty1,ty2 with + match ty1, ty2 with // QUERY: should these be false for non-equal rigid typars? warn-if-not-rigid typars? | TType_var _ , _ | _, TType_var _ -> true - | TType_app (tc1,l1) ,TType_app (tc2,l2) when tyconRefEq g tc1 tc2 -> + | TType_app (tc1, l1) , TType_app (tc2, l2) when tyconRefEq g tc1 tc2 -> List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 - | TType_tuple (tupInfo1, l1) ,TType_tuple (tupInfo2, l2) -> + | TType_tuple (tupInfo1, l1) , TType_tuple (tupInfo2, l2) -> evalTupInfoIsStruct tupInfo1 = evalTupInfoIsStruct tupInfo2 && List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 - | TType_fun (d1,r1) ,TType_fun (d2,r2) -> + | TType_fun (d1, r1) , TType_fun (d2, r2) -> (TypesFeasiblyEquiv ndeep g amap m) d1 d2 && (TypesFeasiblyEquiv ndeep g amap m) r1 r2 | TType_measure _, TType_measure _ -> true @@ -91,16 +87,16 @@ let rec TypeFeasiblySubsumesType ndeep g amap m ty1 canCoerce ty2 = if ndeep > 100 then error(InternalError("recursive class hierarchy (detected in TypeFeasiblySubsumesType), ty1 = " + (DebugPrint.showType ty1), m)) let ty1 = stripTyEqns g ty1 let ty2 = stripTyEqns g ty2 - match ty1,ty2 with + match ty1, ty2 with // QUERY: should these be false for non-equal rigid typars? warn-if-not-rigid typars? | TType_var _ , _ | _, TType_var _ -> true - | TType_app (tc1,l1) ,TType_app (tc2,l2) when tyconRefEq g tc1 tc2 -> + | TType_app (tc1, l1) , TType_app (tc2, l2) when tyconRefEq g tc1 tc2 -> List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 - | TType_tuple (tupInfo1,l1) ,TType_tuple (tupInfo2,l2) -> + | TType_tuple (tupInfo1, l1) , TType_tuple (tupInfo2, l2) -> evalTupInfoIsStruct tupInfo1 = evalTupInfoIsStruct tupInfo2 && List.lengthsEqAndForall2 (TypesFeasiblyEquiv ndeep g amap m) l1 l2 - | TType_fun (d1,r1) ,TType_fun (d2,r2) -> + | TType_fun (d1, r1) , TType_fun (d2, r2) -> (TypesFeasiblyEquiv ndeep g amap m) d1 d2 && (TypesFeasiblyEquiv ndeep g amap m) r1 r2 | TType_measure _, TType_measure _ -> true @@ -121,60 +117,60 @@ let rec TypeFeasiblySubsumesType ndeep g amap m ty1 canCoerce ty2 = /// Choose solutions for Expr.TyChoose type "hidden" variables introduced /// by letrec nodes. Also used by the pattern match compiler to choose type /// variables when compiling patterns at generalized bindings. -/// e.g. let ([],x) = ([],[]) +/// e.g. let ([], x) = ([], []) /// Here x gets a generalized type "list<'T>". let ChooseTyparSolutionAndRange (g: TcGlobals) amap (tp:Typar) = let m = tp.Range - let max,m = + let max, m = let initial = match tp.Kind with | TyparKind.Type -> g.obj_ty | TyparKind.Measure -> TType_measure Measure.One // Loop through the constraints computing the lub - ((initial,m), tp.Constraints) ||> List.fold (fun (maxSoFar,_) tpc -> + ((initial, m), tp.Constraints) ||> List.fold (fun (maxSoFar, _) tpc -> let join m x = if TypeFeasiblySubsumesType 0 g amap m x CanCoerce maxSoFar then maxSoFar elif TypeFeasiblySubsumesType 0 g amap m maxSoFar CanCoerce x then x - else errorR(Error(FSComp.SR.typrelCannotResolveImplicitGenericInstantiation((DebugPrint.showType x), (DebugPrint.showType maxSoFar)),m)); maxSoFar + else errorR(Error(FSComp.SR.typrelCannotResolveImplicitGenericInstantiation((DebugPrint.showType x), (DebugPrint.showType maxSoFar)), m)); maxSoFar // Don't continue if an error occurred and we set the value eagerly - if tp.IsSolved then maxSoFar,m else + if tp.IsSolved then maxSoFar, m else match tpc with - | TyparConstraint.CoercesTo(x,m) -> - join m x,m - | TyparConstraint.MayResolveMember(TTrait(_,_,_,_,_,_),m) -> - maxSoFar,m - | TyparConstraint.SimpleChoice(_,m) -> - errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInPrintf(),m)) - maxSoFar,m + | TyparConstraint.CoercesTo(x, m) -> + join m x, m + | TyparConstraint.MayResolveMember(TTrait(_, _, _, _, _, _), m) -> + maxSoFar, m + | TyparConstraint.SimpleChoice(_, m) -> + errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInPrintf(), m)) + maxSoFar, m | TyparConstraint.SupportsNull m -> - maxSoFar,m + maxSoFar, m | TyparConstraint.SupportsComparison m -> - join m g.mk_IComparable_ty,m + join m g.mk_IComparable_ty, m | TyparConstraint.SupportsEquality m -> - maxSoFar,m - | TyparConstraint.IsEnum(_,m) -> - errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInEnum(),m)) - maxSoFar,m - | TyparConstraint.IsDelegate(_,_,m) -> - errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInDelegate(),m)) - maxSoFar,m + maxSoFar, m + | TyparConstraint.IsEnum(_, m) -> + errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInEnum(), m)) + maxSoFar, m + | TyparConstraint.IsDelegate(_, _, m) -> + errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInDelegate(), m)) + maxSoFar, m | TyparConstraint.IsNonNullableStruct m -> - join m g.int_ty,m + join m g.int_ty, m | TyparConstraint.IsUnmanaged m -> - errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInUnmanaged(),m)) - maxSoFar,m + errorR(Error(FSComp.SR.typrelCannotResolveAmbiguityInUnmanaged(), m)) + maxSoFar, m | TyparConstraint.RequiresDefaultConstructor m -> - maxSoFar,m + maxSoFar, m | TyparConstraint.IsReferenceType m -> - maxSoFar,m - | TyparConstraint.DefaultsTo(_priority,_ty,m) -> - maxSoFar,m) - max,m + maxSoFar, m + | TyparConstraint.DefaultsTo(_priority, _ty, m) -> + maxSoFar, m) + max, m let ChooseTyparSolution g amap tp = - let ty,_m = ChooseTyparSolutionAndRange g amap tp + let ty, _m = ChooseTyparSolutionAndRange g amap tp if tp.Rigidity = TyparRigidity.Anon && typeEquiv g ty (TType_measure Measure.One) then - warning(Error(FSComp.SR.csCodeLessGeneric(),tp.Range)) + warning(Error(FSComp.SR.csCodeLessGeneric(), tp.Range)) ty // Solutions can, in theory, refer to each other @@ -205,7 +201,7 @@ let IterativelySubstituteTyparSolutions g tps solutions = let ChooseTyparSolutionsForFreeChoiceTypars g amap e = match e with - | Expr.TyChoose(tps,e1,_m) -> + | Expr.TyChoose(tps, e1, _m) -> /// Only make choices for variables that are actually used in the expression let ftvs = (freeInExpr CollectTyparsNoCaching e1).FreeTyvars.FreeTypars @@ -222,44 +218,44 @@ let ChooseTyparSolutionsForFreeChoiceTypars g amap e = /// Break apart lambdas. Needs ChooseTyparSolutionsForFreeChoiceTypars because it's used in /// PostTypeCheckSemanticChecks before we've eliminated these nodes. -let tryDestTopLambda g amap (ValReprInfo (tpNames,_,_) as tvd) (e,ty) = - let rec stripLambdaUpto n (e,ty) = +let tryDestTopLambda g amap (ValReprInfo (tpNames, _, _) as tvd) (e, ty) = + let rec stripLambdaUpto n (e, ty) = match e with - | Expr.Lambda (_,None,None,v,b,_,retTy) when n > 0 -> - let (vs',b',retTy') = stripLambdaUpto (n-1) (b,retTy) + | Expr.Lambda (_, None, None, v, b, _, retTy) when n > 0 -> + let (vs', b', retTy') = stripLambdaUpto (n-1) (b, retTy) (v :: vs', b', retTy') | _ -> - ([],e,ty) + ([], e, ty) - let rec startStripLambdaUpto n (e,ty) = + let rec startStripLambdaUpto n (e, ty) = match e with - | Expr.Lambda (_,ctorThisValOpt,baseValOpt,v,b,_,retTy) when n > 0 -> - let (vs',b',retTy') = stripLambdaUpto (n-1) (b,retTy) - (ctorThisValOpt,baseValOpt, (v :: vs'), b', retTy') - | Expr.TyChoose (_tps,_b,_) -> + | Expr.Lambda (_, ctorThisValOpt, baseValOpt, v, b, _, retTy) when n > 0 -> + let (vs', b', retTy') = stripLambdaUpto (n-1) (b, retTy) + (ctorThisValOpt, baseValOpt, (v :: vs'), b', retTy') + | Expr.TyChoose (_tps, _b, _) -> startStripLambdaUpto n (ChooseTyparSolutionsForFreeChoiceTypars g amap e, ty) | _ -> - (None,None,[],e,ty) + (None, None, [], e, ty) let n = tvd.NumCurriedArgs - let tps,taue,tauty = + let tps, taue, tauty = match e with - | Expr.TyLambda (_,tps,b,_,retTy) when not (isNil tpNames) -> tps,b,retTy - | _ -> [],e,ty - let ctorThisValOpt,baseValOpt,vsl,body,retTy = startStripLambdaUpto n (taue,tauty) + | Expr.TyLambda (_, tps, b, _, retTy) when not (isNil tpNames) -> tps, b, retTy + | _ -> [], e, ty + let ctorThisValOpt, baseValOpt, vsl, body, retTy = startStripLambdaUpto n (taue, tauty) if vsl.Length <> n then None else - Some (tps,ctorThisValOpt,baseValOpt,vsl,body,retTy) + Some (tps, ctorThisValOpt, baseValOpt, vsl, body, retTy) -let destTopLambda g amap topValInfo (e,ty) = - match tryDestTopLambda g amap topValInfo (e,ty) with +let destTopLambda g amap topValInfo (e, ty) = + match tryDestTopLambda g amap topValInfo (e, ty) with | None -> error(Error(FSComp.SR.typrelInvalidValue(), e.Range)) | Some res -> res let IteratedAdjustArityOfLambdaBody g arities vsl body = - (arities, vsl, ([],body)) |||> List.foldBack2 (fun arities vs (allvs,body) -> - let vs,body = AdjustArityOfLambdaBody g arities vs body + (arities, vsl, ([], body)) |||> List.foldBack2 (fun arities vs (allvs, body) -> + let vs, body = AdjustArityOfLambdaBody g arities vs body vs :: allvs, body) /// Do AdjustArityOfLambdaBody for a series of @@ -267,12 +263,12 @@ let IteratedAdjustArityOfLambdaBody g arities vsl body = /// The required iterated function arity (List.length topValInfo) must be identical /// to the iterated function arity of the input lambda (List.length vsl) let IteratedAdjustArityOfLambda g amap topValInfo e = - let tps,ctorThisValOpt,baseValOpt,vsl,body,bodyty = destTopLambda g amap topValInfo (e, tyOfExpr g e) + let tps, ctorThisValOpt, baseValOpt, vsl, body, bodyty = destTopLambda g amap topValInfo (e, tyOfExpr g e) let arities = topValInfo.AritiesOfArgs if arities.Length <> vsl.Length then errorR(InternalError(sprintf "IteratedAdjustArityOfLambda, List.length arities = %d, List.length vsl = %d" arities.Length vsl.Length, body.Range)) - let vsl,body = IteratedAdjustArityOfLambdaBody g arities vsl body - tps,ctorThisValOpt,baseValOpt,vsl,body,bodyty + let vsl, body = IteratedAdjustArityOfLambdaBody g arities vsl body + tps, ctorThisValOpt, baseValOpt, vsl, body, bodyty /// "Single Feasible Type" inference diff --git a/src/fsharp/ast.fs b/src/fsharp/ast.fs index 0e0f7ca0d97..b4819ad5392 100644 --- a/src/fsharp/ast.fs +++ b/src/fsharp/ast.fs @@ -89,15 +89,20 @@ type XmlDocCollector() = type XmlDoc = | XmlDoc of string[] + static member Empty = XmlDocStatics.Empty + member x.NonEmpty = (let (XmlDoc lines) = x in lines.Length <> 0) + static member Merge (XmlDoc lines) (XmlDoc lines') = XmlDoc (Array.append lines lines') + + /// This code runs for .XML generation and thus influences cross-project xmldoc tooltips; for within-project tooltips, + /// see XmlDocumentation.fs in the language service static member Process (XmlDoc lines) = - // This code runs for .XML generation and thus influences cross-project xmldoc tooltips; for within-project tooltips, see XmlDocumentation.fs in the language service - let rec processLines (lines:string list) = + let rec processLines (lines: string list) = match lines with | [] -> [] - | (lineA::rest) as lines -> + | (lineA:: rest) as lines -> let lineAT = lineA.TrimStart([|' '|]) if lineAT = "" then processLines rest else if lineAT.StartsWithOrdinal("<") then lines @@ -111,7 +116,9 @@ type XmlDoc = // Discriminated unions can't contain statics, so we use a separate type and XmlDocStatics() = + static let empty = XmlDoc[| |] + static member Empty = empty type PreXmlDoc = @@ -128,11 +135,12 @@ type PreXmlDoc = if lines.Length = 0 then XmlDoc.Empty else XmlDoc lines - static member CreateFromGrabPoint(collector:XmlDocCollector, grabPointPos) = + static member CreateFromGrabPoint(collector: XmlDocCollector, grabPointPos) = collector.AddGrabPoint grabPointPos PreXmlDoc(grabPointPos, collector) static member Empty = PreXmlDocEmpty + static member Merge a b = PreXmlMerge (a, b) type ParserDetail = @@ -161,7 +169,7 @@ type LongIdentWithDots = /// if dotms.Length = lid.Length, then the parser must have reported an error, so the typechecker is allowed /// more freedom about typechecking these expressions. /// LongIdent can be empty list - it is used to denote that name of some AST element is absent (i.e. empty type name in inherit) - | LongIdentWithDots of id:LongIdent * dotms:range list + | LongIdentWithDots of id: LongIdent * dotms: range list member this.Range = match this with @@ -193,12 +201,12 @@ type TyparStaticReq = [] type SynTypar = - | Typar of ident:Ident * staticReq:TyparStaticReq * isCompGen:bool + | Typar of ident: Ident * staticReq: TyparStaticReq * isCompGen: bool - with member this.Range = - match this with - | Typar(id, _, _) -> - id.idRange + member this.Range = + match this with + | Typar(id, _, _) -> + id.idRange //------------------------------------------------------------------------ // AST: the grammar of constants and measures @@ -260,23 +268,23 @@ type /// UserNum(value, suffix) /// /// F# syntax: 1Q, 1Z, 1R, 1N, 1G - | UserNum of value:string * suffix:string + | UserNum of value: string * suffix: string /// F# syntax: verbatim or regular string, e.g. "abc" - | String of text:string * range:range + | String of text: string * range: range /// F# syntax: verbatim or regular byte string, e.g. "abc"B. /// /// Also used internally in the typechecker once an array of unit16 constants /// is detected, to allow more efficient processing of large arrays of uint16 constants. - | Bytes of bytes:byte[] * range:range + | Bytes of bytes: byte[] * range: range /// Used internally in the typechecker once an array of unit16 constants /// is detected, to allow more efficient processing of large arrays of uint16 constants. | UInt16s of uint16[] /// Old comment: "we never iterate, so the const here is not another SynConst.Measure" - | Measure of constant:SynConst * SynMeasure + | Measure of constant: SynConst * SynMeasure member c.Range dflt = match c with @@ -288,21 +296,21 @@ and /// The unchecked abstract syntax tree of F# unit of measure annotations. /// This should probably be merged with the representation of SynType. SynMeasure = - | Named of longId:LongIdent * range:range + | Named of longId: LongIdent * range: range - | Product of SynMeasure * SynMeasure * range:range + | Product of SynMeasure * SynMeasure * range: range - | Seq of SynMeasure list * range:range + | Seq of SynMeasure list * range: range - | Divide of SynMeasure * SynMeasure * range:range + | Divide of SynMeasure * SynMeasure * range: range - | Power of SynMeasure * SynRationalConst * range:range + | Power of SynMeasure * SynRationalConst * range: range | One - | Anon of range:range + | Anon of range: range - | Var of SynTypar * range:range + | Var of SynTypar * range: range and [] @@ -310,11 +318,10 @@ and SynRationalConst = | Integer of int32 - | Rational of int32 * int32 * range:range + | Rational of int32 * int32 * range: range | Negate of SynRationalConst - //------------------------------------------------------------------------ // AST: the grammar of types, expressions, declarations etc. //----------------------------------------------------------------------- @@ -339,29 +346,29 @@ type SequencePointInfoForSeq = | SuppressSequencePointOnStmtOfSequential type SequencePointInfoForTry = - | SequencePointAtTry of range:range + | SequencePointAtTry of range: range // Used for "use" and "for" | SequencePointInBodyOfTry | NoSequencePointAtTry type SequencePointInfoForWith = - | SequencePointAtWith of range:range + | SequencePointAtWith of range: range | NoSequencePointAtWith type SequencePointInfoForFinally = - | SequencePointAtFinally of range:range + | SequencePointAtFinally of range: range | NoSequencePointAtFinally type SequencePointInfoForForLoop = - | SequencePointAtForLoop of range:range + | SequencePointAtForLoop of range: range | NoSequencePointAtForLoop type SequencePointInfoForWhileLoop = - | SequencePointAtWhileLoop of range:range + | SequencePointAtWhileLoop of range: range | NoSequencePointAtWhileLoop type SequencePointInfoForBinding = - | SequencePointAtBinding of range:range + | SequencePointAtBinding of range: range // Indicates the omission of a sequence point for a binding for a 'do expr' | NoSequencePointAtDoBinding @@ -385,7 +392,7 @@ type SequencePointInfoForBinding = | NoSequencePointAtInvisibleBinding // Don't drop sequence points when combining sequence points - member x.Combine(y:SequencePointInfoForBinding) = + member x.Combine(y: SequencePointInfoForBinding) = match x, y with | SequencePointAtBinding _ as g, _ -> g | _, (SequencePointAtBinding _ as g) -> g @@ -427,106 +434,106 @@ type [] /// Represents the explicit declaration of a type parameter SynTyparDecl = - | TyparDecl of attributes:SynAttributes * SynTypar + | TyparDecl of attributes: SynAttributes * SynTypar and [] /// The unchecked abstract syntax tree of F# type constraints SynTypeConstraint = - /// F# syntax : is 'typar : struct - | WhereTyparIsValueType of genericName:SynTypar * range:range + /// F# syntax: is 'typar: struct + | WhereTyparIsValueType of genericName: SynTypar * range: range - /// F# syntax : is 'typar : not struct - | WhereTyparIsReferenceType of genericName:SynTypar * range:range + /// F# syntax: is 'typar: not struct + | WhereTyparIsReferenceType of genericName: SynTypar * range: range - /// F# syntax is 'typar : unmanaged - | WhereTyparIsUnmanaged of genericName:SynTypar * range:range + /// F# syntax is 'typar: unmanaged + | WhereTyparIsUnmanaged of genericName: SynTypar * range: range - /// F# syntax is 'typar : null - | WhereTyparSupportsNull of genericName:SynTypar * range:range + /// F# syntax is 'typar: null + | WhereTyparSupportsNull of genericName: SynTypar * range: range - /// F# syntax is 'typar : comparison - | WhereTyparIsComparable of genericName:SynTypar * range:range + /// F# syntax is 'typar: comparison + | WhereTyparIsComparable of genericName: SynTypar * range: range - /// F# syntax is 'typar : equality - | WhereTyparIsEquatable of genericName:SynTypar * range:range + /// F# syntax is 'typar: equality + | WhereTyparIsEquatable of genericName: SynTypar * range: range - /// F# syntax is default ^T : type - | WhereTyparDefaultsToType of genericName:SynTypar * typeName:SynType * range:range + /// F# syntax is default ^T: type + | WhereTyparDefaultsToType of genericName: SynTypar * typeName: SynType * range: range /// F# syntax is 'typar :> type - | WhereTyparSubtypeOfType of genericName:SynTypar * typeName:SynType * range:range + | WhereTyparSubtypeOfType of genericName: SynTypar * typeName: SynType * range: range - /// F# syntax is ^T : (static member MemberName : ^T * int -> ^T) - | WhereTyparSupportsMember of genericNames:SynType list * memberSig:SynMemberSig * range:range + /// F# syntax is ^T: (static member MemberName: ^T * int -> ^T) + | WhereTyparSupportsMember of genericNames: SynType list * memberSig: SynMemberSig * range: range - /// F# syntax is 'typar : enum<'UnderlyingType> - | WhereTyparIsEnum of genericName:SynTypar * SynType list * range:range + /// F# syntax is 'typar: enum<'UnderlyingType> + | WhereTyparIsEnum of genericName: SynTypar * SynType list * range: range - /// F# syntax is 'typar : delegate<'Args, unit> - | WhereTyparIsDelegate of genericName:SynTypar * SynType list * range:range + /// F# syntax is 'typar: delegate<'Args, unit> + | WhereTyparIsDelegate of genericName: SynTypar * SynType list * range: range and [] /// The unchecked abstract syntax tree of F# types SynType = - /// F# syntax : A.B.C - | LongIdent of longDotId:LongIdentWithDots + /// F# syntax: A.B.C + | LongIdent of longDotId: LongIdentWithDots /// App(typeName, LESSm, typeArgs, commasm, GREATERm, isPostfix, m) /// - /// F# syntax : type or type type or (type, ..., type) type + /// F# syntax: type or type type or (type, ..., type) type /// isPostfix: indicates a postfix type application e.g. "int list" or "(int, string) dict" /// commasm: ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them - | App of typeName:SynType * LESSrange:range option * typeArgs:SynType list * commaRanges:range list * GREATERrange:range option * isPostfix:bool * range:range + | App of typeName: SynType * LESSrange: range option * typeArgs: SynType list * commaRanges: range list * GREATERrange: range option * isPostfix: bool * range: range /// LongIdentApp(typeName, longId, LESSm, tyArgs, commasm, GREATERm, wholem) /// - /// F# syntax : type.A.B.C + /// F# syntax: type.A.B.C /// commasm: ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them - | LongIdentApp of typeName:SynType * longDotId:LongIdentWithDots * LESSRange:range option * typeArgs:SynType list * commaRanges:range list * GREATERrange:range option * range:range + | LongIdentApp of typeName: SynType * longDotId: LongIdentWithDots * LESSRange: range option * typeArgs: SynType list * commaRanges: range list * GREATERrange: range option * range: range - /// F# syntax : type * ... * type - /// F# syntax : struct (type * ... * type) + /// F# syntax: type * ... * type + /// F# syntax: struct (type * ... * type) // the bool is true if / rather than * follows the type - | Tuple of isStruct:bool * typeNames:(bool*SynType) list * range:range + | Tuple of isStruct: bool * typeNames:(bool*SynType) list * range: range - /// F# syntax : {| id: type; ...; id: type |} - /// F# syntax : struct {| id: type; ...; id: type |} - | AnonRecd of isStruct:bool * typeNames:(Ident * SynType) list * range:range + /// F# syntax: {| id: type; ...; id: type |} + /// F# syntax: struct {| id: type; ...; id: type |} + | AnonRecd of isStruct: bool * typeNames:(Ident * SynType) list * range: range - /// F# syntax : type[] - | Array of int * elementType:SynType * range:range + /// F# syntax: type[] + | Array of int * elementType: SynType * range: range - /// F# syntax : type -> type - | Fun of argType:SynType * returnType:SynType * range:range + /// F# syntax: type -> type + | Fun of argType: SynType * returnType: SynType * range: range - /// F# syntax : 'Var - | Var of genericName:SynTypar * range:range + /// F# syntax: 'Var + | Var of genericName: SynTypar * range: range - /// F# syntax : _ - | Anon of range:range + /// F# syntax: _ + | Anon of range: range - /// F# syntax : typ with constraints - | WithGlobalConstraints of typeName:SynType * constraints:SynTypeConstraint list * range:range + /// F# syntax: typ with constraints + | WithGlobalConstraints of typeName: SynType * constraints: SynTypeConstraint list * range: range - /// F# syntax : #type - | HashConstraint of SynType * range:range + /// F# syntax: #type + | HashConstraint of SynType * range: range - /// F# syntax : for units of measure e.g. m / s - | MeasureDivide of dividendType:SynType * divisorType:SynType * range:range + /// F# syntax: for units of measure e.g. m / s + | MeasureDivide of dividendType: SynType * divisorType: SynType * range: range - /// F# syntax : for units of measure e.g. m^3, kg^1/2 - | MeasurePower of measureType:SynType * SynRationalConst * range:range + /// F# syntax: for units of measure e.g. m^3, kg^1/2 + | MeasurePower of measureType: SynType * SynRationalConst * range: range - /// F# syntax : 1, "abc" etc, used in parameters to type providers + /// F# syntax: 1, "abc" etc, used in parameters to type providers /// For the dimensionless units i.e. 1 , and static parameters to provided types - | StaticConstant of constant:SynConst * range:range + | StaticConstant of constant: SynConst * range: range - /// F# syntax : const expr, used in static parameters to type providers - | StaticConstantExpr of expr:SynExpr * range:range + /// F# syntax: const expr, used in static parameters to type providers + | StaticConstantExpr of expr: SynExpr * range: range - /// F# syntax : ident=1 etc., used in static parameters to type providers - | StaticConstantNamed of expr:SynType * SynType * range:range + /// F# syntax: ident=1 etc., used in static parameters to type providers + | StaticConstantNamed of expr: SynType * SynType * range: range /// Get the syntactic range of source code covered by this construct. member x.Range = @@ -558,81 +565,81 @@ and /// /// Parenthesized expressions. Kept in AST to distinguish A.M((x, y)) /// from A.M(x, y), among other things. - | Paren of expr:SynExpr * leftParenRange:range * rightParenRange:range option * range:range + | Paren of expr: SynExpr * leftParenRange: range * rightParenRange: range option * range: range /// F# syntax: <@ expr @>, <@@ expr @@> /// /// Quote(operator, isRaw, quotedSynExpr, isFromQueryExpression, m) - | Quote of operator:SynExpr * isRaw:bool * quotedSynExpr:SynExpr * isFromQueryExpression:bool * range:range + | Quote of operator: SynExpr * isRaw: bool * quotedSynExpr: SynExpr * isFromQueryExpression: bool * range: range /// F# syntax: 1, 1.3, () etc. - | Const of constant:SynConst * range:range + | Const of constant: SynConst * range: range - /// F# syntax: expr : type - | Typed of expr:SynExpr * typeName:SynType * range:range + /// F# syntax: expr: type + | Typed of expr: SynExpr * typeName: SynType * range: range /// F# syntax: e1, ..., eN - | Tuple of isStruct: bool * exprs:SynExpr list * commaRanges:range list * range:range // "range list" is for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them + | Tuple of isStruct: bool * exprs: SynExpr list * commaRanges: range list * range: range // "range list" is for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them /// F# syntax: {| id1=e1; ...; idN=eN |} /// F# syntax: struct {| id1=e1; ...; idN=eN |} - | AnonRecd of isStruct: bool * copyInfo:(SynExpr * BlockSeparator) option * recordFields:(Ident * SynExpr) list * range:range + | AnonRecd of isStruct: bool * copyInfo:(SynExpr * BlockSeparator) option * recordFields:(Ident * SynExpr) list * range: range /// F# syntax: [ e1; ...; en ], [| e1; ...; en |] - | ArrayOrList of isList:bool * exprs:SynExpr list * range:range + | ArrayOrList of isList: bool * exprs: SynExpr list * range: range /// F# syntax: { f1=e1; ...; fn=en } /// SynExpr.Record((baseType, baseCtorArgs, mBaseCtor, sepAfterBase, mInherits), (copyExpr, sepAfterCopyExpr), (recordFieldName, fieldValue, sepAfterField), mWholeExpr) /// inherit includes location of separator (for tooling) /// copyOpt contains range of the following WITH part (for tooling) /// every field includes range of separator after the field (for tooling) - | Record of baseInfo:(SynType * SynExpr * range * BlockSeparator option * range) option * copyInfo:(SynExpr * BlockSeparator) option * recordFields:(RecordFieldName * (SynExpr option) * BlockSeparator option) list * range:range + | Record of baseInfo:(SynType * SynExpr * range * BlockSeparator option * range) option * copyInfo:(SynExpr * BlockSeparator) option * recordFields:(RecordFieldName * (SynExpr option) * BlockSeparator option) list * range: range /// F# syntax: new C(...) /// The flag is true if known to be 'family' ('protected') scope - | New of isProtected:bool * typeName:SynType * expr:SynExpr * range:range + | New of isProtected: bool * typeName: SynType * expr: SynExpr * range: range /// SynExpr.ObjExpr(objTy, argOpt, binds, extraImpls, mNewExpr, mWholeExpr) /// /// F# syntax: { new ... with ... } - | ObjExpr of objType:SynType * argOptions:(SynExpr * Ident option) option * bindings:SynBinding list * extraImpls:SynInterfaceImpl list * newExprRange:range * range:range + | ObjExpr of objType: SynType * argOptions:(SynExpr * Ident option) option * bindings: SynBinding list * extraImpls: SynInterfaceImpl list * newExprRange: range * range: range /// F# syntax: 'while ... do ...' - | While of whileSeqPoint:SequencePointInfoForWhileLoop * whileExpr:SynExpr * doExpr:SynExpr * range:range + | While of whileSeqPoint: SequencePointInfoForWhileLoop * whileExpr: SynExpr * doExpr: SynExpr * range: range /// F# syntax: 'for i = ... to ... do ...' - | For of forSeqPoint:SequencePointInfoForForLoop * ident:Ident * identBody:SynExpr * bool * toBody:SynExpr * doBody:SynExpr * range:range + | For of forSeqPoint: SequencePointInfoForForLoop * ident: Ident * identBody: SynExpr * bool * toBody: SynExpr * doBody: SynExpr * range: range /// SynExpr.ForEach (spBind, seqExprOnly, isFromSource, pat, enumExpr, bodyExpr, mWholeExpr). /// /// F# syntax: 'for ... in ... do ...' - | ForEach of forSeqPoint:SequencePointInfoForForLoop * seqExprOnly:SeqExprOnly * isFromSource:bool * pat:SynPat * enumExpr:SynExpr * bodyExpr:SynExpr * range:range + | ForEach of forSeqPoint: SequencePointInfoForForLoop * seqExprOnly: SeqExprOnly * isFromSource: bool * pat: SynPat * enumExpr: SynExpr * bodyExpr: SynExpr * range: range /// F# syntax: [ expr ], [| expr |] - | ArrayOrListOfSeqExpr of isArray:bool * expr:SynExpr * range:range + | ArrayOrListOfSeqExpr of isArray: bool * expr: SynExpr * range: range /// CompExpr(isArrayOrList, isNotNakedRefCell, expr) /// /// F# syntax: { expr } - | CompExpr of isArrayOrList:bool * isNotNakedRefCell:bool ref * expr:SynExpr * range:range + | CompExpr of isArrayOrList: bool * isNotNakedRefCell: bool ref * expr: SynExpr * range: range /// First bool indicates if lambda originates from a method. Patterns here are always "simple" /// Second bool indicates if this is a "later" part of an iterated sequence of lambdas /// /// F# syntax: fun pat -> expr - | Lambda of fromMethod:bool * inLambdaSeq:bool * args:SynSimplePats * body:SynExpr * range:range + | Lambda of fromMethod: bool * inLambdaSeq: bool * args: SynSimplePats * body: SynExpr * range: range /// F# syntax: function pat1 -> expr | ... | patN -> exprN - | MatchLambda of isExnMatch:bool * range * SynMatchClause list * matchSeqPoint:SequencePointInfoForBinding * range:range + | MatchLambda of isExnMatch: bool * range * SynMatchClause list * matchSeqPoint: SequencePointInfoForBinding * range: range /// F# syntax: match expr with pat1 -> expr | ... | patN -> exprN - | Match of matchSeqPoint:SequencePointInfoForBinding * expr:SynExpr * clauses:SynMatchClause list * range:range (* bool indicates if this is an exception match in a computation expression which throws unmatched exceptions *) + | Match of matchSeqPoint: SequencePointInfoForBinding * expr: SynExpr * clauses: SynMatchClause list * range: range (* bool indicates if this is an exception match in a computation expression which throws unmatched exceptions *) /// F# syntax: do expr - | Do of expr:SynExpr * range:range + | Do of expr: SynExpr * range: range /// F# syntax: assert expr - | Assert of expr:SynExpr * range:range + | Assert of expr: SynExpr * range: range /// App(exprAtomicFlag, isInfix, funcExpr, argExpr, m) /// - exprAtomicFlag: indicates if the application is syntactically atomic, e.g. f.[1] is atomic, but 'f x' is not @@ -640,13 +647,13 @@ and /// (or more generally, for higher operator fixities, if App(x, y) is such that y comes before x in the source code, then the node is marked isInfix=true) /// /// F# syntax: f x - | App of ExprAtomicFlag * isInfix:bool * funcExpr:SynExpr * argExpr:SynExpr * range:range + | App of ExprAtomicFlag * isInfix: bool * funcExpr: SynExpr * argExpr: SynExpr * range: range /// TypeApp(expr, mLessThan, types, mCommas, mGreaterThan, mTypeArgs, mWholeExpr) /// "mCommas" are the ranges for interstitial commas, these only matter for parsing/design-time tooling, the typechecker may munge/discard them /// /// F# syntax: expr - | TypeApp of expr:SynExpr * LESSrange:range * typeNames:SynType list * commaRanges:range list * GREATERrange:range option * typeArgsRange:range * range:range + | TypeApp of expr: SynExpr * LESSrange: range * typeNames: SynType list * commaRanges: range list * GREATERrange: range option * typeArgsRange: range * range: range /// LetOrUse(isRecursive, isUse, bindings, body, wholeRange) /// @@ -654,28 +661,28 @@ and /// F# syntax: let f pat1 .. patN = expr in expr /// F# syntax: let rec f pat1 .. patN = expr in expr /// F# syntax: use pat = expr in expr - | LetOrUse of isRecursive:bool * isUse:bool * bindings:SynBinding list * body:SynExpr * range:range + | LetOrUse of isRecursive: bool * isUse: bool * bindings: SynBinding list * body: SynExpr * range: range /// F# syntax: try expr with pat -> expr - | TryWith of tryExpr:SynExpr * tryRange:range * withCases:SynMatchClause list * withRange:range * range:range * trySeqPoint:SequencePointInfoForTry * withSeqPoint:SequencePointInfoForWith + | TryWith of tryExpr: SynExpr * tryRange: range * withCases: SynMatchClause list * withRange: range * range: range * trySeqPoint: SequencePointInfoForTry * withSeqPoint: SequencePointInfoForWith /// F# syntax: try expr finally expr - | TryFinally of tryExpr:SynExpr * finallyExpr:SynExpr * range:range * trySeqPoint:SequencePointInfoForTry * finallySeqPoint:SequencePointInfoForFinally + | TryFinally of tryExpr: SynExpr * finallyExpr: SynExpr * range: range * trySeqPoint: SequencePointInfoForTry * finallySeqPoint: SequencePointInfoForFinally /// F# syntax: lazy expr - | Lazy of SynExpr * range:range + | Lazy of SynExpr * range: range /// Seq(seqPoint, isTrueSeq, e1, e2, m) /// isTrueSeq: false indicates "let v = a in b; v" /// /// F# syntax: expr; expr - | Sequential of seqPoint:SequencePointInfoForSeq * isTrueSeq:bool * expr1:SynExpr * expr2:SynExpr * range:range + | Sequential of seqPoint: SequencePointInfoForSeq * isTrueSeq: bool * expr1: SynExpr * expr2: SynExpr * range: range /// IfThenElse(exprGuard, exprThen, optionalExprElse, spIfToThen, isFromErrorRecovery, mIfToThen, mIfToEndOfLastBranch) /// /// F# syntax: if expr then expr /// F# syntax: if expr then expr else expr - | IfThenElse of ifExpr:SynExpr * thenExpr:SynExpr * elseExpr:SynExpr option * spIfToThen:SequencePointInfoForBinding * isFromErrorRecovery:bool * ifToThenRange:range * range:range + | IfThenElse of ifExpr: SynExpr * thenExpr: SynExpr * elseExpr: SynExpr option * spIfToThen: SequencePointInfoForBinding * isFromErrorRecovery: bool * ifToThenRange: range * range: range /// F# syntax: ident /// Optimized representation, = SynExpr.LongIdent(false, [id], id.idRange) @@ -685,115 +692,115 @@ and /// LongIdent(isOptional, longIdent, altNameRefCell, m) /// isOptional: true if preceded by a '?' for an optional named parameter /// altNameRefCell: Normally 'None' except for some compiler-generated variables in desugaring pattern matching. See SynSimplePat.Id - | LongIdent of isOptional:bool * longDotId:LongIdentWithDots * altNameRefCell:SynSimplePatAlternativeIdInfo ref option * range:range + | LongIdent of isOptional: bool * longDotId: LongIdentWithDots * altNameRefCell: SynSimplePatAlternativeIdInfo ref option * range: range /// F# syntax: ident.ident...ident <- expr - | LongIdentSet of longDotId:LongIdentWithDots * expr:SynExpr * range:range + | LongIdentSet of longDotId: LongIdentWithDots * expr: SynExpr * range: range /// DotGet(expr, rangeOfDot, lid, wholeRange) /// /// F# syntax: expr.ident.ident - | DotGet of expr:SynExpr * rangeOfDot:range * longDotId:LongIdentWithDots * range:range + | DotGet of expr: SynExpr * rangeOfDot: range * longDotId: LongIdentWithDots * range: range /// F# syntax: expr.ident...ident <- expr - | DotSet of SynExpr * longDotId:LongIdentWithDots * SynExpr * range:range + | DotSet of SynExpr * longDotId: LongIdentWithDots * SynExpr * range: range /// F# syntax: expr <- expr - | Set of SynExpr * SynExpr * range:range + | Set of SynExpr * SynExpr * range: range /// F# syntax: expr.[expr, ..., expr] - | DotIndexedGet of SynExpr * SynIndexerArg list * range * range:range + | DotIndexedGet of SynExpr * SynIndexerArg list * range * range: range /// DotIndexedSet (objectExpr, indexExprs, valueExpr, rangeOfLeftOfSet, rangeOfDot, rangeOfWholeExpr) /// /// F# syntax: expr.[expr, ..., expr] <- expr - | DotIndexedSet of objectExpr:SynExpr * indexExprs:SynIndexerArg list * valueExpr:SynExpr * leftOfSetRange:range * dotRange:range * range:range + | DotIndexedSet of objectExpr: SynExpr * indexExprs: SynIndexerArg list * valueExpr: SynExpr * leftOfSetRange: range * dotRange: range * range: range /// F# syntax: Type.Items(e1) <- e2 , rarely used named-property-setter notation, e.g. Foo.Bar.Chars(3) <- 'a' - | NamedIndexedPropertySet of longDotId:LongIdentWithDots * SynExpr * SynExpr * range:range + | NamedIndexedPropertySet of longDotId: LongIdentWithDots * SynExpr * SynExpr * range: range /// F# syntax: expr.Items(e1) <- e2 , rarely used named-property-setter notation, e.g. (stringExpr).Chars(3) <- 'a' - | DotNamedIndexedPropertySet of SynExpr * longDotId:LongIdentWithDots * SynExpr * SynExpr * range:range + | DotNamedIndexedPropertySet of SynExpr * longDotId: LongIdentWithDots * SynExpr * SynExpr * range: range /// F# syntax: expr :? type - | TypeTest of expr:SynExpr * typeName:SynType * range:range + | TypeTest of expr: SynExpr * typeName: SynType * range: range /// F# syntax: expr :> type - | Upcast of expr:SynExpr * typeName:SynType * range:range + | Upcast of expr: SynExpr * typeName: SynType * range: range /// F# syntax: expr :?> type - | Downcast of expr:SynExpr * typeName:SynType * range:range + | Downcast of expr: SynExpr * typeName: SynType * range: range /// F# syntax: upcast expr - | InferredUpcast of expr:SynExpr * range:range + | InferredUpcast of expr: SynExpr * range: range /// F# syntax: downcast expr - | InferredDowncast of expr:SynExpr * range:range + | InferredDowncast of expr: SynExpr * range: range /// F# syntax: null - | Null of range:range + | Null of range: range /// F# syntax: &expr, &&expr - | AddressOf of isByref:bool * SynExpr * range * range:range + | AddressOf of isByref: bool * SynExpr * range * range: range /// F# syntax: ((typar1 or ... or typarN): (member-dig) expr) - | TraitCall of SynTypar list * SynMemberSig * SynExpr * range:range + | TraitCall of SynTypar list * SynMemberSig * SynExpr * range: range /// F# syntax: ... in ... /// Computation expressions only, based on JOIN_IN token from lex filter - | JoinIn of SynExpr * range * SynExpr * range:range + | JoinIn of SynExpr * range * SynExpr * range: range /// F# syntax: /// Computation expressions only, implied by final "do" or "do!" - | ImplicitZero of range:range + | ImplicitZero of range: range /// F# syntax: yield expr /// F# syntax: return expr /// Computation expressions only - | YieldOrReturn of (bool * bool) * expr:SynExpr * range:range + | YieldOrReturn of (bool * bool) * expr: SynExpr * range: range /// F# syntax: yield! expr /// F# syntax: return! expr /// Computation expressions only - | YieldOrReturnFrom of (bool * bool) * expr:SynExpr * range:range + | YieldOrReturnFrom of (bool * bool) * expr: SynExpr * range: range /// SynExpr.LetOrUseBang(spBind, isUse, isFromSource, pat, rhsExpr, bodyExpr, mWholeExpr). /// /// F# syntax: let! pat = expr in expr /// F# syntax: use! pat = expr in expr /// Computation expressions only - | LetOrUseBang of bindSeqPoint:SequencePointInfoForBinding * isUse:bool * isFromSource:bool * SynPat * SynExpr * SynExpr * range:range + | LetOrUseBang of bindSeqPoint: SequencePointInfoForBinding * isUse: bool * isFromSource: bool * SynPat * SynExpr * SynExpr * range: range /// F# syntax: match! expr with pat1 -> expr | ... | patN -> exprN - | MatchBang of matchSeqPoint:SequencePointInfoForBinding * expr:SynExpr * clauses:SynMatchClause list * range:range (* bool indicates if this is an exception match in a computation expression which throws unmatched exceptions *) + | MatchBang of matchSeqPoint: SequencePointInfoForBinding * expr: SynExpr * clauses: SynMatchClause list * range: range (* bool indicates if this is an exception match in a computation expression which throws unmatched exceptions *) /// F# syntax: do! expr /// Computation expressions only - | DoBang of expr:SynExpr * range:range + | DoBang of expr: SynExpr * range: range /// Only used in FSharp.Core - | LibraryOnlyILAssembly of ILInstr array * SynType list * SynExpr list * SynType list * range:range (* Embedded IL assembly code *) + | LibraryOnlyILAssembly of ILInstr array * SynType list * SynExpr list * SynType list * range: range (* Embedded IL assembly code *) /// Only used in FSharp.Core - | LibraryOnlyStaticOptimization of SynStaticOptimizationConstraint list * SynExpr * SynExpr * range:range + | LibraryOnlyStaticOptimization of SynStaticOptimizationConstraint list * SynExpr * SynExpr * range: range /// Only used in FSharp.Core - | LibraryOnlyUnionCaseFieldGet of expr:SynExpr * longId:LongIdent * int * range:range + | LibraryOnlyUnionCaseFieldGet of expr: SynExpr * longId: LongIdent * int * range: range /// Only used in FSharp.Core - | LibraryOnlyUnionCaseFieldSet of SynExpr * longId:LongIdent * int * SynExpr * range:range + | LibraryOnlyUnionCaseFieldSet of SynExpr * longId: LongIdent * int * SynExpr * range: range /// Inserted for error recovery - | ArbitraryAfterError of debugStr:string * range:range + | ArbitraryAfterError of debugStr: string * range: range /// Inserted for error recovery - | FromParseError of expr:SynExpr * range:range + | FromParseError of expr: SynExpr * range: range /// Inserted for error recovery when there is "expr." and missing tokens or error recovery after the dot - | DiscardAfterMissingQualificationAfterDot of SynExpr * range:range + | DiscardAfterMissingQualificationAfterDot of SynExpr * range: range /// 'use x = fixed expr' - | Fixed of expr:SynExpr * range:range + | Fixed of expr: SynExpr * range: range /// Get the syntactic range of source code covered by this construct. member e.Range = @@ -991,7 +998,7 @@ and e1.RangeOfFirstPortion | SynExpr.ForEach (_, _, _, pat, _, _, r) -> let start = r.Start - let e = (pat.Range : range).Start + let e = (pat.Range: range).Start mkRange r.FileName start e | SynExpr.Ident id -> id.idRange | SynExpr.Fixed (_, m) -> m @@ -1022,14 +1029,14 @@ and /// The info indicates an alternative (compiler generated) identifier to be used because the name of the identifier is already bound. /// See Product Studio FSharp 1.0, bug 6389. /// - /// isCompilerGenerated : true if a compiler generated name + /// isCompilerGenerated: true if a compiler generated name /// isThisVar: true if 'this' variable in member /// isOptArg: true if a '?' is in front of the name - | Id of ident:Ident * altNameRefCell:SynSimplePatAlternativeIdInfo ref option * isCompilerGenerated:bool * isThisVar:bool * isOptArg:bool * range:range + | Id of ident: Ident * altNameRefCell: SynSimplePatAlternativeIdInfo ref option * isCompilerGenerated: bool * isThisVar: bool * isOptArg: bool * range: range - | Typed of SynSimplePat * SynType * range:range + | Typed of SynSimplePat * SynType * range: range - | Attrib of SynSimplePat * SynAttributes * range:range + | Attrib of SynSimplePat * SynAttributes * range: range and SynSimplePatAlternativeIdInfo = @@ -1043,79 +1050,79 @@ and [] SynStaticOptimizationConstraint = - | WhenTyparTyconEqualsTycon of SynTypar * SynType * range:range + | WhenTyparTyconEqualsTycon of SynTypar * SynType * range: range - | WhenTyparIsStruct of SynTypar * range:range + | WhenTyparIsStruct of SynTypar * range: range and [] - /// Represents a simple set of variable bindings a, (a, b) or (a:Type, b:Type) at a lambda, + /// Represents a simple set of variable bindings a, (a, b) or (a: Type, b: Type) at a lambda, /// function definition or other binding point, after the elimination of pattern matching /// from the construct, e.g. after changing a "function pat1 -> rule1 | ..." to a /// "fun v -> match v with ..." SynSimplePats = - | SimplePats of SynSimplePat list * range:range + | SimplePats of SynSimplePat list * range: range - | Typed of SynSimplePats * SynType * range:range + | Typed of SynSimplePats * SynType * range: range and SynConstructorArgs = | Pats of SynPat list - | NamePatPairs of (Ident * SynPat) list * range:range + | NamePatPairs of (Ident * SynPat) list * range: range and [] SynPat = - | Const of SynConst * range:range + | Const of SynConst * range: range - | Wild of range:range + | Wild of range: range - | Named of SynPat * Ident * isSelfIdentifier:bool (* true if 'this' variable *) * accessibility:SynAccess option * range:range + | Named of SynPat * Ident * isSelfIdentifier: bool (* true if 'this' variable *) * accessibility: SynAccess option * range: range - | Typed of SynPat * SynType * range:range + | Typed of SynPat * SynType * range: range - | Attrib of SynPat * SynAttributes * range:range + | Attrib of SynPat * SynAttributes * range: range - | Or of SynPat * SynPat * range:range + | Or of SynPat * SynPat * range: range - | Ands of SynPat list * range:range + | Ands of SynPat list * range: range | LongIdent of - longDotId:LongIdentWithDots * + longDotId: LongIdentWithDots * Ident option * // holds additional ident for tooling SynValTyparDecls option * // usually None: temporary used to parse "f<'a> x = x"*) SynConstructorArgs * - accessibility:SynAccess option * - range:range + accessibility: SynAccess option * + range: range - | Tuple of isStruct: bool * SynPat list * range:range + | Tuple of isStruct: bool * SynPat list * range: range - | Paren of SynPat * range:range + | Paren of SynPat * range: range - | ArrayOrList of bool * SynPat list * range:range + | ArrayOrList of bool * SynPat list * range: range - | Record of ((LongIdent * Ident) * SynPat) list * range:range + | Record of ((LongIdent * Ident) * SynPat) list * range: range /// 'null' - | Null of range:range + | Null of range: range /// '?id' -- for optional argument names - | OptionalVal of Ident * range:range + | OptionalVal of Ident * range: range /// ':? type ' - | IsInst of SynType * range:range + | IsInst of SynType * range: range /// <@ expr @>, used for active pattern arguments - | QuoteExpr of SynExpr * range:range + | QuoteExpr of SynExpr * range: range - /// Deprecated character range:ranges - | DeprecatedCharRange of char * char * range:range + /// Deprecated character range: ranges + | DeprecatedCharRange of char * char * range: range /// Used internally in the type checker - | InstanceMember of Ident * Ident * (* holds additional ident for tooling *) Ident option * accessibility:SynAccess option * range:range (* adhoc overloaded method/property *) + | InstanceMember of Ident * Ident * (* holds additional ident for tooling *) Ident option * accessibility: SynAccess option * range: range (* adhoc overloaded method/property *) /// A pattern arising from a parse error - | FromParseError of SynPat * range:range + | FromParseError of SynPat * range: range member p.Range = match p with @@ -1142,12 +1149,12 @@ and and [] SynInterfaceImpl = - | InterfaceImpl of SynType * SynBinding list * range:range + | InterfaceImpl of SynType * SynBinding list * range: range and [] SynMatchClause = - | Clause of SynPat * whenExpr: SynExpr option * SynExpr * range:range * SequencePointInfoForTarget + | Clause of SynPat * whenExpr: SynExpr option * SynExpr * range: range * SequencePointInfoForTarget member this.RangeOfGuardAndRhs = match this with @@ -1189,18 +1196,18 @@ and [] SynBinding = | Binding of - accessibility:SynAccess option * - kind:SynBindingKind * - mustInline:bool * - isMutable:bool * - attrs:SynAttributes * - xmlDoc:PreXmlDoc * - valData:SynValData * - headPat:SynPat * - returnInfo:SynBindingReturnInfo option * - expr:SynExpr * - range:range * - seqPoint:SequencePointInfoForBinding + accessibility: SynAccess option * + kind: SynBindingKind * + mustInline: bool * + isMutable: bool * + attrs: SynAttributes * + xmlDoc: PreXmlDoc * + valData: SynValData * + headPat: SynPat * + returnInfo: SynBindingReturnInfo option * + expr: SynExpr * + range: range * + seqPoint: SequencePointInfoForBinding // no member just named "Range", as that would be confusing: // - for everything else, the 'range' member that appears last/second-to-last is the 'full range' of the whole tree construct @@ -1215,7 +1222,7 @@ and and [] SynBindingReturnInfo = - | SynBindingReturnInfo of typeName:SynType * range:range * attributes:SynAttributes + | SynBindingReturnInfo of typeName: SynType * range: range * attributes: SynAttributes and @@ -1251,15 +1258,15 @@ and /// and member constraints. SynMemberSig = - | Member of SynValSig * MemberFlags * range:range + | Member of SynValSig * MemberFlags * range: range - | Interface of typeName:SynType * range:range + | Interface of typeName: SynType * range: range - | Inherit of typeName:SynType * range:range + | Inherit of typeName: SynType * range: range - | ValField of SynField * range:range + | ValField of SynField * range: range - | NestedType of SynTypeDefnSig * range:range + | NestedType of SynTypeDefnSig * range: range and SynMemberSigs = SynMemberSig list @@ -1285,28 +1292,28 @@ and SynTypeDefnSimpleRepr = /// A union type definition, type X = A | B - | Union of accessibility:SynAccess option * unionCases:SynUnionCases * range:range + | Union of accessibility: SynAccess option * unionCases: SynUnionCases * range: range /// An enum type definition, type X = A = 1 | B = 2 - | Enum of SynEnumCases * range:range + | Enum of SynEnumCases * range: range - /// A record type definition, type X = { A : int; B : int } - | Record of accessibility:SynAccess option * recordFields:SynFields * range:range + /// A record type definition, type X = { A: int; B: int } + | Record of accessibility: SynAccess option * recordFields: SynFields * range: range /// An object oriented type definition. This is not a parse-tree form, but represents the core /// type representation which the type checker splits out from the "ObjectModel" cases of type definitions. - | General of SynTypeDefnKind * (SynType * range * Ident option) list * (SynValSig * MemberFlags) list * SynField list * bool * bool * SynSimplePat list option * range:range + | General of SynTypeDefnKind * (SynType * range * Ident option) list * (SynValSig * MemberFlags) list * SynField list * bool * bool * SynSimplePat list option * range: range /// A type defined by using an IL assembly representation. Only used in FSharp.Core. /// /// F# syntax: "type X = (# "..."#) - | LibraryOnlyILAssembly of ILType * range:range + | LibraryOnlyILAssembly of ILType * range: range /// A type abbreviation, "type X = A.B.C" - | TypeAbbrev of ParserDetail * SynType * range:range + | TypeAbbrev of ParserDetail * SynType * range: range /// An abstract definition , "type X" - | None of range:range + | None of range: range /// An exception definition , "exception E = ..." | Exception of SynExceptionDefnRepr @@ -1329,7 +1336,7 @@ and SynEnumCase = /// The untyped, unchecked syntax tree for one case in an enum definition. - | EnumCase of attrs:SynAttributes * ident:Ident * SynConst * PreXmlDoc * range:range + | EnumCase of attrs: SynAttributes * ident: Ident * SynConst * PreXmlDoc * range: range member this.Range = match this with @@ -1342,7 +1349,7 @@ and SynUnionCase = /// The untyped, unchecked syntax tree for one case in a union definition. - | UnionCase of SynAttributes * ident:Ident * SynUnionCaseType * PreXmlDoc * accessibility:SynAccess option * range:range + | UnionCase of SynAttributes * ident: Ident * SynUnionCaseType * PreXmlDoc * accessibility: SynAccess option * range: range member this.Range = match this with @@ -1355,9 +1362,9 @@ and SynUnionCaseType = /// Normal style declaration - | UnionCaseFields of cases:SynField list + | UnionCaseFields of cases: SynField list - /// Full type spec given by 'UnionCase : ty1 * tyN -> rty'. Only used in FSharp.Core, otherwise a warning. + /// Full type spec given by 'UnionCase: ty1 * tyN -> rty'. Only used in FSharp.Core, otherwise a warning. | UnionCaseFullType of (SynType * SynValInfo) and @@ -1368,10 +1375,10 @@ and SynTypeDefnSigRepr = /// Indicates the right right-hand-side is a class, struct, interface or other object-model type - | ObjectModel of SynTypeDefnKind * memberSigs:SynMemberSigs * range:range + | ObjectModel of SynTypeDefnKind * memberSigs: SynMemberSigs * range: range /// Indicates the right right-hand-side is a record, union or other simple type. - | Simple of SynTypeDefnSimpleRepr * range:range + | Simple of SynTypeDefnSimpleRepr * range: range | Exception of SynExceptionDefnRepr @@ -1387,7 +1394,7 @@ and SynTypeDefnSig = /// The information for a type definition in a signature - | TypeDefnSig of SynComponentInfo * SynTypeDefnSigRepr * SynMemberSigs * range:range + | TypeDefnSig of SynComponentInfo * SynTypeDefnSigRepr * SynMemberSigs * range: range and SynFields = SynField list @@ -1395,7 +1402,7 @@ and [] /// The untyped, unchecked syntax tree for a field declaration in a record or class SynField = - | Field of attrs:SynAttributes * isStatic:bool * Ident option * SynType * isMutable: bool * xmlDoc:PreXmlDoc * accessibility:SynAccess option * range:range + | Field of attrs: SynAttributes * isStatic: bool * Ident option * SynType * isMutable: bool * xmlDoc: PreXmlDoc * accessibility: SynAccess option * range: range and [] @@ -1406,7 +1413,7 @@ and /// for a type definition or module. For modules, entries such as the type parameters are /// always empty. SynComponentInfo = - | ComponentInfo of attribs:SynAttributes * typeParams:SynTyparDecl list * constraints:SynTypeConstraint list * longId:LongIdent * xmlDoc:PreXmlDoc * preferPostfix:bool * accessibility:SynAccess option * range:range + | ComponentInfo of attribs: SynAttributes * typeParams: SynTyparDecl list * constraints: SynTypeConstraint list * longId: LongIdent * xmlDoc: PreXmlDoc * preferPostfix: bool * accessibility: SynAccess option * range: range member this.Range = match this with @@ -1416,17 +1423,17 @@ and [] SynValSig = | ValSpfn of - synAttributes:SynAttributes * - ident:Ident * - explicitValDecls:SynValTyparDecls * - synType:SynType * - arity:SynValInfo * - isInline:bool * - isMutable:bool * - xmlDoc:PreXmlDoc * - accessibility:SynAccess option * - synExpr:SynExpr option * - range:range + synAttributes: SynAttributes * + ident: Ident * + explicitValDecls: SynValTyparDecls * + synType: SynType * + arity: SynValInfo * + isInline: bool * + isMutable: bool * + xmlDoc: PreXmlDoc * + accessibility: SynAccess option * + synExpr: SynExpr option * + range: range member x.RangeOfId = let (ValSpfn(ident=id)) = x in id.idRange @@ -1449,20 +1456,20 @@ and [] SynArgInfo = - | SynArgInfo of SynAttributes * optional:bool * Ident option + | SynArgInfo of SynAttributes * optional: bool * Ident option /// The names and other metadata for the type parameters for a member or function and [] SynValTyparDecls = - | SynValTyparDecls of SynTyparDecl list * bool * constraints:SynTypeConstraint list + | SynValTyparDecls of SynTyparDecl list * bool * constraints: SynTypeConstraint list /// 'exception E = ... ' and [] SynExceptionDefnRepr = - | SynExceptionDefnRepr of SynAttributes * SynUnionCase * longId:LongIdent option * xmlDoc:PreXmlDoc * accessiblity:SynAccess option * range:range + | SynExceptionDefnRepr of SynAttributes * SynUnionCase * longId: LongIdent option * xmlDoc: PreXmlDoc * accessiblity: SynAccess option * range: range member this.Range = match this with SynExceptionDefnRepr (range=m) -> m @@ -1471,7 +1478,7 @@ and [] SynExceptionDefn = - | SynExceptionDefn of SynExceptionDefnRepr * SynMemberDefns * range:range + | SynExceptionDefn of SynExceptionDefnRepr * SynMemberDefns * range: range member this.Range = match this with @@ -1481,9 +1488,9 @@ and [] SynTypeDefnRepr = - | ObjectModel of SynTypeDefnKind * SynMemberDefns * range:range + | ObjectModel of SynTypeDefnKind * SynMemberDefns * range: range - | Simple of SynTypeDefnSimpleRepr * range:range + | Simple of SynTypeDefnSimpleRepr * range: range | Exception of SynExceptionDefnRepr @@ -1496,7 +1503,7 @@ and and [] SynTypeDefn = - | TypeDefn of SynComponentInfo * SynTypeDefnRepr * members:SynMemberDefns * range:range + | TypeDefn of SynComponentInfo * SynTypeDefnRepr * members: SynMemberDefns * range: range member this.Range = match this with | TypeDefn (range=m) -> m @@ -1505,47 +1512,47 @@ and [] SynMemberDefn = - | Open of longId:LongIdent * range:range + | Open of longId: LongIdent * range: range - | Member of memberDefn:SynBinding * range:range + | Member of memberDefn: SynBinding * range: range /// implicit ctor args as a defn line, 'as' specification - | ImplicitCtor of accessiblity:SynAccess option * attributes:SynAttributes * ctorArgs:SynSimplePat list * selfIdentifier:Ident option * range:range + | ImplicitCtor of accessiblity: SynAccess option * attributes: SynAttributes * ctorArgs: SynSimplePat list * selfIdentifier: Ident option * range: range /// inherit (args...) as base - | ImplicitInherit of inheritType:SynType * inheritArgs:SynExpr * inheritAlias:Ident option * range:range + | ImplicitInherit of inheritType: SynType * inheritArgs: SynExpr * inheritAlias: Ident option * range: range /// LetBindings(bindingList, isStatic, isRecursive, wholeRange) /// /// localDefns - | LetBindings of SynBinding list * isStatic:bool * isRecursive:bool * range:range + | LetBindings of SynBinding list * isStatic: bool * isRecursive: bool * range: range - | AbstractSlot of SynValSig * MemberFlags * range:range + | AbstractSlot of SynValSig * MemberFlags * range: range - | Interface of SynType * SynMemberDefns option * range:range + | Interface of SynType * SynMemberDefns option * range: range - | Inherit of SynType * Ident option * range:range + | Inherit of SynType * Ident option * range: range - | ValField of SynField * range:range + | ValField of SynField * range: range /// A feature that is not implemented - | NestedType of typeDefn:SynTypeDefn * accessibility:SynAccess option * range:range + | NestedType of typeDefn: SynTypeDefn * accessibility: SynAccess option * range: range /// SynMemberDefn.AutoProperty (attribs, isStatic, id, tyOpt, propKind, memberFlags, xmlDoc, access, synExpr, mGetSet, mWholeAutoProp). /// /// F# syntax: 'member val X = expr' | AutoProperty of - attribs:SynAttributes * - isStatic:bool * - ident:Ident * - typeOpt:SynType option * - propKind:MemberKind * + attribs: SynAttributes * + isStatic: bool * + ident: Ident * + typeOpt: SynType option * + propKind: MemberKind * memberFlags:(MemberKind -> MemberFlags) * - xmlDoc:PreXmlDoc * - accessiblity:SynAccess option * - synExpr:SynExpr * - getSetRange:range option * - range:range + xmlDoc: PreXmlDoc * + accessiblity: SynAccess option * + synExpr: SynExpr * + getSetRange: range option * + range: range member d.Range = match d with @@ -1566,15 +1573,15 @@ and SynMemberDefns = SynMemberDefn list and [] SynModuleDecl = - | ModuleAbbrev of ident:Ident * longId:LongIdent * range:range - | NestedModule of SynComponentInfo * isRecursive:bool * SynModuleDecls * bool * range:range - | Let of isRecursive:bool * SynBinding list * range:range - | DoExpr of SequencePointInfoForBinding * SynExpr * range:range - | Types of SynTypeDefn list * range:range - | Exception of SynExceptionDefn * range:range - | Open of longDotId:LongIdentWithDots * range:range - | Attributes of SynAttributes * range:range - | HashDirective of ParsedHashDirective * range:range + | ModuleAbbrev of ident: Ident * longId: LongIdent * range: range + | NestedModule of SynComponentInfo * isRecursive: bool * SynModuleDecls * bool * range: range + | Let of isRecursive: bool * SynBinding list * range: range + | DoExpr of SequencePointInfoForBinding * SynExpr * range: range + | Types of SynTypeDefn list * range: range + | Exception of SynExceptionDefn * range: range + | Open of longDotId: LongIdentWithDots * range: range + | Attributes of SynAttributes * range: range + | HashDirective of ParsedHashDirective * range: range | NamespaceFragment of SynModuleOrNamespace member d.Range = match d with @@ -1594,18 +1601,18 @@ and SynModuleDecls = SynModuleDecl list and [] SynExceptionSig = - | SynExceptionSig of SynExceptionDefnRepr * SynMemberSigs * range:range + | SynExceptionSig of SynExceptionDefnRepr * SynMemberSigs * range: range and [] SynModuleSigDecl = - | ModuleAbbrev of ident:Ident * longId:LongIdent * range:range - | NestedModule of SynComponentInfo * isRecursive:bool * SynModuleSigDecls * range:range - | Val of SynValSig * range:range - | Types of SynTypeDefnSig list * range:range - | Exception of SynExceptionSig * range:range - | Open of longId:LongIdent * range:range - | HashDirective of ParsedHashDirective * range:range + | ModuleAbbrev of ident: Ident * longId: LongIdent * range: range + | NestedModule of SynComponentInfo * isRecursive: bool * SynModuleSigDecls * range: range + | Val of SynValSig * range: range + | Types of SynTypeDefnSig list * range: range + | Exception of SynExceptionSig * range: range + | Open of longId: LongIdent * range: range + | HashDirective of ParsedHashDirective * range: range | NamespaceFragment of SynModuleOrNamespaceSig member d.Range = @@ -1637,7 +1644,7 @@ and and [] SynModuleOrNamespace = - | SynModuleOrNamespace of longId:LongIdent * isRecursive:bool * kind:SynModuleOrNamespaceKind * decls:SynModuleDecls * xmlDoc:PreXmlDoc * attribs:SynAttributes * accessibility:SynAccess option * range:range + | SynModuleOrNamespace of longId: LongIdent * isRecursive: bool * kind: SynModuleOrNamespaceKind * decls: SynModuleDecls * xmlDoc: PreXmlDoc * attribs: SynAttributes * accessibility: SynAccess option * range: range member this.Range = match this with | SynModuleOrNamespace (range=m) -> m @@ -1645,43 +1652,43 @@ and and [] SynModuleOrNamespaceSig = - | SynModuleOrNamespaceSig of longId:LongIdent * isRecursive:bool * kind:SynModuleOrNamespaceKind * SynModuleSigDecls * xmlDoc:PreXmlDoc * attribs:SynAttributes * accessibility:SynAccess option * range:range + | SynModuleOrNamespaceSig of longId: LongIdent * isRecursive: bool * kind: SynModuleOrNamespaceKind * SynModuleSigDecls * xmlDoc: PreXmlDoc * attribs: SynAttributes * accessibility: SynAccess option * range: range and [] ParsedHashDirective = - | ParsedHashDirective of string * string list * range:range + | ParsedHashDirective of string * string list * range: range [] type ParsedImplFileFragment = - | AnonModule of SynModuleDecls * range:range + | AnonModule of SynModuleDecls * range: range | NamedModule of SynModuleOrNamespace - | NamespaceFragment of longId:LongIdent * bool * SynModuleOrNamespaceKind * SynModuleDecls * xmlDoc:PreXmlDoc * SynAttributes * range:range + | NamespaceFragment of longId: LongIdent * bool * SynModuleOrNamespaceKind * SynModuleDecls * xmlDoc: PreXmlDoc * SynAttributes * range: range [] type ParsedSigFileFragment = - | AnonModule of SynModuleSigDecls * range:range + | AnonModule of SynModuleSigDecls * range: range | NamedModule of SynModuleOrNamespaceSig - | NamespaceFragment of longId:LongIdent * bool * SynModuleOrNamespaceKind * SynModuleSigDecls * xmlDoc:PreXmlDoc * SynAttributes * range:range + | NamespaceFragment of longId: LongIdent * bool * SynModuleOrNamespaceKind * SynModuleSigDecls * xmlDoc: PreXmlDoc * SynAttributes * range: range [] type ParsedFsiInteraction = - | IDefns of SynModuleDecl list * range:range - | IHash of ParsedHashDirective * range:range + | IDefns of SynModuleDecl list * range: range + | IHash of ParsedHashDirective * range: range [] type ParsedImplFile = - | ParsedImplFile of hashDirectives:ParsedHashDirective list * ParsedImplFileFragment list + | ParsedImplFile of hashDirectives: ParsedHashDirective list * ParsedImplFileFragment list [] type ParsedSigFile = - | ParsedSigFile of hashDirectives:ParsedHashDirective list * ParsedSigFileFragment list + | ParsedSigFile of hashDirectives: ParsedHashDirective list * ParsedSigFileFragment list //---------------------------------------------------------------------- // AST and parsing utilities. //---------------------------------------------------------------------- let ident (s, r) = new Ident(s, r) -let textOfId (id:Ident) = id.idText +let textOfId (id: Ident) = id.idText let pathOfLid lid = List.map textOfId lid let arrPathOfLid lid = Array.ofList (pathOfLid lid) let textOfPath path = String.concat "." path @@ -1695,7 +1702,7 @@ let rangeOfLid (lid: Ident list) = [] type ScopedPragma = - | WarningOff of range:range * int + | WarningOff of range: range * int // Note: this type may be extended in the future with optimization on/off switches etc. // These are the results of parsing + folding in the implicit file name @@ -1716,22 +1723,22 @@ type QualifiedNameOfFile = [] type ParsedImplFileInput = | ParsedImplFileInput of - fileName : string * - isScript : bool * - qualifiedNameOfFile : QualifiedNameOfFile * - scopedPragmas : ScopedPragma list * - hashDirectives : ParsedHashDirective list * - modules : SynModuleOrNamespace list * + fileName: string * + isScript: bool * + qualifiedNameOfFile: QualifiedNameOfFile * + scopedPragmas: ScopedPragma list * + hashDirectives: ParsedHashDirective list * + modules: SynModuleOrNamespace list * isLastCompiland: (bool * bool) [] type ParsedSigFileInput = | ParsedSigFileInput of - fileName : string * - qualifiedNameOfFile : QualifiedNameOfFile * - scopedPragmas : ScopedPragma list * - hashDirectives : ParsedHashDirective list * - modules : SynModuleOrNamespaceSig list + fileName: string * + qualifiedNameOfFile: QualifiedNameOfFile * + scopedPragmas: ScopedPragma list * + hashDirectives: ParsedHashDirective list * + modules: SynModuleOrNamespaceSig list [] type ParsedInput = @@ -1818,8 +1825,8 @@ let rec IsControlFlowExpression e = let mkAnonField (ty: SynType) = Field([], false, None, ty, false, PreXmlDoc.Empty, None, ty.Range) let mkNamedField (ident, ty: SynType) = Field([], false, Some ident, ty, false, PreXmlDoc.Empty, None, ty.Range) -let mkSynPatVar vis (id:Ident) = SynPat.Named (SynPat.Wild id.idRange, id, false, vis, id.idRange) -let mkSynThisPatVar (id:Ident) = SynPat.Named (SynPat.Wild id.idRange, id, true, None, id.idRange) +let mkSynPatVar vis (id: Ident) = SynPat.Named (SynPat.Wild id.idRange, id, false, vis, id.idRange) +let mkSynThisPatVar (id: Ident) = SynPat.Named (SynPat.Wild id.idRange, id, true, None, id.idRange) let mkSynPatMaybeVar lidwd vis m = SynPat.LongIdent (lidwd, None, None, SynConstructorArgs.Pats [], vis, m) /// Extract the argument for patterns corresponding to the declaration of 'new ... = ...' @@ -1834,17 +1841,17 @@ let (|SynPatForNullaryArgs|_|) x = | SynPat.Paren(SynPat.Const(SynConst.Unit, _), _) -> Some() | _ -> None -let (|SynExprErrorSkip|) (p:SynExpr) = +let (|SynExprErrorSkip|) (p: SynExpr) = match p with | SynExpr.FromParseError(p, _) -> p | _ -> p -let (|SynExprParen|_|) (e:SynExpr) = +let (|SynExprParen|_|) (e: SynExpr) = match e with | SynExpr.Paren(SynExprErrorSkip e, a, b, c) -> Some (e, a, b, c) | _ -> None -let (|SynPatErrorSkip|) (p:SynPat) = +let (|SynPatErrorSkip|) (p: SynPat) = match p with | SynPat.FromParseError(p, _) -> p | _ -> p @@ -1995,7 +2002,7 @@ let opNameParenGet = CompileOpName parenGet let opNameQMark = CompileOpName qmark let mkSynOperator opm oper = mkSynIdGet opm (CompileOpName oper) -let mkSynInfix opm (l:SynExpr) oper (r:SynExpr) = +let mkSynInfix opm (l: SynExpr) oper (r: SynExpr) = let firstTwoRange = unionRanges l.Range opm let wholeRange = unionRanges l.Range r.Range SynExpr.App (ExprAtomicFlag.NonAtomic, false, SynExpr.App (ExprAtomicFlag.NonAtomic, true, mkSynOperator opm oper, l, firstTwoRange), r, wholeRange) @@ -2029,7 +2036,7 @@ let mkSynDotBrackGet m mDot a b = SynExpr.DotIndexedGet(a, [SynIndexerArg.One let mkSynQMarkSet m a b c = mkSynTrifix m qmarkSet a b c let mkSynDotBrackSliceGet m mDot arr sliceArg = SynExpr.DotIndexedGet(arr, [sliceArg], mDot, m) -let mkSynDotBrackSeqSliceGet m mDot arr (argslist:list) = +let mkSynDotBrackSeqSliceGet m mDot arr (argslist: list) = let notsliced=[ for arg in argslist do match arg with | SynIndexerArg.One x -> yield x @@ -2095,7 +2102,7 @@ let mkSynFunMatchLambdas synArgNameGenerator isMember wholem ps e = // error recovery - the contract is that these expressions can only be produced if an error has already been reported // (as a result, future checking may choose not to report errors involving these, to prevent noisy cascade errors) -let arbExpr(debugStr, range:range) = SynExpr.ArbitraryAfterError(debugStr, range.MakeSynthetic()) +let arbExpr(debugStr, range: range) = SynExpr.ArbitraryAfterError(debugStr, range.MakeSynthetic()) type SynExpr with member this.IsArbExprAndThusAlreadyReportedError = match this with @@ -2106,7 +2113,7 @@ type SynExpr with /// mostly dummy information to make the return element look like an argument, /// the important thing is that (a) you can give a return type for the function or method, and /// (b) you can associate .NET attributes to return of a function or method and these get stored in .NET metadata. -type SynReturnInfo = SynReturnInfo of (SynType * SynArgInfo) * range:range +type SynReturnInfo = SynReturnInfo of (SynType * SynArgInfo) * range: range /// Operations related to the syntactic analysis of arguments of value, function and member definitions and signatures. @@ -2305,19 +2312,19 @@ type LexerIfdefStack = LexerIfdefStackEntries ref /// or to continue with 'skip' function. type LexerEndlineContinuation = | Token of LexerIfdefStackEntries - | Skip of LexerIfdefStackEntries * int * range:range + | Skip of LexerIfdefStackEntries * int * range: range member x.LexerIfdefStack = match x with | LexerEndlineContinuation.Token(ifd) | LexerEndlineContinuation.Skip(ifd, _, _) -> ifd type LexerIfdefExpression = - | IfdefAnd of LexerIfdefExpression*LexerIfdefExpression - | IfdefOr of LexerIfdefExpression*LexerIfdefExpression - | IfdefNot of LexerIfdefExpression - | IfdefId of string + | IfdefAnd of LexerIfdefExpression*LexerIfdefExpression + | IfdefOr of LexerIfdefExpression*LexerIfdefExpression + | IfdefNot of LexerIfdefExpression + | IfdefId of string -let rec LexerIfdefEval (lookup : string -> bool) = function +let rec LexerIfdefEval (lookup: string -> bool) = function | IfdefAnd (l, r) -> (LexerIfdefEval lookup l) && (LexerIfdefEval lookup r) | IfdefOr (l, r) -> (LexerIfdefEval lookup l) || (LexerIfdefEval lookup r) | IfdefNot e -> not (LexerIfdefEval lookup e) @@ -2330,18 +2337,18 @@ let rec LexerIfdefEval (lookup : string -> bool) = function [] [] type LexerWhitespaceContinuation = - | Token of ifdef:LexerIfdefStackEntries - | IfDefSkip of ifdef:LexerIfdefStackEntries * int * range:range - | String of ifdef:LexerIfdefStackEntries * range:range - | VerbatimString of ifdef:LexerIfdefStackEntries * range:range - | TripleQuoteString of ifdef:LexerIfdefStackEntries * range:range - | Comment of ifdef:LexerIfdefStackEntries * int * range:range - | SingleLineComment of ifdef:LexerIfdefStackEntries * int * range:range - | StringInComment of ifdef:LexerIfdefStackEntries * int * range:range - | VerbatimStringInComment of ifdef:LexerIfdefStackEntries * int * range:range - | TripleQuoteStringInComment of ifdef:LexerIfdefStackEntries * int * range:range - | MLOnly of ifdef:LexerIfdefStackEntries * range:range - | EndLine of LexerEndlineContinuation + | Token of ifdef: LexerIfdefStackEntries + | IfDefSkip of ifdef: LexerIfdefStackEntries * int * range: range + | String of ifdef: LexerIfdefStackEntries * range: range + | VerbatimString of ifdef: LexerIfdefStackEntries * range: range + | TripleQuoteString of ifdef: LexerIfdefStackEntries * range: range + | Comment of ifdef: LexerIfdefStackEntries * int * range: range + | SingleLineComment of ifdef: LexerIfdefStackEntries * int * range: range + | StringInComment of ifdef: LexerIfdefStackEntries * int * range: range + | VerbatimStringInComment of ifdef: LexerIfdefStackEntries * int * range: range + | TripleQuoteStringInComment of ifdef: LexerIfdefStackEntries * int * range: range + | MLOnly of ifdef: LexerIfdefStackEntries * range: range + | EndLine of LexerEndlineContinuation member x.LexerIfdefStack = match x with @@ -2369,14 +2376,14 @@ and LexCont = LexerWhitespaceContinuation /// information about the grammar at the point where the error occurred, e.g. what tokens /// are valid to shift next at that point in the grammar. This information is processed in CompileOps.fs. [] -exception SyntaxError of obj (* ParseErrorContext<_> *) * range:range +exception SyntaxError of obj (* ParseErrorContext<_> *) * range: range /// Get an F# compiler position from a lexer position -let internal posOfLexPosition (p:Position) = +let internal posOfLexPosition (p: Position) = mkPos p.Line p.Column /// Get an F# compiler range from a lexer range -let internal mkSynRange (p1:Position) (p2: Position) = +let internal mkSynRange (p1: Position) (p2: Position) = mkFileIndexRange p1.FileIndex (posOfLexPosition p1) (posOfLexPosition p2) type LexBuffer<'Char> with @@ -2422,11 +2429,11 @@ module LexbufLocalXmlDocStore = // The key into the BufferLocalStore used to hold the current accumulated XmlDoc lines let private xmlDocKey = "XmlDoc" - let internal ClearXmlDoc (lexbuf:Lexbuf) = + let internal ClearXmlDoc (lexbuf: Lexbuf) = lexbuf.BufferLocalStore.[xmlDocKey] <- box (XmlDocCollector()) /// Called from the lexer to save a single line of XML doc comment. - let internal SaveXmlDocLine (lexbuf:Lexbuf, lineText, pos) = + let internal SaveXmlDocLine (lexbuf: Lexbuf, lineText, pos) = let collector = match lexbuf.BufferLocalStore.TryGetValue(xmlDocKey) with | true, collector -> collector @@ -2439,7 +2446,7 @@ module LexbufLocalXmlDocStore = /// Called from the parser each time we parse a construct that marks the end of an XML doc comment range, /// e.g. a 'type' declaration. The markerRange is the range of the keyword that delimits the construct. - let internal GrabXmlDocBeforeMarker (lexbuf:Lexbuf, markerRange:range) = + let internal GrabXmlDocBeforeMarker (lexbuf: Lexbuf, markerRange: range) = match lexbuf.BufferLocalStore.TryGetValue(xmlDocKey) with | true, collector -> let collector = unbox(collector) @@ -2461,7 +2468,7 @@ type NiceNameGenerator() = let lockObj = obj() let basicNameCounts = new Dictionary(100) - member x.FreshCompilerGeneratedName (name, m:range) = + member x.FreshCompilerGeneratedName (name, m: range) = lock lockObj (fun () -> let basicName = GetBasicNameOfPossibleCompilerGeneratedName name let n = @@ -2492,7 +2499,7 @@ type StableNiceNameGenerator() = let names = new Dictionary<(string * int64), string>(100) let basicNameCounts = new Dictionary(100) - member x.GetUniqueCompilerGeneratedName (name, m:range, uniq) = + member x.GetUniqueCompilerGeneratedName (name, m: range, uniq) = lock lockObj (fun () -> let basicName = GetBasicNameOfPossibleCompilerGeneratedName name let key = basicName, uniq diff --git a/src/fsharp/fsc.fs b/src/fsharp/fsc.fs index 5fb034373fc..ecc94eef7fd 100644 --- a/src/fsharp/fsc.fs +++ b/src/fsharp/fsc.fs @@ -96,7 +96,7 @@ type ErrorLoggerUpToMaxErrors(tcConfigB: TcConfigBuilder, exiter: Exiter, nameFo /// Create an error logger that counts and prints errors -let ConsoleErrorLoggerUpToMaxErrors (tcConfigB:TcConfigBuilder, exiter : Exiter) = +let ConsoleErrorLoggerUpToMaxErrors (tcConfigB: TcConfigBuilder, exiter : Exiter) = { new ErrorLoggerUpToMaxErrors(tcConfigB, exiter, "ConsoleErrorLoggerUpToMaxErrors") with member __.HandleTooManyErrors(text : string) = @@ -114,7 +114,7 @@ let ConsoleErrorLoggerUpToMaxErrors (tcConfigB:TcConfigBuilder, exiter : Exiter) type DelayAndForwardErrorLogger(exiter: Exiter, errorLoggerProvider: ErrorLoggerProvider) = inherit CapturingErrorLogger("DelayAndForwardErrorLogger") - member x.ForwardDelayedDiagnostics(tcConfigB:TcConfigBuilder) = + member x.ForwardDelayedDiagnostics(tcConfigB: TcConfigBuilder) = let errorLogger = errorLoggerProvider.CreateErrorLoggerUpToMaxErrors(tcConfigB, exiter) x.CommitDelayedDiagnostics(errorLogger) @@ -163,7 +163,7 @@ type ConsoleLoggerProvider() = override this.CreateErrorLoggerUpToMaxErrors(tcConfigBuilder, exiter) = ConsoleErrorLoggerUpToMaxErrors(tcConfigBuilder, exiter) /// Notify the exiter if any error has occurred -let AbortOnError (errorLogger:ErrorLogger, exiter : Exiter) = +let AbortOnError (errorLogger: ErrorLogger, exiter : Exiter) = if errorLogger.ErrorCount > 0 then exiter.Exit 1 @@ -187,7 +187,7 @@ type DisposablesTracker() = try i.Dispose() with _ -> () -let TypeCheck (ctok, tcConfig, tcImports, tcGlobals, errorLogger:ErrorLogger, assemblyName, niceNameGen, tcEnv0, inputs, exiter: Exiter) = +let TypeCheck (ctok, tcConfig, tcImports, tcGlobals, errorLogger: ErrorLogger, assemblyName, niceNameGen, tcEnv0, inputs, exiter: Exiter) = try if isNil inputs then error(Error(FSComp.SR.fscNoImplementationFiles(), Range.rangeStartup)) let ccuName = assemblyName @@ -198,7 +198,7 @@ let TypeCheck (ctok, tcConfig, tcImports, tcGlobals, errorLogger:ErrorLogger, as exiter.Exit 1 /// Check for .fsx and, if present, compute the load closure for of #loaded files. -let AdjustForScriptCompile(ctok, tcConfigB:TcConfigBuilder, commandLineSourceFiles, lexResourceManager) = +let AdjustForScriptCompile(ctok, tcConfigB: TcConfigBuilder, commandLineSourceFiles, lexResourceManager) = let combineFilePath file = try @@ -215,7 +215,7 @@ let AdjustForScriptCompile(ctok, tcConfigB:TcConfigBuilder, commandLineSourceFil let tcConfig = TcConfig.Create(tcConfigB, validate=false) - let AddIfNotPresent(filename:string) = + let AddIfNotPresent(filename: string) = if not(!allSources |> List.contains filename) then allSources := filename::!allSources @@ -301,7 +301,7 @@ module InterfaceFileWriter = FSharpLib.ControlPath (IL.splitNamespace FSharpLib.ExtraTopLevelOperatorsName) ] - let WriteInterfaceFile (tcGlobals, tcConfig:TcConfig, infoReader, declaredImpls) = + let WriteInterfaceFile (tcGlobals, tcConfig: TcConfig, infoReader, declaredImpls) = /// Use a UTF-8 Encoding with no Byte Order Mark let os = @@ -332,11 +332,11 @@ module XmlDocWriter = | XmlDoc [| |] -> false | _ -> true - let computeXmlDocSigs (tcGlobals, generatedCcu:CcuThunk) = + let computeXmlDocSigs (tcGlobals, generatedCcu: CcuThunk) = (* the xmlDocSigOf* functions encode type into string to be used in "id" *) let g = tcGlobals - let doValSig ptext (v:Val) = if (hasDoc v.XmlDoc) then v.XmlDocSig <- XmlDocSigOfVal g ptext v - let doTyconSig ptext (tc:Tycon) = + let doValSig ptext (v: Val) = if (hasDoc v.XmlDoc) then v.XmlDocSig <- XmlDocSigOfVal g ptext v + let doTyconSig ptext (tc: Tycon) = if (hasDoc tc.XmlDoc) then tc.XmlDocSig <- XmlDocSigOfTycon [ptext; tc.CompiledName] for vref in tc.MembersOfFSharpTyconSorted do doValSig ptext vref.Deref @@ -351,9 +351,9 @@ module XmlDocWriter = else XmlDocSigOfField [ptext; tc.CompiledName; rf.Id.idText] - let doModuleMemberSig path (m:ModuleOrNamespace) = m.XmlDocSig <- XmlDocSigOfSubModul [path] + let doModuleMemberSig path (m: ModuleOrNamespace) = m.XmlDocSig <- XmlDocSigOfSubModul [path] (* moduleSpec - recurses *) - let rec doModuleSig path (mspec:ModuleOrNamespace) = + let rec doModuleSig path (mspec: ModuleOrNamespace) = let mtype = mspec.ModuleOrNamespaceType let path = (* skip the first item in the path which is the assembly name *) @@ -375,7 +375,7 @@ module XmlDocWriter = doModuleSig None generatedCcu.Contents - let writeXmlDoc (assemblyName, generatedCcu:CcuThunk, xmlfile) = + let writeXmlDoc (assemblyName, generatedCcu: CcuThunk, xmlfile) = if not (Filename.hasSuffixCaseInsensitive "xml" xmlfile ) then error(Error(FSComp.SR.docfileNoXmlSuffix(), Range.rangeStartup)) (* the xmlDocSigOf* functions encode type into string to be used in "id" *) @@ -384,10 +384,10 @@ module XmlDocWriter = if hasDoc xmlDoc then let doc = getDoc xmlDoc members := (id, doc) :: !members - let doVal (v:Val) = addMember v.XmlDocSig v.XmlDoc - let doUnionCase (uc:UnionCase) = addMember uc.XmlDocSig uc.XmlDoc - let doField (rf:RecdField) = addMember rf.XmlDocSig rf.XmlDoc - let doTycon (tc:Tycon) = + let doVal (v: Val) = addMember v.XmlDocSig v.XmlDoc + let doUnionCase (uc: UnionCase) = addMember uc.XmlDocSig uc.XmlDoc + let doField (rf: RecdField) = addMember rf.XmlDocSig rf.XmlDoc + let doTycon (tc: Tycon) = addMember tc.XmlDocSig tc.XmlDoc for vref in tc.MembersOfFSharpTyconSorted do doVal vref.Deref @@ -396,10 +396,10 @@ module XmlDocWriter = for rf in tc.AllFieldsArray do doField rf - let modulMember (m:ModuleOrNamespace) = addMember m.XmlDocSig m.XmlDoc + let modulMember (m: ModuleOrNamespace) = addMember m.XmlDocSig m.XmlDoc (* moduleSpec - recurses *) - let rec doModule (mspec:ModuleOrNamespace) = + let rec doModule (mspec: ModuleOrNamespace) = let mtype = mspec.ModuleOrNamespaceType if mspec.IsModule then modulMember mspec let vals = @@ -430,7 +430,7 @@ module XmlDocWriter = let DefaultFSharpBinariesDir = FSharpEnvironment.BinFolderOfDefaultFSharpCompiler(FSharpEnvironment.tryCurrentDomain()).Value -let GenerateInterfaceData(tcConfig:TcConfig) = +let GenerateInterfaceData(tcConfig: TcConfig) = not tcConfig.standalone && not tcConfig.noSignatureData let EncodeInterfaceData(tcConfig: TcConfig, tcGlobals, exportRemapping, generatedCcu, outfile, isIncrementalBuild) = @@ -482,11 +482,11 @@ module BinaryGenerationUtilities = let b2 n = byte ((n >>> 16) &&& 0xFF) let b3 n = byte ((n >>> 24) &&& 0xFF) - let i16 (i:int32) = [| b0 i; b1 i |] - let i32 (i:int32) = [| b0 i; b1 i; b2 i; b3 i |] + let i16 (i: int32) = [| b0 i; b1 i |] + let i32 (i: int32) = [| b0 i; b1 i; b2 i; b3 i |] // Emit the bytes and pad to a 32-bit alignment - let Padded initialAlignment (v:byte[]) = + let Padded initialAlignment (v: byte[]) = [| yield! v for _ in 1..(4 - (initialAlignment + v.Length) % 4) % 4 do yield 0x0uy |] @@ -496,7 +496,7 @@ module BinaryGenerationUtilities = module ResFileFormat = open BinaryGenerationUtilities - let ResFileNode(dwTypeID, dwNameID, wMemFlags, wLangID, data:byte[]) = + let ResFileNode(dwTypeID, dwNameID, wMemFlags, wLangID, data: byte[]) = [| yield! i32 data.Length // DWORD ResHdr.dwDataSize yield! i32 0x00000020 // dwHeaderSize yield! i32 ((dwTypeID <<< 16) ||| 0x0000FFFF) // dwTypeID, sizeof(DWORD) @@ -516,11 +516,11 @@ module ResFileFormat = module VersionResourceFormat = open BinaryGenerationUtilities - let VersionInfoNode(data:byte[]) = + let VersionInfoNode(data: byte[]) = [| yield! i16 (data.Length + 2) // wLength : int16 // Specifies the length, in bytes, of the VS_VERSION_INFO structure. yield! data |] - let VersionInfoElement(wType, szKey, valueOpt: byte[] option, children:byte[][], isString) = + let VersionInfoElement(wType, szKey, valueOpt: byte[] option, children: byte[][], isString) = // for String structs, wValueLength represents the word count, not the byte count let wValueLength = (match valueOpt with None -> 0 | Some value -> (if isString then value.Length / 2 else value.Length)) VersionInfoNode @@ -582,12 +582,12 @@ module VersionResourceFormat = yield! i16 codePage |]), [| |], false) |] VersionInfoElement(wType, szKey, None, children, false) - let VS_FIXEDFILEINFO(fileVersion:ILVersionInfo, - productVersion:ILVersionInfo, + let VS_FIXEDFILEINFO(fileVersion: ILVersionInfo, + productVersion: ILVersionInfo, dwFileFlagsMask, dwFileFlags, dwFileOS, dwFileType, dwFileSubtype, - lwFileDate:int64) = + lwFileDate: int64) = let dwStrucVersion = 0x00010000 [| // DWORD dwSignature // Contains the value 0xFEEFO4BD. yield! i32 0xFEEF04BD @@ -788,7 +788,7 @@ module MainModuleBuilder = Seq.map (fun t -> mkTypeForwarder (tcGlobals.ilg.primaryAssemblyScopeRef) t (mkILNestedExportedTypes List.empty) (mkILCustomAttrs List.empty) ILTypeDefAccess.Public ) |> Seq.toList - let createSystemNumericsExportList (tcConfig: TcConfig) (tcImports:TcImports) = + let createSystemNumericsExportList (tcConfig: TcConfig) (tcImports: TcImports) = let refNumericsDllName = if (tcConfig.primaryAssembly.Name = "mscorlib") then "System.Numerics" else "System.Runtime.Numerics" @@ -845,7 +845,7 @@ module MainModuleBuilder = let CreateMainModule - (ctok, tcConfig:TcConfig, tcGlobals, tcImports:TcImports, + (ctok, tcConfig: TcConfig, tcGlobals, tcImports: TcImports, pdbfile, assemblyName, outfile, topAttrs, (iattrs, intfDataResources), optDataResources, codegenResults, assemVerFromAttrib, metadataVersion, secDecls) = @@ -1211,7 +1211,7 @@ module StaticLinker = // build new FSharp.Core for that configuration. // // Find all IL modules that are to be statically linked given the static linking roots. - let LegacyFindAndAddMscorlibTypesForStaticLinkingIntoFSharpCoreLibraryForNet20 (tcConfig:TcConfig, ilGlobals:ILGlobals, ilxMainModule) = + let LegacyFindAndAddMscorlibTypesForStaticLinkingIntoFSharpCoreLibraryForNet20 (tcConfig: TcConfig, ilGlobals: ILGlobals, ilxMainModule) = let mscorlib40 = tcConfig.compilingFslib20.Value let ilBinaryReader = @@ -1274,7 +1274,7 @@ module StaticLinker = mutable visited: bool } // Find all IL modules that are to be statically linked given the static linking roots. - let FindDependentILModulesForStaticLinking (ctok, tcConfig:TcConfig, tcImports:TcImports, ilGlobals, ilxMainModule) = + let FindDependentILModulesForStaticLinking (ctok, tcConfig: TcConfig, tcImports: TcImports, ilGlobals, ilxMainModule) = if not tcConfig.standalone && tcConfig.extraStaticLinkRoots.IsEmpty then [] else @@ -1387,7 +1387,7 @@ module StaticLinker = yield (n.ccu, n.data) ] // Add all provider-generated assemblies into the static linking set - let FindProviderGeneratedILModules (ctok, tcImports:TcImports, providerGeneratedAssemblies: (ImportedBinary * _) list) = + let FindProviderGeneratedILModules (ctok, tcImports: TcImports, providerGeneratedAssemblies: (ImportedBinary * _) list) = [ for (importedBinary, provAssemStaticLinkInfo) in providerGeneratedAssemblies do let ilAssemRef = importedBinary.ILScopeRef.AssemblyRef if debugStaticLinking then printfn "adding provider-generated assembly '%s' into static linking set" ilAssemRef.Name @@ -1405,13 +1405,13 @@ module StaticLinker = // Compute a static linker. This only captures tcImports (a large data structure) if // static linking is enabled. Normally this is not the case, which lets us collect tcImports // prior to this point. - let StaticLink (ctok, tcConfig:TcConfig, tcImports:TcImports, ilGlobals:ILGlobals) = + let StaticLink (ctok, tcConfig: TcConfig, tcImports: TcImports, ilGlobals: ILGlobals) = #if !NO_EXTENSIONTYPING let providerGeneratedAssemblies = [ // Add all EST-generated assemblies into the static linking set - for KeyValue(_, importedBinary:ImportedBinary) in tcImports.DllTable do + for KeyValue(_, importedBinary: ImportedBinary) in tcImports.DllTable do if importedBinary.IsProviderGenerated then match importedBinary.ProviderGeneratedStaticLinkMap with | None -> () @@ -1470,7 +1470,7 @@ module StaticLinker = // Build a dictionary of all IL type defs, mapping ilOrigTyRef --> ilTypeDef let allTypeDefsInProviderGeneratedAssemblies = - let rec loop ilOrigTyRef (ilTypeDef:ILTypeDef) = + let rec loop ilOrigTyRef (ilTypeDef: ILTypeDef) = seq { yield (ilOrigTyRef, ilTypeDef) for ntdef in ilTypeDef.NestedTypes do yield! loop (mkILTyRefInTyRef (ilOrigTyRef, ntdef.Name)) ntdef } @@ -1528,7 +1528,7 @@ module StaticLinker = loop xs [] /// Implant the (nested) type definition 'td' at path 'enc' in 'tdefs'. - let rec implantTypeDef isNested (tdefs: ILTypeDefs) (enc:string list) (td: ILTypeDef) = + let rec implantTypeDef isNested (tdefs: ILTypeDefs) (enc: string list) (td: ILTypeDef) = match enc with | [] -> addILTypeDef td tdefs | h::t -> @@ -1697,8 +1697,8 @@ let CopyFSharpCore(outFile: string, referencedDlls: AssemblyReference list) = type Args<'T> = Args of 'T let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, - reduceMemoryUsage:ReduceMemoryFlag, defaultCopyFSharpCore: CopyFSharpCoreFlag, - exiter:Exiter, errorLoggerProvider : ErrorLoggerProvider, disposables : DisposablesTracker) = + reduceMemoryUsage: ReduceMemoryFlag, defaultCopyFSharpCore: CopyFSharpCoreFlag, + exiter: Exiter, errorLoggerProvider : ErrorLoggerProvider, disposables : DisposablesTracker) = // See Bug 735819 let lcidFromCodePage = @@ -1821,7 +1821,7 @@ let main0(ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, let isLastCompiland, isExe = sourceFiles |> tcConfig.ComputeCanContainEntryPoint isLastCompiland |> List.zip sourceFiles // PERF: consider making this parallel, once uses of global state relevant to parsing are cleaned up - |> List.choose (fun (filename:string, isLastCompiland) -> + |> List.choose (fun (filename: string, isLastCompiland) -> let pathOfMetaCommandSource = Path.GetDirectoryName(filename) match ParseOneInputFile(tcConfig, lexResourceManager, ["COMPILED"], filename, (isLastCompiland, isExe), errorLogger, (*retryLocked*)false) with | Some input -> Some (input, pathOfMetaCommandSource) @@ -2086,7 +2086,7 @@ let main2b Args (ctok, tcConfig, tcImports, tcGlobals, errorLogger, staticLinker, outfile, pdbfile, ilxMainModule, signingInfo, exiter) /// Phase 3: static linking -let main3(Args (ctok, tcConfig, tcImports, tcGlobals, errorLogger: ErrorLogger, staticLinker, outfile, pdbfile, ilxMainModule, signingInfo, exiter:Exiter)) = +let main3(Args (ctok, tcConfig, tcImports, tcGlobals, errorLogger: ErrorLogger, staticLinker, outfile, pdbfile, ilxMainModule, signingInfo, exiter: Exiter)) = use unwindBuildPhase = PushThreadBuildPhaseUntilUnwind BuildPhase.Output @@ -2116,7 +2116,7 @@ let main4 dynamicAssemblyCreator (Args (ctok, tcConfig, tcImports: TcImports, t let pdbfile = pdbfile |> Option.map (tcConfig.MakePathAbsolute >> FileSystem.GetFullPathShim) - let normalizeAssemblyRefs (aref:ILAssemblyRef) = + let normalizeAssemblyRefs (aref: ILAssemblyRef) = match tcImports.TryFindDllInfo (ctok, Range.rangeStartup, aref.Name, lookupOnly=false) with | Some dllInfo -> match dllInfo.ILScopeRef with @@ -2167,7 +2167,7 @@ let main4 dynamicAssemblyCreator (Args (ctok, tcConfig, tcImports: TcImports, t /// Entry point typecheckAndCompile let typecheckAndCompile (ctok, argv, legacyReferenceResolver, bannerAlreadyPrinted, reduceMemoryUsage, - defaultCopyFSharpCore, exiter:Exiter, errorLoggerProvider, tcImportsCapture, dynamicAssemblyCreator) = + defaultCopyFSharpCore, exiter: Exiter, errorLoggerProvider, tcImportsCapture, dynamicAssemblyCreator) = use d = new DisposablesTracker() use e = new SaveAndRestoreConsoleEncoding() diff --git a/src/fsharp/import.fs b/src/fsharp/import.fs index e6709a3d007..2bbb90d638a 100644 --- a/src/fsharp/import.fs +++ b/src/fsharp/import.fs @@ -52,13 +52,13 @@ type AssemblyLoader = /// using tcImports.GetImportMap() if needed, and it is not harmful if multiple instances are used. The object /// serves as an interface through to the tables stored in the primary TcImports structures defined in CompileOps.fs. [] -type ImportMap(g:TcGlobals, assemblyLoader:AssemblyLoader) = +type ImportMap(g: TcGlobals, assemblyLoader: AssemblyLoader) = let typeRefToTyconRefCache = ConcurrentDictionary() member this.g = g member this.assemblyLoader = assemblyLoader member this.ILTypeRefToTyconRefCache = typeRefToTyconRefCache -let CanImportILScopeRef (env:ImportMap) m scoref = +let CanImportILScopeRef (env: ImportMap) m scoref = match scoref with | ILScopeRef.Local -> true | ILScopeRef.Module _ -> true @@ -74,7 +74,7 @@ let CanImportILScopeRef (env:ImportMap) m scoref = /// Import a reference to a type definition, given the AbstractIL data for the type reference -let ImportTypeRefData (env:ImportMap) m (scoref, path, typeName) = +let ImportTypeRefData (env: ImportMap) m (scoref, path, typeName) = // Explanation: This represents an unchecked invariant in the hosted compiler: that any operations // which import types (and resolve assemblies from the tcImports tables) happen on the compilation thread. @@ -119,7 +119,7 @@ let ImportTypeRefData (env:ImportMap) m (scoref, path, typeName) = // For example, // Foo.Bar,"1.0" // This is because ImportProvidedType goes via Abstract IL type references. -let ImportILTypeRefUncached (env:ImportMap) m (tref:ILTypeRef) = +let ImportILTypeRefUncached (env: ImportMap) m (tref: ILTypeRef) = let path, typeName = match tref.Enclosing with | [] -> @@ -129,11 +129,11 @@ let ImportILTypeRefUncached (env:ImportMap) m (tref:ILTypeRef) = // Note, subsequent type names do not need to be split, only the first [| yield! nsp; yield tname; yield! t |], tref.Name - ImportTypeRefData (env:ImportMap) m (tref.Scope, path, typeName) + ImportTypeRefData (env: ImportMap) m (tref.Scope, path, typeName) /// Import a reference to a type definition, given an AbstractIL ILTypeRef, with caching -let ImportILTypeRef (env:ImportMap) m (tref:ILTypeRef) = +let ImportILTypeRef (env: ImportMap) m (tref: ILTypeRef) = match env.ILTypeRefToTyconRefCache.TryGetValue(tref) with | true, tcref -> tcref | _ -> @@ -142,18 +142,18 @@ let ImportILTypeRef (env:ImportMap) m (tref:ILTypeRef) = tcref /// Import a reference to a type definition, given an AbstractIL ILTypeRef, with caching -let CanImportILTypeRef (env:ImportMap) m (tref:ILTypeRef) = +let CanImportILTypeRef (env: ImportMap) m (tref: ILTypeRef) = env.ILTypeRefToTyconRefCache.ContainsKey(tref) || CanImportILScopeRef env m tref.Scope /// Import a type, given an AbstractIL ILTypeRef and an F# type instantiation. /// /// Prefer the F# abbreviation for some built-in types, e.g. 'string' rather than /// 'System.String', since we prefer the F# abbreviation to the .NET equivalents. -let ImportTyconRefApp (env:ImportMap) tcref tyargs = +let ImportTyconRefApp (env: ImportMap) tcref tyargs = env.g.improveType tcref tyargs /// Import an IL type as an F# type. -let rec ImportILType (env:ImportMap) m tinst ty = +let rec ImportILType (env: ImportMap) m tinst ty = match ty with | ILType.Void -> env.g.unit_ty @@ -180,7 +180,7 @@ let rec ImportILType (env:ImportMap) m tinst ty = with _ -> error(Error(FSComp.SR.impNotEnoughTypeParamsInScopeWhileImporting(), m)) -let rec CanImportILType (env:ImportMap) m ty = +let rec CanImportILType (env: ImportMap) m ty = match ty with | ILType.Void -> true | ILType.Array(_bounds, ety) -> CanImportILType env m ety @@ -196,7 +196,7 @@ let rec CanImportILType (env:ImportMap) m ty = #if !NO_EXTENSIONTYPING /// Import a provided type reference as an F# type TyconRef -let ImportProvidedNamedType (env:ImportMap) (m:range) (st:Tainted) = +let ImportProvidedNamedType (env: ImportMap) (m: range) (st: Tainted) = // See if a reverse-mapping exists for a generated/relocated System.Type match st.PUntaint((fun st -> st.TryGetTyconRef()), m) with | Some x -> (x :?> TyconRef) @@ -205,7 +205,7 @@ let ImportProvidedNamedType (env:ImportMap) (m:range) (st:Tainted) ImportILTypeRef env m tref /// Import a provided type as an AbstractIL type -let rec ImportProvidedTypeAsILType (env:ImportMap) (m:range) (st:Tainted) = +let rec ImportProvidedTypeAsILType (env: ImportMap) (m: range) (st: Tainted) = if st.PUntaint ((fun x -> x.IsVoid), m) then ILType.Void elif st.PUntaint((fun st -> st.IsGenericParameter), m) then mkILTyvarTy (uint16 (st.PUntaint((fun st -> st.GenericParameterPosition), m))) @@ -241,7 +241,7 @@ let rec ImportProvidedTypeAsILType (env:ImportMap) (m:range) (st:Tainted) = +let rec ImportProvidedType (env: ImportMap) (m: range) (* (tinst: TypeInst) *) (st: Tainted) = // Explanation: The two calls below represent am unchecked invariant of the hosted compiler: // that type providers are only activated on the CompilationThread. This invariant is not currently checked @@ -316,7 +316,7 @@ let rec ImportProvidedType (env:ImportMap) (m:range) (* (tinst:TypeInst) *) (st: /// Import a provided method reference as an Abstract IL method reference -let ImportProvidedMethodBaseAsILMethodRef (env:ImportMap) (m:range) (mbase: Tainted) = +let ImportProvidedMethodBaseAsILMethodRef (env: ImportMap) (m: range) (mbase: Tainted) = let tref = ExtensionTyping.GetILTypeRefOfProvidedType (mbase.PApply((fun mbase -> mbase.DeclaringType), m), m) let mbase = @@ -446,7 +446,7 @@ let multisetDiscriminateAndMap nodef tipf (items: ('Key list * 'Value) list) = /// Import an IL type definition as a new F# TAST Entity node. -let rec ImportILTypeDef amap m scoref (cpath:CompilationPath) enc nm (tdef:ILTypeDef) = +let rec ImportILTypeDef amap m scoref (cpath: CompilationPath) enc nm (tdef: ILTypeDef) = let lazyModuleOrNamespaceTypeForNestedTypes = lazy let cpath = cpath.NestedCompPath nm ModuleOrType @@ -464,7 +464,7 @@ let rec ImportILTypeDef amap m scoref (cpath:CompilationPath) enc nm (tdef:ILTyp /// Import a list of (possibly nested) IL types as a new ModuleOrNamespaceType node /// containing new entities, bucketing by namespace along the way. -and ImportILTypeDefList amap m (cpath:CompilationPath) enc items = +and ImportILTypeDefList amap m (cpath: CompilationPath) enc items = // Split into the ones with namespaces and without. Add the ones with namespaces in buckets. // That is, discriminate based in the first element of the namespace list (e.g. "System") // and, for each bag, fold-in a lazy computation to add the types under that bag . @@ -479,8 +479,8 @@ and ImportILTypeDefList amap m (cpath:CompilationPath) enc items = (fun n tgs -> let modty = lazy (ImportILTypeDefList amap m (cpath.NestedCompPath n Namespace) enc tgs) NewModuleOrNamespace (Some cpath) taccessPublic (mkSynId m n) XmlDoc.Empty [] (MaybeLazy.Lazy modty)) - (fun (n, info:Lazy<_>) -> - let (scoref2, _, lazyTypeDef:ILPreTypeDef) = info.Force() + (fun (n, info: Lazy<_>) -> + let (scoref2, _, lazyTypeDef: ILPreTypeDef) = info.Force() ImportILTypeDef amap m scoref2 cpath enc n (lazyTypeDef.GetTypeDef())) let kind = match enc with [] -> Namespace | _ -> ModuleOrType @@ -504,7 +504,7 @@ let ImportILAssemblyMainTypeDefs amap m scoref modul = modul.TypeDefs |> ImportILTypeDefs amap m scoref (CompPath(scoref, [])) [] /// Import the "exported types" table for multi-module assemblies. -let ImportILAssemblyExportedType amap m auxModLoader (scoref:ILScopeRef) (exportedType:ILExportedTypeOrForwarder) = +let ImportILAssemblyExportedType amap m auxModLoader (scoref: ILScopeRef) (exportedType: ILExportedTypeOrForwarder) = // Forwarders are dealt with separately in the ref->def dereferencing logic in tast.fs as they effectively give rise to type equivalences if exportedType.IsForwarder then [] @@ -532,14 +532,14 @@ let ImportILAssemblyExportedTypes amap m auxModLoader scoref (exportedTypes: ILE /// Import both the main type definitions and the "exported types" table, i.e. all the /// types defined in an IL assembly. -let ImportILAssemblyTypeDefs (amap, m, auxModLoader, aref, mainmod:ILModuleDef) = +let ImportILAssemblyTypeDefs (amap, m, auxModLoader, aref, mainmod: ILModuleDef) = let scoref = ILScopeRef.Assembly aref let mtypsForExportedTypes = ImportILAssemblyExportedTypes amap m auxModLoader scoref mainmod.ManifestOfAssembly.ExportedTypes let mainmod = ImportILAssemblyMainTypeDefs amap m scoref mainmod CombineCcuContentFragments m (mainmod :: mtypsForExportedTypes) /// Import the type forwarder table for an IL assembly -let ImportILAssemblyTypeForwarders (amap, m, exportedTypes:ILExportedTypesAndForwarders) = +let ImportILAssemblyTypeForwarders (amap, m, exportedTypes: ILExportedTypesAndForwarders) = // Note 'td' may be in another module or another assembly! // Note: it is very important that we call auxModLoader lazily [ //printfn "reading forwarders..." @@ -548,7 +548,7 @@ let ImportILAssemblyTypeForwarders (amap, m, exportedTypes:ILExportedTypesAndFor //printfn "found forwarder for %s..." n let tcref = lazy ImportILTypeRefUncached (amap()) m (ILTypeRef.Create(exportedType.ScopeRef, [], exportedType.Name)) yield (Array.ofList ns, n), tcref - let rec nested (nets:ILNestedExportedTypes) enc = + let rec nested (nets: ILNestedExportedTypes) enc = [ for net in nets.AsList do //printfn "found nested forwarder for %s..." net.Name @@ -560,7 +560,7 @@ let ImportILAssemblyTypeForwarders (amap, m, exportedTypes:ILExportedTypesAndFor /// Import an IL assembly as a new TAST CCU -let ImportILAssembly(amap:(unit -> ImportMap), m, auxModuleLoader, ilScopeRef, sourceDir, filename, ilModule:ILModuleDef, invalidateCcu:IEvent) = +let ImportILAssembly(amap:(unit -> ImportMap), m, auxModuleLoader, ilScopeRef, sourceDir, filename, ilModule: ILModuleDef, invalidateCcu: IEvent) = invalidateCcu |> ignore let aref = match ilScopeRef with diff --git a/src/fsharp/infos.fs b/src/fsharp/infos.fs index 642d0d46bc7..ae9e1ff49af 100755 --- a/src/fsharp/infos.fs +++ b/src/fsharp/infos.fs @@ -152,7 +152,7 @@ type AllowMultiIntfInstantiations = Yes | No /// Traverse the type hierarchy, e.g. f D (f C (f System.Object acc)). /// Visit base types and interfaces first. let private FoldHierarchyOfTypeAux followInterfaces allowMultiIntfInst skipUnref visitor g amap m ty acc = - let rec loop ndeep ty ((visitedTycon, visited:TyconRefMultiMap<_>, acc) as state) = + let rec loop ndeep ty ((visitedTycon, visited: TyconRefMultiMap<_>, acc) as state) = let seenThisTycon = isAppTy g ty && Set.contains (tcrefOfAppTy g ty).Stamp visitedTycon @@ -305,7 +305,7 @@ let ImportReturnTypeFromMetadata amap m ilty cattrs scoref tinst minst = /// /// Note: this now looks identical to constraint instantiation. -let CopyTyparConstraints m tprefInst (tporig:Typar) = +let CopyTyparConstraints m tprefInst (tporig: Typar) = tporig.Constraints |> List.map (fun tpc -> match tpc with @@ -338,7 +338,7 @@ let CopyTyparConstraints m tprefInst (tporig:Typar) = /// The constraints for each typar copied from another typar can only be fixed up once /// we have generated all the new constraints, e.g. f List, B :> List> ... -let FixupNewTypars m (formalEnclosingTypars:Typars) (tinst: TType list) (tpsorig: Typars) (tps: Typars) = +let FixupNewTypars m (formalEnclosingTypars: Typars) (tinst: TType list) (tpsorig: Typars) (tps: Typars) = // Checks.. These are defensive programming against early reported errors. let n0 = formalEnclosingTypars.Length let n1 = tinst.Length @@ -401,7 +401,7 @@ type ValRef with #if !NO_EXTENSIONTYPING /// Get the return type of a provided method, where 'void' is returned as 'None' -let GetCompiledReturnTyOfProvidedMethodInfo amap m (mi:Tainted) = +let GetCompiledReturnTyOfProvidedMethodInfo amap m (mi: Tainted) = let returnType = if mi.PUntaint((fun mi -> mi.IsConstructor), m) then mi.PApply((fun mi -> mi.DeclaringType), m) @@ -424,7 +424,7 @@ let ReparentSlotSigToUseMethodTypars g m ovByMethValRef slotsig = /// Construct the data representing a parameter in the signature of an abstract method slot -let MakeSlotParam (ty, argInfo:ArgReprInfo) = TSlotParam(Option.map textOfId argInfo.Name, ty, false, false, false, argInfo.Attribs) +let MakeSlotParam (ty, argInfo: ArgReprInfo) = TSlotParam(Option.map textOfId argInfo.Name, ty, false, false, false, argInfo.Attribs) /// Construct the data representing the signature of an abstract method slot let MakeSlotSig (nm, ty, ctps, mtps, paraml, retTy) = copySlotSig (TSlotSig(nm, ty, ctps, mtps, paraml, retTy)) @@ -435,7 +435,7 @@ let MakeSlotSig (nm, ty, ctps, mtps, paraml, retTy) = copySlotSig (TSlotSig(nm, /// - the type parameters associated with a generic method /// - the return type of the method /// - the actual type arguments of the enclosing type. -let private AnalyzeTypeOfMemberVal isCSharpExt g (ty, vref:ValRef) = +let private AnalyzeTypeOfMemberVal isCSharpExt g (ty, vref: ValRef) = let memberAllTypars, _, retTy, _ = GetTypeOfMemberInMemberForm g vref if isCSharpExt || vref.IsExtensionMember then [], memberAllTypars, retTy, [] @@ -445,12 +445,12 @@ let private AnalyzeTypeOfMemberVal isCSharpExt g (ty, vref:ValRef) = memberParentTypars, memberMethodTypars, retTy, parentTyArgs /// Get the object type for a member value which is an extension method (C#-style or F#-style) -let private GetObjTypeOfInstanceExtensionMethod g (vref:ValRef) = +let private GetObjTypeOfInstanceExtensionMethod g (vref: ValRef) = let _, curriedArgInfos, _, _ = GetTopValTypeInCompiledForm g vref.ValReprInfo.Value vref.Type vref.Range curriedArgInfos.Head.Head |> fst /// Get the object type for a member value which is a C#-style extension method -let private GetArgInfosOfMember isCSharpExt g (vref:ValRef) = +let private GetArgInfosOfMember isCSharpExt g (vref: ValRef) = if isCSharpExt then let _, curriedArgInfos, _, _ = GetTopValTypeInCompiledForm g vref.ValReprInfo.Value vref.Type vref.Range [ curriedArgInfos.Head.Tail ] @@ -588,7 +588,7 @@ type ParamData = type ILFieldInit with /// Compute the ILFieldInit for the given provided constant value for a provided enum type. - static member FromProvidedObj m (v:obj) = + static member FromProvidedObj m (v: obj) = match v with | null -> ILFieldInit.Null | _ -> @@ -616,7 +616,7 @@ type ILFieldInit with /// This is the same logic as OptionalArgInfoOfILParameter except we do not apply the /// Visual Basic rules for IDispatchConstant and IUnknownConstant to optional /// provided parameters. -let OptionalArgInfoOfProvidedParameter (amap:Import.ImportMap) m (provParam : Tainted) = +let OptionalArgInfoOfProvidedParameter (amap: Import.ImportMap) m (provParam : Tainted) = let g = amap.g if provParam.PUntaint((fun p -> p.IsOptional), m) then match provParam.PUntaint((fun p -> p.HasDefaultValue), m) with @@ -644,7 +644,7 @@ let GetAndSanityCheckProviderMethod m (mi: Tainted<'T :> ProvidedMemberInfo>) (g | meth -> meth /// Try to get an arbitrary ProvidedMethodInfo associated with a property. -let ArbitraryMethodInfoOfPropertyInfo (pi:Tainted) m = +let ArbitraryMethodInfoOfPropertyInfo (pi: Tainted) m = if pi.PUntaint((fun pi -> pi.CanRead), m) then GetAndSanityCheckProviderMethod m pi (fun pi -> pi.GetGetMethod()) FSComp.SR.etPropertyCanReadButHasNoGetter elif pi.PUntaint((fun pi -> pi.CanWrite), m) then @@ -1239,13 +1239,13 @@ type MethInfo = isStructTy x.TcGlobals x.ApparentEnclosingType /// Build IL method infos. - static member CreateILMeth (amap:Import.ImportMap, m, ty:TType, md: ILMethodDef) = + static member CreateILMeth (amap: Import.ImportMap, m, ty: TType, md: ILMethodDef) = let tinfo = ILTypeInfo.FromType amap.g ty let mtps = Import.ImportILGenericParameters (fun () -> amap) m tinfo.ILScopeRef tinfo.TypeInstOfRawMetadata md.GenericParams ILMeth (amap.g, ILMethInfo(amap.g, ty, None, md, mtps), None) /// Build IL method infos for a C#-style extension method - static member CreateILExtensionMeth (amap, m, apparentTy:TType, declaringTyconRef:TyconRef, extMethPri, md: ILMethodDef) = + static member CreateILExtensionMeth (amap, m, apparentTy: TType, declaringTyconRef: TyconRef, extMethPri, md: ILMethodDef) = let scoref = declaringTyconRef.CompiledRepresentationForNamedType.Scope let mtps = Import.ImportILGenericParameters (fun () -> amap) m scoref [] md.GenericParams ILMeth (amap.g, ILMethInfo(amap.g, apparentTy, Some declaringTyconRef, md, mtps), extMethPri) @@ -2483,7 +2483,7 @@ type CompiledSig = CompiledSig of TType list list * TType option * Typars * Typ /// Get the information about the compiled form of a method signature. Used when analyzing implementation /// relations between members and abstract slots. -let CompiledSigOfMeth g amap m (minfo:MethInfo) = +let CompiledSigOfMeth g amap m (minfo: MethInfo) = let formalMethTypars = minfo.FormalMethodTypars let fminst = generalizeTypars formalMethTypars let vargtys = minfo.GetParamTypes(amap, m, fminst) @@ -2501,7 +2501,7 @@ let CompiledSigOfMeth g amap m (minfo:MethInfo) = /// Used to hide/filter members from super classes based on signature /// Inref and outref parameter types will be treated as a byref type for equivalency. -let MethInfosEquivByNameAndPartialSig erasureFlag ignoreFinal g amap m (minfo:MethInfo) (minfo2:MethInfo) = +let MethInfosEquivByNameAndPartialSig erasureFlag ignoreFinal g amap m (minfo: MethInfo) (minfo2: MethInfo) = (minfo.LogicalName = minfo2.LogicalName) && (minfo.GenericArity = minfo2.GenericArity) && (ignoreFinal || minfo.IsFinal = minfo2.IsFinal) && @@ -2515,7 +2515,7 @@ let MethInfosEquivByNameAndPartialSig erasureFlag ignoreFinal g amap m (minfo:Me typeAEquivAux erasureFlag g (TypeEquivEnv.FromEquivTypars formalMethTypars formalMethTypars2) (stripByrefTy g ty1) (stripByrefTy g ty2))) /// Used to hide/filter members from super classes based on signature -let PropInfosEquivByNameAndPartialSig erasureFlag g amap m (pinfo:PropInfo) (pinfo2:PropInfo) = +let PropInfosEquivByNameAndPartialSig erasureFlag g amap m (pinfo: PropInfo) (pinfo2: PropInfo) = pinfo.PropertyName = pinfo2.PropertyName && let argtys = pinfo.GetParamTypes(amap, m) let argtys2 = pinfo2.GetParamTypes(amap, m) @@ -2532,12 +2532,12 @@ let MethInfosEquivByNameAndSig erasureFlag ignoreFinal g amap m minfo minfo2 = | _ -> false /// Used to hide/filter members from super classes based on signature -let PropInfosEquivByNameAndSig erasureFlag g amap m (pinfo:PropInfo) (pinfo2:PropInfo) = +let PropInfosEquivByNameAndSig erasureFlag g amap m (pinfo: PropInfo) (pinfo2: PropInfo) = PropInfosEquivByNameAndPartialSig erasureFlag g amap m pinfo pinfo2 && let retTy = pinfo.GetPropertyType(amap, m) let retTy2 = pinfo2.GetPropertyType(amap, m) typeEquivAux erasureFlag g retTy retTy2 -let SettersOfPropInfos (pinfos:PropInfo list) = pinfos |> List.choose (fun pinfo -> if pinfo.HasSetter then Some(pinfo.SetterMethod, Some pinfo) else None) -let GettersOfPropInfos (pinfos:PropInfo list) = pinfos |> List.choose (fun pinfo -> if pinfo.HasGetter then Some(pinfo.GetterMethod, Some pinfo) else None) +let SettersOfPropInfos (pinfos: PropInfo list) = pinfos |> List.choose (fun pinfo -> if pinfo.HasSetter then Some(pinfo.SetterMethod, Some pinfo) else None) +let GettersOfPropInfos (pinfos: PropInfo list) = pinfos |> List.choose (fun pinfo -> if pinfo.HasGetter then Some(pinfo.GetterMethod, Some pinfo) else None) diff --git a/src/fsharp/layout.fs b/src/fsharp/layout.fs index 1664b9c713a..02eaf804773 100644 --- a/src/fsharp/layout.fs +++ b/src/fsharp/layout.fs @@ -21,7 +21,7 @@ type NavigableTaggedText(taggedText: TaggedText, range: Range.range) = member x.Text = taggedText.Text let mkNav r t = NavigableTaggedText(t, r) :> TaggedText -let spaces n = new String(' ',n) +let spaces n = new String(' ', n) //-------------------------------------------------------------------------- @@ -29,20 +29,20 @@ let spaces n = new String(' ',n) //-------------------------------------------------------------------------- let rec juxtLeft = function - | ObjLeaf (jl,_text,_jr) -> jl - | Leaf (jl,_text,_jr) -> jl - | Node (jl,_l,_jm,_r,_jr,_joint) -> jl - | Attr (_tag,_attrs,l) -> juxtLeft l + | ObjLeaf (jl, _text, _jr) -> jl + | Leaf (jl, _text, _jr) -> jl + | Node (jl, _l, _jm, _r, _jr, _joint) -> jl + | Attr (_tag, _attrs, l) -> juxtLeft l let rec juxtRight = function - | ObjLeaf (_jl,_text,jr) -> jr - | Leaf (_jl,_text,jr) -> jr - | Node (_jl,_l,_jm,_r,jr,_joint) -> jr - | Attr (_tag,_attrs,l) -> juxtRight l + | ObjLeaf (_jl, _text, jr) -> jr + | Leaf (_jl, _text, jr) -> jr + | Node (_jl, _l, _jm, _r, jr, _joint) -> jr + | Attr (_tag, _attrs, l) -> juxtRight l // NOTE: emptyL might be better represented as a constructor, so then (Sep"") would have true meaning -let emptyL = Leaf (true,Internal.Utilities.StructuredFormat.TaggedTextOps.tag LayoutTag.Text "",true) -let isEmptyL = function Leaf(true,tag,true) when tag.Text = "" -> true | _ -> false +let emptyL = Leaf (true, Internal.Utilities.StructuredFormat.TaggedTextOps.tag LayoutTag.Text "", true) +let isEmptyL = function Leaf(true, tag, true) when tag.Text = "" -> true | _ -> false let mkNode l r joint = if isEmptyL l then r else @@ -50,17 +50,17 @@ let mkNode l r joint = let jl = juxtLeft l let jm = juxtRight l || juxtLeft r let jr = juxtRight r - Node(jl,l,jm,r,jr,joint) + Node(jl, l, jm, r, jr, joint) //-------------------------------------------------------------------------- //INDEX: constructors //-------------------------------------------------------------------------- -let wordL (str:TaggedText) = Leaf (false,str,false) -let sepL (str:TaggedText) = Leaf (true ,str,true) -let rightL (str:TaggedText) = Leaf (true ,str,false) -let leftL (str:TaggedText) = Leaf (false,str,true) +let wordL (str:TaggedText) = Leaf (false, str, false) +let sepL (str:TaggedText) = Leaf (true , str, true) +let rightL (str:TaggedText) = Leaf (true , str, false) +let leftL (str:TaggedText) = Leaf (false, str, true) module TaggedTextOps = let tagActivePatternCase = Internal.Utilities.StructuredFormat.TaggedTextOps.tag LayoutTag.ActivePatternCase @@ -216,7 +216,7 @@ module RightL = let aboveL l r = mkNode l r (Broken 0) -let tagAttrL str attrs ly = Attr (str,attrs,ly) +let tagAttrL str attrs ly = Attr (str, attrs, ly) //-------------------------------------------------------------------------- //INDEX: constructors derived @@ -281,23 +281,23 @@ type breaks = Breaks of // - if all breaks forced, then outer=next. // - popping under these conditions needs to reduce outer and next. let chunkN = 400 -let breaks0 () = Breaks(0,0,Array.create chunkN 0) -let pushBreak saving (Breaks(next,outer,stack)) = +let breaks0 () = Breaks(0, 0, Array.create chunkN 0) +let pushBreak saving (Breaks(next, outer, stack)) = let stack = if next = stack.Length then Array.append stack (Array.create chunkN 0) (* expand if full *) else stack stack.[next] <- saving - Breaks(next+1,outer,stack) + Breaks(next+1, outer, stack) -let popBreak (Breaks(next,outer,stack)) = +let popBreak (Breaks(next, outer, stack)) = if next=0 then raise (Failure "popBreak: underflow") let topBroke = stack.[next-1] < 0 let outer = if outer=next then outer-1 else outer (* if all broken, unwind *) let next = next - 1 - Breaks(next,outer,stack),topBroke + Breaks(next, outer, stack), topBroke -let forceBreak (Breaks(next,outer,stack)) = +let forceBreak (Breaks(next, outer, stack)) = if outer=next then (* all broken *) None @@ -305,7 +305,7 @@ let forceBreak (Breaks(next,outer,stack)) = let saving = stack.[outer] stack.[outer] <- -stack.[outer] let outer = outer+1 - Some (Breaks(next,outer,stack),saving) + Some (Breaks(next, outer, stack), saving) let squashTo maxWidth layout = // breaks = break context, can force to get indentation savings. @@ -318,111 +318,111 @@ let squashTo maxWidth layout = // pos - current pos in line = rightmost position of last line of block. // offset - width of last line of block // NOTE: offset <= pos -- depending on tabbing of last block - let rec fit breaks (pos,layout) = + let rec fit breaks (pos, layout) = (*printf "\n\nCalling pos=%d layout=[%s]\n" pos (showL layout)*) - let breaks,layout,pos,offset = + let breaks, layout, pos, offset = match layout with | ObjLeaf _ -> failwith "ObjLeaf should not appear here" - | Attr (tag,attrs,l) -> - let breaks,layout,pos,offset = fit breaks (pos,l) - let layout = Attr (tag,attrs,layout) - breaks,layout,pos,offset - | Leaf (_jl,taggedText,_jr) -> + | Attr (tag, attrs, l) -> + let breaks, layout, pos, offset = fit breaks (pos, l) + let layout = Attr (tag, attrs, layout) + breaks, layout, pos, offset + | Leaf (_jl, taggedText, _jr) -> let textWidth = taggedText.Text.Length let rec fitLeaf breaks pos = if pos + textWidth <= maxWidth then - breaks,layout,pos + textWidth,textWidth (* great, it fits *) + breaks, layout, pos + textWidth, textWidth (* great, it fits *) else match forceBreak breaks with - None -> (breaks,layout,pos + textWidth,textWidth (* tough, no more breaks *)) - | Some (breaks,saving) -> (let pos = pos - saving in fitLeaf breaks pos) + None -> (breaks, layout, pos + textWidth, textWidth (* tough, no more breaks *)) + | Some (breaks, saving) -> (let pos = pos - saving in fitLeaf breaks pos) fitLeaf breaks pos - | Node (jl,l,jm,r,jr,joint) -> + | Node (jl, l, jm, r, jr, joint) -> let mid = if jm then 0 else 1 match joint with | Unbreakable -> - let breaks,l,pos,offsetl = fit breaks (pos,l) (* fit left *) + let breaks, l, pos, offsetl = fit breaks (pos, l) (* fit left *) let pos = pos + mid (* fit space if juxt says so *) - let breaks,r,pos,offsetr = fit breaks (pos,r) (* fit right *) - breaks,Node (jl,l,jm,r,jr,Unbreakable),pos,offsetl + mid + offsetr + let breaks, r, pos, offsetr = fit breaks (pos, r) (* fit right *) + breaks, Node (jl, l, jm, r, jr, Unbreakable), pos, offsetl + mid + offsetr | Broken indent -> - let breaks,l,pos,offsetl = fit breaks (pos,l) (* fit left *) + let breaks, l, pos, offsetl = fit breaks (pos, l) (* fit left *) let pos = pos - offsetl + indent (* broken so - offset left + indent *) - let breaks,r,pos,offsetr = fit breaks (pos,r) (* fit right *) - breaks,Node (jl,l,jm,r,jr,Broken indent),pos,indent + offsetr + let breaks, r, pos, offsetr = fit breaks (pos, r) (* fit right *) + breaks, Node (jl, l, jm, r, jr, Broken indent), pos, indent + offsetr | Breakable indent -> - let breaks,l,pos,offsetl = fit breaks (pos,l) (* fit left *) + let breaks, l, pos, offsetl = fit breaks (pos, l) (* fit left *) (* have a break possibility, with saving *) let saving = offsetl + mid - indent let pos = pos + mid if saving>0 then let breaks = pushBreak saving breaks - let breaks,r,pos,offsetr = fit breaks (pos,r) - let breaks,broken = popBreak breaks + let breaks, r, pos, offsetr = fit breaks (pos, r) + let breaks, broken = popBreak breaks if broken then - breaks,Node (jl,l,jm,r,jr,Broken indent) ,pos,indent + offsetr + breaks, Node (jl, l, jm, r, jr, Broken indent) , pos, indent + offsetr else - breaks,Node (jl,l,jm,r,jr,Breakable indent),pos,offsetl + mid + offsetr + breaks, Node (jl, l, jm, r, jr, Breakable indent), pos, offsetl + mid + offsetr else (* actually no saving so no break *) - let breaks,r,pos,offsetr = fit breaks (pos,r) - breaks,Node (jl,l,jm,r,jr,Breakable indent) ,pos,offsetl + mid + offsetr + let breaks, r, pos, offsetr = fit breaks (pos, r) + breaks, Node (jl, l, jm, r, jr, Breakable indent) , pos, offsetl + mid + offsetr (*printf "\nDone: pos=%d offset=%d" pos offset*) - breaks,layout,pos,offset + breaks, layout, pos, offset let breaks = breaks0 () let pos = 0 - let _breaks,layout,_pos,_offset = fit breaks (pos,layout) + let _breaks, layout, _pos, _offset = fit breaks (pos, layout) layout //-------------------------------------------------------------------------- //INDEX: LayoutRenderer //-------------------------------------------------------------------------- -type LayoutRenderer<'a,'b> = +type LayoutRenderer<'a, 'b> = abstract Start : unit -> 'b abstract AddText : 'b -> TaggedText -> 'b abstract AddBreak : 'b -> int -> 'b abstract AddTag : 'b -> string * (string * string) list * bool -> 'b abstract Finish : 'b -> 'a -let renderL (rr: LayoutRenderer<_,_>) layout = +let renderL (rr: LayoutRenderer<_, _>) layout = let rec addL z pos i layout k = match layout with | ObjLeaf _ -> failwith "ObjLeaf should never apper here" (* pos is tab level *) - | Leaf (_,text,_) -> - k(rr.AddText z text,i + text.Text.Length) - | Node (_,l,_,r,_,Broken indent) -> + | Leaf (_, text, _) -> + k(rr.AddText z text, i + text.Text.Length) + | Node (_, l, _, r, _, Broken indent) -> addL z pos i l <| - fun (z,_i) -> - let z,i = rr.AddBreak z (pos+indent),(pos+indent) + fun (z, _i) -> + let z, i = rr.AddBreak z (pos+indent), (pos+indent) addL z (pos+indent) i r k - | Node (_,l,jm,r,_,_) -> + | Node (_, l, jm, r, _, _) -> addL z pos i l <| fun (z, i) -> - let z,i = if jm then z,i else rr.AddText z Literals.space, i+1 + let z, i = if jm then z, i else rr.AddText z Literals.space, i+1 let pos = i addL z pos i r k - | Attr (tag,attrs,l) -> - let z = rr.AddTag z (tag,attrs,true) + | Attr (tag, attrs, l) -> + let z = rr.AddTag z (tag, attrs, true) addL z pos i l <| fun (z, i) -> - let z = rr.AddTag z (tag,attrs,false) - k(z,i) + let z = rr.AddTag z (tag, attrs, false) + k(z, i) let pos = 0 - let z,i = rr.Start(),0 - let z,_i = addL z pos i layout id + let z, i = rr.Start(), 0 + let z, _i = addL z pos i layout id rr.Finish z /// string render let stringR = - { new LayoutRenderer with + { new LayoutRenderer with member x.Start () = [] member x.AddText rstrs taggedText = taggedText.Text::rstrs member x.AddBreak rstrs n = (spaces n) :: "\n" :: rstrs - member x.AddTag z (_,_,_) = z - member x.Finish rstrs = String.Join("",Array.ofList (List.rev rstrs)) } + member x.AddTag z (_, _, _) = z + member x.Finish rstrs = String.Join("", Array.ofList (List.rev rstrs)) } type NoState = NoState type NoResult = NoResult @@ -433,26 +433,26 @@ let taggedTextListR collector = member x.Start () = NoState member x.AddText z text = collector text; z member x.AddBreak rstrs n = collector Literals.lineBreak; collector (tagSpace(spaces n)); rstrs - member x.AddTag z (_,_,_) = z + member x.AddTag z (_, _, _) = z member x.Finish rstrs = NoResult } /// channel LayoutRenderer let channelR (chan:TextWriter) = - { new LayoutRenderer with + { new LayoutRenderer with member r.Start () = NoState member r.AddText z s = chan.Write s.Text; z member r.AddBreak z n = chan.WriteLine(); chan.Write (spaces n); z - member r.AddTag z (tag,attrs,start) = z + member r.AddTag z (tag, attrs, start) = z member r.Finish z = NoResult } /// buffer render let bufferR os = - { new LayoutRenderer with + { new LayoutRenderer with member r.Start () = NoState member r.AddText z s = bprintf os "%s" s.Text; z member r.AddBreak z n = bprintf os "\n"; bprintf os "%s" (spaces n); z - member r.AddTag z (tag,attrs,start) = z + member r.AddTag z (tag, attrs, start) = z member r.Finish z = NoResult } //-------------------------------------------------------------------------- diff --git a/src/fsharp/lib.fs b/src/fsharp/lib.fs index 118ce038bb5..9ec4d713912 100755 --- a/src/fsharp/lib.fs +++ b/src/fsharp/lib.fs @@ -54,7 +54,7 @@ module Bits = module Filename = let fullpath cwd nm = - let p = if FileSystem.IsPathRootedShim(nm) then nm else Path.Combine(cwd,nm) + let p = if FileSystem.IsPathRootedShim(nm) then nm else Path.Combine(cwd, nm) try FileSystem.GetFullPathShim(p) with | :? System.ArgumentException | :? System.ArgumentNullException @@ -83,7 +83,7 @@ module Int64 = module Pair = let order (compare1: IComparer<'T1>, compare2: IComparer<'T2>) = { new IComparer<'T1 * 'T2> with - member __.Compare((a1,a2),(aa1,aa2)) = + member __.Compare((a1, a2), (aa1, aa2)) = let res1 = compare1.Compare (a1, aa1) if res1 <> 0 then res1 else compare2.Compare (a2, aa2) } @@ -137,18 +137,18 @@ module Check = // Library //------------------------------------------------------------------------ -type IntMap<'T> = Zmap +type IntMap<'T> = Zmap module IntMap = let empty () = Zmap.empty Int32.order let add k v (t:IntMap<'T>) = Zmap.add k v t let find k (t:IntMap<'T>) = Zmap.find k t let tryFind k (t:IntMap<'T>) = Zmap.tryFind k t - let remove k (t:IntMap<'T>) = Zmap.remove k t - let mem k (t:IntMap<'T>) = Zmap.mem k t - let iter f (t:IntMap<'T>) = Zmap.iter f t - let map f (t:IntMap<'T>) = Zmap.map f t - let fold f (t:IntMap<'T>) z = Zmap.fold f t z + let remove k (t:IntMap<'T>) = Zmap.remove k t + let mem k (t:IntMap<'T>) = Zmap.mem k t + let iter f (t:IntMap<'T>) = Zmap.iter f t + let map f (t:IntMap<'T>) = Zmap.map f t + let fold f (t:IntMap<'T>) z = Zmap.fold f t z //------------------------------------------------------------------------- @@ -163,7 +163,7 @@ module ListAssoc = let rec find f x l = match l with | [] -> notFound() - | (x',y)::t -> if f x x' then y else find f x t + | (x2, y)::t -> if f x x2 then y else find f x t /// Treat a list of key-value pairs as a lookup collection. /// This function looks up a value based on a match from the supplied @@ -171,7 +171,7 @@ module ListAssoc = let rec tryFind (f:'key->'key->bool) (x:'key) (l:('key*'value) list) : 'value option = match l with | [] -> None - | (x',y)::t -> if f x x' then Some y else tryFind f x t + | (x2, y)::t -> if f x x2 then Some y else tryFind f x t //------------------------------------------------------------------------- // Library: lists as generalized sets @@ -205,18 +205,18 @@ module ListSet = (* NOTE: quadratic! *) let rec subtract f l1 l2 = match l2 with - | (h::t) -> subtract f (remove (fun y2 y1 -> f y1 y2) h l1) t + | (h::t) -> subtract f (remove (fun y2 y1 -> f y1 y2) h l1) t | [] -> l1 let isSubsetOf f l1 l2 = List.forall (fun x1 -> contains f x1 l2) l1 (* nb. preserve orders here: f must be applied to elements of l1 then elements of l2*) - let isSupersetOf f l1 l2 = List.forall (fun x2 -> contains (fun y2 y1 -> f y1 y2) x2 l1) l2 + let isSupersetOf f l1 l2 = List.forall (fun x2 -> contains (fun y2 y1 -> f y1 y2) x2 l1) l2 let equals f l1 l2 = isSubsetOf f l1 l2 && isSupersetOf f l1 l2 let unionFavourLeft f l1 l2 = - match l1,l2 with - | _,[] -> l1 - | [],_ -> l2 + match l1, l2 with + | _, [] -> l1 + | [], _ -> l2 | _ -> l1 @ (subtract f l2 l1) @@ -250,61 +250,61 @@ module ListSet = // Library: pairs //------------------------------------------------------------------------ -let mapFoldFst f s (x,y) = let x',s = f s x in (x',y),s -let mapFoldSnd f s (x,y) = let y',s = f s y in (x,y'),s -let pair a b = a,b - -let p13 (x,_y,_z) = x -let p23 (_x,y,_z) = y -let p33 (_x,_y,z) = z - -let map1Of2 f (a1,a2) = (f a1,a2) -let map2Of2 f (a1,a2) = (a1,f a2) -let map1Of3 f (a1,a2,a3) = (f a1,a2,a3) -let map2Of3 f (a1,a2,a3) = (a1,f a2,a3) -let map3Of3 f (a1,a2,a3) = (a1,a2,f a3) -let map3Of4 f (a1,a2,a3,a4) = (a1,a2,f a3,a4) -let map4Of4 f (a1,a2,a3,a4) = (a1,a2,a3,f a4) -let map5Of5 f (a1,a2,a3,a4,a5) = (a1,a2,a3,a4,f a5) -let map6Of6 f (a1,a2,a3,a4,a5,a6) = (a1,a2,a3,a4,a5,f a6) -let foldPair (f1,f2) acc (a1,a2) = f2 (f1 acc a1) a2 -let fold1Of2 f1 acc (a1,_a2) = f1 acc a1 -let foldTriple (f1,f2,f3) acc (a1,a2,a3) = f3 (f2 (f1 acc a1) a2) a3 -let foldQuadruple (f1,f2,f3,f4) acc (a1,a2,a3,a4) = f4 (f3 (f2 (f1 acc a1) a2) a3) a4 -let mapPair (f1,f2) (a1,a2) = (f1 a1, f2 a2) -let mapTriple (f1,f2,f3) (a1,a2,a3) = (f1 a1, f2 a2, f3 a3) -let mapQuadruple (f1,f2,f3,f4) (a1,a2,a3,a4) = (f1 a1, f2 a2, f3 a3, f4 a4) -let fmap2Of2 f z (a1,a2) = let z,a2 = f z a2 in z,(a1,a2) +let mapFoldFst f s (x, y) = let x2, s = f s x in (x2, y), s +let mapFoldSnd f s (x, y) = let y2, s = f s y in (x, y2), s +let pair a b = a, b + +let p13 (x, _y, _z) = x +let p23 (_x, y, _z) = y +let p33 (_x, _y, z) = z + +let map1Of2 f (a1, a2) = (f a1, a2) +let map2Of2 f (a1, a2) = (a1, f a2) +let map1Of3 f (a1, a2, a3) = (f a1, a2, a3) +let map2Of3 f (a1, a2, a3) = (a1, f a2, a3) +let map3Of3 f (a1, a2, a3) = (a1, a2, f a3) +let map3Of4 f (a1, a2, a3, a4) = (a1, a2, f a3, a4) +let map4Of4 f (a1, a2, a3, a4) = (a1, a2, a3, f a4) +let map5Of5 f (a1, a2, a3, a4, a5) = (a1, a2, a3, a4, f a5) +let map6Of6 f (a1, a2, a3, a4, a5, a6) = (a1, a2, a3, a4, a5, f a6) +let foldPair (f1, f2) acc (a1, a2) = f2 (f1 acc a1) a2 +let fold1Of2 f1 acc (a1, _a2) = f1 acc a1 +let foldTriple (f1, f2, f3) acc (a1, a2, a3) = f3 (f2 (f1 acc a1) a2) a3 +let foldQuadruple (f1, f2, f3, f4) acc (a1, a2, a3, a4) = f4 (f3 (f2 (f1 acc a1) a2) a3) a4 +let mapPair (f1, f2) (a1, a2) = (f1 a1, f2 a2) +let mapTriple (f1, f2, f3) (a1, a2, a3) = (f1 a1, f2 a2, f3 a3) +let mapQuadruple (f1, f2, f3, f4) (a1, a2, a3, a4) = (f1 a1, f2 a2, f3 a3, f4 a4) +let fmap2Of2 f z (a1, a2) = let z, a2 = f z a2 in z, (a1, a2) module List = let noRepeats xOrder xs = - let s = Zset.addList xs (Zset.empty xOrder) // build set - Zset.elements s // get elements... no repeats + let s = Zset.addList xs (Zset.empty xOrder) // build set + Zset.elements s // get elements... no repeats //--------------------------------------------------------------------------- // Zmap rebinds //------------------------------------------------------------------------- module Zmap = - let force k mp = match Zmap.tryFind k mp with Some x -> x | None -> failwith "Zmap.force: lookup failed" + let force k mp = match Zmap.tryFind k mp with Some x -> x | None -> failwith "Zmap.force: lookup failed" let mapKey key f mp = match f (Zmap.tryFind key mp) with - | Some fx -> Zmap.add key fx mp - | None -> Zmap.remove key mp + | Some fx -> Zmap.add key fx mp + | None -> Zmap.remove key mp //--------------------------------------------------------------------------- // Zset //------------------------------------------------------------------------- module Zset = - let ofList order xs = Zset.addList xs (Zset.empty order) + let ofList order xs = Zset.addList xs (Zset.empty order) // CLEANUP NOTE: move to Zset? let rec fixpoint f (s as s0) = let s = f s - if Zset.equal s s0 then s0 (* fixed *) - else fixpoint f s (* iterate *) + if Zset.equal s s0 then s0 (* fixed *) + else fixpoint f s (* iterate *) //--------------------------------------------------------------------------- // Misc @@ -332,7 +332,7 @@ let writeViaBufferWithEnvironmentNewLines (os: TextWriter) f x = let buf = System.Text.StringBuilder 100 f buf x let text = buf.ToString() - let text = text.Replace("\n",System.Environment.NewLine) + let text = text.Replace("\n", System.Environment.NewLine) os.Write text //--------------------------------------------------------------------------- @@ -346,12 +346,12 @@ type Graph<'Data, 'Id when 'Id : comparison and 'Id : equality> nodes: 'Data list, edges: ('Data * 'Data) list) = - let edges = edges |> List.map (fun (v1,v2) -> nodeIdentity v1, nodeIdentity v2) + let edges = edges |> List.map (fun (v1, v2) -> nodeIdentity v1, nodeIdentity v2) let nodes = nodes |> List.map (fun d -> nodeIdentity d, { nodeId = nodeIdentity d; nodeData=d; nodeNeighbours=[] }) let tab = Map.ofList nodes let nodes = List.map snd nodes do for node in nodes do - node.nodeNeighbours <- edges |> List.filter (fun (x,_y) -> x = node.nodeId) |> List.map (fun (_,nodeId) -> tab.[nodeId]) + node.nodeNeighbours <- edges |> List.filter (fun (x, _y) -> x = node.nodeId) |> List.map (fun (_, nodeId) -> tab.[nodeId]) member g.GetNodeData nodeId = tab.[nodeId].nodeData @@ -378,7 +378,7 @@ type Graph<'Data, 'Id when 'Id : comparison and 'Id : equality> type NonNullSlot<'T> = 'T let nullableSlotEmpty() = Unchecked.defaultof<'T> let nullableSlotFull x = x -//#endif +//#endif //--------------------------------------------------------------------------- // Caches, mainly for free variables @@ -422,13 +422,13 @@ module internal AsyncUtil = /// Represents the reified result of an asynchronous computation. [] - type AsyncResult<'T> = - | AsyncOk of 'T - | AsyncException of exn - | AsyncCanceled of OperationCanceledException + type AsyncResult<'T> = + | AsyncOk of 'T + | AsyncException of exn + | AsyncCanceled of OperationCanceledException static member Commit(res:AsyncResult<'T>) = - Async.FromContinuations (fun (cont,econt,ccont) -> + Async.FromContinuations (fun (cont, econt, ccont) -> match res with | AsyncOk v -> cont v | AsyncException exn -> econt exn @@ -450,15 +450,15 @@ module internal AsyncUtil = member x.RegisterResult (res:AsyncResult<'T>) = let grabbedConts = lock syncRoot (fun () -> - if result.IsSome then + if result.IsSome then [] else result <- Some res // Invoke continuations in FIFO order // Continuations that Async.FromContinuations provide do QUWI/SynchContext.Post, - // so the order is not overly relevant but still. + // so the order is not overly relevant but still. List.rev savedConts) - let postOrQueue (sc:SynchronizationContext,cont) = + let postOrQueue (sc:SynchronizationContext, cont) = match sc with | null -> ThreadPool.QueueUserWorkItem(fun _ -> cont res) |> ignore | sc -> sc.Post((fun _ -> cont res), state=null) @@ -466,7 +466,7 @@ module internal AsyncUtil = // Run continuations outside the lock match grabbedConts with | [] -> () - | [(sc,cont) as c] -> + | [(sc, cont) as c] -> if SynchronizationContext.Current = sc then cont res else @@ -476,7 +476,7 @@ module internal AsyncUtil = /// Get the reified result. member private x.AsyncPrimitiveResult = - Async.FromContinuations(fun (cont,_,_) -> + Async.FromContinuations(fun (cont, _, _) -> let grabbedResult = lock syncRoot (fun () -> match result with @@ -485,7 +485,7 @@ module internal AsyncUtil = | None -> // Otherwise save the continuation and call it in RegisterResult let sc = SynchronizationContext.Current - savedConts <- (sc,cont)::savedConts + savedConts <- (sc, cont)::savedConts None) // Run the action outside the lock match grabbedResult with @@ -513,9 +513,9 @@ module UnmanagedProcessExecutionOptions = [] extern bool private HeapSetInformation( - UIntPtr _HeapHandle, - UInt32 _HeapInformationClass, - UIntPtr _HeapInformation, + UIntPtr _HeapHandle, + UInt32 _HeapInformationClass, + UIntPtr _HeapInformation, UIntPtr _HeapInformationLength) [] @@ -523,11 +523,11 @@ module UnmanagedProcessExecutionOptions = // Translation of C# from http://swikb/v1/DisplayOnlineDoc.aspx?entryID=826 and copy in bug://5018 #if !FX_NO_SECURITY_PERMISSIONS - [] + [] #endif let EnableHeapTerminationOnCorruption() = if (System.Environment.OSVersion.Version.Major >= 6 && // If OS is Vista or higher - System.Environment.Version.Major < 3) then // and CLR not 3.0 or higher + System.Environment.Version.Major < 3) then // and CLR not 3.0 or higher // "The flag HeapSetInformation sets is available in Windows XP SP3 and later. // The data structure used for heap information is available on earlier versions of Windows. // The call will either return TRUE (found and set the flag) or false (flag not found). @@ -539,9 +539,9 @@ module UnmanagedProcessExecutionOptions = // See also: // http://blogs.msdn.com/michael_howard/archive/2008/02/18/faq-about-heapsetinformation-in-windows-vista-and-heap-based-buffer-overruns.aspx let HeapEnableTerminationOnCorruption = 1u : uint32 - if not (HeapSetInformation(GetProcessHeap(),HeapEnableTerminationOnCorruption,UIntPtr.Zero,UIntPtr.Zero)) then + if not (HeapSetInformation(GetProcessHeap(), HeapEnableTerminationOnCorruption, UIntPtr.Zero, UIntPtr.Zero)) then raise (System.Security.SecurityException( "Unable to enable unmanaged process execution option TerminationOnCorruption. " + "HeapSetInformation() returned FALSE; LastError = 0x" + - GetLastError().ToString("X").PadLeft(8,'0') + ".")) + GetLastError().ToString("X").PadLeft(8, '0') + ".")) diff --git a/src/fsharp/service/IncrementalBuild.fs b/src/fsharp/service/IncrementalBuild.fs index 0c4ed00657f..836a4f288bd 100755 --- a/src/fsharp/service/IncrementalBuild.fs +++ b/src/fsharp/service/IncrementalBuild.fs @@ -155,8 +155,8 @@ module internal IncrementalBuild = type BuildRules = { RuleList: (string * BuildRuleExpr) list } /// Visit each task and call op with the given accumulator. - let FoldOverBuildRules(rules:BuildRules, op, acc)= - let rec visitVector (ve:VectorBuildRule) acc = + let FoldOverBuildRules(rules: BuildRules, op, acc)= + let rec visitVector (ve: VectorBuildRule) acc = match ve with | VectorInput _ -> op (VectorBuildRule ve) acc | VectorScanLeft(_, _, a, i, _) -> op (VectorBuildRule ve) (visitVector i (visitScalar a acc)) @@ -164,13 +164,13 @@ module internal IncrementalBuild = | VectorStamp (_, _, i, _) -> op (VectorBuildRule ve) (visitVector i acc) | VectorMultiplex(_, _, i, _) -> op (VectorBuildRule ve) (visitScalar i acc) - and visitScalar (se:ScalarBuildRule) acc = + and visitScalar (se: ScalarBuildRule) acc = match se with | ScalarInput _ -> op (ScalarBuildRule se) acc | ScalarDemultiplex(_, _, i, _) -> op (ScalarBuildRule se) (visitVector i acc) | ScalarMap(_, _, i, _) -> op (ScalarBuildRule se) (visitScalar i acc) - let visitRule (expr:BuildRuleExpr) acc = + let visitRule (expr: BuildRuleExpr) acc = match expr with | ScalarBuildRule se ->visitScalar se acc | VectorBuildRule ve ->visitVector ve acc @@ -178,7 +178,7 @@ module internal IncrementalBuild = List.foldBack visitRule (rules.RuleList |> List.map snd) acc /// Convert from interfaces into discriminated union. - let ToBuild (names:NamedOutput list): BuildRules = + let ToBuild (names: NamedOutput list): BuildRules = // Create the rules. let createRules() = @@ -186,7 +186,7 @@ module internal IncrementalBuild = | NamedScalarOutput(s) -> s.Name, ScalarBuildRule(s.Expr)) } // Ensure that all names are unique. - let ensureUniqueNames (expr:BuildRuleExpr) (acc:Map) = + let ensureUniqueNames (expr: BuildRuleExpr) (acc: Map) = let AddUniqueIdToNameMapping(id, name)= match acc.TryFind name with | Some priorId -> @@ -198,7 +198,7 @@ module internal IncrementalBuild = AddUniqueIdToNameMapping(id, name) // Validate the rule tree - let validateRules (rules:BuildRules) = + let validateRules (rules: BuildRules) = FoldOverBuildRules(rules, ensureUniqueNames, Map.empty) |> ignore // Convert and validate @@ -266,7 +266,7 @@ module internal IncrementalBuild = ResultVector(size, zeroElementTimestamp, Map.add slot value map) member rv.MaxTimestamp() = - let maximize (lasttimestamp:DateTime) (_, result:Result) = max lasttimestamp result.Timestamp + let maximize (lasttimestamp: DateTime) (_, result: Result) = max lasttimestamp result.Timestamp List.fold maximize zeroElementTimestamp (asList.Force()) member rv.Signature() = @@ -310,12 +310,12 @@ module internal IncrementalBuild = /// A set of build rules and the corresponding, possibly partial, results from building. [] - type PartialBuild(rules:BuildRules, results:Map) = + type PartialBuild(rules: BuildRules, results: Map) = member bt.Rules = rules member bt.Results = results /// Given an expression, find the expected width. - let rec GetVectorWidthByExpr(bt:PartialBuild, ve:VectorBuildRule) = + let rec GetVectorWidthByExpr(bt: PartialBuild, ve: VectorBuildRule) = let id = ve.Id let KnownValue() = match bt.Results.TryFind id with @@ -335,18 +335,18 @@ module internal IncrementalBuild = | VectorMultiplex _ -> KnownValue() /// Given an expression name, get the corresponding expression. - let GetTopLevelExprByName(bt:PartialBuild, seek:string) = + let GetTopLevelExprByName(bt: PartialBuild, seek: string) = bt.Rules.RuleList |> List.filter(fun(name, _) ->name=seek) |> List.map (fun(_, root) ->root) |> List.head /// Get an expression matching the given name. - let GetExprByName(bt:PartialBuild, node:INode): BuildRuleExpr = - let matchName (expr:BuildRuleExpr) (acc:BuildRuleExpr option): BuildRuleExpr option = + let GetExprByName(bt: PartialBuild, node: INode): BuildRuleExpr = + let matchName (expr: BuildRuleExpr) (acc: BuildRuleExpr option): BuildRuleExpr option = if expr.Name = node.Name then Some expr else acc let matchOption = FoldOverBuildRules(bt.Rules, matchName, None) Option.get matchOption // Given an Id, find the corresponding expression. - let GetExprById(bt:PartialBuild, seek:Id): BuildRuleExpr= + let GetExprById(bt: PartialBuild, seek: Id): BuildRuleExpr= let rec vectorExprOfId ve = match ve with | VectorInput(id, _) ->if seek=id then Some (VectorBuildRule ve) else None @@ -364,7 +364,7 @@ module internal IncrementalBuild = | ScalarDemultiplex(id, _, i, _) ->if seek=id then Some (ScalarBuildRule se) else vectorExprOfId i | ScalarMap(id, _, i, _) ->if seek=id then Some (ScalarBuildRule se) else scalarExprOfId i - let exprOfId(expr:BuildRuleExpr) = + let exprOfId(expr: BuildRuleExpr) = match expr with | ScalarBuildRule se ->scalarExprOfId se | VectorBuildRule ve ->vectorExprOfId ve @@ -374,12 +374,12 @@ module internal IncrementalBuild = | Some expr :: _ -> expr | _ -> failwith (sprintf "GetExprById did not find an expression for Id") - let GetVectorWidthById (bt:PartialBuild) seek = + let GetVectorWidthById (bt: PartialBuild) seek = match GetExprById(bt, seek) with | ScalarBuildRule _ ->failwith "Attempt to get width of scalar." | VectorBuildRule ve -> Option.get (GetVectorWidthByExpr(bt, ve)) - let GetScalarExprResult (bt:PartialBuild, se:ScalarBuildRule) = + let GetScalarExprResult (bt: PartialBuild, se: ScalarBuildRule) = match bt.Results.TryFind (se.Id) with | Some resultSet -> match se, resultSet with @@ -389,7 +389,7 @@ module internal IncrementalBuild = | _ ->failwith "GetScalarExprResult had no match" | None->NotAvailable - let GetVectorExprResultVector (bt:PartialBuild, ve:VectorBuildRule) = + let GetVectorExprResultVector (bt: PartialBuild, ve: VectorBuildRule) = match bt.Results.TryFind (ve.Id) with | Some resultSet -> match ve, resultSet with @@ -401,7 +401,7 @@ module internal IncrementalBuild = | _ -> failwith "GetVectorExprResultVector had no match" | None->None - let GetVectorExprResult (bt:PartialBuild, ve:VectorBuildRule, slot) = + let GetVectorExprResult (bt: PartialBuild, ve: VectorBuildRule, slot) = match bt.Results.TryFind ve.Id with | Some resultSet -> match ve, resultSet with @@ -414,7 +414,7 @@ module internal IncrementalBuild = | None->NotAvailable /// Get the maximum build stamp for an output. - let MaxTimestamp(bt:PartialBuild, id) = + let MaxTimestamp(bt: PartialBuild, id) = match bt.Results.TryFind id with | Some resultset -> match resultset with @@ -422,7 +422,7 @@ module internal IncrementalBuild = | VectorResult rv -> rv.MaxTimestamp() | None -> DateTime.MaxValue - let Signature(bt:PartialBuild, id) = + let Signature(bt: PartialBuild, id) = match bt.Results.TryFind id with | Some resultset -> match resultset with @@ -431,8 +431,8 @@ module internal IncrementalBuild = | None -> UnevaluatedInput /// Get all the results for the given expr. - let AllResultsOfExpr extractor (bt:PartialBuild) (expr: VectorBuildRule) = - let GetAvailable (rv:ResultVector) = + let AllResultsOfExpr extractor (bt: PartialBuild) (expr: VectorBuildRule) = + let GetAvailable (rv: ResultVector) = let Extract acc (_, result) = (extractor result)::acc List.rev (rv.FoldLeft Extract []) let GetVectorResultById id = @@ -453,8 +453,8 @@ module internal IncrementalBuild = | Scalar of INode * obj /// Declare a named scalar output. - static member ScalarInput (node:Scalar<'T>, value: 'T) = BuildInput.Scalar(node, box value) - static member VectorInput(node:Vector<'T>, values: 'T list) = BuildInput.Vector(node, List.map box values) + static member ScalarInput (node: Scalar<'T>, value: 'T) = BuildInput.Scalar(node, box value) + static member VectorInput(node: Vector<'T>, values: 'T list) = BuildInput.Vector(node, List.map box values) let AvailableAllResultsOfExpr bt expr = @@ -462,7 +462,7 @@ module internal IncrementalBuild = AllResultsOfExpr (function Available(o, _, _) -> o | _ -> failwith msg) bt expr /// Bind a set of build rules to a set of input values. - let ToBound(buildRules:BuildRules, inputs: BuildInput list) = + let ToBound(buildRules: BuildRules, inputs: BuildInput list) = let now = DateTime.UtcNow let rec applyScalarExpr(se, results) = match se with @@ -507,7 +507,7 @@ module internal IncrementalBuild = /// Visit each executable action necessary to evaluate the given output (with an optional slot in a /// vector output). Call actionFunc with the given accumulator. - let ForeachAction cache ctok (Target(output, optSlot)) bt (actionFunc:Action -> 'T -> 'T) (acc:'T) = + let ForeachAction cache ctok (Target(output, optSlot)) bt (actionFunc: Action -> 'T -> 'T) (acc:'T) = let seen = Dictionary() let isSeen id = if seen.ContainsKey id then true @@ -515,13 +515,13 @@ module internal IncrementalBuild = seen.[id] <- true false - let shouldEvaluate(bt, currentsig:InputSignature, id) = + let shouldEvaluate(bt, currentsig: InputSignature, id) = if currentsig.IsEvaluated then currentsig <> Signature(bt, id) else false /// Make sure the result vector saved matches the size of expr - let resizeVectorExpr(ve:VectorBuildRule, acc) = + let resizeVectorExpr(ve: VectorBuildRule, acc) = match GetVectorWidthByExpr(bt, ve) with | Some expectedWidth -> match bt.Results.TryFind ve.Id with @@ -651,7 +651,7 @@ module internal IncrementalBuild = | _ -> acc visitScalar inputExpr acc - and visitScalar (se:ScalarBuildRule) acc = + and visitScalar (se: ScalarBuildRule) acc = if isSeen se.Id then acc else match se with @@ -716,7 +716,7 @@ module internal IncrementalBuild = | _ -> failwith "expected a VectorStamp" /// Given the result of a single action, apply that action to the Build - let ApplyResult(actionResult:ActionResult, bt:PartialBuild) = + let ApplyResult(actionResult: ActionResult, bt: PartialBuild) = match actionResult with | ResizeResult(id, slotcount) -> match bt.Results.TryFind id with @@ -763,7 +763,7 @@ module internal IncrementalBuild = { new IDisposable with member __.Dispose() = injectCancellationFault <- false } /// Apply the result, and call the 'save' function to update the build. - let ExecuteApply (ctok: CompilationThreadToken) save (action:Action) bt = + let ExecuteApply (ctok: CompilationThreadToken) save (action: Action) bt = cancellable { let! actionResult = action.Execute(ctok) let newBt = ApplyResult(actionResult, bt) @@ -796,7 +796,7 @@ module internal IncrementalBuild = eval(bt, 0) /// Evaluate one step of the build. Call the 'save' function to save the intermediate result. - let Step cache ctok save target (bt:PartialBuild) = + let Step cache ctok save target (bt: PartialBuild) = cancellable { // REVIEW: we're building up the whole list of actions on the fringe of the work tree, // executing one thing and then throwing the list away. What about saving the list inside the Build instance? @@ -830,7 +830,7 @@ module internal IncrementalBuild = ComputeMaxTimeStamp cache ctok target bt DateTime.MinValue /// Get a scalar vector. Result must be available - let GetScalarResult<'T>(node:Scalar<'T>, bt): ('T*DateTime) option = + let GetScalarResult<'T>(node: Scalar<'T>, bt): ('T*DateTime) option = match GetTopLevelExprByName(bt, node.Name) with | ScalarBuildRule se -> match bt.Results.TryFind se.Id with @@ -845,13 +845,13 @@ module internal IncrementalBuild = | VectorBuildRule _ -> failwith "Expected scalar." /// Get a result vector. All results must be available or thrown an exception. - let GetVectorResult<'T>(node:Vector<'T>, bt): 'T[] = + let GetVectorResult<'T>(node: Vector<'T>, bt): 'T[] = match GetTopLevelExprByName(bt, node.Name) with | ScalarBuildRule _ -> failwith "Expected vector." | VectorBuildRule ve -> AvailableAllResultsOfExpr bt ve |> List.map unbox |> Array.ofList /// Get an element of vector result or None if there were no results. - let GetVectorResultBySlot<'T>(node:Vector<'T>, slot, bt): ('T*DateTime) option = + let GetVectorResultBySlot<'T>(node: Vector<'T>, slot, bt): ('T*DateTime) option = match GetTopLevelExprByName(bt, node.Name) with | ScalarBuildRule _ -> failwith "Expected vector expression" | VectorBuildRule ve -> @@ -860,7 +860,7 @@ module internal IncrementalBuild = | None->None /// Given an input value, find the corresponding slot. - let TryGetSlotByInput<'T>(node:Vector<'T>, build:PartialBuild, found:'T->bool): int option = + let TryGetSlotByInput<'T>(node: Vector<'T>, build: PartialBuild, found:'T->bool): int option = let expr = GetExprByName(build, node) let id = expr.Id match build.Results.TryFind id with @@ -903,7 +903,7 @@ module internal IncrementalBuild = module Vector = /// Maps one vector to another using the given function. - let Map (taskname:string) (task: CompilationThreadToken -> 'I -> 'O) (input:Vector<'I>): Vector<'O> = + let Map (taskname: string) (task: CompilationThreadToken -> 'I -> 'O) (input: Vector<'I>): Vector<'O> = let input = input.Expr let expr = VectorMap(NextId(), taskname, input, (fun ctok x -> box (task ctok (unbox x)))) { new Vector<'O> @@ -914,7 +914,7 @@ module internal IncrementalBuild = /// Apply a function to each element of the vector, threading an accumulator argument /// through the computation. Returns intermediate results in a vector. - let ScanLeft (taskname:string) (task: CompilationThreadToken -> 'A -> 'I -> Eventually<'A>) (acc:Scalar<'A>) (input:Vector<'I>): Vector<'A> = + let ScanLeft (taskname: string) (task: CompilationThreadToken -> 'A -> 'I -> Eventually<'A>) (acc: Scalar<'A>) (input: Vector<'I>): Vector<'A> = let BoxingScanLeft ctok a i = Eventually.box(task ctok (unbox a) (unbox i)) let acc = acc.Expr let input = input.Expr @@ -925,7 +925,7 @@ module internal IncrementalBuild = override pe.Expr = expr } /// Apply a function to a vector to get a scalar value. - let Demultiplex (taskname:string) (task: CompilationThreadToken -> 'I[] -> Cancellable<'O>) (input:Vector<'I>): Scalar<'O> = + let Demultiplex (taskname: string) (task: CompilationThreadToken -> 'I[] -> Cancellable<'O>) (input: Vector<'I>): Scalar<'O> = let BoxingDemultiplex ctok inps = cancellable { let! res = task ctok (Array.map unbox inps) @@ -940,7 +940,7 @@ module internal IncrementalBuild = /// Creates a new vector with the same items but with /// timestamp specified by the passed-in function. - let Stamp (taskname:string) (task: TimeStampCache -> CompilationThreadToken -> 'I -> DateTime) (input:Vector<'I>): Vector<'I> = + let Stamp (taskname: string) (task: TimeStampCache -> CompilationThreadToken -> 'I -> DateTime) (input: Vector<'I>): Vector<'I> = let input = input.Expr let expr = VectorStamp (NextId(), taskname, input, (fun cache ctok x -> task cache ctok (unbox x))) { new Vector<'I> @@ -948,25 +948,25 @@ module internal IncrementalBuild = override __.Name = taskname override pe.Expr = expr } - let AsScalar (taskname:string) (input:Vector<'I>): Scalar<'I array> = + let AsScalar (taskname: string) (input: Vector<'I>): Scalar<'I array> = Demultiplex taskname (fun _ctok x -> cancellable.Return x) input - let VectorInput(node:Vector<'T>, values: 'T list) = (node.Name, values.Length, List.map box values) + let VectorInput(node: Vector<'T>, values: 'T list) = (node.Name, values.Length, List.map box values) /// Declare build outputs and bind them to real values. type BuildDescriptionScope() = let mutable outputs = [] /// Declare a named scalar output. - member b.DeclareScalarOutput(output:Scalar<'T>)= + member b.DeclareScalarOutput(output: Scalar<'T>)= outputs <- NamedScalarOutput(output) :: outputs /// Declare a named vector output. - member b.DeclareVectorOutput(output:Vector<'T>)= + member b.DeclareVectorOutput(output: Vector<'T>)= outputs <- NamedVectorOutput(output) :: outputs /// Set the concrete inputs for this build - member b.GetInitialPartialBuild(inputs:BuildInput list) = + member b.GetInitialPartialBuild(inputs: BuildInput list) = ToBound(ToBuild outputs, inputs) @@ -988,7 +988,7 @@ module IncrementalBuilderEventTesting = curIndex <- (curIndex + 1) % MAX member this.CurrentEventNum = numAdds // called by unit tests, returns 'n' most recent additions. - member this.MostRecentList(n:int) : list<'T> = + member this.MostRecentList(n: int) : list<'T> = if n < 0 || n > MAX then raise <| new System.ArgumentOutOfRangeException("n", sprintf "n must be between 0 and %d, inclusive, but got %d" MAX n) let mutable remaining = n @@ -1021,9 +1021,9 @@ module Tc = FSharp.Compiler.TypeChecker [] type TypeCheckAccumulator = { tcState: TcState - tcImports:TcImports - tcGlobals:TcGlobals - tcConfig:TcConfig + tcImports: TcImports + tcGlobals: TcGlobals + tcConfig: TcConfig tcEnvAtEndOfFile: TcEnv /// Accumulated resolutions, last file first @@ -1035,10 +1035,10 @@ type TypeCheckAccumulator = /// Accumulated 'open' declarations, last file first tcOpenDeclarationsRev: OpenDeclaration[] list - topAttribs:TopAttribs option + topAttribs: TopAttribs option /// Result of checking most recent file, if any - latestImplFile:TypedImplFile option + latestImplFile: TypedImplFile option latestCcuSigForFile: ModuleOrNamespaceType option @@ -1067,7 +1067,7 @@ type FrameworkImportsCache(keepStrongly) = member __.Clear(ctok) = frameworkTcImportsCache.Clear(ctok) /// This function strips the "System" assemblies from the tcConfig and returns a age-cached TcImports for them. - member __.Get(ctok, tcConfig:TcConfig) = + member __.Get(ctok, tcConfig: TcConfig) = cancellable { // Split into installed and not installed. let frameworkDLLs, nonFrameworkResolutions, unresolved = TcAssemblyResolutions.SplitNonFoundationalResolutions(ctok, tcConfig) @@ -1175,7 +1175,7 @@ module Utilities = /// Constructs the build data (IRawFSharpAssemblyData) representing the assembly when used /// as a cross-assembly reference. Note the assembly has not been generated on disk, so this is /// a virtualized view of the assembly contents as computed by background checking. -type RawFSharpAssemblyDataBackedByLanguageService (tcConfig, tcGlobals, tcState:TcState, outfile, topAttrs, assemblyName, ilAssemRef) = +type RawFSharpAssemblyDataBackedByLanguageService (tcConfig, tcGlobals, tcState: TcState, outfile, topAttrs, assemblyName, ilAssemRef) = let generatedCcu = tcState.Ccu let exportRemapping = MakeExportRemapping generatedCcu generatedCcu.Contents @@ -1269,14 +1269,14 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput /// This is a build task function that gets placed into the build rules as the computation for a VectorStamp /// /// Get the timestamp of the given file name. - let StampFileNameTask (cache: TimeStampCache) _ctok (_m:range, filename:string, _isLastCompiland) = + let StampFileNameTask (cache: TimeStampCache) _ctok (_m: range, filename: string, _isLastCompiland) = assertNotDisposed() cache.GetFileTimeStamp filename /// This is a build task function that gets placed into the build rules as the computation for a VectorMap /// /// Parse the given file and return the given input. - let ParseTask ctok (sourceRange:range, filename:string, isLastCompiland) = + let ParseTask ctok (sourceRange: range, filename: string, isLastCompiland) = assertNotDisposed() DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent ctok @@ -1373,7 +1373,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput /// This is a build task function that gets placed into the build rules as the computation for a Vector.ScanLeft /// /// Type check all files. - let TypeCheckTask ctok (tcAcc:TypeCheckAccumulator) input: Eventually = + let TypeCheckTask ctok (tcAcc: TypeCheckAccumulator) input: Eventually = assertNotDisposed() match input with | Some input, _sourceRange, filename, parseErrors-> @@ -1444,7 +1444,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput /// This is a build task function that gets placed into the build rules as the computation for a Vector.Demultiplex /// /// Finish up the typechecking to produce outputs for the rest of the compilation process - let FinalizeTypeCheckTask ctok (tcStates:TypeCheckAccumulator[]) = + let FinalizeTypeCheckTask ctok (tcStates: TypeCheckAccumulator[]) = cancellable { assertNotDisposed() DoesNotRequireCompilerThreadTokenAndCouldPossiblyBeMadeConcurrent ctok @@ -1564,7 +1564,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput RequireCompilationThread ctok // modifying state partialBuild <- b - let MaxTimeStampInDependencies cache (ctok: CompilationThreadToken) (output:INode) = + let MaxTimeStampInDependencies cache (ctok: CompilationThreadToken) (output: INode) = IncrementalBuild.MaxTimeStampInDependencies cache ctok output.Name partialBuild member this.IncrementUsageCount() = @@ -1691,7 +1691,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput let t2 = MaxTimeStampInDependencies cache ctok stampedReferencedAssembliesNode max t1 t2 - member __.GetSlotOfFileName(filename:string) = + member __.GetSlotOfFileName(filename: string) = // Get the slot of the given file and force it to build. let CompareFileNames (_, f2, _) = let result = @@ -1733,9 +1733,9 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput static member TryCreateBackgroundBuilderForProjectOptions (ctok, legacyReferenceResolver, defaultFSharpBinariesDir, frameworkTcImportsCache: FrameworkImportsCache, - loadClosureOpt:LoadClosure option, - sourceFiles:string list, - commandLineArgs:string list, + loadClosureOpt: LoadClosure option, + sourceFiles: string list, + commandLineArgs: string list, projectReferences, projectDirectory, useScriptResolutionRules, keepAssemblyContents, keepAllBackgroundResolutions, maxTimeShareMilliseconds, @@ -1766,7 +1766,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput | Some idx -> Some(commandLineArgs.[idx].Substring(switchstring.Length)) | _ -> None - // see also fsc.fs:runFromCommandLineToImportingAssemblies(), as there are many similarities to where the PS creates a tcConfigB + // see also fsc.fs: runFromCommandLineToImportingAssemblies(), as there are many similarities to where the PS creates a tcConfigB let tcConfigB = TcConfigBuilder.CreateNew(legacyReferenceResolver, defaultFSharpBinariesDir, diff --git a/src/fsharp/service/ServiceDeclarationLists.fs b/src/fsharp/service/ServiceDeclarationLists.fs index 8faf0c41c40..85bc613c7ff 100644 --- a/src/fsharp/service/ServiceDeclarationLists.fs +++ b/src/fsharp/service/ServiceDeclarationLists.fs @@ -56,7 +56,7 @@ type FSharpMethodGroupItemParameter(name: string, canonicalTypeTextForSorting: s module internal DescriptionListsImpl = let isFunction g ty = - let _,tau = tryDestForallTy g ty + let _, tau = tryDestForallTy g ty isFunTy g tau let printCanonicalizedTypeName g (denv:DisplayEnv) tau = @@ -86,8 +86,8 @@ module internal DescriptionListsImpl = // the union type containing this case. NicePrint.layoutOfParamData denv (ParamData(false, false, false, NotOptional, NoCallerInfo, Some f.Id, ReflectedArgInfo.None, f.FormalType)) FSharpMethodGroupItemParameter( - name=initial.ParameterName, - canonicalTypeTextForSorting=initial.CanonicalTypeTextForSorting, + name=initial.ParameterName, + canonicalTypeTextForSorting=initial.CanonicalTypeTextForSorting, display=display, isOptional=false) @@ -100,7 +100,7 @@ module internal DescriptionListsImpl = // TODO this code is similar to NicePrint.fs:formatParamDataToBuffer, refactor or figure out why different? let PrettyParamsOfParamDatas g denv typarInst (paramDatas:ParamData list) rty = - let paramInfo,paramTypes = + let paramInfo, paramTypes = paramDatas |> List.map (fun (ParamData(isParamArrayArg, _isInArg, _isOutArg, optArgInfo, _callerInfo, nmOpt, _reflArgInfo, pty)) -> let isOptArg = optArgInfo.IsOptional @@ -112,10 +112,10 @@ module internal DescriptionListsImpl = let pty = match ptyOpt with ValueSome x -> x | _ -> pty (nm, isOptArg, SepL.questionMark ^^ (wordL (TaggedTextOps.tagParameter nm))), pty // Layout an unnamed argument - | None, _,_ -> + | None, _, _ -> ("", isOptArg, emptyL), pty // Layout a named argument - | Some id,_,_ -> + | Some id, _, _ -> let nm = id.idText let prefix = if isParamArrayArg then @@ -127,7 +127,7 @@ module internal DescriptionListsImpl = wordL (TaggedTextOps.tagParameter nm) ^^ RightL.colon //sprintf "%s: " nm - (nm,isOptArg, prefix),pty) + (nm, isOptArg, prefix), pty) |> List.unzip // Prettify everything @@ -136,7 +136,7 @@ module internal DescriptionListsImpl = // Remake the params using the prettified versions let prettyParams = - (paramInfo,prettyParamTys,prettyParamTysL) |||> List.map3 (fun (nm,isOptArg,paramPrefix) tau tyL -> + (paramInfo, prettyParamTys, prettyParamTysL) |||> List.map3 (fun (nm, isOptArg, paramPrefix) tau tyL -> FSharpMethodGroupItemParameter( name = nm, canonicalTypeTextForSorting = printCanonicalizedTypeName g denv tau, @@ -154,7 +154,7 @@ module internal DescriptionListsImpl = // Remake the params using the prettified versions let parameters = - (prettyParamTys,prettyParamTysL) + (prettyParamTys, prettyParamTysL) ||> List.zip |> List.map (fun (tau, tyL) -> FSharpMethodGroupItemParameter( @@ -178,7 +178,7 @@ module internal DescriptionListsImpl = | SymbolHelpers.ItemIsWithStaticArguments m g staticParameters -> staticParameters |> Array.map (fun sp -> - let ty = Import.ImportProvidedType amap m (sp.PApply((fun x -> x.ParameterType),m)) + let ty = Import.ImportProvidedType amap m (sp.PApply((fun x -> x.ParameterType), m)) let spKind = NicePrint.prettyLayoutOfType denv ty let spName = sp.PUntaint((fun sp -> sp.Name), m) let spOpt = sp.PUntaint((fun sp -> sp.IsOptional), m) @@ -204,7 +204,7 @@ module internal DescriptionListsImpl = let getPrettyParamsOfTypes() = let tau = vref.TauType match tryDestFunTy denv.g tau with - | ValueSome(arg,rtau) -> + | ValueSome(arg, rtau) -> let args = tryDestRefTupleTy denv.g arg let _prettyTyparInst, prettyParams, prettyRetTyL, _prettyConstraintsL = PrettyParamsOfTypes g denv item.TyparInst args rtau // FUTURE: prettyTyparInst is the pretty version of the known instantiations of type parameters in the output. It could be returned @@ -241,7 +241,7 @@ module internal DescriptionListsImpl = // Adjust the return type so it only strips the first argument let curriedRetTy = match tryDestFunTy denv.g vref.TauType with - | ValueSome(_,rtau) -> rtau + | ValueSome(_, rtau) -> rtau | _ -> lastRetTy let _prettyTyparInst, prettyFirstCurriedParams, prettyCurriedRetTyL, prettyConstraintsL = PrettyParamsOfParamDatas g denv item.TyparInst firstCurriedParamDatas curriedRetTy @@ -250,7 +250,7 @@ module internal DescriptionListsImpl = prettyFirstCurriedParams, prettyCurriedRetTyL - | Item.UnionCase(ucinfo,_) -> + | Item.UnionCase(ucinfo, _) -> let prettyParams = match ucinfo.UnionCase.RecdFields with | [f] -> [PrettyParamOfUnionCaseField g denv NicePrint.isGeneratedUnionCaseField -1 f] @@ -283,29 +283,29 @@ module internal DescriptionListsImpl = let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInst [] rfinfo.FieldType [], prettyRetTyL - | Item.AnonRecdField(_anonInfo,tys,i, _) -> + | Item.AnonRecdField(_anonInfo, tys, i, _) -> let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInst [] tys.[i] [], prettyRetTyL | Item.ILField finfo -> - let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInst [] (finfo.FieldType(amap,m)) + let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInst [] (finfo.FieldType(amap, m)) [], prettyRetTyL | Item.Event einfo -> let _prettyTyparInst, prettyRetTyL = NicePrint.prettyLayoutOfUncurriedSig denv item.TyparInst [] (PropTypOfEventInfo infoReader m AccessibleFromSomewhere einfo) [], prettyRetTyL - | Item.Property(_,pinfo :: _) -> - let paramDatas = pinfo.GetParamDatas(amap,m) - let rty = pinfo.GetPropertyType(amap,m) + | Item.Property(_, pinfo :: _) -> + let paramDatas = pinfo.GetParamDatas(amap, m) + let rty = pinfo.GetPropertyType(amap, m) let _prettyTyparInst, prettyParams, prettyRetTyL, _prettyConstraintsL = PrettyParamsOfParamDatas g denv item.TyparInst paramDatas rty // FUTURE: prettyTyparInst is the pretty version of the known instantiations of type parameters in the output. It could be returned // for display as part of the method group prettyParams, prettyRetTyL - | Item.CtorGroup(_,(minfo :: _)) - | Item.MethodGroup(_,(minfo :: _),_) -> + | Item.CtorGroup(_, (minfo :: _)) + | Item.MethodGroup(_, (minfo :: _), _) -> let paramDatas = minfo.GetParamDatas(amap, m, minfo.FormalMethodInst) |> List.head let rty = minfo.GetFSharpReturnTy(amap, m, minfo.FormalMethodInst) let _prettyTyparInst, prettyParams, prettyRetTyL, _prettyConstraintsL = PrettyParamsOfParamDatas g denv item.TyparInst paramDatas rty @@ -313,18 +313,18 @@ module internal DescriptionListsImpl = // for display as part of the method group prettyParams, prettyRetTyL - | Item.CustomBuilder (_,vref) -> + | Item.CustomBuilder (_, vref) -> PrettyParamsAndReturnTypeOfItem infoReader m denv { item with Item = Item.Value vref } | Item.TypeVar _ -> [], emptyL - | Item.CustomOperation (_,usageText, Some minfo) -> + | Item.CustomOperation (_, usageText, Some minfo) -> match usageText() with | None -> let argNamesAndTys = SymbolHelpers.ParamNameAndTypesOfUnaryCustomOperation g minfo - let argTys, _ = PrettyTypes.PrettifyTypes g (argNamesAndTys |> List.map (fun (ParamNameAndType(_,ty)) -> ty)) - let paramDatas = (argNamesAndTys, argTys) ||> List.map2 (fun (ParamNameAndType(nmOpt, _)) argTy -> ParamData(false, false, false, NotOptional, NoCallerInfo, nmOpt, ReflectedArgInfo.None,argTy)) + let argTys, _ = PrettyTypes.PrettifyTypes g (argNamesAndTys |> List.map (fun (ParamNameAndType(_, ty)) -> ty)) + let paramDatas = (argNamesAndTys, argTys) ||> List.map2 (fun (ParamNameAndType(nmOpt, _)) argTy -> ParamData(false, false, false, NotOptional, NoCallerInfo, nmOpt, ReflectedArgInfo.None, argTy)) let rty = minfo.GetFSharpReturnTy(amap, m, minfo.FormalMethodInst) let _prettyTyparInst, prettyParams, prettyRetTyL, _prettyConstraintsL = PrettyParamsOfParamDatas g denv item.TyparInst paramDatas rty @@ -369,7 +369,7 @@ module internal DescriptionListsImpl = | TTyconEnum _ -> FSharpGlyph.Enum | TRecdRepr _ -> FSharpGlyph.Type | TUnionRepr _ -> FSharpGlyph.Union - | TILObjectRepr (TILObjectReprData (_,_,td)) -> + | TILObjectRepr (TILObjectReprData (_, _, td)) -> if td.IsClass then FSharpGlyph.Class elif td.IsStruct then FSharpGlyph.Struct elif td.IsInterface then FSharpGlyph.Interface @@ -399,11 +399,11 @@ module internal DescriptionListsImpl = // In this case just use GlyphMajor.Class. protectAssemblyExploration FSharpGlyph.Class (fun () -> match item with - | Item.Value(vref) | Item.CustomBuilder (_,vref) -> + | Item.Value(vref) | Item.CustomBuilder (_, vref) -> if isFunction denv.g vref.Type then FSharpGlyph.Method elif vref.LiteralValue.IsSome then FSharpGlyph.Constant else FSharpGlyph.Variable - | Item.Types(_,ty::_) -> typeToGlyph (stripTyEqns denv.g ty) + | Item.Types(_, ty::_) -> typeToGlyph (stripTyEqns denv.g ty) | Item.UnionCase _ | Item.ActivePatternCase _ -> FSharpGlyph.EnumMember | Item.ExnCase _ -> FSharpGlyph.Exception @@ -449,7 +449,7 @@ module internal DescriptionListsImpl = /// duplication could potentially be removed) let AnotherFlattenItems g m item = match item with - | Item.CtorGroup(nm,cinfos) -> List.map (fun minfo -> Item.CtorGroup(nm,[minfo])) cinfos + | Item.CtorGroup(nm, cinfos) -> List.map (fun minfo -> Item.CtorGroup(nm, [minfo])) cinfos | Item.FakeInterfaceCtor _ | Item.DelegateCtor _ -> [item] | Item.NewDef _ @@ -459,11 +459,11 @@ module internal DescriptionListsImpl = if isFunction g rfinfo.FieldType then [item] else [] | Item.Value v -> if isFunction g v.Type then [item] else [] - | Item.UnionCase(ucr,_) -> + | Item.UnionCase(ucr, _) -> if not ucr.UnionCase.IsNullary then [item] else [] | Item.ExnCase(ecr) -> if isNil (recdFieldsOfExnDefRef ecr) then [] else [item] - | Item.Property(_,pinfos) -> + | Item.Property(_, pinfos) -> let pinfo = List.head pinfos if pinfo.IsIndexer then [item] else [] #if !NO_EXTENSIONTYPING @@ -471,7 +471,7 @@ module internal DescriptionListsImpl = // we pretend that provided-types-with-static-args are method-like in order to get ParamInfo for them [item] #endif - | Item.MethodGroup(nm,minfos,orig) -> minfos |> List.map (fun minfo -> Item.MethodGroup(nm,[minfo],orig)) + | Item.MethodGroup(nm, minfos, orig) -> minfos |> List.map (fun minfo -> Item.MethodGroup(nm, [minfo], orig)) | Item.CustomOperation(_name, _helpText, _minfo) -> [item] | Item.TypeVar _ -> [] | Item.CustomBuilder _ -> [] @@ -569,17 +569,17 @@ type FSharpDeclarationListInfo(declarations: FSharpDeclarationListItem[], isForT | Some tref1, tref2 -> tyconRefEq g tref1 tref2 | _ -> false - // Adjust items priority. Sort by name. For things with the same name, + // Adjust items priority. Sort by name. For things with the same name, // - show types with fewer generic parameters first // - show types before over other related items - they usually have very useful XmlDocs let _, _, items = items |> List.map (fun x -> match x.Item with - | Item.Types (_,(TType_app(tcref,_) :: _)) -> { x with MinorPriority = 1 + tcref.TyparsNoRange.Length } + | Item.Types (_, (TType_app(tcref, _) :: _)) -> { x with MinorPriority = 1 + tcref.TyparsNoRange.Length } // Put delegate ctors after types, sorted by #typars. RemoveDuplicateItems will remove FakeInterfaceCtor and DelegateCtor if an earlier type is also reported with this name - | Item.FakeInterfaceCtor (TType_app(tcref,_)) - | Item.DelegateCtor (TType_app(tcref,_)) -> { x with MinorPriority = 1000 + tcref.TyparsNoRange.Length } + | Item.FakeInterfaceCtor (TType_app(tcref, _)) + | Item.DelegateCtor (TType_app(tcref, _)) -> { x with MinorPriority = 1000 + tcref.TyparsNoRange.Length } // Put type ctors after types, sorted by #typars. RemoveDuplicateItems will remove DefaultStructCtors if a type is also reported with this name | Item.CtorGroup (_, (cinfo :: _)) -> { x with MinorPriority = 1000 + 10 * cinfo.DeclaringTyconRef.TyparsNoRange.Length } | Item.MethodGroup(_, minfo :: _, _) -> { x with IsOwnMember = tyconRefOptEq x.Type minfo.DeclaringTyconRef } @@ -656,7 +656,7 @@ type FSharpDeclarationListInfo(declarations: FSharpDeclarationListItem[], isForT let name, nameInCode = if displayName.StartsWithOrdinal("( ") && displayName.EndsWithOrdinal(" )") then let cleanName = displayName.[2..displayName.Length - 3] - cleanName, + cleanName, if IsOperatorName displayName then cleanName else "``" + cleanName + "``" else displayName, @@ -697,14 +697,14 @@ type FSharpDeclarationListInfo(declarations: FSharpDeclarationListItem[], isForT | ns -> Some (System.String.Join(".", ns))) FSharpDeclarationListItem( - name, nameInCode, fullName, glyph, Choice1Of2 (items, infoReader, m, denv, reactor, checkAlive), getAccessibility item.Item, + name, nameInCode, fullName, glyph, Choice1Of2 (items, infoReader, m, denv, reactor, checkAlive), getAccessibility item.Item, item.Kind, item.IsOwnMember, item.MinorPriority, item.Unresolved.IsNone, namespaceToOpen)) new FSharpDeclarationListInfo(Array.ofList decls, isForType, false) static member Error msg = new FSharpDeclarationListInfo( - [| FSharpDeclarationListItem("", "", "", FSharpGlyph.Error, Choice2Of2 (FSharpToolTipText [FSharpStructuredToolTipElement.CompositionError msg]), + [| FSharpDeclarationListItem("", "", "", FSharpGlyph.Error, Choice2Of2 (FSharpToolTipText [FSharpStructuredToolTipElement.CompositionError msg]), None, CompletionItemKind.Other, false, 0, false, None) |], false, true) static member Empty = FSharpDeclarationListInfo([| |], false, false) @@ -715,8 +715,8 @@ type FSharpDeclarationListInfo(declarations: FSharpDeclarationListItem[], isForT /// a single, non-overloaded item such as union case or a named function value. // Note: instances of this type do not hold any references to any compiler resources. [] -type FSharpMethodGroupItem(description: FSharpToolTipText, xmlDoc: FSharpXmlDoc, - returnType: layout, parameters: FSharpMethodGroupItemParameter[], +type FSharpMethodGroupItem(description: FSharpToolTipText, xmlDoc: FSharpXmlDoc, + returnType: layout, parameters: FSharpMethodGroupItemParameter[], hasParameters: bool, hasParamArrayArg: bool, staticParameters: FSharpMethodGroupItemParameter[]) = /// The structured description representation for the method (or other item) @@ -737,13 +737,13 @@ type FSharpMethodGroupItem(description: FSharpToolTipText, xmlDoc: FShar /// The parameters of the method in the overload set member __.Parameters = parameters - /// Does the method support an arguments list? This is always true except for static type instantiations like TP<42,"foo">. + /// Does the method support an arguments list? This is always true except for static type instantiations like TP<42, "foo">. member __.HasParameters = hasParameters /// Does the method support a params list arg? member __.HasParamArrayArg = hasParamArrayArg - /// Does the type name or method support a static arguments list, like TP<42,"foo"> or conn.CreateCommand<42, "foo">(arg1, arg2)? + /// Does the type name or method support a static arguments list, like TP<42, "foo"> or conn.CreateCommand<42, "foo">(arg1, arg2)? member __.StaticParameters = staticParameters @@ -802,8 +802,8 @@ type FSharpMethodGroup( name: string, unsortedMethods: FSharpMethodGroupItem[] ) let hasParamArrayArg = match flatItem with - | Item.CtorGroup(_,[meth]) - | Item.MethodGroup(_,[meth],_) -> meth.HasParamArrayArg(infoReader.amap, m, meth.FormalMethodInst) + | Item.CtorGroup(_, [meth]) + | Item.MethodGroup(_, [meth], _) -> meth.HasParamArrayArg(infoReader.amap, m, meth.FormalMethodInst) | _ -> false let hasStaticParameters = diff --git a/src/fsharp/service/ServiceLexing.fs b/src/fsharp/service/ServiceLexing.fs index 23af633f803..e751049ebfc 100755 --- a/src/fsharp/service/ServiceLexing.fs +++ b/src/fsharp/service/ServiceLexing.fs @@ -140,13 +140,13 @@ type FSharpTokenCharKind = /// Information about a particular token from the tokenizer type FSharpTokenInfo = { - LeftColumn:int - RightColumn:int - ColorClass:FSharpTokenColorKind - CharClass:FSharpTokenCharKind - FSharpTokenTriggerClass:FSharpTokenTriggerClass - Tag:int - TokenName:string + LeftColumn: int + RightColumn: int + ColorClass: FSharpTokenColorKind + CharClass: FSharpTokenCharKind + FSharpTokenTriggerClass: FSharpTokenTriggerClass + Tag: int + TokenName: string FullMatchedLength: int } //---------------------------------------------------------------------------- @@ -164,31 +164,31 @@ module internal TokenClassifications = | IDENT s -> if s.Length <= 0 then - System.Diagnostics.Debug.Assert(false, "BUG:Received zero length IDENT token.") + System.Diagnostics.Debug.Assert(false, "BUG: Received zero length IDENT token.") // This is related to 4783. Recover by treating as lower case identifier. - (FSharpTokenColorKind.Identifier,FSharpTokenCharKind.Identifier,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) else if System.Char.ToUpperInvariant s.[0] = s.[0] then - (FSharpTokenColorKind.UpperIdentifier,FSharpTokenCharKind.Identifier,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.UpperIdentifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) else - (FSharpTokenColorKind.Identifier,FSharpTokenCharKind.Identifier,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) // 'in' when used in a 'join' in a query expression | JOIN_IN -> - (FSharpTokenColorKind.Identifier,FSharpTokenCharKind.Identifier,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Identifier, FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) | DECIMAL _ | BIGNUM _ | INT8 _ | UINT8 _ | INT16 _ | UINT16 _ | INT32 _ | UINT32 _ | INT64 _ | UINT64 _ | UNATIVEINT _ | NATIVEINT _ | IEEE32 _ | IEEE64 _ - -> (FSharpTokenColorKind.Number,FSharpTokenCharKind.Literal,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Number, FSharpTokenCharKind.Literal, FSharpTokenTriggerClass.None) | INT32_DOT_DOT _ // This will color the whole "1.." expression in a 'number' color // (this isn't entirely correct, but it'll work for now - see bug 3727) - -> (FSharpTokenColorKind.Number,FSharpTokenCharKind.Operator,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Number, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) | INFIX_STAR_DIV_MOD_OP ("mod" | "land" | "lor" | "lxor") | INFIX_STAR_STAR_OP ("lsl" | "lsr" | "asr") - -> (FSharpTokenColorKind.Keyword,FSharpTokenCharKind.Keyword,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | LPAREN_STAR_RPAREN | DOLLAR | COLON_GREATER | COLON_COLON @@ -197,7 +197,7 @@ module internal TokenClassifications = | HIGH_PRECEDENCE_TYAPP | COLON_EQUALS | EQUALS | RQUOTE_DOT _ | MINUS | ADJACENT_PREFIX_OP _ - -> (FSharpTokenColorKind.Operator,FSharpTokenCharKind.Operator,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) | INFIX_COMPARE_OP _ // This is a whole family: .< .> .= .!= .$ | FUNKY_OPERATOR_NAME _ // This is another whole family, including: .[] and .() @@ -207,52 +207,52 @@ module internal TokenClassifications = | INFIX_BAR_OP _ | INFIX_STAR_DIV_MOD_OP _ | INFIX_AMP_OP _ -> - (FSharpTokenColorKind.Operator,FSharpTokenCharKind.Operator,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.None) | DOT_DOT -> - (FSharpTokenColorKind.Operator,FSharpTokenCharKind.Operator,FSharpTokenTriggerClass.MemberSelect) + (FSharpTokenColorKind.Operator, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.MemberSelect) | COMMA - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter,FSharpTokenTriggerClass.ParamNext) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamNext) | DOT - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter,FSharpTokenTriggerClass.MemberSelect) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MemberSelect) | BAR - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter,FSharpTokenTriggerClass.None (* FSharpTokenTriggerClass.ChoiceSelect *)) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None (* FSharpTokenTriggerClass.ChoiceSelect *)) | HASH | STAR | SEMICOLON | SEMICOLON_SEMICOLON | COLON - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None) | QUOTE | UNDERSCORE | INFIX_AT_HAT_OP _ - -> (FSharpTokenColorKind.Identifier ,FSharpTokenCharKind.Identifier,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Identifier , FSharpTokenCharKind.Identifier, FSharpTokenTriggerClass.None) | LESS _ - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Operator,FSharpTokenTriggerClass.ParamStart) // for type provider static arguments + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamStart) // for type provider static arguments | GREATER _ - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Operator,FSharpTokenTriggerClass.ParamEnd) // for type provider static arguments + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Operator, FSharpTokenTriggerClass.ParamEnd) // for type provider static arguments | LPAREN // We need 'ParamStart' to trigger the 'GetDeclarations' method to show param info automatically // this is needed even if we don't use MPF for determining information about params - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamStart ||| FSharpTokenTriggerClass.MatchBraces) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamStart ||| FSharpTokenTriggerClass.MatchBraces) | RPAREN | RPAREN_COMING_SOON | RPAREN_IS_HERE - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamEnd ||| FSharpTokenTriggerClass.MatchBraces) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.ParamEnd ||| FSharpTokenTriggerClass.MatchBraces) | LBRACK_LESS - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter,FSharpTokenTriggerClass.None ) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None ) | LQUOTE _ | LBRACK | LBRACE | LBRACK_BAR | LBRACE_BAR - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter,FSharpTokenTriggerClass.MatchBraces ) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces ) | GREATER_RBRACK | GREATER_BAR_RBRACK - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter,FSharpTokenTriggerClass.None ) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.None ) | RQUOTE _ | RBRACK | RBRACE | RBRACE_COMING_SOON | RBRACE_IS_HERE | BAR_RBRACK | BAR_RBRACE - -> (FSharpTokenColorKind.Punctuation,FSharpTokenCharKind.Delimiter,FSharpTokenTriggerClass.MatchBraces ) + -> (FSharpTokenColorKind.Punctuation, FSharpTokenCharKind.Delimiter, FSharpTokenTriggerClass.MatchBraces ) | PUBLIC | PRIVATE | INTERNAL | BASE | GLOBAL | CONSTRAINT | INSTANCE | DELEGATE | INHERIT|CONSTRUCTOR|DEFAULT|OVERRIDE|ABSTRACT|CLASS @@ -270,38 +270,38 @@ module internal TokenClassifications = | HIGH_PRECEDENCE_PAREN_APP | FIXED | HIGH_PRECEDENCE_BRACK_APP | TYPE_COMING_SOON | TYPE_IS_HERE | MODULE_COMING_SOON | MODULE_IS_HERE - -> (FSharpTokenColorKind.Keyword,FSharpTokenCharKind.Keyword,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | BEGIN - -> (FSharpTokenColorKind.Keyword,FSharpTokenCharKind.Keyword,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | END - -> (FSharpTokenColorKind.Keyword,FSharpTokenCharKind.Keyword,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | HASH_LIGHT _ | HASH_LINE _ | HASH_IF _ | HASH_ELSE _ | HASH_ENDIF _ -> - (FSharpTokenColorKind.PreprocessorKeyword,FSharpTokenCharKind.WhiteSpace,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.PreprocessorKeyword, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) | INACTIVECODE _ -> - (FSharpTokenColorKind.InactiveCode,FSharpTokenCharKind.WhiteSpace,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.InactiveCode, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) | LEX_FAILURE _ | WHITESPACE _ -> - (FSharpTokenColorKind.Default,FSharpTokenCharKind.WhiteSpace,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Default, FSharpTokenCharKind.WhiteSpace, FSharpTokenTriggerClass.None) | COMMENT _ -> - (FSharpTokenColorKind.Comment,FSharpTokenCharKind.Comment,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Comment, FSharpTokenCharKind.Comment, FSharpTokenTriggerClass.None) | LINE_COMMENT _ -> - (FSharpTokenColorKind.Comment,FSharpTokenCharKind.LineComment,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Comment, FSharpTokenCharKind.LineComment, FSharpTokenTriggerClass.None) | STRING_TEXT _ -> - (FSharpTokenColorKind.String,FSharpTokenCharKind.String,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.String, FSharpTokenCharKind.String, FSharpTokenTriggerClass.None) | KEYWORD_STRING _ -> - (FSharpTokenColorKind.Keyword,FSharpTokenCharKind.Keyword,FSharpTokenTriggerClass.None) + (FSharpTokenColorKind.Keyword, FSharpTokenCharKind.Keyword, FSharpTokenTriggerClass.None) | BYTEARRAY _ | STRING _ | CHAR _ (* bug://2863 asks to color 'char' as "string" *) - -> (FSharpTokenColorKind.String,FSharpTokenCharKind.String,FSharpTokenTriggerClass.None) + -> (FSharpTokenColorKind.String, FSharpTokenCharKind.String, FSharpTokenTriggerClass.None) | EOF _ -> failwith "tokenInfo" module internal TestExpose = @@ -338,7 +338,7 @@ type FSharpTokenizerColorState = module internal LexerStateEncoding = - let computeNextLexState token (prevLexcont:LexerWhitespaceContinuation) = + let computeNextLexState token (prevLexcont: LexerWhitespaceContinuation) = match token with | HASH_LINE s | HASH_LIGHT s @@ -389,13 +389,13 @@ module internal LexerStateEncoding = let inline lexStateOfColorState (state: FSharpTokenizerColorState) = (int64 state <<< lexstateStart) &&& lexstateMask - let encodeLexCont (colorState:FSharpTokenizerColorState) ncomments (b:pos) ifdefStack light = + let encodeLexCont (colorState: FSharpTokenizerColorState) ncomments (b: pos) ifdefStack light = let mutable ifdefStackCount = 0 let mutable ifdefStackBits = 0 for ifOrElse in ifdefStack do match ifOrElse with - | (IfDefIf,_) -> () - | (IfDefElse,_) -> + | (IfDefIf, _) -> () + | (IfDefElse, _) -> ifdefStackBits <- (ifdefStackBits ||| (1 <<< ifdefStackCount)) ifdefStackCount <- ifdefStackCount + 1 @@ -409,7 +409,7 @@ module internal LexerStateEncoding = OtherBits = bits } - let decodeLexCont (state:FSharpTokenizerLexState) = + let decodeLexCont (state: FSharpTokenizerLexState) = let mutable ifDefs = [] let bits = state.OtherBits let ifdefStackCount = (int32) ((bits &&& ifdefstackCountMask) >>> ifdefstackCountStart) @@ -419,51 +419,51 @@ module internal LexerStateEncoding = let bit = ifdefStackCount-i let mask = 1 <<< bit let ifDef = (if ifdefStack &&& mask = 0 then IfDefIf else IfDefElse) - ifDefs<-(ifDef,range0)::ifDefs + ifDefs<-(ifDef, range0)::ifDefs colorStateOfLexState state, int32 ((bits &&& ncommentsMask) >>> ncommentsStart), pos.Decode state.PosBits, ifDefs, boolOfBit ((bits &&& hardwhitePosMask) >>> hardwhitePosStart) - let encodeLexInt lightSyntaxStatus (lexcont:LexerWhitespaceContinuation) = - let tag,n1,p1,ifd = + let encodeLexInt lightSyntaxStatus (lexcont: LexerWhitespaceContinuation) = + let tag, n1, p1, ifd = match lexcont with - | LexCont.Token ifd -> FSharpTokenizerColorState.Token, 0L, pos0, ifd - | LexCont.IfDefSkip (ifd,n,m) -> FSharpTokenizerColorState.IfDefSkip, int64 n, m.Start, ifd - | LexCont.EndLine(LexerEndlineContinuation.Skip(ifd,n,m)) -> FSharpTokenizerColorState.EndLineThenSkip, int64 n, m.Start, ifd - | LexCont.EndLine(LexerEndlineContinuation.Token(ifd)) -> FSharpTokenizerColorState.EndLineThenToken, 0L, pos0, ifd - | LexCont.String (ifd,m) -> FSharpTokenizerColorState.String, 0L, m.Start, ifd - | LexCont.Comment (ifd,n,m) -> FSharpTokenizerColorState.Comment, int64 n, m.Start, ifd - | LexCont.SingleLineComment (ifd,n,m) -> FSharpTokenizerColorState.SingleLineComment, int64 n, m.Start, ifd - | LexCont.StringInComment (ifd,n,m) -> FSharpTokenizerColorState.StringInComment, int64 n, m.Start, ifd - | LexCont.VerbatimStringInComment (ifd,n,m) -> FSharpTokenizerColorState.VerbatimStringInComment, int64 n, m.Start, ifd - | LexCont.TripleQuoteStringInComment (ifd,n,m) -> FSharpTokenizerColorState.TripleQuoteStringInComment,int64 n, m.Start, ifd - | LexCont.MLOnly (ifd,m) -> FSharpTokenizerColorState.CamlOnly, 0L, m.Start, ifd - | LexCont.VerbatimString (ifd,m) -> FSharpTokenizerColorState.VerbatimString, 0L, m.Start, ifd - | LexCont.TripleQuoteString (ifd,m) -> FSharpTokenizerColorState.TripleQuoteString, 0L, m.Start, ifd + | LexCont.Token ifd -> FSharpTokenizerColorState.Token, 0L, pos0, ifd + | LexCont.IfDefSkip (ifd, n, m) -> FSharpTokenizerColorState.IfDefSkip, int64 n, m.Start, ifd + | LexCont.EndLine(LexerEndlineContinuation.Skip(ifd, n, m)) -> FSharpTokenizerColorState.EndLineThenSkip, int64 n, m.Start, ifd + | LexCont.EndLine(LexerEndlineContinuation.Token(ifd)) -> FSharpTokenizerColorState.EndLineThenToken, 0L, pos0, ifd + | LexCont.String (ifd, m) -> FSharpTokenizerColorState.String, 0L, m.Start, ifd + | LexCont.Comment (ifd, n, m) -> FSharpTokenizerColorState.Comment, int64 n, m.Start, ifd + | LexCont.SingleLineComment (ifd, n, m) -> FSharpTokenizerColorState.SingleLineComment, int64 n, m.Start, ifd + | LexCont.StringInComment (ifd, n, m) -> FSharpTokenizerColorState.StringInComment, int64 n, m.Start, ifd + | LexCont.VerbatimStringInComment (ifd, n, m) -> FSharpTokenizerColorState.VerbatimStringInComment, int64 n, m.Start, ifd + | LexCont.TripleQuoteStringInComment (ifd, n, m) -> FSharpTokenizerColorState.TripleQuoteStringInComment, int64 n, m.Start, ifd + | LexCont.MLOnly (ifd, m) -> FSharpTokenizerColorState.CamlOnly, 0L, m.Start, ifd + | LexCont.VerbatimString (ifd, m) -> FSharpTokenizerColorState.VerbatimString, 0L, m.Start, ifd + | LexCont.TripleQuoteString (ifd, m) -> FSharpTokenizerColorState.TripleQuoteString, 0L, m.Start, ifd encodeLexCont tag n1 p1 ifd lightSyntaxStatus - let decodeLexInt (state:FSharpTokenizerLexState) = - let tag,n1,p1,ifd,lightSyntaxStatusInital = decodeLexCont state + let decodeLexInt (state: FSharpTokenizerLexState) = + let tag, n1, p1, ifd, lightSyntaxStatusInital = decodeLexCont state let lexcont = match tag with | FSharpTokenizerColorState.Token -> LexCont.Token ifd - | FSharpTokenizerColorState.IfDefSkip -> LexCont.IfDefSkip (ifd,n1,mkRange "file" p1 p1) - | FSharpTokenizerColorState.String -> LexCont.String (ifd,mkRange "file" p1 p1) - | FSharpTokenizerColorState.Comment -> LexCont.Comment (ifd,n1,mkRange "file" p1 p1) - | FSharpTokenizerColorState.SingleLineComment -> LexCont.SingleLineComment (ifd,n1,mkRange "file" p1 p1) - | FSharpTokenizerColorState.StringInComment -> LexCont.StringInComment (ifd,n1,mkRange "file" p1 p1) - | FSharpTokenizerColorState.VerbatimStringInComment -> LexCont.VerbatimStringInComment (ifd,n1,mkRange "file" p1 p1) - | FSharpTokenizerColorState.TripleQuoteStringInComment -> LexCont.TripleQuoteStringInComment (ifd,n1,mkRange "file" p1 p1) - | FSharpTokenizerColorState.CamlOnly -> LexCont.MLOnly (ifd,mkRange "file" p1 p1) - | FSharpTokenizerColorState.VerbatimString -> LexCont.VerbatimString (ifd,mkRange "file" p1 p1) - | FSharpTokenizerColorState.TripleQuoteString -> LexCont.TripleQuoteString (ifd,mkRange "file" p1 p1) - | FSharpTokenizerColorState.EndLineThenSkip -> LexCont.EndLine(LexerEndlineContinuation.Skip(ifd,n1,mkRange "file" p1 p1)) + | FSharpTokenizerColorState.IfDefSkip -> LexCont.IfDefSkip (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.String -> LexCont.String (ifd, mkRange "file" p1 p1) + | FSharpTokenizerColorState.Comment -> LexCont.Comment (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.SingleLineComment -> LexCont.SingleLineComment (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.StringInComment -> LexCont.StringInComment (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.VerbatimStringInComment -> LexCont.VerbatimStringInComment (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.TripleQuoteStringInComment -> LexCont.TripleQuoteStringInComment (ifd, n1, mkRange "file" p1 p1) + | FSharpTokenizerColorState.CamlOnly -> LexCont.MLOnly (ifd, mkRange "file" p1 p1) + | FSharpTokenizerColorState.VerbatimString -> LexCont.VerbatimString (ifd, mkRange "file" p1 p1) + | FSharpTokenizerColorState.TripleQuoteString -> LexCont.TripleQuoteString (ifd, mkRange "file" p1 p1) + | FSharpTokenizerColorState.EndLineThenSkip -> LexCont.EndLine(LexerEndlineContinuation.Skip(ifd, n1, mkRange "file" p1 p1)) | FSharpTokenizerColorState.EndLineThenToken -> LexCont.EndLine(LexerEndlineContinuation.Token(ifd)) | _ -> LexCont.Token [] - lightSyntaxStatusInital,lexcont + lightSyntaxStatusInital, lexcont let callLexCont lexcont args skip lexbuf = let argsWithIfDefs ifd = @@ -474,18 +474,18 @@ module internal LexerStateEncoding = match lexcont with | LexCont.EndLine cont -> Lexer.endline cont args skip lexbuf | LexCont.Token ifd -> Lexer.token (argsWithIfDefs ifd) skip lexbuf - | LexCont.IfDefSkip (ifd,n,m) -> Lexer.ifdefSkip n m (argsWithIfDefs ifd) skip lexbuf + | LexCont.IfDefSkip (ifd, n, m) -> Lexer.ifdefSkip n m (argsWithIfDefs ifd) skip lexbuf // Q: What's this magic 100 number for? Q: it's just an initial buffer size. - | LexCont.String (ifd,m) -> Lexer.string (ByteBuffer.Create 100,defaultStringFinisher,m,(argsWithIfDefs ifd)) skip lexbuf - | LexCont.Comment (ifd,n,m) -> Lexer.comment (n,m,(argsWithIfDefs ifd)) skip lexbuf + | LexCont.String (ifd, m) -> Lexer.string (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf + | LexCont.Comment (ifd, n, m) -> Lexer.comment (n, m, (argsWithIfDefs ifd)) skip lexbuf // The first argument is 'None' because we don't need XML comments when called from VS - | LexCont.SingleLineComment (ifd,n,m) -> Lexer.singleLineComment (None,n,m,(argsWithIfDefs ifd)) skip lexbuf - | LexCont.StringInComment (ifd,n,m) -> Lexer.stringInComment n m (argsWithIfDefs ifd) skip lexbuf - | LexCont.VerbatimStringInComment (ifd,n,m) -> Lexer.verbatimStringInComment n m (argsWithIfDefs ifd) skip lexbuf - | LexCont.TripleQuoteStringInComment (ifd,n,m) -> Lexer.tripleQuoteStringInComment n m (argsWithIfDefs ifd) skip lexbuf - | LexCont.MLOnly (ifd,m) -> Lexer.mlOnly m (argsWithIfDefs ifd) skip lexbuf - | LexCont.VerbatimString (ifd,m) -> Lexer.verbatimString (ByteBuffer.Create 100,defaultStringFinisher,m,(argsWithIfDefs ifd)) skip lexbuf - | LexCont.TripleQuoteString (ifd,m) -> Lexer.tripleQuoteString (ByteBuffer.Create 100,defaultStringFinisher,m,(argsWithIfDefs ifd)) skip lexbuf + | LexCont.SingleLineComment (ifd, n, m) -> Lexer.singleLineComment (None, n, m, (argsWithIfDefs ifd)) skip lexbuf + | LexCont.StringInComment (ifd, n, m) -> Lexer.stringInComment n m (argsWithIfDefs ifd) skip lexbuf + | LexCont.VerbatimStringInComment (ifd, n, m) -> Lexer.verbatimStringInComment n m (argsWithIfDefs ifd) skip lexbuf + | LexCont.TripleQuoteStringInComment (ifd, n, m) -> Lexer.tripleQuoteStringInComment n m (argsWithIfDefs ifd) skip lexbuf + | LexCont.MLOnly (ifd, m) -> Lexer.mlOnly m (argsWithIfDefs ifd) skip lexbuf + | LexCont.VerbatimString (ifd, m) -> Lexer.verbatimString (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf + | LexCont.TripleQuoteString (ifd, m) -> Lexer.tripleQuoteString (ByteBuffer.Create 100, defaultStringFinisher, m, (argsWithIfDefs ifd)) skip lexbuf //---------------------------------------------------------------------------- // Colorization @@ -500,9 +500,9 @@ type SingleLineTokenState = /// Split a line into tokens and attach information about the tokens. This information is used by Visual Studio. [] -type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, +type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, maxLength: int option, - filename : Option, + filename : Option, lexArgsLightOn : lexargs, lexArgsLightOff : lexargs ) = @@ -524,14 +524,14 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, let delayToken tok = tokenStack.Push(tok) // Process: anywhite* # - let processDirective (str:string) directiveLength delay cont = + let processDirective (str: string) directiveLength delay cont = let hashIdx = str.IndexOf("#", StringComparison.Ordinal) if (hashIdx <> 0) then delay(WHITESPACE cont, 0, hashIdx - 1) delay(HASH_IF(range0, "", cont), hashIdx, hashIdx + directiveLength) hashIdx + directiveLength + 1 // Process: anywhite* ("//" [^'\n''\r']*)? - let processWhiteAndComment (str:string) offset delay cont = + let processWhiteAndComment (str: string) offset delay cont = let rest = str.Substring(offset, str.Length - offset) let comment = rest.IndexOf('/') let spaceLength = if comment = -1 then rest.Length else comment @@ -548,7 +548,7 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, // Split the following line: // anywhite* ("#else"|"#endif") anywhite* ("//" [^'\n''\r']*)? - let processHashEndElse ofs (str:string) length cont = + let processHashEndElse ofs (str: string) length cont = processDirectiveLine ofs (fun delay -> // Process: anywhite* "#else" / anywhite* "#endif" let offset = processDirective str length delay cont @@ -557,7 +557,7 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, // Split the following line: // anywhite* "#if" anywhite+ ident anywhite* ("//" [^'\n''\r']*)? - let processHashIfLine ofs (str:string) cont = + let processHashIfLine ofs (str: string) cont = let With n m = if (n < 0) then m else n processDirectiveLine ofs (fun delay -> // Process: anywhite* "#if" @@ -589,7 +589,7 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, use unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> DiscardErrorsLogger) let lightSyntaxStatusInital, lexcontInitial = LexerStateEncoding.decodeLexInt lexintInitial - let lightSyntaxStatus = LightSyntaxStatus(lightSyntaxStatusInital,false) + let lightSyntaxStatus = LightSyntaxStatus(lightSyntaxStatusInital, false) // Build the arguments to the lexer function let lexargs = if lightSyntaxStatusInital then lexArgsLightOn else lexArgsLightOff @@ -605,7 +605,7 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, | Some mx when rightp.Line > leftp.Line -> mx | _ -> rightp.Column let rightc = rightc - 1 - leftc,rightc + leftc, rightc // Get the token & position - either from a stack or from the lexer try @@ -626,10 +626,10 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, false, processHashEndElse m.StartColumn lineStr 4 cont | HASH_ENDIF(m, lineStr, cont) when lineStr <> "" -> false, processHashEndElse m.StartColumn lineStr 5 cont - | RQUOTE_DOT (s,raw) -> + | RQUOTE_DOT (s, raw) -> delayToken(DOT, rightc, rightc) - false, (RQUOTE (s,raw), leftc, rightc - 1) - | INFIX_COMPARE_OP (LexFilter.TyparsCloseOp(greaters,afterOp) as opstr) -> + false, (RQUOTE (s, raw), leftc, rightc - 1) + | INFIX_COMPARE_OP (LexFilter.TyparsCloseOp(greaters, afterOp) as opstr) -> match afterOp with | None -> () | Some tok -> delayToken(tok, leftc + greaters.Length, rightc) @@ -679,12 +679,12 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, match token with | EOF lexcont -> // End of text! No more tokens. - None,lexcont,0 + None, lexcont, 0 | LEX_FAILURE _ -> None, LexerStateEncoding.revertToDefaultLexCont, 0 | _ -> // Get the information about the token - let (colorClass,charClass,triggerClass) = TokenClassifications.tokenInfo token + let (colorClass, charClass, triggerClass) = TokenClassifications.tokenInfo token let lexcontFinal = // If we're using token from cache, we don't move forward with lexing if isCached then lexcontInitial else LexerStateEncoding.computeNextLexState token lexcontInitial @@ -706,7 +706,7 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, LexerStateEncoding.encodeLexInt lightSyntaxStatus.Status lexcontFinal // Check for patterns like #-IDENT and see if they look like meta commands for .fsx files. If they do then merge them into a single token. - let tokenDataOption,lexintFinal = + let tokenDataOption, lexintFinal = let lexintFinal = FinalState(lexcontFinal) match tokenDataOption, singleLineTokenState, tokenTagToTokenId tokenTag with | Some(tokenData), SingleLineTokenState.BeforeHash, TOKEN_HASH -> @@ -716,40 +716,40 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, let isCached, (nextToken, _, rightc) = GetTokenWithPosition(lexcontInitial) match nextToken with | IDENT possibleMetacommand -> - match fsx,possibleMetacommand with + match fsx, possibleMetacommand with // These are for script (.fsx and .fsscript) files. - | true,"r" - | true,"reference" - | true,"I" - | true,"load" - | true,"time" - | true,"dbgbreak" - | true,"cd" + | true, "r" + | true, "reference" + | true, "I" + | true, "load" + | true, "time" + | true, "dbgbreak" + | true, "cd" #if DEBUG - | true,"terms" - | true,"types" - | true,"savedll" - | true,"nosavedll" + | true, "terms" + | true, "types" + | true, "savedll" + | true, "nosavedll" #endif - | true,"silentCd" - | true,"q" - | true,"quit" - | true,"help" + | true, "silentCd" + | true, "q" + | true, "quit" + | true, "help" // These are for script and non-script - | _,"nowarn" -> + | _, "nowarn" -> // Merge both tokens into one. let lexcontFinal = if (isCached) then lexcontInitial else LexerStateEncoding.computeNextLexState token lexcontInitial let tokenData = {tokenData with RightColumn=rightc;ColorClass=FSharpTokenColorKind.PreprocessorKeyword;CharClass=FSharpTokenCharKind.Keyword;FSharpTokenTriggerClass=FSharpTokenTriggerClass.None} let lexintFinal = FinalState(lexcontFinal) - Some(tokenData),lexintFinal - | _ -> tokenDataOption,lexintFinal - | _ -> tokenDataOption,lexintFinal + Some(tokenData), lexintFinal + | _ -> tokenDataOption, lexintFinal + | _ -> tokenDataOption, lexintFinal | _, SingleLineTokenState.BeforeHash, TOKEN_WHITESPACE -> // Allow leading whitespace. - tokenDataOption,lexintFinal + tokenDataOption, lexintFinal | _ -> singleLineTokenState <- SingleLineTokenState.NoFurtherMatchPossible - tokenDataOption,lexintFinal + tokenDataOption, lexintFinal tokenDataOption, lexintFinal @@ -763,8 +763,8 @@ type FSharpLineTokenizer(lexbuf: UnicodeLexing.Lexbuf, type FSharpSourceTokenizer(defineConstants : string list, filename : string option) = let lexResourceManager = new Lexhelp.LexResourceManager() - let lexArgsLightOn = mkLexargs(filename,defineConstants,LightSyntaxStatus(true,false),lexResourceManager, ref [],DiscardErrorsLogger) - let lexArgsLightOff = mkLexargs(filename,defineConstants,LightSyntaxStatus(false,false),lexResourceManager, ref [],DiscardErrorsLogger) + let lexArgsLightOn = mkLexargs(filename, defineConstants, LightSyntaxStatus(true, false), lexResourceManager, ref [], DiscardErrorsLogger) + let lexArgsLightOff = mkLexargs(filename, defineConstants, LightSyntaxStatus(false, false), lexResourceManager, ref [], DiscardErrorsLogger) member this.CreateLineTokenizer(lineText: string) = let lexbuf = UnicodeLexing.StringAsLexbuf lineText diff --git a/src/fsharp/service/ServiceUntypedParse.fs b/src/fsharp/service/ServiceUntypedParse.fs index ab5db3d70e1..1e6b98ebdc4 100755 --- a/src/fsharp/service/ServiceUntypedParse.fs +++ b/src/fsharp/service/ServiceUntypedParse.fs @@ -149,7 +149,7 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op | _ -> () yield! walkExpr true e ] - and walkExprOpt (spAlways:bool) eOpt = [ match eOpt with Some e -> yield! walkExpr spAlways e | _ -> () ] + and walkExprOpt (spAlways: bool) eOpt = [ match eOpt with Some e -> yield! walkExpr spAlways e | _ -> () ] and IsBreakableExpression e = match e with @@ -162,7 +162,7 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op // Determine the breakpoint locations for an expression. spAlways indicates we always // emit a breakpoint location for the expression unless it is a syntactic control flow construct - and walkExpr (spAlways:bool) e = + and walkExpr (spAlways: bool) e = let m = e.Range if not (isMatchRange m) then [] else [ if spAlways && IsBreakableExpression e then @@ -383,7 +383,7 @@ type FSharpParseFileResults(errors: FSharpErrorInfo[], input: Ast.ParsedInput op [] /// Get information for implementation file - let walkImplFile (modules:SynModuleOrNamespace list) = List.collect walkModule modules + let walkImplFile (modules: SynModuleOrNamespace list) = List.collect walkModule modules match input with | Some(ParsedInput.ImplFile(ParsedImplFileInput(modules = modules))) -> walkImplFile modules @@ -439,7 +439,7 @@ type ModuleKind = { IsAutoOpen: bool; HasModuleSuffix: bool } type EntityKind = | Attribute | Type - | FunctionOrValue of isActivePattern:bool + | FunctionOrValue of isActivePattern: bool | Module of ModuleKind override x.ToString() = sprintf "%A" x @@ -449,11 +449,11 @@ module UntypedParseImpl = let emptyStringSet = HashSet() - let GetRangeOfExprLeftOfDot(pos:pos, parseTreeOpt) = + let GetRangeOfExprLeftOfDot(pos: pos, parseTreeOpt) = match parseTreeOpt with | None -> None | Some(parseTree) -> - let CheckLongIdent(longIdent:LongIdent) = + let CheckLongIdent(longIdent: LongIdent) = // find the longest prefix before the "pos" dot let mutable r = (List.head longIdent).idRange let mutable couldBeBeforeFront = true @@ -546,7 +546,7 @@ module UntypedParseImpl = }) /// searches for the expression island suitable for the evaluation by the debugger - let TryFindExpressionIslandInPosition(pos:pos, parseTreeOpt) = + let TryFindExpressionIslandInPosition(pos: pos, parseTreeOpt) = match parseTreeOpt with | None -> None | Some(parseTree) -> @@ -791,7 +791,7 @@ module UntypedParseImpl = and walkType = function | SynType.LongIdent ident -> // we protect it with try..with because System.Exception : rangeOfLidwd may raise - // at FSharp.Compiler.Ast.LongIdentWithDots.get_Range() in D:\j\workspace\release_ci_pa---3f142ccc\src\fsharp\ast.fs:line 156 + // at FSharp.Compiler.Ast.LongIdentWithDots.get_Range() in D:\j\workspace\release_ci_pa---3f142ccc\src\fsharp\ast.fs: line 156 try ifPosInRange ident.Range (fun _ -> Some EntityKind.Type) with _ -> None | SynType.App(ty, _, types, _, _, _, _) -> walkType ty |> Option.orElse (List.tryPick walkType types) @@ -1341,7 +1341,7 @@ module UntypedParseImpl = | idx when idx < str.Length -> str.[idx + 1..].TrimStart() | _ -> "" - let isLongIdent = Seq.forall (fun c -> IsIdentifierPartCharacter c || c = '.' || c = ':') // ':' may occur in "[]" + let isLongIdent = Seq.forall (fun c -> IsIdentifierPartCharacter c || c = '.' || c = ':') // ':' may occur in "[]" // match the most nested paired [< and >] first let matches = diff --git a/src/fsharp/symbols/Exprs.fs b/src/fsharp/symbols/Exprs.fs index 6cba7d97db1..fc50346f301 100644 --- a/src/fsharp/symbols/Exprs.fs +++ b/src/fsharp/symbols/Exprs.fs @@ -36,7 +36,7 @@ module ExprTranslationImpl = isinstVals = ValMap<_>.Empty substVals = ValMap<_>.Empty } - member env.BindTypar (v:Typar, gp) = + member env.BindTypar (v: Typar, gp) = { env with tyvs = env.tyvs.Add(v.Stamp, gp ) } member env.BindTypars vs = @@ -59,7 +59,7 @@ module ExprTranslationImpl = exception IgnoringPartOfQuotedTermWarning of string * Range.range - let wfail (msg, m:range) = failwith (msg + sprintf " at %s" (m.ToString())) + let wfail (msg, m: range) = failwith (msg + sprintf " at %s" (m.ToString())) /// The core tree of data produced by converting F# compiler TAST expressions into the form which we make available through the compiler API @@ -113,14 +113,14 @@ type E = | ILAsm of string * FSharpType list * FSharpExpr list /// Used to represent the information at an object expression member -and [] FSharpObjectExprOverride(sgn: FSharpAbstractSignature, gps: FSharpGenericParameter list, args:FSharpMemberOrFunctionOrValue list list, body: FSharpExpr) = +and [] FSharpObjectExprOverride(sgn: FSharpAbstractSignature, gps: FSharpGenericParameter list, args: FSharpMemberOrFunctionOrValue list list, body: FSharpExpr) = member __.Signature = sgn member __.GenericParameters = gps member __.CurriedParameterGroups = args member __.Body = body /// The type of expressions provided through the compiler API. -and [] FSharpExpr (cenv, f: (unit -> FSharpExpr) option, e: E, m:range, ty) = +and [] FSharpExpr (cenv, f: (unit -> FSharpExpr) option, e: E, m: range, ty) = member x.Range = m member x.Type = FSharpType(cenv, ty) @@ -275,7 +275,7 @@ module FSharpExprConvert = | DT_REF -> None | _ -> None - let (|TTypeConvOp|_|) (cenv:SymbolEnv) ty = + let (|TTypeConvOp|_|) (cenv: SymbolEnv) ty = let g = cenv.g match ty with | TType_app (tcref,_) -> @@ -298,14 +298,14 @@ module FSharpExprConvert = let ConvType cenv ty = FSharpType(cenv, ty) let ConvTypes cenv tys = List.map (ConvType cenv) tys - let ConvILTypeRefApp (cenv:SymbolEnv) m tref tyargs = + let ConvILTypeRefApp (cenv: SymbolEnv) m tref tyargs = let tcref = Import.ImportILTypeRef cenv.amap m tref ConvType cenv (mkAppTy tcref tyargs) - let ConvUnionCaseRef cenv (ucref:UnionCaseRef) = FSharpUnionCase(cenv, ucref) - let ConvRecdFieldRef cenv (rfref:RecdFieldRef) = FSharpField(cenv, rfref ) + let ConvUnionCaseRef cenv (ucref: UnionCaseRef) = FSharpUnionCase(cenv, ucref) + let ConvRecdFieldRef cenv (rfref: RecdFieldRef) = FSharpField(cenv, rfref ) - let rec exprOfExprAddr (cenv:SymbolEnv) expr = + let rec exprOfExprAddr (cenv: SymbolEnv) expr = match expr with | Expr.Op(op, tyargs, args, m) -> match op, args, tyargs with @@ -328,9 +328,9 @@ module FSharpExprConvert = let Mk cenv m ty e = FSharpExpr(cenv, None, e, m, ty) - let Mk2 cenv (orig:Expr) e = FSharpExpr(cenv, None, e, orig.Range, tyOfExpr cenv.g orig) + let Mk2 cenv (orig: Expr) e = FSharpExpr(cenv, None, e, orig.Range, tyOfExpr cenv.g orig) - let rec ConvLValueExpr (cenv:SymbolEnv) env expr = ConvExpr cenv env (exprOfExprAddr cenv expr) + let rec ConvLValueExpr (cenv: SymbolEnv) env expr = ConvExpr cenv env (exprOfExprAddr cenv expr) and ConvExpr cenv env expr = Mk2 cenv expr (ConvExprPrim cenv env expr) @@ -385,7 +385,7 @@ module FSharpExprConvert = let dtreeR = ConvDecisionTree cenv env retTy dtree m // tailcall ConvTargetsLinear cenv env (List.ofArray tgs) (contf << fun (targetsR: _ list) -> - let (|E|) (x:FSharpExpr) = x.E + let (|E|) (x: FSharpExpr) = x.E // If the match is really an "if-then-else" then return it as such. match dtreeR with @@ -398,7 +398,7 @@ module FSharpExprConvert = /// A nasty function copied from creflect.fs. Made nastier by taking a continuation to process the /// arguments to the call in a tail-recursive fashion. - and ConvModuleValueOrMemberUseLinear (cenv:SymbolEnv) env (expr:Expr, vref, vFlags, tyargs, curriedArgs) contf = + and ConvModuleValueOrMemberUseLinear (cenv: SymbolEnv) env (expr: Expr, vref, vFlags, tyargs, curriedArgs) contf = let m = expr.Range let (numEnclTypeArgs, _, isNewObj, _valUseFlags, _isSelfInit, takesInstanceArg, _isPropGet, _isPropSet) = @@ -469,7 +469,7 @@ module FSharpExprConvert = // tailcall ConvObjectModelCallLinear cenv env (false, v, [], tyargs, List.concat untupledCurriedArgs) contf2 - and ConvExprPrim (cenv:SymbolEnv) (env:ExprTranslationEnv) expr = + and ConvExprPrim (cenv: SymbolEnv) (env: ExprTranslationEnv) expr = // Eliminate integer 'for' loops let expr = DetectAndOptimizeForExpression cenv.g OptimizeIntRangesOnly expr @@ -870,7 +870,7 @@ module FSharpExprConvert = let envinner = env.BindVal v Some(vR, rhsR), envinner - and ConvILCall (cenv:SymbolEnv) env (isNewObj, valUseFlags, ilMethRef, enclTypeArgs, methTypeArgs, callArgs, m) = + and ConvILCall (cenv: SymbolEnv) env (isNewObj, valUseFlags, ilMethRef, enclTypeArgs, methTypeArgs, callArgs, m) = let isNewObj = (isNewObj || (match valUseFlags with CtorValUsedAsSuperInit | CtorValUsedAsSelfInit -> true | _ -> false)) let methName = ilMethRef.Name let isPropGet = methName.StartsWithOrdinal("get_") @@ -1074,7 +1074,7 @@ module FSharpExprConvert = with e -> failwithf "An IL call to '%s' could not be resolved: %s" (ilMethRef.ToString()) e.Message - and ConvObjectModelCallLinear cenv env (isNewObj, v:FSharpMemberOrFunctionOrValue, enclTyArgs, methTyArgs, callArgs) contf = + and ConvObjectModelCallLinear cenv env (isNewObj, v: FSharpMemberOrFunctionOrValue, enclTyArgs, methTyArgs, callArgs) contf = let enclTyArgsR = ConvTypes cenv enclTyArgs let methTyArgsR = ConvTypes cenv methTyArgs let obj, callArgs = @@ -1111,7 +1111,7 @@ module FSharpExprConvert = ConvTargetsLinear cenv env rest (fun restR -> contf ((varsR, targetR) :: restR))) - and ConvValRef cenv env m (vref:ValRef) = + and ConvValRef cenv env m (vref: ValRef) = let v = vref.Deref if env.isinstVals.ContainsVal v then let (ty, e) = env.isinstVals.[v] @@ -1126,7 +1126,7 @@ module FSharpExprConvert = else E.Value(FSharpMemberOrFunctionOrValue(cenv, vref)) - and ConvVal cenv (v:Val) = + and ConvVal cenv (v: Val) = let vref = mkLocalValRef v FSharpMemberOrFunctionOrValue(cenv, vref) @@ -1284,49 +1284,49 @@ and FSharpImplementationFileContents(cenv, mimpl) = module BasicPatterns = - let (|Value|_|) (e:FSharpExpr) = match e.E with E.Value (v) -> Some (v) | _ -> None - let (|Const|_|) (e:FSharpExpr) = match e.E with E.Const (v, ty) -> Some (v, ty) | _ -> None - let (|TypeLambda|_|) (e:FSharpExpr) = match e.E with E.TypeLambda (v, e) -> Some (v, e) | _ -> None - let (|Lambda|_|) (e:FSharpExpr) = match e.E with E.Lambda (v, e) -> Some (v, e) | _ -> None - let (|Application|_|) (e:FSharpExpr) = match e.E with E.Application (f, tys, e) -> Some (f, tys, e) | _ -> None - let (|IfThenElse|_|) (e:FSharpExpr) = match e.E with E.IfThenElse (e1, e2, e3) -> Some (e1, e2, e3) | _ -> None - let (|Let|_|) (e:FSharpExpr) = match e.E with E.Let ((v, e), b) -> Some ((v, e), b) | _ -> None - let (|LetRec|_|) (e:FSharpExpr) = match e.E with E.LetRec (ves, b) -> Some (ves, b) | _ -> None - let (|NewRecord|_|) (e:FSharpExpr) = match e.E with E.NewRecord (ty, es) -> Some (ty, es) | _ -> None - let (|NewAnonRecord|_|) (e:FSharpExpr) = match e.E with E.NewAnonRecord (ty, es) -> Some (ty, es) | _ -> None - let (|NewUnionCase|_|) (e:FSharpExpr) = match e.E with E.NewUnionCase (e, tys, es) -> Some (e, tys, es) | _ -> None - let (|NewTuple|_|) (e:FSharpExpr) = match e.E with E.NewTuple (ty, es) -> Some (ty, es) | _ -> None - let (|TupleGet|_|) (e:FSharpExpr) = match e.E with E.TupleGet (ty, n, es) -> Some (ty, n, es) | _ -> None - let (|Call|_|) (e:FSharpExpr) = match e.E with E.Call (a, b, c, d, e) -> Some (a, b, c, d, e) | _ -> None - let (|NewObject|_|) (e:FSharpExpr) = match e.E with E.NewObject (a, b, c) -> Some (a, b, c) | _ -> None - let (|FSharpFieldGet|_|) (e:FSharpExpr) = match e.E with E.FSharpFieldGet (a, b, c) -> Some (a, b, c) | _ -> None - let (|AnonRecordGet|_|) (e:FSharpExpr) = match e.E with E.AnonRecordGet (a, b, c) -> Some (a, b, c) | _ -> None - let (|FSharpFieldSet|_|) (e:FSharpExpr) = match e.E with E.FSharpFieldSet (a, b, c, d) -> Some (a, b, c, d) | _ -> None - let (|UnionCaseGet|_|) (e:FSharpExpr) = match e.E with E.UnionCaseGet (a, b, c, d) -> Some (a, b, c, d) | _ -> None - let (|UnionCaseTag|_|) (e:FSharpExpr) = match e.E with E.UnionCaseTag (a, b) -> Some (a, b) | _ -> None - let (|UnionCaseTest|_|) (e:FSharpExpr) = match e.E with E.UnionCaseTest (a, b, c) -> Some (a, b, c) | _ -> None - let (|NewArray|_|) (e:FSharpExpr) = match e.E with E.NewArray (a, b) -> Some (a, b) | _ -> None - let (|Coerce|_|) (e:FSharpExpr) = match e.E with E.Coerce (a, b) -> Some (a, b) | _ -> None - let (|Quote|_|) (e:FSharpExpr) = match e.E with E.Quote (a) -> Some (a) | _ -> None - let (|TypeTest|_|) (e:FSharpExpr) = match e.E with E.TypeTest (a, b) -> Some (a, b) | _ -> None - let (|Sequential|_|) (e:FSharpExpr) = match e.E with E.Sequential (a, b) -> Some (a, b) | _ -> None - let (|FastIntegerForLoop|_|) (e:FSharpExpr) = match e.E with E.FastIntegerForLoop (a, b, c, d) -> Some (a, b, c, d) | _ -> None - let (|WhileLoop|_|) (e:FSharpExpr) = match e.E with E.WhileLoop (a, b) -> Some (a, b) | _ -> None - let (|TryFinally|_|) (e:FSharpExpr) = match e.E with E.TryFinally (a, b) -> Some (a, b) | _ -> None - let (|TryWith|_|) (e:FSharpExpr) = match e.E with E.TryWith (a, b, c, d, e) -> Some (a, b, c, d, e) | _ -> None - let (|NewDelegate|_|) (e:FSharpExpr) = match e.E with E.NewDelegate (ty, e) -> Some (ty, e) | _ -> None - let (|DefaultValue|_|) (e:FSharpExpr) = match e.E with E.DefaultValue (ty) -> Some (ty) | _ -> None - let (|AddressSet|_|) (e:FSharpExpr) = match e.E with E.AddressSet (a, b) -> Some (a, b) | _ -> None - let (|ValueSet|_|) (e:FSharpExpr) = match e.E with E.ValueSet (a, b) -> Some (a, b) | _ -> None - let (|AddressOf|_|) (e:FSharpExpr) = match e.E with E.AddressOf (a) -> Some (a) | _ -> None - let (|ThisValue|_|) (e:FSharpExpr) = match e.E with E.ThisValue (a) -> Some (a) | _ -> None - let (|BaseValue|_|) (e:FSharpExpr) = match e.E with E.BaseValue (a) -> Some (a) | _ -> None - let (|ILAsm|_|) (e:FSharpExpr) = match e.E with E.ILAsm (a, b, c) -> Some (a, b, c) | _ -> None - let (|ILFieldGet|_|) (e:FSharpExpr) = match e.E with E.ILFieldGet (a, b, c) -> Some (a, b, c) | _ -> None - let (|ILFieldSet|_|) (e:FSharpExpr) = match e.E with E.ILFieldSet (a, b, c, d) -> Some (a, b, c, d) | _ -> None - let (|ObjectExpr|_|) (e:FSharpExpr) = match e.E with E.ObjectExpr (a, b, c, d) -> Some (a, b, c, d) | _ -> None - let (|DecisionTree|_|) (e:FSharpExpr) = match e.E with E.DecisionTree (a, b) -> Some (a, b) | _ -> None - let (|DecisionTreeSuccess|_|) (e:FSharpExpr) = match e.E with E.DecisionTreeSuccess (a, b) -> Some (a, b) | _ -> None - let (|UnionCaseSet|_|) (e:FSharpExpr) = match e.E with E.UnionCaseSet (a, b, c, d, e) -> Some (a, b, c, d, e) | _ -> None - let (|TraitCall|_|) (e:FSharpExpr) = match e.E with E.TraitCall (a, b, c, d, e, f) -> Some (a, b, c, d, e, f) | _ -> None + let (|Value|_|) (e: FSharpExpr) = match e.E with E.Value (v) -> Some (v) | _ -> None + let (|Const|_|) (e: FSharpExpr) = match e.E with E.Const (v, ty) -> Some (v, ty) | _ -> None + let (|TypeLambda|_|) (e: FSharpExpr) = match e.E with E.TypeLambda (v, e) -> Some (v, e) | _ -> None + let (|Lambda|_|) (e: FSharpExpr) = match e.E with E.Lambda (v, e) -> Some (v, e) | _ -> None + let (|Application|_|) (e: FSharpExpr) = match e.E with E.Application (f, tys, e) -> Some (f, tys, e) | _ -> None + let (|IfThenElse|_|) (e: FSharpExpr) = match e.E with E.IfThenElse (e1, e2, e3) -> Some (e1, e2, e3) | _ -> None + let (|Let|_|) (e: FSharpExpr) = match e.E with E.Let ((v, e), b) -> Some ((v, e), b) | _ -> None + let (|LetRec|_|) (e: FSharpExpr) = match e.E with E.LetRec (ves, b) -> Some (ves, b) | _ -> None + let (|NewRecord|_|) (e: FSharpExpr) = match e.E with E.NewRecord (ty, es) -> Some (ty, es) | _ -> None + let (|NewAnonRecord|_|) (e: FSharpExpr) = match e.E with E.NewAnonRecord (ty, es) -> Some (ty, es) | _ -> None + let (|NewUnionCase|_|) (e: FSharpExpr) = match e.E with E.NewUnionCase (e, tys, es) -> Some (e, tys, es) | _ -> None + let (|NewTuple|_|) (e: FSharpExpr) = match e.E with E.NewTuple (ty, es) -> Some (ty, es) | _ -> None + let (|TupleGet|_|) (e: FSharpExpr) = match e.E with E.TupleGet (ty, n, es) -> Some (ty, n, es) | _ -> None + let (|Call|_|) (e: FSharpExpr) = match e.E with E.Call (a, b, c, d, e) -> Some (a, b, c, d, e) | _ -> None + let (|NewObject|_|) (e: FSharpExpr) = match e.E with E.NewObject (a, b, c) -> Some (a, b, c) | _ -> None + let (|FSharpFieldGet|_|) (e: FSharpExpr) = match e.E with E.FSharpFieldGet (a, b, c) -> Some (a, b, c) | _ -> None + let (|AnonRecordGet|_|) (e: FSharpExpr) = match e.E with E.AnonRecordGet (a, b, c) -> Some (a, b, c) | _ -> None + let (|FSharpFieldSet|_|) (e: FSharpExpr) = match e.E with E.FSharpFieldSet (a, b, c, d) -> Some (a, b, c, d) | _ -> None + let (|UnionCaseGet|_|) (e: FSharpExpr) = match e.E with E.UnionCaseGet (a, b, c, d) -> Some (a, b, c, d) | _ -> None + let (|UnionCaseTag|_|) (e: FSharpExpr) = match e.E with E.UnionCaseTag (a, b) -> Some (a, b) | _ -> None + let (|UnionCaseTest|_|) (e: FSharpExpr) = match e.E with E.UnionCaseTest (a, b, c) -> Some (a, b, c) | _ -> None + let (|NewArray|_|) (e: FSharpExpr) = match e.E with E.NewArray (a, b) -> Some (a, b) | _ -> None + let (|Coerce|_|) (e: FSharpExpr) = match e.E with E.Coerce (a, b) -> Some (a, b) | _ -> None + let (|Quote|_|) (e: FSharpExpr) = match e.E with E.Quote (a) -> Some (a) | _ -> None + let (|TypeTest|_|) (e: FSharpExpr) = match e.E with E.TypeTest (a, b) -> Some (a, b) | _ -> None + let (|Sequential|_|) (e: FSharpExpr) = match e.E with E.Sequential (a, b) -> Some (a, b) | _ -> None + let (|FastIntegerForLoop|_|) (e: FSharpExpr) = match e.E with E.FastIntegerForLoop (a, b, c, d) -> Some (a, b, c, d) | _ -> None + let (|WhileLoop|_|) (e: FSharpExpr) = match e.E with E.WhileLoop (a, b) -> Some (a, b) | _ -> None + let (|TryFinally|_|) (e: FSharpExpr) = match e.E with E.TryFinally (a, b) -> Some (a, b) | _ -> None + let (|TryWith|_|) (e: FSharpExpr) = match e.E with E.TryWith (a, b, c, d, e) -> Some (a, b, c, d, e) | _ -> None + let (|NewDelegate|_|) (e: FSharpExpr) = match e.E with E.NewDelegate (ty, e) -> Some (ty, e) | _ -> None + let (|DefaultValue|_|) (e: FSharpExpr) = match e.E with E.DefaultValue (ty) -> Some (ty) | _ -> None + let (|AddressSet|_|) (e: FSharpExpr) = match e.E with E.AddressSet (a, b) -> Some (a, b) | _ -> None + let (|ValueSet|_|) (e: FSharpExpr) = match e.E with E.ValueSet (a, b) -> Some (a, b) | _ -> None + let (|AddressOf|_|) (e: FSharpExpr) = match e.E with E.AddressOf (a) -> Some (a) | _ -> None + let (|ThisValue|_|) (e: FSharpExpr) = match e.E with E.ThisValue (a) -> Some (a) | _ -> None + let (|BaseValue|_|) (e: FSharpExpr) = match e.E with E.BaseValue (a) -> Some (a) | _ -> None + let (|ILAsm|_|) (e: FSharpExpr) = match e.E with E.ILAsm (a, b, c) -> Some (a, b, c) | _ -> None + let (|ILFieldGet|_|) (e: FSharpExpr) = match e.E with E.ILFieldGet (a, b, c) -> Some (a, b, c) | _ -> None + let (|ILFieldSet|_|) (e: FSharpExpr) = match e.E with E.ILFieldSet (a, b, c, d) -> Some (a, b, c, d) | _ -> None + let (|ObjectExpr|_|) (e: FSharpExpr) = match e.E with E.ObjectExpr (a, b, c, d) -> Some (a, b, c, d) | _ -> None + let (|DecisionTree|_|) (e: FSharpExpr) = match e.E with E.DecisionTree (a, b) -> Some (a, b) | _ -> None + let (|DecisionTreeSuccess|_|) (e: FSharpExpr) = match e.E with E.DecisionTreeSuccess (a, b) -> Some (a, b) | _ -> None + let (|UnionCaseSet|_|) (e: FSharpExpr) = match e.E with E.UnionCaseSet (a, b, c, d, e) -> Some (a, b, c, d, e) | _ -> None + let (|TraitCall|_|) (e: FSharpExpr) = match e.E with E.TraitCall (a, b, c, d, e, f) -> Some (a, b, c, d, e, f) | _ -> None diff --git a/src/fsharp/symbols/SymbolHelpers.fs b/src/fsharp/symbols/SymbolHelpers.fs index 5bedc506752..943337a7da6 100644 --- a/src/fsharp/symbols/SymbolHelpers.fs +++ b/src/fsharp/symbols/SymbolHelpers.fs @@ -60,14 +60,14 @@ type FSharpErrorInfo(fileName, s: pos, e: pos, severity: FSharpErrorSeverity, me override __.ToString()= sprintf "%s (%d,%d)-(%d,%d) %s %s %s" fileName (int s.Line) (s.Column + 1) (int e.Line) (e.Column + 1) subcategory (if severity=FSharpErrorSeverity.Warning then "warning" else "error") message /// Decompose a warning or error into parts: position, severity, message, error number - static member CreateFromException(exn, isError, fallbackRange:range) = + static member CreateFromException(exn, isError, fallbackRange: range) = let m = match GetRangeOfDiagnostic exn with Some m -> m | None -> fallbackRange let msg = bufs (fun buf -> OutputPhasedDiagnostic buf exn false) let errorNum = GetDiagnosticNumber exn FSharpErrorInfo(m.FileName, m.Start, m.End, (if isError then FSharpErrorSeverity.Error else FSharpErrorSeverity.Warning), msg, exn.Subcategory(), errorNum) /// Decompose a warning or error into parts: position, severity, message, error number - static member CreateFromExceptionAndAdjustEof(exn, isError, fallbackRange:range, (linesCount:int, lastLength:int)) = + static member CreateFromExceptionAndAdjustEof(exn, isError, fallbackRange: range, (linesCount: int, lastLength: int)) = let r = FSharpErrorInfo.CreateFromException(exn, isError, fallbackRange) // Adjust to make sure that errors reported at Eof are shown at the linesCount @@ -120,7 +120,7 @@ type ErrorScope() = /// if there is a "msising assembly" error while formatting the text of the description of an /// autocomplete, then the error message is shown in replacement of the text (rather than crashing Visual /// Studio, or swallowing the exception completely) - static member Protect<'a> (m:range) (f:unit->'a) (err:string->'a): 'a = + static member Protect<'a> (m: range) (f: unit->'a) (err: string->'a): 'a = use errorScope = new ErrorScope() let res = try @@ -163,7 +163,7 @@ type internal CompilationErrorLogger (debugName: string, options: FSharpErrorSev /// This represents the global state established as each task function runs as part of the build. /// /// Use to reset error and warning handlers. -type CompilationGlobalsScope(errorLogger:ErrorLogger, phase: BuildPhase) = +type CompilationGlobalsScope(errorLogger: ErrorLogger, phase: BuildPhase) = let unwindEL = PushErrorLoggerPhaseUntilUnwind(fun _ -> errorLogger) let unwindBP = PushThreadBuildPhaseUntilUnwind phase // Return the disposable object that cleans up @@ -308,27 +308,27 @@ module internal SymbolHelpers = | Some _ -> wordL (tagText (FSComp.SR.typeInfoFullName())) ^^ RightL.colon ^^ (fnF r) else emptyL - let rangeOfValRef preferFlag (vref:ValRef) = + let rangeOfValRef preferFlag (vref: ValRef) = match preferFlag with | None -> vref.Range | Some false -> vref.DefinitionRange | Some true -> vref.SigRange - let rangeOfEntityRef preferFlag (eref:EntityRef) = + let rangeOfEntityRef preferFlag (eref: EntityRef) = match preferFlag with | None -> eref.Range | Some false -> eref.DefinitionRange | Some true -> eref.SigRange - let rangeOfPropInfo preferFlag (pinfo:PropInfo) = + let rangeOfPropInfo preferFlag (pinfo: PropInfo) = match pinfo with #if !NO_EXTENSIONTYPING | ProvidedProp(_, pi, _) -> ComputeDefinitionLocationOfProvidedItem pi #endif | _ -> pinfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) - let rangeOfMethInfo (g:TcGlobals) preferFlag (minfo:MethInfo) = + let rangeOfMethInfo (g: TcGlobals) preferFlag (minfo: MethInfo) = match minfo with #if !NO_EXTENSIONTYPING | ProvidedMeth(_, mi, _, _) -> ComputeDefinitionLocationOfProvidedItem mi @@ -336,26 +336,26 @@ module internal SymbolHelpers = | DefaultStructCtor(_, AppTy g (tcref, _)) -> Some(rangeOfEntityRef preferFlag tcref) | _ -> minfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) - let rangeOfEventInfo preferFlag (einfo:EventInfo) = + let rangeOfEventInfo preferFlag (einfo: EventInfo) = match einfo with #if !NO_EXTENSIONTYPING | ProvidedEvent (_, ei, _) -> ComputeDefinitionLocationOfProvidedItem ei #endif | _ -> einfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) - let rangeOfUnionCaseInfo preferFlag (ucinfo:UnionCaseInfo) = + let rangeOfUnionCaseInfo preferFlag (ucinfo: UnionCaseInfo) = match preferFlag with | None -> ucinfo.UnionCase.Range | Some false -> ucinfo.UnionCase.DefinitionRange | Some true -> ucinfo.UnionCase.SigRange - let rangeOfRecdFieldInfo preferFlag (rfinfo:RecdFieldInfo) = + let rangeOfRecdFieldInfo preferFlag (rfinfo: RecdFieldInfo) = match preferFlag with | None -> rfinfo.RecdField.Range | Some false -> rfinfo.RecdField.DefinitionRange | Some true -> rfinfo.RecdField.SigRange - let rec rangeOfItem (g:TcGlobals) preferFlag d = + let rec rangeOfItem (g: TcGlobals) preferFlag d = match d with | Item.Value vref | Item.CustomBuilder (_, vref) -> Some (rangeOfValRef preferFlag vref) | Item.UnionCase(ucinfo, _) -> Some (rangeOfUnionCaseInfo preferFlag ucinfo) @@ -384,13 +384,13 @@ module internal SymbolHelpers = | Item.NewDef _ -> None // Provided type definitions do not have a useful F# CCU for the purposes of goto-definition. - let computeCcuOfTyconRef (tcref:TyconRef) = + let computeCcuOfTyconRef (tcref: TyconRef) = #if !NO_EXTENSIONTYPING if tcref.IsProvided then None else #endif ccuOfTyconRef tcref - let ccuOfMethInfo (g:TcGlobals) (minfo:MethInfo) = + let ccuOfMethInfo (g: TcGlobals) (minfo: MethInfo) = match minfo with | DefaultStructCtor(_, AppTy g (tcref, _)) -> computeCcuOfTyconRef tcref | _ -> @@ -399,7 +399,7 @@ module internal SymbolHelpers = |> Option.orElseWith (fun () -> minfo.DeclaringTyconRef |> computeCcuOfTyconRef) - let rec ccuOfItem (g:TcGlobals) d = + let rec ccuOfItem (g: TcGlobals) d = match d with | Item.Value vref | Item.CustomBuilder (_, vref) -> ccuOfValRef vref | Item.UnionCase(ucinfo, _) -> computeCcuOfTyconRef ucinfo.TyconRef @@ -433,7 +433,7 @@ module internal SymbolHelpers = | _ -> None /// Work out the source file for an item and fix it up relative to the CCU if it is relative. - let fileNameOfItem (g:TcGlobals) qualProjectDir (m:range) h = + let fileNameOfItem (g: TcGlobals) qualProjectDir (m: range) h = let file = m.FileName if verbose then dprintf "file stored in metadata is '%s'\n" file if not (FileSystem.IsPathRootedShim file) then @@ -468,7 +468,7 @@ module internal SymbolHelpers = | _ -> [] // Find the name of the metadata file for this external definition - let metaInfoOfEntityRef (infoReader:InfoReader) m tcref = + let metaInfoOfEntityRef (infoReader: InfoReader) m tcref = let g = infoReader.g match tcref with | ERefLocal _ -> None @@ -487,7 +487,7 @@ module internal SymbolHelpers = | Some (Some(fileName), xmlDocSig) -> FSharpXmlDoc.XmlDocFileSignature(fileName, xmlDocSig) | _ -> FSharpXmlDoc.None - let GetXmlDocSigOfEntityRef infoReader m (eref:EntityRef) = + let GetXmlDocSigOfEntityRef infoReader m (eref: EntityRef) = if eref.IsILTycon then match metaInfoOfEntityRef infoReader m eref with | None -> None @@ -499,7 +499,7 @@ module internal SymbolHelpers = m.XmlDocSig <- XmlDocSigOfEntity eref Some (ccuFileName, m.XmlDocSig) - let GetXmlDocSigOfScopedValRef g (tcref:TyconRef) (vref:ValRef) = + let GetXmlDocSigOfScopedValRef g (tcref: TyconRef) (vref: ValRef) = let ccuFileName = libFileOfEntityRef tcref let v = vref.Deref if v.XmlDocSig = "" && v.HasDeclaringEntity then @@ -513,21 +513,21 @@ module internal SymbolHelpers = v.XmlDocSig <- XmlDocSigOfVal g path v Some (ccuFileName, v.XmlDocSig) - let GetXmlDocSigOfRecdFieldInfo (rfinfo:RecdFieldInfo) = + let GetXmlDocSigOfRecdFieldInfo (rfinfo: RecdFieldInfo) = let tcref = rfinfo.TyconRef let ccuFileName = libFileOfEntityRef tcref if rfinfo.RecdField.XmlDocSig = "" then rfinfo.RecdField.XmlDocSig <- XmlDocSigOfProperty [tcref.CompiledRepresentationForNamedType.FullName; rfinfo.Name] Some (ccuFileName, rfinfo.RecdField.XmlDocSig) - let GetXmlDocSigOfUnionCaseInfo (ucinfo:UnionCaseInfo) = + let GetXmlDocSigOfUnionCaseInfo (ucinfo: UnionCaseInfo) = let tcref = ucinfo.TyconRef let ccuFileName = libFileOfEntityRef tcref if ucinfo.UnionCase.XmlDocSig = "" then ucinfo.UnionCase.XmlDocSig <- XmlDocSigOfUnionCase [tcref.CompiledRepresentationForNamedType.FullName; ucinfo.Name] Some (ccuFileName, ucinfo.UnionCase.XmlDocSig) - let GetXmlDocSigOfMethInfo (infoReader:InfoReader) m (minfo:MethInfo) = + let GetXmlDocSigOfMethInfo (infoReader: InfoReader) m (minfo: MethInfo) = let amap = infoReader.amap match minfo with | FSMeth (g, _, vref, _) -> @@ -558,7 +558,7 @@ module internal SymbolHelpers = | ProvidedMeth _ -> None #endif - let GetXmlDocSigOfValRef g (vref:ValRef) = + let GetXmlDocSigOfValRef g (vref: ValRef) = if not vref.IsLocalRef then let ccuFileName = vref.nlr.Ccu.FileName let v = vref.Deref @@ -585,7 +585,7 @@ module internal SymbolHelpers = Some (ccuFileName, "P:"+formalTypeInfo.ILTypeRef.FullName+"."+pdef.Name+XmlDocArgsEnc g (formalTypars, []) (filpinfo.GetParamTypes(infoReader.amap, m))) | _ -> None - let GetXmlDocSigOfEvent infoReader m (einfo:EventInfo) = + let GetXmlDocSigOfEvent infoReader m (einfo: EventInfo) = match einfo with | ILEvent _ -> match metaInfoOfEntityRef infoReader m einfo.DeclaringTyconRef with @@ -594,14 +594,14 @@ module internal SymbolHelpers = | _ -> None | _ -> None - let GetXmlDocSigOfILFieldInfo infoReader m (finfo:ILFieldInfo) = + let GetXmlDocSigOfILFieldInfo infoReader m (finfo: ILFieldInfo) = match metaInfoOfEntityRef infoReader m finfo.DeclaringTyconRef with | Some (ccuFileName, _, formalTypeInfo) -> Some(ccuFileName, "F:"+formalTypeInfo.ILTypeRef.FullName+"."+finfo.FieldName) | _ -> None /// This function gets the signature to pass to Visual Studio to use its lookup functions for .NET stuff. - let GetXmlDocHelpSigOfItemForLookup (infoReader:InfoReader) m d = + let GetXmlDocHelpSigOfItemForLookup (infoReader: InfoReader) m d = let g = infoReader.g match d with @@ -631,14 +631,14 @@ module internal SymbolHelpers = | _ -> FSharpXmlDoc.None /// Produce an XmlComment with a signature or raw text, given the F# comment and the item - let GetXmlCommentForItemAux (xmlDoc:XmlDoc option) (infoReader:InfoReader) m d = + let GetXmlCommentForItemAux (xmlDoc: XmlDoc option) (infoReader: InfoReader) m d = let result = match xmlDoc with | None | Some (XmlDoc [| |]) -> "" | Some (XmlDoc l) -> bufs (fun os -> bprintf os "\n" - l |> Array.iter (fun (s:string) -> + l |> Array.iter (fun (s: string) -> // Note: this code runs for local/within-project xmldoc tooltips, but not for cross-project or .XML bprintf os "\n%s" s)) @@ -660,7 +660,7 @@ module internal SymbolHelpers = wordL (tagTypeParameter ("'" + tp.DisplayName)) ^^ wordL (tagText (FSComp.SR.descriptionWordIs())) ^^ NicePrint.layoutType denv ty ] /// Generate the structured tooltip for a method info - let FormatOverloadsToList (infoReader:InfoReader) m denv (item: ItemWithInst) minfos : FSharpStructuredToolTipElement = + let FormatOverloadsToList (infoReader: InfoReader) m denv (item: ItemWithInst) minfos : FSharpStructuredToolTipElement = ToolTipFault |> Option.iter (fun msg -> let exn = Error((0, msg), range.Zero) let ph = PhasedDiagnostic.Create(exn, BuildPhase.TypeCheck) @@ -676,8 +676,8 @@ module internal SymbolHelpers = FSharpStructuredToolTipElement.Group(layouts) - let pubpathOfValRef (v:ValRef) = v.PublicPath - let pubpathOfTyconRef (x:TyconRef) = x.PublicPath + let pubpathOfValRef (v: ValRef) = v.PublicPath + let pubpathOfTyconRef (x: TyconRef) = x.PublicPath let (|ItemWhereTypIsPreferred|_|) item = @@ -912,7 +912,7 @@ module internal SymbolHelpers = | Item.Property(_, []) -> "" /// Output a the description of a language item - let rec GetXmlCommentForItem (infoReader:InfoReader) m item = + let rec GetXmlCommentForItem (infoReader: InfoReader) m item = let g = infoReader.g match item with | Item.ImplicitOp(_, { contents = Some(TraitConstraintSln.FSMethSln(_, vref, _)) }) -> @@ -992,7 +992,7 @@ module internal SymbolHelpers = with _ -> false /// Output the quick info information of a language item - let rec FormatItemDescriptionToToolTipElement isListItem (infoReader:InfoReader) m denv (item: ItemWithInst) = + let rec FormatItemDescriptionToToolTipElement isListItem (infoReader: InfoReader) m denv (item: ItemWithInst) = let g = infoReader.g let amap = infoReader.amap let denv = SimplerDisplayEnv denv diff --git a/src/fsharp/tast.fs b/src/fsharp/tast.fs index e02f27bf399..08851f56464 100644 --- a/src/fsharp/tast.fs +++ b/src/fsharp/tast.fs @@ -119,7 +119,7 @@ type ValBaseOrThisInfo = [] /// Flags on values -type ValFlags(flags:int64) = +type ValFlags(flags: int64) = new (recValInfo, baseOrThis, isCompGen, inlineInfo, isMutable, isModuleOrMemberBinding, isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal) = let flags = @@ -311,9 +311,9 @@ type TyparRigidity = /// Encode typar flags into a bit field [] -type TyparFlags(flags:int32) = +type TyparFlags(flags: int32) = - new (kind:TyparKind, rigidity:TyparRigidity, isFromError:bool, isCompGen:bool, staticReq:TyparStaticReq, dynamicReq:TyparDynamicReq, equalityDependsOn: bool, comparisonDependsOn: bool) = + new (kind: TyparKind, rigidity: TyparRigidity, isFromError: bool, isCompGen: bool, staticReq: TyparStaticReq, dynamicReq: TyparDynamicReq, equalityDependsOn: bool, comparisonDependsOn: bool) = TyparFlags((if isFromError then 0b00000000000000010 else 0) ||| (if isCompGen then 0b00000000000000100 else 0) ||| (match staticReq with @@ -398,7 +398,7 @@ type TyparFlags(flags:int32) = /// Encode entity flags into a bit field. We leave lots of space to allow for future expansion. [] -type EntityFlags(flags:int64) = +type EntityFlags(flags: int64) = new (usesPrefixDisplay, isModuleOrNamespace, preEstablishedHasDefaultCtor, hasSelfReferentialCtor, isStructRecordOrUnionType) = EntityFlags((if isModuleOrNamespace then 0b000000000000001L else 0L) ||| @@ -505,7 +505,7 @@ let getNameOfScopeRef sref = | ILScopeRef.Assembly aref -> aref.Name #if !NO_EXTENSIONTYPING -let ComputeDefinitionLocationOfProvidedItem (p : Tainted<#IProvidedCustomAttributeProvider>) = +let ComputeDefinitionLocationOfProvidedItem (p: Tainted<#IProvidedCustomAttributeProvider>) = let attrs = p.PUntaintNoFailure(fun x -> x.GetDefinitionLocationAttribute(p.TypeProvider.PUntaintNoFailure(id))) match attrs with | None | Some (null, _, _) -> None @@ -537,7 +537,7 @@ type CompilationPath = member x.MangledPath = List.map fst x.AccessPath - member x.NestedPublicPath (id:Ident) = PubPath(Array.append (Array.ofList x.MangledPath) [| id.idText |]) + member x.NestedPublicPath (id: Ident) = PubPath(Array.append (Array.ofList x.MangledPath) [| id.idText |]) member x.ParentCompPath = let a, _ = List.frontAndBack x.AccessPath @@ -569,14 +569,14 @@ type EntityOptionalData = mutable entity_other_range: (range * bool) option // MUTABILITY; used only when establishing tycons. - mutable entity_kind : TyparKind + mutable entity_kind: TyparKind /// The declared documentation for the type or module // MUTABILITY: only for unpickle linkage - mutable entity_xmldoc : XmlDoc + mutable entity_xmldoc: XmlDoc /// The XML document signature for this entity - mutable entity_xmldocsig : string + mutable entity_xmldocsig: string /// If non-None, indicates the type is an abbreviation for another type. // @@ -608,7 +608,7 @@ and /// Represents a type definition, exception definition, module definition or // MUTABILITY; used only during creation and remapping of tycons mutable entity_typars: LazyWithContext - mutable entity_flags : EntityFlags + mutable entity_flags: EntityFlags /// The unique stamp of the "tycon blob". Note the same tycon in signature and implementation get different stamps // MUTABILITY: only for unpickle linkage @@ -645,17 +645,17 @@ and /// Represents a type definition, exception definition, module definition or /// The stable path to the type, e.g. Microsoft.FSharp.Core.FSharpFunc`2 // REVIEW: it looks like entity_cpath subsumes this // MUTABILITY: only for unpickle linkage - mutable entity_pubpath : PublicPath option + mutable entity_pubpath: PublicPath option /// The stable path to the type, e.g. Microsoft.FSharp.Core.FSharpFunc`2 // MUTABILITY: only for unpickle linkage - mutable entity_cpath : CompilationPath option + mutable entity_cpath: CompilationPath option /// Used during codegen to hold the ILX representation indicating how to access the type // MUTABILITY: only for unpickle linkage and caching - mutable entity_il_repr_cache : CompiledTypeRepr cache + mutable entity_il_repr_cache: CompiledTypeRepr cache - mutable entity_opt_data : EntityOptionalData option + mutable entity_opt_data: EntityOptionalData option } static member NewEmptyEntityOptData() = @@ -1275,7 +1275,7 @@ and [] MaybeLazy<'T> = | Strict of 'T | Lazy of Lazy<'T> - member this.Value : 'T = + member this.Value: 'T = match this with | Strict x -> x | Lazy x -> x.Value @@ -1297,46 +1297,46 @@ and { /// This is the value implementing the auto-generated comparison /// semantics if any. It is not present if the type defines its own implementation /// of IComparable or if the type doesn't implement IComparable implicitly. - mutable tcaug_compare : (ValRef * ValRef) option + mutable tcaug_compare: (ValRef * ValRef) option /// This is the value implementing the auto-generated comparison /// semantics if any. It is not present if the type defines its own implementation /// of IStructuralComparable or if the type doesn't implement IComparable implicitly. - mutable tcaug_compare_withc : ValRef option + mutable tcaug_compare_withc: ValRef option /// This is the value implementing the auto-generated equality /// semantics if any. It is not present if the type defines its own implementation /// of Object.Equals or if the type doesn't override Object.Equals implicitly. - mutable tcaug_equals : (ValRef * ValRef) option + mutable tcaug_equals: (ValRef * ValRef) option /// This is the value implementing the auto-generated comparison /// semantics if any. It is not present if the type defines its own implementation /// of IStructuralEquatable or if the type doesn't implement IComparable implicitly. - mutable tcaug_hash_and_equals_withc : (ValRef * ValRef * ValRef) option + mutable tcaug_hash_and_equals_withc: (ValRef * ValRef * ValRef) option /// True if the type defined an Object.GetHashCode method. In this /// case we give a warning if we auto-generate a hash method since the semantics may not match up - mutable tcaug_hasObjectGetHashCode : bool + mutable tcaug_hasObjectGetHashCode: bool /// Properties, methods etc. in declaration order. The boolean flag for each indicates if the /// member is known to be an explicit interface implementation. This must be computed and /// saved prior to remapping assembly information. - tcaug_adhoc_list : ResizeArray + tcaug_adhoc_list: ResizeArray /// Properties, methods etc. as lookup table - mutable tcaug_adhoc : NameMultiMap + mutable tcaug_adhoc: NameMultiMap /// Interface implementations - boolean indicates compiler-generated - mutable tcaug_interfaces : (TType * bool * range) list + mutable tcaug_interfaces: (TType * bool * range) list /// Super type, if any - mutable tcaug_super : TType option + mutable tcaug_super: TType option /// Set to true at the end of the scope where proper augmentations are allowed - mutable tcaug_closed : bool + mutable tcaug_closed: bool /// Set to true if the type is determined to be abstract - mutable tcaug_abstract : bool + mutable tcaug_abstract: bool } member tcaug.SetCompare x = tcaug.tcaug_compare <- Some x @@ -1436,7 +1436,7 @@ and /// The information kept about a provided type TProvidedTypeInfo = { /// The parameters given to the provider that provided to this type. - ResolutionEnvironment : ExtensionTyping.ResolutionEnvironment + ResolutionEnvironment: ExtensionTyping.ResolutionEnvironment /// The underlying System.Type (wrapped as a ProvidedType to make sure we don't call random things on /// System.Type, and wrapped as Tainted to make sure we track which provider this came from, for reporting @@ -1474,7 +1474,7 @@ and IsErased: bool /// Indicates the type is generated, but type-relocation is suppressed - IsSuppressRelocate : bool } + IsSuppressRelocate: bool } member info.IsGenerated = not info.IsErased @@ -1535,7 +1535,7 @@ and FieldsByIndex: RecdField[] /// The fields of the record, indexed by name. - FieldsByName : NameMap } + FieldsByName: NameMap } member x.FieldByIndex n = if n >= 0 && n < x.FieldsByIndex.Length then x.FieldsByIndex.[n] @@ -1560,7 +1560,7 @@ and { /// The cases of the discriminated union, in declaration order. CasesByIndex: UnionCase[] /// The cases of the discriminated union, indexed by name. - CasesByName : NameMap + CasesByName: NameMap } member x.GetUnionCaseByIndex n = if n >= 0 && n < x.CasesByIndex.Length then x.CasesByIndex.[n] @@ -1599,10 +1599,10 @@ and ReturnType: TType /// Documentation for the case - XmlDoc : XmlDoc + XmlDoc: XmlDoc /// XML documentation signature for the case - mutable XmlDocSig : string + mutable XmlDocSig: string /// Name/range of the case Id: Ident @@ -1610,7 +1610,7 @@ and /// If this field is populated, this is the implementation range for an item in a signature, otherwise it is /// the signature range for an item in an implementation // MUTABILITY: used when propagating signature attributes into the implementation. - mutable OtherRangeOpt : (range * bool) option + mutable OtherRangeOpt: (range * bool) option /// Indicates the declared visibility of the union constructor, not taking signatures into account Accessibility: Accessibility @@ -1662,10 +1662,10 @@ and rfield_mutable: bool /// Documentation for the field - rfield_xmldoc : XmlDoc + rfield_xmldoc: XmlDoc /// XML Documentation signature for the field - mutable rfield_xmldocsig : string + mutable rfield_xmldocsig: string /// The type of the field, w.r.t. the generic parameters of the enclosing type constructor rfield_type: TType @@ -1807,15 +1807,23 @@ and [] // We should probably change to 'mutable'. // // We do not need to lock this mutable state this it is only ever accessed from the compiler thread. - let activePatternElemRefCache : NameMap option ref = ref None - let modulesByDemangledNameCache : NameMap option ref = ref None - let exconsByDemangledNameCache : NameMap option ref = ref None - let tyconsByDemangledNameAndArityCache: LayeredMap option ref = ref None - let tyconsByAccessNamesCache : LayeredMultiMap option ref = ref None - let tyconsByMangledNameCache : NameMap option ref = ref None - let allEntitiesByMangledNameCache : NameMap option ref = ref None - let allValsAndMembersByPartialLinkageKeyCache : MultiMap option ref = ref None - let allValsByLogicalNameCache : NameMap option ref = ref None + let activePatternElemRefCache: NameMap option ref = ref None + + let modulesByDemangledNameCache: NameMap option ref = ref None + + let exconsByDemangledNameCache: NameMap option ref = ref None + + let tyconsByDemangledNameAndArityCache: LayeredMap option ref = ref None + + let tyconsByAccessNamesCache: LayeredMultiMap option ref = ref None + + let tyconsByMangledNameCache: NameMap option ref = ref None + + let allEntitiesByMangledNameCache: NameMap option ref = ref None + + let allValsAndMembersByPartialLinkageKeyCache: MultiMap option ref = ref None + + let allValsByLogicalNameCache: NameMap option ref = ref None /// Namespace or module-compiled-as-type? member mtyp.ModuleOrNamespaceKind = kind @@ -1830,14 +1838,14 @@ and [] member mtyp.AllEntities = entities /// Mutation used during compilation of FSharp.Core.dll - member mtyp.AddModuleOrNamespaceByMutation(modul:ModuleOrNamespace) = + member mtyp.AddModuleOrNamespaceByMutation(modul: ModuleOrNamespace) = entities <- QueueList.appendOne entities modul modulesByDemangledNameCache := None allEntitiesByMangledNameCache := None #if !NO_EXTENSIONTYPING /// Mutation used in hosting scenarios to hold the hosted types in this module or namespace - member mtyp.AddProvidedTypeEntity(entity:Entity) = + member mtyp.AddProvidedTypeEntity(entity: Entity) = entities <- QueueList.appendOne entities entity tyconsByMangledNameCache := None tyconsByDemangledNameAndArityCache := None @@ -1846,11 +1854,11 @@ and [] #endif /// Return a new module or namespace type with an entity added. - member mtyp.AddEntity(tycon:Tycon) = + member mtyp.AddEntity(tycon: Tycon) = ModuleOrNamespaceType(kind, vals, entities.AppendOne tycon) /// Return a new module or namespace type with a value added. - member mtyp.AddVal(vspec:Val) = + member mtyp.AddVal(vspec: Val) = ModuleOrNamespaceType(kind, vals.AppendOne vspec, entities) /// Get a table of the active patterns defined in this module. @@ -1873,23 +1881,23 @@ and [] /// types "List`1", the entry (List, 1) will be present. member mtyp.TypesByDemangledNameAndArity m = cacheOptRef tyconsByDemangledNameAndArityCache (fun () -> - LayeredMap.Empty.AddAndMarkAsCollapsible( mtyp.TypeAndExceptionDefinitions |> List.map (fun (tc:Tycon) -> KeyTyconByDemangledNameAndArity tc.LogicalName (tc.Typars m) tc) |> List.toArray)) + LayeredMap.Empty.AddAndMarkAsCollapsible( mtyp.TypeAndExceptionDefinitions |> List.map (fun (tc: Tycon) -> KeyTyconByDemangledNameAndArity tc.LogicalName (tc.Typars m) tc) |> List.toArray)) /// Get a table of types defined within this module, namespace or type. The /// table is indexed by both name and, for generic types, also by mangled name. member mtyp.TypesByAccessNames = cacheOptRef tyconsByAccessNamesCache (fun () -> - LayeredMultiMap.Empty.AddAndMarkAsCollapsible (mtyp.TypeAndExceptionDefinitions |> List.toArray |> Array.collect (fun (tc:Tycon) -> KeyTyconByAccessNames tc.LogicalName tc))) + LayeredMultiMap.Empty.AddAndMarkAsCollapsible (mtyp.TypeAndExceptionDefinitions |> List.toArray |> Array.collect (fun (tc: Tycon) -> KeyTyconByAccessNames tc.LogicalName tc))) // REVIEW: we can remove this lookup and use AllEntitiedByMangledName instead? member mtyp.TypesByMangledName = - let addTyconByMangledName (x:Tycon) tab = NameMap.add x.LogicalName x tab + let addTyconByMangledName (x: Tycon) tab = NameMap.add x.LogicalName x tab cacheOptRef tyconsByMangledNameCache (fun () -> List.foldBack addTyconByMangledName mtyp.TypeAndExceptionDefinitions Map.empty) /// Get a table of entities indexed by both logical and compiled names - member mtyp.AllEntitiesByCompiledAndLogicalMangledNames : NameMap = - let addEntityByMangledName (x:Entity) tab = + member mtyp.AllEntitiesByCompiledAndLogicalMangledNames: NameMap = + let addEntityByMangledName (x: Entity) tab = let name1 = x.LogicalName let name2 = x.CompiledName let tab = NameMap.add name1 x tab @@ -1900,14 +1908,14 @@ and [] QueueList.foldBack addEntityByMangledName entities Map.empty) /// Get a table of entities indexed by both logical name - member mtyp.AllEntitiesByLogicalMangledName : NameMap = - let addEntityByMangledName (x:Entity) tab = NameMap.add x.LogicalName x tab + member mtyp.AllEntitiesByLogicalMangledName: NameMap = + let addEntityByMangledName (x: Entity) tab = NameMap.add x.LogicalName x tab QueueList.foldBack addEntityByMangledName entities Map.empty /// Get a table of values and members indexed by partial linkage key, which includes name, the mangled name of the parent type (if any), /// and the method argument count (if any). member mtyp.AllValsAndMembersByPartialLinkageKey = - let addValByMangledName (x:Val) tab = + let addValByMangledName (x: Val) tab = if x.IsCompiledAsTopLevel then let key = x.GetLinkagePartialKey() MultiMap.add key x tab @@ -1917,7 +1925,7 @@ and [] QueueList.foldBack addValByMangledName vals MultiMap.empty) /// Try to find the member with the given linkage key in the given module. - member mtyp.TryLinkVal(ccu:CcuThunk, key:ValLinkageFullKey) = + member mtyp.TryLinkVal(ccu: CcuThunk, key: ValLinkageFullKey) = mtyp.AllValsAndMembersByPartialLinkageKey |> MultiMap.find key.PartialKey |> List.tryFind (fun v -> match key.TypeForLinkage with @@ -1927,7 +1935,7 @@ and [] /// Get a table of values indexed by logical name member mtyp.AllValsByLogicalName = - let addValByName (x:Val) tab = + let addValByName (x: Val) tab = // Note: names may occur twice prior to raising errors about this in PostTypeCheckSemanticChecks // Earlier ones take precedence since we report errors about the later ones if not x.IsMember && not x.IsCompilerGenerated then @@ -1939,7 +1947,7 @@ and [] /// Compute a table of values and members indexed by logical name. member mtyp.AllValsAndMembersByLogicalNameUncached = - let addValByName (x:Val) tab = + let addValByName (x: Val) tab = if not x.IsCompilerGenerated then MultiMap.add x.LogicalName x tab else @@ -1948,13 +1956,13 @@ and [] /// Get a table of F# exception definitions indexed by demangled name, so 'FailureException' is indexed by 'Failure' member mtyp.ExceptionDefinitionsByDemangledName = - let add (tycon:Tycon) acc = NameMap.add tycon.LogicalName tycon acc + let add (tycon: Tycon) acc = NameMap.add tycon.LogicalName tycon acc cacheOptRef exconsByDemangledNameCache (fun () -> List.foldBack add mtyp.ExceptionDefinitions Map.empty) /// Get a table of nested module and namespace fragments indexed by demangled name (so 'ListModule' becomes 'List') member mtyp.ModulesAndNamespacesByDemangledName = - let add (entity:Entity) acc = + let add (entity: Entity) acc = if entity.IsModuleOrNamespace then NameMap.add entity.DemangledModuleOrNamespaceName entity acc else acc @@ -1980,7 +1988,7 @@ and Construct = #if !NO_EXTENSIONTYPING - static member NewProvidedTyconRepr(resolutionEnvironment, st:Tainted, importProvidedType, isSuppressRelocate, m) = + static member NewProvidedTyconRepr(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m) = let isErased = st.PUntaint((fun st -> st.IsErased), m) @@ -2013,14 +2021,14 @@ and Construct = IsErased = isErased IsSuppressRelocate = isSuppressRelocate } - static member NewProvidedTycon(resolutionEnvironment, st:Tainted, importProvidedType, isSuppressRelocate, m, ?access, ?cpath) = + static member NewProvidedTycon(resolutionEnvironment, st: Tainted, importProvidedType, isSuppressRelocate, m, ?access, ?cpath) = let stamp = newStamp() let name = st.PUntaint((fun st -> st.Name), m) let id = ident (name, m) let kind = let isMeasure = st.PApplyWithProvider((fun (st, provider) -> - let findAttrib (ty:System.Type) (a:CustomAttributeData) = (a.Constructor.DeclaringType.FullName = ty.FullName) + let findAttrib (ty: System.Type) (a: CustomAttributeData) = (a.Constructor.DeclaringType.FullName = ty.FullName) let ty = st.RawSystemType ignore provider ty.CustomAttributes @@ -2063,7 +2071,7 @@ and Construct = | _ -> Some { Entity.NewEmptyEntityOptData() with entity_kind = kind; entity_accessiblity = access } } #endif - static member NewModuleOrNamespace cpath access (id:Ident) xml attribs mtype = + static member NewModuleOrNamespace cpath access (id: Ident) xml attribs mtype = let stamp = newStamp() // Put the module suffix on if needed Tycon.New "mspec" @@ -2075,7 +2083,7 @@ and Construct = entity_typars=LazyWithContext.NotLazy [] entity_tycon_repr = TNoRepr entity_tycon_tcaug=TyconAugmentation.Create() - entity_pubpath=cpath |> Option.map (fun (cp:CompilationPath) -> cp.NestedPublicPath id) + entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath id) entity_cpath=cpath entity_attribs=attribs entity_il_repr_cache = newCache() @@ -2104,7 +2112,7 @@ and /// The documentation for the type parameter. Empty for type inference variables. /// MUTABILITY: for linking when unpickling - mutable typar_xmldoc : XmlDoc + mutable typar_xmldoc: XmlDoc /// The inferred constraints for the type inference variable mutable typar_constraints: TyparConstraint list @@ -2441,7 +2449,7 @@ and and [] ValLinkagePartialKey = { /// The name of the type with which the member is associated. None for non-member values. - MemberParentMangledName : string option + MemberParentMangledName: string option /// Indicates if the member is an override. MemberIsOverride: bool @@ -2461,7 +2469,7 @@ and [] /// amongst all those in a ModuleOrNamespace. and [< (* NoEquality; NoComparison; *) StructuredFormatDisplay("{DebugText}")>] - ValLinkageFullKey(partialKey: ValLinkagePartialKey, typeForLinkage:TType option) = + ValLinkageFullKey(partialKey: ValLinkagePartialKey, typeForLinkage: TType option) = /// The partial information used to index the value in a ModuleOrNamespace. member x.PartialKey = partialKey @@ -2506,7 +2514,7 @@ and /// XML documentation attached to a value. /// MUTABILITY: for unpickle linkage - mutable val_xmldoc : XmlDoc + mutable val_xmldoc: XmlDoc /// Is the value actually an instance method/property/event that augments /// a type, and if so what name does it take in the IL? @@ -2520,7 +2528,7 @@ and mutable val_declaring_entity: ParentRef /// XML documentation signature for the value - mutable val_xmldocsig : string + mutable val_xmldocsig: string /// Custom attributes attached to the value. These contain references to other values (i.e. constructors in types). Mutable to fixup /// these value references after copying a collection of values. @@ -2550,7 +2558,7 @@ and [] /// See vflags section further below for encoding/decodings here mutable val_flags: ValFlags - mutable val_opt_data : ValOptionalData option } + mutable val_opt_data: ValOptionalData option } static member NewEmptyValOptData() = { val_compiled_name = None @@ -2617,7 +2625,7 @@ and [] /// /// TLR also sets this for inner bindings that it wants to /// represent as "top level" bindings. - member x.ValReprInfo : ValReprInfo option = + member x.ValReprInfo: ValReprInfo option = match x.val_opt_data with | Some optData -> optData.val_repr_info | _ -> None @@ -2795,7 +2803,7 @@ and [] | ParentNone -> false /// Get the apparent parent entity for a member - member x.MemberApparentEntity : TyconRef = + member x.MemberApparentEntity: TyconRef = match x.MemberInfo with | Some membInfo -> membInfo.ApparentEnclosingEntity | None -> error(InternalError("MemberApparentEntity", x.Range)) @@ -2818,9 +2826,9 @@ and [] /// IsMemberOrModuleBinding is set. // // We use it here: - // - in opt.fs : when compiling fslib, we bind an entry for the value in a global table (see bind_escaping_local_vspec) + // - in opt.fs: when compiling fslib, we bind an entry for the value in a global table (see bind_escaping_local_vspec) // - in ilxgen.fs: when compiling fslib, we bind an entry for the value in a global table (see bind_escaping_local_vspec) - // - in opt.fs : (fullDebugTextOfValRef) for error reporting of non-inlinable values + // - in opt.fs: (fullDebugTextOfValRef) for error reporting of non-inlinable values // - in service.fs (boutput_item_description): to display the full text of a value's binding location // - in check.fs: as a boolean to detect public values for saving quotations // - in ilxgen.fs: as a boolean to detect public values for saving quotations @@ -2988,7 +2996,7 @@ and [] /// Create a new value with the given backing data. Only used during unpickling of F# metadata. - static member New data : Val = data + static member New data: Val = data /// Link a value based on empty, unlinked data to the given data. Only used during unpickling of F# metadata. member x.Link (tg: ValData) = x.SetData tg @@ -3049,7 +3057,7 @@ and [] NonLocalValOrMemberRef = { /// A reference to the entity containing the value or member. This will always be a non-local reference - EnclosingEntity : EntityRef + EnclosingEntity: EntityRef /// The name of the value, or the full signature of the member ItemKey: ValLinkageFullKey } @@ -3084,7 +3092,7 @@ and | NonLocalEntityRef of CcuThunk * string[] /// Try to find the entity corresponding to the given path in the given CCU - static member TryDerefEntityPath(ccu: CcuThunk, path:string[], i:int, entity:Entity) = + static member TryDerefEntityPath(ccu: CcuThunk, path: string[], i: int, entity: Entity) = if i >= path.Length then ValueSome entity else match entity.ModuleOrNamespaceType.AllEntitiesByCompiledAndLogicalMangledNames.TryGetValue path.[i] with @@ -3097,7 +3105,7 @@ and #if !NO_EXTENSIONTYPING /// Try to find the entity corresponding to the given path, using type-providers to link the data - static member TryDerefEntityPathViaProvidedType(ccu: CcuThunk, path:string[], i:int, entity:Entity) = + static member TryDerefEntityPathViaProvidedType(ccu: CcuThunk, path: string[], i: int, entity: Entity) = // Errors during linking are not necessarily given good ranges. This has always been the case in F# 2.0, but also applies to // type provider type linking errors in F# 3.0. let m = range0 @@ -3108,7 +3116,7 @@ and // In this case, we're safely in the realm of types. Just iterate through the nested // types until i = path.Length-1. Create the Tycon's as needed - let rec tryResolveNestedTypeOf(parentEntity:Entity, resolutionEnvironment, st:Tainted, i) = + let rec tryResolveNestedTypeOf(parentEntity: Entity, resolutionEnvironment, st: Tainted, i) = match st.PApply((fun st -> st.GetNestedType path.[i]), m) with | Tainted.Null -> ValueNone | st -> @@ -3397,7 +3405,7 @@ and member x.CompiledReprCache = x.Deref.CompiledReprCache /// Get a blob of data indicating how this type is nested in other namespaces, modules or types. - member x.PublicPath : PublicPath option = x.Deref.PublicPath + member x.PublicPath: PublicPath option = x.Deref.PublicPath /// Get the value representing the accessibility of an F# type definition or module. member x.Accessibility = x.Deref.Accessibility @@ -3704,13 +3712,13 @@ and member x.IsPropertyGetterMethod = match x.MemberInfo with | None -> false - | Some (memInfo:ValMemberInfo) -> memInfo.MemberFlags.MemberKind = MemberKind.PropertyGet || memInfo.MemberFlags.MemberKind = MemberKind.PropertyGetSet + | Some (memInfo: ValMemberInfo) -> memInfo.MemberFlags.MemberKind = MemberKind.PropertyGet || memInfo.MemberFlags.MemberKind = MemberKind.PropertyGetSet /// Indicates whether this value represents a property setter. member x.IsPropertySetterMethod = match x.MemberInfo with | None -> false - | Some (memInfo:ValMemberInfo) -> memInfo.MemberFlags.MemberKind = MemberKind.PropertySet || memInfo.MemberFlags.MemberKind = MemberKind.PropertyGetSet + | Some (memInfo: ValMemberInfo) -> memInfo.MemberFlags.MemberKind = MemberKind.PropertySet || memInfo.MemberFlags.MemberKind = MemberKind.PropertyGetSet /// A unique stamp within the context of this invocation of the compiler process member x.Stamp = x.Deref.Stamp @@ -4125,15 +4133,15 @@ and IsProviderGenerated: bool /// Triggered when the contents of the CCU are invalidated - InvalidateEvent : IEvent + InvalidateEvent: IEvent /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality /// logic in tastops.fs - ImportProvidedType : Tainted -> TType + ImportProvidedType: Tainted -> TType #endif /// Indicates that this DLL uses pre-F#-4.0 quotation literals somewhere. This is used to implement a restriction on static linking - mutable UsesFSharp20PlusQuotations : bool + mutable UsesFSharp20PlusQuotations: bool /// A handle to the full specification of the contents of the module contained in this ccu // NOTE: may contain transient state during typechecking @@ -4145,10 +4153,10 @@ and /// A helper function used to link method signatures using type equality. This is effectively a forward call to the type equality /// logic in tastops.fs - MemberSignatureEquality : (TType -> TType -> bool) + MemberSignatureEquality: (TType -> TType -> bool) /// The table of .NET CLI type forwarders for this assembly - TypeForwarders : CcuTypeForwarderTable } + TypeForwarders: CcuTypeForwarderTable } [] member x.DebugText = x.ToString() @@ -4189,7 +4197,7 @@ and /// used in the F# metadata-deserializer or the .NET metadata reader returns a failing value (e.g. None). /// Note: When used from Visual Studio, the loader will not automatically chase down transitively referenced DLLs - they /// must be in the explicit references in the project. - mutable orphanfixup : bool + mutable orphanfixup: bool name: CcuReference } @@ -4201,7 +4209,7 @@ and member ccu.IsUnresolvedReference = isNull (ccu.target :> obj) || ccu.orphanfixup /// Ensure the ccu is derefable in advance. Supply a path to attach to any resulting error message. - member ccu.EnsureDerefable(requiringPath:string[]) = + member ccu.EnsureDerefable(requiringPath: string[]) = if ccu.IsUnresolvedReference then let path = System.String.Join(".", requiringPath) raise(UnresolvedPathReferenceNoRange(ccu.name, path)) @@ -4230,7 +4238,7 @@ and member ccu.IsProviderGenerated = ccu.Deref.IsProviderGenerated /// Used to make 'forward' calls into the loader during linking - member ccu.ImportProvidedType ty : TType = ccu.Deref.ImportProvidedType ty + member ccu.ImportProvidedType ty: TType = ccu.Deref.ImportProvidedType ty #endif @@ -4248,7 +4256,7 @@ and member ccu.Contents = ccu.Deref.Contents /// The table of type forwarders for this assembly - member ccu.TypeForwarders : Map> = ccu.Deref.TypeForwarders + member ccu.TypeForwarders: Map> = ccu.Deref.TypeForwarders /// The table of modules and namespaces at the "root" of the assembly member ccu.RootModulesAndNamespaces = ccu.Contents.ModuleOrNamespaceType.ModuleAndNamespaceDefinitions @@ -4269,7 +4277,7 @@ and name = nm } /// Fixup a CCU to have the given contents - member x.Fixup(avail:CcuThunk) = + member x.Fixup(avail: CcuThunk) = match box x.target with | null -> () @@ -4291,7 +4299,7 @@ and | _ -> errorR(Failure("internal error: FixupOrphaned: the ccu thunk for assembly "+x.AssemblyName+" not delayed!")) /// Try to resolve a path into the CCU by referencing the .NET/CLI type forwarder table of the CCU - member ccu.TryForward(nlpath:string[], item:string) : EntityRef option = + member ccu.TryForward(nlpath: string[], item: string) : EntityRef option = ccu.EnsureDerefable(nlpath) let key = nlpath, item match ccu.TypeForwarders.TryGetValue key with @@ -4300,7 +4308,7 @@ and //printfn "trying to forward %A::%s from ccu '%s', res = '%A'" p n ccu.AssemblyName res.IsSome /// Used to make forward calls into the type/assembly loader when comparing member signatures during linking - member ccu.MemberSignatureEquality(ty1:TType, ty2:TType) = + member ccu.MemberSignatureEquality(ty1: TType, ty2: TType) = ccu.Deref.MemberSignatureEquality ty1 ty2 [] @@ -4331,7 +4339,7 @@ and compileTimeWorkingDir: string - usesQuotations : bool } + usesQuotations: bool } [] member x.DebugText = x.ToString() @@ -4603,7 +4611,7 @@ and let (ValReprInfo(_, args, _)) = x // This is List.sumBy List.length args // We write this by hand as it can be a performance bottleneck in LinkagePartialKey - let rec loop (args:ArgReprInfo list list) acc = + let rec loop (args: ArgReprInfo list list) acc = match args with | [] -> acc | []::t -> loop t acc @@ -4623,10 +4631,10 @@ and ArgReprInfo = { // MUTABILITY: used when propagating signature attributes into the implementation. - mutable Attribs : Attribs + mutable Attribs: Attribs // MUTABILITY: used when propagating names of parameters from signature into the implementation. - mutable Name : Ident option } + mutable Name: Ident option } [] member x.DebugText = x.ToString() @@ -5030,7 +5038,7 @@ and | TMDefDo of Expr * range /// Indicates the module fragment is a 'rec' or 'non-rec' definition of types and modules - | TMDefRec of isRec:bool * Tycon list * ModuleOrNamespaceBinding list * range + | TMDefRec of isRec: bool * Tycon list * ModuleOrNamespaceBinding list * range // %+A formatting is used, so this is not needed //[] @@ -5188,7 +5196,7 @@ and // type ``[, ]``<'T> = (# "!0[0 ..., 0 ...]" #) // type ``[, , ]``<'T> = (# "!0[0 ..., 0 ..., 0 ...]" #) // type byref<'T> = (# "!0&" #) - // type nativeptr<'T when 'T : unmanaged> = (# "native int" #) + // type nativeptr<'T when 'T: unmanaged> = (# "native int" #) // type ilsigptr<'T> = (# "!0*" #) | ILAsmOpen of ILType @@ -5206,23 +5214,23 @@ and [] module ValReprInfo = - let unnamedTopArg1 : ArgReprInfo = { Attribs=[]; Name=None } + let unnamedTopArg1: ArgReprInfo = { Attribs=[]; Name=None } let unnamedTopArg = [unnamedTopArg1] - let unitArgData : ArgReprInfo list list = [[]] + let unitArgData: ArgReprInfo list list = [[]] - let unnamedRetVal : ArgReprInfo = { Attribs = []; Name=None } + let unnamedRetVal: ArgReprInfo = { Attribs = []; Name=None } let selfMetadata = unnamedTopArg let emptyValData = ValReprInfo([], [], unnamedRetVal) - let InferTyparInfo (tps:Typar list) = tps |> List.map (fun tp -> TyparReprInfo(tp.Id, tp.Kind)) + let InferTyparInfo (tps: Typar list) = tps |> List.map (fun tp -> TyparReprInfo(tp.Id, tp.Kind)) - let InferArgReprInfo (v:Val) : ArgReprInfo = { Attribs = []; Name= Some v.Id } + let InferArgReprInfo (v: Val) : ArgReprInfo = { Attribs = []; Name= Some v.Id } - let InferArgReprInfos (vs:Val list list) = ValReprInfo([], List.mapSquared InferArgReprInfo vs, unnamedRetVal) + let InferArgReprInfos (vs: Val list list) = ValReprInfo([], List.mapSquared InferArgReprInfo vs, unnamedRetVal) let HasNoArgs (ValReprInfo(n, args, _)) = n.IsEmpty && args.IsEmpty @@ -5230,10 +5238,10 @@ module ValReprInfo = // Basic properties via functions (old style) //--------------------------------------------------------------------------- -let typeOfVal (v:Val) = v.Type -let typesOfVals (v:Val list) = v |> List.map (fun v -> v.Type) -let nameOfVal (v:Val) = v.LogicalName -let arityOfVal (v:Val) = (match v.ValReprInfo with None -> ValReprInfo.emptyValData | Some arities -> arities) +let typeOfVal (v: Val) = v.Type +let typesOfVals (v: Val list) = v |> List.map (fun v -> v.Type) +let nameOfVal (v: Val) = v.LogicalName +let arityOfVal (v: Val) = (match v.ValReprInfo with None -> ValReprInfo.emptyValData | Some arities -> arities) let tupInfoRef = TupInfo.Const false let tupInfoStruct = TupInfo.Const true @@ -5255,7 +5263,7 @@ let foldTImplFile f z (TImplFile(_, _, moduleExpr, _, _, _)) = f z moduleExpr // Equality relations on locally defined things //--------------------------------------------------------------------------- -let typarEq (lv1:Typar) (lv2:Typar) = (lv1.Stamp = lv2.Stamp) +let typarEq (lv1: Typar) (lv2: Typar) = (lv1.Stamp = lv2.Stamp) /// Equality on type variables, implemented as reference equality. This should be equivalent to using typarEq. let typarRefEq (tp1: Typar) (tp2: Typar) = (tp1 === tp2) @@ -5273,7 +5281,7 @@ let ccuEq (mv1: CcuThunk) (mv2: CcuThunk) = mv1.Contents === mv2.Contents) /// For dereferencing in the middle of a pattern -let (|ValDeref|) (vr :ValRef) = vr.Deref +let (|ValDeref|) (vr: ValRef) = vr.Deref //-------------------------------------------------------------------------- @@ -5284,9 +5292,9 @@ let mkRecdFieldRef tcref f = RFRef(tcref, f) let mkUnionCaseRef tcref c = UCRef(tcref, c) -let ERefLocal x : EntityRef = { binding=x; nlr=Unchecked.defaultof<_> } -let ERefNonLocal x : EntityRef = { binding=Unchecked.defaultof<_>; nlr=x } -let ERefNonLocalPreResolved x xref : EntityRef = { binding=x; nlr=xref } +let ERefLocal x: EntityRef = { binding=x; nlr=Unchecked.defaultof<_> } +let ERefNonLocal x: EntityRef = { binding=Unchecked.defaultof<_>; nlr=x } +let ERefNonLocalPreResolved x xref: EntityRef = { binding=x; nlr=xref } let (|ERefLocal|ERefNonLocal|) (x: EntityRef) = match box x.nlr with | null -> ERefLocal x.binding @@ -5299,28 +5307,28 @@ let (|ERefLocal|ERefNonLocal|) (x: EntityRef) = let mkLocalTyconRef x = ERefLocal x let mkNonLocalEntityRef ccu mp = NonLocalEntityRef(ccu, mp) -let mkNestedNonLocalEntityRef (nleref:NonLocalEntityRef) id = mkNonLocalEntityRef nleref.Ccu (Array.append nleref.Path [| id |]) +let mkNestedNonLocalEntityRef (nleref: NonLocalEntityRef) id = mkNonLocalEntityRef nleref.Ccu (Array.append nleref.Path [| id |]) let mkNonLocalTyconRef nleref id = ERefNonLocal (mkNestedNonLocalEntityRef nleref id) let mkNonLocalTyconRefPreResolved x nleref id = ERefNonLocalPreResolved x (mkNestedNonLocalEntityRef nleref id) type EntityRef with - member tcref.NestedTyconRef (x:Entity) = + member tcref.NestedTyconRef (x: Entity) = match tcref with | ERefLocal _ -> mkLocalTyconRef x | ERefNonLocal nlr -> mkNonLocalTyconRefPreResolved x nlr x.LogicalName - member tcref.RecdFieldRefInNestedTycon tycon (id:Ident) = RFRef (tcref.NestedTyconRef tycon, id.idText) + member tcref.RecdFieldRefInNestedTycon tycon (id: Ident) = RFRef (tcref.NestedTyconRef tycon, id.idText) /// Make a reference to a union case for type in a module or namespace -let mkModuleUnionCaseRef (modref:ModuleOrNamespaceRef) tycon uc = +let mkModuleUnionCaseRef (modref: ModuleOrNamespaceRef) tycon uc = (modref.NestedTyconRef tycon).MakeNestedUnionCaseRef uc -let VRefLocal x : ValRef = { binding=x; nlr=Unchecked.defaultof<_> } +let VRefLocal x: ValRef = { binding=x; nlr=Unchecked.defaultof<_> } -let VRefNonLocal x : ValRef = { binding=Unchecked.defaultof<_>; nlr=x } +let VRefNonLocal x: ValRef = { binding=Unchecked.defaultof<_>; nlr=x } -let VRefNonLocalPreResolved x xref : ValRef = { binding=x; nlr=xref } +let VRefNonLocalPreResolved x xref: ValRef = { binding=x; nlr=xref } let (|VRefLocal|VRefNonLocal|) (x: ValRef) = match box x.nlr with @@ -5344,7 +5352,7 @@ let ccuOfTyconRef eref = // Type parameters and inference unknowns //------------------------------------------------------------------------- -let mkTyparTy (tp:Typar) = +let mkTyparTy (tp: Typar) = match tp.Kind with | TyparKind.Type -> tp.AsType | TyparKind.Measure -> TType_measure (Measure.Var tp) @@ -5365,7 +5373,7 @@ let copyTypars tps = List.map copyTypar tps // Inference variables //-------------------------------------------------------------------------- -let tryShortcutSolvedUnitPar canShortcut (r:Typar) = +let tryShortcutSolvedUnitPar canShortcut (r: Typar) = if r.Kind = TyparKind.Type then failwith "tryShortcutSolvedUnitPar: kind=type" match r.Solution with | Some (TType_measure unt) -> @@ -5418,13 +5426,13 @@ let stripUnitEqns unt = stripUnitEqnsAux false unt // the item is globally stable ("published") or not. //--------------------------------------------------------------------------- -let mkLocalValRef (v:Val) = VRefLocal v -let mkLocalModRef (v:ModuleOrNamespace) = ERefLocal v -let mkLocalEntityRef (v:Entity) = ERefLocal v +let mkLocalValRef (v: Val) = VRefLocal v +let mkLocalModRef (v: ModuleOrNamespace) = ERefLocal v +let mkLocalEntityRef (v: Entity) = ERefLocal v -let mkNonLocalCcuRootEntityRef ccu (x:Entity) = mkNonLocalTyconRefPreResolved x (mkNonLocalEntityRef ccu [| |]) x.LogicalName +let mkNonLocalCcuRootEntityRef ccu (x: Entity) = mkNonLocalTyconRefPreResolved x (mkNonLocalEntityRef ccu [| |]) x.LogicalName -let mkNestedValRef (cref:EntityRef) (v:Val) : ValRef = +let mkNestedValRef (cref: EntityRef) (v: Val) : ValRef = match cref with | ERefLocal _ -> mkLocalValRef v | ERefNonLocal nlr -> @@ -5462,7 +5470,7 @@ let entityRefInThisAssembly compilingFslib (x: EntityRef) = | ERefLocal _ -> true | ERefNonLocal _ -> compilingFslib -let arrayPathEq (y1:string[]) (y2:string[]) = +let arrayPathEq (y1: string[]) (y2: string[]) = let len1 = y1.Length let len2 = y2.Length (len1 = len2) && @@ -5482,7 +5490,7 @@ let nonLocalRefDefinitelyNotEq (NonLocalEntityRef(_, y1)) (NonLocalEntityRef(_, let pubPathEq (PubPath path1) (PubPath path2) = arrayPathEq path1 path2 -let fslibRefEq (nlr1:NonLocalEntityRef) (PubPath(path2)) = +let fslibRefEq (nlr1: NonLocalEntityRef) (PubPath(path2)) = arrayPathEq nlr1.Path path2 // Compare two EntityRef's for equality when compiling fslib (FSharp.Core.dll) @@ -5491,7 +5499,7 @@ let fslibRefEq (nlr1:NonLocalEntityRef) (PubPath(path2)) = // This breaks certain invariants that hold elsewhere, because they dereference to point to // Entity's from signatures rather than Entity's from implementations. This means backup, alternative // equality comparison techniques are needed when compiling fslib itself. -let fslibEntityRefEq fslibCcu (eref1:EntityRef) (eref2:EntityRef) = +let fslibEntityRefEq fslibCcu (eref1: EntityRef) (eref2: EntityRef) = match eref1, eref2 with | (ERefNonLocal nlr1, ERefLocal x2) | (ERefLocal x2, ERefNonLocal nlr1) -> @@ -5538,7 +5546,7 @@ let fslibValRefEq fslibCcu vref1 vref2 = /// Primitive routine to compare two EntityRef's for equality /// This takes into account the possibility that they may have type forwarders -let primEntityRefEq compilingFslib fslibCcu (x : EntityRef) (y : EntityRef) = +let primEntityRefEq compilingFslib fslibCcu (x: EntityRef) (y: EntityRef) = x === y || if x.IsResolved && y.IsResolved && not compilingFslib then @@ -5567,7 +5575,7 @@ let primUnionCaseRefEq compilingFslib fslibCcu (UCRef(tcr1, c1) as uc1) (UCRef(t /// and quotation splicing /// /// Note this routine doesn't take type forwarding into account -let primValRefEq compilingFslib fslibCcu (x : ValRef) (y : ValRef) = +let primValRefEq compilingFslib fslibCcu (x: ValRef) (y: ValRef) = x === y || if (x.IsResolved && y.IsResolved && x.ResolvedTarget === y.ResolvedTarget) || (x.IsLocalRef && y.IsLocalRef && valEq x.PrivateTarget y.PrivateTarget) then @@ -5584,7 +5592,7 @@ let primValRefEq compilingFslib fslibCcu (x : ValRef) (y : ValRef) = // pubpath/cpath mess //--------------------------------------------------------------------------- -let fullCompPathOfModuleOrNamespace (m:ModuleOrNamespace) = +let fullCompPathOfModuleOrNamespace (m: ModuleOrNamespace) = let (CompPath(scoref, cpath)) = m.CompilationPath CompPath(scoref, cpath@[(m.LogicalName, m.ModuleOrNamespaceType.ModuleOrNamespaceKind)]) @@ -5614,7 +5622,7 @@ let accessSubstPaths (newPath, oldPath) (TAccess paths) = let subst cpath = if cpath=oldPath then newPath else cpath TAccess (List.map subst paths) -let compPathOfCcu (ccu:CcuThunk) = CompPath(ccu.ILScopeRef, []) +let compPathOfCcu (ccu: CcuThunk) = CompPath(ccu.ILScopeRef, []) let taccessPublic = TAccess [] let taccessPrivate accessPath = TAccess [accessPath] let compPathInternal = CompPath(ILScopeRef.Local, []) @@ -5627,16 +5635,16 @@ let combineAccess (TAccess a1) (TAccess a2) = TAccess(a1@a2) let NewFreeVarsCache() = newCache () -let MakeUnionCasesTable ucs : TyconUnionCases = +let MakeUnionCasesTable ucs: TyconUnionCases = { CasesByIndex = Array.ofList ucs CasesByName = NameMap.ofKeyedList (fun uc -> uc.DisplayName) ucs } -let MakeRecdFieldsTable ucs : TyconRecdFields = +let MakeRecdFieldsTable ucs: TyconRecdFields = { FieldsByIndex = Array.ofList ucs FieldsByName = ucs |> NameMap.ofKeyedList (fun rfld -> rfld.Name) } -let MakeUnionCases ucs : TyconUnionData = +let MakeUnionCases ucs: TyconUnionData = { CasesTable=MakeUnionCasesTable ucs CompiledRepresentation=newCache() } @@ -5656,7 +5664,7 @@ let NewTypar (kind, rigid, Typar(id, staticReq, isCompGen), isFromError, dynamic let NewRigidTypar nm m = NewTypar (TyparKind.Type, TyparRigidity.Rigid, Typar(mkSynId m nm, NoStaticReq, true), false, TyparDynamicReq.Yes, [], false, false) -let NewUnionCase id tys rty attribs docOption access : UnionCase = +let NewUnionCase id tys rty attribs docOption access: UnionCase = { Id=id XmlDoc=docOption XmlDocSig="" @@ -5672,14 +5680,14 @@ let NewModuleOrNamespaceType mkind tycons vals = let NewEmptyModuleOrNamespaceType mkind = NewModuleOrNamespaceType mkind [] [] /// Create a new TAST Entity node for an F# exception definition -let NewExn cpath (id:Ident) access repr attribs doc = +let NewExn cpath (id: Ident) access repr attribs doc = Tycon.New "exnc" { entity_stamp=newStamp() entity_attribs=attribs entity_logical_name=id.idText entity_range=id.idRange entity_tycon_tcaug=TyconAugmentation.Create() - entity_pubpath=cpath |> Option.map (fun (cp:CompilationPath) -> cp.NestedPublicPath id) + entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath id) entity_modul_contents = MaybeLazy.Strict (NewEmptyModuleOrNamespaceType ModuleOrType) entity_cpath= cpath entity_typars=LazyWithContext.NotLazy [] @@ -5721,7 +5729,7 @@ let NewTycon (cpath, nm, m, access, reprAccess, kind, typars, docOption, usesPre entity_tycon_repr = TNoRepr entity_tycon_tcaug=TyconAugmentation.Create() entity_modul_contents = mtyp - entity_pubpath=cpath |> Option.map (fun (cp:CompilationPath) -> cp.NestedPublicPath (mkSynId m nm)) + entity_pubpath=cpath |> Option.map (fun (cp: CompilationPath) -> cp.NestedPublicPath (mkSynId m nm)) entity_cpath = cpath entity_il_repr_cache = newCache() entity_opt_data = @@ -5730,7 +5738,7 @@ let NewTycon (cpath, nm, m, access, reprAccess, kind, typars, docOption, usesPre | _ -> Some { Entity.NewEmptyEntityOptData() with entity_kind = kind; entity_xmldoc = docOption; entity_tycon_repr_accessibility = reprAccess; entity_accessiblity=access } } -let NewILTycon nlpath (nm, m) tps (scoref:ILScopeRef, enc, tdef:ILTypeDef) mtyp = +let NewILTycon nlpath (nm, m) tps (scoref: ILScopeRef, enc, tdef: ILTypeDef) mtyp = // NOTE: hasSelfReferentialCtor=false is an assumption about mscorlib let hasSelfReferentialCtor = tdef.IsClass && (not scoref.IsAssemblyRef && scoref.AssemblyRef.Name = "mscorlib") @@ -5744,12 +5752,12 @@ exception Duplicate of string * string * range exception NameClash of string * string * string * range * string * string * range exception FullAbstraction of string * range -let NewModuleOrNamespace cpath access (id:Ident) xml attribs mtype = +let NewModuleOrNamespace cpath access (id: Ident) xml attribs mtype = Construct.NewModuleOrNamespace cpath access id xml attribs mtype /// Create a new Val object let NewVal - (logicalName:string, m:range, compiledName, ty, isMutable, isCompGen, arity, access, + (logicalName: string, m: range, compiledName, ty, isMutable, isCompGen, arity, access, recValInfo, specialRepr, baseOrThis, attribs, inlineInfo, doc, isModuleOrMemberBinding, isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal, konst, actualParent) : Val = @@ -5790,7 +5798,7 @@ let NewCcuContents sref m nm mty = /// We require that we be given the new parent for the new tycon. /// We pass the new tycon to 'f' in case it needs to reparent the /// contents of the tycon. -let NewModifiedTycon f (orig:Tycon) = +let NewModifiedTycon f (orig: Tycon) = let data = { orig with entity_stamp = newStamp() } Tycon.New "NewModifiedTycon" (f data) @@ -5804,7 +5812,7 @@ let NewModifiedModuleOrNamespace f orig = /// Create a Val based on an existing one using the function 'f'. /// We require that we be given the parent for the new Val. -let NewModifiedVal f (orig:Val) = +let NewModifiedVal f (orig: Val) = let stamp = newStamp() let data' = f { orig with val_stamp=stamp } Val.New data' @@ -5820,7 +5828,7 @@ let CombineCcuContentFragments m l = /// Combine module types when multiple namespace fragments contribute to the /// same namespace, making new module specs as we go. - let rec CombineModuleOrNamespaceTypes path m (mty1:ModuleOrNamespaceType) (mty2:ModuleOrNamespaceType) = + let rec CombineModuleOrNamespaceTypes path m (mty1: ModuleOrNamespaceType) (mty2: ModuleOrNamespaceType) = match mty1.ModuleOrNamespaceKind, mty2.ModuleOrNamespaceKind with | Namespace, Namespace -> let kind = mty1.ModuleOrNamespaceKind @@ -5846,7 +5854,7 @@ let CombineCcuContentFragments m l = | _-> error(Error(FSComp.SR.tastTwoModulesWithSameNameInAssembly(textOfPath path), m)) - and CombineEntites path (entity1:Entity) (entity2:Entity) = + and CombineEntites path (entity1: Entity) (entity2: Entity) = match entity1.IsModuleOrNamespace, entity2.IsModuleOrNamespace with | true, true -> diff --git a/tests/scripts/codingConventions.fsx b/tests/scripts/codingConventions.fsx index c8fa69bbe32..46ddf3804d6 100644 --- a/tests/scripts/codingConventions.fsx +++ b/tests/scripts/codingConventions.fsx @@ -67,3 +67,37 @@ let semis = printfn "Top files that have semicolon at end of line: %A" (Array.truncate 10 semis) + +printfn "------NO SPACE AFTER COLON----------" + +open System.Text.RegularExpressions + +let noSpaceAfterColons = + let re = Regex(":[a-zA-Z]") + lines + |> Array.groupBy fst + |> Array.map (fun (file, lines) -> + file, + lines + |> Array.filter (fun (_,(_,line)) -> re.IsMatch(line)) + |> Array.length) + |> Array.sortByDescending snd + +printfn "Top files that have no space after colon:\n%A" (Array.truncate 10 noSpaceAfterColons) + +printfn "------ SPACE BEFORE COLON----------" + + +let spaceBeforeColon = + let re = Regex("[^\\)] : [a-zA-Z]") + lines + |> Array.groupBy fst + |> Array.map (fun (file, lines) -> + file, + lines + |> Array.filter (fun (_,(_,line)) -> re.IsMatch(line)) + |> Array.length) + |> Array.sortByDescending snd + +printfn "Top files that have extra space before colon:\n%A" (Array.truncate 10 spaceBeforeColon) +