From d5f5bd005aebdd20088a4be20939aea0e9da29fb Mon Sep 17 00:00:00 2001 From: Don Syme Date: Wed, 20 Mar 2019 17:27:42 +0000 Subject: [PATCH 01/27] more cleanup - spacing for commas and colons (#6343) * spacing for commas and colons * code review --- src/absil/il.fs | 150 ++-- src/absil/illib.fs | 269 +++--- src/absil/ilprint.fs | 127 +-- src/absil/ilread.fs | 260 +++--- src/absil/ilreflect.fs | 208 ++--- src/absil/ilsupp.fs | 516 +++++------ src/absil/ilwrite.fs | 200 ++--- src/absil/ilwritepdb.fs | 52 +- src/absil/zmap.fs | 44 +- src/absil/zset.fs | 49 +- src/fsharp/AugmentWithHashCompare.fs | 86 +- src/fsharp/CompileOps.fs | 464 +++++----- src/fsharp/CompileOptions.fs | 630 ++++++------- src/fsharp/ConstraintSolver.fs | 136 +-- src/fsharp/DetupleArgs.fs | 23 +- src/fsharp/ExtensionTyping.fs | 176 ++-- src/fsharp/FindUnsolved.fs | 84 +- src/fsharp/IlxGen.fs | 458 +++++----- src/fsharp/InfoReader.fs | 46 +- src/fsharp/InnerLambdasToTopLevelFuncs.fs | 111 +-- src/fsharp/LexFilter.fs | 32 +- src/fsharp/MethodCalls.fs | 62 +- src/fsharp/MethodOverrides.fs | 38 +- src/fsharp/NameResolution.fs | 312 +++---- src/fsharp/NicePrint.fs | 350 ++++---- src/fsharp/Optimizer.fs | 78 +- src/fsharp/PatternMatchCompilation.fs | 4 +- src/fsharp/PostInferenceChecks.fs | 54 +- src/fsharp/PrettyNaming.fs | 70 +- src/fsharp/QuotationTranslator.fs | 36 +- src/fsharp/SignatureConformance.fs | 42 +- src/fsharp/TastOps.fs | 840 +++++++++--------- src/fsharp/TastPickle.fs | 128 +-- src/fsharp/TypeChecker.fs | 680 +++++++------- src/fsharp/TypeRelations.fs | 142 ++- src/fsharp/ast.fs | 669 +++++++------- src/fsharp/fsc.fs | 88 +- src/fsharp/import.fs | 46 +- src/fsharp/infos.fs | 38 +- src/fsharp/layout.fs | 146 +-- src/fsharp/lib.fs | 140 +-- src/fsharp/service/IncrementalBuild.fs | 128 +-- src/fsharp/service/ServiceDeclarationLists.fs | 88 +- src/fsharp/service/ServiceLexing.fs | 250 +++--- src/fsharp/service/ServiceUntypedParse.fs | 18 +- src/fsharp/symbols/Exprs.fs | 126 +-- src/fsharp/symbols/SymbolHelpers.fs | 66 +- src/fsharp/tast.fs | 312 +++---- tests/scripts/codingConventions.fsx | 34 + 49 files changed, 4603 insertions(+), 4503 deletions(-) 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) + From bb110d5865381fe35e8605219e59e0c94eada721 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Tue, 19 Mar 2019 13:44:16 -0700 Subject: [PATCH 02/27] consume dotnet arcade sdk --- .gitignore | 5 +- .vsts-pr.yaml | 144 ++- .vsts-signed.yaml | 158 +-- Build.cmd | 2 + DEVGUIDE.md | 111 +- ...ctory.Build.props => Directory.Build.props | 0 ...y.Build.targets => Directory.Build.targets | 2 - DotnetCLIToolsVersion.txt | 1 - FSharp.sln | 150 +-- FSharpBuild.Directory.Build.props | 28 +- FSharpBuild.Directory.Build.targets | 8 +- FSharpTests.Directory.Build.props | 4 +- NuGet.Config => NuGet.config | 0 PublishToBlob.proj | 42 - Restore.cmd | 2 + Test.cmd | 2 + VisualFSharp.sln | 494 ++++++-- build.cmd | 1087 ----------------- build.sh | 17 +- build/config/AssemblySignToolData.json | 70 -- build/config/InsertionSignToolData.json | 37 - build/config/PackageSignToolData.json | 24 - build/projects/Directory.Build.props | 3 - build/projects/Directory.Build.targets | 3 - build/projects/Signing.proj | 27 - build/targets/AssemblyVersions.props | 62 - build/targets/CommonPackages.targets | 7 - build/targets/ConvertPortablePdbs.targets | 40 - .../GenerateAssemblyAttributes.targets | 119 -- .../GenerateInternalsVisibleTo.targets | 80 -- build/targets/GitHash.props | 51 - build/targets/NGenOrCrossGen.targets | 36 - eng/Build.ps1 | 286 +++++ eng/CIBuild.cmd | 2 + eng/Version.Details.xml | 11 + .../Versions.props | 89 +- eng/build-utils.ps1 | 257 ++++ eng/build.sh | 245 ++++ eng/cibuild.sh | 19 + eng/common/PublishBuildAssets.cmd | 3 - eng/common/PublishToPackageFeed.proj | 46 +- eng/common/build.ps1 | 13 +- eng/common/build.sh | 70 +- eng/common/cibuild.sh | 0 eng/common/cross/armel/tizen-build-rootfs.sh | 0 eng/common/cross/armel/tizen-fetch.sh | 0 eng/common/cross/build-android-rootfs.sh | 0 eng/common/cross/build-rootfs.sh | 0 eng/common/darc-init.ps1 | 2 +- eng/common/darc-init.sh | 23 +- eng/common/generate-graph-files.ps1 | 87 ++ eng/common/init-tools-native.ps1 | 14 +- eng/common/init-tools-native.sh | 0 eng/common/internal/Directory.Build.props | 4 + eng/common/internal/Tools.csproj | 23 + eng/common/msbuild.sh | 0 eng/common/native/common-library.sh | 0 eng/common/native/install-cmake.sh | 0 eng/common/sdk-task.ps1 | 73 +- .../templates/job/generate-graph-files.yml | 48 + eng/common/templates/job/job.yml | 48 +- .../templates/job/publish-build-assets.yml | 17 +- eng/common/templates/jobs/jobs.yml | 31 +- .../templates/phases/publish-build-assets.yml | 13 +- eng/common/templates/steps/send-to-helix.yml | 64 +- eng/common/templates/steps/telemetry-end.yml | 87 +- .../templates/steps/telemetry-start.yml | 161 ++- eng/common/tools.ps1 | 41 +- eng/common/tools.sh | 17 +- eng/targets/NuGet.targets | 20 + eng/targets/Settings.props | 11 + fcs/Directory.Build.props | 8 + .../FSharp.Compiler.Service.Tests.fsproj | 1 + fcs/build.fsx | 9 +- fsharp.proj | 178 --- global.json | 19 +- packages.config | 4 - proto.proj | 1 - restore.sh | 16 + scripts/AssemblyVersionCheck.fsx | 69 ++ .../VerifyAllTranslations.fsx | 0 init-tools.cmd => scripts/init-tools.cmd | 4 +- init-tools.sh => scripts/init-tools.sh | 4 +- scripts/verify-translations.cmd | 3 + setup/Directory.Build.props | 5 +- setup/Directory.Build.targets | 3 - setup/Swix/Directory.Build.props | 4 +- setup/Swix/Directory.Build.targets | 16 +- .../Microsoft.FSharp.Compiler.MSBuild.csproj | 131 ++ .../Empty.swr | 5 - .../Files.swr | 11 - ...crosoft.FSharp.Compiler.Resources.swixproj | 33 - .../Dependencies.swr | 9 - .../Swix/Microsoft.FSharp.Compiler/Files.swr | 39 - .../Microsoft.FSharp.Compiler.swixproj | 31 - .../Dependencies.swr | 4 +- .../Microsoft.FSharp.Dependencies/Files.swr | 4 +- .../Microsoft.FSharp.Dependencies.csproj | 19 + .../Microsoft.FSharp.Dependencies.swixproj | 33 - .../Microsoft.FSharp.IDE/Dependencies.swr | 8 +- setup/Swix/Microsoft.FSharp.IDE/Files.swr | 2 +- .../Microsoft.FSharp.IDE.csproj | 17 + .../Microsoft.FSharp.IDE.swixproj | 29 - setup/Swix/Microsoft.FSharp.SDK/Files.swr | 2 +- .../Microsoft.FSharp.SDK.csproj | 23 + .../Microsoft.FSharp.SDK.swixproj | 26 - .../Microsoft.FSharp.Vsix.Resources/Empty.swr | 6 - .../Microsoft.FSharp.Vsix.Resources/Files.swr | 20 - .../Microsoft.FSharp.Vsix.Resources.swixproj | 44 - .../Templates.swr | 13 - setup/Swix/Microsoft.FSharp.vsmanproj | 43 - setup/build-insertion.proj | 47 - setup/fsharp-setup-build.csproj | 58 - src/Directory.Build.props | 3 - src/Directory.Build.targets | 3 - src/buildtools/buildtools.targets | 19 +- src/fsharp/Directory.Nuget.props | 27 - src/fsharp/Directory.Nuget.targets | 11 - src/fsharp/FSharp.Build/Directory.Build.props | 9 + src/fsharp/FSharp.Build/FSharp.Build.fsproj | 2 +- .../Directory.Build.props | 9 + ...Sharp.Compiler.Interactive.Settings.fsproj | 2 +- .../Directory.Build.props | 9 + .../FSharp.Compiler.Private.fsproj | 10 +- .../Directory.Build.props | 9 + .../FSharp.Compiler.Server.Shared.fsproj | 2 - .../Directory.Build.props | 10 +- .../Directory.Build.targets | 18 - ...icrosoft.FSharp.Compiler.Prerelease.csproj | 8 - .../Microsoft.FSharp.Compiler.csproj | 24 +- .../Microsoft.FSharp.Compiler.nuspec | 57 +- .../Testing.FSharp.Compiler.csproj | 8 - src/fsharp/FSharp.Compiler.nuget/_._ | 0 src/fsharp/FSharp.Core/Directory.Build.props | 14 - .../FSharp.Core/Directory.Build.targets | 6 - src/fsharp/FSharp.Core/FSharp.Core.fsproj | 6 +- src/fsharp/FSharp.Core/FSharp.Core.nuspec | 41 +- src/fsharp/fsc/Directory.Build.props | 9 + src/fsharp/fsc/fsc.fsproj | 3 +- src/fsharp/fsi/Directory.Build.props | 9 + src/fsharp/fsi/fsi.fsproj | 3 +- src/fsharp/fsiAnyCpu/Directory.Build.props | 9 + src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj | 2 - test.sh | 16 + tests/Directory.Build.targets | 12 + .../Directory.Build.props | 8 +- .../Directory.Build.targets | 3 - .../FSharp.Build.UnitTests.fsproj | 1 + .../Directory.Build.props | 8 +- .../Directory.Build.targets | 3 - .../FSharp.Compiler.UnitTests.fsproj | 1 + .../Language/StringConcat.fs | 3 + .../Directory.Build.props | 3 - .../Directory.Build.targets | 3 - .../FSharp.Core.UnitTests.fsproj | 11 +- .../Microsoft.FSharp.Control/App.config | 19 - tests/FSharp.Directory.Build.props | 36 - tests/FSharp.Directory.Build.targets | 11 - tests/Resources/Directory.Build.props | 3 + tests/Resources/Directory.Build.targets | 3 + tests/fsharp/Directory.Build.props | 8 +- tests/fsharp/Directory.Build.targets | 3 - ...pSuite.fsproj => FSharpSuite.Tests.fsproj} | 1 + tests/fsharp/single-test.fs | 4 +- tests/fsharp/test-framework.fs | 6 +- tests/fsharp/tests.fs | 4 +- .../Source/CodeGen/StringEncoding/.gitignore | 3 + .../Source/CodeGen/StringEncoding/env.lst | 8 +- .../CompilerOptions/fsc/gccerrors/.gitignore | 2 + .../CompilerOptions/fsc/help/.gitignore | 2 + .../CompilerOptions/fsc/nologo/.gitignore | 3 + .../CompilerOptions/fsi/exename/.gitignore | 2 + .../CompilerOptions/fsi/help/.gitignore | 2 + .../IdentifiersAndKeywords/.gitignore | 2 + .../SignatureConformance/.gitignore | 2 + .../StructFieldEqualityComparison/.gitignore | 2 + tests/fsharpqa/Source/EntryPoint/.gitignore | 2 + .../ErrorMessages/ConfusingTypeName/env.lst | 2 +- .../Source/InteractiveSession/Misc/.gitignore | 4 + .../GenericConstraintWoes/issue2411/env.lst | 2 +- tests/fsharpqa/Source/Stress/.gitignore | 3 + tests/fsharpqa/Source/XmlDoc/.gitignore | 2 + tests/fsharpqa/Source/run.pl | 41 +- .../src/AssemblyVersionCheck/.gitignore | 2 - .../AssemblyVersionCheck.fsx | 95 -- .../testenv/src/Directory.Build.props | 3 - .../testenv/src/Directory.Build.targets | 3 - .../Directory.Build.props | 3 +- .../Directory.Build.targets | 3 +- tests/service/data/Directory.Build.props | 3 - tests/service/data/Directory.Build.targets | 3 - verify-translations.cmd | 3 - vsintegration/Directory.Build.props | 4 +- vsintegration/Directory.Build.targets | 10 +- .../DisableVsixManifestTargets.targets | 4 - .../ItemTemplates/AppConfig/AppConfig.csproj | 4 - .../AppConfig/source.extension.vsixmanifest | 25 + .../ItemTemplates/CodeFile/CodeFile.csproj | 4 - .../CodeFile/source.extension.vsixmanifest | 25 + .../ResourceFile/ResourceFile.csproj | 4 - .../source.extension.vsixmanifest | 25 + .../ScriptFile/ScriptFile.csproj | 4 - .../ScriptFile/source.extension.vsixmanifest | 25 + .../SignatureFile/SignatureFile.csproj | 4 - .../source.extension.vsixmanifest | 25 + .../ItemTemplates/TextFile/TextFile.csproj | 4 - .../TextFile/source.extension.vsixmanifest | 25 + .../ItemTemplates/XMLFile/XMLFile.csproj | 4 - .../XMLFile/source.extension.vsixmanifest | 25 + .../source.extension.vsixmanifest | 24 + .../ProjectTemplates/Directory.Build.props | 1 + .../source.extension.vsixmanifest | 25 + .../source.extension.vsixmanifest | 25 + vsintegration/Templates.Directory.Build.props | 14 +- vsintegration/Vsix/Directory.Build.props | 10 +- vsintegration/Vsix/Directory.Build.targets | 28 - .../Source.extension.vsixmanifest | 2 +- .../VisualFSharpFull/VisualFSharpFull.csproj | 25 +- .../Source.extension.vsixmanifest | 2 +- .../VisualFSharpTemplates.csproj | 16 +- ...rp-vsintegration-item-templates-build.proj | 23 - ...vsintegration-project-templates-build.proj | 20 - .../fsharp-vsintegration-src-build.proj | 26 - .../fsharp-vsintegration-unittests-build.proj | 31 - .../fsharp-vsintegration-vsix-build.proj | 15 - vsintegration/src/Directory.Build.props | 2 + .../FSharp.Editor/Completion/SignatureHelp.fs | 4 +- .../src/FSharp.Editor/FSharp.Editor.fsproj | 4 +- .../QuickInfo/QuickInfoProvider.fs | 30 +- .../DocumentTask.cs | 31 +- .../FSharp.LanguageService.Base.csproj | 3 +- .../GlobalSuppressions.cs | 7 + .../src/FSharp.LanguageService.Base/Source.cs | 2 + .../FSharp.LanguageService.fsproj | 5 +- .../FSharp.PatternMatcher.csproj | 1 + .../Project/FileNode.cs | 2 + .../Project/GlobalSuppressions.cs | 2 + .../Project/ProjectConfig.cs | 2 +- .../Project/ProjectNode.cs | 2 +- .../Project/ProjectSystem.Base.csproj | 3 +- .../Project/UIThread.cs | 27 +- .../FSharp.ProjectSystem.FSharp/.gitignore | 1 + .../ProjectSystem.fsproj | 16 +- .../source.extension.vsixmanifest | 2 + .../FSharp.PropertiesPages.vbproj | 60 +- .../My Project/Application.Designer.vb | 10 +- .../My Project/Settings.Designer.vb | 16 +- .../PropertyPages/ApplicationPropPage.vb | 2 - .../PropertyPages/BuildPropPage.vb | 4 +- .../PropertyPages/PropPageUserControlBase.vb | 2 +- .../PropertyPages/ReferencePathsPropPage.vb | 2 +- .../FSharp.UIResources.csproj | 18 +- .../src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj | 2 - .../GetTypesVS.UnitTests.fs} | 0 .../GetTypesVS.UnitTests.fsproj} | 5 +- .../tests/GetTypesVSUnitTests/App.config | 13 - .../MockTypeProviders/Directory.Build.props | 2 +- .../MockTypeProviders/Directory.Build.targets | 2 +- .../tests/Salsa/VisualFSharp.Salsa.fsproj | 1 + vsintegration/tests/UnitTests/App.config | 2 +- .../Tests.LanguageService.ParameterInfo.fs | 19 - .../Tests.LanguageService.QuickInfo.fs | 206 ---- .../Tests.LanguageService.Script.fs | 9 +- .../Tests.ProjectSystem.References.fs | 1 + .../tests/UnitTests/ProjectOptionsBuilder.fs | 140 +++ .../tests/UnitTests/QuickInfoTests.fs | 445 +++++++ .../UnitTests/SignatureHelpProviderTests.fs | 80 +- vsintegration/tests/UnitTests/Tests.Watson.fs | 6 +- .../UnitTests/VisualFSharp.UnitTests.fsproj | 79 +- 269 files changed, 4001 insertions(+), 4135 deletions(-) create mode 100644 Build.cmd rename FSharp.Directory.Build.props => Directory.Build.props (100%) rename FSharp.Directory.Build.targets => Directory.Build.targets (99%) delete mode 100644 DotnetCLIToolsVersion.txt rename NuGet.Config => NuGet.config (100%) delete mode 100644 PublishToBlob.proj create mode 100644 Restore.cmd create mode 100644 Test.cmd delete mode 100644 build.cmd delete mode 100644 build/config/AssemblySignToolData.json delete mode 100644 build/config/InsertionSignToolData.json delete mode 100644 build/config/PackageSignToolData.json delete mode 100644 build/projects/Directory.Build.props delete mode 100644 build/projects/Directory.Build.targets delete mode 100644 build/projects/Signing.proj delete mode 100644 build/targets/AssemblyVersions.props delete mode 100644 build/targets/CommonPackages.targets delete mode 100644 build/targets/ConvertPortablePdbs.targets delete mode 100644 build/targets/GenerateAssemblyAttributes.targets delete mode 100644 build/targets/GenerateInternalsVisibleTo.targets delete mode 100644 build/targets/GitHash.props delete mode 100644 build/targets/NGenOrCrossGen.targets create mode 100644 eng/Build.ps1 create mode 100644 eng/CIBuild.cmd create mode 100644 eng/Version.Details.xml rename build/targets/PackageVersions.props => eng/Versions.props (71%) create mode 100644 eng/build-utils.ps1 create mode 100755 eng/build.sh create mode 100755 eng/cibuild.sh delete mode 100644 eng/common/PublishBuildAssets.cmd mode change 100755 => 100644 eng/common/build.sh mode change 100755 => 100644 eng/common/cibuild.sh mode change 100755 => 100644 eng/common/cross/armel/tizen-build-rootfs.sh mode change 100755 => 100644 eng/common/cross/armel/tizen-fetch.sh mode change 100755 => 100644 eng/common/cross/build-android-rootfs.sh mode change 100755 => 100644 eng/common/cross/build-rootfs.sh mode change 100755 => 100644 eng/common/darc-init.sh create mode 100644 eng/common/generate-graph-files.ps1 mode change 100755 => 100644 eng/common/init-tools-native.sh create mode 100644 eng/common/internal/Directory.Build.props create mode 100644 eng/common/internal/Tools.csproj mode change 100755 => 100644 eng/common/msbuild.sh mode change 100755 => 100644 eng/common/native/common-library.sh mode change 100755 => 100644 eng/common/native/install-cmake.sh create mode 100644 eng/common/templates/job/generate-graph-files.yml mode change 100755 => 100644 eng/common/tools.sh create mode 100644 eng/targets/NuGet.targets create mode 100644 eng/targets/Settings.props delete mode 100644 fsharp.proj delete mode 100644 packages.config create mode 100755 restore.sh create mode 100644 scripts/AssemblyVersionCheck.fsx rename {src/scripts => scripts}/VerifyAllTranslations.fsx (100%) rename init-tools.cmd => scripts/init-tools.cmd (91%) rename init-tools.sh => scripts/init-tools.sh (98%) mode change 100755 => 100644 create mode 100644 scripts/verify-translations.cmd delete mode 100644 setup/Directory.Build.targets create mode 100644 setup/Swix/Microsoft.FSharp.Compiler.MSBuild/Microsoft.FSharp.Compiler.MSBuild.csproj delete mode 100644 setup/Swix/Microsoft.FSharp.Compiler.Resources/Empty.swr delete mode 100644 setup/Swix/Microsoft.FSharp.Compiler.Resources/Files.swr delete mode 100644 setup/Swix/Microsoft.FSharp.Compiler.Resources/Microsoft.FSharp.Compiler.Resources.swixproj delete mode 100644 setup/Swix/Microsoft.FSharp.Compiler/Dependencies.swr delete mode 100644 setup/Swix/Microsoft.FSharp.Compiler/Files.swr delete mode 100644 setup/Swix/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.swixproj create mode 100644 setup/Swix/Microsoft.FSharp.Dependencies/Microsoft.FSharp.Dependencies.csproj delete mode 100644 setup/Swix/Microsoft.FSharp.Dependencies/Microsoft.FSharp.Dependencies.swixproj create mode 100644 setup/Swix/Microsoft.FSharp.IDE/Microsoft.FSharp.IDE.csproj delete mode 100644 setup/Swix/Microsoft.FSharp.IDE/Microsoft.FSharp.IDE.swixproj create mode 100644 setup/Swix/Microsoft.FSharp.SDK/Microsoft.FSharp.SDK.csproj delete mode 100644 setup/Swix/Microsoft.FSharp.SDK/Microsoft.FSharp.SDK.swixproj delete mode 100644 setup/Swix/Microsoft.FSharp.Vsix.Resources/Empty.swr delete mode 100644 setup/Swix/Microsoft.FSharp.Vsix.Resources/Files.swr delete mode 100644 setup/Swix/Microsoft.FSharp.Vsix.Resources/Microsoft.FSharp.Vsix.Resources.swixproj delete mode 100644 setup/Swix/Microsoft.FSharp.Vsix.Resources/Templates.swr delete mode 100644 setup/Swix/Microsoft.FSharp.vsmanproj delete mode 100644 setup/build-insertion.proj delete mode 100644 setup/fsharp-setup-build.csproj delete mode 100644 src/Directory.Build.props delete mode 100644 src/Directory.Build.targets delete mode 100644 src/fsharp/Directory.Nuget.props delete mode 100644 src/fsharp/Directory.Nuget.targets create mode 100644 src/fsharp/FSharp.Build/Directory.Build.props create mode 100644 src/fsharp/FSharp.Compiler.Interactive.Settings/Directory.Build.props create mode 100644 src/fsharp/FSharp.Compiler.Private/Directory.Build.props create mode 100644 src/fsharp/FSharp.Compiler.Server.Shared/Directory.Build.props delete mode 100644 src/fsharp/FSharp.Compiler.nuget/Directory.Build.targets delete mode 100644 src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.Prerelease.csproj delete mode 100644 src/fsharp/FSharp.Compiler.nuget/Testing.FSharp.Compiler.csproj delete mode 100644 src/fsharp/FSharp.Compiler.nuget/_._ delete mode 100644 src/fsharp/FSharp.Core/Directory.Build.props delete mode 100644 src/fsharp/FSharp.Core/Directory.Build.targets create mode 100644 src/fsharp/fsc/Directory.Build.props create mode 100644 src/fsharp/fsi/Directory.Build.props create mode 100644 src/fsharp/fsiAnyCpu/Directory.Build.props create mode 100755 test.sh create mode 100644 tests/Directory.Build.targets delete mode 100644 tests/FSharp.Build.UnitTests/Directory.Build.targets delete mode 100644 tests/FSharp.Compiler.UnitTests/Directory.Build.targets delete mode 100644 tests/FSharp.Core.UnitTests/Directory.Build.props delete mode 100644 tests/FSharp.Core.UnitTests/Directory.Build.targets delete mode 100644 tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/App.config delete mode 100644 tests/FSharp.Directory.Build.props delete mode 100644 tests/FSharp.Directory.Build.targets create mode 100644 tests/Resources/Directory.Build.props create mode 100644 tests/Resources/Directory.Build.targets delete mode 100644 tests/fsharp/Directory.Build.targets rename tests/fsharp/{FSharp.Tests.FSharpSuite.fsproj => FSharpSuite.Tests.fsproj} (96%) create mode 100644 tests/fsharpqa/Source/CodeGen/StringEncoding/.gitignore create mode 100644 tests/fsharpqa/Source/CompilerOptions/fsc/gccerrors/.gitignore create mode 100644 tests/fsharpqa/Source/CompilerOptions/fsc/help/.gitignore create mode 100644 tests/fsharpqa/Source/CompilerOptions/fsc/nologo/.gitignore create mode 100644 tests/fsharpqa/Source/CompilerOptions/fsi/exename/.gitignore create mode 100644 tests/fsharpqa/Source/CompilerOptions/fsi/help/.gitignore create mode 100644 tests/fsharpqa/Source/Conformance/LexicalAnalysis/IdentifiersAndKeywords/.gitignore create mode 100644 tests/fsharpqa/Source/Conformance/Signatures/SignatureConformance/.gitignore create mode 100644 tests/fsharpqa/Source/Conformance/StructFieldEqualityComparison/.gitignore create mode 100644 tests/fsharpqa/Source/EntryPoint/.gitignore create mode 100644 tests/fsharpqa/Source/InteractiveSession/Misc/.gitignore create mode 100644 tests/fsharpqa/Source/Stress/.gitignore create mode 100644 tests/fsharpqa/Source/XmlDoc/.gitignore delete mode 100644 tests/fsharpqa/testenv/src/AssemblyVersionCheck/.gitignore delete mode 100644 tests/fsharpqa/testenv/src/AssemblyVersionCheck/AssemblyVersionCheck.fsx delete mode 100644 tests/fsharpqa/testenv/src/Directory.Build.props delete mode 100644 tests/fsharpqa/testenv/src/Directory.Build.targets delete mode 100644 tests/service/data/Directory.Build.props delete mode 100644 tests/service/data/Directory.Build.targets delete mode 100644 verify-translations.cmd delete mode 100644 vsintegration/DisableVsixManifestTargets.targets create mode 100644 vsintegration/ItemTemplates/AppConfig/source.extension.vsixmanifest create mode 100644 vsintegration/ItemTemplates/CodeFile/source.extension.vsixmanifest create mode 100644 vsintegration/ItemTemplates/ResourceFile/source.extension.vsixmanifest create mode 100644 vsintegration/ItemTemplates/ScriptFile/source.extension.vsixmanifest create mode 100644 vsintegration/ItemTemplates/SignatureFile/source.extension.vsixmanifest create mode 100644 vsintegration/ItemTemplates/TextFile/source.extension.vsixmanifest create mode 100644 vsintegration/ItemTemplates/XMLFile/source.extension.vsixmanifest create mode 100644 vsintegration/ProjectTemplates/ConsoleProject/source.extension.vsixmanifest create mode 100644 vsintegration/ProjectTemplates/LibraryProject/source.extension.vsixmanifest create mode 100644 vsintegration/ProjectTemplates/TutorialProject/source.extension.vsixmanifest delete mode 100644 vsintegration/Vsix/Directory.Build.targets delete mode 100644 vsintegration/fsharp-vsintegration-item-templates-build.proj delete mode 100644 vsintegration/fsharp-vsintegration-project-templates-build.proj delete mode 100644 vsintegration/fsharp-vsintegration-src-build.proj delete mode 100644 vsintegration/fsharp-vsintegration-unittests-build.proj delete mode 100644 vsintegration/fsharp-vsintegration-vsix-build.proj create mode 100644 vsintegration/src/FSharp.LanguageService.Base/GlobalSuppressions.cs create mode 100644 vsintegration/src/FSharp.ProjectSystem.FSharp/.gitignore create mode 100644 vsintegration/src/FSharp.ProjectSystem.FSharp/source.extension.vsixmanifest rename vsintegration/tests/{GetTypesVSUnitTests/GetTypesVSUnitTests.fs => GetTypesVS.UnitTests/GetTypesVS.UnitTests.fs} (100%) rename vsintegration/tests/{GetTypesVSUnitTests/GetTypesVSUnitTests.fsproj => GetTypesVS.UnitTests/GetTypesVS.UnitTests.fsproj} (92%) delete mode 100644 vsintegration/tests/GetTypesVSUnitTests/App.config create mode 100644 vsintegration/tests/UnitTests/ProjectOptionsBuilder.fs create mode 100644 vsintegration/tests/UnitTests/QuickInfoTests.fs diff --git a/.gitignore b/.gitignore index 418b3677b36..1a1ec2707c2 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ # output location artifacts/ -packages/ - /tests/scripts/current +.dotnet/ +.packages/ +./tools # Patches that may have been generated by scripts. # (These aren't generally useful to commit directly; if anything, they should be applied.) diff --git a/.vsts-pr.yaml b/.vsts-pr.yaml index c9f88e2296c..b7d3862888d 100644 --- a/.vsts-pr.yaml +++ b/.vsts-pr.yaml @@ -1,4 +1,5 @@ jobs: + - job: Linux pool: vmImage: ubuntu-16.04 @@ -6,21 +7,42 @@ jobs: strategy: maxParallel: 3 matrix: - dotnet_sdk: - _command: make - _args: Configuration=release - release_fcs: - _command: ./fcs/build.sh - _args: Build + coreclr_release: + _configuration: Release + _testKind: testcoreclr + steps: + - script: ./eng/cibuild.sh --configuration $(_configuration) --$(_testKind) + - task: PublishBuildArtifacts@1 + displayName: Publish Build Logs + inputs: + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_configuration)' + ArtifactName: 'Linux $(_configuration) $(_testKind) build log' + publishLocation: Container + continueOnError: true + condition: not(succeeded()) + - task: PublishBuildArtifacts@1 + displayName: Publish Test Results + inputs: + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults' + ArtifactName: 'Linux $(_configuration) $(_testKind)' + publishLocation: Container + continueOnError: true + condition: not(succeeded()) + +- job: Linux_FCS + pool: + vmImage: ubuntu-16.04 + timeoutInMinutes: 90 steps: - - script: $(_command) $(_args) + - script: ./fcs/build.sh Build - task: PublishBuildArtifacts@1 + displayName: Publish Test Results inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults' - ArtifactName: 'Linux $(_command) $(_args)' + ArtifactName: 'Linux FCS test results' publishLocation: Container continueOnError: true - condition: failed() + condition: not(succeeded()) - job: MacOS pool: @@ -29,56 +51,92 @@ jobs: strategy: maxParallel: 3 matrix: - dotnet_sdk: - _command: make - _args: Configuration=release - release_fcs: - _command: ./fcs/build.sh - _args: Build + coreclr_release: + _configuration: Release + _testKind: testcoreclr steps: - - script: $(_command) $(_args) + - script: ./eng/cibuild.sh --configuration $(_configuration) --$(_testKind) - task: PublishBuildArtifacts@1 + displayName: Publish Build Logs + inputs: + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_configuration)' + ArtifactName: 'MacOS $(_configuration) $(_testKind) build log' + publishLocation: Container + continueOnError: true + condition: not(succeeded()) + - task: PublishBuildArtifacts@1 + displayName: Publish Test Results inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults' - ArtifactName: 'MacOS $(_command) $(_args)' + ArtifactName: 'MacOS $(_configuration) $(_testKind)' publishLocation: Container continueOnError: true - condition: failed() + condition: not(succeeded()) + +- job: MacOS_FCS + pool: + vmImage: macOS-10.13 + timeoutInMinutes: 90 + steps: + - script: ./fcs/build.sh Build + - task: PublishBuildArtifacts@1 + displayName: Publish Test Results + inputs: + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/TestResults' + ArtifactName: 'MacOS FCS test results' + publishLocation: Container + continueOnError: true + condition: not(succeeded()) - job: Windows pool: vmImage: vs2017-win2016 timeoutInMinutes: 120 strategy: - maxParallel: 7 + maxParallel: 4 matrix: - ci_part1: - _command: build.cmd - _args: release ci_part1 - ci_part2: - _command: build.cmd - _args: release ci_part2 - ci_part3: - _command: build.cmd - _args: release ci_part3 - ci_part4: - _command: build.cmd - _args: release ci_part4 - debug_default: - _command: build.cmd - _args: debug - net40_no_vs: - _command: build.cmd - _args: release net40 - release_fcs: - _command: fcs\build.cmd - _args: TestAndNuget + desktop_release: + _configuration: Release + _testKind: testDesktop + coreclr_release: + _configuration: Release + _testKind: testCoreclr + fsharpqa_release: + _configuration: Release + _testKind: testFSharpQA + vs_release: + _configuration: Release + _testKind: testVs + steps: + - script: eng\CIBuild.cmd -configuration $(_configuration) -$(_testKind) + - task: PublishBuildArtifacts@1 + displayName: Publish Build Logs + inputs: + PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(_configuration)' + ArtifactName: 'Windows $(_configuration) $(_testKind) build log' + publishLocation: Container + continueOnError: true + condition: not(succeeded()) + - task: PublishBuildArtifacts@1 + displayName: Publish Test Results + inputs: + PathtoPublish: '$(Build.SourcesDirectory)\artifacts\TestResults' + ArtifactName: 'Windows $(_configuration) $(_testKind) test results' + publishLocation: Container + continueOnError: true + condition: not(succeeded()) + +- job: Windows_FCS + pool: + vmImage: vs2017-win2016 + timeoutInMinutes: 120 steps: - - script: $(_command) $(_args) + - script: fcs\build.cmd TestAndNuget - task: PublishBuildArtifacts@1 + displayName: Publish Test Results inputs: PathtoPublish: '$(Build.SourcesDirectory)\artifacts\TestResults' - ArtifactName: 'Windows $(_command) $(_args)' + ArtifactName: 'Windows FCS test results' publishLocation: Container continueOnError: true - condition: failed() + condition: not(succeeded()) diff --git a/.vsts-signed.yaml b/.vsts-signed.yaml index 823ac20297a..599237086b3 100644 --- a/.vsts-signed.yaml +++ b/.vsts-signed.yaml @@ -1,9 +1,9 @@ variables: -- name: PB_PublishBlobFeedUrl - value: https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json - group: DotNet-Blob-Feed -- name: PB_PublishBlobFeedKey - value: $(dotnetfeed-storage-access-key-1) +- name: SignType + value: real +- name: VisualStudioDropName + value: Products/$(System.TeamProject)/$(Build.Repository.Name)/$(Build.SourceBranchName)/$(Build.BuildNumber) jobs: - job: Full_Signed @@ -13,124 +13,96 @@ jobs: variables: BuildConfiguration: 'Release' steps: + # Install Signing Plugin - task: ms-vseng.MicroBuildTasks.30666190-6959-11e5-9f96-f56098202fef.MicroBuildSigningPlugin@1 displayName: Install Signing Plugin inputs: signType: real - condition: and(succeeded(), in(variables['PB_SignType'], 'test', 'real')) - - # Install Swix Plugin - - task: ms-vseng.MicroBuildTasks.32f78468-e895-4f47-962c-58a699361df8.MicroBuildSwixPlugin@1 - displayName: Install Swix Plugin + esrpSigning: true + condition: and(succeeded(), ne(variables['SignType'], '')) - # Run build.cmd - - task: CmdLine@1 - displayName: Run build.cmd - inputs: - filename: build.cmd - arguments: microbuild + # Build + - script: eng\CIBuild.cmd + -configuration $(BuildConfiguration) + -testAll + /p:OfficialBuildId=$(BUILD.BUILDNUMBER) + /p:VisualStudioDropName=$(VisualStudioDropName) + /p:DotNetSignType=$(SignType) + /p:DotNetPublishToBlobFeed=true + /p:DotNetPublishBlobFeedKey=$(dotnetfeed-storage-access-key-1) + /p:DotNetPublishBlobFeedUrl=https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json + /p:PublishToSymbolServer=true + /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) + /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) + displayName: Build - # Publish nightly package to MyGet - - task: PowerShell@1 - displayName: Publish nightly package to MyGet + # Publish logs + - task: PublishBuildArtifacts@1 + displayName: Publish Logs inputs: - scriptName: 'setup\publish-assets.ps1' - arguments: '-binariesPath artifacts\bin -configuration $(BuildConfiguration) -branchName $(Build.SourceBranch) -apiKey $(FSharp.MyGetApiKey)' - condition: and(succeeded(), contains(variables['PB_PublishType'], 'myget')) + PathtoPublish: '$(Build.SourcesDirectory)\artifacts\log\$(BuildConfiguration)' + ArtifactName: 'Build Diagnostic Files' + publishLocation: Container + continueOnError: true + condition: succeededOrFailed() - # Package publish - - task: CmdLine@1 - displayName: Restore package publishing - inputs: - filename: '.nuget\NuGet.exe' - arguments: 'restore packages.config -PackagesDirectory packages -Source https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json' - condition: and(succeeded(), contains(variables['PB_PublishType'], 'blob')) - - task: MSBuild@1 - displayName: Publish packages to Azure Blob Storage - inputs: - solution: PublishToBlob.proj - msbuildArguments: '/t:Build /p:Configuration=$(BuildConfiguration) /p:ExpectedFeedUrl=$(PB_PublishBlobFeedUrl) /p:AccountKey=$(PB_PublishBlobFeedKey) /p:ManifestRepouri=$(Build.Repository.Uri) /p:ManifestBranch=$(Build.SourceBranch) /p:ManifestCommit=$(Build.SourceVersion) /p:ManifestBuildId=$(Build.BuildNumber) /bl:$(Build.SourcesDirectory)/artifacts/log/$(BuildConfiguration)/pub/publish.binlog' - condition: and(succeeded(), contains(variables['PB_PublishType'], 'blob')) + # Publish test results - task: PublishBuildArtifacts@1 - displayName: Publish publishing bin log + displayName: Publish Test Results inputs: - PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(BuildConfiguration)/pub' - ArtifactName: 'Publish_bin_log' + PathtoPublish: '$(Build.SourcesDirectory)\artifacts\TestResults' + ArtifactName: 'Test Results' publishLocation: Container continueOnError: true - condition: and(succeeded(), contains(variables['PB_PublishType'], 'blob')) - - task: CopyFiles@2 - displayName: Gather Asset Manifests + condition: succeededOrFailed() + + # Upload VSTS Drop + - task: ms-vseng.MicroBuildTasks.4305a8de-ba66-4d8b-b2d1-0dc4ecbbf5e8.MicroBuildUploadVstsDropFolder@1 + displayName: Upload VSTS Drop inputs: - SourceFolder: '$(Build.SourcesDirectory)/artifacts/log/$(BuildConfiguration)/AssetManifest' - TargetFolder: '$(Build.StagingDirectory)/AssetManifests' - continueOnError: true - condition: and(succeeded(), contains(variables['PB_PublishType'], 'blob')) + DropName: $(VisualStudioDropName) + DropFolder: '$(Build.SourcesDirectory)\artifacts\VSSetup\$(BuildConfiguration)\Insertion' + condition: succeeded() + + # Publish an artifact that the RoslynInsertionTool is able to find by its name. - task: PublishBuildArtifacts@1 - displayName: Push Asset Manifests + displayName: Publish Artifact VSSetup inputs: - PathtoPublish: '$(Build.StagingDirectory)/AssetManifests' - PublishLocation: Container - ArtifactName: AssetManifests - continueOnError: true - condition: and(succeeded(), contains(variables['PB_PublishType'], 'blob')) + PathtoPublish: '$(Build.SourcesDirectory)\artifacts\VSSetup\$(BuildConfiguration)\Insertion' + ArtifactName: 'VSSetup' + condition: succeeded() - # Create static drop + # Archive NuGet packages to DevOps. - task: PublishBuildArtifacts@1 - displayName: Create static drop + displayName: Publish Artifact Packages inputs: - PathtoPublish: 'artifacts' - ArtifactName: '$(Build.BuildNumber)' - publishLocation: FilePath - TargetPath: '$(DropRoot)\$(Build.DefinitionName)\$(Build.SourceBranchName)' - Parallel: true - ParallelCount: 64 - condition: and(succeeded(), contains(variables['PB_PublishType'], 'drop')) + PathtoPublish: '$(Build.SourcesDirectory)\artifacts\packages\$(BuildConfiguration)' + ArtifactName: 'Packages' + condition: succeeded() - # Publish symbols - - task: PublishSymbols@1 - displayName: Publish symbols + # Publish nightly package to MyGet + - task: PowerShell@1 + displayName: Publish nightly package to MyGet inputs: - SymbolsPath: '$(DropRoot)\$(Build.DefinitionName)\$(Build.SourceBranchName)\$(Build.BuildNumber)\Symbols' - SearchPattern: '**\*.dll;**\*.exe;**\*.pdb' - SymbolsFolder: '$(Build.SourcesDirectory)\artifacts\SymStore' - TreatNotIndexedAsWarning: true - SymbolsProduct: '$(Build.DefinitionName)' - SymbolsVersion: '$(Build.BuildNumber)' - continueOnError: true - condition: and(succeeded(), contains(variables['PB_PublishType'], 'symbols')) + scriptName: 'setup\publish-assets.ps1' + arguments: '-binariesPath artifacts\bin -configuration $(BuildConfiguration) -branchName $(Build.SourceBranch) -apiKey $(FSharp.MyGetApiKey)' + condition: succeeded() - # Upload VSTS Drop - - task: ms-vseng.MicroBuildTasks.4305a8de-ba66-4d8b-b2d1-0dc4ecbbf5e8.MicroBuildUploadVstsDropFolder@1 - displayName: Upload VSTS Drop + # Package publish + - task: PublishBuildArtifacts@1 + displayName: Push Asset Manifests inputs: - DropFolder: '$(Build.SourcesDirectory)\artifacts\VSSetup\$(BuildConfiguration)\Insertion' - condition: and(succeeded(), contains(variables['PB_PublishType'], 'vsts')) + PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(BuildConfiguration)/AssetManifest' + ArtifactName: AssetManifests + continueOnError: true + condition: succeeded() # Execute cleanup tasks - task: ms-vseng.MicroBuildTasks.521a94ea-9e68-468a-8167-6dcf361ea776.MicroBuildCleanup@1 displayName: Execute cleanup tasks condition: succeededOrFailed() - # Publish Artifact: MicroBuildOutputs - - task: PublishBuildArtifacts@1 - displayName: 'Publish Artifact: MicroBuildOutputs' - inputs: - PathtoPublish: '$(Build.StagingDirectory)\MicroBuild\Output' - ArtifactName: MicroBuildOutputs - publishLocation: Container - condition: and(succeeded(), contains(variables['PB_PublishType'], 'microbuild')) - - # Publish Symbols to Symweb - - task: ms-vscs-artifact.build-tasks.artifactSymbolTask-1.artifactSymbolTask@0 - displayName: Publish symbols to SymWeb - inputs: - symbolServiceURI: 'https://microsoft.artifacts.visualstudio.com/DefaultCollection' - sourcePath: '$(DropRoot)\$(Build.DefinitionName)\$(Build.SourceBranchName)\$(Build.BuildNumber)\SymStore' - usePat: false - condition: and(succeeded(), contains(variables['PB_PublishType'], 'symweb')) - - template: /eng/common/templates/job/publish-build-assets.yml parameters: dependsOn: diff --git a/Build.cmd b/Build.cmd new file mode 100644 index 00000000000..ad55484933d --- /dev/null +++ b/Build.cmd @@ -0,0 +1,2 @@ +@echo off +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0eng\build.ps1""" -build -restore %*" diff --git a/DEVGUIDE.md b/DEVGUIDE.md index e9c62109a96..1c0ff3eabe3 100644 --- a/DEVGUIDE.md +++ b/DEVGUIDE.md @@ -34,97 +34,33 @@ Install 2. The command prompt must have Administrator rights (`Run as Administrator`). -On Windows you can build the F# compiler for .NET Framework as follows: +On Windows you can build the F# compiler and tools as follows: - build.cmd + Build.cmd -This is the same as +Desktop tests can be run with: - build.cmd net40 + Build.cmd -test -There are various qualifiers: +Additional options are available via: - build.cmd release -- build release (the default) - build.cmd debug -- build debug instead of release - - build.cmd net40 -- build .NET Framework compiler (the default) - build.cmd coreclr -- build .NET Core compiler - build.cmd vs -- build the Visual F# IDE Tools (see below) - build.cmd pcls -- build the PCL FSharp.Core libraries - build.cmd all -- build all - - build.cmd proto -- force the rebuild of the Proto bootstrap compiler in addition to other things - - build.cmd test -- build default targets, run suitable tests - build.cmd net40 test -- build net40, run suitable tests - build.cmd coreclr test -- build coreclr, run suitable tests - build.cmd vs test -- build Visual F# IDE Tools, run all tests (see below) - build.cmd all test -- build all, run all tests - - build.cmd test-smoke -- build, run smoke tests - build.cmd test-net40-fsharp -- build, run tests\fsharp suite for .NET Framework - build.cmd test-net40-fsharpqa -- build, run tests\fsharpqa suite for .NET Framework + Build.cmd /? After you build the first time you can open and use this solution: - .\FSharp.sln - -or just build it directly: - - msbuild FSharp.sln + .\VisualFSharp.sln If you are just developing the core compiler and library then building ``FSharp.sln`` will be enough. -### Developing the F# Compiler (Linux) - -For Linux/Mono, follow [these instructions](http://www.mono-project.com/docs/getting-started/install/linux/). Also you may need: - - sudo apt-get install mono-complete make git - -Then: - - make - -Then to replace your machine-wide installation: - - sudo make install - -Full testing is not yet enabled on Linux. - -### Developing the F# Compiler (macOS) +### Developing the F# Compiler (Linux/macOS) -Install XCode command line tools (or homebrew equivalents) and Mono or Visual Studio for Mac. +For Linux/Mac: -Then: + ./build.sh - make +Running tests: -Then to replace your machine-wide installation: - - sudo make install - -Full testing is not yet enabled on macOS. - -### [Optional] Specifying the install path (Linux or macOS) - -You can specify a custom installation path using the DESTDIR shell variable - - DESTDIR=/my/path/to/fsharp make install - -### Developing the F# Compiler (Linux or macOS - .NET Core) - -Install [the latest .NET SDK](https://www.microsoft.com/net/download/). Then use - - src/buildfromsource.sh - -Outputs are placed in - - BuildFromSource/Debug/... - BuildFromSource/Release/... - -This uses an installed .NET SDK 2.0 to build the various duplicated project - -Testing the .NET Core version of the F# compiler on macOS and Linux is TBD. + ./build.sh -test ### Developing the Visual F# IDE Tools (Windows Only) @@ -132,15 +68,26 @@ To build and test Visual F# IDE Tools, install these requirements: - Download [Visual Studio 2017](https://www.visualstudio.com/downloads/) - Launch the Visual Studio Installer - - Under the "Windows" workloads, select ".NET desktop development" - - Select "F# desktop language support" under the optional components - - Under the "Other Toolsets" workloads, select "Visual Studio extension development" + - Under the **"Windows"** workload, select **".NET desktop development"** + - Select the optional component **"F# desktop language support"** + - Under the **"Mobile & Gaming"** workload, select **"Mobile development with .NET"** + - Under the **"Other Toolsets"** workload, select **"Visual Studio extension development"** + - On the **"Individual Components"** tab, select **".NET Framework 4.7.2 SDK"** and **".NET Framework 4.7.2 targeting pack"** Steps to build: - build.cmd vs -- build the Visual F# IDE Tools in Release configuration (see below) - build.cmd vs debug -- build the Visual F# IDE Tools in Debug configuration (see below) - build.cmd vs test -- build Visual F# IDE Tools, run all tests (see below) + Build.cmd -- build all F# components under the default configuration (Debug) + Build.cmd -configuration Release -- build all F# components as Release + Build.cmd -testDesktop -- build and test all net46 tests + +All test options: + + -testDesktop -- test all net46 target frameworks + -testCoreClr -- test all netstandard and netcoreapp target frameworks + -testFSharpQA -- test all F# Cambridge tests + -testVs -- test all VS integration points + -testFcs -- test F# compiler service components + -testAll -- all of the above Use ``VisualFSharp.sln`` if you're building the Visual F# IDE Tools. diff --git a/FSharp.Directory.Build.props b/Directory.Build.props similarity index 100% rename from FSharp.Directory.Build.props rename to Directory.Build.props diff --git a/FSharp.Directory.Build.targets b/Directory.Build.targets similarity index 99% rename from FSharp.Directory.Build.targets rename to Directory.Build.targets index 84125426d58..08da3ab0966 100644 --- a/FSharp.Directory.Build.targets +++ b/Directory.Build.targets @@ -1,7 +1,5 @@ - - diff --git a/DotnetCLIToolsVersion.txt b/DotnetCLIToolsVersion.txt deleted file mode 100644 index 38295b0d98d..00000000000 --- a/DotnetCLIToolsVersion.txt +++ /dev/null @@ -1 +0,0 @@ -2.1.504 \ No newline at end of file diff --git a/FSharp.sln b/FSharp.sln index 923255dd35b..115e9a219c9 100644 --- a/FSharp.sln +++ b/FSharp.sln @@ -3,35 +3,28 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26403.7 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.Private", "src\fsharp\FSharp.Compiler.Private\FSharp.Compiler.Private.fsproj", "{2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Private", "src\fsharp\FSharp.Compiler.Private\FSharp.Compiler.Private.fsproj", "{2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.Server.Shared", "src\fsharp\FSharp.Compiler.Server.Shared\FSharp.Compiler.Server.Shared.fsproj", "{D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}" -EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Core", "src\fsharp\FSharp.Core\FSharp.Core.fsproj", "{DED3BBD7-53F4-428A-8C9F-27968E768605}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Core", "src\fsharp\FSharp.Core\FSharp.Core.fsproj", "{DED3BBD7-53F4-428A-8C9F-27968E768605}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{CFE3259A-2D30-4EB0-80D5-E8B5F3D01449}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Build", "src\fsharp\FSharp.Build\FSharp.Build.fsproj", "{702A7979-BCF9-4C41-853E-3ADFC9897890}" -EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Fsc", "src\fsharp\Fsc\Fsc.fsproj", "{C94C257C-3C0A-4858-B5D8-D746498D1F08}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Build", "src\fsharp\FSharp.Build\FSharp.Build.fsproj", "{702A7979-BCF9-4C41-853E-3ADFC9897890}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.Interactive.Settings", "src\fsharp\FSharp.Compiler.Interactive.Settings\FSharp.Compiler.Interactive.Settings.fsproj", "{649FA588-F02E-457C-9FCF-87E46407481E}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsc", "src\fsharp\fsc\fsc.fsproj", "{C94C257C-3C0A-4858-B5D8-D746498D1F08}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FsiAnyCPU", "src\fsharp\fsiAnyCpu\FsiAnyCPU.fsproj", "{8B3E283D-B5FE-4055-9D80-7E3A32F3967B}" - ProjectSection(ProjectDependencies) = postProject - {649FA588-F02E-457C-9FCF-87E46407481E} = {649FA588-F02E-457C-9FCF-87E46407481E} - EndProjectSection +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Interactive.Settings", "src\fsharp\FSharp.Compiler.Interactive.Settings\FSharp.Compiler.Interactive.Settings.fsproj", "{649FA588-F02E-457C-9FCF-87E46407481E}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Fsi", "src\fsharp\fsi\Fsi.fsproj", "{D0E98C0D-490B-4C61-9329-0862F6E87645}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsi", "src\fsharp\fsi\fsi.fsproj", "{D0E98C0D-490B-4C61-9329-0862F6E87645}" ProjectSection(ProjectDependencies) = postProject {649FA588-F02E-457C-9FCF-87E46407481E} = {649FA588-F02E-457C-9FCF-87E46407481E} EndProjectSection EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Tests.FSharpSuite", "tests\fsharp\FSharp.Tests.FSharpSuite.fsproj", "{C163E892-5BF7-4B59-AA99-B0E8079C67C4}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharpSuite.Tests", "tests\fsharp\FSharpSuite.Tests.fsproj", "{C163E892-5BF7-4B59-AA99-B0E8079C67C4}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.UnitTests", "tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj", "{A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.UnitTests", "tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj", "{A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Core.UnitTests", "tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj", "{88E2D422-6852-46E3-A740-83E391DC7973}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Core.UnitTests", "tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj", "{88E2D422-6852-46E3-A740-83E391DC7973}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Compiler", "Compiler", "{3881429D-A97A-49EB-B7AE-A82BA5FE9C77}" EndProject @@ -39,7 +32,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{B8DDA694 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{3058BC79-8E79-4645-B05D-48CC182FA8A6}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "fsharpqafiles", "tests\fsharpqa\fsharpqafiles.csproj", "{AAAAD274-696A-49EC-AAAA-F870BE91AAAA}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Build.UnitTests", "tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj", "{53C0DAAD-158C-4658-8EC7-D7341530239F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -55,34 +48,22 @@ Global {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Debug|x86.ActiveCfg = Debug|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Debug|x86.Build.0 = Debug|Any CPU - {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|Any CPU.Build.0 = Proto|Any CPU - {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|x86.ActiveCfg = Proto|Any CPU - {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|x86.Build.0 = Proto|Any CPU + {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|Any CPU.Build.0 = Release|Any CPU + {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|x86.ActiveCfg = Release|Any CPU + {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|x86.Build.0 = Release|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Release|Any CPU.Build.0 = Release|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Release|x86.ActiveCfg = Release|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Release|x86.Build.0 = Release|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|x86.ActiveCfg = Debug|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|x86.Build.0 = Debug|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Proto|Any CPU.Build.0 = Proto|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Proto|x86.ActiveCfg = Proto|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Proto|x86.Build.0 = Proto|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Release|Any CPU.Build.0 = Release|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Release|x86.ActiveCfg = Release|Any CPU - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Release|x86.Build.0 = Release|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Debug|Any CPU.Build.0 = Debug|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Debug|x86.ActiveCfg = Debug|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Debug|x86.Build.0 = Debug|Any CPU - {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|Any CPU.Build.0 = Proto|Any CPU - {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|x86.ActiveCfg = Proto|Any CPU - {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|x86.Build.0 = Proto|Any CPU + {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|Any CPU.Build.0 = Release|Any CPU + {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|x86.ActiveCfg = Release|Any CPU + {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|x86.Build.0 = Release|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Release|Any CPU.ActiveCfg = Release|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Release|Any CPU.Build.0 = Release|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Release|x86.ActiveCfg = Release|Any CPU @@ -91,10 +72,10 @@ Global {702A7979-BCF9-4C41-853E-3ADFC9897890}.Debug|Any CPU.Build.0 = Debug|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Debug|x86.ActiveCfg = Debug|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Debug|x86.Build.0 = Debug|Any CPU - {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|Any CPU.Build.0 = Proto|Any CPU - {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|x86.ActiveCfg = Proto|Any CPU - {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|x86.Build.0 = Proto|Any CPU + {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|Any CPU.Build.0 = Release|Any CPU + {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|x86.ActiveCfg = Release|Any CPU + {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|x86.Build.0 = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|Any CPU.ActiveCfg = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|Any CPU.Build.0 = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|x86.ActiveCfg = Release|Any CPU @@ -103,10 +84,10 @@ Global {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|Any CPU.Build.0 = Debug|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|x86.ActiveCfg = Debug|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|x86.Build.0 = Debug|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.Build.0 = Proto|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.ActiveCfg = Proto|Any CPU - {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.Build.0 = Proto|Any CPU + {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.Build.0 = Release|Any CPU + {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.ActiveCfg = Release|Any CPU + {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.Build.0 = Release|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|Any CPU.ActiveCfg = Release|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|Any CPU.Build.0 = Release|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|x86.ActiveCfg = Release|Any CPU @@ -115,34 +96,22 @@ Global {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|Any CPU.Build.0 = Debug|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|x86.ActiveCfg = Debug|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|x86.Build.0 = Debug|Any CPU - {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|Any CPU.Build.0 = Proto|Any CPU - {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|x86.ActiveCfg = Proto|Any CPU - {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|x86.Build.0 = Proto|Any CPU + {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|Any CPU.Build.0 = Release|Any CPU + {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|x86.ActiveCfg = Release|Any CPU + {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|x86.Build.0 = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|Any CPU.ActiveCfg = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|Any CPU.Build.0 = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|x86.ActiveCfg = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|x86.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|x86.ActiveCfg = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|x86.Build.0 = Debug|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|Any CPU.Build.0 = Proto|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|x86.ActiveCfg = Proto|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|x86.Build.0 = Proto|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|Any CPU.Build.0 = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|x86.ActiveCfg = Release|Any CPU - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|x86.Build.0 = Release|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|Any CPU.Build.0 = Debug|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|x86.ActiveCfg = Debug|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|x86.Build.0 = Debug|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.Build.0 = Proto|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.ActiveCfg = Proto|Any CPU - {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.Build.0 = Proto|Any CPU + {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.Build.0 = Release|Any CPU + {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.ActiveCfg = Release|Any CPU + {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.Build.0 = Release|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|Any CPU.ActiveCfg = Release|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|Any CPU.Build.0 = Release|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|x86.ActiveCfg = Release|Any CPU @@ -151,10 +120,10 @@ Global {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Debug|Any CPU.Build.0 = Debug|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Debug|x86.ActiveCfg = Debug|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Debug|x86.Build.0 = Debug|Any CPU - {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|Any CPU.Build.0 = Proto|Any CPU - {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|x86.ActiveCfg = Proto|Any CPU - {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|x86.Build.0 = Proto|Any CPU + {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|Any CPU.Build.0 = Release|Any CPU + {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|x86.ActiveCfg = Release|Any CPU + {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|x86.Build.0 = Release|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Release|Any CPU.ActiveCfg = Release|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Release|Any CPU.Build.0 = Release|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Release|x86.ActiveCfg = Release|Any CPU @@ -163,10 +132,10 @@ Global {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Debug|Any CPU.Build.0 = Debug|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Debug|x86.ActiveCfg = Debug|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Debug|x86.Build.0 = Debug|Any CPU - {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|Any CPU.Build.0 = Proto|Any CPU - {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|x86.ActiveCfg = Proto|Any CPU - {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|x86.Build.0 = Proto|Any CPU + {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|Any CPU.Build.0 = Release|Any CPU + {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|x86.ActiveCfg = Release|Any CPU + {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|x86.Build.0 = Release|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Release|Any CPU.ActiveCfg = Release|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Release|Any CPU.Build.0 = Release|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Release|x86.ActiveCfg = Release|Any CPU @@ -175,42 +144,41 @@ Global {88E2D422-6852-46E3-A740-83E391DC7973}.Debug|Any CPU.Build.0 = Debug|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Debug|x86.ActiveCfg = Debug|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Debug|x86.Build.0 = Debug|Any CPU - {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|Any CPU.ActiveCfg = Proto|Any CPU - {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|Any CPU.Build.0 = Proto|Any CPU - {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|x86.ActiveCfg = Proto|Any CPU - {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|x86.Build.0 = Proto|Any CPU + {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|Any CPU.Build.0 = Release|Any CPU + {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|x86.ActiveCfg = Release|Any CPU + {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|x86.Build.0 = Release|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Release|Any CPU.ActiveCfg = Release|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Release|Any CPU.Build.0 = Release|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Release|x86.ActiveCfg = Release|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Release|x86.Build.0 = Release|Any CPU - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Debug|Any CPU.ActiveCfg = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Debug|x86.ActiveCfg = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Debug|x86.Build.0 = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Proto|Any CPU.ActiveCfg = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Proto|Any CPU.Build.0 = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Proto|x86.ActiveCfg = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Proto|x86.Build.0 = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Release|Any CPU.ActiveCfg = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Release|Any CPU.Build.0 = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Release|x86.ActiveCfg = Debug|x86 - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA}.Release|x86.Build.0 = Debug|x86 + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Debug|x86.ActiveCfg = Debug|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Debug|x86.Build.0 = Debug|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Proto|Any CPU.Build.0 = Release|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Proto|x86.ActiveCfg = Release|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Proto|x86.Build.0 = Release|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Release|Any CPU.Build.0 = Release|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Release|x86.ActiveCfg = Release|Any CPU + {53C0DAAD-158C-4658-8EC7-D7341530239F}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3} = {3881429D-A97A-49EB-B7AE-A82BA5FE9C77} - {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06} = {B8DDA694-7939-42E3-95E5-265C2217C142} {DED3BBD7-53F4-428A-8C9F-27968E768605} = {3058BC79-8E79-4645-B05D-48CC182FA8A6} {702A7979-BCF9-4C41-853E-3ADFC9897890} = {B8DDA694-7939-42E3-95E5-265C2217C142} {C94C257C-3C0A-4858-B5D8-D746498D1F08} = {3881429D-A97A-49EB-B7AE-A82BA5FE9C77} {649FA588-F02E-457C-9FCF-87E46407481E} = {B8DDA694-7939-42E3-95E5-265C2217C142} - {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} = {B8DDA694-7939-42E3-95E5-265C2217C142} {D0E98C0D-490B-4C61-9329-0862F6E87645} = {B8DDA694-7939-42E3-95E5-265C2217C142} {C163E892-5BF7-4B59-AA99-B0E8079C67C4} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {88E2D422-6852-46E3-A740-83E391DC7973} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} - {AAAAD274-696A-49EC-AAAA-F870BE91AAAA} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} + {53C0DAAD-158C-4658-8EC7-D7341530239F} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {BD5177C7-1380-40E7-94D2-7768E1A8B1B8} diff --git a/FSharpBuild.Directory.Build.props b/FSharpBuild.Directory.Build.props index fcbe5205d0b..c38700df06c 100644 --- a/FSharpBuild.Directory.Build.props +++ b/FSharpBuild.Directory.Build.props @@ -1,25 +1,14 @@ - - - - + + - Debug - $(MSBuildThisFileDirectory) $(RepoRoot)src - $(RepoRoot)artifacts - $(ArtifactsDir)\toolset - $(ArtifactsDir)\bin - $(ArtifactsDir)\obj - $(ArtifactsDir)\packages - $(ArtifactsBinDir)\$(MSBuildProjectName) - $(ArtifactsObjDir)\$(MSBuildProjectName) $(ArtifactsDir)\SymStore - $(ArtifactsBinDir)\fsc\Proto\net46 - $(ArtifactsBinDir)/fsc/Proto/netcoreapp2.1 + $(ArtifactsDir)\Bootstrap + $(ArtifactsDir)/fsc/Proto/netcoreapp2.1 4.4.0 1182;0025;$(WarningsAsErrors) @@ -62,13 +51,8 @@ - false - true - $(FSharpSourcesRoot)\fsharp\msft.pubkey - true - true + Microsoft - $(FSharpSourcesRoot)\fsharp\test.snk false @@ -83,6 +67,8 @@ + $(NoWarn);FS2003 + true portable fs false diff --git a/FSharpBuild.Directory.Build.targets b/FSharpBuild.Directory.Build.targets index fa39d7498fd..4c700d1ac22 100644 --- a/FSharpBuild.Directory.Build.targets +++ b/FSharpBuild.Directory.Build.targets @@ -1,5 +1,7 @@ + + @@ -13,6 +15,7 @@ during `net46`, but for purposes of restore needs to be present. --> $(AssetTargetFallback);net462 + $(NoWarn);NU1605;NU1701 @@ -34,9 +37,4 @@ - - - - - diff --git a/FSharpTests.Directory.Build.props b/FSharpTests.Directory.Build.props index a0481c8b4a0..6c298fe4426 100644 --- a/FSharpTests.Directory.Build.props +++ b/FSharpTests.Directory.Build.props @@ -19,12 +19,12 @@ true - $(MSBuildThisFileDirectory)artifacts\toolset\dotnet + $([System.IO.Path]::GetDirectoryName('$(DOTNET_HOST_PATH)')) dotnet.exe dotnet $(MSBuildThisFileDirectory)artifacts\bin\fsc\$(Configuration)\netcoreapp2.1\fsc.exe - $(MSBuildThisFileDirectory)artifacts\toolset\dotnet + $([System.IO.Path]::GetDirectoryName('$(DOTNET_HOST_PATH)')) dotnet.exe dotnet $(MSBuildThisFileDirectory)artifacts\bin\fsi\$(Configuration)\netcoreapp2.1\fsi.exe diff --git a/NuGet.Config b/NuGet.config similarity index 100% rename from NuGet.Config rename to NuGet.config diff --git a/PublishToBlob.proj b/PublishToBlob.proj deleted file mode 100644 index 21e8ec6eb6f..00000000000 --- a/PublishToBlob.proj +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - Microsoft.DotNet.Build.Tasks.Feed - - 2.2.0-beta.19066.1 - - - - - - - - - - - $(MSBuildThisFileDirectory)artifacts\log\$(Configuration)\ - AnyCPU - $(Platform) - $(ArtifactsLogDir)AssetManifest\$(OS)-$(PlatformName).xml - - - - - - - diff --git a/Restore.cmd b/Restore.cmd new file mode 100644 index 00000000000..1b84815f3ed --- /dev/null +++ b/Restore.cmd @@ -0,0 +1,2 @@ +@echo off +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0eng\build.ps1""" -restore %*" diff --git a/Test.cmd b/Test.cmd new file mode 100644 index 00000000000..4a6eabc39e2 --- /dev/null +++ b/Test.cmd @@ -0,0 +1,2 @@ +@echo off +powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0eng\build.ps1""" -test %*" diff --git a/VisualFSharp.sln b/VisualFSharp.sln index ea9bbe592d7..2ac4e75bf61 100644 --- a/VisualFSharp.sln +++ b/VisualFSharp.sln @@ -3,98 +3,98 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.28010.2036 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.VS.FSI", "vsintegration\src\FSharp.VS.FSI\FSharp.VS.FSI.fsproj", "{991DCF75-C2EB-42B6-9A0D-AA1D2409D519}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{CFE3259A-2D30-4EB0-80D5-E8B5F3D01449}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.Private", "src\fsharp\FSharp.Compiler.Private\FSharp.Compiler.Private.fsproj", "{2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VisualFSharp.UnitTests Support", "VisualFSharp.UnitTests Support", "{3F044931-FB83-4433-B934-AE66AB27B278}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VisualFSharpFull", "vsintegration\Vsix\VisualFSharpFull\VisualFSharpFull.csproj", "{59ADCE46-9740-4079-834D-9A03A3494EBC}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VisualFSharp", "VisualFSharp", "{4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D}" + ProjectSection(SolutionItems) = preProject + vsintegration\readme.md = vsintegration\readme.md + EndProjectSection EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.Server.Shared", "src\fsharp\FSharp.Compiler.Server.Shared\FSharp.Compiler.Server.Shared.fsproj", "{D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Compiler", "Compiler", "{3881429D-A97A-49EB-B7AE-A82BA5FE9C77}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Core", "src\fsharp\FSharp.Core\FSharp.Core.fsproj", "{DED3BBD7-53F4-428A-8C9F-27968E768605}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F7876C9B-FB6A-4EFB-B058-D6967DB75FB2}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.LanguageService", "vsintegration\src\FSharp.LanguageService\FSharp.LanguageService.fsproj", "{EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{B8DDA694-7939-42E3-95E5-265C2217C142}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FSharp.LanguageService.Base", "vsintegration\src\FSharp.LanguageService.Base\FSharp.LanguageService.Base.csproj", "{1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{3058BC79-8E79-4645-B05D-48CC182FA8A6}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Editor", "vsintegration\src\FSharp.Editor\FSharp.Editor.fsproj", "{65E0E82A-EACE-4787-8994-888674C2FE87}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ItemTemplates", "ItemTemplates", "{F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectSystem.Base", "vsintegration\src\FSharp.ProjectSystem.Base\Project\ProjectSystem.Base.csproj", "{B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Utils", "Utils", "{D086C8C6-D00D-4C3B-9AB2-A4286C9F5922}" EndProject -Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "FSharp.PropertiesPages", "vsintegration\src\FSharp.ProjectSystem.PropertyPages\FSharp.PropertiesPages.vbproj", "{FCFB214C-462E-42B3-91CA-FC557EFEE74F}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "FSharp.Compiler.Service.tests Support", "FSharp.Compiler.Service.tests Support", "{35636A82-401A-4C3A-B2AB-EB7DC5E9C268}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "ProjectSystem", "vsintegration\src\FSharp.ProjectSystem.FSharp\ProjectSystem.fsproj", "{6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Legacy", "Legacy", "{CCAB6E50-34C6-42AF-A6B0-567C29FCD91B}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ProjectTemplates", "ProjectTemplates", "{C9B1D3F5-4971-4F04-9C26-37E3AC809AB4}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.VS.FSI", "vsintegration\src\FSharp.VS.FSI\FSharp.VS.FSI.fsproj", "{991DCF75-C2EB-42B6-9A0D-AA1D2409D519}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{CFE3259A-2D30-4EB0-80D5-E8B5F3D01449}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Private", "src\fsharp\FSharp.Compiler.Private\FSharp.Compiler.Private.fsproj", "{2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "VisualFSharp.Salsa", "vsintegration\tests\Salsa\VisualFSharp.Salsa.fsproj", "{FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VisualFSharpFull", "vsintegration\Vsix\VisualFSharpFull\VisualFSharpFull.csproj", "{59ADCE46-9740-4079-834D-9A03A3494EBC}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "VisualFSharp.UnitTests", "vsintegration\tests\UnitTests\VisualFSharp.UnitTests.fsproj", "{EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VisualFSharpTemplates", "vsintegration\Vsix\VisualFSharpTemplates\VisualFSharpTemplates.csproj", "{025CE01B-98F3-4C3C-B486-2C0BD038D011}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DefinitionLocationAttribute", "vsintegration\tests\MockTypeProviders\DefinitionLocationAttribute\DefinitionLocationAttribute.csproj", "{DA39AD38-4A58-47BF-9215-E49768295169}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Server.Shared", "src\fsharp\FSharp.Compiler.Server.Shared\FSharp.Compiler.Server.Shared.fsproj", "{D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DefinitionLocationAttributeFileDoesnotExist", "vsintegration\tests\MockTypeProviders\DefinitionLocationAttributeFileDoesnotExist\DefinitionLocationAttributeFileDoesnotExist.csproj", "{8C2439BD-0E49-4929-A8B1-29CEE228191E}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Core", "src\fsharp\FSharp.Core\FSharp.Core.fsproj", "{DED3BBD7-53F4-428A-8C9F-27968E768605}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DefinitionLocationAttributeLineDoesnotExist", "vsintegration\tests\MockTypeProviders\DefinitionLocationAttributeLineDoesnotExist\DefinitionLocationAttributeLineDoesnotExist.csproj", "{F47196DC-186D-4055-BAF2-658282A12F33}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.LanguageService", "vsintegration\src\FSharp.LanguageService\FSharp.LanguageService.fsproj", "{EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DefinitionLocationAttributeWithSpaceInTheType", "vsintegration\tests\MockTypeProviders\DefinitionLocationAttributeWithSpaceInTheType\DefinitionLocationAttributeWithSpaceInTheType.csproj", "{D4C88934-5893-467E-A55C-A11ECD6479FE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FSharp.LanguageService.Base", "vsintegration\src\FSharp.LanguageService.Base\FSharp.LanguageService.Base.csproj", "{1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "DummyProviderForLanguageServiceTesting", "vsintegration\tests\MockTypeProviders\DummyProviderForLanguageServiceTesting\DummyProviderForLanguageServiceTesting.fsproj", "{6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Editor", "vsintegration\src\FSharp.Editor\FSharp.Editor.fsproj", "{65E0E82A-EACE-4787-8994-888674C2FE87}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EditorHideMethodsAttribute", "vsintegration\tests\MockTypeProviders\EditorHideMethodsAttribute\EditorHideMethodsAttribute.csproj", "{0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectSystem.Base", "vsintegration\src\FSharp.ProjectSystem.Base\Project\ProjectSystem.Base.csproj", "{B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "EmptyAssembly", "vsintegration\tests\MockTypeProviders\EmptyAssembly\EmptyAssembly.fsproj", "{004982C6-93EA-4E70-B4F0-BE7D7219926A}" +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "FSharp.PropertiesPages", "vsintegration\src\FSharp.ProjectSystem.PropertyPages\FSharp.PropertiesPages.vbproj", "{FCFB214C-462E-42B3-91CA-FC557EFEE74F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XmlDocAttributeWithAdequateComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithAdequateComment\XmlDocAttributeWithAdequateComment.csproj", "{243A81AC-A954-4601-833A-60EEEFB00FCD}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "ProjectSystem", "vsintegration\src\FSharp.ProjectSystem.FSharp\ProjectSystem.fsproj", "{6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XmlDocAttributeWithEmptyComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithEmptyComment\XmlDocAttributeWithEmptyComment.csproj", "{B4595EB6-053A-400E-AA1B-7727F1BC900F}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "VisualFSharp.Salsa", "vsintegration\tests\Salsa\VisualFSharp.Salsa.fsproj", "{FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XmlDocAttributeWithLocalizedComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithLocalizedComment\XmlDocAttributeWithLocalizedComment.csproj", "{A559D7E8-7EFD-473A-B618-A10B41AB523B}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "VisualFSharp.UnitTests", "vsintegration\tests\UnitTests\VisualFSharp.UnitTests.fsproj", "{EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XmlDocAttributeWithLongComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithLongComment\XmlDocAttributeWithLongComment.csproj", "{AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DefinitionLocationAttribute", "vsintegration\tests\MockTypeProviders\DefinitionLocationAttribute\DefinitionLocationAttribute.csproj", "{DA39AD38-4A58-47BF-9215-E49768295169}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XmlDocAttributeWithNullComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithNullComment\XmlDocAttributeWithNullComment.csproj", "{956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DefinitionLocationAttributeFileDoesnotExist", "vsintegration\tests\MockTypeProviders\DefinitionLocationAttributeFileDoesnotExist\DefinitionLocationAttributeFileDoesnotExist.csproj", "{8C2439BD-0E49-4929-A8B1-29CEE228191E}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Build", "src\fsharp\FSharp.Build\FSharp.Build.fsproj", "{702A7979-BCF9-4C41-853E-3ADFC9897890}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DefinitionLocationAttributeLineDoesnotExist", "vsintegration\tests\MockTypeProviders\DefinitionLocationAttributeLineDoesnotExist\DefinitionLocationAttributeLineDoesnotExist.csproj", "{F47196DC-186D-4055-BAF2-658282A12F33}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Fsc", "src\fsharp\Fsc\Fsc.fsproj", "{C94C257C-3C0A-4858-B5D8-D746498D1F08}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DefinitionLocationAttributeWithSpaceInTheType", "vsintegration\tests\MockTypeProviders\DefinitionLocationAttributeWithSpaceInTheType\DefinitionLocationAttributeWithSpaceInTheType.csproj", "{D4C88934-5893-467E-A55C-A11ECD6479FE}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.Interactive.Settings", "src\fsharp\FSharp.Compiler.Interactive.Settings\FSharp.Compiler.Interactive.Settings.fsproj", "{649FA588-F02E-457C-9FCF-87E46407481E}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "DummyProviderForLanguageServiceTesting", "vsintegration\tests\MockTypeProviders\DummyProviderForLanguageServiceTesting\DummyProviderForLanguageServiceTesting.fsproj", "{6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FsiAnyCPU", "src\fsharp\fsiAnyCpu\FsiAnyCPU.fsproj", "{8B3E283D-B5FE-4055-9D80-7E3A32F3967B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EditorHideMethodsAttribute", "vsintegration\tests\MockTypeProviders\EditorHideMethodsAttribute\EditorHideMethodsAttribute.csproj", "{0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "Fsi", "src\fsharp\fsi\Fsi.fsproj", "{D0E98C0D-490B-4C61-9329-0862F6E87645}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "EmptyAssembly", "vsintegration\tests\MockTypeProviders\EmptyAssembly\EmptyAssembly.fsproj", "{004982C6-93EA-4E70-B4F0-BE7D7219926A}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Tests.FSharpSuite", "tests\fsharp\FSharp.Tests.FSharpSuite.fsproj", "{C163E892-5BF7-4B59-AA99-B0E8079C67C4}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XmlDocAttributeWithAdequateComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithAdequateComment\XmlDocAttributeWithAdequateComment.csproj", "{243A81AC-A954-4601-833A-60EEEFB00FCD}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VisualFSharp.UnitTests Support", "VisualFSharp.UnitTests Support", "{3F044931-FB83-4433-B934-AE66AB27B278}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XmlDocAttributeWithEmptyComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithEmptyComment\XmlDocAttributeWithEmptyComment.csproj", "{B4595EB6-053A-400E-AA1B-7727F1BC900F}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Compiler.UnitTests", "tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj", "{A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XmlDocAttributeWithLocalizedComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithLocalizedComment\XmlDocAttributeWithLocalizedComment.csproj", "{A559D7E8-7EFD-473A-B618-A10B41AB523B}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Core.UnitTests", "tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj", "{88E2D422-6852-46E3-A740-83E391DC7973}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XmlDocAttributeWithLongComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithLongComment\XmlDocAttributeWithLongComment.csproj", "{AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VisualFSharp", "VisualFSharp", "{4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D}" - ProjectSection(SolutionItems) = preProject - vsintegration\readme.md = vsintegration\readme.md - EndProjectSection +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XmlDocAttributeWithNullComment", "vsintegration\tests\MockTypeProviders\XmlDocAttributeWithNullComment\XmlDocAttributeWithNullComment.csproj", "{956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Compiler", "Compiler", "{3881429D-A97A-49EB-B7AE-A82BA5FE9C77}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Build", "src\fsharp\FSharp.Build\FSharp.Build.fsproj", "{702A7979-BCF9-4C41-853E-3ADFC9897890}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F7876C9B-FB6A-4EFB-B058-D6967DB75FB2}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsc", "src\fsharp\fsc\fsc.fsproj", "{C94C257C-3C0A-4858-B5D8-D746498D1F08}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tools", "Tools", "{B8DDA694-7939-42E3-95E5-265C2217C142}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.Interactive.Settings", "src\fsharp\FSharp.Compiler.Interactive.Settings\FSharp.Compiler.Interactive.Settings.fsproj", "{649FA588-F02E-457C-9FCF-87E46407481E}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{3058BC79-8E79-4645-B05D-48CC182FA8A6}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsiAnyCpu", "src\fsharp\fsiAnyCpu\fsiAnyCpu.fsproj", "{8B3E283D-B5FE-4055-9D80-7E3A32F3967B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleProject", "vsintegration\ProjectTemplates\ConsoleProject\ConsoleProject.csproj", "{604F0DAA-2D33-48DD-B162-EDF0B672803D}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fsi", "src\fsharp\fsi\fsi.fsproj", "{D0E98C0D-490B-4C61-9329-0862F6E87645}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibraryProject", "vsintegration\ProjectTemplates\LibraryProject\LibraryProject.csproj", "{01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharpSuite.Tests", "tests\fsharp\FSharpSuite.Tests.fsproj", "{C163E892-5BF7-4B59-AA99-B0E8079C67C4}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TutorialProject", "vsintegration\ProjectTemplates\TutorialProject\TutorialProject.csproj", "{2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Compiler.UnitTests", "tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj", "{A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ItemTemplates", "ItemTemplates", "{F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Core.UnitTests", "tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj", "{88E2D422-6852-46E3-A740-83E391DC7973}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AppConfig", "vsintegration\ItemTemplates\AppConfig\AppConfig.csproj", "{6BA13AA4-C25F-480F-856B-8E8000299A72}" EndProject @@ -108,38 +108,56 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TextFile", "vsintegration\I EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XMLFile", "vsintegration\ItemTemplates\XMLFile\XMLFile.csproj", "{1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "HostedCompilerServer", "tests\fsharpqa\testenv\src\HostedCompilerServer\HostedCompilerServer.fsproj", "{4239EFEA-E746-446A-BF7A-51FCBAB13946}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "HostedCompilerServer", "tests\fsharpqa\testenv\src\HostedCompilerServer\HostedCompilerServer.fsproj", "{4239EFEA-E746-446A-BF7A-51FCBAB13946}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "ILComparer", "tests\fsharpqa\testenv\src\ILComparer\ILComparer.fsproj", "{2E60864A-E3FF-4BCC-810F-DC7C34E6B236}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Utils", "Utils", "{D086C8C6-D00D-4C3B-9AB2-A4286C9F5922}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "ILComparer", "tests\fsharpqa\testenv\src\ILComparer\ILComparer.fsproj", "{2E60864A-E3FF-4BCC-810F-DC7C34E6B236}" EndProject Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "LanguageServiceProfiling", "vsintegration\Utils\LanguageServiceProfiling\LanguageServiceProfiling.fsproj", "{E7FA3A71-51AF-4FCA-9C2F-7C853E515903}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FSharp.UIResources", "vsintegration\src\FSharp.UIResources\FSharp.UIResources.csproj", "{C4586A06-1402-48BC-8E35-A1B8642F895B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharp_Analysis", "tests\service\data\CSharp_Analysis\CSharp_Analysis.csproj", "{887630A3-4B1D-40EA-B8B3-2D842E9C40DB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharp_Analysis", "tests\service\data\CSharp_Analysis\CSharp_Analysis.csproj", "{887630A3-4B1D-40EA-B8B3-2D842E9C40DB}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "FSharp.Compiler.Service.tests Support", "FSharp.Compiler.Service.tests Support", "{35636A82-401A-4C3A-B2AB-EB7DC5E9C268}" -EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "TestTP", "tests\service\data\TestTP\TestTP.fsproj", "{FF76BD3C-5E0A-4752-B6C3-044F6E15719B}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "TestTP", "tests\service\data\TestTP\TestTP.fsproj", "{FF76BD3C-5E0A-4752-B6C3-044F6E15719B}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResourceFile", "vsintegration\ItemTemplates\ResourceFile\ResourceFile.csproj", "{0385564F-07B4-4264-AB8A-17C393E9140C}" EndProject -Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "FSharp.Build.UnitTests", "tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj", "{400FAB03-786E-40CC-85A8-04B0C2869B14}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "FSharp.Build.UnitTests", "tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj", "{400FAB03-786E-40CC-85A8-04B0C2869B14}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PEVerify", "tests\fsharpqa\testenv\src\PEVerify\PEVerify.csproj", "{B0689A4E-07D8-494D-A0C8-791CB1D74E54}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FSharp.PatternMatcher", "vsintegration\src\FSharp.PatternMatcher\FSharp.PatternMatcher.csproj", "{18227628-DF90-4C47-AF3D-CC72D2EDD986}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Legacy", "Legacy", "{CCAB6E50-34C6-42AF-A6B0-567C29FCD91B}" +Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "GetTypesVS.UnitTests", "vsintegration\tests\GetTypesVS.UnitTests\GetTypesVS.UnitTests.fsproj", "{6D93CEBD-4540-4D96-A153-B440A661FD09}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Setup", "Setup", "{6235B3AF-774D-4EA1-8F37-789E767F6368}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.FSharp.Compiler.MSBuild", "setup\Swix\Microsoft.FSharp.Compiler.MSBuild\Microsoft.FSharp.Compiler.MSBuild.csproj", "{4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.FSharp.Dependencies", "setup\Swix\Microsoft.FSharp.Dependencies\Microsoft.FSharp.Dependencies.csproj", "{6BCFED7A-3F67-4180-B307-C7D69D191D8C}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.FSharp.IDE", "setup\Swix\Microsoft.FSharp.IDE\Microsoft.FSharp.IDE.csproj", "{E93E7D28-1C6B-4E04-BE83-68428CF7E039}" EndProject -Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "GetTypesVSUnitTests", "vsintegration\tests\GetTypesVSUnitTests\GetTypesVSUnitTests.fsproj", "{6D93CEBD-4540-4D96-A153-B440A661FD09}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.FSharp.SDK", "setup\Swix\Microsoft.FSharp.SDK\Microsoft.FSharp.SDK.csproj", "{9482211E-23D0-4BD0-9893-E4AA5559F67A}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NuGet", "NuGet", "{647810D0-5307-448F-99A2-E83917010DAE}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.FSharp.Compiler", "src\fsharp\FSharp.Compiler.nuget\Microsoft.FSharp.Compiler.csproj", "{04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ProjectTemplates", "ProjectTemplates", "{BED74F9E-A0D2-48E2-9EE7-449832100487}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleProject", "vsintegration\ProjectTemplates\ConsoleProject\ConsoleProject.csproj", "{1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibraryProject", "vsintegration\ProjectTemplates\LibraryProject\LibraryProject.csproj", "{C32806E0-71C2-40E4-AEC4-517F73F6A18A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TutorialProject", "vsintegration\ProjectTemplates\TutorialProject\TutorialProject.csproj", "{7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x86 = Debug|x86 + Proto|Any CPU = Proto|Any CPU + Proto|x86 = Proto|x86 Release|Any CPU = Release|Any CPU Release|x86 = Release|x86 EndGlobalSection @@ -148,6 +166,10 @@ Global {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Debug|Any CPU.Build.0 = Debug|Any CPU {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Debug|x86.ActiveCfg = Debug|Any CPU {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Debug|x86.Build.0 = Debug|Any CPU + {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Proto|Any CPU.Build.0 = Release|Any CPU + {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Proto|x86.ActiveCfg = Release|Any CPU + {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Proto|x86.Build.0 = Release|Any CPU {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Release|Any CPU.ActiveCfg = Release|Any CPU {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Release|Any CPU.Build.0 = Release|Any CPU {991DCF75-C2EB-42B6-9A0D-AA1D2409D519}.Release|x86.ActiveCfg = Release|Any CPU @@ -156,6 +178,10 @@ Global {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Debug|Any CPU.Build.0 = Debug|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Debug|x86.ActiveCfg = Debug|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Debug|x86.Build.0 = Debug|Any CPU + {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|Any CPU.Build.0 = Release|Any CPU + {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|x86.ActiveCfg = Release|Any CPU + {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Proto|x86.Build.0 = Release|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Release|Any CPU.Build.0 = Release|Any CPU {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3}.Release|x86.ActiveCfg = Release|Any CPU @@ -164,6 +190,10 @@ Global {59ADCE46-9740-4079-834D-9A03A3494EBC}.Debug|Any CPU.Build.0 = Debug|Any CPU {59ADCE46-9740-4079-834D-9A03A3494EBC}.Debug|x86.ActiveCfg = Debug|Any CPU {59ADCE46-9740-4079-834D-9A03A3494EBC}.Debug|x86.Build.0 = Debug|Any CPU + {59ADCE46-9740-4079-834D-9A03A3494EBC}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {59ADCE46-9740-4079-834D-9A03A3494EBC}.Proto|Any CPU.Build.0 = Release|Any CPU + {59ADCE46-9740-4079-834D-9A03A3494EBC}.Proto|x86.ActiveCfg = Release|Any CPU + {59ADCE46-9740-4079-834D-9A03A3494EBC}.Proto|x86.Build.0 = Release|Any CPU {59ADCE46-9740-4079-834D-9A03A3494EBC}.Release|Any CPU.ActiveCfg = Release|Any CPU {59ADCE46-9740-4079-834D-9A03A3494EBC}.Release|Any CPU.Build.0 = Release|Any CPU {59ADCE46-9740-4079-834D-9A03A3494EBC}.Release|x86.ActiveCfg = Release|Any CPU @@ -172,6 +202,10 @@ Global {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|Any CPU.Build.0 = Debug|Any CPU {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|x86.ActiveCfg = Debug|Any CPU {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|x86.Build.0 = Debug|Any CPU + {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Proto|Any CPU.Build.0 = Release|Any CPU + {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Proto|x86.ActiveCfg = Release|Any CPU + {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Proto|x86.Build.0 = Release|Any CPU {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Release|Any CPU.ActiveCfg = Release|Any CPU {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Release|Any CPU.Build.0 = Release|Any CPU {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Release|x86.ActiveCfg = Release|Any CPU @@ -180,6 +214,10 @@ Global {DED3BBD7-53F4-428A-8C9F-27968E768605}.Debug|Any CPU.Build.0 = Debug|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Debug|x86.ActiveCfg = Debug|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Debug|x86.Build.0 = Debug|Any CPU + {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|Any CPU.Build.0 = Release|Any CPU + {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|x86.ActiveCfg = Release|Any CPU + {DED3BBD7-53F4-428A-8C9F-27968E768605}.Proto|x86.Build.0 = Release|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Release|Any CPU.ActiveCfg = Release|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Release|Any CPU.Build.0 = Release|Any CPU {DED3BBD7-53F4-428A-8C9F-27968E768605}.Release|x86.ActiveCfg = Release|Any CPU @@ -188,6 +226,10 @@ Global {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Debug|Any CPU.Build.0 = Debug|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Debug|x86.ActiveCfg = Debug|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Debug|x86.Build.0 = Debug|Any CPU + {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Proto|Any CPU.Build.0 = Release|Any CPU + {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Proto|x86.ActiveCfg = Release|Any CPU + {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Proto|x86.Build.0 = Release|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Release|Any CPU.ActiveCfg = Release|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Release|Any CPU.Build.0 = Release|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F}.Release|x86.ActiveCfg = Release|Any CPU @@ -196,6 +238,10 @@ Global {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Debug|Any CPU.Build.0 = Debug|Any CPU {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Debug|x86.ActiveCfg = Debug|Any CPU {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Debug|x86.Build.0 = Debug|Any CPU + {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Proto|Any CPU.Build.0 = Release|Any CPU + {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Proto|x86.ActiveCfg = Release|Any CPU + {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Proto|x86.Build.0 = Release|Any CPU {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Release|Any CPU.ActiveCfg = Release|Any CPU {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Release|Any CPU.Build.0 = Release|Any CPU {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF}.Release|x86.ActiveCfg = Release|Any CPU @@ -204,6 +250,10 @@ Global {65E0E82A-EACE-4787-8994-888674C2FE87}.Debug|Any CPU.Build.0 = Debug|Any CPU {65E0E82A-EACE-4787-8994-888674C2FE87}.Debug|x86.ActiveCfg = Debug|Any CPU {65E0E82A-EACE-4787-8994-888674C2FE87}.Debug|x86.Build.0 = Debug|Any CPU + {65E0E82A-EACE-4787-8994-888674C2FE87}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {65E0E82A-EACE-4787-8994-888674C2FE87}.Proto|Any CPU.Build.0 = Release|Any CPU + {65E0E82A-EACE-4787-8994-888674C2FE87}.Proto|x86.ActiveCfg = Release|Any CPU + {65E0E82A-EACE-4787-8994-888674C2FE87}.Proto|x86.Build.0 = Release|Any CPU {65E0E82A-EACE-4787-8994-888674C2FE87}.Release|Any CPU.ActiveCfg = Release|Any CPU {65E0E82A-EACE-4787-8994-888674C2FE87}.Release|Any CPU.Build.0 = Release|Any CPU {65E0E82A-EACE-4787-8994-888674C2FE87}.Release|x86.ActiveCfg = Release|Any CPU @@ -212,6 +262,10 @@ Global {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Debug|Any CPU.Build.0 = Debug|Any CPU {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Debug|x86.ActiveCfg = Debug|Any CPU {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Debug|x86.Build.0 = Debug|Any CPU + {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Proto|Any CPU.Build.0 = Release|Any CPU + {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Proto|x86.ActiveCfg = Release|Any CPU + {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Proto|x86.Build.0 = Release|Any CPU {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Release|Any CPU.ActiveCfg = Release|Any CPU {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Release|Any CPU.Build.0 = Release|Any CPU {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7}.Release|x86.ActiveCfg = Release|Any CPU @@ -220,6 +274,10 @@ Global {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Debug|Any CPU.Build.0 = Debug|Any CPU {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Debug|x86.ActiveCfg = Debug|Any CPU {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Debug|x86.Build.0 = Debug|Any CPU + {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Proto|Any CPU.Build.0 = Proto|Any CPU + {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Proto|x86.ActiveCfg = Proto|Any CPU + {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Proto|x86.Build.0 = Proto|Any CPU {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Release|Any CPU.ActiveCfg = Release|Any CPU {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Release|Any CPU.Build.0 = Release|Any CPU {FCFB214C-462E-42B3-91CA-FC557EFEE74F}.Release|x86.ActiveCfg = Release|Any CPU @@ -228,6 +286,10 @@ Global {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Debug|Any CPU.Build.0 = Debug|Any CPU {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Debug|x86.ActiveCfg = Debug|Any CPU {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Debug|x86.Build.0 = Debug|Any CPU + {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Proto|Any CPU.Build.0 = Release|Any CPU + {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Proto|x86.ActiveCfg = Release|Any CPU + {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Proto|x86.Build.0 = Release|Any CPU {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Release|Any CPU.ActiveCfg = Release|Any CPU {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Release|Any CPU.Build.0 = Release|Any CPU {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44}.Release|x86.ActiveCfg = Release|Any CPU @@ -236,6 +298,10 @@ Global {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Debug|x86.ActiveCfg = Debug|Any CPU {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Debug|x86.Build.0 = Debug|Any CPU + {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Proto|Any CPU.Build.0 = Release|Any CPU + {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Proto|x86.ActiveCfg = Release|Any CPU + {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Proto|x86.Build.0 = Release|Any CPU {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Release|Any CPU.ActiveCfg = Release|Any CPU {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Release|Any CPU.Build.0 = Release|Any CPU {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7}.Release|x86.ActiveCfg = Release|Any CPU @@ -244,6 +310,10 @@ Global {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Debug|Any CPU.Build.0 = Debug|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Debug|x86.ActiveCfg = Debug|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Debug|x86.Build.0 = Debug|Any CPU + {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Proto|Any CPU.Build.0 = Release|Any CPU + {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Proto|x86.ActiveCfg = Release|Any CPU + {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Proto|x86.Build.0 = Release|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Release|Any CPU.ActiveCfg = Release|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Release|Any CPU.Build.0 = Release|Any CPU {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F}.Release|x86.ActiveCfg = Release|Any CPU @@ -252,6 +322,10 @@ Global {DA39AD38-4A58-47BF-9215-E49768295169}.Debug|Any CPU.Build.0 = Debug|Any CPU {DA39AD38-4A58-47BF-9215-E49768295169}.Debug|x86.ActiveCfg = Debug|Any CPU {DA39AD38-4A58-47BF-9215-E49768295169}.Debug|x86.Build.0 = Debug|Any CPU + {DA39AD38-4A58-47BF-9215-E49768295169}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {DA39AD38-4A58-47BF-9215-E49768295169}.Proto|Any CPU.Build.0 = Release|Any CPU + {DA39AD38-4A58-47BF-9215-E49768295169}.Proto|x86.ActiveCfg = Release|Any CPU + {DA39AD38-4A58-47BF-9215-E49768295169}.Proto|x86.Build.0 = Release|Any CPU {DA39AD38-4A58-47BF-9215-E49768295169}.Release|Any CPU.ActiveCfg = Release|Any CPU {DA39AD38-4A58-47BF-9215-E49768295169}.Release|Any CPU.Build.0 = Release|Any CPU {DA39AD38-4A58-47BF-9215-E49768295169}.Release|x86.ActiveCfg = Release|Any CPU @@ -260,6 +334,10 @@ Global {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Debug|Any CPU.Build.0 = Debug|Any CPU {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Debug|x86.ActiveCfg = Debug|Any CPU {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Debug|x86.Build.0 = Debug|Any CPU + {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Proto|Any CPU.Build.0 = Release|Any CPU + {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Proto|x86.ActiveCfg = Release|Any CPU + {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Proto|x86.Build.0 = Release|Any CPU {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Release|Any CPU.ActiveCfg = Release|Any CPU {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Release|Any CPU.Build.0 = Release|Any CPU {8C2439BD-0E49-4929-A8B1-29CEE228191E}.Release|x86.ActiveCfg = Release|Any CPU @@ -268,6 +346,10 @@ Global {F47196DC-186D-4055-BAF2-658282A12F33}.Debug|Any CPU.Build.0 = Debug|Any CPU {F47196DC-186D-4055-BAF2-658282A12F33}.Debug|x86.ActiveCfg = Debug|Any CPU {F47196DC-186D-4055-BAF2-658282A12F33}.Debug|x86.Build.0 = Debug|Any CPU + {F47196DC-186D-4055-BAF2-658282A12F33}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {F47196DC-186D-4055-BAF2-658282A12F33}.Proto|Any CPU.Build.0 = Release|Any CPU + {F47196DC-186D-4055-BAF2-658282A12F33}.Proto|x86.ActiveCfg = Release|Any CPU + {F47196DC-186D-4055-BAF2-658282A12F33}.Proto|x86.Build.0 = Release|Any CPU {F47196DC-186D-4055-BAF2-658282A12F33}.Release|Any CPU.ActiveCfg = Release|Any CPU {F47196DC-186D-4055-BAF2-658282A12F33}.Release|Any CPU.Build.0 = Release|Any CPU {F47196DC-186D-4055-BAF2-658282A12F33}.Release|x86.ActiveCfg = Release|Any CPU @@ -276,6 +358,10 @@ Global {D4C88934-5893-467E-A55C-A11ECD6479FE}.Debug|Any CPU.Build.0 = Debug|Any CPU {D4C88934-5893-467E-A55C-A11ECD6479FE}.Debug|x86.ActiveCfg = Debug|Any CPU {D4C88934-5893-467E-A55C-A11ECD6479FE}.Debug|x86.Build.0 = Debug|Any CPU + {D4C88934-5893-467E-A55C-A11ECD6479FE}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {D4C88934-5893-467E-A55C-A11ECD6479FE}.Proto|Any CPU.Build.0 = Release|Any CPU + {D4C88934-5893-467E-A55C-A11ECD6479FE}.Proto|x86.ActiveCfg = Release|Any CPU + {D4C88934-5893-467E-A55C-A11ECD6479FE}.Proto|x86.Build.0 = Release|Any CPU {D4C88934-5893-467E-A55C-A11ECD6479FE}.Release|Any CPU.ActiveCfg = Release|Any CPU {D4C88934-5893-467E-A55C-A11ECD6479FE}.Release|Any CPU.Build.0 = Release|Any CPU {D4C88934-5893-467E-A55C-A11ECD6479FE}.Release|x86.ActiveCfg = Release|Any CPU @@ -284,6 +370,10 @@ Global {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Debug|Any CPU.Build.0 = Debug|Any CPU {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Debug|x86.ActiveCfg = Debug|Any CPU {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Debug|x86.Build.0 = Debug|Any CPU + {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Proto|Any CPU.Build.0 = Release|Any CPU + {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Proto|x86.ActiveCfg = Release|Any CPU + {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Proto|x86.Build.0 = Release|Any CPU {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Release|Any CPU.ActiveCfg = Release|Any CPU {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Release|Any CPU.Build.0 = Release|Any CPU {6AFF752D-E991-4A08-9ED2-5BF46B0E0F8B}.Release|x86.ActiveCfg = Release|Any CPU @@ -292,6 +382,10 @@ Global {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Debug|Any CPU.Build.0 = Debug|Any CPU {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Debug|x86.ActiveCfg = Debug|Any CPU {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Debug|x86.Build.0 = Debug|Any CPU + {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Proto|Any CPU.Build.0 = Release|Any CPU + {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Proto|x86.ActiveCfg = Release|Any CPU + {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Proto|x86.Build.0 = Release|Any CPU {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Release|Any CPU.ActiveCfg = Release|Any CPU {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Release|Any CPU.Build.0 = Release|Any CPU {0B9CDEAF-EE8F-45E0-A4E0-34A8ED6DD09E}.Release|x86.ActiveCfg = Release|Any CPU @@ -300,6 +394,10 @@ Global {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Debug|Any CPU.Build.0 = Debug|Any CPU {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Debug|x86.ActiveCfg = Debug|Any CPU {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Debug|x86.Build.0 = Debug|Any CPU + {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Proto|Any CPU.Build.0 = Release|Any CPU + {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Proto|x86.ActiveCfg = Release|Any CPU + {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Proto|x86.Build.0 = Release|Any CPU {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Release|Any CPU.ActiveCfg = Release|Any CPU {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Release|Any CPU.Build.0 = Release|Any CPU {004982C6-93EA-4E70-B4F0-BE7D7219926A}.Release|x86.ActiveCfg = Release|Any CPU @@ -308,6 +406,10 @@ Global {243A81AC-A954-4601-833A-60EEEFB00FCD}.Debug|Any CPU.Build.0 = Debug|Any CPU {243A81AC-A954-4601-833A-60EEEFB00FCD}.Debug|x86.ActiveCfg = Debug|Any CPU {243A81AC-A954-4601-833A-60EEEFB00FCD}.Debug|x86.Build.0 = Debug|Any CPU + {243A81AC-A954-4601-833A-60EEEFB00FCD}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {243A81AC-A954-4601-833A-60EEEFB00FCD}.Proto|Any CPU.Build.0 = Release|Any CPU + {243A81AC-A954-4601-833A-60EEEFB00FCD}.Proto|x86.ActiveCfg = Release|Any CPU + {243A81AC-A954-4601-833A-60EEEFB00FCD}.Proto|x86.Build.0 = Release|Any CPU {243A81AC-A954-4601-833A-60EEEFB00FCD}.Release|Any CPU.ActiveCfg = Release|Any CPU {243A81AC-A954-4601-833A-60EEEFB00FCD}.Release|Any CPU.Build.0 = Release|Any CPU {243A81AC-A954-4601-833A-60EEEFB00FCD}.Release|x86.ActiveCfg = Release|Any CPU @@ -316,6 +418,10 @@ Global {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Debug|Any CPU.Build.0 = Debug|Any CPU {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Debug|x86.ActiveCfg = Debug|Any CPU {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Debug|x86.Build.0 = Debug|Any CPU + {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Proto|Any CPU.Build.0 = Release|Any CPU + {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Proto|x86.ActiveCfg = Release|Any CPU + {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Proto|x86.Build.0 = Release|Any CPU {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Release|Any CPU.ActiveCfg = Release|Any CPU {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Release|Any CPU.Build.0 = Release|Any CPU {B4595EB6-053A-400E-AA1B-7727F1BC900F}.Release|x86.ActiveCfg = Release|Any CPU @@ -324,6 +430,10 @@ Global {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Debug|Any CPU.Build.0 = Debug|Any CPU {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Debug|x86.ActiveCfg = Debug|Any CPU {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Debug|x86.Build.0 = Debug|Any CPU + {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Proto|Any CPU.Build.0 = Release|Any CPU + {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Proto|x86.ActiveCfg = Release|Any CPU + {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Proto|x86.Build.0 = Release|Any CPU {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Release|Any CPU.ActiveCfg = Release|Any CPU {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Release|Any CPU.Build.0 = Release|Any CPU {A559D7E8-7EFD-473A-B618-A10B41AB523B}.Release|x86.ActiveCfg = Release|Any CPU @@ -332,6 +442,10 @@ Global {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Debug|Any CPU.Build.0 = Debug|Any CPU {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Debug|x86.ActiveCfg = Debug|Any CPU {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Debug|x86.Build.0 = Debug|Any CPU + {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Proto|Any CPU.Build.0 = Release|Any CPU + {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Proto|x86.ActiveCfg = Release|Any CPU + {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Proto|x86.Build.0 = Release|Any CPU {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Release|Any CPU.ActiveCfg = Release|Any CPU {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Release|Any CPU.Build.0 = Release|Any CPU {AC85EE6D-033C-45F9-B8BA-884BC22EC6D9}.Release|x86.ActiveCfg = Release|Any CPU @@ -340,6 +454,10 @@ Global {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Debug|Any CPU.Build.0 = Debug|Any CPU {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Debug|x86.ActiveCfg = Debug|Any CPU {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Debug|x86.Build.0 = Debug|Any CPU + {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Proto|Any CPU.Build.0 = Release|Any CPU + {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Proto|x86.ActiveCfg = Release|Any CPU + {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Proto|x86.Build.0 = Release|Any CPU {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Release|Any CPU.ActiveCfg = Release|Any CPU {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Release|Any CPU.Build.0 = Release|Any CPU {956BBE41-ABD1-4DBA-9F3B-BA1C9821C98C}.Release|x86.ActiveCfg = Release|Any CPU @@ -348,6 +466,10 @@ Global {702A7979-BCF9-4C41-853E-3ADFC9897890}.Debug|Any CPU.Build.0 = Debug|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Debug|x86.ActiveCfg = Debug|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Debug|x86.Build.0 = Debug|Any CPU + {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|Any CPU.Build.0 = Release|Any CPU + {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|x86.ActiveCfg = Release|Any CPU + {702A7979-BCF9-4C41-853E-3ADFC9897890}.Proto|x86.Build.0 = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|Any CPU.ActiveCfg = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|Any CPU.Build.0 = Release|Any CPU {702A7979-BCF9-4C41-853E-3ADFC9897890}.Release|x86.ActiveCfg = Release|Any CPU @@ -356,6 +478,10 @@ Global {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|Any CPU.Build.0 = Debug|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|x86.ActiveCfg = Debug|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Debug|x86.Build.0 = Debug|Any CPU + {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|Any CPU.Build.0 = Release|Any CPU + {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.ActiveCfg = Release|Any CPU + {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Proto|x86.Build.0 = Release|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|Any CPU.ActiveCfg = Release|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|Any CPU.Build.0 = Release|Any CPU {C94C257C-3C0A-4858-B5D8-D746498D1F08}.Release|x86.ActiveCfg = Release|Any CPU @@ -364,6 +490,10 @@ Global {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|Any CPU.Build.0 = Debug|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|x86.ActiveCfg = Debug|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Debug|x86.Build.0 = Debug|Any CPU + {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|Any CPU.Build.0 = Release|Any CPU + {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|x86.ActiveCfg = Release|Any CPU + {649FA588-F02E-457C-9FCF-87E46407481E}.Proto|x86.Build.0 = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|Any CPU.ActiveCfg = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|Any CPU.Build.0 = Release|Any CPU {649FA588-F02E-457C-9FCF-87E46407481E}.Release|x86.ActiveCfg = Release|Any CPU @@ -372,6 +502,10 @@ Global {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|Any CPU.Build.0 = Debug|Any CPU {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|x86.ActiveCfg = Debug|Any CPU {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Debug|x86.Build.0 = Debug|Any CPU + {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|Any CPU.Build.0 = Release|Any CPU + {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|x86.ActiveCfg = Release|Any CPU + {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Proto|x86.Build.0 = Release|Any CPU {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|Any CPU.ActiveCfg = Release|Any CPU {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|Any CPU.Build.0 = Release|Any CPU {8B3E283D-B5FE-4055-9D80-7E3A32F3967B}.Release|x86.ActiveCfg = Release|Any CPU @@ -380,6 +514,10 @@ Global {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|Any CPU.Build.0 = Debug|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|x86.ActiveCfg = Debug|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Debug|x86.Build.0 = Debug|Any CPU + {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|Any CPU.Build.0 = Release|Any CPU + {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.ActiveCfg = Release|Any CPU + {D0E98C0D-490B-4C61-9329-0862F6E87645}.Proto|x86.Build.0 = Release|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|Any CPU.ActiveCfg = Release|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|Any CPU.Build.0 = Release|Any CPU {D0E98C0D-490B-4C61-9329-0862F6E87645}.Release|x86.ActiveCfg = Release|Any CPU @@ -388,6 +526,10 @@ Global {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Debug|Any CPU.Build.0 = Debug|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Debug|x86.ActiveCfg = Debug|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Debug|x86.Build.0 = Debug|Any CPU + {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|Any CPU.Build.0 = Release|Any CPU + {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|x86.ActiveCfg = Release|Any CPU + {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Proto|x86.Build.0 = Release|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Release|Any CPU.ActiveCfg = Release|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Release|Any CPU.Build.0 = Release|Any CPU {C163E892-5BF7-4B59-AA99-B0E8079C67C4}.Release|x86.ActiveCfg = Release|Any CPU @@ -396,6 +538,10 @@ Global {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Debug|Any CPU.Build.0 = Debug|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Debug|x86.ActiveCfg = Debug|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Debug|x86.Build.0 = Debug|Any CPU + {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|Any CPU.Build.0 = Release|Any CPU + {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|x86.ActiveCfg = Release|Any CPU + {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Proto|x86.Build.0 = Release|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Release|Any CPU.ActiveCfg = Release|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Release|Any CPU.Build.0 = Release|Any CPU {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5}.Release|x86.ActiveCfg = Release|Any CPU @@ -404,38 +550,22 @@ Global {88E2D422-6852-46E3-A740-83E391DC7973}.Debug|Any CPU.Build.0 = Debug|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Debug|x86.ActiveCfg = Debug|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Debug|x86.Build.0 = Debug|Any CPU + {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|Any CPU.Build.0 = Release|Any CPU + {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|x86.ActiveCfg = Release|Any CPU + {88E2D422-6852-46E3-A740-83E391DC7973}.Proto|x86.Build.0 = Release|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Release|Any CPU.ActiveCfg = Release|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Release|Any CPU.Build.0 = Release|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Release|x86.ActiveCfg = Release|Any CPU {88E2D422-6852-46E3-A740-83E391DC7973}.Release|x86.Build.0 = Release|Any CPU - {604F0DAA-2D33-48DD-B162-EDF0B672803D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {604F0DAA-2D33-48DD-B162-EDF0B672803D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {604F0DAA-2D33-48DD-B162-EDF0B672803D}.Debug|x86.ActiveCfg = Debug|Any CPU - {604F0DAA-2D33-48DD-B162-EDF0B672803D}.Debug|x86.Build.0 = Debug|Any CPU - {604F0DAA-2D33-48DD-B162-EDF0B672803D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {604F0DAA-2D33-48DD-B162-EDF0B672803D}.Release|Any CPU.Build.0 = Release|Any CPU - {604F0DAA-2D33-48DD-B162-EDF0B672803D}.Release|x86.ActiveCfg = Release|Any CPU - {604F0DAA-2D33-48DD-B162-EDF0B672803D}.Release|x86.Build.0 = Release|Any CPU - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}.Debug|x86.ActiveCfg = Debug|Any CPU - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}.Debug|x86.Build.0 = Debug|Any CPU - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}.Release|Any CPU.Build.0 = Release|Any CPU - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}.Release|x86.ActiveCfg = Release|Any CPU - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7}.Release|x86.Build.0 = Release|Any CPU - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}.Debug|x86.ActiveCfg = Debug|Any CPU - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}.Debug|x86.Build.0 = Debug|Any CPU - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}.Release|Any CPU.Build.0 = Release|Any CPU - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}.Release|x86.ActiveCfg = Release|Any CPU - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4}.Release|x86.Build.0 = Release|Any CPU {6BA13AA4-C25F-480F-856B-8E8000299A72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6BA13AA4-C25F-480F-856B-8E8000299A72}.Debug|Any CPU.Build.0 = Debug|Any CPU {6BA13AA4-C25F-480F-856B-8E8000299A72}.Debug|x86.ActiveCfg = Debug|Any CPU {6BA13AA4-C25F-480F-856B-8E8000299A72}.Debug|x86.Build.0 = Debug|Any CPU + {6BA13AA4-C25F-480F-856B-8E8000299A72}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {6BA13AA4-C25F-480F-856B-8E8000299A72}.Proto|Any CPU.Build.0 = Proto|Any CPU + {6BA13AA4-C25F-480F-856B-8E8000299A72}.Proto|x86.ActiveCfg = Proto|Any CPU + {6BA13AA4-C25F-480F-856B-8E8000299A72}.Proto|x86.Build.0 = Proto|Any CPU {6BA13AA4-C25F-480F-856B-8E8000299A72}.Release|Any CPU.ActiveCfg = Release|Any CPU {6BA13AA4-C25F-480F-856B-8E8000299A72}.Release|Any CPU.Build.0 = Release|Any CPU {6BA13AA4-C25F-480F-856B-8E8000299A72}.Release|x86.ActiveCfg = Release|Any CPU @@ -444,6 +574,10 @@ Global {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Debug|Any CPU.Build.0 = Debug|Any CPU {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Debug|x86.ActiveCfg = Debug|Any CPU {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Debug|x86.Build.0 = Debug|Any CPU + {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Proto|Any CPU.Build.0 = Proto|Any CPU + {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Proto|x86.ActiveCfg = Proto|Any CPU + {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Proto|x86.Build.0 = Proto|Any CPU {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Release|Any CPU.ActiveCfg = Release|Any CPU {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Release|Any CPU.Build.0 = Release|Any CPU {12AC2813-E895-4AAA-AE6C-94E21DA09F64}.Release|x86.ActiveCfg = Release|Any CPU @@ -452,6 +586,10 @@ Global {A333B85A-DC23-49B6-9797-B89A7951E92D}.Debug|Any CPU.Build.0 = Debug|Any CPU {A333B85A-DC23-49B6-9797-B89A7951E92D}.Debug|x86.ActiveCfg = Debug|Any CPU {A333B85A-DC23-49B6-9797-B89A7951E92D}.Debug|x86.Build.0 = Debug|Any CPU + {A333B85A-DC23-49B6-9797-B89A7951E92D}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {A333B85A-DC23-49B6-9797-B89A7951E92D}.Proto|Any CPU.Build.0 = Proto|Any CPU + {A333B85A-DC23-49B6-9797-B89A7951E92D}.Proto|x86.ActiveCfg = Proto|Any CPU + {A333B85A-DC23-49B6-9797-B89A7951E92D}.Proto|x86.Build.0 = Proto|Any CPU {A333B85A-DC23-49B6-9797-B89A7951E92D}.Release|Any CPU.ActiveCfg = Release|Any CPU {A333B85A-DC23-49B6-9797-B89A7951E92D}.Release|Any CPU.Build.0 = Release|Any CPU {A333B85A-DC23-49B6-9797-B89A7951E92D}.Release|x86.ActiveCfg = Release|Any CPU @@ -460,6 +598,10 @@ Global {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Debug|Any CPU.Build.0 = Debug|Any CPU {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Debug|x86.ActiveCfg = Debug|Any CPU {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Debug|x86.Build.0 = Debug|Any CPU + {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Proto|Any CPU.Build.0 = Proto|Any CPU + {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Proto|x86.ActiveCfg = Proto|Any CPU + {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Proto|x86.Build.0 = Proto|Any CPU {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Release|Any CPU.ActiveCfg = Release|Any CPU {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Release|Any CPU.Build.0 = Release|Any CPU {E3FDD4AC-46B6-4B9F-B672-317D1202CC50}.Release|x86.ActiveCfg = Release|Any CPU @@ -468,6 +610,10 @@ Global {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Debug|Any CPU.Build.0 = Debug|Any CPU {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Debug|x86.ActiveCfg = Debug|Any CPU {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Debug|x86.Build.0 = Debug|Any CPU + {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Proto|Any CPU.Build.0 = Proto|Any CPU + {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Proto|x86.ActiveCfg = Proto|Any CPU + {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Proto|x86.Build.0 = Proto|Any CPU {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Release|Any CPU.ActiveCfg = Release|Any CPU {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Release|Any CPU.Build.0 = Release|Any CPU {D11FC318-8F5D-4C8C-9287-AB40A016D13C}.Release|x86.ActiveCfg = Release|Any CPU @@ -476,6 +622,10 @@ Global {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Debug|Any CPU.Build.0 = Debug|Any CPU {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Debug|x86.ActiveCfg = Debug|Any CPU {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Debug|x86.Build.0 = Debug|Any CPU + {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Proto|Any CPU.Build.0 = Proto|Any CPU + {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Proto|x86.ActiveCfg = Proto|Any CPU + {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Proto|x86.Build.0 = Proto|Any CPU {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Release|Any CPU.ActiveCfg = Release|Any CPU {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Release|Any CPU.Build.0 = Release|Any CPU {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6}.Release|x86.ActiveCfg = Release|Any CPU @@ -484,6 +634,10 @@ Global {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Debug|Any CPU.Build.0 = Debug|Any CPU {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Debug|x86.ActiveCfg = Debug|Any CPU {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Debug|x86.Build.0 = Debug|Any CPU + {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Proto|Any CPU.Build.0 = Release|Any CPU + {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Proto|x86.ActiveCfg = Release|Any CPU + {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Proto|x86.Build.0 = Release|Any CPU {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Release|Any CPU.ActiveCfg = Release|Any CPU {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Release|Any CPU.Build.0 = Release|Any CPU {4239EFEA-E746-446A-BF7A-51FCBAB13946}.Release|x86.ActiveCfg = Release|Any CPU @@ -492,6 +646,10 @@ Global {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Debug|Any CPU.Build.0 = Debug|Any CPU {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Debug|x86.ActiveCfg = Debug|Any CPU {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Debug|x86.Build.0 = Debug|Any CPU + {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Proto|Any CPU.Build.0 = Release|Any CPU + {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Proto|x86.ActiveCfg = Release|Any CPU + {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Proto|x86.Build.0 = Release|Any CPU {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Release|Any CPU.ActiveCfg = Release|Any CPU {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Release|Any CPU.Build.0 = Release|Any CPU {2E60864A-E3FF-4BCC-810F-DC7C34E6B236}.Release|x86.ActiveCfg = Release|Any CPU @@ -500,6 +658,10 @@ Global {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Debug|Any CPU.Build.0 = Debug|Any CPU {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Debug|x86.ActiveCfg = Debug|Any CPU {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Debug|x86.Build.0 = Debug|Any CPU + {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Proto|Any CPU.Build.0 = Release|Any CPU + {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Proto|x86.ActiveCfg = Release|Any CPU + {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Proto|x86.Build.0 = Release|Any CPU {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Release|Any CPU.ActiveCfg = Release|Any CPU {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Release|Any CPU.Build.0 = Release|Any CPU {E7FA3A71-51AF-4FCA-9C2F-7C853E515903}.Release|x86.ActiveCfg = Release|Any CPU @@ -508,6 +670,10 @@ Global {C4586A06-1402-48BC-8E35-A1B8642F895B}.Debug|Any CPU.Build.0 = Debug|Any CPU {C4586A06-1402-48BC-8E35-A1B8642F895B}.Debug|x86.ActiveCfg = Debug|Any CPU {C4586A06-1402-48BC-8E35-A1B8642F895B}.Debug|x86.Build.0 = Debug|Any CPU + {C4586A06-1402-48BC-8E35-A1B8642F895B}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {C4586A06-1402-48BC-8E35-A1B8642F895B}.Proto|Any CPU.Build.0 = Release|Any CPU + {C4586A06-1402-48BC-8E35-A1B8642F895B}.Proto|x86.ActiveCfg = Release|Any CPU + {C4586A06-1402-48BC-8E35-A1B8642F895B}.Proto|x86.Build.0 = Release|Any CPU {C4586A06-1402-48BC-8E35-A1B8642F895B}.Release|Any CPU.ActiveCfg = Release|Any CPU {C4586A06-1402-48BC-8E35-A1B8642F895B}.Release|Any CPU.Build.0 = Release|Any CPU {C4586A06-1402-48BC-8E35-A1B8642F895B}.Release|x86.ActiveCfg = Release|Any CPU @@ -516,6 +682,10 @@ Global {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Debug|Any CPU.Build.0 = Debug|Any CPU {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Debug|x86.ActiveCfg = Debug|Any CPU {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Debug|x86.Build.0 = Debug|Any CPU + {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Proto|Any CPU.Build.0 = Release|Any CPU + {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Proto|x86.ActiveCfg = Release|Any CPU + {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Proto|x86.Build.0 = Release|Any CPU {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Release|Any CPU.ActiveCfg = Release|Any CPU {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Release|Any CPU.Build.0 = Release|Any CPU {887630A3-4B1D-40EA-B8B3-2D842E9C40DB}.Release|x86.ActiveCfg = Release|Any CPU @@ -524,6 +694,10 @@ Global {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Debug|Any CPU.Build.0 = Debug|Any CPU {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Debug|x86.ActiveCfg = Debug|Any CPU {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Debug|x86.Build.0 = Debug|Any CPU + {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Proto|Any CPU.Build.0 = Release|Any CPU + {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Proto|x86.ActiveCfg = Release|Any CPU + {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Proto|x86.Build.0 = Release|Any CPU {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Release|Any CPU.ActiveCfg = Release|Any CPU {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Release|Any CPU.Build.0 = Release|Any CPU {FF76BD3C-5E0A-4752-B6C3-044F6E15719B}.Release|x86.ActiveCfg = Release|Any CPU @@ -532,6 +706,10 @@ Global {0385564F-07B4-4264-AB8A-17C393E9140C}.Debug|Any CPU.Build.0 = Debug|Any CPU {0385564F-07B4-4264-AB8A-17C393E9140C}.Debug|x86.ActiveCfg = Debug|Any CPU {0385564F-07B4-4264-AB8A-17C393E9140C}.Debug|x86.Build.0 = Debug|Any CPU + {0385564F-07B4-4264-AB8A-17C393E9140C}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {0385564F-07B4-4264-AB8A-17C393E9140C}.Proto|Any CPU.Build.0 = Proto|Any CPU + {0385564F-07B4-4264-AB8A-17C393E9140C}.Proto|x86.ActiveCfg = Proto|Any CPU + {0385564F-07B4-4264-AB8A-17C393E9140C}.Proto|x86.Build.0 = Proto|Any CPU {0385564F-07B4-4264-AB8A-17C393E9140C}.Release|Any CPU.ActiveCfg = Release|Any CPU {0385564F-07B4-4264-AB8A-17C393E9140C}.Release|Any CPU.Build.0 = Release|Any CPU {0385564F-07B4-4264-AB8A-17C393E9140C}.Release|x86.ActiveCfg = Release|Any CPU @@ -540,6 +718,10 @@ Global {400FAB03-786E-40CC-85A8-04B0C2869B14}.Debug|Any CPU.Build.0 = Debug|Any CPU {400FAB03-786E-40CC-85A8-04B0C2869B14}.Debug|x86.ActiveCfg = Debug|Any CPU {400FAB03-786E-40CC-85A8-04B0C2869B14}.Debug|x86.Build.0 = Debug|Any CPU + {400FAB03-786E-40CC-85A8-04B0C2869B14}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {400FAB03-786E-40CC-85A8-04B0C2869B14}.Proto|Any CPU.Build.0 = Release|Any CPU + {400FAB03-786E-40CC-85A8-04B0C2869B14}.Proto|x86.ActiveCfg = Release|Any CPU + {400FAB03-786E-40CC-85A8-04B0C2869B14}.Proto|x86.Build.0 = Release|Any CPU {400FAB03-786E-40CC-85A8-04B0C2869B14}.Release|Any CPU.ActiveCfg = Release|Any CPU {400FAB03-786E-40CC-85A8-04B0C2869B14}.Release|Any CPU.Build.0 = Release|Any CPU {400FAB03-786E-40CC-85A8-04B0C2869B14}.Release|x86.ActiveCfg = Release|Any CPU @@ -548,6 +730,10 @@ Global {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Debug|Any CPU.Build.0 = Debug|Any CPU {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Debug|x86.ActiveCfg = Debug|Any CPU {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Debug|x86.Build.0 = Debug|Any CPU + {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Proto|Any CPU.Build.0 = Release|Any CPU + {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Proto|x86.ActiveCfg = Release|Any CPU + {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Proto|x86.Build.0 = Release|Any CPU {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Release|Any CPU.ActiveCfg = Release|Any CPU {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Release|Any CPU.Build.0 = Release|Any CPU {B0689A4E-07D8-494D-A0C8-791CB1D74E54}.Release|x86.ActiveCfg = Release|Any CPU @@ -556,6 +742,10 @@ Global {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Debug|Any CPU.Build.0 = Debug|Any CPU {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Debug|x86.ActiveCfg = Debug|Any CPU {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Debug|x86.Build.0 = Debug|Any CPU + {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Proto|Any CPU.Build.0 = Release|Any CPU + {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Proto|x86.ActiveCfg = Release|Any CPU + {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Proto|x86.Build.0 = Release|Any CPU {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Release|Any CPU.ActiveCfg = Release|Any CPU {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Release|Any CPU.Build.0 = Release|Any CPU {18227628-DF90-4C47-AF3D-CC72D2EDD986}.Release|x86.ActiveCfg = Release|Any CPU @@ -564,15 +754,133 @@ Global {6D93CEBD-4540-4D96-A153-B440A661FD09}.Debug|Any CPU.Build.0 = Debug|Any CPU {6D93CEBD-4540-4D96-A153-B440A661FD09}.Debug|x86.ActiveCfg = Debug|Any CPU {6D93CEBD-4540-4D96-A153-B440A661FD09}.Debug|x86.Build.0 = Debug|Any CPU + {6D93CEBD-4540-4D96-A153-B440A661FD09}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {6D93CEBD-4540-4D96-A153-B440A661FD09}.Proto|Any CPU.Build.0 = Release|Any CPU + {6D93CEBD-4540-4D96-A153-B440A661FD09}.Proto|x86.ActiveCfg = Release|Any CPU + {6D93CEBD-4540-4D96-A153-B440A661FD09}.Proto|x86.Build.0 = Release|Any CPU {6D93CEBD-4540-4D96-A153-B440A661FD09}.Release|Any CPU.ActiveCfg = Release|Any CPU {6D93CEBD-4540-4D96-A153-B440A661FD09}.Release|Any CPU.Build.0 = Release|Any CPU {6D93CEBD-4540-4D96-A153-B440A661FD09}.Release|x86.ActiveCfg = Release|Any CPU {6D93CEBD-4540-4D96-A153-B440A661FD09}.Release|x86.Build.0 = Release|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Debug|x86.ActiveCfg = Debug|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Debug|x86.Build.0 = Debug|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Proto|Any CPU.Build.0 = Release|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Proto|x86.ActiveCfg = Release|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Proto|x86.Build.0 = Release|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Release|Any CPU.Build.0 = Release|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Release|x86.ActiveCfg = Release|Any CPU + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A}.Release|x86.Build.0 = Release|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Debug|x86.ActiveCfg = Debug|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Debug|x86.Build.0 = Debug|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Proto|Any CPU.Build.0 = Debug|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Proto|x86.ActiveCfg = Debug|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Proto|x86.Build.0 = Debug|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Release|Any CPU.Build.0 = Release|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Release|x86.ActiveCfg = Release|Any CPU + {6BCFED7A-3F67-4180-B307-C7D69D191D8C}.Release|x86.Build.0 = Release|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Debug|x86.ActiveCfg = Debug|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Debug|x86.Build.0 = Debug|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Proto|Any CPU.Build.0 = Debug|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Proto|x86.ActiveCfg = Debug|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Proto|x86.Build.0 = Debug|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Release|Any CPU.Build.0 = Release|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Release|x86.ActiveCfg = Release|Any CPU + {E93E7D28-1C6B-4E04-BE83-68428CF7E039}.Release|x86.Build.0 = Release|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Debug|x86.ActiveCfg = Debug|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Debug|x86.Build.0 = Debug|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Proto|Any CPU.ActiveCfg = Debug|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Proto|Any CPU.Build.0 = Debug|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Proto|x86.ActiveCfg = Debug|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Proto|x86.Build.0 = Debug|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Release|Any CPU.Build.0 = Release|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Release|x86.ActiveCfg = Release|Any CPU + {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Release|x86.Build.0 = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|Any CPU.Build.0 = Debug|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|x86.ActiveCfg = Debug|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|x86.Build.0 = Debug|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|Any CPU.Build.0 = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|x86.ActiveCfg = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|x86.Build.0 = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|Any CPU.ActiveCfg = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|Any CPU.Build.0 = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|x86.ActiveCfg = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|x86.Build.0 = Release|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Debug|x86.ActiveCfg = Debug|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Debug|x86.Build.0 = Debug|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Proto|Any CPU.Build.0 = Release|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Proto|x86.ActiveCfg = Release|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Proto|x86.Build.0 = Release|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Release|Any CPU.Build.0 = Release|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Release|x86.ActiveCfg = Release|Any CPU + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Release|x86.Build.0 = Release|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Debug|x86.ActiveCfg = Debug|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Debug|x86.Build.0 = Debug|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Proto|Any CPU.Build.0 = Proto|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Proto|x86.ActiveCfg = Proto|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Proto|x86.Build.0 = Proto|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Release|Any CPU.Build.0 = Release|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Release|x86.ActiveCfg = Release|Any CPU + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8}.Release|x86.Build.0 = Release|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Debug|x86.ActiveCfg = Debug|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Debug|x86.Build.0 = Debug|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Proto|Any CPU.Build.0 = Proto|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Proto|x86.ActiveCfg = Proto|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Proto|x86.Build.0 = Proto|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Release|Any CPU.Build.0 = Release|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Release|x86.ActiveCfg = Release|Any CPU + {C32806E0-71C2-40E4-AEC4-517F73F6A18A}.Release|x86.Build.0 = Release|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Debug|x86.ActiveCfg = Debug|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Debug|x86.Build.0 = Debug|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Proto|Any CPU.ActiveCfg = Proto|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Proto|Any CPU.Build.0 = Proto|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Proto|x86.ActiveCfg = Proto|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Proto|x86.Build.0 = Proto|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Release|Any CPU.Build.0 = Release|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Release|x86.ActiveCfg = Release|Any CPU + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution + {3F044931-FB83-4433-B934-AE66AB27B278} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} + {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} + {F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} + {D086C8C6-D00D-4C3B-9AB2-A4286C9F5922} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} + {35636A82-401A-4C3A-B2AB-EB7DC5E9C268} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} + {CCAB6E50-34C6-42AF-A6B0-567C29FCD91B} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {991DCF75-C2EB-42B6-9A0D-AA1D2409D519} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3} = {3881429D-A97A-49EB-B7AE-A82BA5FE9C77} {59ADCE46-9740-4079-834D-9A03A3494EBC} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} @@ -584,7 +892,6 @@ Global {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7} = {CCAB6E50-34C6-42AF-A6B0-567C29FCD91B} {FCFB214C-462E-42B3-91CA-FC557EFEE74F} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44} = {CCAB6E50-34C6-42AF-A6B0-567C29FCD91B} - {C9B1D3F5-4971-4F04-9C26-37E3AC809AB4} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {FBD4B354-DC6E-4032-8EC7-C81D8DFB1AF7} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} {EE85AAB7-CDA0-4C4E-BDA0-A64DDDD13E3F} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} {DA39AD38-4A58-47BF-9215-E49768295169} = {3F044931-FB83-4433-B934-AE66AB27B278} @@ -605,14 +912,8 @@ Global {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} = {B8DDA694-7939-42E3-95E5-265C2217C142} {D0E98C0D-490B-4C61-9329-0862F6E87645} = {B8DDA694-7939-42E3-95E5-265C2217C142} {C163E892-5BF7-4B59-AA99-B0E8079C67C4} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} - {3F044931-FB83-4433-B934-AE66AB27B278} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} {A8D9641A-9170-4CF4-8FE0-6DB8C134E1B5} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {88E2D422-6852-46E3-A740-83E391DC7973} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} - {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} - {604F0DAA-2D33-48DD-B162-EDF0B672803D} = {C9B1D3F5-4971-4F04-9C26-37E3AC809AB4} - {01678CDA-A11F-4DEE-9344-2EDF91CF1AE7} = {C9B1D3F5-4971-4F04-9C26-37E3AC809AB4} - {2FACEE44-48BD-40B5-A2EE-B54A0C9BB7C4} = {C9B1D3F5-4971-4F04-9C26-37E3AC809AB4} - {F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {6BA13AA4-C25F-480F-856B-8E8000299A72} = {F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA} {12AC2813-E895-4AAA-AE6C-94E21DA09F64} = {F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA} {A333B85A-DC23-49B6-9797-B89A7951E92D} = {F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA} @@ -621,18 +922,25 @@ Global {1FB1DD07-06AA-45B4-B5AC-20FF5BEE98B6} = {F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA} {4239EFEA-E746-446A-BF7A-51FCBAB13946} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {2E60864A-E3FF-4BCC-810F-DC7C34E6B236} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} - {D086C8C6-D00D-4C3B-9AB2-A4286C9F5922} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {E7FA3A71-51AF-4FCA-9C2F-7C853E515903} = {D086C8C6-D00D-4C3B-9AB2-A4286C9F5922} {C4586A06-1402-48BC-8E35-A1B8642F895B} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {887630A3-4B1D-40EA-B8B3-2D842E9C40DB} = {35636A82-401A-4C3A-B2AB-EB7DC5E9C268} - {35636A82-401A-4C3A-B2AB-EB7DC5E9C268} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} {FF76BD3C-5E0A-4752-B6C3-044F6E15719B} = {35636A82-401A-4C3A-B2AB-EB7DC5E9C268} {0385564F-07B4-4264-AB8A-17C393E9140C} = {F6DAEE9A-8BE1-4C4A-BC83-09215517C7DA} {400FAB03-786E-40CC-85A8-04B0C2869B14} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {B0689A4E-07D8-494D-A0C8-791CB1D74E54} = {CFE3259A-2D30-4EB0-80D5-E8B5F3D01449} {18227628-DF90-4C47-AF3D-CC72D2EDD986} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} - {CCAB6E50-34C6-42AF-A6B0-567C29FCD91B} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {6D93CEBD-4540-4D96-A153-B440A661FD09} = {F7876C9B-FB6A-4EFB-B058-D6967DB75FB2} + {4CBEE353-EB7F-4A47-988B-0070AEB4EE7A} = {6235B3AF-774D-4EA1-8F37-789E767F6368} + {6BCFED7A-3F67-4180-B307-C7D69D191D8C} = {6235B3AF-774D-4EA1-8F37-789E767F6368} + {E93E7D28-1C6B-4E04-BE83-68428CF7E039} = {6235B3AF-774D-4EA1-8F37-789E767F6368} + {9482211E-23D0-4BD0-9893-E4AA5559F67A} = {6235B3AF-774D-4EA1-8F37-789E767F6368} + {025CE01B-98F3-4C3C-B486-2C0BD038D011} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} + {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8} = {647810D0-5307-448F-99A2-E83917010DAE} + {BED74F9E-A0D2-48E2-9EE7-449832100487} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} + {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8} = {BED74F9E-A0D2-48E2-9EE7-449832100487} + {C32806E0-71C2-40E4-AEC4-517F73F6A18A} = {BED74F9E-A0D2-48E2-9EE7-449832100487} + {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1} = {BED74F9E-A0D2-48E2-9EE7-449832100487} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {48EDBBBE-C8EE-4E3C-8B19-97184A487B37} diff --git a/build.cmd b/build.cmd deleted file mode 100644 index ab85f177c5d..00000000000 --- a/build.cmd +++ /dev/null @@ -1,1087 +0,0 @@ -rem Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -@if "%_echo%"=="" echo off -setlocal enableDelayedExpansion - -:ARGUMENTS_VALIDATION -if /I "%1" == "--help" (goto :USAGE) -if /I "%1" == "/help" (goto :USAGE) -if /I "%1" == "/h" (goto :USAGE) -if /I "%1" == "/?" (goto :USAGE) -goto :ARGUMENTS_OK - - -:USAGE - -echo Build and run a subset of test suites -echo. -echo Usage: -echo. -echo build.cmd ^ -echo ^ -echo ^ -echo ^ -echo ^ -echo ^ -echo ^ -echo ^ -echo. -echo No arguments default to default", meaning this (no testing) -echo. -echo build.cmd net40 -echo. -echo.Other examples: -echo. -echo. build.cmd net40 (build compiler for .NET Framework) -echo. build.cmd coreclr (build compiler for .NET Core) -echo. build.cmd buildfromsource (build compiler for .NET Core -- Verify that buildfromsource works) -echo. build.cmd vs (build Visual Studio IDE Tools) -echo. build.cmd all (build everything) -echo. build.cmd test (build and test default targets) -echo. build.cmd net40 test (build and test compiler for .NET Framework) -echo. build.cmd coreclr test (build and test compiler for .NET Core) -echo. build.cmd vs test (build and test Visual Studio IDE Tools) -echo. build.cmd all test (build and test everything) -echo. build.cmd nobuild test include Conformance (run only tests marked with Conformance category) -echo. build.cmd nobuild test include Expensive (run only tests marked with Expensive category) -echo. -goto :success - -:ARGUMENTS_OK - -rem disable setup build by setting FSC_BUILD_SETUP=0 -if /i "%FSC_BUILD_SETUP%" == "" (set FSC_BUILD_SETUP=1) - -rem by default don't build coreclr lkg. However allow configuration by setting an environment variable : set BUILD_PROTO_WITH_CORECLR_LKG = 1 -if "%BUILD_PROTO_WITH_CORECLR_LKG%" =="" (set BUILD_PROTO_WITH_CORECLR_LKG=0) - -set BUILD_PROTO=0 -set BUILD_PHASE=1 -set BUILD_NET40=0 -set BUILD_NET40_FSHARP_CORE=0 -set BUILD_CORECLR=0 -set BUILD_FROMSOURCE=0 -set BUILD_VS=0 -set BUILD_FCS=0 -set BUILD_CONFIG=Release -set BUILD_DIAG= -set BUILD_PUBLICSIGN=0 -set BUILD_FSHARP_PROJ=1 - -set TEST_NET40_COMPILERUNIT_SUITE=0 -set TEST_NET40_COREUNIT_SUITE=0 -set TEST_NET40_FSHARP_SUITE=0 -set TEST_NET40_FSHARPQA_SUITE=0 -set TEST_CORECLR_COREUNIT_SUITE=0 -set TEST_CORECLR_FSHARP_SUITE=0 -set TEST_VS_IDEUNIT_SUITE=0 -set TEST_FCS=0 -set TEST_END_2_END=0 -set INCLUDE_TEST_TAGS= - -set COPY_FSCOMP_RESOURCE_FOR_BUILD_FROM_SOURCES=0 - -set SIGN_TYPE=%PB_SIGNTYPE% - -REM ------------------ Parse all arguments ----------------------- - -set _autoselect=1 -set _autoselect_tests=0 -set no_test=0 -set /a counter=0 -for /l %%x in (1 1 9) do ( - set /a counter=!counter!+1 - set /a nextcounter=!counter!+1 - call :PROCESS_ARG %%!counter! %%!nextcounter! "!counter!" -) -for %%i in (%BUILD_FSC_DEFAULT%) do ( call :PROCESS_ARG %%i ) - -REM apply defaults - -if /i "%_buildexit%" == "1" ( - exit /B %_buildexitvalue% -) - -if /i "%_autoselect%" == "1" ( - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_NET40=1 -) - -if /i "%_autoselect_tests%" == "1" ( - if /i "%BUILD_NET40_FSHARP_CORE%" == "1" ( - set BUILD_NUGET=1 - set TEST_NET40_COREUNIT_SUITE=1 - ) - - if /i "%BUILD_NET40%" == "1" ( - set BUILD_NUGET=1 - set TEST_NET40_COMPILERUNIT_SUITE=1 - set TEST_NET40_COREUNIT_SUITE=1 - set TEST_NET40_FSHARP_SUITE=1 - set TEST_NET40_FSHARPQA_SUITE=1 - ) - - if /i "%BUILD_FCS%" == "1" ( - set TEST_FCS=1 - ) - - if /i "%BUILD_CORECLR%" == "1" ( - set TEST_CORECLR_FSHARP_SUITE=1 - set TEST_CORECLR_COREUNIT_SUITE=1 - ) - - if /i "%BUILD_VS%" == "1" ( - set TEST_VS_IDEUNIT_SUITE=1 - ) -) - -goto :MAIN - -REM ------------------ Procedure to parse one argument ----------------------- - -:PROCESS_ARG -set ARG=%~1 -set ARG2=%~2 -if "%ARG%" == "1" if "%2" == "" (set ARG=default) -if "%2" == "" if not "%ARG%" == "default" goto :EOF - -rem Do no work -if /i "%ARG%" == "none" ( - set _buildexit=1 - set _buildexitvalue=0 -) - -if /i "%ARG%" == "net40-lib" ( - set _autoselect=0 - set BUILD_NET40_FSHARP_CORE=1 -) - -if /i "%ARG%" == "net40" ( - set _autoselect=0 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_NET40=1 - set COPY_FSCOMP_RESOURCE_FOR_BUILD_FROM_SOURCES=1 -) - -if /i "%ARG%" == "coreclr" ( - set _autoselect=0 - set BUILD_CORECLR=1 - set BUILD_FROMSOURCE=1 -) - -if /i "%ARG%" == "buildfromsource" ( - set _autoselect=0 - set BUILD_PROTO_WITH_CORECLR_LKG=1 - set BUILD_FROMSOURCE=1 -) - -if /i "%ARG%" == "vs" ( - set _autoselect=0 - set BUILD_NET40=1 - set BUILD_VS=1 - set COPY_FSCOMP_RESOURCE_FOR_BUILD_FROM_SOURCES=1 -) - -if /i "%ARG%" == "fcs" ( - set _autoselect=0 - set BUILD_FCS=1 -) - -if /i "%ARG%" == "vstest" ( - set TEST_VS_IDEUNIT_SUITE=1 -) - -if /i "%ARG%" == "nobuild" ( - set BUILD_PHASE=0 -) -if /i "%ARG%" == "all" ( - set _autoselect=0 - set COPY_FSCOMP_RESOURCE_FOR_BUILD_FROM_SOURCES=1 - set BUILD_PROTO=1 - set BUILD_PROTO_WITH_CORECLR_LKG=1 - set BUILD_NET40=1 - set BUILD_CORECLR=1 - set BUILD_VS=1 - set BUILD_FCS=1 - set BUILD_SETUP=%FSC_BUILD_SETUP% - set BUILD_NUGET=1 - set CI=1 -) - -if /i "%ARG%" == "microbuild" ( - set _autoselect=0 - set BUILD_PROTO=1 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_PROTO_WITH_CORECLR_LKG=1 - set BUILD_CORECLR=1 - set BUILD_VS=1 - set BUILD_SETUP=%FSC_BUILD_SETUP% - set BUILD_NUGET=1 - set BUILD_MICROBUILD=1 - - set TEST_NET40_COMPILERUNIT_SUITE=1 - set TEST_NET40_COREUNIT_SUITE=1 - set TEST_NET40_FSHARP_SUITE=1 - set TEST_NET40_FSHARPQA_SUITE=1 - set TEST_CORECLR_COREUNIT_SUITE=0 - set TEST_CORECLR_FSHARP_SUITE=0 - set TEST_VS_IDEUNIT_SUITE=1 - set CI=1 - - REM redirecting TEMP directories - set TEMP=%~dp0artifacts\tmp - set TMP=%~dp0artifacts\tmp -) - -if /i "%ARG%" == "nuget" ( - set _autoselect=0 - - set BUILD_PROTO=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_NET40=1 - set BUILD_CORECLR=1 - set BUILD_NUGET=1 -) - -REM These divide "ci" into three chunks which can be done in parallel -if /i "%ARG%" == "ci_part1" ( - set _autoselect=0 - - REM what we do - build and test Visual F# Tools, including setup and nuget - set BUILD_PROTO=1 - set BUILD_NUGET=1 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_VS=1 - set TEST_VS_IDEUNIT_SUITE=1 - set BUILD_CORECLR=1 - set BUILD_SETUP=%FSC_BUILD_SETUP% - set CI=1 -) - -if /i "%ARG%" == "ci_part2" ( - set _autoselect=0 - - REM what we do - test F# on .NET Framework - set BUILD_PROTO=1 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_NUGET=1 - set TEST_NET40_COMPILERUNIT_SUITE=1 - set TEST_NET40_COREUNIT_SUITE=1 - set TEST_NET40_FSHARPQA_SUITE=1 - set TEST_NET40_FSHARP_SUITE=1 - set CI=1 -) - -if /i "%ARG%" == "ci_part3" ( - set _autoselect=0 - - REM what we do: test F# on Core CLR: nuget requires coreclr, fcs requires coreclr - set BUILD_PROTO_WITH_CORECLR_LKG=1 - set BUILD_PROTO=1 - set BUILD_CORECLR=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_NET40=1 - set TEST_CORECLR_FSHARP_SUITE=1 - set TEST_CORECLR_COREUNIT_SUITE=1 - set CI=1 -) - -if /i "%ARG%" == "ci_part4" ( - set _autoselect=0 - - REM what we do: test F# on Core CLR: nuget requires coreclr, fcs requires coreclr - set BUILD_PROTO_WITH_CORECLR_LKG=1 - set BUILD_PROTO=1 - set BUILD_CORECLR=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_NET40=1 - set BUILD_NUGET=1 - set BUILD_FCS=1 - set TEST_FCS=1 - set CI=1 -) - -if /i "%ARG%" == "end-2-end" ( - set BUILD_PROTO=1 - set BUILD_CORECLR=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_NET40=1 - set TEST_END_2_END=1 -) - -if /i "%ARG%" == "proto" ( - set _autoselect=0 - set BUILD_PROTO=1 -) - -if /i "%ARG%" == "diag" ( - set BUILD_DIAG=/v:detailed - if not defined APPVEYOR ( set BUILD_LOG=fsharp_build_log.log ) -) - -if /i "%ARG%" == "debug" ( - set BUILD_CONFIG=Debug -) - -if /i "%ARG%" == "release" ( - set BUILD_CONFIG=Release -) - -if /i "%ARG%" == "test-sign" ( - set SIGN_TYPE=test -) - -if /i "%ARG%" == "real-sign" ( - set SIGN_TYPE=real -) - -if /i "%ARG%" == "test" ( - set _autoselect_tests=1 -) - -if /i "%ARG%" == "no-test" ( - set no_test=1 -) - -if /i "%ARG%" == "include" ( - set /a counter=!counter!+1 - if "!INCLUDE_TEST_TAGS!" == "" ( set INCLUDE_TEST_TAGS=%ARG2% ) else (set INCLUDE_TEST_TAGS=%ARG2%;!INCLUDE_TEST_TAGS! ) -) - -if /i "%ARG%" == "test-all" ( - set _autoselect=0 - set BUILD_PROTO=1 - set BUILD_PROTO_WITH_CORECLR_LKG=1 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_CORECLR=1 - set BUILD_VS=1 - set BUILD_FCS=1 - set BUILD_SETUP=%FSC_BUILD_SETUP% - set BUILD_NUGET=1 - - set TEST_NET40_COMPILERUNIT_SUITE=1 - set TEST_NET40_COREUNIT_SUITE=1 - set TEST_NET40_FSHARP_SUITE=1 - set TEST_NET40_FSHARPQA_SUITE=1 - set TEST_CORECLR_COREUNIT_SUITE=1 - set TEST_VS_IDEUNIT_SUITE=1 - set TEST_FCS=1 - set TEST_END_2_END=1 -) - -if /i "%ARG%" == "test-net40-fsharpqa" ( - set _autoselect=0 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set TEST_NET40_FSHARPQA_SUITE=1 -) - -if /i "%ARG%" == "test-compiler-unit" ( - set _autoselect=0 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set TEST_NET40_COMPILERUNIT_SUITE=1 -) - -if /i "%ARG%" == "test-net40-ideunit" ( - set _autoselect=0 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_VS=1 - set TEST_VS_IDEUNIT_SUITE=1 -) - -if /i "%ARG%" == "test-net40-coreunit" ( - set _autoselect=0 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_NUGET=1 - set TEST_NET40_COREUNIT_SUITE=1 -) - -if /i "%ARG%" == "test-coreclr-coreunit" ( - set _autoselect=0 - set BUILD_PROTO_WITH_CORECLR_LKG=1 - set BUILD_CORECLR=1 - set BUILD_NUGET=1 - set TEST_CORECLR_COREUNIT_SUITE=1 -) - -if /i "%ARG%" == "test-net40-fsharp" ( - set _autoselect=0 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set TEST_NET40_FSHARP_SUITE=1 -) - -if /i "%ARG%" == "test-fcs" ( - set _autoselect=0 - set BUILD_FCS=1 - set TEST_FCS=1 -) - -if /i "%ARG%" == "test-coreclr-fsharp" ( - set _autoselect=0 - set BUILD_NET40=1 - set BUILD_NET40_FSHARP_CORE=1 - set BUILD_PROTO_WITH_CORECLR_LKG=1 - set BUILD_CORECLR=1 - set TEST_CORECLR_FSHARP_SUITE=1 -) - -if /i "%ARG%" == "publicsign" ( - set BUILD_PUBLICSIGN=1 -) - -if /i "%ARG%" == "init" ( - set BUILD_PROTO_WITH_CORECLR_LKG=1 -) - -goto :EOF -:: Note: "goto :EOF" returns from an in-batchfile "call" command -:: in preference to returning from the entire batch file. - -REM ------------------ Report config ----------------------- - -:MAIN - -REM after this point, ARG variable should not be used, use only BUILD_* or TEST_* - -REM all PB_* variables override any settings - -REM if the `PB_SKIPTESTS` variable is set to 'true' then no tests should be built or run, even if explicitly specified -if /i "%PB_SKIPTESTS%" == "true" ( - set TEST_NET40_COMPILERUNIT_SUITE=0 - set TEST_NET40_COREUNIT_SUITE=0 - set TEST_NET40_FSHARP_SUITE=0 - set TEST_NET40_FSHARPQA_SUITE=0 - set TEST_CORECLR_COREUNIT_SUITE=0 - set TEST_CORECLR_FSHARP_SUITE=0 - set TEST_VS_IDEUNIT_SUITE=0 -) - -if /i "%TEST_NET40_FSHARP_SUITE" == "1" ( - if /i "%TEST_CORECLR_FSHARP_SUITE%" == "1" ( - TEST_END_2_END=1 - ) -) - -rem Decide if Proto need building -if NOT EXIST "%~dp0artifacts\bin\fsc\Proto\net46\fsc.exe" ( - set BUILD_PROTO=1 -) - -rem decide if FSharp.Proj needs building -if "%BUILD_NET40%"=="0" if "%BUILD_NET40_FSHARP_CORE%"=="0" if "%BUILD_CORECLR%"=="0" if "%BUILD_VS%"=="0" if "%BUILD_FCS%"=="0" if "%TEST_NET40_COMPILERUNIT_SUITE%"=="0" if "%TEST_NET40_COREUNIT_SUITE%"=="0" if "%TEST_NET40_FSHARP_SUITE%"=="0" if "%TEST_NET40_FSHARPQA_SUITE%"=="0" if "%TEST_CORECLR_COREUNIT_SUITE%"=="0" if "%TEST_CORECLR_FSHARP_SUITE%"=="0" if "%TEST_VS_IDEUNIT_SUITE%"=="0" if "%TEST_FCS%"=="0" if "%TEST_END_2_END%"=="0" if "%COPY_FSCOMP_RESOURCE_FOR_BUILD_FROM_SOURCES%"=="0" ( - set BUILD_FSHARP_PROJ=0 -) - -rem -rem This stops the dotnet cli from hunting around and -rem finding the highest possible dotnet sdk version to use. -rem -rem description of dotnet lookup here: -rem https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet?tabs=netcore2x -set DOTNET_MULTILEVEL_LOOKUP=false - -echo Build/Tests configuration: -echo. -echo BUILD_PROTO=%BUILD_PROTO% -echo BUILD_PROTO_WITH_CORECLR_LKG=%BUILD_PROTO_WITH_CORECLR_LKG% -echo BUILD_NET40=%BUILD_NET40% -echo BUILD_NET40_FSHARP_CORE=%BUILD_NET40_FSHARP_CORE% -echo BUILD_CORECLR=%BUILD_CORECLR% -echo BUILD_VS=%BUILD_VS% -echo BUILD_FCS=%BUILD_FCS% -echo BUILD_SETUP=%BUILD_SETUP% -echo BUILD_NUGET=%BUILD_NUGET% -echo BUILD_CONFIG=%BUILD_CONFIG% -echo BUILD_PUBLICSIGN=%BUILD_PUBLICSIGN% -echo BUILD_MICROBUILD=%BUILD_MICROBUILD% -echo BUILD_FROMSOURCE=%BUILD_FROMSOURCE% -echo BUILD_FSHARP_PROJ=%BUILD_FSHARP_PROJ% -echo. -echo PB_SKIPTESTS=%PB_SKIPTESTS% -echo PB_RESTORESOURCE=%PB_RESTORESOURCE% -echo. -echo SIGN_TYPE=%SIGN_TYPE% -echo. -echo COPY_FSCOMP_RESOURCE_FOR_BUILD_FROM_SOURCES=%COPY_FSCOMP_RESOURCE_FOR_BUILD_FROM_SOURCES% -echo. -echo TEST_FCS=%TEST_FCS% -echo TEST_NET40_COMPILERUNIT_SUITE=%TEST_NET40_COMPILERUNIT_SUITE% -echo TEST_NET40_COREUNIT_SUITE=%TEST_NET40_COREUNIT_SUITE% -echo TEST_NET40_FSHARP_SUITE=%TEST_NET40_FSHARP_SUITE% -echo TEST_NET40_FSHARPQA_SUITE=%TEST_NET40_FSHARPQA_SUITE% -echo TEST_CORECLR_COREUNIT_SUITE=%TEST_CORECLR_COREUNIT_SUITE% -echo TEST_CORECLR_FSHARP_SUITE=%TEST_CORECLR_FSHARP_SUITE% -echo TEST_VS_IDEUNIT_SUITE=%TEST_VS_IDEUNIT_SUITE% -echo INCLUDE_TEST_TAGS=%INCLUDE_TEST_TAGS% -echo TEMP=%TEMP% - -:: load Visual Studio 2017 developer command prompt if VS150COMNTOOLS is not set - -:: If this is not set, VsDevCmd.bat will change %cd% to [USERPROFILE]\source, causing the build to fail. -SET VSCMD_START_DIR=%cd% - -:: Try find installation path of VS2017 with vswhere.exe -if "%VS150COMNTOOLS%" EQU "" if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\" ( - for /f "usebackq delims=" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -prerelease -property installationPath`) do set VS_INSTALLATION_PATH=%%i -) - -if "%VS_INSTALLATION_PATH%" NEQ "" ( - call "%VS_INSTALLATION_PATH%\Common7\Tools\VsDevCmd.bat" -) - -:: If there's no installation of VS2017 or VS2017 Preview, use the build tools -if "%VS150COMNTOOLS%" EQU "" if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\BuildTools\Common7\Tools\VsDevCmd.bat" ( - call "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\BuildTools\Common7\Tools\VsDevCmd.bat" -) - -echo. -echo Environment -set -echo. -echo. - -echo ---------------- Done with arguments, starting preparation ----------------- -rem set TargetFrameworkSDKToolsDirectory --- needed for sdk to find al.exe. -if not "%TargetFrameworkSDKToolsDirectory%" == "" ( goto have_TargetFrameworkSDKToolsDirectory ) -set TargetFrameworkSDKToolsDirectory=%WindowsSDK_ExecutablePath_x64% - -if not "%TargetFrameworkSDKToolsDirectory%" == "" ( goto have_TargetFrameworkSDKToolsDirectory ) -set TargetFrameworkSDKToolsDirectory=%WindowsSDK_ExecutablePath_x86% - -:have_TargetFrameworkSDKToolsDirectory - -if "%RestorePackages%"=="" ( - set RestorePackages=true -) - -@echo VSSDKToolsPath: %VSSDKToolsPath% -@echo VSSDKIncludes: %VSSDKIncludes% -@echo TargetFrameworkSDKToolsDirectory: %TargetFrameworkSDKToolsDirectory% - -@call src\update.cmd signonly - -:: Check prerequisites -if not "%VisualStudioVersion%" == "" goto vsversionset -if exist "%VS160COMNTOOLS%\..\ide\devenv.exe" set VisualStudioVersion=16.0 -if not "%VisualStudioVersion%" == "" goto vsversionset - -if not "%VisualStudioVersion%" == "" goto vsversionset -if exist "%VS150COMNTOOLS%\..\ide\devenv.exe" set VisualStudioVersion=15.0 -if not "%VisualStudioVersion%" == "" goto vsversionset - -if not "%VisualStudioVersion%" == "" goto vsversionset -if exist "%VS150COMNTOOLS%\..\..\ide\devenv.exe" set VisualStudioVersion=15.0 -if not "%VisualStudioVersion%" == "" goto vsversionset - -if exist "%VS140COMNTOOLS%\..\ide\devenv.exe" set VisualStudioVersion=14.0 -if exist "%ProgramFiles(x86)%\Microsoft Visual Studio 14.0\common7\ide\devenv.exe" set VisualStudioVersion=14.0 -if exist "%ProgramFiles%\Microsoft Visual Studio 14.0\common7\ide\devenv.exe" set VisualStudioVersion=14.0 -if not "%VisualStudioVersion%" == "" goto vsversionset - -if exist "%VS120COMNTOOLS%\..\ide\devenv.exe" set VisualStudioVersion=12.0 -if exist "%ProgramFiles(x86)%\Microsoft Visual Studio 12.0\common7\ide\devenv.exe" set VisualStudioVersion=12.0 -if exist "%ProgramFiles%\Microsoft Visual Studio 12.0\common7\ide\devenv.exe" set VisualStudioVersion=12.0 - -:vsversionset -if "%VisualStudioVersion%" == "" echo Error: Could not find an installation of Visual Studio && goto :failure - -if exist "%VS160COMNTOOLS%\..\..\MSBuild\Current\Bin\MSBuild.exe" ( - set _msbuildexe="%VS160COMNTOOLS%\..\..\MSBuild\Current\Bin\MSBuild.exe" - goto :havemsbuild -) -if exist "%VS150COMNTOOLS%\..\..\MSBuild\15.0\Bin\MSBuild.exe" ( - set _msbuildexe="%VS150COMNTOOLS%\..\..\MSBuild\15.0\Bin\MSBuild.exe" - goto :havemsbuild -) -if exist "%ProgramFiles(x86)%\MSBuild\%VisualStudioVersion%\Bin\MSBuild.exe" ( - set _msbuildexe="%ProgramFiles(x86)%\MSBuild\%VisualStudioVersion%\Bin\MSBuild.exe" - goto :havemsbuild -) -if exist "%ProgramFiles%\MSBuild\%VisualStudioVersion%\Bin\MSBuild.exe" ( - set _msbuildexe="%ProgramFiles%\MSBuild\%VisualStudioVersion%\Bin\MSBuild.exe" - goto :havemsbuild -) -echo Error: Could not find MSBuild.exe. && goto :failure -goto :eof - -:havemsbuild -set _nrswitch=/nr:false - -set msbuildflags=%_nrswitch% /nologo /clp:Summary /v:minimal -set _ngenexe="%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\ngen.exe" -if not exist %_ngenexe% echo Error: Could not find ngen.exe. && goto :failure - -echo ---------------- Done with prepare, starting package restore ---------------- - -:: Restore the Tools directory -call "%~dp0init-tools.cmd" -set _dotnetexe=%~dp0artifacts\toolset\dotnet\dotnet.exe -set path=%~dp0artifacts\toolset\dotnet;%path% - -if not "%PB_PackageVersionPropsUrl%" == "" ( - echo ----------- do dependency uptake check ----------- - - set dependencyUptakeDir=%~dp0artifacts\dependencyUptake - if not exist "!dependencyUptakeDir!" mkdir "!dependencyUptakeDir!" - - :: download package version overrides - echo powershell -noprofile -executionPolicy RemoteSigned -command "Invoke-WebRequest -Uri '%PB_PackageVersionPropsUrl%' -OutFile '!dependencyUptakeDir!\PackageVersions.props'" - powershell -noprofile -executionPolicy RemoteSigned -command "Invoke-WebRequest -Uri '%PB_PackageVersionPropsUrl%' -OutFile '!dependencyUptakeDir!\PackageVersions.props'" - if ERRORLEVEL 1 echo Error downloading package version properties && goto :failure -) - -if "%RestorePackages%" == "true" ( - if "%BUILD_FCS%" == "1" ( - cd fcs - .paket\paket.exe restore - cd.. - @if ERRORLEVEL 1 echo Error: Paket restore failed && goto :failure - ) -) - -echo ---------------- Done with package restore, verify buildfrom source --------------- -if "%BUILD_PROTO_WITH_CORECLR_LKG%" == "1" ( - pushd src - call buildfromsource.cmd - @if ERRORLEVEL 1 echo Error: buildfromsource.cmd failed && goto :failure - popd -) - -echo ---------------- Done with package restore, starting proto ------------------------ -set logdir=%~dp0artifacts\log\%BUILD_CONFIG% -if not exist "!logdir!" mkdir "!logdir!" - -rem Build Proto -if "%BUILD_PROTO%" == "1" ( - rmdir /s /q artifacts/bin/fsc/Proto - - echo %_msbuildexe% proto.proj /t:Restore /bl:%~dp0artifacts\log\Proto\proto.proj.restore.binlog - %_msbuildexe% proto.proj /t:Restore /bl:%~dp0artifacts\log\Proto\proto.proj.restore.binlog - @if ERRORLEVEL 1 echo Error restoring proto failed && goto :failure - - echo %_msbuildexe% proto.proj /t:Build /bl:%~dp0artifacts\log\Proto\proto.proj.build.binlog - %_msbuildexe% proto.proj /t:Build /bl:%~dp0artifacts\log\Proto\proto.proj.build.binlog - @if ERRORLEVEL 1 echo Error building proto failed && goto :failure -) - -echo ---------------- Done with SDK restore, starting build ------------------------ - -if "%BUILD_PHASE%" == "1" if "%BUILD_FSHARP_PROJ%" == "1" ( - - echo %_dotnetexe% restore fsharp.proj /p:Configuration=%BUILD_CONFIG% /bl:!logdir!\fsharp.proj.restore.binlog - %_dotnetexe% restore fsharp.proj /p:Configuration=%BUILD_CONFIG% /bl:!logdir!\fsharp.proj.restore.binlog - - echo %_msbuildexe% fsharp.proj /t:Build /p:Configuration=%BUILD_CONFIG% /p:BUILD_PUBLICSIGN=%BUILD_PUBLICSIGN% /bl:!logdir!\fsharp.proj.build.binlog - %_msbuildexe% fsharp.proj /t:Build /p:Configuration=%BUILD_CONFIG% /p:BUILD_PUBLICSIGN=%BUILD_PUBLICSIGN% /bl:!logdir!\fsharp.proj.build.binlog - - @if ERRORLEVEL 1 echo Error build failed && goto :failure -) - -echo ---------------- Done with build, starting assembly version checks --------------- -set asmvercheckpath=%~dp0tests\fsharpqa\testenv\src\AssemblyVersionCheck - -if "%BUILD_NET40%" == "1" ( - echo #r @"%USERPROFILE%\.nuget\packages\Newtonsoft.Json\9.0.1\lib\net45\Newtonsoft.Json.dll">%asmvercheckpath%\assemblies.fsx - echo "%~dp0artifacts\bin\fsi\%BUILD_CONFIG%\net46\fsi.exe" "%asmvercheckpath%\AssemblyVersionCheck.fsx" -- "%~dp0build\config\AssemblySignToolData.json" "%~dp0artifacts" - "%~dp0artifacts\bin\fsi\%BUILD_CONFIG%\net46\fsi.exe" "%asmvercheckpath%\AssemblyVersionCheck.fsx" -- "%~dp0build\config\AssemblySignToolData.json" "%~dp0artifacts" - if ERRORLEVEL 1 echo Error verifying assembly versions and commit hashes. && goto :failure -) - -echo ---------------- Done with assembly version checks, starting assembly signing --------------- - -if not "%SIGN_TYPE%" == "" ( - echo %_msbuildexe% build\projects\Signing.proj /t:Restore - %_msbuildexe% build\projects\Signing.proj /t:Restore - - echo %_msbuildexe% build\projects\Signing.proj /t:DoSigning /p:SignType=%SIGN_TYPE% /p:Configuration=%BUILD_CONFIG% /p:BinaryBasePath=%~dp0artifacts /p:ConfigFile=%~dp0build\config\AssemblySignToolData.json - %_msbuildexe% build\projects\Signing.proj /t:DoSigning /p:SignType=%SIGN_TYPE% /p:Configuration=%BUILD_CONFIG% /p:BinaryBasePath=%~dp0artifacts /p:ConfigFile=%~dp0build\config\AssemblySignToolData.json - - if ERRORLEVEL 1 echo Error running sign tool && goto :failure -) - -if not "%SIGN_TYPE%" == "" ( - echo %_msbuildexe% build\projects\Signing.proj /t:DoSigning /p:SignType=%SIGN_TYPE% /p:Configuration=%BUILD_CONFIG% /p:BinaryBasepath=%~dp0artifacts\packages\%BUILD_CONFIG% /p:ConfigFile=%~dp0build\config\PackageSignToolData.json - %_msbuildexe% build\projects\Signing.proj /t:DoSigning /p:SignType=%SIGN_TYPE% /p:Configuration=%BUILD_CONFIG% /p:BinaryBasepath=%~dp0artifacts\packages\%BUILD_CONFIG% /p:ConfigFile=%~dp0build\config\PackageSignToolData.json - if ERRORLEVEL 1 echo Error running sign tool && goto :failure -) - -if "%BUILD_SETUP%" == "1" ( - echo %_msbuildexe% %msbuildflags% setup\build-insertion.proj /p:Configuration=%BUILD_CONFIG% /bl:!logdir!\msbuild.build-insertion.build.%BUILD_CONFIG%.binlog - %_msbuildexe% %msbuildflags% setup\build-insertion.proj /p:Configuration=%BUILD_CONFIG% /bl:!logdir!\msbuild.build-insertion.build.%BUILD_CONFIG%.binlog - if ERRORLEVEL 1 echo Error building insertion packages && goto :failure -) - -if not "%SIGN_TYPE%" == "" ( - echo %_msbuildexe% build\projects\Signing.proj /t:DoSigning /p:SignType=%SIGN_TYPE% /p:Configuration=%BUILD_CONFIG% /p:BinaryBasepath=%~dp0artifacts\VSSetup\%BUILD_CONFIG%\Insertion /p:ConfigFile=%~dp0build\config\InsertionSignToolData.json - %_msbuildexe% build\projects\Signing.proj /t:DoSigning /p:SignType=%SIGN_TYPE% /p:Configuration=%BUILD_CONFIG% /p:BinaryBasePath=%~dp0artifacts\VSSetup\%BUILD_CONFIG%\Insertion /p:ConfigFile=%~dp0build\config\InsertionSignToolData.json - if ERRORLEVEL 1 echo Error running sign tool && goto :failure -) - -echo ---------------- Done with signing, building insertion files --------------- - -if "%BUILD_SETUP%" == "1" ( - echo %_msbuildexe% %msbuildflags% setup\Swix\Microsoft.FSharp.vsmanproj /p:Configuration=%BUILD_CONFIG% /bl:!logdir!\msbuild.setup-swix.build.%BUILD_CONFIG%.binlog - %_msbuildexe% %msbuildflags% setup\Swix\Microsoft.FSharp.vsmanproj /p:Configuration=%BUILD_CONFIG% /bl:!logdir!\msbuild.setup-swix.build.%BUILD_CONFIG%.binlog - if ERRORLEVEL 1 echo Error building .vsmanproj && goto :failure -) - -echo ---------------- Done building insertion files, starting pack/update/prepare --------------- - -set X86_PROGRAMFILES=%ProgramFiles% -if "%OSARCH%"=="AMD64" set X86_PROGRAMFILES=%ProgramFiles(x86)% - -set SYSWOW64=. -if "%OSARCH%"=="AMD64" set SYSWOW64=SysWoW64 - -if not "%OSARCH%"=="x86" set REGEXE32BIT=%WINDIR%\syswow64\reg.exe - -echo SDK environment vars from Registry -echo ================================== - -for /d %%i in (%WINDIR%\Microsoft.NET\Framework\v4.0.?????) do set CORDIR=%%i -set PATH=%PATH%;%CORDIR% - -set REGEXE32BIT=reg.exe - -IF NOT DEFINED SNEXE32 IF EXIST "%WINSDKNETFXTOOLS%\sn.exe" set SNEXE32=%WINSDKNETFXTOOLS%sn.exe -IF NOT DEFINED SNEXE64 IF EXIST "%WINSDKNETFXTOOLS%x64\sn.exe" set SNEXE64=%WINSDKNETFXTOOLS%x64\sn.exe - -echo. -echo SDK environment vars -echo ======================= -echo WINSDKNETFXTOOLS: %WINSDKNETFXTOOLS% -echo SNEXE32: %SNEXE32% -echo SNEXE64: %SNEXE64% -echo - -if "%TEST_NET40_COMPILERUNIT_SUITE%" == "0" if "%TEST_FCS%" == "0" if "%TEST_NET40_COREUNIT_SUITE%" == "0" if "TEST_CORECLR_FSHARP_SUITE" == "0" if "%TEST_CORECLR_COREUNIT_SUITE%" == "0" if "%TEST_VS_IDEUNIT_SUITE%" == "0" if "%TEST_NET40_FSHARP_SUITE%" == "0" if "%TEST_NET40_FSHARPQA_SUITE%" == "0" goto :success - -if "%no_test%" == "1" goto :success - -echo ---------------- Done with update, starting tests ----------------------- - -if NOT "%INCLUDE_TEST_TAGS%" == "" ( - set TTAGS_ARG_RUNALL=-ttags:%INCLUDE_TEST_TAGS% -) - -set link_exe=%~dp0tests\fsharpqa\testenv\bin\link\link.exe -if not exist "%link_exe%" ( - echo Error: failed to find "%link_exe%" use nuget to restore the VisualCppTools package - goto :failure -) - -if /I not "%single_threaded%" == "true" (set PARALLEL_ARG=-procs:%NUMBER_OF_PROCESSORS%) else set PARALLEL_ARG=-procs:0 - -set FSCBINPATH=%~dp0artifacts\bin\fsc\%BUILD_CONFIG%\net46 -set FSIANYCPUBINPATH=%~dp0artifacts\bin\fsiAnyCpu\%BUILD_CONFIG%\net46 -set FSIBINPATH=%~dp0artifacts\bin\fsi\%BUILD_CONFIG%\net46 - -ECHO FSCBINPATH=%FSCBINPATH% -ECHO FSIANYCPUBINPATH=%FSIANYCPUBINPATH% -ECHO FSIBINPATH=%FSIBINPATH% -ECHO link_exe=%link_exe% - -REM ---------------- test-net40-fsharp ----------------------- - -set TESTLOGDIR=%~dp0artifacts\TestResults\%BUILD_CONFIG% -if "%TEST_NET40_FSHARP_SUITE%" == "1" ( - - set LOGFILE=%TESTLOGDIR%\FSharp.Tests.FSharpSuite_net46.trx - echo "%_dotnetexe%" test "%~dp0tests\fsharp\FSharp.Tests.FSharpSuite.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0tests\fsharp\FSharp.Tests.FSharpSuite.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo -------------------------------------------------------------- - echo Error: Running tests net40-fsharp failed, see file `!LOGFILE!` - echo -------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) -) - -REM ---------------- test-fcs ----------------------- - -if "%TEST_FCS%" == "1" ( - - set LOGFILE=%TESTLOGDIR%\FSharp.Compiler.Service.Tests_net46.trx - echo "%_dotnetexe%" test "%~dp0fcs\FSharp.Compiler.Service.Tests\FSharp.Compiler.Service.Tests.fsproj" -s "%~dp0fcs\FSharp.Compiler.Service.Tests\app.runsettings" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0fcs\FSharp.Compiler.Service.Tests\FSharp.Compiler.Service.Tests.fsproj" -s "%~dp0fcs\FSharp.Compiler.Service.Tests\app.runsettings" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo -------------------------------------------------------------- - echo Error: Running net40 fcs tests, see file `!LOGFILE!` - echo -------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) - - set LOGFILE=%TESTLOGDIR%\FSharp.Compiler.Service.Tests_netcoreapp2.0.trx - echo "%_dotnetexe%" test "%~dp0fcs\FSharp.Compiler.Service.Tests\FSharp.Compiler.Service.Tests.fsproj" -s "%~dp0fcs\FSharp.Compiler.Service.Tests\app.runsettings" --no-restore --no-build -c %BUILD_CONFIG% -f netcoreapp2.0 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0fcs\FSharp.Compiler.Service.Tests\FSharp.Compiler.Service.Tests.fsproj" -s "%~dp0fcs\FSharp.Compiler.Service.Tests\app.runsettings" --no-restore --no-build -c %BUILD_CONFIG% -f netcoreapp2.0 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo -------------------------------------------------------------- - echo Error: Running coreclr fcs tests, see file `!LOGFILE!` - echo -------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) -) - -REM ---------------- end2end ----------------------- -if "%TEST_END_2_END%" == "1" ( - - pushd %~dp0tests\EndToEndBuildTests - - echo Execute end to end compiler tests - echo call EndToEndBuildTests.cmd - call EndToEndBuildTests.cmd - if errorlevel 1 ( - popd - Echo end to end tests failed. - goto :failure - ) -) - -REM ---------------- net40-fsharpqa ----------------------- - -set OSARCH=%PROCESSOR_ARCHITECTURE% - -rem Set this to 1 in order to use an external compiler host process -rem This only has an effect when running the FSHARPQA tests, but can -rem greatly speed up execution since fsc.exe does not need to be spawned thousands of times -set HOSTED_COMPILER=1 - -if "%TEST_NET40_FSHARPQA_SUITE%" == "1" ( - - set CSC_PIPE=%USERPROFILE%\.nuget\packages\Microsoft.Net.Compilers\2.7.0\tools\csc.exe - set FSC=!FSCBINPATH!\fsc.exe - set FSI=!FSIBINPATH!\fsi.exe - set FSIANYCPU=!FSIANYCPUBINPATH!\fsi.exe - set FSCOREDLLPATH=!FSCBinPath!\FSharp.Core.dll - set PATH=!FSCBINPATH!;!FSIBINPATH!;!FSIANYCPUBINPATH!;!PATH! - set perlexe=%USERPROFILE%\.nuget\packages\StrawberryPerl64\5.22.2.1\Tools\perl\bin\perl.exe - if not exist !perlexe! (echo Error: perl was not downloaded from check the packages directory: !perlexe! && goto :failure ) - - set RESULTSDIR=%~dp0artifacts\TestResults\%BUILD_CONFIG% - set OUTPUTFILE=test-net40-fsharpqa-results.log - set ERRORFILE=test-net40-fsharpqa-errors.log - set FAILENV=test-net40-fsharpqa-errors - - pushd %~dp0tests\fsharpqa\source - echo !perlexe! %~dp0tests\fsharpqa\testenv\bin\runall.pl -resultsroot !RESULTSDIR! -results !OUTPUTFILE! -log !ERRORFILE! -fail !FAILENV! -cleanup:no !TTAGS_ARG_RUNALL! !PARALLEL_ARG! - !perlexe! %~dp0tests\fsharpqa\testenv\bin\runall.pl -resultsroot !RESULTSDIR! -results !OUTPUTFILE! -log !ERRORFILE! -fail !FAILENV! -cleanup:no !TTAGS_ARG_RUNALL! !PARALLEL_ARG! - - popd - if ERRORLEVEL 1 ( - echo ----------------------------------------------------------------- - type "!RESULTSDIR!\!OUTPUTFILE!" - echo ----------------------------------------------------------------- - type "!RESULTSDIR!\!ERRORFILE!" - echo ----------------------------------------------------------------- - echo Error: Running tests net40-fsharpqa failed, see logs above -- FAILED - echo ----------------------------------------------------------------- - goto :failure - ) -) - -REM ---------------- net40-compilerunit ----------------------- - -if "%TEST_NET40_COMPILERUNIT_SUITE%" == "1" ( - - set LOGFILE=%TESTLOGDIR%\FSharp.Compiler.UnitTests_net46.trx - echo "%_dotnetexe%" test "%~dp0tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo ----------------------------------------------------------------- - echo Error: Running tests net40-compilerunit failed, see file `!LOGFILE!` - echo ----------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) - - set LOGFILE=%TESTLOGDIR%\FSharp.Build.UnitTests_net46.trx - echo "%_dotnetexe%" test "%~dp0tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo ----------------------------------------------------------------- - echo Error: Running tests net40-compilernit failed, see file `!LOGFILE!` - echo ----------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) -) - -REM ---------------- net40-coreunit ----------------------- - -if "%TEST_NET40_COREUNIT_SUITE%" == "1" ( - - set LOGFILE=%TESTLOGDIR%\FSharp.Core.UnitTests_net46.trx - echo "%_dotnetexe%" test "%~dp0tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo ----------------------------------------------------------------- - echo Error: Running tests net40-coreunit failed, see file `!LOGFILE!` - echo ----------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) -) - -REM ---------------- coreclr-coreunit ----------------------- - -if "%TEST_CORECLR_COREUNIT_SUITE%" == "1" ( - - set LOGFILE=%TESTLOGDIR%\FSharp.Build.UnitTests_netcoreapp2.0.trx - echo "%_dotnetexe%" test "%~dp0tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f netcoreapp2.0 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f netcoreapp2.0 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo ----------------------------------------------------------------- - echo Error: Running tests coreclr-compilernit failed, see file `!LOGFILE!` - echo ----------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) - - set LOGFILE=%TESTLOGDIR%\FSharp.Core.UnitTests_netcoreapp2.0.trx - echo "%_dotnetexe%" test "%~dp0tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f netcoreapp2.0 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f netcoreapp2.0 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo ------------------------------------------------------------------ - echo Error: Running tests coreclr-coreunit failed, see file `!LOGFILE!` - echo ------------------------------------------------------------------ - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) -) - -REM ---------------- coreclr-fsharp ----------------------- - -if "%TEST_CORECLR_FSHARP_SUITE%" == "1" ( - set LOGFILE=%TESTLOGDIR%\FSharp.Tests.FSharpSuite_netcoreapp2.0.trx - echo "%_dotnetexe%" test "%~dp0tests\fsharp\FSharp.Tests.FSharpSuite.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f netcoreapp2.0 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0tests\fsharp\FSharp.Tests.FSharpSuite.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f netcoreapp2.0 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo ---------------------------------------------------------------- - echo Error: Running tests coreclr-fsharp failed, see file `!LOGFILE!` - echo ---------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) -) - -REM ---------------- vs-ideunit ----------------------- - -if "%TEST_VS_IDEUNIT_SUITE%" == "1" ( - set LOGFILE=%TESTLOGDIR%\GetTypesVSUnitTests_net46.trx - echo "%_dotnetexe%" test "%~dp0vsintegration\tests\GetTypesVSUnitTests\GetTypesVSUnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0vsintegration\tests\GetTypesVSUnitTests\GetTypesVSUnitTests.fsproj" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - - if errorlevel 1 ( - echo --------------------------------------------------------------------------- - echo Error: Running tests net40-gettypesvsunittests failed, see file `!LOGFILE!` - echo --------------------------------------------------------------------------- - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) - - set LOGFILE=%TESTLOGDIR%\VisualFSharp.UnitTests_net46.trx - echo "%_dotnetexe%" test "%~dp0vsintegration\tests\UnitTests\VisualFSharp.UnitTests.fsproj" -s "%~dp0vsintegration\tests\UnitTests\app.runsettings" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - "%_dotnetexe%" test "%~dp0vsintegration\tests\UnitTests\VisualFSharp.UnitTests.fsproj" -s "%~dp0vsintegration\tests\UnitTests\app.runsettings" --no-restore --no-build -c %BUILD_CONFIG% -f net46 -l "trx;LogFileName=!LOGFILE!" - if errorlevel 1 ( - echo ------------------------------------------------------------ - echo Error: Running tests vs-ideunit failed, see file `!LOGFILE!` - echo ------------------------------------------------------------ - goto :failure - ) - - if not exist "!LOGFILE!" ( - echo -------------------------------------------------------- - echo Test results file !LOGFILE! not found, ensure tests ran. - echo -------------------------------------------------------- - goto :failure - ) -) - -goto :success -REM ------ exit ------------------------------------- -:failure -endlocal -@echo -exit /b 1 - -:success -endlocal -exit /b 0 diff --git a/build.sh b/build.sh index 4e78c56091c..ed167ab24ac 100755 --- a/build.sh +++ b/build.sh @@ -1,3 +1,16 @@ -#!/bin/sh +#!/usr/bin/env bash -make Configuration=release +source="${BASH_SOURCE[0]}" + +# resolve $SOURCE until the file is no longer a symlink +while [[ -h $source ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done + +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" +"$scriptroot/eng/build.sh" --build $@ diff --git a/build/config/AssemblySignToolData.json b/build/config/AssemblySignToolData.json deleted file mode 100644 index 8e8aebed7d6..00000000000 --- a/build/config/AssemblySignToolData.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "sign": [ - { - "certificate": "Microsoft", - "strongName": "StrongName", - "values": [ - "bin\\FSharp.Core\\*\\*\\FSharp.Core.dll", - "bin\\FSharp.Core\\*\\*\\*\\FSharp.Core.resources.dll", - "bin\\FSharp.Build\\*\\*\\FSharp.Build.dll", - "bin\\FSharp.Build\\*\\*\\*\\FSharp.Build.resources.dll", - "bin\\FSharp.Compiler.Private\\*\\*\\FSharp.Compiler.Private.dll", - "bin\\FSharp.Compiler.Private\\*\\*\\*\\FSharp.Compiler.Private.resources.dll", - "bin\\FSharp.Compiler.Server.Shared\\*\\*\\FSharp.Compiler.Server.Shared.dll", - "bin\\FSharp.Compiler.Interactive.Settings\\*\\*\\FSharp.Compiler.Interactive.Settings.dll", - "bin\\FSharp.Compiler.Interactive.Settings\\*\\*\\*\\FSharp.Compiler.Interactive.Settings.resources.dll", - "bin\\fsc\\*\\*\\fsc.exe", - "bin\\fsi\\*\\*\\fsi.exe", - "bin\\fsiAnyCpu\\*\\*\\fsiAnyCpu.exe", - "bin\\FSharp.VS.FSI\\*\\*\\FSharp.VS.FSI.dll", - "bin\\FSharp.VS.FSI\\*\\*\\*\\FSharp.VS.FSI.resources.dll", - "bin\\FSharp.LanguageService.Base\\*\\*\\FSharp.LanguageService.Base.dll", - "bin\\FSharp.LanguageService.Base\\*\\*\\*\\FSharp.LanguageService.Base.resources.dll", - "bin\\FSharp.LanguageService\\*\\*\\FSharp.LanguageService.dll", - "bin\\FSharp.LanguageService\\*\\*\\*\\FSharp.LanguageService.resources.dll", - "bin\\FSharp.UIResources\\*\\*\\FSharp.UIResources.dll", - "bin\\FSharp.UIResources\\*\\*\\*\\FSharp.UIResources.resources.dll", - "bin\\FSharp.Editor\\*\\*\\FSharp.Editor.dll", - "bin\\FSharp.Editor\\*\\*\\*\\FSharp.Editor.resources.dll", - "bin\\FSharp.PatternMatcher\\*\\*\\FSharp.PatternMatcher.dll", - "bin\\FSharp.PropertiesPages\\*\\*\\FSharp.ProjectSystem.PropertyPages.dll", - "bin\\FSharp.PropertiesPages\\*\\*\\*\\FSharp.ProjectSystem.PropertyPages.resources.dll", - "bin\\ProjectSystem\\*\\*\\FSharp.ProjectSystem.FSharp.dll", - "bin\\ProjectSystem\\*\\*\\*\\FSharp.ProjectSystem.FSharp.resources.dll", - "bin\\ProjectSystem.Base\\*\\*\\FSharp.ProjectSystem.Base.dll", - "bin\\ProjectSystem.Base\\*\\*\\*\\FSharp.ProjectSystem.Base.resources.dll" - ] - }, - { - "certificate": "VsixSHA2", - "strongName": null, - "values": [ - "bin\\VisualFSharpFull\\*\\*\\VisualFSharpFull.vsix", - "bin\\VisualFSharpTemplates\\*\\*\\VisualFSharpTemplate.vsix", - "VSSetup\\*\\Insertion\\Microsoft.FSharp.Dependencies.vsix", - "VSSetup\\*\\Insertion\\Microsoft.FSharp.VSIX.Full.Resources.*.vsix" - ] - }, - { - "certificate": "NuGet", - "strongName": null, - "values": [ - "packages\\*\\*.nupkg" - ] - } - ], - "exclude": [ - "e_sqlite3.dll", - "FSharp.Core.UnitTests.dll", - "FSharp.Data.TypeProviders.dll", - "Microsoft.Build.dll", - "Microsoft.Build.Framework.dll", - "Microsoft.Build.Tasks.Core.dll", - "Microsoft.Build.Utilities.Core.dll", - "Newtonsoft.Json.dll", - "System.Collections.Immutable.dll", - "System.Reflection.Metadata.dll", - "System.ValueTuple.4.4.0.nupkg", - "System.ValueTuple.dll" - ] -} diff --git a/build/config/InsertionSignToolData.json b/build/config/InsertionSignToolData.json deleted file mode 100644 index d81579b12c9..00000000000 --- a/build/config/InsertionSignToolData.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "sign": [ - { - "certificate": "VsixSHA2", - "strongName": null, - "values": [ - "Microsoft.FSharp.Compiler.vsix", - "Microsoft.FSharp.Compiler.Resources.*.vsix", - "Microsoft.FSharp.Dependencies.vsix", - "Microsoft.FSharp.IDE.vsix", - "Microsoft.FSharp.SDK.vsix" - ] - } - ], - "exclude": [ - "fsc.exe", - "FSharp.Build.dll", - "FSharp.Build.resources.dll", - "FSharp.Core.dll", - "FSharp.Core.resources.dll", - "FSharp.Compiler.Private.dll", - "FSharp.Compiler.Private.resources.dll", - "FSharp.Compiler.Server.Shared.dll", - "FSharp.Compiler.Interactive.Settings.dll", - "FSharp.Compiler.Interactive.Settings.resources.dll", - "fsi.exe", - "fsiAnyCpu.exe", - "FSharp.Data.TypeProviders.dll", - "Microsoft.Build.dll", - "Microsoft.Build.Framework.dll", - "Microsoft.Build.Tasks.Core.dll", - "Microsoft.Build.Utilities.Core.dll", - "System.Collections.Immutable.dll", - "System.Reflection.Metadata.dll", - "System.ValueTuple.dll" - ] -} diff --git a/build/config/PackageSignToolData.json b/build/config/PackageSignToolData.json deleted file mode 100644 index bee55c6df1c..00000000000 --- a/build/config/PackageSignToolData.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "sign": [ - { - "certificate": "NuGet", - "strongName": null, - "values": [ - "*.nupkg" - ] - } - ], - "exclude": [ - "FSharp.Build.resources.dll", - "FSharp.Compiler.Interactive.Settings.resources.dll", - "FSharp.Compiler.Private.resources.dll", - "FSharp.Core.resources.dll", - "fsc.exe", - "FSharp.Build.dll", - "FSharp.Compiler.Interactive.Settings.dll", - "FSharp.Compiler.Private.dll", - "FSharp.Core.dll", - "FSharp.Core.UnitTests.dll", - "fsi.exe" - ] -} \ No newline at end of file diff --git a/build/projects/Directory.Build.props b/build/projects/Directory.Build.props deleted file mode 100644 index bb8eac309b1..00000000000 --- a/build/projects/Directory.Build.props +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/build/projects/Directory.Build.targets b/build/projects/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/build/projects/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/build/projects/Signing.proj b/build/projects/Signing.proj deleted file mode 100644 index 9e981e135ec..00000000000 --- a/build/projects/Signing.proj +++ /dev/null @@ -1,27 +0,0 @@ - - - - - net46 - $(NuGetPackageRoot)RoslynTools.SignTool\$(RoslynToolsSignToolPackageVersion)\tools\SignTool.exe - -msbuildPath "$(MSBuildBinPath)\msbuild.exe" -nugetPackagesPath "$(NuGetPackageRoot.TrimEnd('\'))" -config "$(ConfigFile)" - -testSign $(SignToolArgs) - -test $(SignToolArgs) - - - - - - - - - - - - - - - - - diff --git a/build/targets/AssemblyVersions.props b/build/targets/AssemblyVersions.props deleted file mode 100644 index d76ea06ec5f..00000000000 --- a/build/targets/AssemblyVersions.props +++ /dev/null @@ -1,62 +0,0 @@ - - - - - $([System.DateTime]::Now.ToString(yyyyMMdd.0)) - - $(BUILD_BUILDNUMBER.Replace(".DRAFT", "")) - - - <_Build_Year>$(BUILD_BUILDNUMBER.Substring(0, 4)) - <_Build_Month>$(BUILD_BUILDNUMBER.Substring(4, 2)) - <_Build_Day>$(BUILD_BUILDNUMBER.Substring(6, 2)) - <_Build_Number>$(BUILD_BUILDNUMBER.Substring(9)) - $(_Build_Year).$(_Build_Month).$(_Build_Day).$(_Build_Number) - - 4.5 - $(FSLanguageVersion) - $(FSCoreMajorVersion).4 - $(FSCoreMajorVersion).0.0 - $(FSCorePackageVersion).0 - - 10.2 - $(FSPackageMajorVersion).3 - $(FSPackageVersion).0 - - 15 - 9 - $(VSMajorVersion).0 - $(VSMajorVersion).$(VSMinorVersion).0.0 - - - $(BUILD_BUILDNUMBER.Split('.')[0].Substring(2)) - $(BUILD_BUILDNUMBER.Split('.')[1].PadLeft(2, '0')) - $(BuildTimeStamp_Date)$(BuildTimeStamp_Number) - $(VSAssemblyVersion.Split('.')[0]).$(VSAssemblyVersion.Split('.')[1]).$(BUILD_BUILDNUMBER) - 42.42.42.42 - $(BuildTimeStamp_Date)-$(BuildTimeStamp_Number) - - - - - - diff --git a/build/targets/CommonPackages.targets b/build/targets/CommonPackages.targets deleted file mode 100644 index dc21381a3a8..00000000000 --- a/build/targets/CommonPackages.targets +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/build/targets/ConvertPortablePdbs.targets b/build/targets/ConvertPortablePdbs.targets deleted file mode 100644 index 9d65dab2dc4..00000000000 --- a/build/targets/ConvertPortablePdbs.targets +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - $(SymStoreDirectory)\$(TargetFramework) - $(NuGetPackageRoot)Pdb2Pdb\$(Pdb2PdbPackageVersion)\tools\Pdb2Pdb.exe - "$(TargetPath)" /out "$(ConvertedPdbsDirectory)\$(TargetName).pdb" /srcsvrvar SRC_INDEX=public - - - - - - - - - $(TargetDir)\$(TargetName).pdb - - - - - - - diff --git a/build/targets/GenerateAssemblyAttributes.targets b/build/targets/GenerateAssemblyAttributes.targets deleted file mode 100644 index 7b747c9dd92..00000000000 --- a/build/targets/GenerateAssemblyAttributes.targets +++ /dev/null @@ -1,119 +0,0 @@ - - - - - false - - - - - $(IntermediateOutputPath)$(MSBuildProjectName).AssemblyLevelAttributes$(DefaultLanguageSourceExtension) - - - $(NoWarn);2003 - - - - - - - - - - - - - - - - $(FSCoreVersion) - - - $(FSProductVersion) - - - $(VSAssemblyVersion) - - $(IntermediateOutputPath)$(MSBuildProjectName).AssemblyVersion$(DefaultLanguageSourceExtension) - - - - <_UseWriteCodeFragmentHack Condition="'$(OS)' == 'Unix' and '$(Language)' == 'F#'">true - - - - <_AssemblyVersionAttributes Include="System.Reflection.AssemblyCompanyAttribute"> - <_Parameter1>Microsoft Corporation - - <_AssemblyVersionAttributes Include="System.Reflection.AssemblyCopyrightAttribute"> - <_Parameter1>© Microsoft Corporation. All Rights Reserved. - - <_AssemblyVersionAttributes Include="System.Reflection.AssemblyDescriptionAttribute"> - <_Parameter1>$(AssemblyName) - - <_AssemblyVersionAttributes Include="System.Reflection.AssemblyFileVersionAttribute"> - <_Parameter1>$(Build_FileVersion) - - <_AssemblyVersionAttributes Include="System.Reflection.AssemblyInformationalVersionAttribute"> - <_Parameter1>$(MicroBuildAssemblyVersion). Commit Hash: $(GitHeadSha). - - <_AssemblyVersionAttributes Include="System.Reflection.AssemblyProductAttribute"> - <_Parameter1>Microsoft® F# - - <_AssemblyVersionAttributes Include="System.Reflection.AssemblyTitleAttribute"> - <_Parameter1>$(AssemblyName) - - <_AssemblyVersionAttributes Include="System.Reflection.AssemblyVersionAttribute"> - <_Parameter1>$(MicroBuildAssemblyVersion) - - - - - - - - - - - - - - - - - <_LinesToWrite Include="// <auto-generated>" /> - <_LinesToWrite Include="namespace FSharp" /> - <_LinesToWrite Include="open System" /> - <_LinesToWrite Include="open System.Reflection" /> - <_LinesToWrite Include="[<assembly: %(_AssemblyVersionAttributes.Identity)("%(_AssemblyVersionAttributes._Parameter1)")>]" /> - <_LinesToWrite Include="do()" /> - - - - - - - - - - - diff --git a/build/targets/GenerateInternalsVisibleTo.targets b/build/targets/GenerateInternalsVisibleTo.targets deleted file mode 100644 index 4950837d36a..00000000000 --- a/build/targets/GenerateInternalsVisibleTo.targets +++ /dev/null @@ -1,80 +0,0 @@ - - - - $(IntermediateOutputPath)$(MSBuildProjectName).InternalsVisibleTo$(DefaultLanguageSourceExtension) - - - - - false - - - - - - <_PublicKey>002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293 - - - <_PublicKey>002400000480000094000000060200000024000052534131000400000100010077d32e043d184cf8cebf177201ec6fad091581a3a639a0534f1c4ebb3ab847a6b6636990224a04cf4bd1aec51ecec44cf0c8922eb5bb2ee65ec3fb9baa87e141042c96ce414f98af33508c7e24dab5b068aa802f6693881537ee0efcb5d3f1c9aaf8215ac42e92ba9a5a02574d6890d07464cb2f338b043b1c4ffe98efe069ee - - - <_InternalsVisibleToAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute"> - <_Parameter1 Condition="'%(InternalsVisibleTo.Key)' != ''">%(InternalsVisibleTo.Identity), PublicKey=%(InternalsVisibleTo.Key) - <_Parameter1 Condition="'%(InternalsVisibleTo.Key)' == ''">%(InternalsVisibleTo.Identity), PublicKey=$(_PublicKey) - - - - - - - - - <_UseWriteCodeFragmentHack Condition="'$(OS)' == 'Unix' and '$(Language)' == 'F#'">true - - - - - - - - - - - - - <_LinesToWrite Include="// <auto-generated>" /> - <_LinesToWrite Include="namespace FSharp" /> - <_LinesToWrite Include="open System" /> - <_LinesToWrite Include="open System.Reflection" /> - <_LinesToWrite Include="[<assembly: %(_InternalsVisibleToAttribute.Identity)("%(_InternalsVisibleToAttribute._Parameter1)")>]" /> - <_LinesToWrite Include="do()" /> - - - - - - - - - diff --git a/build/targets/GitHash.props b/build/targets/GitHash.props deleted file mode 100644 index 30f2d03b915..00000000000 --- a/build/targets/GitHash.props +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - $(MSBuildThisFileDirectory)..\..\ - - - - - - $(BUILD_SOURCEVERSION) - - - - - - $(GIT_COMMIT) - - - - - - <developer build> - - - - - - - <_DotGitDir>$(RepoRoot).git - <_HeadFileContent Condition="Exists('$(_DotGitDir)/HEAD')">$([System.IO.File]::ReadAllText('$(_DotGitDir)/HEAD').Trim()) - <_RefPath Condition="$(_HeadFileContent.StartsWith('ref: '))">$(_DotGitDir)/$(_HeadFileContent.Substring(5)) - $([System.IO.File]::ReadAllText('$(_RefPath)').Trim()) - $(_HeadFileContent) - - - - - diff --git a/build/targets/NGenOrCrossGen.targets b/build/targets/NGenOrCrossGen.targets deleted file mode 100644 index 3dba4fc5b2d..00000000000 --- a/build/targets/NGenOrCrossGen.targets +++ /dev/null @@ -1,36 +0,0 @@ - - - - - $(windir)\Microsoft.NET\Framework64\v4.0.30319\ngen.exe - $(windir)\Microsoft.NET\Framework\v4.0.30319\ngen.exe - - - - - - - - - - - - - - - - true - false - - - - diff --git a/eng/Build.ps1 b/eng/Build.ps1 new file mode 100644 index 00000000000..ffa7b6d788a --- /dev/null +++ b/eng/Build.ps1 @@ -0,0 +1,286 @@ +# +# This script controls the F# build process. This encompasess everything from build, testing to +# publishing of NuGet packages. The intent is to structure it to allow for a simple flow of logic +# between the following phases: +# +# - restore +# - build +# - sign +# - pack +# - test +# - publish +# +# Each of these phases has a separate command which can be executed independently. For instance +# it's fine to call `build.ps1 -build -testDesktop` followed by repeated calls to +# `.\build.ps1 -testDesktop`. + +[CmdletBinding(PositionalBinding=$false)] +param ( + [string][Alias('c')]$configuration = "Debug", + [string][Alias('v')]$verbosity = "m", + [string]$msbuildEngine = "vs", + + # Actions + [switch][Alias('r')]$restore, + [switch][Alias('b')]$build, + [switch]$rebuild, + [switch]$sign, + [switch]$pack, + [switch]$publish, + [switch]$launch, + [switch]$help, + + # Options + [switch][Alias('proto')]$bootstrap, + [string]$bootstrapConfiguration = "Proto", + [string]$bootstrapTfm = "net46", + [switch][Alias('bl')]$binaryLog, + [switch]$ci, + [switch]$official, + [switch]$procdump, + [switch]$deployExtensions, + [switch]$prepareMachine, + [switch]$useGlobalNuGetCache = $true, + [switch]$warnAsError = $true, + [switch][Alias('test')]$testDesktop, + [switch]$testCoreClr, + [switch]$testFSharpQA, + [switch]$testVs, + [switch]$testAll, + + [parameter(ValueFromRemainingArguments=$true)][string[]]$properties) + +Set-StrictMode -version 2.0 +$ErrorActionPreference = "Stop" + +function Print-Usage() { + Write-Host "Common settings:" + Write-Host " -configuration Build configuration: 'Debug' or 'Release' (short: -c)" + Write-Host " -verbosity Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]" + Write-Host " -deployExtensions Deploy built vsixes" + Write-Host " -binaryLog Create MSBuild binary log (short: -bl)" + Write-Host "" + Write-Host "Actions:" + Write-Host " -restore Restore packages (short: -r)" + Write-Host " -build Build main solution (short: -b)" + Write-Host " -rebuild Rebuild main solution" + Write-Host " -pack Build NuGet packages, VS insertion manifests and installer" + Write-Host " -sign Sign our binaries" + Write-Host " -publish Publish build artifacts (e.g. symbols)" + Write-Host " -launch Launch Visual Studio in developer hive" + Write-Host " -help Print help and exit" + Write-Host "" + Write-Host "Test actions" + Write-Host " -testAll Run all tests" + Write-Host " -testDesktop Run tests against full .NET Framework" + Write-Host " -testCoreClr Run tests against CoreCLR" + Write-Host " -testFSharpQA Run F# Cambridge tests" + Write-Host " -testVs Run F# editor unit tests" + Write-Host "" + Write-Host "Advanced settings:" + Write-Host " -ci Set when running on CI server" + Write-Host " -official Set when building an official build" + Write-Host " -bootstrap Build using a bootstrap compiler" + Write-Host " -msbuildEngine Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." + Write-Host " -procdump Monitor test runs with procdump" + Write-Host " -prepareMachine Prepare machine for CI run, clean up processes after build" + Write-Host " -useGlobalNuGetCache Use global NuGet cache." + Write-Host "" + Write-Host "Command line arguments starting with '/p:' are passed through to MSBuild." +} + +# Process the command line arguments and establish defaults for the values which are not +# specified. +function Process-Arguments() { + if ($help -or (($properties -ne $null) -and ($properties.Contains("/help") -or $properties.Contains("/?")))) { + Print-Usage + exit 0 + } + + if ($testAll) { + $script:testDesktop = $True + $script:testCoreClr = $True + $script:testFSharpQA = $True + $script:testVs = $True + } + + foreach ($property in $properties) { + if (!$property.StartsWith("/p:", "InvariantCultureIgnoreCase")) { + Write-Host "Invalid argument: $property" + Print-Usage + exit 1 + } + } +} + +function Update-Arguments() { + if (-Not (Test-Path "$ArtifactsDir\Bootstrap\fsc.exe")) { + $script:bootstrap = $True + } +} + +function BuildSolution() { + # VisualFSharp.sln can't be built with dotnet due to WPF, WinForms and VSIX build task dependencies + $solution = "VisualFSharp.sln" + + Write-Host "$($solution):" + + $bl = if ($binaryLog) { "/bl:" + (Join-Path $LogDir "Build.binlog") } else { "" } + $projects = Join-Path $RepoRoot $solution + $officialBuildId = if ($official) { $env:BUILD_BUILDNUMBER } else { "" } + $toolsetBuildProj = InitializeToolset + $quietRestore = !$ci + $testTargetFrameworks = if ($testCoreClr) { "netcoreapp2.1" } else { "" } + + # Do not set the property to true explicitly, since that would override value projects might set. + $suppressExtensionDeployment = if (!$deployExtensions) { "/p:DeployExtension=false" } else { "" } + + MSBuild $toolsetBuildProj ` + $bl ` + /p:Configuration=$configuration ` + /p:Projects=$projects ` + /p:RepoRoot=$RepoRoot ` + /p:Restore=$restore ` + /p:Build=$build ` + /p:Rebuild=$rebuild ` + /p:Pack=$pack ` + /p:Sign=$sign ` + /p:Publish=$publish ` + /p:ContinuousIntegrationBuild=$ci ` + /p:OfficialBuildId=$officialBuildId ` + /p:BootstrapBuildPath=$bootstrapDir ` + /p:QuietRestore=$quietRestore ` + /p:QuietRestoreBinaryLog=$binaryLog ` + /p:TestTargetFrameworks=$testTargetFrameworks ` + $suppressExtensionDeployment ` + @properties +} + +function TestAndAddToPath([string] $testPath) { + if (Test-Path $testPath) { + $env:PATH = "$testPath;$env:PATH" + Write-Host "Added [$testPath] to the path." + } +} + +function UpdatePath() { + # add highest framework dir + $subdir = "" + foreach ($child in Get-ChildItem "$env:WINDIR\Microsoft.NET\Framework\v4.0.?????") { + $subdir = $child + } + TestAndAddToPath $subdir + + # add windows SDK dir for ildasm.exe + foreach ($child in Get-ChildItem "${env:ProgramFiles(x86)}\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.?.? Tools") { + $subdir = $child + } + TestAndAddToPath $subdir + + TestAndAddToPath "$ArtifactsDir\bin\fsc\$configuration\net46" + TestAndAddToPath "$ArtifactsDir\bin\fsiAnyCpu\$configuration\net46" +} + +function VerifyAssemblyVersions() { + $fsiPath = Join-Path $ArtifactsDir "bin\fsi\$configuration\net46\fsi.exe" + + # desktop fsi isn't always built + if (Test-Path $fsiPath) { + $asmVerCheckPath = "$RepoRoot\scripts" + Exec-Console $fsiPath """$asmVerCheckPath\AssemblyVersionCheck.fsx"" -- ""$ArtifactsDir""" + } +} + +function TestUsingNUnit([string] $testProject, [string] $targetFramework) { + $dotnetPath = InitializeDotNetCli + $dotnetExe = Join-Path $dotnetPath "dotnet.exe" + $projectName = [System.IO.Path]::GetFileNameWithoutExtension($testProject) + $testLogPath = "$ArtifactsDir\TestResults\$configuration\${projectName}_$targetFramework.xml" + $testBinLogPath = "$LogDir\${projectName}_$targetFramework.binlog" + $args = "test $testProject --no-restore --no-build -c $configuration -f $targetFramework -v n --test-adapter-path . --logger ""nunit;LogFilePath=$testLogPath"" /bl:$testBinLogPath" + Exec-Console $dotnetExe $args +} + +function Prepare-TempDir() { + Copy-Item (Join-Path $RepoRoot "tests\Resources\Directory.Build.props") $TempDir + Copy-Item (Join-Path $RepoRoot "tests\Resources\Directory.Build.targets") $TempDir +} + +try { + Process-Arguments + + . (Join-Path $PSScriptRoot "build-utils.ps1") + + Update-Arguments + + Push-Location $RepoRoot + + if ($ci) { + Prepare-TempDir + } + + if ($bootstrap) { + $bootstrapDir = Make-BootstrapBuild + } + + if ($restore -or $build -or $rebuild -or $pack -or $sign -or $publish) { + BuildSolution + } + + if ($build) { + VerifyAssemblyVersions + } + + $desktopTargetFramework = "net46" + $coreclrTargetFramework = "netcoreapp2.0" + + if ($testDesktop) { + TestUsingNUnit -testProject "$RepoRoot\tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj" -targetFramework $desktopTargetFramework + TestUsingNUnit -testProject "$RepoRoot\tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj" -targetFramework $desktopTargetFramework + TestUsingNUnit -testProject "$RepoRoot\tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj" -targetFramework $desktopTargetFramework + TestUsingNUnit -testProject "$RepoRoot\tests\fsharp\FSharpSuite.Tests.fsproj" -targetFramework $desktopTargetFramework + } + + if ($testCoreClr) { + TestUsingNUnit -testProject "$RepoRoot\tests\FSharp.Compiler.UnitTests\FSharp.Compiler.UnitTests.fsproj" -targetFramework $coreclrTargetFramework + TestUsingNUnit -testProject "$RepoRoot\tests\FSharp.Build.UnitTests\FSharp.Build.UnitTests.fsproj" -targetFramework $coreclrTargetFramework + TestUsingNUnit -testProject "$RepoRoot\tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj" -targetFramework $coreclrTargetFramework + TestUsingNUnit -testProject "$RepoRoot\tests\fsharp\FSharpSuite.Tests.fsproj" -targetFramework $coreclrTargetFramework + } + + if ($testFSharpQA) { + Push-Location "$RepoRoot\tests\fsharpqa\source" + $resultsRoot = "$ArtifactsDir\TestResults\$configuration" + $resultsLog = "test-net40-fsharpqa-results.log" + $errorLog = "test-net40-fsharpqa-errors.log" + $failLog = "test-net40-fsharpqa-errors" + $perlExe = "$env:USERPROFILE\.nuget\packages\StrawberryPerl64\5.22.2.1\Tools\perl\bin\perl.exe" + Create-Directory $resultsRoot + UpdatePath + $env:HOSTED_COMPILER = 1 + $env:CSC_PIPE = "$env:USERPROFILE\.nuget\packages\Microsoft.Net.Compilers\2.7.0\tools\csc.exe" + $env:FSCOREDLLPATH = "$ArtifactsDir\bin\fsc\$configuration\net46\FSharp.Core.dll" + $env:LINK_EXE = "$RepoRoot\tests\fsharpqa\testenv\bin\link\link.exe" + $env:OSARCH = $env:PROCESSOR_ARCHITECTURE + Exec-Console $perlExe """$RepoRoot\tests\fsharpqa\testenv\bin\runall.pl"" -resultsroot ""$resultsRoot"" -results $resultsLog -log $errorLog -fail $failLog -cleanup:no -procs:$env:NUMBER_OF_PROCESSORS" + Pop-Location + } + + if ($testVs) { + Write-Host "Environment Variables" + Get-Childitem Env: + TestUsingNUnit -testProject "$RepoRoot\vsintegration\tests\GetTypesVS.UnitTests\GetTypesVS.UnitTests.fsproj" -targetFramework $desktopTargetFramework + TestUsingNUnit -testProject "$RepoRoot\vsintegration\tests\UnitTests\VisualFSharp.UnitTests.fsproj" -targetFramework $desktopTargetFramework + } + + ExitWithExitCode 0 +} +catch { + Write-Host $_ + Write-Host $_.Exception + Write-Host $_.ScriptStackTrace + ExitWithExitCode 1 +} +finally { + Pop-Location +} diff --git a/eng/CIBuild.cmd b/eng/CIBuild.cmd new file mode 100644 index 00000000000..84640d7efc5 --- /dev/null +++ b/eng/CIBuild.cmd @@ -0,0 +1,2 @@ +@echo off +powershell -noprofile -executionPolicy RemoteSigned -file "%~dp0\Build.ps1" -ci -restore -build -bootstrap -pack -sign -publish -binaryLog %* diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml new file mode 100644 index 00000000000..4b3e52da9c9 --- /dev/null +++ b/eng/Version.Details.xml @@ -0,0 +1,11 @@ + + + + + + + https://github.com/dotnet/arcade + 9ba7a4ced36358fc130b762d25a83fa370c296c9 + + + diff --git a/build/targets/PackageVersions.props b/eng/Versions.props similarity index 71% rename from build/targets/PackageVersions.props rename to eng/Versions.props index 498a9d7fd68..1e029d23606 100644 --- a/build/targets/PackageVersions.props +++ b/eng/Versions.props @@ -1,5 +1,48 @@ + + + false + + + true + true + true + true + true + + + + + beta + + 4.5 + $(FSCoreMajorVersion).5 + $(FSCoreMajorVersion).0 + $(FSCoreVersion).0 + + 10.2 + $(FSPackageMajorVersion).3 + $(FSPackageVersion) + $(FSProductVersion).0 + + 15 + 9 + $(VSMajorVersion).0 + $(VSMajorVersion).$(VSMinorVersion).0 + $(VSAssemblyVersion).0 + + + + + $(FSCoreVersion) + $(FSProductVersion) + $(VSAssemblyVersion) + $(VSMajorVersion).$(VSMinorVersion).0 + + $(VersionPrefix) + + @@ -13,14 +56,14 @@ https://api.nuget.org/v3/index.json; https://dotnet.myget.org/F/roslyn/api/v3/index.json; https://dotnet.myget.org/F/symreader-converter/api/v3/index.json; + https://myget.org/F/vs-devcore/api/v3/index.json; + https://myget.org/F/vs-editor/api/v3/index.json; + https://vside.myget.org/F/vssdk/api/v3/index.json; + https://vside.myget.org/F/vs-impl/api/v3/index.json; - - $(PB_RestoreSource);$(RestoreSources) - $(MSBuildThisFileDirectory)..\..\artifacts\dependencyUptake\PackageVersions.props - - $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)..\..\RoslynPackageVersion.txt').Trim()) + $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)..\RoslynPackageVersion.txt').Trim()) 1.5.0 @@ -66,14 +109,14 @@ 8.0.1 14.0.25420 - 15.6.27740 + 15.8.525 15.0.26201-alpha 1.1.4322 - 15.0.26201 + 15.8.525 15.0.26201 - 15.6.27740 - 15.6.27740 - 15.6.27740 + 15.8.525 + 15.8.525 + 15.8.525 8.0.50727 7.10.6071 15.0.26201 @@ -82,7 +125,7 @@ 14.3.25407 15.0.26201 15.0.26201 - 15.0.26201 + 15.9.28307 10.0.30319 11.0.50727 15.0.25123-Dev15Preview @@ -92,18 +135,18 @@ 10.0.30319 11.0.61030 12.0.30110 - 15.6.27740 + 15.8.525 7.10.6071 8.0.50727 10.0.30319 12.0.30112 - 15.6.27740 - 15.6.27740 - 15.3.23 + 15.8.525 + 15.8.525 + 15.8.209 15.0.26201 15.3.15 9.0.30729 - 15.6.170 + 15.7.109 12.0.4 7.0.4 8.0.4 @@ -114,13 +157,10 @@ 0.2.0 1.0.0 1.0.147 - 10.1.0 - 1.0.0 3.0.0-alpha4 1.0.30 - 1.1.0-beta1-63314-01 8.0.0-alpha 2.7.0 2.0.3 @@ -128,16 +168,13 @@ 1.0.0 4.3.0 9.0.1 - 3.10.1 - 3.10.0 - 3.10.1 + 3.11.0 + 3.11.2 + 3.11.0 + 2.1.36 1.0.0-beta2-dev3 5.22.2.1 - 0.2.0-beta-000081 - - - diff --git a/eng/build-utils.ps1 b/eng/build-utils.ps1 new file mode 100644 index 00000000000..845169db12a --- /dev/null +++ b/eng/build-utils.ps1 @@ -0,0 +1,257 @@ +# Collection of powershell build utility functions that we use across our scripts. + +Set-StrictMode -version 2.0 +$ErrorActionPreference="Stop" + +# Import Arcade functions +. (Join-Path $PSScriptRoot "common\tools.ps1") + +$VSSetupDir = Join-Path $ArtifactsDir "VSSetup\$configuration" +$PackagesDir = Join-Path $ArtifactsDir "packages\$configuration" + +$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $false } +$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { $false } +$bootstrapDir = if (Test-Path variable:bootstrapDir) { $bootstrapDir } else { "" } +$bootstrapConfiguration = if (Test-Path variable:bootstrapConfiguration) { $bootstrapConfiguration } else { "Proto" } +$bootstrapTrm = if (Test-Path variable:bootstrapTfm) { $bootstrapConfiguration } else { "net46" } +$properties = if (Test-Path variable:properties) { $properties } else { @() } + +function GetProjectOutputBinary([string]$fileName, [string]$projectName = "", [string]$configuration = $script:configuration, [string]$tfm = "net46", [string]$rid = "", [bool]$published = $false) { + $projectName = if ($projectName -ne "") { $projectName } else { [System.IO.Path]::GetFileNameWithoutExtension($fileName) } + $publishDir = if ($published) { "publish\" } else { "" } + $ridDir = if ($rid -ne "") { "$rid\" } else { "" } + return Join-Path $ArtifactsDir "bin\$projectName\$configuration\$tfm\$ridDir$publishDir$fileName" +} + +# Handy function for executing a command in powershell and throwing if it +# fails. +# +# Use this when the full command is known at script authoring time and +# doesn't require any dynamic argument build up. Example: +# +# Exec-Block { & $msbuild Test.proj } +# +# Original sample came from: http://jameskovacs.com/2010/02/25/the-exec-problem/ +function Exec-Block([scriptblock]$cmd) { + & $cmd + + # Need to check both of these cases for errors as they represent different items + # - $?: did the powershell script block throw an error + # - $lastexitcode: did a windows command executed by the script block end in error + if ((-not $?) -or ($lastexitcode -ne 0)) { + throw "Command failed to execute: $cmd" + } +} + +function Exec-CommandCore([string]$command, [string]$commandArgs, [switch]$useConsole = $true) { + if ($useConsole) { + $exitCode = Exec-Process $command $commandArgs + if ($exitCode -ne 0) { + throw "Command failed to execute with exit code $($exitCode): $command $commandArgs" + } + return + } + + $startInfo = New-Object System.Diagnostics.ProcessStartInfo + $startInfo.FileName = $command + $startInfo.Arguments = $commandArgs + + $startInfo.UseShellExecute = $false + $startInfo.WorkingDirectory = Get-Location + $startInfo.RedirectStandardOutput = $true + $startInfo.CreateNoWindow = $true + + $process = New-Object System.Diagnostics.Process + $process.StartInfo = $startInfo + $process.Start() | Out-Null + + $finished = $false + try { + # The OutputDataReceived event doesn't fire as events are sent by the + # process in powershell. Possibly due to subtlties of how Powershell + # manages the thread pool that I'm not aware of. Using blocking + # reading here as an alternative which is fine since this blocks + # on completion already. + $out = $process.StandardOutput + while (-not $out.EndOfStream) { + $line = $out.ReadLine() + Write-Output $line + } + + while (-not $process.WaitForExit(100)) { + # Non-blocking loop done to allow ctr-c interrupts + } + + $finished = $true + if ($process.ExitCode -ne 0) { + throw "Command failed to execute with exit code $($process.ExitCode): $command $commandArgs" + } + } + finally { + # If we didn't finish then an error occured or the user hit ctrl-c. Either + # way kill the process + if (-not $finished) { + $process.Kill() + } + } +} + +# Handy function for executing a windows command which needs to go through +# windows command line parsing. +# +# Use this when the command arguments are stored in a variable. Particularly +# when the variable needs reparsing by the windows command line. Example: +# +# $args = "/p:ManualBuild=true Test.proj" +# Exec-Command $msbuild $args +# +function Exec-Command([string]$command, [string]$commandArgs) { + Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$false +} + +# Functions exactly like Exec-Command but lets the process re-use the current +# console. This means items like colored output will function correctly. +# +# In general this command should be used in place of +# Exec-Command $msbuild $args | Out-Host +# +function Exec-Console([string]$command, [string]$commandArgs) { + Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$true +} + +# Handy function for executing a powershell script in a clean environment with +# arguments. Prefer this over & sourcing a script as it will both use a clean +# environment and do proper error checking +function Exec-Script([string]$script, [string]$scriptArgs = "") { + Exec-Command "powershell" "-noprofile -executionPolicy RemoteSigned -file `"$script`" $scriptArgs" +} + +# Ensure the proper .NET Core SDK is available. Returns the location to the dotnet.exe. +function Ensure-DotnetSdk() { + return Join-Path (InitializeDotNetCli -install:$true) "dotnet.exe" +} + +function Get-VersionCore([string]$name, [string]$versionFile) { + $name = $name.Replace(".", "") + $name = $name.Replace("-", "") + $nodeName = "$($name)Version" + $x = [xml](Get-Content -raw $versionFile) + $node = $x.SelectSingleNode("//Project/PropertyGroup/$nodeName") + if ($node -ne $null) { + return $node.InnerText + } + + throw "Cannot find package $name in $versionFile" + +} + +# Return the version of the NuGet package as used in this repo +function Get-PackageVersion([string]$name) { + return Get-VersionCore $name (Join-Path $EngRoot "Versions.props") +} + +# Locate the directory where our NuGet packages will be deployed. Needs to be kept in sync +# with the logic in Version.props +function Get-PackagesDir() { + $d = $null + if ($env:NUGET_PACKAGES -ne $null) { + $d = $env:NUGET_PACKAGES + } + else { + $d = Join-Path $env:UserProfile ".nuget\packages\" + } + + Create-Directory $d + return $d +} + +# Locate the directory of a specific NuGet package which is restored via our main +# toolset values. +function Get-PackageDir([string]$name, [string]$version = "") { + if ($version -eq "") { + $version = Get-PackageVersion $name + } + + $p = Get-PackagesDir + $p = Join-Path $p $name.ToLowerInvariant() + $p = Join-Path $p $version + return $p +} + +function Run-MSBuild([string]$projectFilePath, [string]$buildArgs = "", [string]$logFileName = "", [switch]$parallel = $true, [switch]$summary = $true, [switch]$warnAsError = $true, [string]$configuration = $script:configuration) { + # Because we override the C#/VB toolset to build against our LKG package, it is important + # that we do not reuse MSBuild nodes from other jobs/builds on the machine. Otherwise, + # we'll run into issues such as https://github.com/dotnet/roslyn/issues/6211. + # MSBuildAdditionalCommandLineArgs= + $args = "/p:TreatWarningsAsErrors=true /nologo /nodeReuse:false /p:Configuration=$configuration "; + + if ($warnAsError) { + $args += " /warnaserror" + } + + if ($summary) { + $args += " /consoleloggerparameters:Verbosity=minimal;summary" + } else { + $args += " /consoleloggerparameters:Verbosity=minimal" + } + + if ($parallel) { + $args += " /m" + } + + if ($binaryLog) { + if ($logFileName -eq "") { + $logFileName = [IO.Path]::GetFileNameWithoutExtension($projectFilePath) + } + $logFileName = [IO.Path]::ChangeExtension($logFileName, ".binlog") + $logFilePath = Join-Path $LogDir $logFileName + $args += " /bl:$logFilePath" + } + + if ($official) { + $args += " /p:OfficialBuildId=" + $env:BUILD_BUILDNUMBER + } + + if ($ci) { + $args += " /p:ContinuousIntegrationBuild=true" + } + + if ($bootstrapDir -ne "") { + $args += " /p:BootstrapBuildPath=$bootstrapDir" + } + + $args += " $buildArgs" + $args += " $projectFilePath" + $args += " $properties" + + $buildTool = InitializeBuildTool + Exec-Console $buildTool.Path "$($buildTool.Command) $args" +} + +# Create a bootstrap build of the compiler. Returns the directory where the bootstrap build +# is located. +# +# Important to not set $script:bootstrapDir here yet as we're actually in the process of +# building the bootstrap. +function Make-BootstrapBuild() { + Write-Host "Building bootstrap compiler" + + $dir = Join-Path $ArtifactsDir "Bootstrap" + Remove-Item -re $dir -ErrorAction SilentlyContinue + Create-Directory $dir + + # prepare FsLex and Fsyacc + Run-MSBuild "$RepoRoot\src\buildtools\buildtools.proj" "/restore /t:Build" -logFileName "BuildTools" -configuration $bootstrapConfiguration + Copy-Item "$ArtifactsDir\bin\fslex\$bootstrapConfiguration\netcoreapp2.0\*" -Destination $dir + Copy-Item "$ArtifactsDir\bin\fsyacc\$bootstrapConfiguration\netcoreapp2.0\*" -Destination $dir + + # prepare compiler + $projectPath = "$RepoRoot\proto.proj" + Run-MSBuild $projectPath "/restore /t:Build" -logFileName "Bootstrap" -configuration $bootstrapConfiguration + Copy-Item "$ArtifactsDir\bin\fsc\$bootstrapConfiguration\$bootstrapTfm\*" -Destination $dir + + Write-Host "Cleaning Bootstrap compiler artifacts" + Run-MSBuild $projectPath "/t:Clean" -logFileName "BootstrapClean" -configuration $bootstrapConfiguration + + return $dir +} diff --git a/eng/build.sh b/eng/build.sh new file mode 100755 index 00000000000..c2d362c267f --- /dev/null +++ b/eng/build.sh @@ -0,0 +1,245 @@ +#!/usr/bin/env bash +# Copyright (c) .NET Foundation and contributors. All rights reserved. +# Licensed under the MIT license. See LICENSE file in the project root for full license information. + +# Stop script if unbound variable found (use ${var:-} if intentional) +set -u + +usage() +{ + echo "Common settings:" + echo " --configuration Build configuration: 'Debug' or 'Release' (short: -c)" + echo " --verbosity Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic] (short: -v)" + echo " --binaryLog Create MSBuild binary log (short: -bl)" + echo "" + echo "Actions:" + echo " --restore Restore projects required to build (short: -r)" + echo " --build Build all projects (short: -b)" + echo " --rebuild Rebuild all projects" + echo " --pack Build nuget packages" + echo " --publish Publish build artifacts" + echo " --help Print help and exit" + echo "" + echo "Test actions:" + echo " --testcoreclr Run unit tests on .NET Core (short: --test, -t)" + echo "" + echo "Advanced settings:" + echo " --ci Building in CI" + echo " --docker Run in a docker container if applicable" + echo " --skipAnalyzers Do not run analyzers during build operations" + echo " --prepareMachine Prepare machine for CI run, clean up processes after build" + echo "" + echo "Command line arguments starting with '/p:' are passed through to MSBuild." +} + +source="${BASH_SOURCE[0]}" + +# resolve $source until the file is no longer a symlink +while [[ -h "$source" ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + +restore=false +build=false +rebuild=false +pack=false +publish=false +test_core_clr=false + +configuration="Debug" +verbosity='minimal' +binary_log=false +ci=false +skip_analyzers=false +prepare_machine=false +properties="" + +docker=false +args="" + +if [[ $# = 0 ]] +then + usage + exit 1 +fi + +while [[ $# > 0 ]]; do + opt="$(echo "$1" | awk '{print tolower($0)}')" + case "$opt" in + --help|-h) + usage + exit 0 + ;; + --configuration|-c) + configuration=$2 + args="$args $1" + shift + ;; + --verbosity|-v) + verbosity=$2 + args="$args $1" + shift + ;; + --binarylog|-bl) + binary_log=true + ;; + --restore|-r) + restore=true + ;; + --build|-b) + build=true + ;; + --rebuild) + rebuild=true + ;; + --pack) + pack=true + ;; + --publish) + publish=true + ;; + --testcoreclr|--test|-t) + test_core_clr=true + ;; + --ci) + ci=true + ;; + --skipanalyzers) + skip_analyzers=true + ;; + --preparemachine) + prepare_machine=true + ;; + --docker) + docker=true + shift + continue + ;; + /p:*) + properties="$properties $1" + ;; + *) + echo "Invalid argument: $1" + usage + exit 1 + ;; + esac + args="$args $1" + shift +done + +# Import Arcade functions +. "$scriptroot/common/tools.sh" + +function TestUsingNUnit() { + testproject="" + targetframework="" + while [[ $# > 0 ]]; do + opt="$(echo "$1" | awk '{print tolower($0)}')" + case "$opt" in + --testproject) + testproject=$2 + shift + ;; + --targetframework) + targetframework=$2 + shift + ;; + *) + echo "Invalid argument: $1" + exit 1 + ;; + esac + shift + done + + if [[ "$testproject" == "" || "$targetframework" == "" ]]; then + echo "--testproject and --targetframework must be specified" + exit 1 + fi + + projectname=$(basename -- "$testproject") + projectname="${projectname%.*}" + testlogpath="$artifacts_dir/TestResults/$configuration/${projectname}_$targetframework.xml" + args="test \"$testproject\" --no-restore --no-build -c $configuration -f $targetframework --test-adapter-path . --logger \"nunit;LogFilePath=$testlogpath\"" + "$DOTNET_INSTALL_DIR/dotnet" $args +} + +function BuildSolution { + local solution="FSharp.sln" + echo "$solution:" + + InitializeToolset + local toolset_build_proj=$_InitializeToolset + + local bl="" + if [[ "$binary_log" = true ]]; then + bl="/bl:\"$log_dir/Build.binlog\"" + fi + + local projects="$repo_root/$solution" + + # https://github.com/dotnet/roslyn/issues/23736 + local enable_analyzers=!$skip_analyzers + UNAME="$(uname)" + if [[ "$UNAME" == "Darwin" ]]; then + enable_analyzers=false + fi + + # NuGet often exceeds the limit of open files on Mac and Linux + # https://github.com/NuGet/Home/issues/2163 + if [[ "$UNAME" == "Darwin" || "$UNAME" == "Linux" ]]; then + ulimit -n 6500 + fi + + local quiet_restore="" + if [[ "$ci" != true ]]; then + quiet_restore=true + fi + + # build bootstrap tools + bootstrap_config=Proto + MSBuild "$repo_root/src/buildtools/buildtools.proj" \ + /restore \ + /p:Configuration=$bootstrap_config \ + /t:Build + + bootstrap_dir=$artifacts_dir/Bootstrap + mkdir -p "$bootstrap_dir" + cp $artifacts_dir/bin/fslex/$bootstrap_config/netcoreapp2.0/* $bootstrap_dir + cp $artifacts_dir/bin/fsyacc/$bootstrap_config/netcoreapp2.0/* $bootstrap_dir + + # do real build + MSBuild $toolset_build_proj \ + $bl \ + /p:Configuration=$configuration \ + /p:Projects="$projects" \ + /p:RepoRoot="$repo_root" \ + /p:Restore=$restore \ + /p:Build=$build \ + /p:Rebuild=$rebuild \ + /p:Pack=$pack \ + /p:Publish=$publish \ + /p:UseRoslynAnalyzers=$enable_analyzers \ + /p:ContinuousIntegrationBuild=$ci \ + /p:QuietRestore=$quiet_restore \ + /p:QuietRestoreBinaryLog="$binary_log" \ + $properties +} + +InitializeDotNetCli $restore + +BuildSolution + +if [[ "$test_core_clr" == true ]]; then + TestUsingNUnit --testproject "$repo_root/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj" --targetframework netcoreapp2.0 + TestUsingNUnit --testproject "$repo_root/tests/FSharp.Build.UnitTests/FSharp.Build.UnitTests.fsproj" --targetframework netcoreapp2.0 + TestUsingNUnit --testproject "$repo_root/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj" --targetframework netcoreapp2.0 +fi + +ExitWithExitCode 0 diff --git a/eng/cibuild.sh b/eng/cibuild.sh new file mode 100755 index 00000000000..290f7ebaa58 --- /dev/null +++ b/eng/cibuild.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +source="${BASH_SOURCE[0]}" + +# resolve $SOURCE until the file is no longer a symlink +while [[ -h $source ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + + # if $source was a relative symlink, we need to resolve it relative to the path where + # the symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done +scriptroot="$( cd -P "$( dirname "$source" )" && pwd)" + +echo "Building this commit:" +git show --no-patch --pretty=raw HEAD + +. "$scriptroot/build.sh" --ci --restore --build --pack --publish --binaryLog "$@" diff --git a/eng/common/PublishBuildAssets.cmd b/eng/common/PublishBuildAssets.cmd deleted file mode 100644 index 3c6e4ff829d..00000000000 --- a/eng/common/PublishBuildAssets.cmd +++ /dev/null @@ -1,3 +0,0 @@ -@echo off -powershell -ExecutionPolicy ByPass -NoProfile -command "& """%~dp0sdk-task.ps1""" -msbuildEngine dotnet -restore -projects PublishBuildAssets.proj -ci %*" -exit /b %ErrorLevel% diff --git a/eng/common/PublishToPackageFeed.proj b/eng/common/PublishToPackageFeed.proj index 7dc478d981f..25362ff060c 100644 --- a/eng/common/PublishToPackageFeed.proj +++ b/eng/common/PublishToPackageFeed.proj @@ -10,25 +10,57 @@ netcoreapp2.1 - + + + + + - + - - + + + + + + + + + + + + + https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json + https://dotnetfeed.blob.core.windows.net/arcade-validation/index.json + + + + + AssetManifestPath="%(ManifestFiles.Identity)" + BlobAssetsBasePath="$(BlobBasePath)" + PackageAssetsBasePath="$(PackageBasePath)" /> diff --git a/eng/common/build.ps1 b/eng/common/build.ps1 index 8279dc71339..d0147db4bd5 100644 --- a/eng/common/build.ps1 +++ b/eng/common/build.ps1 @@ -11,7 +11,7 @@ Param( [switch][Alias('b')]$build, [switch] $rebuild, [switch] $deploy, - [switch] $test, + [switch][Alias('t')]$test, [switch] $integrationTest, [switch] $performanceTest, [switch] $sign, @@ -40,10 +40,10 @@ function Print-Usage() { Write-Host " -rebuild Rebuild solution" Write-Host " -deploy Deploy built VSIXes" Write-Host " -deployDeps Deploy dependencies (e.g. VSIXes for integration tests)" - Write-Host " -test Run all unit tests in the solution" - Write-Host " -pack Package build outputs into NuGet packages and Willow components" + Write-Host " -test Run all unit tests in the solution (short: -t)" Write-Host " -integrationTest Run all integration tests in the solution" Write-Host " -performanceTest Run all performance tests in the solution" + Write-Host " -pack Package build outputs into NuGet packages and Willow components" Write-Host " -sign Sign build outputs" Write-Host " -publish Publish artifacts (e.g. symbols)" Write-Host "" @@ -51,9 +51,11 @@ function Print-Usage() { Write-Host "Advanced settings:" Write-Host " -projects Semi-colon delimited list of sln/proj's to build. Globbing is supported (*.sln)" Write-Host " -ci Set when running on CI server" - Write-Host " -prepareMachine Prepare machine for CI run" + Write-Host " -prepareMachine Prepare machine for CI run, clean up processes after build" + Write-Host " -warnAsError Sets warnaserror msbuild parameter ('true' or 'false')" Write-Host " -msbuildEngine Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." Write-Host "" + Write-Host "Command line arguments not listed above are passed thru to msbuild." Write-Host "The above arguments can be shortened as much as to be unambiguous (e.g. -co for configuration, -t for test, etc.)." } @@ -99,12 +101,11 @@ function Build { /p:PerformanceTest=$performanceTest ` /p:Sign=$sign ` /p:Publish=$publish ` - /p:ContinuousIntegrationBuild=$ci ` @properties } try { - if ($help -or (($properties -ne $null) -and ($properties.Contains("/help") -or $properties.Contains("/?")))) { + if ($help -or (($null -ne $properties) -and ($properties.Contains("/help") -or $properties.Contains("/?")))) { Print-Usage exit 0 } diff --git a/eng/common/build.sh b/eng/common/build.sh old mode 100755 new mode 100644 index 4fe8b41ed70..40b1e8ec73e --- a/eng/common/build.sh +++ b/eng/common/build.sh @@ -10,20 +10,24 @@ set -e usage() { echo "Common settings:" - echo " --configuration Build configuration: 'Debug' or 'Release' (short: --c)" + echo " --configuration Build configuration: 'Debug' or 'Release' (short: -c)" echo " --verbosity Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic] (short: -v)" echo " --binaryLog Create MSBuild binary log (short: -bl)" + echo " --help Print help and exit (short: -h)" echo "" + echo "Actions:" echo " --restore Restore dependencies (short: -r)" - echo " --build Build all projects (short: -b)" - echo " --rebuild Rebuild all projects" - echo " --test Run all unit tests (short: -t)" + echo " --build Build solution (short: -b)" + echo " --rebuild Rebuild solution" + echo " --test Run all unit tests in the solution (short: -t)" + echo " --integrationTest Run all integration tests in the solution" + echo " --performanceTest Run all performance tests in the solution" + echo " --pack Package build outputs into NuGet packages and Willow components" echo " --sign Sign build outputs" echo " --publish Publish artifacts (e.g. symbols)" - echo " --pack Package build outputs into NuGet packages and Willow components" - echo " --help Print help and exit (short: -h)" echo "" + echo "Advanced settings:" echo " --projects Project or solution file(s) to build" echo " --ci Set when running on CI server" @@ -32,6 +36,7 @@ usage() echo " --warnAsError Sets warnaserror msbuild parameter ('true' or 'false')" echo "" echo "Command line arguments starting with '/p:' are passed through to MSBuild." + echo "Arguments can also be passed in with a single hyphen." } source="${BASH_SOURCE[0]}" @@ -50,10 +55,10 @@ restore=false build=false rebuild=false test=false -pack=false -publish=false integration_test=false performance_test=false +pack=false +publish=false sign=false public=false ci=false @@ -66,78 +71,82 @@ projects='' configuration='Debug' prepare_machine=false verbosity='minimal' + properties='' while [[ $# > 0 ]]; do - opt="$(echo "$1" | awk '{print tolower($0)}')" + opt="$(echo "${1/#--/-}" | awk '{print tolower($0)}')" case "$opt" in - --help|-h) + -help|-h) usage exit 0 ;; - --configuration|-c) + -configuration|-c) configuration=$2 shift ;; - --verbosity|-v) + -verbosity|-v) verbosity=$2 shift ;; - --binarylog|-bl) + -binarylog|-bl) binary_log=true ;; - --restore|-r) + -restore|-r) restore=true ;; - --build|-b) + -build|-b) build=true ;; - --rebuild) + -rebuild) rebuild=true ;; - --pack) + -pack) pack=true ;; - --test|-t) + -test|-t) test=true ;; - --integrationtest) + -integrationtest) integration_test=true ;; - --performancetest) + -performancetest) performance_test=true ;; - --sign) + -sign) sign=true ;; - --publish) + -publish) publish=true ;; - --preparemachine) + -preparemachine) prepare_machine=true ;; - --projects) + -projects) projects=$2 shift ;; - --ci) + -ci) ci=true ;; - --warnaserror) + -warnaserror) warn_as_error=$2 shift ;; - --nodereuse) + -nodereuse) node_reuse=$2 shift ;; - /p:*) + -p:*|/p:*) + properties="$properties $1" + ;; + -m:*|/m:*) properties="$properties $1" ;; - /m:*) + -bl:*|/bl:*) properties="$properties $1" ;; - /bl:*) + -dl:*|/dl:*) properties="$properties $1" ;; *) @@ -191,7 +200,6 @@ function Build { /p:PerformanceTest=$performance_test \ /p:Sign=$sign \ /p:Publish=$publish \ - /p:ContinuousIntegrationBuild=$ci \ $properties ExitWithExitCode 0 diff --git a/eng/common/cibuild.sh b/eng/common/cibuild.sh old mode 100755 new mode 100644 diff --git a/eng/common/cross/armel/tizen-build-rootfs.sh b/eng/common/cross/armel/tizen-build-rootfs.sh old mode 100755 new mode 100644 diff --git a/eng/common/cross/armel/tizen-fetch.sh b/eng/common/cross/armel/tizen-fetch.sh old mode 100755 new mode 100644 diff --git a/eng/common/cross/build-android-rootfs.sh b/eng/common/cross/build-android-rootfs.sh old mode 100755 new mode 100644 diff --git a/eng/common/cross/build-rootfs.sh b/eng/common/cross/build-rootfs.sh old mode 100755 new mode 100644 diff --git a/eng/common/darc-init.ps1 b/eng/common/darc-init.ps1 index 96cad844ba3..2467ebdd422 100644 --- a/eng/common/darc-init.ps1 +++ b/eng/common/darc-init.ps1 @@ -19,7 +19,7 @@ function InstallDarcCli ($darcVersion) { # Until we can anonymously query the BAR API for the latest arcade-services # build applied to the PROD channel, this is hardcoded. if (-not $darcVersion) { - $darcVersion = '1.1.0-beta.19057.9' + $darcVersion = '1.1.0-beta.19151.3' } $arcadeServicesSource = 'https://dotnetfeed.blob.core.windows.net/dotnet-arcade/index.json' diff --git a/eng/common/darc-init.sh b/eng/common/darc-init.sh old mode 100755 new mode 100644 index bad07c3ae61..8d63dd711b2 --- a/eng/common/darc-init.sh +++ b/eng/common/darc-init.sh @@ -1,6 +1,24 @@ #!/usr/bin/env bash source="${BASH_SOURCE[0]}" +darcVersion="1.1.0-beta.19151.3" + +while [[ $# > 0 ]]; do + opt="$(echo "$1" | awk '{print tolower($0)}')" + case "$opt" in + --darcversion) + darcVersion=$2 + shift + ;; + *) + echo "Invalid argument: $1" + usage + exit 1 + ;; + esac + + shift +done # resolve $source until the file is no longer a symlink while [[ -h "$source" ]]; do @@ -27,12 +45,11 @@ function InstallDarcCli { echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name -g) fi - ReadGlobalVersion "Microsoft.DotNet.Arcade.Sdk" - local toolset_version=$_ReadGlobalVersion + local arcadeServicesSource="https://dotnetfeed.blob.core.windows.net/dotnet-arcade/index.json" echo "Installing Darc CLI version $toolset_version..." echo "You may need to restart your command shell if this is the first dotnet tool you have installed." - echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $toolset_version -v $verbosity -g) + echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g) } InstallDarcCli diff --git a/eng/common/generate-graph-files.ps1 b/eng/common/generate-graph-files.ps1 new file mode 100644 index 00000000000..76f57076a32 --- /dev/null +++ b/eng/common/generate-graph-files.ps1 @@ -0,0 +1,87 @@ +Param( + [Parameter(Mandatory=$true)][string] $barToken, # Token generated at https://maestro-prod.westus2.cloudapp.azure.com/Account/Tokens + [Parameter(Mandatory=$true)][string] $gitHubPat, # GitHub personal access token from https://github.com/settings/tokens (no auth scopes needed) + [Parameter(Mandatory=$true)][string] $azdoPat, # Azure Dev Ops tokens from https://dev.azure.com/dnceng/_details/security/tokens (code read scope needed) + [Parameter(Mandatory=$true)][string] $outputFolder, # Where the graphviz.txt file will be created + [string] $darcVersion = '1.1.0-beta.19169.5', # darc's version + [string] $graphvizVersion = '2.38', # GraphViz version + [switch] $includeToolset # Whether the graph should include toolset dependencies or not. i.e. arcade, optimization. For more about + # toolset dependencies see https://github.com/dotnet/arcade/blob/master/Documentation/Darc.md#toolset-vs-product-dependencies +) + +$ErrorActionPreference = "Stop" +. $PSScriptRoot\tools.ps1 + +Import-Module -Name (Join-Path $PSScriptRoot "native\CommonLibrary.psm1") + +function CheckExitCode ([string]$stage) +{ + $exitCode = $LASTEXITCODE + if ($exitCode -ne 0) { + Write-Host "Something failed in stage: '$stage'. Check for errors above. Exiting now..." + ExitWithExitCode $exitCode + } +} + +try { + Push-Location $PSScriptRoot + + Write-Host "Installing darc..." + . .\darc-init.ps1 -darcVersion $darcVersion + CheckExitCode "Running darc-init" + + $engCommonBaseDir = Join-Path $PSScriptRoot "native\" + $graphvizInstallDir = CommonLibrary\Get-NativeInstallDirectory + $nativeToolBaseUri = "https://netcorenativeassets.blob.core.windows.net/resource-packages/external" + $installBin = Join-Path $graphvizInstallDir "bin" + + Write-Host "Installing dot..." + .\native\install-tool.ps1 -ToolName graphviz -InstallPath $installBin -BaseUri $nativeToolBaseUri -CommonLibraryDirectory $engCommonBaseDir -Version $graphvizVersion -Verbose + + $darcExe = "$env:USERPROFILE\.dotnet\tools" + $darcExe = Resolve-Path "$darcExe\darc.exe" + + Create-Directory $outputFolder + + # Generate 3 graph descriptions: + # 1. Flat with coherency information + # 2. Graphviz (dot) file + # 3. Standard dependency graph + $graphVizFilePath = "$outputFolder\graphviz.txt" + $graphVizImageFilePath = "$outputFolder\graph.png" + $normalGraphFilePath = "$outputFolder\graph-full.txt" + $flatGraphFilePath = "$outputFolder\graph-flat.txt" + $baseOptions = "get-dependency-graph --github-pat $gitHubPat --azdev-pat $azdoPat --password $barToken" + + if ($includeToolset) { + Write-Host "Toolsets will be included in the graph..." + $baseOptions += " --include-toolset" + } + + Write-Host "Generating standard dependency graph..." + Invoke-Expression "& `"$darcExe`" $baseOptions --output-file $normalGraphFilePath" + CheckExitCode "Generating normal dependency graph" + + Write-Host "Generating flat dependency graph and graphviz file..." + Invoke-Expression "& `"$darcExe`" $baseOptions --flat --coherency --graphviz $graphVizFilePath --output-file $flatGraphFilePath" + CheckExitCode "Generating flat and graphviz dependency graph" + + Write-Host "Generating graph image $graphVizFilePath" + $dotFilePath = Join-Path $installBin "graphviz\$graphvizVersion\release\bin\dot.exe" + Invoke-Expression "& `"$dotFilePath`" -Tpng -o'$graphVizImageFilePath' `"$graphVizFilePath`"" + CheckExitCode "Generating graphviz image" + + Write-Host "'$graphVizFilePath', '$flatGraphFilePath', '$normalGraphFilePath' and '$graphVizImageFilePath' created!" +} +catch { + if (!$includeToolset) { + Write-Host "This might be a toolset repo which includes only toolset dependencies. " -NoNewline -ForegroundColor Yellow + Write-Host "Since -includeToolset is not set there is no graph to create. Include -includeToolset and try again..." -ForegroundColor Yellow + } + Write-Host $_ + Write-Host $_.Exception + Write-Host $_.ScriptStackTrace + ExitWithExitCode 1 +} finally { + Pop-Location +} \ No newline at end of file diff --git a/eng/common/init-tools-native.ps1 b/eng/common/init-tools-native.ps1 index e25c60fed42..495a563a758 100644 --- a/eng/common/init-tools-native.ps1 +++ b/eng/common/init-tools-native.ps1 @@ -98,10 +98,20 @@ try { Write-Verbose "Executing '$LocalInstallerCommand'" Invoke-Expression "$LocalInstallerCommand" if ($LASTEXITCODE -Ne "0") { - Write-Error "Execution failed" - exit 1 + $errMsg = "$ToolName installation failed" + if ((Get-Variable 'DoNotAbortNativeToolsInstallationOnFailure' -ErrorAction 'SilentlyContinue') -and $DoNotAbortNativeToolsInstallationOnFailure) { + Write-Warning $errMsg + $toolInstallationFailure = $true + } else { + Write-Error $errMsg + exit 1 + } } } + + if ((Get-Variable 'toolInstallationFailure' -ErrorAction 'SilentlyContinue') -and $toolInstallationFailure) { + exit 1 + } } else { Write-Host "No native tools defined in global.json" diff --git a/eng/common/init-tools-native.sh b/eng/common/init-tools-native.sh old mode 100755 new mode 100644 diff --git a/eng/common/internal/Directory.Build.props b/eng/common/internal/Directory.Build.props new file mode 100644 index 00000000000..e33179ef373 --- /dev/null +++ b/eng/common/internal/Directory.Build.props @@ -0,0 +1,4 @@ + + + + diff --git a/eng/common/internal/Tools.csproj b/eng/common/internal/Tools.csproj new file mode 100644 index 00000000000..1a81ff906f6 --- /dev/null +++ b/eng/common/internal/Tools.csproj @@ -0,0 +1,23 @@ + + + + + net472 + false + + + + + + + + + + https://devdiv.pkgs.visualstudio.com/_packaging/8f470c7e-ac49-4afe-a6ee-cf784e438b93/nuget/v3/index.json; + https://devdiv.pkgs.visualstudio.com/_packaging/VS/nuget/v3/index.json; + + + + + + diff --git a/eng/common/msbuild.sh b/eng/common/msbuild.sh old mode 100755 new mode 100644 diff --git a/eng/common/native/common-library.sh b/eng/common/native/common-library.sh old mode 100755 new mode 100644 diff --git a/eng/common/native/install-cmake.sh b/eng/common/native/install-cmake.sh old mode 100755 new mode 100644 diff --git a/eng/common/sdk-task.ps1 b/eng/common/sdk-task.ps1 index 9ba7530122f..d0eec5163ef 100644 --- a/eng/common/sdk-task.ps1 +++ b/eng/common/sdk-task.ps1 @@ -1,48 +1,47 @@ [CmdletBinding(PositionalBinding=$false)] Param( - [string] $projects = "", - [string][Alias('v')]$verbosity = "minimal", + [string] $configuration = "Debug", + [string] $task, + [string] $verbosity = "minimal", [string] $msbuildEngine = $null, - [bool] $warnAsError = $true, - [switch][Alias('bl')]$binaryLog, - [switch][Alias('r')]$restore, - [switch] $ci, + [switch] $restore, [switch] $prepareMachine, [switch] $help, [Parameter(ValueFromRemainingArguments=$true)][String[]]$properties ) +$ci = $true +$binaryLog = $true +$warnAsError = $true + . $PSScriptRoot\tools.ps1 function Print-Usage() { - Write-Host "Common settings:" - Write-Host " -v[erbosity] Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]" - Write-Host " -[bl|binaryLog] Output binary log (short: -bl)" - Write-Host " -help Print help and exit" - Write-Host "" + Write-Host "Common settings:" + Write-Host " -task Name of Arcade task (name of a project in SdkTasks directory of the Arcade SDK package)" + Write-Host " -restore Restore dependencies" + Write-Host " -verbosity Msbuild verbosity: q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]" + Write-Host " -help Print help and exit" + Write-Host "" - Write-Host "Advanced settings:" - Write-Host " -restore Restore dependencies (short: -r)" - Write-Host " -projects Semi-colon delimited list of sln/proj's from the Arcade sdk to build. Globbing is supported (*.sln)" - Write-Host " -ci Set when running on CI server" - Write-Host " -prepareMachine Prepare machine for CI run" - Write-Host " -msbuildEngine Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." - Write-Host "" - Write-Host "Command line arguments not listed above are passed thru to msbuild." - Write-Host "The above arguments can be shortened as much as to be unambiguous (e.g. -co for configuration, -t for test, etc.)." + Write-Host "Advanced settings:" + Write-Host " -prepareMachine Prepare machine for CI run" + Write-Host " -msbuildEngine Msbuild engine to use to run build ('dotnet', 'vs', or unspecified)." + Write-Host "" + Write-Host "Command line arguments not listed above are passed thru to msbuild." } -function Build { - $toolsetBuildProj = InitializeToolset +function Build([string]$target) { + $logSuffix = if ($target -eq "Execute") { "" } else { ".$target" } + $log = Join-Path $LogDir "$task$logSuffix.binlog" + $outputPath = Join-Path $ToolsetDir "$task\\" - $toolsetBuildProj = Join-Path (Split-Path $toolsetBuildProj -Parent) "SdkTasks\SdkTask.proj" - $bl = if ($binaryLog) { "/bl:" + (Join-Path $LogDir "SdkTask.binlog") } else { "" } - MSBuild $toolsetBuildProj ` - $bl ` - /p:Projects=$projects ` - /p:Restore=$restore ` + MSBuild $taskProject ` + /bl:$log ` + /t:$target ` + /p:Configuration=$configuration ` /p:RepoRoot=$RepoRoot ` - /p:ContinuousIntegrationBuild=$ci ` + /p:BaseIntermediateOutputPath=$outputPath ` @properties } @@ -52,17 +51,23 @@ try { exit 0 } - if ($projects -eq "") { - Write-Error "Missing required parameter '-projects '" + if ($task -eq "") { + Write-Host "Missing required parameter '-task '" -ForegroundColor Red Print-Usage ExitWithExitCode 1 } - if ($ci) { - $binaryLog = $true + $taskProject = GetSdkTaskProject $task + if (!(Test-Path $taskProject)) { + Write-Host "Unknown task: $task" -ForegroundColor Red + ExitWithExitCode 1 + } + + if ($restore) { + Build "Restore" } - Build + Build "Execute" } catch { Write-Host $_ diff --git a/eng/common/templates/job/generate-graph-files.yml b/eng/common/templates/job/generate-graph-files.yml new file mode 100644 index 00000000000..e54ce956f90 --- /dev/null +++ b/eng/common/templates/job/generate-graph-files.yml @@ -0,0 +1,48 @@ +parameters: + # Optional: dependencies of the job + dependsOn: '' + + # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool + pool: {} + + # Optional: Include toolset dependencies in the generated graph files + includeToolset: false + +jobs: +- job: Generate_Graph_Files + + dependsOn: ${{ parameters.dependsOn }} + + displayName: Generate Graph Files + + pool: ${{ parameters.pool }} + + variables: + # Publish-Build-Assets provides: MaestroAccessToken, BotAccount-dotnet-maestro-bot-PAT + # DotNet-AllOrgs-Darc-Pats provides: dn-bot-devdiv-dnceng-rw-code-pat + - group: Publish-Build-Assets + - group: DotNet-AllOrgs-Darc-Pats + - name: _GraphArguments + value: -gitHubPat $(BotAccount-dotnet-maestro-bot-PAT) + -azdoPat $(dn-bot-devdiv-dnceng-rw-code-pat) + -barToken $(MaestroAccessToken) + -outputFolder '$(Build.StagingDirectory)/GraphFiles/' + - ${{ if ne(parameters.includeToolset, 'false') }}: + - name: _GraphArguments + value: ${{ variables._GraphArguments }} -includeToolset + + steps: + - task: PowerShell@2 + displayName: Generate Graph Files + inputs: + filePath: eng\common\generate-graph-files.ps1 + arguments: $(_GraphArguments) + continueOnError: true + - task: PublishBuildArtifacts@1 + displayName: Publish Graph to Artifacts + inputs: + PathtoPublish: '$(Build.StagingDirectory)/GraphFiles' + PublishLocation: Container + ArtifactName: GraphFiles + continueOnError: true + condition: always() diff --git a/eng/common/templates/job/job.yml b/eng/common/templates/job/job.yml index 5e293db35d7..74dd81fdc0a 100644 --- a/eng/common/templates/job/job.yml +++ b/eng/common/templates/job/job.yml @@ -41,18 +41,11 @@ parameters: enablePublishTestResults: false # Optional: enable sending telemetry - # if 'true', these "variables" must be specified in the variables object or as part of the queue matrix - # _HelixBuildConfig - differentiate between Debug, Release, other - # _HelixType - Example: build/product/ - # _HelixSource - Example: official/dotnet/arcade/$(Build.SourceBranch) enableTelemetry: false - # Optional: If specified, then automatically derive "_HelixSource" variable for telemetry + # Optional: define the helix repo for telemeetry (example: 'dotnet/arcade') helixRepo: '' - # Optional: Define the type for helix telemetry (must end in '/') - helixType: build/product/ - # Required: name of the job name: '' @@ -115,29 +108,24 @@ jobs: - name: ${{ pair.key }} value: ${{ pair.value }} - # Add additional variables - - ${{ if and(ne(parameters.helixRepo, ''), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notIn(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: official/${{ parameters.helixRepo }}/$(Build.SourceBranch) - - ${{ if and(ne(parameters.helixRepo, ''), or(ne(parameters.runAsPublic, 'false'), eq(variables['System.TeamProject'], 'public'), in(variables['Build.Reason'], 'PullRequest'))) }}: - - name: _HelixSource - value: pr/${{ parameters.helixRepo }}/$(Build.SourceBranch) - - name: _HelixType - value: ${{ parameters.helixType }} - - name: _HelixBuildConfig - value: $(_BuildConfig) + # DotNet-HelixApi-Access provides 'HelixApiAccessToken' for internal builds + - ${{ if and(eq(parameters.enableTelemetry, 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - group: DotNet-HelixApi-Access ${{ if ne(parameters.workspace, '') }}: workspace: ${{ parameters.workspace }} steps: - ${{ if eq(parameters.enableTelemetry, 'true') }}: - - template: /eng/common/templates/steps/telemetry-start.yml - parameters: - buildConfig: $(_HelixBuildConfig) - helixSource: $(_HelixSource) - helixType: $(_HelixType) + # Telemetry tasks are built from https://github.com/dotnet/arcade-extensions + - task: sendStartTelemetry@0 + displayName: 'Send Helix Start Telemetry' + inputs: + helixRepo: ${{ parameters.helixRepo }} + buildConfig: $(_BuildConfig) runAsPublic: ${{ parameters.runAsPublic }} + continueOnError: ${{ parameters.continueOnError }} + condition: always() - ${{ if eq(parameters.enableMicrobuild, 'true') }}: - ${{ if and(eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: @@ -165,11 +153,15 @@ jobs: TeamName: $(_TeamName) - ${{ if eq(parameters.enableTelemetry, 'true') }}: - - template: /eng/common/templates/steps/telemetry-end.yml + # Telemetry tasks are built from https://github.com/dotnet/arcade-extensions + - task: sendEndTelemetry@0 + displayName: 'Send Helix End Telemetry' + continueOnError: ${{ parameters.continueOnError }} + condition: always() - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: - task: PublishBuildArtifacts@1 - displayName: Publish Logs to VSTS + displayName: Publish Logs inputs: PathtoPublish: '$(Build.SourcesDirectory)/artifacts/log/$(_BuildConfig)' PublishLocation: Container @@ -187,7 +179,7 @@ jobs: continueOnError: true condition: always() - - ${{ if and(eq(parameters.enablePublishBuildAssets, true), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - ${{ if and(eq(parameters.enablePublishBuildAssets, true), ne(variables['_PublishUsingPipelines'], 'true'), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: - task: CopyFiles@2 displayName: Gather Asset Manifests inputs: @@ -202,4 +194,4 @@ jobs: PublishLocation: Container ArtifactName: AssetManifests continueOnError: ${{ parameters.continueOnError }} - condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) \ No newline at end of file + condition: and(succeeded(), eq(variables['_DotNetPublishToBlobFeed'], 'true')) diff --git a/eng/common/templates/job/publish-build-assets.yml b/eng/common/templates/job/publish-build-assets.yml index c094658fefc..620bd3c62e7 100644 --- a/eng/common/templates/job/publish-build-assets.yml +++ b/eng/common/templates/job/publish-build-assets.yml @@ -20,6 +20,9 @@ parameters: # if 'true', the build won't run any of the internal only steps, even if it is running in non-public projects. runAsPublic: false + # Optional: whether the build's artifacts will be published using release pipelines or direct feed publishing + publishUsingPipelines: false + jobs: - job: Asset_Registry_Publish @@ -44,12 +47,16 @@ jobs: downloadPath: '$(Build.StagingDirectory)/Download' condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - - script: eng\common\publishbuildassets.cmd - /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' - /p:BuildAssetRegistryToken=$(MaestroAccessToken) - /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com - /p:Configuration=$(_BuildConfig) + - task: PowerShell@2 displayName: Publish Build Assets + inputs: + filePath: eng\common\sdk-task.ps1 + arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet + /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' + /p:BuildAssetRegistryToken=$(MaestroAccessToken) + /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com + /p:PublishUsingPipelines=${{ parameters.publishUsingPipelines }} + /p:Configuration=$(_BuildConfig) condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - ${{ if eq(parameters.enablePublishBuildArtifacts, 'true') }}: diff --git a/eng/common/templates/jobs/jobs.yml b/eng/common/templates/jobs/jobs.yml index c7226b12ed2..6a2f98c036f 100644 --- a/eng/common/templates/jobs/jobs.yml +++ b/eng/common/templates/jobs/jobs.yml @@ -14,25 +14,28 @@ parameters: # Optional: Enable publishing to the build asset registry enablePublishBuildAssets: false + # Optional: Enable publishing using release pipelines + enablePublishUsingPipelines: false + + graphFileGeneration: + # Optional: Enable generating the graph files at the end of the build + enabled: false + # Optional: Include toolset dependencies in the generated graph files + includeToolset: false + # Optional: Include PublishTestResults task enablePublishTestResults: false # Optional: enable sending telemetry - # if 'true', these "variables" must be specified in the variables object or as part of the queue matrix - # _HelixBuildConfig - differentiate between Debug, Release, other - # _HelixType - Example: build/product/ - # _HelixSource - Example: official/dotnet/arcade/$(Build.SourceBranch) + # if enabled then the 'helixRepo' parameter should also be specified enableTelemetry: false # Required: A collection of jobs to run - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job jobs: [] - # Optional: If specified, then automatically derive "_HelixSource" variable for telemetry + # Optional: define the helix repo for telemetry (example: 'dotnet/arcade') helixRepo: '' - # Optional: Define the type for helix telemetry (must end in '/') - helixType: build/product/ - # Optional: Override automatically derived dependsOn value for "publish build assets" job publishBuildAssetsDependsOn: '' @@ -73,5 +76,15 @@ jobs: pool: vmImage: vs2017-win2016 runAsPublic: ${{ parameters.runAsPublic }} + publishUsingPipelines: ${{ parameters.enablePublishUsingPipelines }} enablePublishBuildArtifacts: ${{ parameters.enablePublishBuildArtifacts }} - + +- ${{ if and(eq(parameters.graphFileGeneration.enabled, true), eq(parameters.runAsPublic, 'false'), ne(variables['System.TeamProject'], 'public'), notin(variables['Build.Reason'], 'PullRequest')) }}: + - template: ../job/generate-graph-files.yml + parameters: + continueOnError: ${{ parameters.continueOnError }} + includeToolset: ${{ parameters.graphFileGeneration.includeToolset }} + dependsOn: + - Asset_Registry_Publish + pool: + vmImage: vs2017-win2016 diff --git a/eng/common/templates/phases/publish-build-assets.yml b/eng/common/templates/phases/publish-build-assets.yml index 0df6203b506..211967debab 100644 --- a/eng/common/templates/phases/publish-build-assets.yml +++ b/eng/common/templates/phases/publish-build-assets.yml @@ -28,12 +28,15 @@ phases: SecretsFilter: 'MaestroAccessToken' condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - - script: eng\common\publishbuildassets.cmd - -configuration $(_BuildConfig) - /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' - /p:BuildAssetRegistryToken=$(MaestroAccessToken) - /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com + - task: PowerShell@2 displayName: Publish Build Assets + inputs: + filePath: eng\common\sdk-task.ps1 + arguments: -task PublishBuildAssets -restore -msbuildEngine dotnet + /p:ManifestsPath='$(Build.StagingDirectory)/Download/AssetManifests' + /p:BuildAssetRegistryToken=$(MaestroAccessToken) + /p:MaestroApiEndpoint=https://maestro-prod.westus2.cloudapp.azure.com + /p:Configuration=$(_BuildConfig) condition: ${{ parameters.condition }} continueOnError: ${{ parameters.continueOnError }} - task: PublishBuildArtifacts@1 diff --git a/eng/common/templates/steps/send-to-helix.yml b/eng/common/templates/steps/send-to-helix.yml index a5835c0f473..0187597681e 100644 --- a/eng/common/templates/steps/send-to-helix.yml +++ b/eng/common/templates/steps/send-to-helix.yml @@ -1,32 +1,34 @@ parameters: - HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ - HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' - HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number - HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/api/2018-03-14/info/queues for a list of queues - HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group - HelixPreCommands: '' # optional -- commands to run before Helix work item execution - HelixPostCommands: '' # optional -- commands to run after Helix work item execution - WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects - WorkItemCommand: '' # optional -- a command to execute on the payload; requires WorkItemDirectory; incompatible with XUnitProjects - WorkItemTimeout: '' # optional -- a timeout in seconds for the work item command; requires WorkItemDirectory; incompatible with XUnitProjects - CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload - XUnitProjects: '' # optional -- semicolon delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true - XUnitPublishTargetFramework: '' # optional -- framework to use to publish your xUnit projects - XUnitRuntimeTargetFramework: '' # optional -- framework to use for the xUnit console runner - XUnitRunnerVersion: '' # optional -- version of the xUnit nuget package you wish to use on Helix; required for XUnitProjects - IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion - DotNetCliPackageType: '' # optional -- either 'sdk' or 'runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases.json - DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases.json - EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control - WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." - IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set - Creator: '' # optional -- if the build is external, use this to specify who is sending the job - condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() - continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false + HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ + HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' + HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number + HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues + HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group + HelixPreCommands: '' # optional -- commands to run before Helix work item execution + HelixPostCommands: '' # optional -- commands to run after Helix work item execution + WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects + WorkItemCommand: '' # optional -- a command to execute on the payload; requires WorkItemDirectory; incompatible with XUnitProjects + WorkItemTimeout: '' # optional -- a timeout in seconds for the work item command; requires WorkItemDirectory; incompatible with XUnitProjects + CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload + XUnitProjects: '' # optional -- semicolon delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true + XUnitWorkItemTimeout: '' # optional -- the workitem timeout in seconds for all workitems created from the xUnit projects specified by XUnitProjects + XUnitPublishTargetFramework: '' # optional -- framework to use to publish your xUnit projects + XUnitRuntimeTargetFramework: '' # optional -- framework to use for the xUnit console runner + XUnitRunnerVersion: '' # optional -- version of the xUnit nuget package you wish to use on Helix; required for XUnitProjects + IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion + DotNetCliPackageType: '' # optional -- either 'sdk' or 'runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases.json + DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/master/release-notes/releases.json + EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control + WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." + IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set + Creator: '' # optional -- if the build is external, use this to specify who is sending the job + DisplayNamePrefix: 'Send job to Helix' # optional -- rename the beginning of the displayName of the steps in AzDO + condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() + continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false steps: - - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY\eng\common\helixpublish.proj /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' - displayName: Send job to Helix (Windows) + - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY\eng\common\helixpublish.proj /restore /t:Test /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' + displayName: ${{ parameters.DisplayNamePrefix }} (Windows) env: BuildConfig: $(_BuildConfig) HelixSource: ${{ parameters.HelixSource }} @@ -41,6 +43,7 @@ steps: WorkItemTimeout: ${{ parameters.WorkItemTimeout }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} XUnitProjects: ${{ parameters.XUnitProjects }} + XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} @@ -50,10 +53,11 @@ steps: EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} Creator: ${{ parameters.Creator }} + SYSTEM_ACCESSTOKEN: $(System.AccessToken) condition: and(${{ parameters.condition }}, eq(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }} - - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/eng/common/helixpublish.proj /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog - displayName: Send job to Helix (Unix) + - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/eng/common/helixpublish.proj /restore /t:Test /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog + displayName: ${{ parameters.DisplayNamePrefix }} (Unix) env: BuildConfig: $(_BuildConfig) HelixSource: ${{ parameters.HelixSource }} @@ -68,6 +72,7 @@ steps: WorkItemTimeout: ${{ parameters.WorkItemTimeout }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} XUnitProjects: ${{ parameters.XUnitProjects }} + XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} @@ -77,5 +82,6 @@ steps: EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} Creator: ${{ parameters.Creator }} + SYSTEM_ACCESSTOKEN: $(System.AccessToken) condition: and(${{ parameters.condition }}, ne(variables['Agent.Os'], 'Windows_NT')) - continueOnError: ${{ parameters.continueOnError }} + continueOnError: ${{ parameters.continueOnError }} \ No newline at end of file diff --git a/eng/common/templates/steps/telemetry-end.yml b/eng/common/templates/steps/telemetry-end.yml index 9b61481e7e1..fadc04ca1b9 100644 --- a/eng/common/templates/steps/telemetry-end.yml +++ b/eng/common/templates/steps/telemetry-end.yml @@ -1,3 +1,7 @@ +parameters: + maxRetries: 5 + retryDelay: 10 # in seconds + steps: - bash: | if [ "$AGENT_JOBSTATUS" = "Succeeded" ] || [ "$AGENT_JOBSTATUS" = "PartiallySucceeded" ]; then @@ -7,27 +11,41 @@ steps: fi warningCount=0 - # create a temporary file for curl output - res=`mktemp` - - curlResult=` - curl --verbose --output $res --write-out "%{http_code}"\ - -H 'Content-Type: application/json' \ - -H "X-Helix-Job-Token: $Helix_JobToken" \ - -H 'Content-Length: 0' \ - -X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$Helix_WorkItemId/finish" \ - --data-urlencode "errorCount=$errorCount" \ - --data-urlencode "warningCount=$warningCount"` - curlStatus=$? - - if [ $curlStatus -eq 0 ]; then - if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then - curlStatus=$curlResult + curlStatus=1 + retryCount=0 + # retry loop to harden against spotty telemetry connections + # we don't retry successes and 4xx client errors + until [[ $curlStatus -eq 0 || ( $curlStatus -ge 400 && $curlStatus -le 499 ) || $retryCount -ge $MaxRetries ]] + do + if [ $retryCount -gt 0 ]; then + echo "Failed to send telemetry to Helix; waiting $RetryDelay seconds before retrying..." + sleep $RetryDelay fi - fi + + # create a temporary file for curl output + res=`mktemp` + + curlResult=` + curl --verbose --output $res --write-out "%{http_code}"\ + -H 'Content-Type: application/json' \ + -H "X-Helix-Job-Token: $Helix_JobToken" \ + -H 'Content-Length: 0' \ + -X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$Helix_WorkItemId/finish" \ + --data-urlencode "errorCount=$errorCount" \ + --data-urlencode "warningCount=$warningCount"` + curlStatus=$? + + if [ $curlStatus -eq 0 ]; then + if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then + curlStatus=$curlResult + fi + fi + + let retryCount++ + done if [ $curlStatus -ne 0 ]; then - echo "Failed to Send Build Finish information" + echo "Failed to Send Build Finish information after $retryCount retries" vstsLogOutput="vso[task.logissue type=error;sourcepath=templates/steps/telemetry-end.yml;code=1;]Failed to Send Build Finish information: $curlStatus" echo "##$vstsLogOutput" exit 1 @@ -37,6 +55,8 @@ steps: # defined via VSTS variables in start-job.sh Helix_JobToken: $(Helix_JobToken) Helix_WorkItemId: $(Helix_WorkItemId) + MaxRetries: ${{ parameters.maxRetries }} + RetryDelay: ${{ parameters.retryDelay }} condition: and(always(), ne(variables['Agent.Os'], 'Windows_NT')) - powershell: | if (($env:Agent_JobStatus -eq 'Succeeded') -or ($env:Agent_JobStatus -eq 'PartiallySucceeded')) { @@ -46,13 +66,30 @@ steps: } $WarningCount = 0 - try { - Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$env:Helix_WorkItemId/finish?errorCount=$ErrorCount&warningCount=$WarningCount" -Method Post -ContentType "application/json" -Body "" ` - -Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken } + # Basic retry loop to harden against server flakiness + $retryCount = 0 + while ($retryCount -lt $env:MaxRetries) { + try { + Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build/$env:Helix_WorkItemId/finish?errorCount=$ErrorCount&warningCount=$WarningCount" -Method Post -ContentType "application/json" -Body "" ` + -Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken } + break + } + catch { + $statusCode = $_.Exception.Response.StatusCode.value__ + if ($statusCode -ge 400 -and $statusCode -le 499) { + Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix (status code $statusCode); not retrying (4xx client error)" + Write-Host "##vso[task.logissue]error ", $_.Exception.GetType().FullName, $_.Exception.Message + exit 1 + } + Write-Host "Failed to send telemetry to Helix (status code $statusCode); waiting $env:RetryDelay seconds before retrying..." + $retryCount++ + sleep $env:RetryDelay + continue + } } - catch { - Write-Error $_ - Write-Error $_.Exception + + if ($retryCount -ge $env:MaxRetries) { + Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix after $retryCount retries." exit 1 } displayName: Send Windows Build End Telemetry @@ -60,4 +97,6 @@ steps: # defined via VSTS variables in start-job.ps1 Helix_JobToken: $(Helix_JobToken) Helix_WorkItemId: $(Helix_WorkItemId) + MaxRetries: ${{ parameters.maxRetries }} + RetryDelay: ${{ parameters.retryDelay }} condition: and(always(),eq(variables['Agent.Os'], 'Windows_NT')) diff --git a/eng/common/templates/steps/telemetry-start.yml b/eng/common/templates/steps/telemetry-start.yml index 79c128c5de8..32c01ef0b55 100644 --- a/eng/common/templates/steps/telemetry-start.yml +++ b/eng/common/templates/steps/telemetry-start.yml @@ -3,6 +3,8 @@ parameters: helixType: 'undefined_defaulted_in_telemetry.yml' buildConfig: '' runAsPublic: false + maxRetries: 5 + retryDelay: 10 # in seconds steps: - ${{ if and(eq(parameters.runAsPublic, 'false'), not(eq(variables['System.TeamProject'], 'public'))) }}: @@ -30,7 +32,7 @@ steps: } } JobListStuff - + cat $jobInfo # create a temporary file for curl output @@ -38,30 +40,44 @@ steps: accessTokenParameter="?access_token=$HelixApiAccessToken" - curlResult=` - cat $jobInfo |\ - curl --trace - --verbose --output $res --write-out "%{http_code}" \ - -H 'Content-Type: application/json' \ - -X POST "https://helix.dot.net/api/2018-03-14/telemetry/job$accessTokenParameter" -d @-` - curlStatus=$? + curlStatus=1 + retryCount=0 + # retry loop to harden against spotty telemetry connections + # we don't retry successes and 4xx client errors + until [[ $curlStatus -eq 0 || ( $curlStatus -ge 400 && $curlStatus -le 499 ) || $retryCount -ge $MaxRetries ]] + do + if [ $retryCount -gt 0 ]; then + echo "Failed to send telemetry to Helix; waiting $RetryDelay seconds before retrying..." + sleep $RetryDelay + fi + + curlResult=` + cat $jobInfo |\ + curl --trace - --verbose --output $res --write-out "%{http_code}" \ + -H 'Content-Type: application/json' \ + -X POST "https://helix.dot.net/api/2018-03-14/telemetry/job$accessTokenParameter" -d @-` + curlStatus=$? - if [ $curlStatus -eq 0 ]; then - if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then - curlStatus=$curlResult + if [ $curlStatus -eq 0 ]; then + if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then + curlStatus=$curlResult + fi fi - fi + + let retryCount++ + done curlResult=`cat $res` - + # validate status of curl command if [ $curlStatus -ne 0 ]; then - echo "Failed To Send Job Start information" + echo "Failed To Send Job Start information after $retryCount retries" # We have to append the ## vso prefix or vso will pick up the command when it dumps the inline script into the shell vstsLogOutput="vso[task.logissue type=error;sourcepath=telemetry/start-job.sh;code=1;]Failed to Send Job Start information: $curlStatus" echo "##$vstsLogOutput" exit 1 fi - + # Set the Helix_JobToken variable export Helix_JobToken=`echo $curlResult | xargs echo` # Strip Quotes echo "##vso[task.setvariable variable=Helix_JobToken;issecret=true;]$Helix_JobToken" @@ -75,29 +91,44 @@ steps: Attempt: 1 OperatingSystem: $(Agent.Os) Configuration: ${{ parameters.buildConfig }} + MaxRetries: ${{ parameters.maxRetries }} + RetryDelay: ${{ parameters.retryDelay }} condition: and(always(), ne(variables['Agent.Os'], 'Windows_NT')) - bash: | - res=`mktemp` - curlResult=` - curl --verbose --output $res --write-out "%{http_code}"\ - -H 'Content-Type: application/json' \ - -H "X-Helix-Job-Token: $Helix_JobToken" \ - -H 'Content-Length: 0' \ - -X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build" \ - --data-urlencode "buildUri=$BuildUri"` - curlStatus=$? - - if [ $curlStatus -eq 0 ]; then - if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then - curlStatus=$curlResult + curlStatus=1 + retryCount=0 + # retry loop to harden against spotty telemetry connections + # we don't retry successes and 4xx client errors + until [[ $curlStatus -eq 0 || ( $curlStatus -ge 400 && $curlStatus -le 499 ) || $retryCount -ge $MaxRetries ]] + do + if [ $retryCount -gt 0 ]; then + echo "Failed to send telemetry to Helix; waiting $RetryDelay seconds before retrying..." + sleep $RetryDelay fi - fi - curlResult=`cat $res` + res=`mktemp` + curlResult=` + curl --verbose --output $res --write-out "%{http_code}"\ + -H 'Content-Type: application/json' \ + -H "X-Helix-Job-Token: $Helix_JobToken" \ + -H 'Content-Length: 0' \ + -X POST -G "https://helix.dot.net/api/2018-03-14/telemetry/job/build" \ + --data-urlencode "buildUri=$BuildUri"` + curlStatus=$? + + if [ $curlStatus -eq 0 ]; then + if [ $curlResult -gt 299 ] || [ $curlResult -lt 200 ]; then + curlStatus=$curlResult + fi + fi + + curlResult=`cat $res` + let retryCount++ + done # validate status of curl command if [ $curlStatus -ne 0 ]; then - echo "Failed to Send Build Start information" + echo "Failed to Send Build Start information after $retryCount retries" vstsLogOutput="vso[task.logissue type=error;sourcepath=telemetry/build/start.sh;code=1;]Failed to Send Build Start information: $curlStatus" echo "##$vstsLogOutput" exit 1 @@ -109,8 +140,10 @@ steps: env: BuildUri: $(System.TaskDefinitionsUri)$(System.TeamProject)/_build/index?buildId=$(Build.BuildId)&_a=summary Helix_JobToken: $(Helix_JobToken) + MaxRetries: ${{ parameters.maxRetries }} + RetryDelay: ${{ parameters.retryDelay }} condition: and(always(), ne(variables['Agent.Os'], 'Windows_NT')) - + - powershell: | $jobInfo = [pscustomobject]@{ QueueId=$env:QueueId; @@ -120,17 +153,42 @@ steps: Attempt=$env:Attempt; Properties=[pscustomobject]@{ operatingSystem=$env:OperatingSystem; configuration=$env:Configuration }; } - + $jobInfoJson = $jobInfo | ConvertTo-Json if ($env:HelixApiAccessToken) { $accessTokenParameter="?access_token=$($env:HelixApiAccessToken)" } Write-Host "Job Info: $jobInfoJson" - $jobToken = Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job$($accessTokenParameter)" -Method Post -ContentType "application/json" -Body $jobInfoJson + + # Basic retry loop to harden against server flakiness + $retryCount = 0 + while ($retryCount -lt $env:MaxRetries) { + try { + $jobToken = Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job$($accessTokenParameter)" -Method Post -ContentType "application/json" -Body $jobInfoJson + break + } + catch { + $statusCode = $_.Exception.Response.StatusCode.value__ + if ($statusCode -ge 400 -and $statusCode -le 499) { + Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix (status code $statusCode); not retrying (4xx client error)" + Write-Host "##vso[task.logissue]error ", $_.Exception.GetType().FullName, $_.Exception.Message + exit 1 + } + Write-Host "Failed to send telemetry to Helix (status code $statusCode); waiting $env:RetryDelay seconds before retrying..." + $retryCount++ + sleep $env:RetryDelay + continue + } + } + + if ($retryCount -ge $env:MaxRetries) { + Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix after $retryCount retries." + exit 1 + } + $env:Helix_JobToken = $jobToken Write-Host "##vso[task.setvariable variable=Helix_JobToken;issecret=true;]$env:Helix_JobToken" - displayName: Send Windows Job Start Telemetry env: HelixApiAccessToken: $(HelixApiAccessToken) Source: ${{ parameters.helixSource }} @@ -140,15 +198,44 @@ steps: Attempt: 1 OperatingSystem: $(Agent.Os) Configuration: ${{ parameters.buildConfig }} + MaxRetries: ${{ parameters.maxRetries }} + RetryDelay: ${{ parameters.retryDelay }} condition: and(always(), eq(variables['Agent.Os'], 'Windows_NT')) + displayName: Send Windows Job Start Telemetry - powershell: | - $workItemId = Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build?buildUri=$([Net.WebUtility]::UrlEncode($env:BuildUri))" -Method Post -ContentType "application/json" -Body "" ` - -Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken } - + # Basic retry loop to harden against server flakiness + $retryCount = 0 + while ($retryCount -lt $env:MaxRetries) { + try { + $workItemId = Invoke-RestMethod -Uri "https://helix.dot.net/api/2018-03-14/telemetry/job/build?buildUri=$([Net.WebUtility]::UrlEncode($env:BuildUri))" -Method Post -ContentType "application/json" -Body "" ` + -Headers @{ 'X-Helix-Job-Token'=$env:Helix_JobToken } + break + } + catch { + $statusCode = $_.Exception.Response.StatusCode.value__ + if ($statusCode -ge 400 -and $statusCode -le 499) { + Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix (status code $statusCode); not retrying (4xx client error)" + Write-Host "##vso[task.logissue]error ", $_.Exception.GetType().FullName, $_.Exception.Message + exit 1 + } + Write-Host "Failed to send telemetry to Helix (status code $statusCode); waiting $env:RetryDelay seconds before retrying..." + $retryCount++ + sleep $env:RetryDelay + continue + } + } + + if ($retryCount -ge $env:MaxRetries) { + Write-Host "##vso[task.logissue]error Failed to send telemetry to Helix after $retryCount retries." + exit 1 + } + $env:Helix_WorkItemId = $workItemId Write-Host "##vso[task.setvariable variable=Helix_WorkItemId]$env:Helix_WorkItemId" displayName: Send Windows Build Start Telemetry env: BuildUri: $(System.TaskDefinitionsUri)$(System.TeamProject)/_build/index?buildId=$(Build.BuildId)&_a=summary Helix_JobToken: $(Helix_JobToken) + MaxRetries: ${{ parameters.maxRetries }} + RetryDelay: ${{ parameters.retryDelay }} condition: and(always(), eq(variables['Agent.Os'], 'Windows_NT')) diff --git a/eng/common/tools.ps1 b/eng/common/tools.ps1 index 4204dc14f89..de7523cae58 100644 --- a/eng/common/tools.ps1 +++ b/eng/common/tools.ps1 @@ -161,9 +161,10 @@ function GetDotNetInstallScript([string] $dotnetRoot) { return $installScript } -function InstallDotNetSdk([string] $dotnetRoot, [string] $version) { +function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $architecture = "") { $installScript = GetDotNetInstallScript $dotnetRoot - & $installScript -Version $version -InstallDir $dotnetRoot + $archArg = if ($architecture) { $architecture } else { "" } + & $installScript -Version $version -InstallDir $dotnetRoot -Architecture $archArg if ($lastExitCode -ne 0) { Write-Host "Failed to install dotnet cli (exit code '$lastExitCode')." -ForegroundColor Red ExitWithExitCode $lastExitCode @@ -210,7 +211,7 @@ function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = $vsMajorVersion = $vsInfo.installationVersion.Split('.')[0] InitializeVisualStudioEnvironmentVariables $vsInstallDir $vsMajorVersion - } elseif ($install) { + } else { if (Get-Member -InputObject $GlobalJson.tools -Name "xcopy-msbuild") { $xcopyMSBuildVersion = $GlobalJson.tools.'xcopy-msbuild' @@ -220,9 +221,10 @@ function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = $xcopyMSBuildVersion = "$vsMajorVersion.$($vsMinVersion.Minor).0-alpha" } - $vsInstallDir = InstallXCopyMSBuild $xcopyMSBuildVersion - } else { - throw "Unable to find Visual Studio that has required version and components installed" + $vsInstallDir = InitializeXCopyMSBuild $xcopyMSBuildVersion $install + if ($vsInstallDir -eq $null) { + throw "Unable to find Visual Studio that has required version and components installed" + } } $msbuildVersionDir = if ([int]$vsMajorVersion -lt 16) { "$vsMajorVersion.0" } else { "Current" } @@ -240,12 +242,20 @@ function InitializeVisualStudioEnvironmentVariables([string] $vsInstallDir, [str } } -function InstallXCopyMSBuild([string] $packageVersion) { +function InstallXCopyMSBuild([string]$packageVersion) { + return InitializeXCopyMSBuild $packageVersion -install $true +} + +function InitializeXCopyMSBuild([string]$packageVersion, [bool]$install) { $packageName = "RoslynTools.MSBuild" $packageDir = Join-Path $ToolsDir "msbuild\$packageVersion" $packagePath = Join-Path $packageDir "$packageName.$packageVersion.nupkg" if (!(Test-Path $packageDir)) { + if (!$install) { + return $null + } + Create-Directory $packageDir Write-Host "Downloading $packageName $packageVersion" Invoke-WebRequest "https://dotnet.myget.org/F/roslyn-tools/api/v2/package/$packageName/$packageVersion/" -OutFile $packagePath @@ -376,6 +386,11 @@ function GetNuGetPackageCachePath() { return $env:NUGET_PACKAGES } +# Returns a full path to an Arcade SDK task project file. +function GetSdkTaskProject([string]$taskName) { + return Join-Path (Split-Path (InitializeToolset) -Parent) "SdkTasks\$taskName.proj" +} + function InitializeToolset() { if (Test-Path variable:global:_ToolsetBuildProj) { return $global:_ToolsetBuildProj @@ -394,7 +409,7 @@ function InitializeToolset() { } if (-not $restore) { - Write-Host "Toolset version $toolsetVersion has not been restored." + Write-Host "Toolset version $toolsetVersion has not been restored." -ForegroundColor Red ExitWithExitCode 1 } @@ -402,15 +417,15 @@ function InitializeToolset() { $proj = Join-Path $ToolsetDir "restore.proj" $bl = if ($binaryLog) { "/bl:" + (Join-Path $LogDir "ToolsetRestore.binlog") } else { "" } - + '' | Set-Content $proj - MSBuild $proj $bl /t:__WriteToolsetLocation /noconsolelogger /p:__ToolsetLocationOutputFile=$toolsetLocationFile - + MSBuild $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile + $path = Get-Content $toolsetLocationFile -TotalCount 1 if (!(Test-Path $path)) { throw "Invalid toolset path: $path" } - + return $global:_ToolsetBuildProj = $path } @@ -446,7 +461,7 @@ function MSBuild() { $buildTool = InitializeBuildTool - $cmdArgs = "$($buildTool.Command) /m /nologo /clp:Summary /v:$verbosity /nr:$nodeReuse" + $cmdArgs = "$($buildTool.Command) /m /nologo /clp:Summary /v:$verbosity /nr:$nodeReuse /p:ContinuousIntegrationBuild=$ci" if ($warnAsError) { $cmdArgs += " /warnaserror /p:TreatWarningsAsErrors=true" diff --git a/eng/common/tools.sh b/eng/common/tools.sh old mode 100755 new mode 100644 index 8a253bef513..ecdece1f855 --- a/eng/common/tools.sh +++ b/eng/common/tools.sh @@ -153,7 +153,12 @@ function InstallDotNetSdk { GetDotNetInstallScript "$root" local install_script=$_GetDotNetInstallScript - bash "$install_script" --version $version --install-dir "$root" || { + local arch_arg="" + if [[ $# == 3 ]]; then + arch_arg="--architecture $3" + fi + + bash "$install_script" --version $version --install-dir "$root" $arch_arg || { local exit_code=$? echo "Failed to install dotnet SDK (exit code '$exit_code')." >&2 ExitWithExitCode $exit_code @@ -233,11 +238,15 @@ function InitializeToolset { ExitWithExitCode 2 fi - local toolset_restore_log="$log_dir/ToolsetRestore.binlog" local proj="$toolset_dir/restore.proj" + local bl="" + if [[ "$binary_log" == true ]]; then + bl="/bl:$log_dir/ToolsetRestore.binlog" + fi + echo '' > "$proj" - MSBuild "$proj" /t:__WriteToolsetLocation /noconsolelogger /bl:"$toolset_restore_log" /p:__ToolsetLocationOutputFile="$toolset_location_file" + MSBuild "$proj" $bl /t:__WriteToolsetLocation /clp:ErrorsOnly\;NoSummary /p:__ToolsetLocationOutputFile="$toolset_location_file" local toolset_build_proj=`cat "$toolset_location_file"` @@ -284,7 +293,7 @@ function MSBuild { warnaserror_switch="/warnaserror" fi - "$_InitializeBuildTool" "$_InitializeBuildToolCommand" /m /nologo /clp:Summary /v:$verbosity /nr:$node_reuse $warnaserror_switch /p:TreatWarningsAsErrors=$warn_as_error "$@" || { + "$_InitializeBuildTool" "$_InitializeBuildToolCommand" /m /nologo /clp:Summary /v:$verbosity /nr:$node_reuse $warnaserror_switch /p:TreatWarningsAsErrors=$warn_as_error /p:ContinuousIntegrationBuild=$ci "$@" || { local exit_code=$? echo "Build failed (exit code '$exit_code')." >&2 ExitWithExitCode $exit_code diff --git a/eng/targets/NuGet.targets b/eng/targets/NuGet.targets new file mode 100644 index 00000000000..c2db06b6c1a --- /dev/null +++ b/eng/targets/NuGet.targets @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + diff --git a/eng/targets/Settings.props b/eng/targets/Settings.props new file mode 100644 index 00000000000..0022b125e42 --- /dev/null +++ b/eng/targets/Settings.props @@ -0,0 +1,11 @@ + + + + MIT + Microsoft and F# Software Foundation + Visual F# Compiler FSharp functional programming + $(CopyrightMicrosoft) + $(ArtifactsBinDir) + + + diff --git a/fcs/Directory.Build.props b/fcs/Directory.Build.props index 3478a48aa9a..3179fe221f9 100644 --- a/fcs/Directory.Build.props +++ b/fcs/Directory.Build.props @@ -1,4 +1,12 @@ + + + + $(RestoreSources); + https://api.nuget.org/v3/index.json; + + + $(UserProfile)\.nuget\packages\ $(HOME)/.nuget/packages/ diff --git a/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj b/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj index 9c3eb687c20..edb85fcf648 100644 --- a/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj +++ b/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj @@ -82,6 +82,7 @@ + diff --git a/fcs/build.fsx b/fcs/build.fsx index 5a533714524..50735795d88 100644 --- a/fcs/build.fsx +++ b/fcs/build.fsx @@ -92,7 +92,9 @@ Target "BuildVersion" (fun _ -> Target "Build" (fun _ -> runDotnet __SOURCE_DIRECTORY__ "build ../src/buildtools/buildtools.proj -v n -c Proto" - runDotnet __SOURCE_DIRECTORY__ "build FSharp.Compiler.Service.sln -v n -c release" + let fslexPath = __SOURCE_DIRECTORY__ + "/../artifacts/bin/fslex/Proto/netcoreapp2.0/fslex.dll" + let fsyaccPath = __SOURCE_DIRECTORY__ + "/../artifacts/bin/fsyacc/Proto/netcoreapp2.0/fsyacc.dll" + runDotnet __SOURCE_DIRECTORY__ (sprintf "build FSharp.Compiler.Service.sln -v n -c Release /p:FsLexPath=%s /p:FsYaccPath=%s" fslexPath fsyaccPath) ) Target "Test" (fun _ -> @@ -100,11 +102,12 @@ Target "Test" (fun _ -> runDotnet __SOURCE_DIRECTORY__ "build ../tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Sample_NETCoreSDK_FSharp_Library_netstandard2_0.fsproj -v n /restore /p:DisableCompilerRedirection=true" // Now run the tests - runDotnet __SOURCE_DIRECTORY__ "test FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj --no-restore --no-build -v n -c release" + let logFilePath = Path.Combine(__SOURCE_DIRECTORY__, "..", "artifacts", "TestResults", "Release", "FSharp.Compiler.Service.Test.xml") + runDotnet __SOURCE_DIRECTORY__ (sprintf "test FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj --no-restore --no-build -v n -c Release --test-adapter-path . --logger \"nunit;LogFilePath=%s\"" logFilePath) ) Target "NuGet" (fun _ -> - runDotnet __SOURCE_DIRECTORY__ "pack FSharp.Compiler.Service.sln -v n -c release" + runDotnet __SOURCE_DIRECTORY__ "pack FSharp.Compiler.Service.sln -v n -c Release" ) Target "GenerateDocsEn" (fun _ -> diff --git a/fsharp.proj b/fsharp.proj deleted file mode 100644 index a550b60eac0..00000000000 --- a/fsharp.proj +++ /dev/null @@ -1,178 +0,0 @@ - - - - Debug - AssemblySearchPaths={HintPathFromItem};{TargetFrameworkDirectory};{RawFileName} - - - - - true - false - false - false - false - - false - false - false - false - false - - - - - true - true - true - true - true - true - - true - true - true - true - true - true - true - true - - - - - true - true - - - - - - - - TargetFramework=netstandard1.6 - TargetFramework=net45 - - - TargetFramework=netstandard2.0 - TargetFramework=net46 - - - TargetFramework=netstandard2.0 - TargetFramework=net46 - - - TargetFramework=net46 - - - TargetFramework=netstandard2.0 - TargetFramework=net46 - - - TargetFramework=netcoreapp2.1 - TargetFramework=net46 - - - TargetFramework=netcoreapp2.1 - TargetFramework=net46 - - - TargetFramework=net46 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_RunningRestore>true - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/global.json b/global.json index ac6900880b3..a6d9f0d3ca5 100644 --- a/global.json +++ b/global.json @@ -1,9 +1,16 @@ { - "tools": { - "dotnet": "2.1.500" - }, - "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.19069.2", - "Microsoft.DotNet.Helix.Sdk": "2.0.0-beta.19069.2" + "tools": { + "dotnet": "2.1.504", + "vs": { + "version": "15.9", + "components": [ + "Microsoft.Net.Core.Component.SDK.2.1", + "Microsoft.VisualStudio.Component.FSharp" + ] } + }, + "msbuild-sdks": { + "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.19170.12", + "Microsoft.DotNet.Helix.Sdk": "2.0.0-beta.19069.2" + } } diff --git a/packages.config b/packages.config deleted file mode 100644 index 709d225851d..00000000000 --- a/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/proto.proj b/proto.proj index 0974580af5a..c60f17d8426 100644 --- a/proto.proj +++ b/proto.proj @@ -6,7 +6,6 @@ - TargetFramework=net46 TargetFramework=netcoreapp2.1 diff --git a/restore.sh b/restore.sh new file mode 100755 index 00000000000..58a2abb50f7 --- /dev/null +++ b/restore.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +source="${BASH_SOURCE[0]}" + +# resolve $SOURCE until the file is no longer a symlink +while [[ -h $source ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done + +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" +"$scriptroot/eng/build.sh" --restore $@ diff --git a/scripts/AssemblyVersionCheck.fsx b/scripts/AssemblyVersionCheck.fsx new file mode 100644 index 00000000000..0f3816a2e6c --- /dev/null +++ b/scripts/AssemblyVersionCheck.fsx @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +open System +open System.Diagnostics +open System.IO +open System.Reflection +open System.Text.RegularExpressions + +module AssemblyVersionCheck = + + let private versionZero = Version(0, 0, 0, 0) + let private versionOne = Version(1, 0, 0, 0) + let private commitHashPattern = new Regex(@"Commit Hash: ()|([0-9a-fA-F]{40})", RegexOptions.Compiled) + let private devVersionPattern = new Regex(@"-(ci|dev)", RegexOptions.Compiled) + + let verifyAssemblyVersions (binariesPath:string) = + let excludedAssemblies = + [ "FSharp.Data.TypeProviders.dll" ] + |> Set.ofList + let fsharpAssemblies = + [ "FSharp*.dll" + "fsc.exe" + "fsc.dll" + "fsi*.exe" + "fsi*.dll" ] + |> List.map (fun p -> Directory.EnumerateFiles(binariesPath, p, SearchOption.AllDirectories)) + |> Seq.concat + |> List.ofSeq + |> List.filter (fun p -> (Set.contains (Path.GetFileName(p)) excludedAssemblies) |> not) + + // verify that all assemblies have a version number other than 0.0.0.0 or 1.0.0.0 + let failedVersionCheck = + fsharpAssemblies + |> List.filter (fun a -> + let assemblyVersion = AssemblyName.GetAssemblyName(a).Version + assemblyVersion = versionZero || assemblyVersion = versionOne) + if failedVersionCheck.Length > 0 then + printfn "The following assemblies had a version of %A or %A" versionZero versionOne + printfn "%s\r\n" <| String.Join("\r\n", failedVersionCheck) + else + printfn "All shipping assemblies had an appropriate version number." + + // verify that all assemblies have a commit hash + let failedCommitHash = + fsharpAssemblies + |> List.filter (fun a -> + let fileProductVersion = FileVersionInfo.GetVersionInfo(a).ProductVersion + not (commitHashPattern.IsMatch(fileProductVersion) || devVersionPattern.IsMatch(fileProductVersion))) + if failedCommitHash.Length > 0 then + printfn "The following assemblies don't have a commit hash set" + printfn "%s\r\n" <| String.Join("\r\n", failedCommitHash) + else + printfn "All shipping assemblies had an appropriate commit hash." + + // return code is the number of failures + failedVersionCheck.Length + failedCommitHash.Length + +let main (argv:string array) = + if argv.Length <> 1 then + printfn "Usage: fsi.exe AssemblyVersionCheck.fsx -- path/to/binaries" + 1 + else + AssemblyVersionCheck.verifyAssemblyVersions argv.[0] + +Environment.GetCommandLineArgs() +|> Seq.skipWhile ((<>) "--") +|> Seq.skip 1 +|> Array.ofSeq +|> main diff --git a/src/scripts/VerifyAllTranslations.fsx b/scripts/VerifyAllTranslations.fsx similarity index 100% rename from src/scripts/VerifyAllTranslations.fsx rename to scripts/VerifyAllTranslations.fsx diff --git a/init-tools.cmd b/scripts/init-tools.cmd similarity index 91% rename from init-tools.cmd rename to scripts/init-tools.cmd index cbdeb27afef..3b17a835b9e 100644 --- a/init-tools.cmd +++ b/scripts/init-tools.cmd @@ -1,8 +1,8 @@ @echo off setlocal enabledelayedexpansion -set /p DOTNET_TOOLS_VERSION=<"%~dp0DotnetCLIToolsVersion.txt" -set DOTNET_TOOLS_PATH=%~dp0artifacts\toolset\dotnet +set /p DOTNET_TOOLS_VERSION=<"%~dp0..\DotnetCLIToolsVersion.txt" +set DOTNET_TOOLS_PATH=%~dp0..\artifacts\toolset\dotnet set dotnetexe=%DOTNET_TOOLS_PATH%\dotnet.exe set sdksentinel=%DOTNET_TOOLS_PATH%\sdk-version.txt diff --git a/init-tools.sh b/scripts/init-tools.sh old mode 100755 new mode 100644 similarity index 98% rename from init-tools.sh rename to scripts/init-tools.sh index 9d5a2e2f8c6..67067dd4867 --- a/init-tools.sh +++ b/scripts/init-tools.sh @@ -7,10 +7,10 @@ __TOOLRUNTIME_DIR=$__scriptpath/Tools __DOTNET_PATH=$__TOOLRUNTIME_DIR/dotnetcli __DOTNET_CMD=$__DOTNET_PATH/dotnet -__DOTNET_VERSION=$(cat $__scriptpath/DotnetCLIVersion.txt) +__DOTNET_VERSION=$(cat $__scriptpath/../DotnetCLIVersion.txt) if [ -z "$__BUILDTOOLS_SOURCE" ]; then __BUILDTOOLS_SOURCE=https://dotnet.myget.org/F/dotnet-buildtools/api/v3/index.json; fi -__BUILD_TOOLS_PACKAGE_VERSION=$(cat $__scriptpath/BuildToolsVersion.txt) +__BUILD_TOOLS_PACKAGE_VERSION=$(cat $__scriptpath/../BuildToolsVersion.txt) __BUILD_TOOLS_PATH=$__PACKAGES_DIR/microsoft.dotnet.buildtools/$__BUILD_TOOLS_PACKAGE_VERSION/lib diff --git a/scripts/verify-translations.cmd b/scripts/verify-translations.cmd new file mode 100644 index 00000000000..86094da755e --- /dev/null +++ b/scripts/verify-translations.cmd @@ -0,0 +1,3 @@ +@echo off + +%~dp0..\artifacts\bin\fsi\Release\net46\fsi.exe %~dp0VerifyAllTranslations.fsx -- %~dp0 diff --git a/setup/Directory.Build.props b/setup/Directory.Build.props index bd233e75785..53933526bc4 100644 --- a/setup/Directory.Build.props +++ b/setup/Directory.Build.props @@ -1,6 +1,6 @@ - + @@ -13,9 +13,6 @@ $(ArtifactsDir)\VSSetup.obj\$(Configuration)\$(MSBuildProjectName) $(SetupRootFolder)..\artifacts\VSSetup\$(Configuration) $(SetupRootFolder)..\artifacts\VSSetup\$(Configuration)\Insertion - - - $(VSMajorVersion).$(VSMinorVersion).$(BUILD_BUILDNUMBER) diff --git a/setup/Directory.Build.targets b/setup/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/setup/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/setup/Swix/Directory.Build.props b/setup/Swix/Directory.Build.props index f64df1d29de..772bd04080a 100644 --- a/setup/Swix/Directory.Build.props +++ b/setup/Swix/Directory.Build.props @@ -1,9 +1,9 @@ + - - Debug + Microsoft.FSharp neutral false vsix diff --git a/setup/Swix/Directory.Build.targets b/setup/Swix/Directory.Build.targets index 974c6da4f1b..ca0fe04d03a 100644 --- a/setup/Swix/Directory.Build.targets +++ b/setup/Swix/Directory.Build.targets @@ -1,10 +1,22 @@ + + $(ArtifactsDir)\VSSetup\$(Configuration)\Insertion\$(OutputName).vsix - - + + + false + + + + + + + + + diff --git a/setup/Swix/Microsoft.FSharp.Compiler.MSBuild/Microsoft.FSharp.Compiler.MSBuild.csproj b/setup/Swix/Microsoft.FSharp.Compiler.MSBuild/Microsoft.FSharp.Compiler.MSBuild.csproj new file mode 100644 index 00000000000..27625453ec9 --- /dev/null +++ b/setup/Swix/Microsoft.FSharp.Compiler.MSBuild/Microsoft.FSharp.Compiler.MSBuild.csproj @@ -0,0 +1,131 @@ + + + + net46 + net462 + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_Line> + + + + + <_BuiltSwrLines Include="$(_Line)" /> + + + + + + <_SwrFilePath>$(IntermediateOutputPath)Microsoft.FSharp.Compiler.swr + + + + + + + <_Lines> + + + + + + + + + + + + + + diff --git a/setup/Swix/Microsoft.FSharp.Compiler.Resources/Empty.swr b/setup/Swix/Microsoft.FSharp.Compiler.Resources/Empty.swr deleted file mode 100644 index 32da88c9291..00000000000 --- a/setup/Swix/Microsoft.FSharp.Compiler.Resources/Empty.swr +++ /dev/null @@ -1,5 +0,0 @@ -use vs - -package name=Microsoft.FSharp.Compiler.Resources - version=$(FSharpPackageVersion) - vs.package.language=$(LocaleSpecificCulture) diff --git a/setup/Swix/Microsoft.FSharp.Compiler.Resources/Files.swr b/setup/Swix/Microsoft.FSharp.Compiler.Resources/Files.swr deleted file mode 100644 index f3f60d490b9..00000000000 --- a/setup/Swix/Microsoft.FSharp.Compiler.Resources/Files.swr +++ /dev/null @@ -1,11 +0,0 @@ -use vs - -package name=Microsoft.FSharp.Compiler.Resources - version=$(FSharpPackageVersion) - vs.package.language=$(LocaleSpecificCulture) - -folder "InstallDir:Common7\IDE\CommonExtensions\Microsoft\FSharpCompiler\$(LocaleParentCulture)" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.Build.resources.dll" - file source="$(BinariesFolder)\FSharp.Compiler.Interactive.Settings\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.Compiler.Interactive.Settings.resources.dll" - file source="$(BinariesFolder)\FSharp.Compiler.Private\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.Compiler.Private.resources.dll" - file source="$(BinariesFolder)\FSharp.Core\$(Configuration)\net45\$(LocaleParentCulture)\FSharp.Core.resources.dll" diff --git a/setup/Swix/Microsoft.FSharp.Compiler.Resources/Microsoft.FSharp.Compiler.Resources.swixproj b/setup/Swix/Microsoft.FSharp.Compiler.Resources/Microsoft.FSharp.Compiler.Resources.swixproj deleted file mode 100644 index ac8e74d4854..00000000000 --- a/setup/Swix/Microsoft.FSharp.Compiler.Resources/Microsoft.FSharp.Compiler.Resources.swixproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - Microsoft.FSharp.Compiler.Resources.$(LocaleCode) - - - - $(PackagePreprocessorDefinitions);BinariesFolder=$(BinariesFolder) - $(PackagePreprocessorDefinitions);Configuration=$(Configuration) - $(PackagePreprocessorDefinitions);FSharpPackageVersion=$(FSharpPackageVersion) - $(PackagePreprocessorDefinitions);LocaleParentCulture=$(LocaleParentCulture) - $(PackagePreprocessorDefinitions);LocaleSpecificCulture=$(LocaleSpecificCulture) - - - - - - - - - - - - - - - - - diff --git a/setup/Swix/Microsoft.FSharp.Compiler/Dependencies.swr b/setup/Swix/Microsoft.FSharp.Compiler/Dependencies.swr deleted file mode 100644 index c5dcc628603..00000000000 --- a/setup/Swix/Microsoft.FSharp.Compiler/Dependencies.swr +++ /dev/null @@ -1,9 +0,0 @@ -use vs - -package name=Microsoft.FSharp.Compiler - version=$(FSharpPackageVersion) - -vs.dependencies - vs.dependency id=Microsoft.FSharp.Dependencies - version=$(FSharpPackageVersion) - type=Required diff --git a/setup/Swix/Microsoft.FSharp.Compiler/Files.swr b/setup/Swix/Microsoft.FSharp.Compiler/Files.swr deleted file mode 100644 index b56667d2465..00000000000 --- a/setup/Swix/Microsoft.FSharp.Compiler/Files.swr +++ /dev/null @@ -1,39 +0,0 @@ -use vs - -package name=Microsoft.FSharp.Compiler - version=$(FSharpPackageVersion) - -folder "InstallDir:Common7\IDE\CommonExtensions\Microsoft\FSharp" - - file source=$(BinariesFolder)\fsc\$(Configuration)\net46\fsc.exe vs.file.ngen=yes vs.file.ngenArchitecture=All vs.file.ngenPriority=2 vs.file.ngenApplication="[installDir]\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe" - file source="$(BinariesFolder)\fsc\$(Configuration)\net46\fsc.exe.config" - - file source=$(BinariesFolder)\fsi\$(Configuration)\net46\fsi.exe vs.file.ngen=yes vs.file.ngenArchitecture=X86 vs.file.ngenPriority=2 vs.file.ngenApplication="[installDir]\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsi.exe" - file source="$(BinariesFolder)\fsi\$(Configuration)\net46\fsi.exe.config" - - file source="$(BinariesFolder)\fsiAnyCpu\$(Configuration)\net46\fsiAnyCpu.exe" vs.file.ngen=yes vs.file.ngenArchitecture=X64 vs.file.ngenPriority=2 vs.file.ngenApplication="[installDir]\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsiAnyCpu.exe" - file source="$(BinariesFolder)\fsiAnyCpu\$(Configuration)\net46\fsiAnyCpu.exe.config" - - file source="$(BinariesFolder)\FSharp.Compiler.Interactive.Settings\$(Configuration)\net46\FSharp.Compiler.Interactive.Settings.dll" vs.file.ngen=yes vs.file.ngenArchitecture=All vs.file.ngenPriority=2 - file source="$(BinariesFolder)\FSharp.Compiler.Private\$(Configuration)\net46\FSharp.Compiler.Private.dll" vs.file.ngen=yes vs.file.ngenArchitecture=All vs.file.ngenPriority=2 - file source="$(BinariesFolder)\FSharp.Compiler.Server.Shared\$(Configuration)\net46\FSharp.Compiler.Server.Shared.dll" vs.file.ngen=yes vs.file.ngenArchitecture=All vs.file.ngenPriority=2 - - file source="$(BinariesFolder)\FSharp.Core\$(Configuration)\net45\FSharp.Core.dll" vs.file.ngen=yes vs.file.ngenArchitecture=All vs.file.ngenPriority=2 - file source="$(BinariesFolder)\FSharp.Core\$(Configuration)\net45\FSharp.Core.optdata" - file source="$(BinariesFolder)\FSharp.Core\$(Configuration)\net45\FSharp.Core.sigdata" - - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\FSharp.Build.dll" vs.file.ngen=yes vs.file.ngenArchitecture=All vs.file.ngenPriority=2 - - file source="$(PackagesFolder)\Microsoft.VisualFSharp.Type.Providers.Redist\$(MicrosoftVisualFSharpTypeProvidersRedistPackageVersion)\content\4.3.0.0\FSharp.Data.TypeProviders.dll" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.Build.dll" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.Build.Framework.dll" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.Build.Tasks.Core.dll" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.Build.Utilities.Core.dll" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.Portable.FSharp.Targets" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\System.Collections.Immutable.dll" - file source="$(BinariesFolder)\FSharp.Compiler.Private\$(Configuration)\net46\System.Reflection.Metadata.dll" - file source="$(BinariesFolder)\FSharp.Compiler.Private\$(Configuration)\net46\System.ValueTuple.dll" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.FSharp.NetSdk.props" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.FSharp.NetSdk.targets" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.FSharp.Overrides.NetSdk.targets" - file source="$(BinariesFolder)\FSharp.Build\$(Configuration)\net46\Microsoft.FSharp.Targets" diff --git a/setup/Swix/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.swixproj b/setup/Swix/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.swixproj deleted file mode 100644 index f256dd46779..00000000000 --- a/setup/Swix/Microsoft.FSharp.Compiler/Microsoft.FSharp.Compiler.swixproj +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - Microsoft.FSharp.Compiler - - - - $(PackagePreprocessorDefinitions);BinariesFolder=$(BinariesFolder) - $(PackagePreprocessorDefinitions);Configuration=$(Configuration) - $(PackagePreprocessorDefinitions);PackagesFolder=$(NuGetPackageRoot) - $(PackagePreprocessorDefinitions);FSharpTreeRoot=$(FSharpTreeRoot) - $(PackagePreprocessorDefinitions);FSharpPackageVersion=$(FSharpPackageVersion) - $(PackagePreprocessorDefinitions);MicrosoftVisualFSharpTypeProvidersRedistPackageVersion=$(MicrosoftVisualFSharpTypeProvidersRedistPackageVersion) - - - - - - - - - - - - - - diff --git a/setup/Swix/Microsoft.FSharp.Dependencies/Dependencies.swr b/setup/Swix/Microsoft.FSharp.Dependencies/Dependencies.swr index 97fadaec582..82f9caaec1f 100644 --- a/setup/Swix/Microsoft.FSharp.Dependencies/Dependencies.swr +++ b/setup/Swix/Microsoft.FSharp.Dependencies/Dependencies.swr @@ -1,9 +1,9 @@ use vs package name=Microsoft.FSharp.Dependencies - version=$(FSharpPackageVersion) + version=$(VsixVersion) vs.dependencies vs.dependency id=Microsoft.FSharp.SDK - version=$(FSharpPackageVersion) + version=$(VsixVersion) type=Required diff --git a/setup/Swix/Microsoft.FSharp.Dependencies/Files.swr b/setup/Swix/Microsoft.FSharp.Dependencies/Files.swr index f927497e193..9b2836fd190 100644 --- a/setup/Swix/Microsoft.FSharp.Dependencies/Files.swr +++ b/setup/Swix/Microsoft.FSharp.Dependencies/Files.swr @@ -1,7 +1,7 @@ use vs package name=Microsoft.FSharp.Dependencies - version=$(FSharpPackageVersion) + version=$(VsixVersion) folder "InstallDir:MSBuild\Microsoft\VisualStudio\v$(VSGeneralVersion)\FSharp" file "Microsoft.FSharp.targets" source="$(SetupShimsDir)\Microsoft.FSharp.Shim.targets" @@ -11,4 +11,4 @@ folder "InstallDir:MSBuild\Microsoft\VisualStudio\v$(VSGeneralVersion)\FSharp" file "Microsoft.FSharp.NetSdk.props" source="$(SetupShimsDir)\Microsoft.FSharp.NetSdk.Shim.props" folder "InstallDir:Common7\Tools\VsDevCmd\Ext" - file source="fsharp.bat" + file source="$(ProjectDir)\fsharp.bat" diff --git a/setup/Swix/Microsoft.FSharp.Dependencies/Microsoft.FSharp.Dependencies.csproj b/setup/Swix/Microsoft.FSharp.Dependencies/Microsoft.FSharp.Dependencies.csproj new file mode 100644 index 00000000000..657be2a1f48 --- /dev/null +++ b/setup/Swix/Microsoft.FSharp.Dependencies/Microsoft.FSharp.Dependencies.csproj @@ -0,0 +1,19 @@ + + + + net46 + + + + + + + + + + + + + + + diff --git a/setup/Swix/Microsoft.FSharp.Dependencies/Microsoft.FSharp.Dependencies.swixproj b/setup/Swix/Microsoft.FSharp.Dependencies/Microsoft.FSharp.Dependencies.swixproj deleted file mode 100644 index e30eaaf0fe1..00000000000 --- a/setup/Swix/Microsoft.FSharp.Dependencies/Microsoft.FSharp.Dependencies.swixproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - Microsoft.FSharp.Dependencies - - - - $(PackagePreprocessorDefinitions);BinariesFolder=$(BinariesFolder) - $(PackagePreprocessorDefinitions);Configuration=$(Configuration) - $(PackagePreprocessorDefinitions);FSharpPackageVersion=$(FSharpPackageVersion) - $(PackagePreprocessorDefinitions);SetupShimsDir=$(MSBuildThisFileDirectory)..\..\shims - $(PackagePreprocessorDefinitions);TargetFramework=$(TargetFramework) - $(PackagePreprocessorDefinitions);VSGeneralVersion=$(VSGeneralVersion) - - - - - - - - - - - - - - - - diff --git a/setup/Swix/Microsoft.FSharp.IDE/Dependencies.swr b/setup/Swix/Microsoft.FSharp.IDE/Dependencies.swr index 875b8af13f6..9ed63a9ff0c 100644 --- a/setup/Swix/Microsoft.FSharp.IDE/Dependencies.swr +++ b/setup/Swix/Microsoft.FSharp.IDE/Dependencies.swr @@ -1,19 +1,19 @@ use vs package name=Microsoft.FSharp.IDE - version=$(FSharpPackageVersion) + version=$(VsixVersion) vs.dependencies vs.dependency id=Microsoft.FSharp.Dependencies - version=$(FSharpPackageVersion) + version=$(VsixVersion) type=Required vs.dependency id=Microsoft.FSharp.VSIX.Full.Core - version=$(FSharpPackageVersion) + version=$(VsixVersion) type=Required when=Microsoft.VisualStudio.Product.Enterprise,Microsoft.VisualStudio.Product.Professional,Microsoft.VisualStudio.Product.Community vs.dependency id=Microsoft.FSharp.VSIX.Full.Resources - version=$(FSharpPackageVersion) + version=$(VsixVersion) type=Required when=Microsoft.VisualStudio.Product.Enterprise,Microsoft.VisualStudio.Product.Professional,Microsoft.VisualStudio.Product.Community diff --git a/setup/Swix/Microsoft.FSharp.IDE/Files.swr b/setup/Swix/Microsoft.FSharp.IDE/Files.swr index 2e0ee2bcf3b..79257b19395 100644 --- a/setup/Swix/Microsoft.FSharp.IDE/Files.swr +++ b/setup/Swix/Microsoft.FSharp.IDE/Files.swr @@ -1,7 +1,7 @@ use vs package name=Microsoft.FSharp.IDE - version=$(FSharpPackageVersion) + version=$(VsixVersion) folder "InstallDir:Common7\IDE\NewScriptItems" file source="$(SetupResourcesDir)\NewFileDialog\Script\NewFSharpScriptItems.vsdir" diff --git a/setup/Swix/Microsoft.FSharp.IDE/Microsoft.FSharp.IDE.csproj b/setup/Swix/Microsoft.FSharp.IDE/Microsoft.FSharp.IDE.csproj new file mode 100644 index 00000000000..c86f94ec07a --- /dev/null +++ b/setup/Swix/Microsoft.FSharp.IDE/Microsoft.FSharp.IDE.csproj @@ -0,0 +1,17 @@ + + + + net46 + + + + + + + + + + + + + diff --git a/setup/Swix/Microsoft.FSharp.IDE/Microsoft.FSharp.IDE.swixproj b/setup/Swix/Microsoft.FSharp.IDE/Microsoft.FSharp.IDE.swixproj deleted file mode 100644 index 223a7262fcb..00000000000 --- a/setup/Swix/Microsoft.FSharp.IDE/Microsoft.FSharp.IDE.swixproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - Microsoft.FSharp.IDE - - - - $(PackagePreprocessorDefinitions);FSharpPackageVersion=$(FSharpPackageVersion) - $(PackagePreprocessorDefinitions);SetupResourcesDir=$(MSBuildThisFileDirectory)..\..\resources - $(PackagePreprocessorDefinitions);TargetFramework=$(TargetFramework) - - - - - - - - - - - - - - - diff --git a/setup/Swix/Microsoft.FSharp.SDK/Files.swr b/setup/Swix/Microsoft.FSharp.SDK/Files.swr index cffd90ed366..38ac95d4ec8 100644 --- a/setup/Swix/Microsoft.FSharp.SDK/Files.swr +++ b/setup/Swix/Microsoft.FSharp.SDK/Files.swr @@ -1,7 +1,7 @@ use vs package name=Microsoft.FSharp.SDK - version=$(FSharpPackageVersion) + version=$(VsixVersion) folder "InstallDir:Common7\IDE\CommonExtensions\Microsoft\FSharpSdk" diff --git a/setup/Swix/Microsoft.FSharp.SDK/Microsoft.FSharp.SDK.csproj b/setup/Swix/Microsoft.FSharp.SDK/Microsoft.FSharp.SDK.csproj new file mode 100644 index 00000000000..d736e5c5c55 --- /dev/null +++ b/setup/Swix/Microsoft.FSharp.SDK/Microsoft.FSharp.SDK.csproj @@ -0,0 +1,23 @@ + + + + net46 + + + + + + + + + + + + + + + + + + + diff --git a/setup/Swix/Microsoft.FSharp.SDK/Microsoft.FSharp.SDK.swixproj b/setup/Swix/Microsoft.FSharp.SDK/Microsoft.FSharp.SDK.swixproj deleted file mode 100644 index aac26eaaa0d..00000000000 --- a/setup/Swix/Microsoft.FSharp.SDK/Microsoft.FSharp.SDK.swixproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - Microsoft.FSharp.SDK - - - - $(PackagePreprocessorDefinitions);PackagesFolder=$(NuGetPackageRoot) - $(PackagePreprocessorDefinitions);FSharpPackageVersion=$(FSharpPackageVersion) - - - - - - - - - - - - - diff --git a/setup/Swix/Microsoft.FSharp.Vsix.Resources/Empty.swr b/setup/Swix/Microsoft.FSharp.Vsix.Resources/Empty.swr deleted file mode 100644 index dd1ca136dac..00000000000 --- a/setup/Swix/Microsoft.FSharp.Vsix.Resources/Empty.swr +++ /dev/null @@ -1,6 +0,0 @@ -use vs - -package name=Microsoft.FSharp.VSIX.Full.Resources - version=$(FSharpPackageVersion) - vs.package.language=$(LocaleSpecificCulture) - vs.package.installSize=1 diff --git a/setup/Swix/Microsoft.FSharp.Vsix.Resources/Files.swr b/setup/Swix/Microsoft.FSharp.Vsix.Resources/Files.swr deleted file mode 100644 index f3b95d49900..00000000000 --- a/setup/Swix/Microsoft.FSharp.Vsix.Resources/Files.swr +++ /dev/null @@ -1,20 +0,0 @@ -use vs - -package name=Microsoft.FSharp.VSIX.Full.Resources - version=$(FSharpPackageVersion) - vs.package.language=$(LocaleSpecificCulture) - -folder "InstallDir:Common7\IDE\PublicAssemblies\$(LocaleParentCulture)" - file source="$(BinariesFolder)\FSharp.Core\$(Configuration)\net45\$(LocaleParentCulture)\FSharp.Core.resources.dll" vs.file.ngen=yes - -folder "InstallDir:Common7\IDE\CommonExtensions\Microsoft\FSharp\$(LocaleParentCulture)" - file source="$(BinariesFolder)\FSharp.Compiler.Private\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.Compiler.Private.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\FSharp.Core\$(Configuration)\net45\$(LocaleParentCulture)\FSharp.Core.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\FSharp.Editor\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.Editor.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\FSharp.LanguageService.Base\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.LanguageService.Base.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\FSharp.LanguageService\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.LanguageService.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\ProjectSystem.Base\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.ProjectSystem.Base.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\ProjectSystem\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.ProjectSystem.FSharp.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\FSharp.PropertiesPages\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.ProjectSystem.PropertyPages.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\FSharp.UIResources\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.UIResources.resources.dll" vs.file.ngen=yes - file source="$(BinariesFolder)\FSharp.VS.FSI\$(Configuration)\net46\$(LocaleParentCulture)\FSharp.VS.FSI.resources.dll" vs.file.ngen=yes diff --git a/setup/Swix/Microsoft.FSharp.Vsix.Resources/Microsoft.FSharp.Vsix.Resources.swixproj b/setup/Swix/Microsoft.FSharp.Vsix.Resources/Microsoft.FSharp.Vsix.Resources.swixproj deleted file mode 100644 index d8952b40fe7..00000000000 --- a/setup/Swix/Microsoft.FSharp.Vsix.Resources/Microsoft.FSharp.Vsix.Resources.swixproj +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - Microsoft.FSharp.VSIX.Full.Resources.$(LocaleCode) - - - - $(PackagePreprocessorDefinitions);Configuration=$(Configuration) - $(PackagePreprocessorDefinitions);BinariesFolder=$(BinariesFolder) - $(PackagePreprocessorDefinitions);FSharpPackageVersion=$(FSharpPackageVersion) - $(PackagePreprocessorDefinitions);LocaleCode=$(LocaleCode) - $(PackagePreprocessorDefinitions);LocaleId=$(LocaleId) - $(PackagePreprocessorDefinitions);LocaleParentId=$(LocaleParentId) - $(PackagePreprocessorDefinitions);LocaleParentCulture=$(LocaleParentCulture) - $(PackagePreprocessorDefinitions);LocaleSpecificCulture=$(LocaleSpecificCulture) - $(PackagePreprocessorDefinitions);IsLangPack=$(IsLangPack) - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/setup/Swix/Microsoft.FSharp.Vsix.Resources/Templates.swr b/setup/Swix/Microsoft.FSharp.Vsix.Resources/Templates.swr deleted file mode 100644 index 5de89f0cadd..00000000000 --- a/setup/Swix/Microsoft.FSharp.Vsix.Resources/Templates.swr +++ /dev/null @@ -1,13 +0,0 @@ -use vs - -package name=Microsoft.FSharp.VSIX.Full.Resources - version=$(FSharpPackageVersion) - vs.package.language=$(LocaleSpecificCulture) - -folder "InstallDir:Common7\IDE\ProjectTemplates\FSharp\$(LocaleId)" - folder "ConsoleApplication" - file source="$(BinariesFolder)\ConsoleProject\$(Configuration)\$(LocaleParentId)\ConsoleApplication.zip" - folder "Library" - file source="$(BinariesFolder)\LibraryProject\$(Configuration)\$(LocaleParentId)\Library.zip" - folder "Tutorial" - file source="$(BinariesFolder)\TutorialProject\$(Configuration)\$(LocaleParentId)\Tutorial.zip" diff --git a/setup/Swix/Microsoft.FSharp.vsmanproj b/setup/Swix/Microsoft.FSharp.vsmanproj deleted file mode 100644 index a09ca5442f5..00000000000 --- a/setup/Swix/Microsoft.FSharp.vsmanproj +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - true - true - $(ArtifactsDir)\VSSetup\$(Configuration)\Insertion - $(OutputPath) - $(FSharpPackageVersion) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/setup/build-insertion.proj b/setup/build-insertion.proj deleted file mode 100644 index b132d3edfea..00000000000 --- a/setup/build-insertion.proj +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - . - Debug - - - - - - Swix\Microsoft.FSharp.SDK\Microsoft.FSharp.SDK.swixproj - - - Swix\Microsoft.FSharp.Compiler\Microsoft.FSharp.Compiler.swixproj - - - - - - - - - - - AssemblySearchPaths={HintPathFromItem};{TargetFrameworkDirectory};{RawFileName} - - - - - - - - - - - - - - - diff --git a/setup/fsharp-setup-build.csproj b/setup/fsharp-setup-build.csproj deleted file mode 100644 index 074879dc20e..00000000000 --- a/setup/fsharp-setup-build.csproj +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - net46 - - - - - - - - - - - - - - - - - - - - - - - Swix\Microsoft.FSharp.Dependencies\Microsoft.FSharp.Dependencies.swixproj - - - Swix\Microsoft.FSharp.IDE\Microsoft.FSharp.IDE.swixproj - - - - - - - - - - - - - - - AssemblySearchPaths={HintPathFromItem};{TargetFrameworkDirectory};{RawFileName} - - - - - diff --git a/src/Directory.Build.props b/src/Directory.Build.props deleted file mode 100644 index bb8eac309b1..00000000000 --- a/src/Directory.Build.props +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/Directory.Build.targets b/src/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/src/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/src/buildtools/buildtools.targets b/src/buildtools/buildtools.targets index 9b00e18cf72..303ab00825d 100644 --- a/src/buildtools/buildtools.targets +++ b/src/buildtools/buildtools.targets @@ -1,10 +1,15 @@ - dotnet - dotnet.exe - + + dotnet + dotnet.exe + + $(DOTNET_HOST_PATH) $(DotNetExe) + + + $(DotNetExePath) @@ -15,14 +20,14 @@ BeforeTargets="CoreCompile"> - $(ArtifactsBinDir)\fslex\Proto\netcoreapp2.0\fslex.dll + $(ArtifactsDir)\Bootstrap\fslex.dll - + @@ -38,14 +43,14 @@ BeforeTargets="CoreCompile"> - $(ArtifactsBinDir)\fsyacc\Proto\netcoreapp2.0\fsyacc.dll + $(ArtifactsDir)\Bootstrap\fsyacc.dll - + diff --git a/src/fsharp/Directory.Nuget.props b/src/fsharp/Directory.Nuget.props deleted file mode 100644 index 6521936cfe3..00000000000 --- a/src/fsharp/Directory.Nuget.props +++ /dev/null @@ -1,27 +0,0 @@ - - - - https://github.com/Microsoft/visualfsharp/blob/master/License.txt - https://github.com/Microsoft/visualfsharp - Microsoft and F# Software Foundation - Microsoft and F# Software Foundation - Visual F# Compiler FSharp functional programming - (C) Microsoft Corporation. All rights reserved. - - $(GitHeadSha) - [developer build] - - - licenseUrl=$(PackageLicenceUrl); - authors=$(PackageAuthors); - owners=$(PackageOwners); - projectUrl=$(PackageProjectUrl); - copyright=$(PackageCopyright); - tags=$(PackageTags); - githeadsha=$(NormalizedGitHeadSha); - configuration=$(Configuration); - artifactsbindir=$(ArtifactsBinDir); - - - - diff --git a/src/fsharp/Directory.Nuget.targets b/src/fsharp/Directory.Nuget.targets deleted file mode 100644 index e30b155faad..00000000000 --- a/src/fsharp/Directory.Nuget.targets +++ /dev/null @@ -1,11 +0,0 @@ - - - - - $(NuspecProperties); - packageId=$(PackageId); - version=$(PackageVersion); - - - - diff --git a/src/fsharp/FSharp.Build/Directory.Build.props b/src/fsharp/FSharp.Build/Directory.Build.props new file mode 100644 index 00000000000..7cd41381b5d --- /dev/null +++ b/src/fsharp/FSharp.Build/Directory.Build.props @@ -0,0 +1,9 @@ + + + + true + + + + + diff --git a/src/fsharp/FSharp.Build/FSharp.Build.fsproj b/src/fsharp/FSharp.Build/FSharp.Build.fsproj index 162c6bf3d31..4bf0eb97289 100644 --- a/src/fsharp/FSharp.Build/FSharp.Build.fsproj +++ b/src/fsharp/FSharp.Build/FSharp.Build.fsproj @@ -5,11 +5,11 @@ Library net46;netstandard2.0 + netstandard2.0 FSharp.Build $(NoWarn);45;55;62;75;1204 true $(OtherFlags) --maxerrors:20 --extraoptimizationloops:1 - true diff --git a/src/fsharp/FSharp.Compiler.Interactive.Settings/Directory.Build.props b/src/fsharp/FSharp.Compiler.Interactive.Settings/Directory.Build.props new file mode 100644 index 00000000000..7cd41381b5d --- /dev/null +++ b/src/fsharp/FSharp.Compiler.Interactive.Settings/Directory.Build.props @@ -0,0 +1,9 @@ + + + + true + + + + + diff --git a/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj b/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj index 06a4c43055f..3569093c47f 100644 --- a/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj +++ b/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj @@ -5,11 +5,11 @@ Library net46;netstandard2.0 + netstandard2.0 FSharp.Compiler.Interactive.Settings $(NoWarn);45;55;62;75;1182;1204 true $(OtherFlags) --maxerrors:20 --extraoptimizationloops:1 - true diff --git a/src/fsharp/FSharp.Compiler.Private/Directory.Build.props b/src/fsharp/FSharp.Compiler.Private/Directory.Build.props new file mode 100644 index 00000000000..7cd41381b5d --- /dev/null +++ b/src/fsharp/FSharp.Compiler.Private/Directory.Build.props @@ -0,0 +1,9 @@ + + + + true + + + + + diff --git a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj index 7f4546da3a6..ce3e578f7ae 100644 --- a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj +++ b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj @@ -5,21 +5,27 @@ Library net46;netstandard2.0 + netstandard2.0 FSharp.Compiler.Private $(NoWarn);45;55;62;75;1204 true $(DefineConstants);COMPILER $(DefineConstants);MSBUILD_AT_LEAST_15 $(OtherFlags) --warnon:1182 --maxerrors:20 --extraoptimizationloops:1 - true true true true - + full + false + + + + + false diff --git a/src/fsharp/FSharp.Compiler.Server.Shared/Directory.Build.props b/src/fsharp/FSharp.Compiler.Server.Shared/Directory.Build.props new file mode 100644 index 00000000000..7cd41381b5d --- /dev/null +++ b/src/fsharp/FSharp.Compiler.Server.Shared/Directory.Build.props @@ -0,0 +1,9 @@ + + + + true + + + + + diff --git a/src/fsharp/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj b/src/fsharp/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj index 4feaf0da4e1..2940172c7e6 100644 --- a/src/fsharp/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj +++ b/src/fsharp/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj @@ -4,8 +4,6 @@ net46 - FSharp.Compiler.Server.Shared - true diff --git a/src/fsharp/FSharp.Compiler.nuget/Directory.Build.props b/src/fsharp/FSharp.Compiler.nuget/Directory.Build.props index 8093275dba0..7cd41381b5d 100644 --- a/src/fsharp/FSharp.Compiler.nuget/Directory.Build.props +++ b/src/fsharp/FSharp.Compiler.nuget/Directory.Build.props @@ -1,11 +1,9 @@ - - - - + - netcoreapp2.1 - Microsoft.FSharp.Compiler.nuspec + true + + diff --git a/src/fsharp/FSharp.Compiler.nuget/Directory.Build.targets b/src/fsharp/FSharp.Compiler.nuget/Directory.Build.targets deleted file mode 100644 index 2721c93a906..00000000000 --- a/src/fsharp/FSharp.Compiler.nuget/Directory.Build.targets +++ /dev/null @@ -1,18 +0,0 @@ - - - - -rtm-$(NuGetPackageVersionSuffix) - $(FSPackageVersion)$(PreReleaseSuffix) - - - - - - - - - - - - - diff --git a/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.Prerelease.csproj b/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.Prerelease.csproj deleted file mode 100644 index 692e5aba1b2..00000000000 --- a/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.Prerelease.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Microsoft.FSharp.Compiler - true - - - diff --git a/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.csproj b/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.csproj index 692e5aba1b2..d6306806993 100644 --- a/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.csproj +++ b/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.csproj @@ -1,8 +1,28 @@ - + - Microsoft.FSharp.Compiler true + netcoreapp2.1 + Microsoft.FSharp.Compiler.nuspec + true + .NET Core compatible version of the F# compiler fsc.exe. + + + TargetFramework=netcoreapp2.1 + + + TargetFramework=netcoreapp2.1 + + + TargetFramework=netstandard2.0 + + + TargetFramework=netstandard2.0 + + + + + diff --git a/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.nuspec b/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.nuspec index 1082f9b47b3..e73c9e2452b 100644 --- a/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.nuspec +++ b/src/fsharp/FSharp.Compiler.nuget/Microsoft.FSharp.Compiler.nuspec @@ -1,19 +1,8 @@ - $packageId$ - - .NET Core compatible version of the F# compiler fsc.exe. - Supported Platforms: - .NET Core (.netstandard2.0). - Commit hash: $githeadsha$. - + $CommonMetadataElements$ en-US - true - $version$ - $authors$ - $licenseUrl$ - $projectUrl$ - $tags$ @@ -54,35 +43,35 @@ this approach gives a very small deployment. Which is kind of necessary. --> - - - - - - + + + + + - - - - - - + + + + + - - - - - - + + + + + + - - + - - + diff --git a/src/fsharp/FSharp.Compiler.nuget/Testing.FSharp.Compiler.csproj b/src/fsharp/FSharp.Compiler.nuget/Testing.FSharp.Compiler.csproj deleted file mode 100644 index aaee9c73942..00000000000 --- a/src/fsharp/FSharp.Compiler.nuget/Testing.FSharp.Compiler.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - Testing.FSharp.Compiler - true - - - diff --git a/src/fsharp/FSharp.Compiler.nuget/_._ b/src/fsharp/FSharp.Compiler.nuget/_._ deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/src/fsharp/FSharp.Core/Directory.Build.props b/src/fsharp/FSharp.Core/Directory.Build.props deleted file mode 100644 index cee6fa763d9..00000000000 --- a/src/fsharp/FSharp.Core/Directory.Build.props +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - $(NuspecProperties); - fsCoreMajorVersion=$(FSCoreMajorVersion); - fsPackageMajorVersion=$(FSPackageMajorVersion); - - - - diff --git a/src/fsharp/FSharp.Core/Directory.Build.targets b/src/fsharp/FSharp.Core/Directory.Build.targets deleted file mode 100644 index 8bf68e8bc7b..00000000000 --- a/src/fsharp/FSharp.Core/Directory.Build.targets +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/src/fsharp/FSharp.Core/FSharp.Core.fsproj b/src/fsharp/FSharp.Core/FSharp.Core.fsproj index 6ddda3f2e7e..de0fca82aa6 100644 --- a/src/fsharp/FSharp.Core/FSharp.Core.fsproj +++ b/src/fsharp/FSharp.Core/FSharp.Core.fsproj @@ -5,9 +5,9 @@ Library net45;netstandard1.6 - FSharp.Core - FSharp.Core - $(FSCorePackageVersion) + netstandard1.6 + true + FSharp.Core redistributables from Visual F# Tools version $(FSPackageMajorVersion) For F# $(FSCoreMajorVersion) FSharp.Core.nuspec $(NoWarn);45;55;62;75;1204 true diff --git a/src/fsharp/FSharp.Core/FSharp.Core.nuspec b/src/fsharp/FSharp.Core/FSharp.Core.nuspec index 0fa30ba781f..b11df35fca0 100644 --- a/src/fsharp/FSharp.Core/FSharp.Core.nuspec +++ b/src/fsharp/FSharp.Core/FSharp.Core.nuspec @@ -1,27 +1,8 @@ - FSharp.Core - FSharp.Core for F# $fsCoreMajorVersion$ - FSharp.Core for F# $fsCoreMajorVersion$ - - FSharp.Core redistributables from Visual F# Tools version $fsPackageMajorVersion$ For F# $fsCoreMajorVersion$ - Supported Platforms: - .NET Framework 4.5+ (net45) - netstandard1.6 (netstandard1.6) - netstandard2.0 (netstandard2.0) - - Commit hash: $githeadsha$ - - $owners$ - $version$ - $authors$ - $copyright$ - $licenseUrl$ - $projectUrl$ + $CommonMetadataElements$ http://fsharp.org/img/logo.png - $tags$ - true en-US @@ -56,18 +37,18 @@ - - - - + + + + - - - - + + + + - - + + diff --git a/src/fsharp/fsc/Directory.Build.props b/src/fsharp/fsc/Directory.Build.props new file mode 100644 index 00000000000..7cd41381b5d --- /dev/null +++ b/src/fsharp/fsc/Directory.Build.props @@ -0,0 +1,9 @@ + + + + true + + + + + diff --git a/src/fsharp/fsc/fsc.fsproj b/src/fsharp/fsc/fsc.fsproj index a2e5127b61a..581b4a11797 100644 --- a/src/fsharp/fsc/fsc.fsproj +++ b/src/fsharp/fsc/fsc.fsproj @@ -5,12 +5,11 @@ Exe net46;netcoreapp2.1 + netcoreapp2.1 .exe - fsc $(NoWarn);45;55;62;75;1204 true $(OtherFlags) --maxerrors:20 --extraoptimizationloops:1 - true true true diff --git a/src/fsharp/fsi/Directory.Build.props b/src/fsharp/fsi/Directory.Build.props new file mode 100644 index 00000000000..7cd41381b5d --- /dev/null +++ b/src/fsharp/fsi/Directory.Build.props @@ -0,0 +1,9 @@ + + + + true + + + + + diff --git a/src/fsharp/fsi/fsi.fsproj b/src/fsharp/fsi/fsi.fsproj index b8b6a9a020f..77a9274a1e6 100644 --- a/src/fsharp/fsi/fsi.fsproj +++ b/src/fsharp/fsi/fsi.fsproj @@ -5,13 +5,12 @@ Exe net46;netcoreapp2.1 + netcoreapp2.1 .exe - fsi $(NoWarn);45;55;62;75;1204 true $(OtherFlags) --warnon:1182 --maxerrors:20 --extraoptimizationloops:1 fsi.res - true true true diff --git a/src/fsharp/fsiAnyCpu/Directory.Build.props b/src/fsharp/fsiAnyCpu/Directory.Build.props new file mode 100644 index 00000000000..7cd41381b5d --- /dev/null +++ b/src/fsharp/fsiAnyCpu/Directory.Build.props @@ -0,0 +1,9 @@ + + + + true + + + + + diff --git a/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj b/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj index 200bd6d40a3..868b379f234 100644 --- a/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj +++ b/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj @@ -7,12 +7,10 @@ net46 AnyCPU .exe - fsiAnyCpu $(NoWarn);45;55;62;75;1204 true $(OtherFlags) --warnon:1182 --maxerrors:20 --extraoptimizationloops:1 ..\fsi\fsi.res - true true diff --git a/test.sh b/test.sh new file mode 100755 index 00000000000..ea8631bd230 --- /dev/null +++ b/test.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +source="${BASH_SOURCE[0]}" + +# resolve $SOURCE until the file is no longer a symlink +while [[ -h $source ]]; do + scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" + source="$(readlink "$source")" + + # if $source was a relative symlink, we need to resolve it relative to the path where the + # symlink file was located + [[ $source != /* ]] && source="$scriptroot/$source" +done + +scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" +"$scriptroot/eng/build.sh" --test $@ diff --git a/tests/Directory.Build.targets b/tests/Directory.Build.targets new file mode 100644 index 00000000000..4bf59eb4aa6 --- /dev/null +++ b/tests/Directory.Build.targets @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/tests/FSharp.Build.UnitTests/Directory.Build.props b/tests/FSharp.Build.UnitTests/Directory.Build.props index bb8eac309b1..7cd41381b5d 100644 --- a/tests/FSharp.Build.UnitTests/Directory.Build.props +++ b/tests/FSharp.Build.UnitTests/Directory.Build.props @@ -1,3 +1,9 @@ - + + + true + + + + diff --git a/tests/FSharp.Build.UnitTests/Directory.Build.targets b/tests/FSharp.Build.UnitTests/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/tests/FSharp.Build.UnitTests/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/FSharp.Build.UnitTests/FSharp.Build.UnitTests.fsproj b/tests/FSharp.Build.UnitTests/FSharp.Build.UnitTests.fsproj index 9e04e6e5845..fa9b74422c4 100644 --- a/tests/FSharp.Build.UnitTests/FSharp.Build.UnitTests.fsproj +++ b/tests/FSharp.Build.UnitTests/FSharp.Build.UnitTests.fsproj @@ -4,6 +4,7 @@ net46;netcoreapp2.0 + netcoreapp2.0 Library true nunit diff --git a/tests/FSharp.Compiler.UnitTests/Directory.Build.props b/tests/FSharp.Compiler.UnitTests/Directory.Build.props index bb8eac309b1..7cd41381b5d 100644 --- a/tests/FSharp.Compiler.UnitTests/Directory.Build.props +++ b/tests/FSharp.Compiler.UnitTests/Directory.Build.props @@ -1,3 +1,9 @@ - + + + true + + + + diff --git a/tests/FSharp.Compiler.UnitTests/Directory.Build.targets b/tests/FSharp.Compiler.UnitTests/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/tests/FSharp.Compiler.UnitTests/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj b/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj index 4b9f4d21a30..a1acb6f9fda 100644 --- a/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj +++ b/tests/FSharp.Compiler.UnitTests/FSharp.Compiler.UnitTests.fsproj @@ -4,6 +4,7 @@ net46;netcoreapp2.0 + netcoreapp2.0 Library true nunit diff --git a/tests/FSharp.Compiler.UnitTests/Language/StringConcat.fs b/tests/FSharp.Compiler.UnitTests/Language/StringConcat.fs index fa18e7bb427..4069052a033 100644 --- a/tests/FSharp.Compiler.UnitTests/Language/StringConcat.fs +++ b/tests/FSharp.Compiler.UnitTests/Language/StringConcat.fs @@ -8,7 +8,10 @@ open NUnit.Framework [] module StringConcat = +// helper methods in this test only run on the full framework +#if !NETCOREAPP [] +#endif let Optimizations () = let baseSource = """ module Test diff --git a/tests/FSharp.Core.UnitTests/Directory.Build.props b/tests/FSharp.Core.UnitTests/Directory.Build.props deleted file mode 100644 index bb8eac309b1..00000000000 --- a/tests/FSharp.Core.UnitTests/Directory.Build.props +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/FSharp.Core.UnitTests/Directory.Build.targets b/tests/FSharp.Core.UnitTests/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/tests/FSharp.Core.UnitTests/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj index 54b955b2c1e..31351eca6b2 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj @@ -4,6 +4,7 @@ net46;netcoreapp2.0 + netcoreapp2.0 Library FSharp.Core.UnitTests @@ -12,9 +13,11 @@ true true - xunit + nunit true true + MIT + false @@ -93,7 +96,6 @@ - @@ -101,9 +103,4 @@ - - - - - diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/App.config b/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/App.config deleted file mode 100644 index 47c31e4eac0..00000000000 --- a/tests/FSharp.Core.UnitTests/FSharp.Core/Microsoft.FSharp.Control/App.config +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/FSharp.Directory.Build.props b/tests/FSharp.Directory.Build.props deleted file mode 100644 index f073b7b0858..00000000000 --- a/tests/FSharp.Directory.Build.props +++ /dev/null @@ -1,36 +0,0 @@ - - - - - $(ArtifactsPackagesDir)\$(Configuration) - - - - $(DefineConstants);FX_VERIFY_SURFACEAREA - - - - https://github.com/Microsoft/visualfsharp/blob/master/License.txt - https://github.com/Microsoft/visualfsharp - Microsoft and F# Software Foundation - Microsoft and F# Software Foundation - Visual F# Compiler FSharp functional programming - (C) Microsoft Corporation. All rights reserved. - - $(GitHeadSha) - [developer build] - - - licenseUrl=$(PackageLicenceUrl); - authors=$(PackageAuthors); - owners=$(PackageOwners); - projectUrl=$(PackageProjectUrl); - copyright=$(PackageCopyright); - tags=$(PackageTags); - githeadsha=$(NormalizedGitHeadSha); - configuration=$(Configuration); - artifactsbindir=$(ArtifactsBinDir); - - - - diff --git a/tests/FSharp.Directory.Build.targets b/tests/FSharp.Directory.Build.targets deleted file mode 100644 index 590214e9b00..00000000000 --- a/tests/FSharp.Directory.Build.targets +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/tests/Resources/Directory.Build.props b/tests/Resources/Directory.Build.props new file mode 100644 index 00000000000..08b24f28003 --- /dev/null +++ b/tests/Resources/Directory.Build.props @@ -0,0 +1,3 @@ + + + diff --git a/tests/Resources/Directory.Build.targets b/tests/Resources/Directory.Build.targets new file mode 100644 index 00000000000..08b24f28003 --- /dev/null +++ b/tests/Resources/Directory.Build.targets @@ -0,0 +1,3 @@ + + + diff --git a/tests/fsharp/Directory.Build.props b/tests/fsharp/Directory.Build.props index bb8eac309b1..7cd41381b5d 100644 --- a/tests/fsharp/Directory.Build.props +++ b/tests/fsharp/Directory.Build.props @@ -1,3 +1,9 @@ - + + + true + + + + diff --git a/tests/fsharp/Directory.Build.targets b/tests/fsharp/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/tests/fsharp/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/fsharp/FSharp.Tests.FSharpSuite.fsproj b/tests/fsharp/FSharpSuite.Tests.fsproj similarity index 96% rename from tests/fsharp/FSharp.Tests.FSharpSuite.fsproj rename to tests/fsharp/FSharpSuite.Tests.fsproj index 97aa63d88fb..057ff6af08f 100644 --- a/tests/fsharp/FSharp.Tests.FSharpSuite.fsproj +++ b/tests/fsharp/FSharpSuite.Tests.fsproj @@ -3,6 +3,7 @@ net46;netcoreapp2.0 + netcoreapp2.0 win-x86;win-x64 $(AssetTargetFallback);portable-net45+win8+wp8+wpa81 true diff --git a/tests/fsharp/single-test.fs b/tests/fsharp/single-test.fs index 557ee021ed9..b0a24ccb8e9 100644 --- a/tests/fsharp/single-test.fs +++ b/tests/fsharp/single-test.fs @@ -68,7 +68,7 @@ let generateProps testCompilerVersion = Release $(TESTCOMPILERVERSION) - + " template |> replaceTokens "$(PROJECTDIRECTORY)" (Path.GetFullPath(__SOURCE_DIRECTORY__)) @@ -76,7 +76,7 @@ let generateProps testCompilerVersion = let generateTargets = let template = @" - + " template diff --git a/tests/fsharp/test-framework.fs b/tests/fsharp/test-framework.fs index 7c535ae549e..1e40e0bd3ea 100644 --- a/tests/fsharp/test-framework.fs +++ b/tests/fsharp/test-framework.fs @@ -184,7 +184,11 @@ let config configurationName envVars = let FSI_FOR_SCRIPTS = artifactsBinPath ++ "fsi" ++ configurationName ++ fsiArchitecture ++ "fsi.exe" let FSharpBuild = requireFile (artifactsBinPath ++ "FSharp.Build" ++ configurationName ++ fsharpBuildArchitecture ++ "FSharp.Build.dll") let FSharpCompilerInteractiveSettings = requireFile (artifactsBinPath ++ "FSharp.Compiler.Interactive.Settings" ++ configurationName ++ fsharpCompilerInteractiveSettingsArchitecture ++ "FSharp.Compiler.Interactive.Settings.dll") - let dotNetExe = artifactsPath ++ "toolset" ++ "dotnet" ++ "dotnet.exe" + let dotNetExe = + // first look for {repoRoot}\.dotnet\dotnet.exe, otherwise fallback to %PATH% + let repoLocalDotnetPath = repoRoot ++ ".dotnet" ++ "dotnet.exe" + if File.Exists(repoLocalDotnetPath) then repoLocalDotnetPath + else "dotnet.exe" // ildasm requires coreclr.dll to run which has already been restored to the packages directory File.Copy(coreclrdll, Path.GetDirectoryName(ILDASM) ++ "coreclr.dll", overwrite=true) diff --git a/tests/fsharp/tests.fs b/tests/fsharp/tests.fs index dbd5dbc0170..b109b9a8956 100644 --- a/tests/fsharp/tests.fs +++ b/tests/fsharp/tests.fs @@ -75,7 +75,7 @@ module CoreTests = let namespaceAttributes () = singleTestBuildAndRun "core/namespaces" FSC_BASIC [] - let unicode2 () = singleTestBuildAndRun "core/unicode" FSC_BASIC + let unicode2 () = singleTestBuildAndRun "core/unicode" FSC_BASIC // TODO: fails on coreclr [] let ``unicode2-FSI_BASIC`` () = singleTestBuildAndRun "core/unicode" FSI_BASIC @@ -164,7 +164,7 @@ module CoreTests = #if !FSHARP_SUITE_DRIVES_CORECLR_TESTS [] - let ``quotes-FSC-BASIC`` () = singleTestBuildAndRun "core/quotes" FSC_BASIC + let ``quotes-FSC-BASIC`` () = singleTestBuildAndRun "core/quotes" FSC_BASIC // TODO: fails on coreclr [] let ``attributes-FSC_BASIC`` () = singleTestBuildAndRun "core/attributes" FSC_BASIC diff --git a/tests/fsharpqa/Source/CodeGen/StringEncoding/.gitignore b/tests/fsharpqa/Source/CodeGen/StringEncoding/.gitignore new file mode 100644 index 00000000000..2bc99dcf85e --- /dev/null +++ b/tests/fsharpqa/Source/CodeGen/StringEncoding/.gitignore @@ -0,0 +1,3 @@ +# generated as part of the test +oracle.cs +testcase.fs diff --git a/tests/fsharpqa/Source/CodeGen/StringEncoding/env.lst b/tests/fsharpqa/Source/CodeGen/StringEncoding/env.lst index ec112a51d2e..6dba35a3cb9 100644 --- a/tests/fsharpqa/Source/CodeGen/StringEncoding/env.lst +++ b/tests/fsharpqa/Source/CodeGen/StringEncoding/env.lst @@ -1,5 +1,5 @@ - SOURCE="dummy.fs testcase.fs" PRECMD="\$FSI_PIPE --exec NormalizationFormKC.fsx > oracle.cs && csc oracle.cs && oracle.exe>testcase.fs" # FormKC - SOURCE="dummy.fs testcase.fs" PRECMD="\$FSI_PIPE --exec NormalizationFormKD.fsx > oracle.cs && csc oracle.cs && oracle.exe>testcase.fs" # FormKD - SOURCE="dummy.fs testcase.fs" PRECMD="\$FSI_PIPE --exec NormalizationFormC.fsx > oracle.cs && csc oracle.cs && oracle.exe>testcase.fs" # FormC - SOURCE="dummy.fs testcase.fs" PRECMD="\$FSI_PIPE --exec NormalizationFormD.fsx > oracle.cs && csc oracle.cs && oracle.exe>testcase.fs" # FormD + SOURCE="dummy.fs testcase.fs" PRECMD="\$FSI_PIPE --exec NormalizationFormKC.fsx > oracle.cs && \$CSC_PIPE oracle.cs && oracle.exe>testcase.fs" # FormKC + SOURCE="dummy.fs testcase.fs" PRECMD="\$FSI_PIPE --exec NormalizationFormKD.fsx > oracle.cs && \$CSC_PIPE oracle.cs && oracle.exe>testcase.fs" # FormKD + SOURCE="dummy.fs testcase.fs" PRECMD="\$FSI_PIPE --exec NormalizationFormC.fsx > oracle.cs && \$CSC_PIPE oracle.cs && oracle.exe>testcase.fs" # FormC + SOURCE="dummy.fs testcase.fs" PRECMD="\$FSI_PIPE --exec NormalizationFormD.fsx > oracle.cs && \$CSC_PIPE oracle.cs && oracle.exe>testcase.fs" # FormD diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/gccerrors/.gitignore b/tests/fsharpqa/Source/CompilerOptions/fsc/gccerrors/.gitignore new file mode 100644 index 00000000000..af1ac38976b --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/gccerrors/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +gccerrors01.txt diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/help/.gitignore b/tests/fsharpqa/Source/CompilerOptions/fsc/help/.gitignore new file mode 100644 index 00000000000..5641b0f57a4 --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/help/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +help40.txt diff --git a/tests/fsharpqa/Source/CompilerOptions/fsc/nologo/.gitignore b/tests/fsharpqa/Source/CompilerOptions/fsc/nologo/.gitignore new file mode 100644 index 00000000000..b852d34929d --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsc/nologo/.gitignore @@ -0,0 +1,3 @@ +# generated as part of the test +logo.txt +nologo.txt diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/exename/.gitignore b/tests/fsharpqa/Source/CompilerOptions/fsi/exename/.gitignore new file mode 100644 index 00000000000..5107f2d354b --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/exename/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +help.txt diff --git a/tests/fsharpqa/Source/CompilerOptions/fsi/help/.gitignore b/tests/fsharpqa/Source/CompilerOptions/fsi/help/.gitignore new file mode 100644 index 00000000000..5107f2d354b --- /dev/null +++ b/tests/fsharpqa/Source/CompilerOptions/fsi/help/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +help.txt diff --git a/tests/fsharpqa/Source/Conformance/LexicalAnalysis/IdentifiersAndKeywords/.gitignore b/tests/fsharpqa/Source/Conformance/LexicalAnalysis/IdentifiersAndKeywords/.gitignore new file mode 100644 index 00000000000..87df167d754 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/LexicalAnalysis/IdentifiersAndKeywords/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +test.ok diff --git a/tests/fsharpqa/Source/Conformance/Signatures/SignatureConformance/.gitignore b/tests/fsharpqa/Source/Conformance/Signatures/SignatureConformance/.gitignore new file mode 100644 index 00000000000..ae2245951c1 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/Signatures/SignatureConformance/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +InternalAccessibility02.fsi diff --git a/tests/fsharpqa/Source/Conformance/StructFieldEqualityComparison/.gitignore b/tests/fsharpqa/Source/Conformance/StructFieldEqualityComparison/.gitignore new file mode 100644 index 00000000000..d1189108015 --- /dev/null +++ b/tests/fsharpqa/Source/Conformance/StructFieldEqualityComparison/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +floatsanddoubles.exe.out diff --git a/tests/fsharpqa/Source/EntryPoint/.gitignore b/tests/fsharpqa/Source/EntryPoint/.gitignore new file mode 100644 index 00000000000..8f0ecc58b19 --- /dev/null +++ b/tests/fsharpqa/Source/EntryPoint/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +E_CompilingToAModule01.netmodule diff --git a/tests/fsharpqa/Source/ErrorMessages/ConfusingTypeName/env.lst b/tests/fsharpqa/Source/ErrorMessages/ConfusingTypeName/env.lst index a78d70a69ec..8189ed0b1f8 100644 --- a/tests/fsharpqa/Source/ErrorMessages/ConfusingTypeName/env.lst +++ b/tests/fsharpqa/Source/ErrorMessages/ConfusingTypeName/env.lst @@ -1,3 +1,3 @@ # see compile.bat for clearer steps, aim is to get message highlighting fix for https://github.com/Microsoft/visualfsharp/issues/2561 - SOURCE="app.fs" SCFLAGS="-r:liba.dll -r:libb.dll -r:libc.dll -r:libd.dll" PRECMD="csc -t:library -out:liba.dll liba-and-b.cs && csc -t:library -out:libb.dll liba-and-b.cs && fsc --target:library -r:liba.dll --out:libc.dll libc.fs && fsc --target:library -r:libb.dll --out:libd.dll libd.fs" + SOURCE="app.fs" SCFLAGS="-r:liba.dll -r:libb.dll -r:libc.dll -r:libd.dll" PRECMD="\$CSC_PIPE -t:library -out:liba.dll liba-and-b.cs && \$CSC_PIPE -t:library -out:libb.dll liba-and-b.cs && fsc --target:library -r:liba.dll --out:libc.dll libc.fs && fsc --target:library -r:libb.dll --out:libd.dll libd.fs" \ No newline at end of file diff --git a/tests/fsharpqa/Source/InteractiveSession/Misc/.gitignore b/tests/fsharpqa/Source/InteractiveSession/Misc/.gitignore new file mode 100644 index 00000000000..f0a93261615 --- /dev/null +++ b/tests/fsharpqa/Source/InteractiveSession/Misc/.gitignore @@ -0,0 +1,4 @@ +# generated as part of the test +LoadOrderOfExecution3a.fs +LoadOrderOfExecution4.fs +ReferencesFullPath.fsx diff --git a/tests/fsharpqa/Source/InteractiveSession/Misc/GenericConstraintWoes/issue2411/env.lst b/tests/fsharpqa/Source/InteractiveSession/Misc/GenericConstraintWoes/issue2411/env.lst index 822c79ae7de..6ec14cc9a8f 100644 --- a/tests/fsharpqa/Source/InteractiveSession/Misc/GenericConstraintWoes/issue2411/env.lst +++ b/tests/fsharpqa/Source/InteractiveSession/Misc/GenericConstraintWoes/issue2411/env.lst @@ -1 +1 @@ - SOURCE=app.fsx COMPILE_ONLY=1 FSIMODE=EXEC SCFLAGS="--nologo" PRECMD="csc -t:library lib.cs" # mode exec: used to produce internal error \ No newline at end of file + SOURCE=app.fsx COMPILE_ONLY=1 FSIMODE=EXEC SCFLAGS="--nologo" PRECMD="\$CSC_PIPE -t:library lib.cs" # mode exec: used to produce internal error \ No newline at end of file diff --git a/tests/fsharpqa/Source/Stress/.gitignore b/tests/fsharpqa/Source/Stress/.gitignore new file mode 100644 index 00000000000..09214bda72c --- /dev/null +++ b/tests/fsharpqa/Source/Stress/.gitignore @@ -0,0 +1,3 @@ +# generated as part of the test +2766.fs +SeqExprCapacity.fs diff --git a/tests/fsharpqa/Source/XmlDoc/.gitignore b/tests/fsharpqa/Source/XmlDoc/.gitignore new file mode 100644 index 00000000000..abfcd8dcc29 --- /dev/null +++ b/tests/fsharpqa/Source/XmlDoc/.gitignore @@ -0,0 +1,2 @@ +# generated as part of the test +*.xml diff --git a/tests/fsharpqa/Source/run.pl b/tests/fsharpqa/Source/run.pl index e9363e6aea6..751bcdd8935 100644 --- a/tests/fsharpqa/Source/run.pl +++ b/tests/fsharpqa/Source/run.pl @@ -159,13 +159,13 @@ # SOURCE=foo.fs PRECMD="\$FSC_PIPE bar.fs" # and it will expanded into $FSC_PIPE before invoking it $_ = $ENV{PRECMD}; - s/^\$FSC_PIPE/$FSC_PIPE/; + s/\$FSC_PIPE/$FSC_PIPE/g; s/\$FSI_PIPE/$FSI_PIPE/g; - s/^\$FSI32_PIPE/$FSI32_PIPE/; - s/\$ISCFLAGS/$ISCFLAGS/; - s/^\$CSC_PIPE/$CSC_PIPE/; - s/^\$VBC_PIPE/$VBC_PIPE/; - RunExit(TEST_FAIL, "Fail to execute the PRECMD" . @CommandOutput . "\n") if RunCommand("PRECMD",$_ ,1); + s/\$FSI32_PIPE/$FSI32_PIPE/g; + s/\$ISCFLAGS/$ISCFLAGS/g; + s/\$CSC_PIPE/$CSC_PIPE/g; + s/\$VBC_PIPE/$VBC_PIPE/g; + RunExit(TEST_FAIL, "Fail to execute the PRECMD:\n" . join("\n", @CommandOutput) . "\n") if RunCommand("PRECMD",$_ ,1); } # Normal testing begins @@ -265,12 +265,13 @@ my $PEVERIFY = $ENV{PEVERIFY}; unless(defined($PEVERIFY)) { my $scriptPath = dirname(__FILE__); - $PEVERIFY = "$scriptPath\\..\\..\\..\\artifacts\\bin\\PEVerify\\Release\\net46\\PEVerify.exe"; - if (-e $PEVERIFY) { - $ENV{PEVERIFY} = $PEVERIFY; - } - else { - $ENV{PEVERIFY} = "$scriptPath\\..\\..\\..\\artifacts\\bin\\PEVerify\\Debug\\net46\\PEVerify.exe"; + my @configurations = ("Debug", "Release"); + foreach my $config (@configurations) { + $PEVERIFY = "$scriptPath\\..\\..\\..\\artifacts\\bin\\PEVerify\\$config\\net46\\PEVerify.exe"; + if (-e $PEVERIFY) { + $ENV{PEVERIFY} = $PEVERIFY; + last; + } } } @@ -468,9 +469,10 @@ sub RunCommand { open(COMMAND,"$cmd 2>&1 |") or RunExit(TEST_FAIL, "Command Process Couldn't Be Created: $! Returned $? \n"); @CommandOutput = ; close COMMAND; + my $result = $?; # close STDERR; open STDERR, ">&SAVEERR"; #resore stderr - print @CommandOutput if ($dumpOutput == 1); + print(join("\n", @CommandOutput)) if ($dumpOutput == 1); # Test for an assertion failure if (-e ASSERT_FILE) { @@ -482,7 +484,8 @@ sub RunCommand { close ASSERT; RunExit(TEST_FAIL, "Command Unexpectedly Failed with ASSERT \n"); } - return $?; + + return $result; } ############################################################# @@ -770,11 +773,11 @@ sub RunExit { # SOURCE=foo.fs POSTCMD="\$FSC_PIPE bar.fs" # and it will expanded into $FSC_PIPE before invoking it $_ = $ENV{POSTCMD}; - s/^\$FSC_PIPE/$FSC_PIPE/; - s/^\$FSI_PIPE/$FSI_PIPE/; - s/^\$FSI32_PIPE/$FSI32_PIPE/; - s/^\$CSC_PIPE/$CSC_PIPE/; - s/^\$VBC_PIPE/$VBC_PIPE/; + s/\$FSC_PIPE/$FSC_PIPE/g; + s/\$FSI_PIPE/$FSI_PIPE/g; + s/\$FSI32_PIPE/$FSI32_PIPE/g; + s/\$CSC_PIPE/$CSC_PIPE/g; + s/\$VBC_PIPE/$VBC_PIPE/g; if (RunCommand("POSTCMD",$_,1)){ $exitVal = TEST_FAIL; diff --git a/tests/fsharpqa/testenv/src/AssemblyVersionCheck/.gitignore b/tests/fsharpqa/testenv/src/AssemblyVersionCheck/.gitignore deleted file mode 100644 index c0e717b21de..00000000000 --- a/tests/fsharpqa/testenv/src/AssemblyVersionCheck/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# this file has to be dynamically written at build time -assemblies.fsx diff --git a/tests/fsharpqa/testenv/src/AssemblyVersionCheck/AssemblyVersionCheck.fsx b/tests/fsharpqa/testenv/src/AssemblyVersionCheck/AssemblyVersionCheck.fsx deleted file mode 100644 index 727916d4986..00000000000 --- a/tests/fsharpqa/testenv/src/AssemblyVersionCheck/AssemblyVersionCheck.fsx +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -// this points to assemblies that were restored by packages.config in the root -#load "assemblies.fsx" - -open System -open System.Diagnostics -open System.IO -open System.Reflection -open System.Text.RegularExpressions -open Newtonsoft.Json.Linq - -module AssemblyVersionCheck = - - let private versionZero = Version(0, 0, 0, 0) - let private commitHashPattern = new Regex(@"Commit Hash: ()|([0-9a-fA-F]{40})", RegexOptions.Compiled) - - let verifyAssemblyVersions (signToolData:string) (binariesPath:string) = - let json = File.ReadAllText(signToolData) - let jobject = JObject.Parse(json) - - // could either contain things like 'net40\bin\FSharp.Core.dll' or patterns like 'net40\bin\*\FSharp.Core.resources.dll' - let assemblyPatterns = - (jobject.["sign"] :?> JArray) - |> Seq.map (fun a -> (a :?> JObject).["values"] :?> JArray) - |> Seq.map (fun a -> a :> seq) - |> Seq.collect (fun t -> t) - |> Seq.map (fun t -> t.ToString()) - |> Seq.filter (fun p -> p.EndsWith(".dll") || p.EndsWith(".exe")) // only check assemblies - - // map the assembly patterns to actual files on disk - let actualAssemblies = - assemblyPatterns - |> Seq.map (fun a -> - if not (a.Contains("*")) then - [a] // just a raw file name - else - let parts = a.Split([|'\\'|]) - let mutable candidatePaths = [binariesPath] - for p in parts do - match p with - | "*" -> - // expand all candidates into multiples - let expansions = - candidatePaths - |> List.filter Directory.Exists - |> List.map (Directory.EnumerateDirectories >> Seq.toList) - |> List.collect (fun x -> x) - candidatePaths <- expansions - | _ -> - // regular path part, just append it to all candidates - candidatePaths <- List.map (fun d -> Path.Combine(d, p)) candidatePaths - candidatePaths) - |> Seq.collect (fun a -> a) - |> Seq.map (fun a -> Path.Combine(binariesPath, a)) - |> Seq.filter (fun p -> File.Exists(p)) // not all test runs produce all files - |> Seq.toList - - // verify that all assemblies have a version number other than 0.0.0.0 - let failedVersionCheck = - actualAssemblies - |> List.filter (fun a -> - let assemblyVersion = AssemblyName.GetAssemblyName(a).Version - printfn "Checking version: %s (%A)" a assemblyVersion - assemblyVersion = versionZero) - if failedVersionCheck.Length > 0 then - printfn "The following assemblies had a version of %A" versionZero - printfn "%s\r\n" <| String.Join("\r\n", failedVersionCheck) - - // verify that all assemblies have a commit hash - let failedCommitHash = - actualAssemblies - |> List.filter (fun a -> - let fileProductVersion = FileVersionInfo.GetVersionInfo(a).ProductVersion - printfn "Checking commit hash: %s (%s)" a fileProductVersion - not <| commitHashPattern.IsMatch(fileProductVersion)) - if failedCommitHash.Length > 0 then - printfn "The following assemblies don't have a commit hash set" - printfn "%s\r\n" <| String.Join("\r\n", failedCommitHash) - - // return code is the number of failures - failedVersionCheck.Length + failedCommitHash.Length - -let main (argv:string array) = - if argv.Length <> 2 then - printfn "Usage: fsi.exe AssemblyVersionCheck.fsx -- SignToolData.json path/to/binaries" - 1 - else - AssemblyVersionCheck.verifyAssemblyVersions argv.[0] argv.[1] - -Environment.GetCommandLineArgs() -|> Seq.skipWhile ((<>) "--") -|> Seq.skip 1 -|> Array.ofSeq -|> main diff --git a/tests/fsharpqa/testenv/src/Directory.Build.props b/tests/fsharpqa/testenv/src/Directory.Build.props deleted file mode 100644 index bb8eac309b1..00000000000 --- a/tests/fsharpqa/testenv/src/Directory.Build.props +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/fsharpqa/testenv/src/Directory.Build.targets b/tests/fsharpqa/testenv/src/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/tests/fsharpqa/testenv/src/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Directory.Build.props b/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Directory.Build.props index bb8eac309b1..aa744e6acad 100644 --- a/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Directory.Build.props +++ b/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Directory.Build.props @@ -1,3 +1,4 @@ - + + diff --git a/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Directory.Build.targets b/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Directory.Build.targets index ccd47cc0a9a..4d469fc9359 100644 --- a/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Directory.Build.targets +++ b/tests/projects/Sample_NETCoreSDK_FSharp_Library_netstandard2_0/Directory.Build.targets @@ -1,3 +1,4 @@ - + + diff --git a/tests/service/data/Directory.Build.props b/tests/service/data/Directory.Build.props deleted file mode 100644 index bb8eac309b1..00000000000 --- a/tests/service/data/Directory.Build.props +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/tests/service/data/Directory.Build.targets b/tests/service/data/Directory.Build.targets deleted file mode 100644 index ccd47cc0a9a..00000000000 --- a/tests/service/data/Directory.Build.targets +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/verify-translations.cmd b/verify-translations.cmd deleted file mode 100644 index 2580890c6fb..00000000000 --- a/verify-translations.cmd +++ /dev/null @@ -1,3 +0,0 @@ -@echo off - -%~dp0artifacts\bin\fsi\Release\net46\fsi.exe %~dp0src\scripts\VerifyAllTranslations.fsx -- %~dp0 diff --git a/vsintegration/Directory.Build.props b/vsintegration/Directory.Build.props index 5a7b0782ce1..45173358d89 100644 --- a/vsintegration/Directory.Build.props +++ b/vsintegration/Directory.Build.props @@ -1,11 +1,11 @@ - - net46 v4.6 true + + diff --git a/vsintegration/Directory.Build.targets b/vsintegration/Directory.Build.targets index 0a555189d7e..af547ce3c0c 100644 --- a/vsintegration/Directory.Build.targets +++ b/vsintegration/Directory.Build.targets @@ -1,19 +1,11 @@ - + true - $(NuGetPackageRoot)Microsoft.VSSDK.BuildTools\$(MicrosoftVSSDKBuildToolsPackageVersion) - - - - - - - diff --git a/vsintegration/DisableVsixManifestTargets.targets b/vsintegration/DisableVsixManifestTargets.targets deleted file mode 100644 index 86c5ada70cb..00000000000 --- a/vsintegration/DisableVsixManifestTargets.targets +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/vsintegration/ItemTemplates/AppConfig/AppConfig.csproj b/vsintegration/ItemTemplates/AppConfig/AppConfig.csproj index 48500b15a86..4fd83ab1811 100644 --- a/vsintegration/ItemTemplates/AppConfig/AppConfig.csproj +++ b/vsintegration/ItemTemplates/AppConfig/AppConfig.csproj @@ -2,10 +2,6 @@ - - AppConfig - - diff --git a/vsintegration/ItemTemplates/AppConfig/source.extension.vsixmanifest b/vsintegration/ItemTemplates/AppConfig/source.extension.vsixmanifest new file mode 100644 index 00000000000..05eedbb1f39 --- /dev/null +++ b/vsintegration/ItemTemplates/AppConfig/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ItemTemplates/CodeFile/CodeFile.csproj b/vsintegration/ItemTemplates/CodeFile/CodeFile.csproj index cf6a5e3e4f6..85c251a6571 100644 --- a/vsintegration/ItemTemplates/CodeFile/CodeFile.csproj +++ b/vsintegration/ItemTemplates/CodeFile/CodeFile.csproj @@ -2,10 +2,6 @@ - - CodeFile - - diff --git a/vsintegration/ItemTemplates/CodeFile/source.extension.vsixmanifest b/vsintegration/ItemTemplates/CodeFile/source.extension.vsixmanifest new file mode 100644 index 00000000000..77860d0c1ce --- /dev/null +++ b/vsintegration/ItemTemplates/CodeFile/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ItemTemplates/ResourceFile/ResourceFile.csproj b/vsintegration/ItemTemplates/ResourceFile/ResourceFile.csproj index 17760a303bf..e3b839ca84e 100644 --- a/vsintegration/ItemTemplates/ResourceFile/ResourceFile.csproj +++ b/vsintegration/ItemTemplates/ResourceFile/ResourceFile.csproj @@ -2,10 +2,6 @@ - - ResourceFile - - diff --git a/vsintegration/ItemTemplates/ResourceFile/source.extension.vsixmanifest b/vsintegration/ItemTemplates/ResourceFile/source.extension.vsixmanifest new file mode 100644 index 00000000000..080d4b6e73a --- /dev/null +++ b/vsintegration/ItemTemplates/ResourceFile/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ItemTemplates/ScriptFile/ScriptFile.csproj b/vsintegration/ItemTemplates/ScriptFile/ScriptFile.csproj index d8affe83605..2ebcd32a52a 100644 --- a/vsintegration/ItemTemplates/ScriptFile/ScriptFile.csproj +++ b/vsintegration/ItemTemplates/ScriptFile/ScriptFile.csproj @@ -2,10 +2,6 @@ - - ScriptFile - - diff --git a/vsintegration/ItemTemplates/ScriptFile/source.extension.vsixmanifest b/vsintegration/ItemTemplates/ScriptFile/source.extension.vsixmanifest new file mode 100644 index 00000000000..926e18fb041 --- /dev/null +++ b/vsintegration/ItemTemplates/ScriptFile/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ItemTemplates/SignatureFile/SignatureFile.csproj b/vsintegration/ItemTemplates/SignatureFile/SignatureFile.csproj index 89a34c354b7..8afaaa6536b 100644 --- a/vsintegration/ItemTemplates/SignatureFile/SignatureFile.csproj +++ b/vsintegration/ItemTemplates/SignatureFile/SignatureFile.csproj @@ -2,10 +2,6 @@ - - SignatureFile - - diff --git a/vsintegration/ItemTemplates/SignatureFile/source.extension.vsixmanifest b/vsintegration/ItemTemplates/SignatureFile/source.extension.vsixmanifest new file mode 100644 index 00000000000..f58462b5bfe --- /dev/null +++ b/vsintegration/ItemTemplates/SignatureFile/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ItemTemplates/TextFile/TextFile.csproj b/vsintegration/ItemTemplates/TextFile/TextFile.csproj index 880085abaaa..0d4fe964bb4 100644 --- a/vsintegration/ItemTemplates/TextFile/TextFile.csproj +++ b/vsintegration/ItemTemplates/TextFile/TextFile.csproj @@ -2,10 +2,6 @@ - - TextFile - - diff --git a/vsintegration/ItemTemplates/TextFile/source.extension.vsixmanifest b/vsintegration/ItemTemplates/TextFile/source.extension.vsixmanifest new file mode 100644 index 00000000000..c27fecaff60 --- /dev/null +++ b/vsintegration/ItemTemplates/TextFile/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ItemTemplates/XMLFile/XMLFile.csproj b/vsintegration/ItemTemplates/XMLFile/XMLFile.csproj index bef2612dc20..2c345a1dfae 100644 --- a/vsintegration/ItemTemplates/XMLFile/XMLFile.csproj +++ b/vsintegration/ItemTemplates/XMLFile/XMLFile.csproj @@ -2,10 +2,6 @@ - - XMLFile - - diff --git a/vsintegration/ItemTemplates/XMLFile/source.extension.vsixmanifest b/vsintegration/ItemTemplates/XMLFile/source.extension.vsixmanifest new file mode 100644 index 00000000000..405769509e5 --- /dev/null +++ b/vsintegration/ItemTemplates/XMLFile/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ProjectTemplates/ConsoleProject/source.extension.vsixmanifest b/vsintegration/ProjectTemplates/ConsoleProject/source.extension.vsixmanifest new file mode 100644 index 00000000000..5f28d2c06ed --- /dev/null +++ b/vsintegration/ProjectTemplates/ConsoleProject/source.extension.vsixmanifest @@ -0,0 +1,24 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ProjectTemplates/Directory.Build.props b/vsintegration/ProjectTemplates/Directory.Build.props index a67b0e382ed..49fb4e2d1fc 100644 --- a/vsintegration/ProjectTemplates/Directory.Build.props +++ b/vsintegration/ProjectTemplates/Directory.Build.props @@ -2,6 +2,7 @@ ProjectTemplates + Microsoft.FSharp diff --git a/vsintegration/ProjectTemplates/LibraryProject/source.extension.vsixmanifest b/vsintegration/ProjectTemplates/LibraryProject/source.extension.vsixmanifest new file mode 100644 index 00000000000..f5157eaa6b0 --- /dev/null +++ b/vsintegration/ProjectTemplates/LibraryProject/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/ProjectTemplates/TutorialProject/source.extension.vsixmanifest b/vsintegration/ProjectTemplates/TutorialProject/source.extension.vsixmanifest new file mode 100644 index 00000000000..39bac985bc1 --- /dev/null +++ b/vsintegration/ProjectTemplates/TutorialProject/source.extension.vsixmanifest @@ -0,0 +1,25 @@ + + + + + F# .NETCore Project Templates + F# project templates for .NETCore. + + + + + + + + + + + + + + + + + + + diff --git a/vsintegration/Templates.Directory.Build.props b/vsintegration/Templates.Directory.Build.props index c6a5cea2009..df7e87a2cdd 100644 --- a/vsintegration/Templates.Directory.Build.props +++ b/vsintegration/Templates.Directory.Build.props @@ -6,18 +6,24 @@ + + + false + true + true + false + false + false + false net46 v4.6 - true true - false - false + false false false - false false false false diff --git a/vsintegration/Vsix/Directory.Build.props b/vsintegration/Vsix/Directory.Build.props index 2a730726842..e2386bf5eff 100644 --- a/vsintegration/Vsix/Directory.Build.props +++ b/vsintegration/Vsix/Directory.Build.props @@ -3,20 +3,13 @@ + Microsoft.FSharp RoslynDev - false - true $(VSRootSuffix) true publish\ true Disk - false - Foreground - 7 - Days - true - false true false false @@ -31,7 +24,6 @@ CommonExtensions None true - true diff --git a/vsintegration/Vsix/Directory.Build.targets b/vsintegration/Vsix/Directory.Build.targets deleted file mode 100644 index 677cf0afc9d..00000000000 --- a/vsintegration/Vsix/Directory.Build.targets +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - $(ArtifactsDir)\VSSetup\$(Configuration) - $(ArtifactsDir)\VSSetup.obj\$(Configuration)\Microsoft.FSharp\ - - - - - False - Microsoft .NET Framework 4.6 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - - diff --git a/vsintegration/Vsix/VisualFSharpFull/Source.extension.vsixmanifest b/vsintegration/Vsix/VisualFSharpFull/Source.extension.vsixmanifest index 26436755087..4d068326675 100644 --- a/vsintegration/Vsix/VisualFSharpFull/Source.extension.vsixmanifest +++ b/vsintegration/Vsix/VisualFSharpFull/Source.extension.vsixmanifest @@ -2,7 +2,7 @@ - + Visual F# Tools Deploy Visual F# Tools Binaries to Visual Studio Microsoft.FSharp.VSIX.Full.Core diff --git a/vsintegration/Vsix/VisualFSharpFull/VisualFSharpFull.csproj b/vsintegration/Vsix/VisualFSharpFull/VisualFSharpFull.csproj index 95a623bfa12..90baf6d789c 100644 --- a/vsintegration/Vsix/VisualFSharpFull/VisualFSharpFull.csproj +++ b/vsintegration/Vsix/VisualFSharpFull/VisualFSharpFull.csproj @@ -6,6 +6,7 @@ Library Microsoft\FSharp netcoreapp1.0 + true @@ -66,7 +67,7 @@ {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3} FSharp.Compiler.Private - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All @@ -77,7 +78,7 @@ {DED3BBD7-53F4-428A-8C9F-27968E768605} FSharp.Core - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All @@ -85,9 +86,9 @@ True TargetFramework=net45 - + {8B3E283D-B5FE-4055-9D80-7E3A32F3967B} - FsiAnyCPU + FsiAnyCpu BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3b DebugSymbolsProjectOutputGroup%3b true @@ -124,7 +125,7 @@ {65e0e82a-eace-4787-8994-888674c2fe87} FSharp.Editor - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All @@ -134,14 +135,14 @@ {c4586a06-1402-48bc-8e35-a1b8642f895b} FSharp.UIResources - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b True {1C5C163C-37EA-4A3C-8CCC-0D34B74BF8EF} FSharp.LanguageService.Base - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All @@ -151,7 +152,7 @@ {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F} FSharp.LanguageService - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All @@ -161,7 +162,7 @@ {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7} ProjectSystem.Base - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All @@ -171,7 +172,7 @@ {6196B0F8-CAEA-4CF1-AF82-1B520F77FE44} ProjectSystem - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All @@ -181,7 +182,7 @@ {FCFB214C-462E-42B3-91CA-FC557EFEE74F} FSharp.PropertiesPages - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All @@ -191,7 +192,7 @@ {991DCF75-C2EB-42B6-9A0D-AA1D2409D519} FSharp.VS.FSI - BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3b + BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems%3bPkgDefProjectOutputGroup%3bSatelliteDllsProjectOutputGroup%3b DebugSymbolsProjectOutputGroup%3b true All diff --git a/vsintegration/Vsix/VisualFSharpTemplates/Source.extension.vsixmanifest b/vsintegration/Vsix/VisualFSharpTemplates/Source.extension.vsixmanifest index 3d17751f813..628e678cdcd 100644 --- a/vsintegration/Vsix/VisualFSharpTemplates/Source.extension.vsixmanifest +++ b/vsintegration/Vsix/VisualFSharpTemplates/Source.extension.vsixmanifest @@ -3,7 +3,7 @@ - + Visual F# Templates Deploy Visual F# Tools Desktop Project Templates to Visual Studio Microsoft.FSharp.VSIX.Templates diff --git a/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj b/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj index fefaecb6614..36034d0509a 100644 --- a/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj +++ b/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj @@ -3,17 +3,13 @@ - VisualFSharpTemplate Library Microsoft\FSharpTemplates + net46 + true - - PreserveNewest - packages\FSharp.Core.$(FSCorePackageVersion).nupkg - true - PreserveNewest packages\System.ValueTuple.4.4.0.nupkg @@ -24,6 +20,14 @@ + + + packages + PackOutputGroup%3b + false + + + {604f0daa-2d33-48dd-b162-edf0b672803d} diff --git a/vsintegration/fsharp-vsintegration-item-templates-build.proj b/vsintegration/fsharp-vsintegration-item-templates-build.proj deleted file mode 100644 index 0a1fd670f91..00000000000 --- a/vsintegration/fsharp-vsintegration-item-templates-build.proj +++ /dev/null @@ -1,23 +0,0 @@ - - - - net40 - - - - - - - - - - - - - - - - - - - diff --git a/vsintegration/fsharp-vsintegration-project-templates-build.proj b/vsintegration/fsharp-vsintegration-project-templates-build.proj deleted file mode 100644 index da89b3a5d23..00000000000 --- a/vsintegration/fsharp-vsintegration-project-templates-build.proj +++ /dev/null @@ -1,20 +0,0 @@ - - - - net40 - - - - - - - - - - - - - - - - diff --git a/vsintegration/fsharp-vsintegration-src-build.proj b/vsintegration/fsharp-vsintegration-src-build.proj deleted file mode 100644 index 93a8fbfd273..00000000000 --- a/vsintegration/fsharp-vsintegration-src-build.proj +++ /dev/null @@ -1,26 +0,0 @@ - - - - - net40 - - - - - - - - - - - - - - - - - - - - - diff --git a/vsintegration/fsharp-vsintegration-unittests-build.proj b/vsintegration/fsharp-vsintegration-unittests-build.proj deleted file mode 100644 index 489e91ad2e9..00000000000 --- a/vsintegration/fsharp-vsintegration-unittests-build.proj +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vsintegration/fsharp-vsintegration-vsix-build.proj b/vsintegration/fsharp-vsintegration-vsix-build.proj deleted file mode 100644 index c208129ec44..00000000000 --- a/vsintegration/fsharp-vsintegration-vsix-build.proj +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/vsintegration/src/Directory.Build.props b/vsintegration/src/Directory.Build.props index 1ad6fb80ecd..df989b6c15c 100644 --- a/vsintegration/src/Directory.Build.props +++ b/vsintegration/src/Directory.Build.props @@ -4,6 +4,8 @@ false + false + true diff --git a/vsintegration/src/FSharp.Editor/Completion/SignatureHelp.fs b/vsintegration/src/FSharp.Editor/Completion/SignatureHelp.fs index 8dd6b4c5a02..6ffc30c88cc 100644 --- a/vsintegration/src/FSharp.Editor/Completion/SignatureHelp.fs +++ b/vsintegration/src/FSharp.Editor/Completion/SignatureHelp.fs @@ -168,7 +168,7 @@ type internal FSharpSignatureHelpProvider XmlDocumentation.BuildMethodParamText(documentationBuilder, RoslynHelpers.CollectTaggedText doc, method.XmlDoc, p.ParameterName) let parts = List() renderL (taggedTextListR (RoslynHelpers.CollectTaggedText parts)) p.StructuredDisplay |> ignore - yield (p.ParameterName, p.IsOptional, doc, parts) + yield (p.ParameterName, p.IsOptional, p.CanonicalTypeTextForSorting, doc, parts) |] let prefixParts = @@ -210,7 +210,7 @@ type internal FSharpSignatureHelpProvider results |> Array.map (fun (hasParamArrayArg, doc, prefixParts, separatorParts, suffixParts, parameters, descriptionParts) -> let parameters = parameters - |> Array.map (fun (paramName, isOptional, paramDoc, displayParts) -> + |> Array.map (fun (paramName, isOptional, _typeText, paramDoc, displayParts) -> SignatureHelpParameter(paramName,isOptional,documentationFactory=(fun _ -> paramDoc :> seq<_>),displayParts=displayParts)) SignatureHelpItem(isVariadic=hasParamArrayArg, documentationFactory=(fun _ -> doc :> seq<_>),prefixParts=prefixParts,separatorParts=separatorParts,suffixParts=suffixParts,parameters=parameters,descriptionParts=descriptionParts)) diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj index 98d8e28f771..6a95fa56b62 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj @@ -4,8 +4,6 @@ Library - true - false $(NoWarn);75 true true @@ -13,6 +11,7 @@ $(OtherFlags) --warnon:1182 --subsystemversion:6.00 true false + true @@ -155,7 +154,6 @@ - diff --git a/vsintegration/src/FSharp.Editor/QuickInfo/QuickInfoProvider.fs b/vsintegration/src/FSharp.Editor/QuickInfo/QuickInfoProvider.fs index 5712af54fb8..9f8bf73fddb 100644 --- a/vsintegration/src/FSharp.Editor/QuickInfo/QuickInfoProvider.fs +++ b/vsintegration/src/FSharp.Editor/QuickInfo/QuickInfoProvider.fs @@ -23,13 +23,13 @@ open FSharp.Compiler open Internal.Utilities.StructuredFormat -type private QuickInfo = +type internal QuickInfo = { StructuredText: FSharpStructuredToolTipText Span: TextSpan Symbol: FSharpSymbol SymbolKind: LexerSymbolKind } -module private FSharpQuickInfo = +module internal FSharpQuickInfo = let userOpName = "QuickInfo" @@ -166,6 +166,12 @@ type internal FSharpAsyncQuickInfoSource textBuffer:ITextBuffer ) = + static let joinWithLineBreaks segments = + let lineBreak = TaggedTextOps.Literals.lineBreak + match segments |> List.filter (Seq.isEmpty >> not) with + | [] -> Seq.empty + | xs -> xs |> List.reduce (fun acc elem -> seq { yield! acc; yield lineBreak; yield! elem }) + // test helper static member ProvideQuickInfo(checker:FSharpChecker, documentId:DocumentId, sourceText:SourceText, filePath:string, position:int, parsingOptions:FSharpParsingOptions, options:FSharpProjectOptions, textVersionHash:int, languageServicePerformanceOptions: LanguageServicePerformanceOptions) = asyncMaybe { @@ -181,9 +187,18 @@ type internal FSharpAsyncQuickInfoSource | _ -> let! symbolUse = checkFileResults.GetSymbolUseAtLocation (textLineNumber, symbol.Ident.idRange.EndColumn, textLine.ToString(), symbol.FullIsland, userOpName=FSharpQuickInfo.userOpName) let! symbolSpan = RoslynHelpers.TryFSharpRangeToTextSpan (sourceText, symbol.Range) - return res, symbolSpan, symbolUse.Symbol, symbol.Kind + return { StructuredText = res + Span = symbolSpan + Symbol = symbolUse.Symbol + SymbolKind = symbol.Kind } } + static member BuildSingleQuickInfoItem (documentationBuilder:IDocumentationBuilder) (quickInfo:QuickInfo) = + let mainDescription, documentation, typeParameterMap, usage, exceptions = ResizeArray(), ResizeArray(), ResizeArray(), ResizeArray(), ResizeArray() + XmlDocumentation.BuildDataTipText(documentationBuilder, mainDescription.Add, documentation.Add, typeParameterMap.Add, usage.Add, exceptions.Add, quickInfo.StructuredText) + let docs = joinWithLineBreaks [documentation; typeParameterMap; usage; exceptions] + (mainDescription, docs) + interface IAsyncQuickInfoSource with override __.Dispose() = () // no cleanup necessary @@ -201,21 +216,14 @@ type internal FSharpAsyncQuickInfoSource let! symbolUse, sigQuickInfo, targetQuickInfo = FSharpQuickInfo.getQuickInfo(checkerProvider.Checker, projectInfoManager, document, triggerPoint.Position, cancellationToken) let getTrackingSpan (span:TextSpan) = textBuffer.CurrentSnapshot.CreateTrackingSpan(span.Start, span.Length, SpanTrackingMode.EdgeInclusive) - let lineBreak = TaggedTextOps.Literals.lineBreak - let joinWithLineBreaks segments = - match segments |> List.filter (Seq.isEmpty >> not) with - | [] -> Seq.empty - | xs -> xs |> List.reduce (fun acc elem -> seq { yield! acc; yield lineBreak; yield! elem }) match sigQuickInfo, targetQuickInfo with | None, None -> return null | Some quickInfo, None | None, Some quickInfo-> - let mainDescription, documentation, typeParameterMap, usage, exceptions = ResizeArray(), ResizeArray(), ResizeArray(), ResizeArray(), ResizeArray() - XmlDocumentation.BuildDataTipText(documentationBuilder, mainDescription.Add, documentation.Add, typeParameterMap.Add, usage.Add, exceptions.Add, quickInfo.StructuredText) + let mainDescription, docs = FSharpAsyncQuickInfoSource.BuildSingleQuickInfoItem documentationBuilder quickInfo let imageId = Tokenizer.GetImageIdForSymbol(quickInfo.Symbol, quickInfo.SymbolKind) let navigation = QuickInfoNavigation(statusBar, checkerProvider.Checker, projectInfoManager, document, symbolUse.RangeAlternate) - let docs = joinWithLineBreaks [documentation; typeParameterMap; usage; exceptions] let content = QuickInfoViewProvider.provideContent(imageId, mainDescription, docs, navigation) let span = getTrackingSpan quickInfo.Span return QuickInfoItem(span, content) diff --git a/vsintegration/src/FSharp.LanguageService.Base/DocumentTask.cs b/vsintegration/src/FSharp.LanguageService.Base/DocumentTask.cs index d6664bb6a5f..58855165b7c 100644 --- a/vsintegration/src/FSharp.LanguageService.Base/DocumentTask.cs +++ b/vsintegration/src/FSharp.LanguageService.Base/DocumentTask.cs @@ -89,7 +89,9 @@ public static void Run(Action action) { #if DEBUG StackTrace stackTrace = new StackTrace(true); #endif - ctxt.Post(delegate(object ignore) +#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs + ctxt.Post(delegate(object ignore) +#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs { UIThread.MustBeCalledFromUIThread(); ourUIQueue.Enqueue(action); @@ -142,8 +144,10 @@ public static void RunSync(Action a) Exception exn = null; Debug.Assert(ctxt != null, "The SynchronizationContext must be captured before calling this method"); // Send on UI thread will execute immediately. +#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs ctxt.Send(ignore => - { +#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs + { try { UIThread.MustBeCalledFromUIThread(); @@ -167,28 +171,7 @@ public static void RunSync(Action a) /// Local JoinableTaskContext /// ensuring non-reentrancy. /// - private static JoinableTaskContext jtc = null; - private static JoinableTaskFactory JTF - { - get - { - if (jtc == null) - { - JoinableTaskContext j = null; - if (VsTaskLibraryHelper.ServiceInstance == null) - { - j = new JoinableTaskContext(); - } - else - { - j = ThreadHelper.JoinableTaskContext; - } - Interlocked.CompareExchange(ref jtc, j, null); - } - - return jtc.Factory; - } - } + private static JoinableTaskFactory JTF => ThreadHelper.JoinableTaskContext.Factory; /// /// Performs a callback on the UI thread and blocks until it is done, using the VS mechanism for diff --git a/vsintegration/src/FSharp.LanguageService.Base/FSharp.LanguageService.Base.csproj b/vsintegration/src/FSharp.LanguageService.Base/FSharp.LanguageService.Base.csproj index ce5cfed08aa..336ba963f5a 100644 --- a/vsintegration/src/FSharp.LanguageService.Base/FSharp.LanguageService.Base.csproj +++ b/vsintegration/src/FSharp.LanguageService.Base/FSharp.LanguageService.Base.csproj @@ -4,9 +4,8 @@ Library - true - false $(NoWarn);1570;1574;1587;1591;3001,3002,3003 + $(NoWarn);VSTHRD010 true true false diff --git a/vsintegration/src/FSharp.LanguageService.Base/GlobalSuppressions.cs b/vsintegration/src/FSharp.LanguageService.Base/GlobalSuppressions.cs new file mode 100644 index 00000000000..cf5e76c97c5 --- /dev/null +++ b/vsintegration/src/FSharp.LanguageService.Base/GlobalSuppressions.cs @@ -0,0 +1,7 @@ + +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. + +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "VSSDK006:Check services exist")] diff --git a/vsintegration/src/FSharp.LanguageService.Base/Source.cs b/vsintegration/src/FSharp.LanguageService.Base/Source.cs index 0d230262392..f46dc2f7eab 100644 --- a/vsintegration/src/FSharp.LanguageService.Base/Source.cs +++ b/vsintegration/src/FSharp.LanguageService.Base/Source.cs @@ -2141,7 +2141,9 @@ public int GetBestMatch(string textSoFar, int length, out int index, out uint fl #endif if (textSoFar != this.filterText) { +#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs System.Threading.SynchronizationContext.Current.Post((object state) => +#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs { this.filterText = textSoFar; if (this.textView != null) diff --git a/vsintegration/src/FSharp.LanguageService/FSharp.LanguageService.fsproj b/vsintegration/src/FSharp.LanguageService/FSharp.LanguageService.fsproj index ccd97fff422..29eee6ad191 100644 --- a/vsintegration/src/FSharp.LanguageService/FSharp.LanguageService.fsproj +++ b/vsintegration/src/FSharp.LanguageService/FSharp.LanguageService.fsproj @@ -5,8 +5,6 @@ net46 Library - true - false $(NoWarn);75 true true @@ -71,6 +69,8 @@ + + @@ -79,6 +79,7 @@ + diff --git a/vsintegration/src/FSharp.PatternMatcher/FSharp.PatternMatcher.csproj b/vsintegration/src/FSharp.PatternMatcher/FSharp.PatternMatcher.csproj index 0ae980c7049..5005944c7fa 100644 --- a/vsintegration/src/FSharp.PatternMatcher/FSharp.PatternMatcher.csproj +++ b/vsintegration/src/FSharp.PatternMatcher/FSharp.PatternMatcher.csproj @@ -5,6 +5,7 @@ Library true + false diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/FileNode.cs b/vsintegration/src/FSharp.ProjectSystem.Base/Project/FileNode.cs index 97f9616ee88..ae4e1084d87 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/FileNode.cs +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/FileNode.cs @@ -348,7 +348,9 @@ private static bool PromptYesNoWithYesSelected(string message, string title, OLE { Guid emptyGuid = Guid.Empty; int result = 0; +#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs ThreadHelper.Generic.Invoke(() => +#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs { ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(0u, ref emptyGuid, title, message, null, 0u, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, icon, 0, out result)); }); diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/GlobalSuppressions.cs b/vsintegration/src/FSharp.ProjectSystem.Base/Project/GlobalSuppressions.cs index 2c77ef92ef4..487279fd767 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/GlobalSuppressions.cs +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/GlobalSuppressions.cs @@ -306,3 +306,5 @@ [assembly: SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", Scope = "member", Target = "Microsoft.VisualStudio.Package.Web.WAUtilities.#MakeRelativePath(System.String,System.String)", MessageId = "System.String.StartsWith(System.String)")] [assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope = "resource", Target = "Microsoft.VisualStudio.Package.Project.resources", MessageId = "dataset")] [assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "Microsoft.VisualStudio.Package.Project.resources", MessageId = "msbuild")] + +[assembly: SuppressMessage("Reliability", "VSSDK006:Check services exist")] diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectConfig.cs b/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectConfig.cs index 41832e24b27..1bc6706dd2b 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectConfig.cs +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectConfig.cs @@ -1935,7 +1935,7 @@ public void Build(uint options, IVsOutputWindowPane output, string target) if (!NotifyBuildBegin()) return; try { - config.ProjectMgr.BuildAsync(options, this.config.ConfigCanonicalName, output, target, (result, projectInstance) => + config.ProjectMgr.Build(options, this.config.ConfigCanonicalName, output, target, (result, projectInstance) => { this.BuildCoda(new BuildResult(result, projectInstance), output, shouldRepaintReferences); }); diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectNode.cs b/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectNode.cs index 79091e1fe6a..37f6af8e8e2 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectNode.cs +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectNode.cs @@ -2156,7 +2156,7 @@ private void BuildCoda(IVsOutputWindowPane output, bool engineLogOnlyCritical) BuildEngine.OnlyLogCriticalEvents = engineLogOnlyCritical; } } - internal virtual void BuildAsync(uint vsopts, ConfigCanonicalName configCanonicalName, IVsOutputWindowPane output, string target, MSBuildCoda coda) + internal virtual void Build(uint vsopts, ConfigCanonicalName configCanonicalName, IVsOutputWindowPane output, string target, MSBuildCoda coda) { bool engineLogOnlyCritical = BuildPrelude(output); MSBuildCoda fullCoda = (res,instance) => diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectSystem.Base.csproj b/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectSystem.Base.csproj index 462541e5dde..17a5023ae7c 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectSystem.Base.csproj +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectSystem.Base.csproj @@ -5,9 +5,8 @@ Library FSharp.ProjectSystem.Base - true - false $(NoWarn),1570,1572,1573,1574,1591,3001,3002,3003,3005,3008,3009,3021,3024 + $(NoWarn);VSTHRD010 $(DefineConstants);CODE_ANALYSIS Microsoft.VisualStudio.FSharp.ProjectSystem true diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/UIThread.cs b/vsintegration/src/FSharp.ProjectSystem.Base/Project/UIThread.cs index e35eccd1318..9692b409ba7 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/UIThread.cs +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/UIThread.cs @@ -100,7 +100,9 @@ public static void Run(Action action) #if DEBUG StackTrace stackTrace = new StackTrace(true); #endif +#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs ctxt.Post(delegate (object ignore) +#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs { UIThread.MustBeCalledFromUIThread(); ourUIQueue.Enqueue(action); @@ -153,7 +155,9 @@ public static void RunSync(Action a) Exception exn = null; Debug.Assert(ctxt != null, "The SynchronizationContext must be captured before calling this method"); // Send on UI thread will execute immediately. +#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs ctxt.Send(ignore => +#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs { try { @@ -178,28 +182,7 @@ public static void RunSync(Action a) /// Local JoinableTaskContext /// ensuring non-reentrancy. /// - private static JoinableTaskContext jtc = null; - private static JoinableTaskFactory JTF - { - get - { - if (jtc == null) - { - JoinableTaskContext j = null; - if (VsTaskLibraryHelper.ServiceInstance == null) - { - j = new JoinableTaskContext(); - } - else - { - j = ThreadHelper.JoinableTaskContext; - } - Interlocked.CompareExchange(ref jtc, j, null); - } - - return jtc.Factory; - } - } + private static JoinableTaskFactory JTF => ThreadHelper.JoinableTaskContext.Factory; /// /// Performs a callback on the UI thread and blocks until it is done, using the VS mechanism for diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/.gitignore b/vsintegration/src/FSharp.ProjectSystem.FSharp/.gitignore new file mode 100644 index 00000000000..dca31eb19ac --- /dev/null +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/.gitignore @@ -0,0 +1 @@ +ctofiles/ diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/ProjectSystem.fsproj b/vsintegration/src/FSharp.ProjectSystem.FSharp/ProjectSystem.fsproj index 264584077ef..548c5344550 100644 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/ProjectSystem.fsproj +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/ProjectSystem.fsproj @@ -5,8 +5,6 @@ Library FSharp.ProjectSystem.FSharp - true - false $(NoWarn);52;62;75 true true @@ -24,13 +22,15 @@ - false Menus.ctmenu + Designer true Microsoft.VisualStudio.FSharp.ProjectSystem.FSharpSR true + VSPackage + Designer @@ -91,7 +91,7 @@ - + @@ -108,4 +108,12 @@ + + + <_GeneratedCTOFilesWithCulture Update="%(Identity)"> + %(ResourceName).%(Culture) + + + + diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/source.extension.vsixmanifest b/vsintegration/src/FSharp.ProjectSystem.FSharp/source.extension.vsixmanifest new file mode 100644 index 00000000000..c07a10b9126 --- /dev/null +++ b/vsintegration/src/FSharp.ProjectSystem.FSharp/source.extension.vsixmanifest @@ -0,0 +1,2 @@ + + diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/FSharp.PropertiesPages.vbproj b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/FSharp.PropertiesPages.vbproj index a04064212fd..7e105171e1a 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/FSharp.PropertiesPages.vbproj +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/FSharp.PropertiesPages.vbproj @@ -1,46 +1,31 @@  - - + - Debug - $(ArtifactsBinDir)\$(MSBuildProjectName)\$(Configuration)\$(TargetFramework) - AnyCPU - 9.0.21022 - 2.0 - {FCFB214C-462E-42B3-91CA-FC557EFEE74F} Library + + true FSharp.ProjectSystem.PropertyPages true - 512 - Windows - On - Binary - On - Off _MYFORMS=True false 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 40026;42105;42107;42353 win - v4.6 - - - true - false - false true - true - true true - true false + false + true + v4.6 + + + + + 2.0 + {FCFB214C-462E-42B3-91CA-FC557EFEE74F} - - - - @@ -51,15 +36,13 @@ - - + - @@ -70,16 +53,18 @@ + - - + + {B700E38B-F8C0-4E49-B5EC-DB7B7AC0C4E7} + ProjectSystem.Base + - @@ -274,11 +259,4 @@ - - - $(SuiteBinPath)\FSharp - - - - - + \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/My Project/Application.Designer.vb b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/My Project/Application.Designer.vb index a6ad1d45105..88dd01c78a6 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/My Project/Application.Designer.vb +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/My Project/Application.Designer.vb @@ -1,4 +1,12 @@ -' Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ Option Strict On Option Explicit On diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/My Project/Settings.Designer.vb b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/My Project/Settings.Designer.vb index 88c922cb98c..3085cb235d0 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/My Project/Settings.Designer.vb +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/My Project/Settings.Designer.vb @@ -1,4 +1,12 @@ -' Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ Option Strict On Option Explicit On @@ -7,12 +15,12 @@ Option Explicit On Namespace My _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase - Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings) + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then @@ -21,7 +29,7 @@ Namespace My Private Shared addedHandlerLockObject As New Object _ - Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/ApplicationPropPage.vb b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/ApplicationPropPage.vb index 692619c912b..4ada44f4e11 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/ApplicationPropPage.vb +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/ApplicationPropPage.vb @@ -569,8 +569,6 @@ Namespace Microsoft.VisualStudio.Editors.PropertyPages ''' Fill up the allowed values in the target framework listbox ''' ''' - - 'REVIEW: Are the periods in my version strings culture-safe? Private Function ValidateTargetFrameworkMoniker(ByVal moniker As String) As Boolean If moniker = "" Or moniker = Nothing Then Return False diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/BuildPropPage.vb b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/BuildPropPage.vb index 5df1d151353..160a550abe2 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/BuildPropPage.vb +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/BuildPropPage.vb @@ -93,7 +93,7 @@ Namespace Microsoft.VisualStudio.Editors.PropertyPages Private components As System.ComponentModel.IContainer 'PERF: A note about the labels used as lines. The 3D label is being set to 1 px high, - ' so you�re really only using the grey part of it. Using BorderStyle.Fixed3D seems + ' so you�re really only using the grey part of it. Using BorderStyle.Fixed3D seems ' to fire an extra resize OnHandleCreated. The simple solution is to use BorderStyle.None ' and BackColor = SystemColors.ControlDark. @@ -645,7 +645,7 @@ Namespace Microsoft.VisualStudio.Editors.PropertyPages End If ' Remove the project directory path - If String.Compare(BasePath, Microsoft.VisualBasic.Strings.Left(DirectoryPath, Len(BasePath)), StringComparison.OrdinalIgnoreCase) = 0 Then + If String.Compare(BasePath, VisualBasic.Left(DirectoryPath, Len(BasePath)), StringComparison.OrdinalIgnoreCase) = 0 Then Dim ch As Char = CChar(Mid(DirectoryPath, Len(BasePath), 1)) If ch = System.IO.Path.DirectorySeparatorChar OrElse ch = System.IO.Path.AltDirectorySeparatorChar Then RelativePath = Mid(DirectoryPath, Len(BasePath) + 1) diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/PropPageUserControlBase.vb b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/PropPageUserControlBase.vb index 486024fff2d..bbe32c6fde2 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/PropPageUserControlBase.vb +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/PropPageUserControlBase.vb @@ -3378,7 +3378,7 @@ NextControl: End If ' Remove the project directory path - If String.Compare(BasePath, Microsoft.VisualBasic.Strings.Left(DirectoryPath, Len(BasePath)), StringComparison.OrdinalIgnoreCase) = 0 Then + If String.Compare(BasePath, VisualBasic.Left(DirectoryPath, Len(BasePath)), StringComparison.OrdinalIgnoreCase) = 0 Then Dim ch As Char = CChar(Mid(DirectoryPath, Len(BasePath), 1)) If ch = System.IO.Path.DirectorySeparatorChar OrElse ch = System.IO.Path.AltDirectorySeparatorChar Then RelativePath = Mid(DirectoryPath, Len(BasePath) + 1) diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/ReferencePathsPropPage.vb b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/ReferencePathsPropPage.vb index f1c0e62b298..5b630c65720 100644 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/ReferencePathsPropPage.vb +++ b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/ReferencePathsPropPage.vb @@ -523,7 +523,7 @@ Namespace Microsoft.VisualStudio.Editors.PropertyPages End If ' Remove the project directory path - If String.Compare(BasePath, Microsoft.VisualBasic.Strings.Left(DirectoryPath, Len(BasePath)), StringComparison.OrdinalIgnoreCase) = 0 Then + If String.Compare(BasePath, VisualBasic.Left(DirectoryPath, Len(BasePath)), StringComparison.OrdinalIgnoreCase) = 0 Then Dim ch As Char = CChar(Mid(DirectoryPath, Len(BasePath), 1)) If ch = System.IO.Path.DirectorySeparatorChar OrElse ch = System.IO.Path.AltDirectorySeparatorChar Then RelativePath = Mid(DirectoryPath, Len(BasePath) + 1) diff --git a/vsintegration/src/FSharp.UIResources/FSharp.UIResources.csproj b/vsintegration/src/FSharp.UIResources/FSharp.UIResources.csproj index dd0c543cb54..f5ad99e1796 100644 --- a/vsintegration/src/FSharp.UIResources/FSharp.UIResources.csproj +++ b/vsintegration/src/FSharp.UIResources/FSharp.UIResources.csproj @@ -6,7 +6,7 @@ Library $(NoWarn);1591 Microsoft.VisualStudio.FSharp.UIResources - $(NoWarn);1591 + false @@ -31,6 +31,9 @@ True Strings.resx + + FormattingOptionsControl.xaml + @@ -48,19 +51,6 @@ - - - True - True - Strings.resx - - - - - PublicResXFileCodeGenerator - Strings.Designer.cs - - $(VS150COMNTOOLS)\..\..\MSBuild\$(VisualStudioVersion)\Bin diff --git a/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj b/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj index ff45634d032..24c46b5b96f 100644 --- a/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj +++ b/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj @@ -4,8 +4,6 @@ Library - true - false $(NoWarn);47;75 true true diff --git a/vsintegration/tests/GetTypesVSUnitTests/GetTypesVSUnitTests.fs b/vsintegration/tests/GetTypesVS.UnitTests/GetTypesVS.UnitTests.fs similarity index 100% rename from vsintegration/tests/GetTypesVSUnitTests/GetTypesVSUnitTests.fs rename to vsintegration/tests/GetTypesVS.UnitTests/GetTypesVS.UnitTests.fs diff --git a/vsintegration/tests/GetTypesVSUnitTests/GetTypesVSUnitTests.fsproj b/vsintegration/tests/GetTypesVS.UnitTests/GetTypesVS.UnitTests.fsproj similarity index 92% rename from vsintegration/tests/GetTypesVSUnitTests/GetTypesVSUnitTests.fsproj rename to vsintegration/tests/GetTypesVS.UnitTests/GetTypesVS.UnitTests.fsproj index 68470cf046d..76980662ccd 100644 --- a/vsintegration/tests/GetTypesVSUnitTests/GetTypesVSUnitTests.fsproj +++ b/vsintegration/tests/GetTypesVS.UnitTests/GetTypesVS.UnitTests.fsproj @@ -4,7 +4,9 @@ net46 + x86 Library + $(NoWarn);3005 true true false @@ -15,8 +17,7 @@ - - + diff --git a/vsintegration/tests/GetTypesVSUnitTests/App.config b/vsintegration/tests/GetTypesVSUnitTests/App.config deleted file mode 100644 index 274bc3450a3..00000000000 --- a/vsintegration/tests/GetTypesVSUnitTests/App.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/vsintegration/tests/MockTypeProviders/Directory.Build.props b/vsintegration/tests/MockTypeProviders/Directory.Build.props index a1295702c08..12ae9770dd0 100644 --- a/vsintegration/tests/MockTypeProviders/Directory.Build.props +++ b/vsintegration/tests/MockTypeProviders/Directory.Build.props @@ -1,7 +1,7 @@ - + false diff --git a/vsintegration/tests/MockTypeProviders/Directory.Build.targets b/vsintegration/tests/MockTypeProviders/Directory.Build.targets index 4bc8389ec97..a15fbc0995b 100644 --- a/vsintegration/tests/MockTypeProviders/Directory.Build.targets +++ b/vsintegration/tests/MockTypeProviders/Directory.Build.targets @@ -1,4 +1,4 @@ - + diff --git a/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj b/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj index 6552af44642..5564f3a7bcb 100644 --- a/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj +++ b/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj @@ -61,6 +61,7 @@ + diff --git a/vsintegration/tests/UnitTests/App.config b/vsintegration/tests/UnitTests/App.config index 34d853e9f43..75d99e7329b 100644 --- a/vsintegration/tests/UnitTests/App.config +++ b/vsintegration/tests/UnitTests/App.config @@ -6,7 +6,7 @@ - + diff --git a/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.ParameterInfo.fs b/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.ParameterInfo.fs index 06b42d32efc..0f4271beae3 100644 --- a/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.ParameterInfo.fs +++ b/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.ParameterInfo.fs @@ -2031,25 +2031,6 @@ We really need to rewrite some code paths here to use the real parse tree rather end""" this.VerifyNoParameterInfoAtStartOfMarker(fileContents,"(*Mark*)") - (* Project ref method for multi-parameterinfo tests ----------------------------------------------- *) - - [] - member public this.``Multi.ReferenceToProjectLibrary``() = - use _guard = this.UsingNewVS() - let solution = this.CreateSolution() - let project1 = CreateProject(solution, "FSharpLib") - let project2 = CreateProject(solution, "FSharpPro") - AddProjectReference(project2,project1) - let _ = AddFileFromText(project1, "file1.fs", ["namespace Test";"type public Foo() = class";" static member Sum(x:int,y:int) = x+y";"end"]) - let result1 = Build(project1) - AddFileFromText(project2, "file2.fs", ["open Test";"Foo.Sum(12,(*Mark*)"]) |> ignore - let result2 = Build(project2) - let file = OpenFile(project2, "file2.fs") - MoveCursorToStartOfMarker(file, "(*Mark*)") - - let methodstr = GetParameterInfoAtCursor(file) - AssertMethodGroupContain(methodstr,["int";"int"]) - (* Regression tests/negative tests for multi-parameterinfos --------------------------------------- *) // To be added when the bugs are fixed... [] diff --git a/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.QuickInfo.fs b/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.QuickInfo.fs index 267943da1d3..16d2f34a4e8 100644 --- a/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.QuickInfo.fs +++ b/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.QuickInfo.fs @@ -3171,113 +3171,6 @@ query." ("(*Marker4*)", "Gets and sets X")] this.VerifyUsingFsTestLib fileContent queries false - [] - member public this.``Automation.EnumDUInterfacefromFSBrowse``() = - let fileContent ="""module Test - - open FSTestLib - - type MyTestType() = - [] - val mutable field : int - - interface IMyInterface with - member this.Represent () = "Implement Interface" - - [] - let Main (args : string []) = - let MyEnumFieldSeq = - seq { - for i in 1..10 do - // TC 14 Field Enum F# Browse Comp Expression - let myEnumField = MyColors.Red(*Marker1*) - yield myEnumField - } - - let MyDUList = (fun x -> - match x%3 with - //TC 15 Self DiscUnion F# Browse Lambda - | 0 -> MyDistance(*Marker2*).Kilometers - | 1 -> MyDistance.Miles - | _ -> MyDistance.NauticalMiles - ) - - - - //TC 16 Method Interface F# Browse Lambda - let resultString = new MyTestType() - |> fun (x : MyTestType) -> x :> IMyInterface - |> fun (x : IMyInterface) -> x.Represent(*Marker3*) - 0""" - let queries = [("(*Marker1*)", "Red: MyColors = 0"); - ("(*Marker2*)", "type MyDistance ="); -// ("(*Marker2*)", "DocComment: This is my discriminated union type"); //Fail: due to DocComments - ("(*Marker2*)", "Full name: FSTestLib.MyDistance"); -// ("(*Marker3*)", "DocComment: abstract method in Interface"); //Fail: due to DocComments - ("(*Marker3*)", "abstract member IMyInterface.Represent : unit -> string") - ] - this.VerifyUsingFsTestLib fileContent queries true - - [] - member public this.``Automation.RecordAndInterfaceFromFSProj``() = - let fileContent ="""module Test - - open FSTestLib - - let construct = - seq { - for i in 1..10 do - // TC23 - Testing "Record" type from "F# P2P" inside "Comp Expression" - let a = MyEmployee(*Marker1*).MakeDummy() - a.Name <- "Emp" + i.ToString() - a.Age <- 20 + i - a.IsFTE <- System.Convert.ToBoolean(System.Random().Next(2)) - - // TC25 - Testing "Identifier" of "Record" type from "F# P2P" inside "Quotation" - let b = <@ a(*Marker2*).Name @> - - yield a - } - - // TC27 - Testing "Field/Method" of "Record" type from "F# P2P" inside "Lambda" - let fte_count = - construct - |> Seq.filter (fun a -> a.IsFTE(*Marker3*)) - |> Seq.mapi (fun i a -> i.ToString() + a.ToString(*Marker4*)() ) - |> Seq.length - - // TC24 - Testing "Identifier" of "Interface" type from "F# P2P" inside "Pattern Matching" - type MyTestType() = - [] - val mutable x : int - - interface IMyInterface with - member this.Represent () = this.x.ToString() - - let res = - seq { yield MyTestType() - yield Unchecked.defaultof } - |> Seq.map (fun a -> - let myItf = a :> IMyInterface - match myItf with - | x when x = Unchecked.defaultof -> "" - | itf(*Marker5*) -> itf.Represent() ) - |> Seq.filter (fun s -> s.Length > 0) - |> Seq.length - |> (=) 1""" - let queries = [("(*Marker1*)", "type MyEmployee ="); - ("(*Marker1*)", "mutable IsFTE: bool;"); -// ("(*Marker1*)", "DocComment: This is my record type."); //Fail: due to DocComments - // ("(*Marker1*)", "Full name: FSTestLib.MyEmployee"); // removed from declaration infos - // ("(*Marker1*)", "implements: System.IComparable"); // removed from declaration infos - ("(*Marker2*)", "val a : MyEmployee"); -// ("(*Marker2*)", "implements: System.IComparable"); // removed from declaration infos - ("(*Marker3*)", "MyEmployee.IsFTE: bool"); -// ("(*Marker3*)", "Indicates whether the employee is full time or not"); //Fail: due to DocComments - ("(*Marker5*)", "val itf : IMyInterface") - ] - this.VerifyUsingFsTestLib fileContent queries true - [] member public this.``Automation.StructDelegateDUfromOwnCode``() = let fileContent ="""module Test @@ -3373,105 +3266,6 @@ query." ] this.VerifyUsingFsTestLib fileContent queries false - [] - member public this.``Automation.TupleRecordfromFSBrowse``() = - let fileContent ="""module Test - - open FSTestLib - - let GenerateTuple = fun x -> let tuple = (x,x.ToString(),(float)x, ( fun y -> (y.ToString(),y+1)) ) - // TC 19 Identifier Tuple F# Browse Lambda - tuple(*Marker3*) - let MyTupleSeq = - seq { - for i in 1..9 do - // TC 17 Identifier Tuple F# Browse Comp Expression - let myTuple(*Marker1*) = GenerateTuple i - yield myTuple - } - - let GetTupleMethod tuple= - let (intInTuple,stringInTuple,floatInTuple,methodInTuple) = tuple - methodInTuple - - // TC 20 method Tuple F# Browse Quotation - let methodSeq(*Marker4*) = Seq.map GetTupleMethod MyTupleSeq - - let RecordArray = - [| for x in 1..5 - // TC 18 Method Record F# Browse Imperative - -> MyEmployee.MakeDummy(*Marker2*)()|]""" - let queries = [("(*Marker1*)", "val myTuple : int * string * float * (int -> string * int)"); - ("(*Marker2*)", "static member MyEmployee.MakeDummy : unit -> MyEmployee"); - // ("(*Marker2*)", "DocComment: Method"); //FAIL due to DocComment. - ("(*Marker3*)", "val tuple : int * string * float * (int -> string * int)"); - ("(*Marker4*)", "val methodSeq : seq<(int -> string * int)>"); - ("(*Marker4*)", "Full name: Test.methodSeq") - ] - this.VerifyUsingFsTestLib fileContent queries true - - [] - member public this.``Automation.UnionAndStructFromFSProj``() = - let fileContent ="""module Test - - open FSTestLib - - [] - let Main (args : string []) = - let p1 = FSTestLib.MyPoint(1.0, 2.0) - let (p2 : FSTestLib.MyPoint) = FSTestLib.MyPoint(2.0, 3.0) - - // TODO: Add active pattern testing - let TC21 = - // TC21 - Testing "Identifier" of "Struct" type from "F# P2P" inside "Pattern Matching" - match p1(*Marker1*) + p2 with - | p3(*Marker2*) when p3.X = 4.0 -> p2.Len - | _ as (*Marker3*)Res -> Res.Len - - let TCs () = - let toSun = Kilometers 149597892.0 - - // TC22 - Testing "Identifier" of "Union" type from "F# P2P" inside "Imperative" context - if MyDistance.toMiles toSun(*Marker4*) > toSun then - failwith "Distance in miles can't be bigger than in kilometers." - - let distances : MyDistance list = [toSun; toSun.toNautical; MyDistance.toMiles toSun]; - for element(*Marker5*) in distances do - () - - // TC28 - Testing "Method" of "Union" type from "F# P2P" inside "Pattern Matching" - match MyDistance.toMiles(*Marker6*) toSun with - | Miles x -> - toSun.IncreaseBy(*Marker7*) 1.0 - |> sprintf "Such a distance to Earth [%A] would mean end of world!" |> ignore - | _ -> - failwith "the previos method should have returned Miles type" - - // TC26 - Testing "Property" of "Union" type from "F# P2P" inside "Comp Expression" - async { - let res = toSun.toNautical(*Marker8*) - return res - } - 0""" - let queries = [("(*Marker1*)", "val p1 : MyPoint"); - //("(*Marker1*)", "implements: System.IComparable"); - ("(*Marker2*)", "val p3 : MyPoint"); - //("(*Marker2*)", "type: MyPoint"); - //("(*Marker2*)", "inherits: System.ValueType"); - ("(*Marker4*)", "val toSun : MyDistance"); - //("(*Marker4*)", "type: MyDistance"); - //("(*Marker4*)", "implements: System.IComparable"); - ("(*Marker5*)", "val element : MyDistance"); - //("(*Marker5*)", "type: MyDistance"); - ("(*Marker6*)", "static member MyDistance.toMiles : x:MyDistance -> MyDistance"); -// ("(*Marker6*)", "DocComment: Static Method"); //FAIL due to DocComment - ("(*Marker7*)", "member MyDistance.IncreaseBy : dist:float -> MyDistance"); -// ("(*Marker7*)", "DocComment: Method"); //FAIL due to DocComment - ("(*Marker8*)", "property MyDistance.toNautical: MyDistance"); -// ("(*Marker8*)", "DocComment: Property"); //FAIL due to DocComment - ] - this.VerifyUsingFsTestLib fileContent queries true - (*------------------------------------------IDE Query automation start -------------------------------------------------*) member private this.AssertQuickInfoInQuery(code: string, mark : string, expectedstring : string) = diff --git a/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.Script.fs b/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.Script.fs index cb5c4da346e..cd1589117ad 100644 --- a/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.Script.fs +++ b/vsintegration/tests/UnitTests/LegacyLanguageService/Tests.LanguageService.Script.fs @@ -1337,21 +1337,18 @@ type UsingMSBuild() as this = use _guard = this.UsingNewVS() let solution = this.CreateSolution() let project = CreateProject(solution,"testproject") - let fsVersion = "10.2.3.0" let binariesFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) PlaceIntoProjectFileBeforeImport (project, sprintf @" - - True + %s\\FSharp.Compiler.Interactive.Settings.dll - - True + %s\\FSharp.Compiler.Private.dll - " fsVersion binariesFolder fsVersion binariesFolder) + " binariesFolder binariesFolder) let fsx = AddFileFromTextEx(project,"Script.fsx","Script.fsx",BuildAction.Compile, ["let x = fsi.CommandLineArgs"]) diff --git a/vsintegration/tests/UnitTests/LegacyProjectSystem/Tests.ProjectSystem.References.fs b/vsintegration/tests/UnitTests/LegacyProjectSystem/Tests.ProjectSystem.References.fs index 81b6b55ccb8..0727925db6f 100644 --- a/vsintegration/tests/UnitTests/LegacyProjectSystem/Tests.ProjectSystem.References.fs +++ b/vsintegration/tests/UnitTests/LegacyProjectSystem/Tests.ProjectSystem.References.fs @@ -248,6 +248,7 @@ type References() = with e -> TheTests.HelpfulAssertMatches ' ' "A reference to '.*' could not be added. A reference to the component '.*' already exists in the project." e.Message + [] [] member public this.``ReferenceResolution.Bug650591.AutomationReference.Add.FullPath``() = match Net20AssemExPath() with diff --git a/vsintegration/tests/UnitTests/ProjectOptionsBuilder.fs b/vsintegration/tests/UnitTests/ProjectOptionsBuilder.fs new file mode 100644 index 00000000000..1d3df25165f --- /dev/null +++ b/vsintegration/tests/UnitTests/ProjectOptionsBuilder.fs @@ -0,0 +1,140 @@ +namespace VisualFSharp.UnitTests.Roslyn + +open System +open System.IO +open System.Xml.Linq +open FSharp.Compiler.SourceCodeServices + +type FSharpProject = + { + Directory: string + Options: FSharpProjectOptions + Files: (string * string) list + } + + /// Strips cursor information from each file and returns the name and cursor position of the last file to specify it. + member this.GetCaretPosition () = + let caretSentinel = "$$" + let mutable cursorInfo: (string * int) = (null, 0) + this.Files + |> List.iter (fun (name, contents) -> + // find the '$$' sentinel that represents the cursor location + let caretPosition = contents.IndexOf(caretSentinel) + if caretPosition >= 0 then + let newContents = contents.Substring(0, caretPosition) + contents.Substring(caretPosition + caretSentinel.Length) + File.WriteAllText(Path.Combine(this.Directory, name), newContents) + cursorInfo <- (name, caretPosition)) + cursorInfo + interface IDisposable with + member this.Dispose() = + // delete each source file + this.Files + |> List.iter (fun (path, _contents) -> File.Delete(path)) + // delete the directory + Directory.Delete(this.Directory) + // project file doesn't really exist, nothing to delete + () + +[] +module internal ProjectOptionsBuilder = + let private FileName = XName.op_Implicit "File" + let private NameName = XName.op_Implicit "Name" + let private ProjectName = XName.op_Implicit "Project" + let private ReferenceName = XName.op_Implicit "Reference" + + let private CreateSingleProjectFromMarkup(markup:XElement) = + if markup.Name.LocalName <> "Project" then failwith "Expected root node to be " + let projectRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()) + if Directory.Exists(projectRoot) then Directory.Delete(projectRoot, true) + Directory.CreateDirectory(projectRoot) |> ignore + let files = // filename -> fileContents + markup.Elements(FileName) + |> Seq.map (fun file -> + let fileName = Path.Combine(projectRoot, file.Attribute(NameName).Value) + let fileContents = file.Value + File.WriteAllText(fileName, fileContents) + (fileName, fileContents)) + |> List.ofSeq + let options = + { + ProjectFileName = Path.Combine(projectRoot, markup.Attribute(NameName).Value) + ProjectId = None + SourceFiles = files |> Seq.map fst |> Array.ofSeq + ReferencedProjects = [||] // potentially filled in later + OtherOptions = [||] + IsIncompleteTypeCheckEnvironment = true + UseScriptResolutionRules = false + LoadTime = DateTime.MaxValue + OriginalLoadReferences = [] + UnresolvedReferences = None + ExtraProjectInfo = None + Stamp = None + } + { + Directory = projectRoot + Options = options + Files = files + } + + let private CreateMultipleProjectsFromMarkup(markup:XElement) = + if markup.Name.LocalName <> "Projects" then failwith "Expected root node to be " + let projectsAndXml = + markup.Elements(ProjectName) + |> Seq.map (fun xml -> (CreateSingleProjectFromMarkup xml, xml)) + |> List.ofSeq + // setup project references + let projectMap = + projectsAndXml + |> List.map (fun (projectOptions, _xml) -> + let normalizedProjectName = Path.GetFileName(projectOptions.Options.ProjectFileName) + (normalizedProjectName, projectOptions)) + |> Map.ofList + let projects = + projectsAndXml + |> List.map(fun (projectOptions, xml) -> + // bind references to their `FSharpProjectOptions` counterpart + let referenceList = + xml.Elements(ReferenceName) + |> Seq.map (fun reference -> reference.Value) + |> Seq.fold (fun list reference -> reference :: list) [] + |> List.rev + |> List.map (fun referencedProject -> + let project = projectMap.[referencedProject] + let asmName = Path.GetFileNameWithoutExtension(project.Options.ProjectFileName) + let binaryPath = Path.Combine(project.Directory, "bin", asmName + ".dll") + (binaryPath, project.Options)) + |> Array.ofList + let binaryRefs = + referenceList + |> Array.map fst + |> Array.map (fun r -> "-r:" + r) + let otherOptions = Array.append projectOptions.Options.OtherOptions binaryRefs + { projectOptions with + Options = { projectOptions.Options with + ReferencedProjects = referenceList + OtherOptions = otherOptions + } + }) + let rootProject = List.head projects + rootProject + + let CreateProjectFromMarkup(markup:XElement) = + match markup.Name.LocalName with + | "Project" -> CreateSingleProjectFromMarkup markup + | "Projects" -> CreateMultipleProjectsFromMarkup markup + | name -> failwith <| sprintf "Unsupported root node name: %s" name + + let CreateProject(markup:string) = + XDocument.Parse(markup).Root + |> CreateProjectFromMarkup + + let SingleFileProject(code:string) = + code + |> sprintf @" + + + + + +" + |> CreateProject diff --git a/vsintegration/tests/UnitTests/QuickInfoTests.fs b/vsintegration/tests/UnitTests/QuickInfoTests.fs new file mode 100644 index 00000000000..19d140de88b --- /dev/null +++ b/vsintegration/tests/UnitTests/QuickInfoTests.fs @@ -0,0 +1,445 @@ +namespace Microsoft.VisualStudio.FSharp.Editor.Tests.Roslyn + +open System.IO +open FSharp.Compiler.SourceCodeServices +open Microsoft.CodeAnalysis +open Microsoft.CodeAnalysis.Text +open Microsoft.VisualStudio.FSharp.Editor +open NUnit.Framework +open UnitTests.TestLib.LanguageService +open VisualFSharp.UnitTests.Roslyn + +[] +module QuickInfo = + +let internal GetQuickInfo (project:FSharpProject) (fileName:string) (caretPosition:int) = + async { + let code = File.ReadAllText(fileName) + let sourceText = SourceText.From(code) + let documentId = DocumentId.CreateNewId(ProjectId.CreateNewId()) // only used for caching purposes + return! FSharpAsyncQuickInfoSource.ProvideQuickInfo(checker, documentId, sourceText, fileName, caretPosition, FSharpParsingOptions.Default, project.Options, 0, LanguageServicePerformanceOptions.Default) + } |> Async.RunSynchronously + +let GetQuickInfoText (project:FSharpProject) (fileName:string) (caretPosition:int) = + let sigHelp = GetQuickInfo project fileName caretPosition + match sigHelp with + | Some (quickInfo) -> + let documentationBuilder = + { new IDocumentationBuilder with + override __.AppendDocumentationFromProcessedXML(_, _, _, _, _, _) = () + override __.AppendDocumentation(_, _, _, _, _, _, _) = () + } + let mainDescription, docs = FSharpAsyncQuickInfoSource.BuildSingleQuickInfoItem documentationBuilder quickInfo + let mainTextItems = + mainDescription + |> Seq.map (fun x -> x.Text) + let docTextItems = + docs + |> Seq.map (fun x -> x.Text) + System.String.Join(System.String.Empty, (Seq.concat [mainTextItems; docTextItems])) + | _ -> "" + +let GetQuickInfoTextFromCode (code:string) = + use project = SingleFileProject code + let fileName, caretPosition = project.GetCaretPosition() + GetQuickInfoText project fileName caretPosition + +let expectedLines (lines:string list) = System.String.Join("\n", lines) + +// migrated from legacy test +[] +let ``Automation.EnumDUInterfacefromFSBrowse.InsideComputationExpression`` () = + let code = """ +namespace FsTest + +type MyColors = + | Red = 0 + | Green = 1 + | Blue = 2 + +module Test = + let test() = + let x = + seq { + for i in 1..10 do + let f = MyColors.Re$$d + yield f + } + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "MyColors.Red: MyColors = 0" + Assert.AreEqual(expected, quickInfo) + +// migrated from legacy test +[] +let ``Automation.EnumDUInterfacefromFSBrowse.InsideMatch`` () = + let code = """ +namespace FsTest + +type MyDistance = + | Kilometers of float + | Miles of float + | NauticalMiles of float + +module Test = + let test() = + let myDuList = (fun x -> + match x with + | 0 -> MyDistanc$$e.Kilometers + | 1 -> MyDistance.Miles + | _ -> MyDistance.NauticalMiles + ) + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = + expectedLines [ "type MyDistance =" + " | Kilometers of float" + " | Miles of float" + " | NauticalMiles of float" + "Full name: FsTest.MyDistance" ] + Assert.AreEqual(expected, quickInfo) + +// migrated from legacy test +[] +let ``Automation.EnumDUInterfacefromFSBrowse.InsideLambda`` () = + let code = """ +namespace FsTest + +type IMyInterface = + interface + abstract Represent : unit -> string + end + +type MyTestType() = + [] + val mutable field : int + + interface IMyInterface with + member this.Represent () = "Implement Interface" + +module Test = + let test() = + let s = new MyTestType() + |> fun (x:MyTestType) -> x :> IMyInterface + |> fun (x:IMyInterface) -> x.Represen$$t() + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "abstract member IMyInterface.Represent : unit -> string" + Assert.AreEqual(expected, quickInfo) + +// migrated from legacy test +[] +let ``Automation.RecordAndInterfaceFromFSProj.InsideComputationExpression``() = + let code = """ +namespace FsTest + +type MyEmployee = + { mutable Name : string; + mutable Age : int; + mutable IsFTE : bool } + +module Test = + let test() = + let construct = + seq { + for i in 1..10 do + let a = MyEmploye$$e.MakeDummy() + () + } + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = + expectedLines [ "type MyEmployee =" + " {mutable Name: string;" + " mutable Age: int;" + " mutable IsFTE: bool;}" + "Full name: FsTest.MyEmployee" ] + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.RecordAndInterfaceFromFSProj.InsideQuotation``() = + let code = """ +namespace FsTest + +type MyEmployee = + { mutable Name : string; + mutable Age : int; + mutable IsFTE : bool } + +module Test = + let test() = + let aa = { Name: "name"; + Age: 1; + IsFTE: false; } + let b = <@ a$$a.Name @> + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "val aa : MyEmployee" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.RecordAndInterfaceFromFSProj.InsideLambda``() = + let code = """ +namespace FsTest + +type MyEmployee = + { mutable Name : string; + mutable Age : int; + mutable IsFTE : bool } + +module Test = + let test() = + let aa = { Name: "name"; + Age: 1; + IsFTE: false; } + let b = + [ aa ] + |> List.filter (fun e -> e.IsFT$$E) + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "MyEmployee.IsFTE: bool" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.TupleRecordFromFSBrowse.InsideComputationExpression``() = + let code = """ +namespace FsTest + +module Test = + let GenerateTuple = + fun x -> + let tuple = (x, x.ToString(), (float)x, (fun y -> (y.ToString(), y + 1))) + tuple + let test() = + let mySeq = + seq { + for i in 1..9 do + let my$$Tuple = GenerateTuple i + yield myTuple + } + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "val myTuple : int * string * float * (int -> string * int)" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.TupleRecordFromFSBrowse.SequenceOfMethods``() = + let code = """ +namespace FsTest + +module Test = + let GenerateTuple = + fun x -> + let tuple = (x, x.ToString(), (float)x, (fun y -> (y.ToString(), y + 1))) + tuple + let GetTupleMethod tuple = + let (_intInTuple, _stringInTuple, _floatInTuple, methodInTuple) = tuple + methodInTuple + let test() = + let mySeq = + seq { + for i in 1..9 do + let myTuple = GenerateTuple i + yield myTuple + } + let method$$Seq = Seq.map GetTupleMethod mySeq + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "val methodSeq : seq<(int -> string * int)>" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.UnionAndStructFromFSProj.MatchExpression``() = + let code = """ +namespace FsTest + +[] +type MyPoint(x:int, y:int) = + member this.X = x + member this.Y = y + +module Test = + let test() = + let p1 = MyPoint(1, 2) + match p$$1 with + | p3 when p3.X = 1 -> 0 + | _ -> 1 +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "val p1 : MyPoint" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.UnionAndStructFromFSProj.MatchPattern``() = + let code = """ +namespace FsTest + +[] +type MyPoint(x:int, y:int) = + member this.X = x + member this.Y = y + +module Test = + let test() = + let p1 = MyPoint(1, 2) + match p1 with + | p$$3 when p3.X = 1 -> 0 + | _ -> 1 +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "val p3 : MyPoint" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.UnionAndStructFromFSProj.UnionIfPredicate``() = + let code = """ +namespace FsTest + +type MyDistance = + | Kilometers of float + | Miles of float + | NauticalMiles of float + +module Test = + let test() = + let dd = MyDistance.Kilometers 1.0 + if MyDistance.toMiles d$$d > 0 then () + else () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "val dd : MyDistance" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.UnionAndStructFromFSProj.UnionForPattern``() = + let code = """ +namespace FsTest + +type MyDistance = + | Kilometers of float + | Miles of float + | NauticalMiles of float + +module Test = + let test() = + let distances = [ MyDistance.Kilometers 1.0; MyDistance.Miles 1.0 ] + for dist$$ance in distances do + () +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "val distance : MyDistance" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.UnionAndStructFromFSProj.UnionMethodPatternMatch``() = + let code = """ +namespace FsTest + +type MyDistance = + | Kilometers of float + | Miles of float + | NauticalMiles of float + static member toMiles x = + Miles( + match x with + | Miles x -> x + | Kilometers x -> x / 1.6 + | NauticalMiles x -> x * 1.15 + ) + +module Test = + let test() = + let dd = MyDistance.Kilometers 1.0 + match MyDistance.to$$Miles dd with + | Miles x -> 0 + | _ -> 1 +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "static member MyDistance.toMiles : x:MyDistance -> MyDistance" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.UnionAndStructFromFSProj.UnionMethodPatternMatchBody``() = + let code = """ +namespace FsTest + +type MyDistance = + | Kilometers of float + | Miles of float + | NauticalMiles of float + member this.IncreaseBy dist = + match this with + | Kilometers x -> Kilometers (x + dist) + | Miles x -> Miles (x + dist) + | NauticalMiles x -> NauticalMiles (x + dist) + +module Test = + let test() = + let dd = MyDistance.Kilometers 1.0 + match dd.toMiles() with + | Miles x -> dd.Increase$$By 1.0 + | _ -> dd +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "member MyDistance.IncreaseBy : dist:float -> MyDistance" + Assert.AreEqual(expected, quickInfo) + () + +// migrated from legacy test +[] +let ``Automation.UnionAndStructFromFSProj.UnionPropertyInComputationExpression``() = + let code = """ +namespace FsTest + +type MyDistance = + | Kilometers of float + | Miles of float + | NauticalMiles of float + member this.asNautical = + NauticalMiles( + match this with + | Kilometers x -> x / 1.852 + | Miles x -> x / 1.15 + | NauticalMiles x -> x + ) + +module Test = + let test() = + let dd = MyDistance.Kilometers 1.0 + async { + let r = dd.as$$Nautical + return r + } +""" + let quickInfo = GetQuickInfoTextFromCode code + let expected = "property MyDistance.asNautical: MyDistance" + Assert.AreEqual(expected, quickInfo) + () diff --git a/vsintegration/tests/UnitTests/SignatureHelpProviderTests.fs b/vsintegration/tests/UnitTests/SignatureHelpProviderTests.fs index f61517bf4da..f981fe94cb7 100644 --- a/vsintegration/tests/UnitTests/SignatureHelpProviderTests.fs +++ b/vsintegration/tests/UnitTests/SignatureHelpProviderTests.fs @@ -26,6 +26,7 @@ open System.IO open System.Text open NUnit.Framework open Microsoft.CodeAnalysis.Text +open VisualFSharp.UnitTests.Roslyn open Microsoft.VisualStudio.FSharp.Editor open FSharp.Compiler.SourceCodeServices open UnitTests.TestLib.LanguageService @@ -49,6 +50,43 @@ let internal projectOptions = { Stamp = None } +let private DefaultDocumentationProvider = + { new IDocumentationBuilder with + override doc.AppendDocumentationFromProcessedXML(_, _, _, _, _, _) = () + override doc.AppendDocumentation(_, _, _, _, _, _, _) = () + } + +let GetSignatureHelp (project:FSharpProject) (fileName:string) (caretPosition:int) = + async { + let triggerChar = None // TODO: + let code = File.ReadAllText(fileName) + let! triggered = FSharpSignatureHelpProvider.ProvideMethodsAsyncAux(checker, DefaultDocumentationProvider, SourceText.From(code), caretPosition, project.Options, triggerChar, fileName, 0) + return triggered + } |> Async.RunSynchronously + +let GetCompletionTypeNames (project:FSharpProject) (fileName:string) (caretPosition:int) = + let sigHelp = GetSignatureHelp project fileName caretPosition + match sigHelp with + | None -> [||] + | Some (items, _applicableSpan, _argumentIndex, _argumentCount, _argumentName) -> + let completionTypeNames = + items + |> Array.map (fun (_, _, _, _, _, x, _) -> x |> Array.map (fun (_, _, x, _, _) -> x)) + completionTypeNames + +let GetCompletionTypeNamesFromCursorPosition (project:FSharpProject) = + let fileName, caretPosition = project.GetCaretPosition() + let completionNames = GetCompletionTypeNames project fileName caretPosition + completionNames + +let GetCompletionTypeNamesFromXmlString (xml:string) = + use project = CreateProject xml + GetCompletionTypeNamesFromCursorPosition project + +let GetCompletionTypeNamesFromCode (code:string) = + use project = SingleFileProject code + GetCompletionTypeNamesFromCursorPosition project + [] let ShouldGiveSignatureHelpAtCorrectMarkers() = let manyTestCases = @@ -139,14 +177,8 @@ type foo5 = N1.T let caretPosition = fileContents.IndexOf(marker) + marker.Length - let documentationProvider = - { new IDocumentationBuilder with - override doc.AppendDocumentationFromProcessedXML(_, _, _, _, _, _) = () - override doc.AppendDocumentation(_, _, _, _, _, _, _) = () - } - let triggerChar = if marker = "," then Some ',' elif marker = "(" then Some '(' elif marker = "<" then Some '<' else None - let triggered = FSharpSignatureHelpProvider.ProvideMethodsAsyncAux(checker, documentationProvider, SourceText.From(fileContents), caretPosition, projectOptions, triggerChar, filePath, 0) |> Async.RunSynchronously + let triggered = FSharpSignatureHelpProvider.ProvideMethodsAsyncAux(checker, DefaultDocumentationProvider, SourceText.From(fileContents), caretPosition, projectOptions, triggerChar, filePath, 0) |> Async.RunSynchronously checker.ClearLanguageServiceRootCachesAndCollectAndFinalizeAllTransients() let actual = match triggered with @@ -164,8 +196,36 @@ type foo5 = N1.T | "" -> () | errorText -> Assert.Fail errorText +// migrated from legacy test +[] +let ``Multi.ReferenceToProjectLibrary``() = + let completionNames = GetCompletionTypeNamesFromXmlString @" + + + + HelperLibrary.fsproj + + + + + + + + + + -#if EXE -ShouldGiveSignatureHelpAtCorrectMarkers() -#endif + +" + let expected = [| + [|"System.Int32"; "System.Int32"|] + |] + Assert.AreEqual(expected, completionNames) diff --git a/vsintegration/tests/UnitTests/Tests.Watson.fs b/vsintegration/tests/UnitTests/Tests.Watson.fs index 491a4bf37da..9cb4b7afa65 100644 --- a/vsintegration/tests/UnitTests/Tests.Watson.fs +++ b/vsintegration/tests/UnitTests/Tests.Watson.fs @@ -26,7 +26,11 @@ type Check = if (File.Exists("watson-test.fs")) then File.Delete("watson-test.fs") File.WriteAllText("watson-test.fs", "// Hello watson" ) - let argv = [| "--simulateException:"+simulationCode; "watson-test.fs"|] + let argv = + [| "--simulateException:"+simulationCode + "--nowarn:988" // don't show `watson-test.fs(1,16): warning FS0988: Main module of program is empty: nothing will happen when it is run` + "watson-test.fs" + |] let ctok = AssumeCompilationThreadWithoutEvidence () let _code = mainCompile (ctok, argv, FSharp.Compiler.MSBuildReferenceResolver.Resolver, false, ReduceMemoryFlag.No, CopyFSharpCoreFlag.No, FSharp.Compiler.ErrorLogger.QuitProcessExiter, ConsoleLoggerProvider(), None, None) diff --git a/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj b/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj index 33f14a5e284..a92cc7cdd64 100644 --- a/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj +++ b/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj @@ -4,8 +4,9 @@ net46 + x86 Library - $(NoWarn);58;75 + $(NoWarn);44;58;75;3005 NO_PROJECTCRACKER;$(DefineConstants) true true @@ -110,6 +111,9 @@ CompilerService\TreeVisitorTests.fs + + Roslyn\ProjectOptionsBuilder.fs + Roslyn\SyntacticColorizationServiceTests.fs @@ -148,6 +152,9 @@ Roslyn\SignatureHelpProviderTests.fs + + Roslyn\QuickInfoTests.fs + Roslyn\GoToDefinitionServiceTests.fs @@ -163,6 +170,8 @@ PreserveNewest + + @@ -212,7 +221,7 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + From af97b92e65ed4a29d564ff0502a21e0cc3362a9c Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Thu, 21 Mar 2019 16:47:50 -0700 Subject: [PATCH 03/27] update nightly publish path (#6361) --- .vsts-signed.yaml | 2 +- setup/publish-assets.ps1 | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.vsts-signed.yaml b/.vsts-signed.yaml index 599237086b3..21986906d64 100644 --- a/.vsts-signed.yaml +++ b/.vsts-signed.yaml @@ -86,7 +86,7 @@ jobs: displayName: Publish nightly package to MyGet inputs: scriptName: 'setup\publish-assets.ps1' - arguments: '-binariesPath artifacts\bin -configuration $(BuildConfiguration) -branchName $(Build.SourceBranch) -apiKey $(FSharp.MyGetApiKey)' + arguments: '-artifactsPath artifacts -configuration $(BuildConfiguration) -branchName $(Build.SourceBranch) -apiKey $(FSharp.MyGetApiKey)' condition: succeeded() # Package publish diff --git a/setup/publish-assets.ps1 b/setup/publish-assets.ps1 index bfa905bbad9..7ef01a5ffc3 100644 --- a/setup/publish-assets.ps1 +++ b/setup/publish-assets.ps1 @@ -2,7 +2,7 @@ .SYNOPSIS Publishes the VSIX package on MyGet. -.PARAMETER binariesPath +.PARAMETER artifactsPath The root directory where the build outputs are written. .PARAMETER branchName @@ -14,7 +14,7 @@ The API key used to authenticate with MyGet. #> Param( - [string]$binariesPath = $null, + [string]$artifactsPath = $null, [string]$branchName = $null, [string]$apiKey = $null, [string]$configuration = $null @@ -41,7 +41,7 @@ try { } $branchName = $branchName.Replace("/", "_") # can't have slashes in the branch name - $vsix = Join-Path $binariesPath "VisualFSharpFull\$configuration\net46\VisualFSharpFull.vsix" + $vsix = Join-Path $artifactsPath "VSSetup\$configuration\Insertion\VisualFSharpFull.vsix" Write-Host " Uploading '$vsix' to '$requestUrl'." From 13db5a279941fb96632154cd3f5c51f4f2ebe9f5 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" Date: Fri, 22 Mar 2019 09:55:25 -0700 Subject: [PATCH 04/27] Update dependencies from https://github.com/dotnet/arcade build 20190321.3 (#6366) - Microsoft.DotNet.Arcade.Sdk - 1.0.0-beta.19171.3 --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 31 ++++++++----------------------- global.json | 2 +- 3 files changed, 11 insertions(+), 26 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 4b3e52da9c9..5ea98bd6922 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -3,9 +3,9 @@ - + https://github.com/dotnet/arcade - 9ba7a4ced36358fc130b762d25a83fa370c296c9 + b3bcf3034ff395bd09066114379ec64736b13633 diff --git a/eng/Versions.props b/eng/Versions.props index 1e029d23606..e78e3b4c5ee 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -1,9 +1,7 @@ - false - true true @@ -11,40 +9,36 @@ true true - beta - 4.5 $(FSCoreMajorVersion).5 $(FSCoreMajorVersion).0 - $(FSCoreVersion).0 - + $(FSCoreVersion).0 + 10.2 $(FSPackageMajorVersion).3 $(FSPackageVersion) - $(FSProductVersion).0 - + $(FSProductVersion).0 + 15 9 $(VSMajorVersion).0 $(VSMajorVersion).$(VSMinorVersion).0 - $(VSAssemblyVersion).0 + $(VSAssemblyVersion).0 + - $(FSCoreVersion) $(FSProductVersion) $(VSAssemblyVersion) $(VSMajorVersion).$(VSMinorVersion).0 - - $(VersionPrefix) + $(VersionPrefix) + - - $(RestoreSources); @@ -61,10 +55,8 @@ https://vside.myget.org/F/vssdk/api/v3/index.json; https://vside.myget.org/F/vs-impl/api/v3/index.json; - $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)..\RoslynPackageVersion.txt').Trim()) - 1.5.0 4.3.0 @@ -91,21 +83,18 @@ 4.3.0 4.3.0 4.4.0 - $(RoslynPackageVersion) $(RoslynPackageVersion) $(RoslynPackageVersion) $(RoslynPackageVersion) $(RoslynPackageVersion) - 15.8.166 $(MicrosoftBuildOverallPackagesVersion) $(MicrosoftBuildOverallPackagesVersion) $(MicrosoftBuildOverallPackagesVersion) $(MicrosoftBuildOverallPackagesVersion) - 8.0.1 14.0.25420 @@ -152,12 +141,10 @@ 8.0.4 11.0.4 7.0.4 - 0.2.0 1.0.0 1.0.147 - 3.0.0-alpha4 1.0.30 @@ -174,7 +161,5 @@ 2.1.36 1.0.0-beta2-dev3 5.22.2.1 - - diff --git a/global.json b/global.json index a6d9f0d3ca5..099f010dd1c 100644 --- a/global.json +++ b/global.json @@ -10,7 +10,7 @@ } }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.19170.12", + "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.19171.3", "Microsoft.DotNet.Helix.Sdk": "2.0.0-beta.19069.2" } } From da973133c29b21e955834b4a4fcc201899f690b5 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Fri, 22 Mar 2019 11:20:07 -0700 Subject: [PATCH 05/27] build FSharp.Core package with appropriate version number (#6368) --- VisualFSharp.sln | 41 +++++++++++++------ eng/Versions.props | 1 + .../FSharp.Core.nuget/Directory.Build.props | 9 ++++ .../FSharp.Core.nuget.csproj | 20 +++++++++ .../FSharp.Core.nuspec | 0 src/fsharp/FSharp.Core/FSharp.Core.fsproj | 3 -- .../VisualFSharpTemplates.csproj | 2 +- 7 files changed, 59 insertions(+), 17 deletions(-) create mode 100644 src/fsharp/FSharp.Core.nuget/Directory.Build.props create mode 100644 src/fsharp/FSharp.Core.nuget/FSharp.Core.nuget.csproj rename src/fsharp/{FSharp.Core => FSharp.Core.nuget}/FSharp.Core.nuspec (100%) diff --git a/VisualFSharp.sln b/VisualFSharp.sln index 2ac4e75bf61..278bea71bc8 100644 --- a/VisualFSharp.sln +++ b/VisualFSharp.sln @@ -152,6 +152,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibraryProject", "vsintegra EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TutorialProject", "vsintegration\ProjectTemplates\TutorialProject\TutorialProject.csproj", "{7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FSharp.Core.nuget", "src\fsharp\FSharp.Core.nuget\FSharp.Core.nuget.csproj", "{8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -198,6 +200,18 @@ Global {59ADCE46-9740-4079-834D-9A03A3494EBC}.Release|Any CPU.Build.0 = Release|Any CPU {59ADCE46-9740-4079-834D-9A03A3494EBC}.Release|x86.ActiveCfg = Release|Any CPU {59ADCE46-9740-4079-834D-9A03A3494EBC}.Release|x86.Build.0 = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|Any CPU.Build.0 = Debug|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|x86.ActiveCfg = Debug|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|x86.Build.0 = Debug|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|Any CPU.Build.0 = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|x86.ActiveCfg = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|x86.Build.0 = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|Any CPU.ActiveCfg = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|Any CPU.Build.0 = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|x86.ActiveCfg = Release|Any CPU + {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|x86.Build.0 = Release|Any CPU {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|Any CPU.Build.0 = Debug|Any CPU {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -810,18 +824,6 @@ Global {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Release|Any CPU.Build.0 = Release|Any CPU {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Release|x86.ActiveCfg = Release|Any CPU {9482211E-23D0-4BD0-9893-E4AA5559F67A}.Release|x86.Build.0 = Release|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|Any CPU.Build.0 = Debug|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|x86.ActiveCfg = Debug|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Debug|x86.Build.0 = Debug|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|Any CPU.ActiveCfg = Release|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|Any CPU.Build.0 = Release|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|x86.ActiveCfg = Release|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Proto|x86.Build.0 = Release|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|Any CPU.ActiveCfg = Release|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|Any CPU.Build.0 = Release|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|x86.ActiveCfg = Release|Any CPU - {025CE01B-98F3-4C3C-B486-2C0BD038D011}.Release|x86.Build.0 = Release|Any CPU {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Debug|Any CPU.Build.0 = Debug|Any CPU {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8}.Debug|x86.ActiveCfg = Debug|Any CPU @@ -870,6 +872,18 @@ Global {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Release|Any CPU.Build.0 = Release|Any CPU {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Release|x86.ActiveCfg = Release|Any CPU {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1}.Release|x86.Build.0 = Release|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Debug|x86.ActiveCfg = Debug|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Debug|x86.Build.0 = Debug|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Proto|Any CPU.ActiveCfg = Release|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Proto|Any CPU.Build.0 = Release|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Proto|x86.ActiveCfg = Release|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Proto|x86.Build.0 = Release|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Release|Any CPU.Build.0 = Release|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Release|x86.ActiveCfg = Release|Any CPU + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -884,6 +898,7 @@ Global {991DCF75-C2EB-42B6-9A0D-AA1D2409D519} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {2E4D67B4-522D-4CF7-97E4-BA940F0B18F3} = {3881429D-A97A-49EB-B7AE-A82BA5FE9C77} {59ADCE46-9740-4079-834D-9A03A3494EBC} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} + {025CE01B-98F3-4C3C-B486-2C0BD038D011} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {D5870CF0-ED51-4CBC-B3D7-6F56DA84AC06} = {B8DDA694-7939-42E3-95E5-265C2217C142} {DED3BBD7-53F4-428A-8C9F-27968E768605} = {3058BC79-8E79-4645-B05D-48CC182FA8A6} {EE85AAB7-CDA0-4C4E-BDA0-A64CCC413E3F} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} @@ -935,12 +950,12 @@ Global {6BCFED7A-3F67-4180-B307-C7D69D191D8C} = {6235B3AF-774D-4EA1-8F37-789E767F6368} {E93E7D28-1C6B-4E04-BE83-68428CF7E039} = {6235B3AF-774D-4EA1-8F37-789E767F6368} {9482211E-23D0-4BD0-9893-E4AA5559F67A} = {6235B3AF-774D-4EA1-8F37-789E767F6368} - {025CE01B-98F3-4C3C-B486-2C0BD038D011} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {04C59F6E-1C76-4F6A-AC21-2EA7F296A1B8} = {647810D0-5307-448F-99A2-E83917010DAE} {BED74F9E-A0D2-48E2-9EE7-449832100487} = {4C7B48D7-19AF-4AE7-9D1D-3BB289D5480D} {1D8D778E-8D6B-4A8C-88A6-BE578988FBE8} = {BED74F9E-A0D2-48E2-9EE7-449832100487} {C32806E0-71C2-40E4-AEC4-517F73F6A18A} = {BED74F9E-A0D2-48E2-9EE7-449832100487} {7B345E51-F2C0-4D4B-B0E0-05432EC9D5E1} = {BED74F9E-A0D2-48E2-9EE7-449832100487} + {8EC30B2E-F1F9-4A98-BBB5-DD0CF6C84DDC} = {647810D0-5307-448F-99A2-E83917010DAE} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {48EDBBBE-C8EE-4E3C-8B19-97184A487B37} diff --git a/eng/Versions.props b/eng/Versions.props index e78e3b4c5ee..e8849e035f9 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -32,6 +32,7 @@ $(FSCoreVersion) + $(FSCorePackageVersion) $(FSProductVersion) $(VSAssemblyVersion) $(VSMajorVersion).$(VSMinorVersion).0 diff --git a/src/fsharp/FSharp.Core.nuget/Directory.Build.props b/src/fsharp/FSharp.Core.nuget/Directory.Build.props new file mode 100644 index 00000000000..7509ab35a14 --- /dev/null +++ b/src/fsharp/FSharp.Core.nuget/Directory.Build.props @@ -0,0 +1,9 @@ + + + + true + + + + + diff --git a/src/fsharp/FSharp.Core.nuget/FSharp.Core.nuget.csproj b/src/fsharp/FSharp.Core.nuget/FSharp.Core.nuget.csproj new file mode 100644 index 00000000000..fd2d5162c75 --- /dev/null +++ b/src/fsharp/FSharp.Core.nuget/FSharp.Core.nuget.csproj @@ -0,0 +1,20 @@ + + + + true + net45;netstandard1.6 + FSharp.Core + FSharp.Core.nuspec + true + FSharp.Core redistributables from Visual F# Tools version $(FSPackageMajorVersion) For F# $(FSCoreMajorVersion) + + + + + false + + + + + + diff --git a/src/fsharp/FSharp.Core/FSharp.Core.nuspec b/src/fsharp/FSharp.Core.nuget/FSharp.Core.nuspec similarity index 100% rename from src/fsharp/FSharp.Core/FSharp.Core.nuspec rename to src/fsharp/FSharp.Core.nuget/FSharp.Core.nuspec diff --git a/src/fsharp/FSharp.Core/FSharp.Core.fsproj b/src/fsharp/FSharp.Core/FSharp.Core.fsproj index de0fca82aa6..b7f089b3e0c 100644 --- a/src/fsharp/FSharp.Core/FSharp.Core.fsproj +++ b/src/fsharp/FSharp.Core/FSharp.Core.fsproj @@ -6,9 +6,6 @@ Library net45;netstandard1.6 netstandard1.6 - true - FSharp.Core redistributables from Visual F# Tools version $(FSPackageMajorVersion) For F# $(FSCoreMajorVersion) - FSharp.Core.nuspec $(NoWarn);45;55;62;75;1204 true $(DefineConstants);FSHARP_CORE diff --git a/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj b/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj index 36034d0509a..ba573f93ad5 100644 --- a/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj +++ b/vsintegration/Vsix/VisualFSharpTemplates/VisualFSharpTemplates.csproj @@ -21,7 +21,7 @@ - + packages PackOutputGroup%3b false From e6baf1cd9b4f7226bb87e5b9c2e606c1421a1ce3 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Fri, 22 Mar 2019 14:56:18 -0700 Subject: [PATCH 06/27] ensure dev15.9 nightly package version numbers are increasing (#6369) --- eng/Versions.props | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/eng/Versions.props b/eng/Versions.props index e8849e035f9..d1cc8d36cfd 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -35,7 +35,17 @@ $(FSCorePackageVersion) $(FSProductVersion) $(VSAssemblyVersion) - $(VSMajorVersion).$(VSMinorVersion).0 + + <_BuildNumber>$(OfficialBuildId) + <_BuildNumber Condition="'$(OfficialBuildId)' == ''">$([System.DateTime]::Now.ToString(yyyyMMdd)).0 + $(_BuildNumber.Split('.')[0]) + $(VSMajorVersion).$(VSMinorVersion).$(VsixVersionDateStampFix) $(VersionPrefix) From 3afeccc4d639d483cceb98e52529fca7597fc74a Mon Sep 17 00:00:00 2001 From: Phillip Carter Date: Fri, 22 Mar 2019 15:57:55 -0700 Subject: [PATCH 07/27] Update vsix links --- DEVGUIDE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DEVGUIDE.md b/DEVGUIDE.md index 1c0ff3eabe3..83d88b8e8d9 100644 --- a/DEVGUIDE.md +++ b/DEVGUIDE.md @@ -114,12 +114,12 @@ components installed in that VS installation. You can revert this step by disab For **Debug**, uninstall then reinstall: VSIXInstaller.exe /u:"VisualFSharp" - VSIXInstaller.exe artifacts\bin\VisualFSharpFull\Debug\net46\VisualFSharpFull.vsix + VSIXInstaller.exe artifacts\VSSetup\Debug\VisualFSharpFull.vsix For **Release**, uninstall then reinstall: VSIXInstaller.exe /u:"VisualFSharp" - VSIXInstaller.exe artifacts\bin\VisualFSharpFull\Release\net46\VisualFSharpFull.vsix + VSIXInstaller.exe artifacts\VSSetup\Release\VisualFSharpFull.vsix Restart Visual Studio, it should now be running your freshly-built Visual F# IDE Tools with updated F# Interactive. From 74f83e1e27b5849b19463fd55bd597f952da4ab6 Mon Sep 17 00:00:00 2001 From: Phillip Carter Date: Fri, 22 Mar 2019 16:16:06 -0700 Subject: [PATCH 08/27] Clear status bar after navigable symbol is resolved --- .../src/FSharp.Editor/Navigation/NavigableSymbolsService.fs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vsintegration/src/FSharp.Editor/Navigation/NavigableSymbolsService.fs b/vsintegration/src/FSharp.Editor/Navigation/NavigableSymbolsService.fs index bc6cf3e233e..ca4e36fb581 100644 --- a/vsintegration/src/FSharp.Editor/Navigation/NavigableSymbolsService.fs +++ b/vsintegration/src/FSharp.Editor/Navigation/NavigableSymbolsService.fs @@ -62,6 +62,8 @@ type internal FSharpNavigableSymbolSource(checkerProvider: FSharpCheckerProvider let declarationSpan = Span(declarationTextSpan.Start, declarationTextSpan.Length) let symbolSpan = SnapshotSpan(snapshot, declarationSpan) + statusBar.Clear() + return FSharpNavigableSymbol(navigableItem, symbolSpan, gtd, statusBar) :> INavigableSymbol else statusBar.TempMessage(SR.CannotDetermineSymbol()) From 4adf5513ecfa86a4bf9428a78f9979ca694d86a6 Mon Sep 17 00:00:00 2001 From: Phillip Carter Date: Fri, 22 Mar 2019 16:17:17 -0700 Subject: [PATCH 09/27] yert --- .../src/FSharp.Editor/Navigation/NavigableSymbolsService.fs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Navigation/NavigableSymbolsService.fs b/vsintegration/src/FSharp.Editor/Navigation/NavigableSymbolsService.fs index ca4e36fb581..e433733f4d0 100644 --- a/vsintegration/src/FSharp.Editor/Navigation/NavigableSymbolsService.fs +++ b/vsintegration/src/FSharp.Editor/Navigation/NavigableSymbolsService.fs @@ -54,6 +54,7 @@ type internal FSharpNavigableSymbolSource(checkerProvider: FSharpCheckerProvider try // This call to Wait() is fine because we want to be able to provide the error message in the status bar. gtdTask.Wait() + statusBar.Clear() if gtdTask.Status = TaskStatus.RanToCompletion && gtdTask.Result.IsSome then let navigableItem, range = gtdTask.Result.Value @@ -62,8 +63,6 @@ type internal FSharpNavigableSymbolSource(checkerProvider: FSharpCheckerProvider let declarationSpan = Span(declarationTextSpan.Start, declarationTextSpan.Length) let symbolSpan = SnapshotSpan(snapshot, declarationSpan) - statusBar.Clear() - return FSharpNavigableSymbol(navigableItem, symbolSpan, gtd, statusBar) :> INavigableSymbol else statusBar.TempMessage(SR.CannotDetermineSymbol()) From 61f2faf52ccd62f811a92e16842df82769510205 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Fri, 22 Mar 2019 19:11:46 -0700 Subject: [PATCH 10/27] allow norestore switch for regular workflow (#6371) --- eng/Build.ps1 | 5 +++++ eng/build.sh | 3 +++ 2 files changed, 8 insertions(+) diff --git a/eng/Build.ps1 b/eng/Build.ps1 index ffa7b6d788a..04afc1b1d46 100644 --- a/eng/Build.ps1 +++ b/eng/Build.ps1 @@ -22,6 +22,7 @@ param ( # Actions [switch][Alias('r')]$restore, + [switch]$noRestore, [switch][Alias('b')]$build, [switch]$rebuild, [switch]$sign, @@ -104,6 +105,10 @@ function Process-Arguments() { $script:testVs = $True } + if ($noRestore) { + $script:restore = $False; + } + foreach ($property in $properties) { if (!$property.StartsWith("/p:", "InvariantCultureIgnoreCase")) { Write-Host "Invalid argument: $property" diff --git a/eng/build.sh b/eng/build.sh index c2d362c267f..d814dcd04d4 100755 --- a/eng/build.sh +++ b/eng/build.sh @@ -91,6 +91,9 @@ while [[ $# > 0 ]]; do --restore|-r) restore=true ;; + --norestore) + restore=false + ;; --build|-b) build=true ;; From 1c402513d592fdbcf2313ec9677389de6e20bfd4 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Sat, 23 Mar 2019 15:41:35 -0700 Subject: [PATCH 11/27] remove *.en.xlf hack (#6377) --- FSharpBuild.Directory.Build.targets | 4 - scripts/VerifyAllTranslations.fsx | 1 - setup/Directory.Build.props | 1 - setup/Localization.props | 120 - .../FSharp.Build/xlf/FSBuild.txt.en.xlf | 12 - src/fsharp/FSharp.Core/xlf/FSCore.en.xlf | 712 -- src/fsharp/fsi/xlf/FSIstrings.txt.en.xlf | 272 - src/fsharp/xlf/FSComp.txt.en.xlf | 7137 ----------------- .../xlf/FSInteractiveSettings.txt.en.xlf | 6 - src/fsharp/xlf/FSStrings.en.xlf | 1632 ---- .../Template/xlf/AssemblyInfo.fs.en.xlf | 77 - .../Template/xlf/Program.fs.en.xlf | 22 - .../Template/xlf/AssemblyInfo.fs.en.xlf | 77 - .../Template/xlf/Script.fsx.en.xlf | 22 - .../Template/xlf/Tutorial.fsx.en.xlf | 1637 ---- .../FSharp.Editor/xlf/FSharp.Editor.en.xlf | 167 - ...isualStudio.Package.LanguageService.en.xlf | 82 - .../xlf/FSLangSvcStrings.en.xlf | 52 - .../xlf/VSPackage.en.xlf | 72 - ...rosoft.VisualStudio.Package.Project.en.xlf | 820 -- .../xlf/MenusAndCommands.vsct.en.xlf | 252 - .../xlf/VSPackage.en.xlf | 582 -- .../xlf/ApplicationPropPage.en.xlf | 52 - .../xlf/ApplicationPropPageBase.en.xlf | 6 - .../xlf/BuildEventCommandLineDialog.en.xlf | 52 - .../xlf/BuildEventsPropPage.en.xlf | 67 - .../PropertyPages/xlf/BuildPropPage.en.xlf | 137 - .../PropertyPages/xlf/DebugPropPage.en.xlf | 92 - .../xlf/FSharpApplicationPropPage.en.xlf | 6 - .../xlf/PropPageHostDialog.en.xlf | 22 - .../xlf/PropPageUserControlBase.en.xlf | 12 - .../xlf/ReferencePathsPropPage.en.xlf | 52 - ...osoft.VisualStudio.Editors.Designer.en.xlf | 2938 ------- .../Resources/xlf/MyExtensibilityRes.en.xlf | 107 - .../Resources/xlf/WCF.en.xlf | 312 - .../src/FSharp.UIResources/xlf/Strings.en.xlf | 192 - .../src/FSharp.VS.FSI/xlf/Properties.en.xlf | 57 - .../FSharp.VS.FSI/xlf/VFSIstrings.txt.en.xlf | 57 - .../src/FSharp.VS.FSI/xlf/VSPackage.en.xlf | 12 - 39 files changed, 17932 deletions(-) delete mode 100644 setup/Localization.props delete mode 100644 src/fsharp/FSharp.Build/xlf/FSBuild.txt.en.xlf delete mode 100644 src/fsharp/FSharp.Core/xlf/FSCore.en.xlf delete mode 100644 src/fsharp/fsi/xlf/FSIstrings.txt.en.xlf delete mode 100644 src/fsharp/xlf/FSComp.txt.en.xlf delete mode 100644 src/fsharp/xlf/FSInteractiveSettings.txt.en.xlf delete mode 100644 src/fsharp/xlf/FSStrings.en.xlf delete mode 100644 vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/AssemblyInfo.fs.en.xlf delete mode 100644 vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.en.xlf delete mode 100644 vsintegration/ProjectTemplates/LibraryProject/Template/xlf/AssemblyInfo.fs.en.xlf delete mode 100644 vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.en.xlf delete mode 100644 vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.en.xlf delete mode 100644 vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.en.xlf delete mode 100644 vsintegration/src/FSharp.LanguageService.Base/xlf/Microsoft.VisualStudio.Package.LanguageService.en.xlf delete mode 100644 vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.en.xlf delete mode 100644 vsintegration/src/FSharp.LanguageService/xlf/VSPackage.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/MenusAndCommands.vsct.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPage.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPageBase.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildEventCommandLineDialog.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildEventsPropPage.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildPropPage.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/DebugPropPage.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/FSharpApplicationPropPage.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/PropPageHostDialog.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/PropPageUserControlBase.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ReferencePathsPropPage.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/MyExtensibilityRes.en.xlf delete mode 100644 vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.en.xlf delete mode 100644 vsintegration/src/FSharp.UIResources/xlf/Strings.en.xlf delete mode 100644 vsintegration/src/FSharp.VS.FSI/xlf/Properties.en.xlf delete mode 100644 vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.en.xlf delete mode 100644 vsintegration/src/FSharp.VS.FSI/xlf/VSPackage.en.xlf diff --git a/FSharpBuild.Directory.Build.targets b/FSharpBuild.Directory.Build.targets index 4c700d1ac22..c9f98da4493 100644 --- a/FSharpBuild.Directory.Build.targets +++ b/FSharpBuild.Directory.Build.targets @@ -4,10 +4,6 @@ - - en;$(XlfLanguages) - - - - - - - ENU - 1033 - 9 - en - en-US - false - - - CHT - 1028 - 31748 - zh-Hant - zh-TW - true - - - CSY - 1029 - 5 - cs - cs-CZ - true - - - DEU - 1031 - 7 - de - de-DE - true - - - FRA - 1036 - 12 - fr - fr-FR - true - - - ITA - 1040 - 16 - it - it-IT - true - - - JPN - 1041 - 17 - ja - ja-JP - true - - - KOR - 1042 - 18 - ko - ko-KR - true - - - PLK - 1045 - 21 - pl - pl-PL - true - - - PTB - 1046 - 1046 - pt-BR - pt-BR - true - - - RUS - 1049 - 25 - ru - ru-RU - true - - - TRK - 1055 - 31 - tr - tr-TR - true - - - CHS - 2052 - 4 - zh-Hans - zh-CN - true - - - ESN - 3082 - 10 - es - es-ES - true - - - - diff --git a/src/fsharp/FSharp.Build/xlf/FSBuild.txt.en.xlf b/src/fsharp/FSharp.Build/xlf/FSBuild.txt.en.xlf deleted file mode 100644 index 50915d20e20..00000000000 --- a/src/fsharp/FSharp.Build/xlf/FSBuild.txt.en.xlf +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - ToolPath is unknown; specify the path to the tool. - ToolPath is unknown; specify the path to the tool. - - - - - \ No newline at end of file diff --git a/src/fsharp/FSharp.Core/xlf/FSCore.en.xlf b/src/fsharp/FSharp.Core/xlf/FSCore.en.xlf deleted file mode 100644 index 10fca2c29ed..00000000000 --- a/src/fsharp/FSharp.Core/xlf/FSCore.en.xlf +++ /dev/null @@ -1,712 +0,0 @@ - - - - - - The match cases were incomplete - The match cases were incomplete - - - - First class uses of address-of operators are not permitted. - First class uses of address-of operators are not permitted. - - - - The arrays have different lengths. - The arrays have different lengths. - - - - The input array was empty. - The input array was empty. - - - - Input string was not in a correct format. - Input string was not in a correct format. - - - - Expecting delegate type. - Expecting delegate type. - - - - Dynamic invocation of DivideByInt involving coercions is not supported. - Dynamic invocation of DivideByInt involving coercions is not supported. - - - - Dynamic invocation of op_Addition involving coercions is not supported. - Dynamic invocation of op_Addition involving coercions is not supported. - - - - Dynamic invocation of op_Addition involving overloading is not supported. - Dynamic invocation of op_Addition involving overloading is not supported. - - - - Dynamic invocation of op_Multiply involving coercions is not supported. - Dynamic invocation of op_Multiply involving coercions is not supported. - - - - Dynamic invocation of op_Multiply involving overloading is not supported. - Dynamic invocation of op_Multiply involving overloading is not supported. - - - - The end of a range cannot be NaN. - The end of a range cannot be NaN. - - - - Enumeration already finished. - Enumeration already finished. - - - - Enumeration has not started. Call MoveNext. - Enumeration has not started. Call MoveNext. - - - - Set contains no elements. - Set contains no elements. - - - - Enumeration based on System.Int32 exceeded System.Int32.MaxValue. - Enumeration based on System.Int32 exceeded System.Int32.MaxValue. - - - - Failed to read enough bytes from the stream. - Failed to read enough bytes from the stream. - - - - Failure during generic comparison: the type '{0}' does not implement the System.IComparable interface. This error may be arise from the use of a function such as 'compare', 'max' or 'min' or a data structure such as 'Set' or 'Map' whose keys contain instances of this type. - Failure during generic comparison: the type '{0}' does not implement the System.IComparable interface. This error may be arise from the use of a function such as 'compare', 'max' or 'min' or a data structure such as 'Set' or 'Map' whose keys contain instances of this type. - - - - The index was outside the range of elements in the list. - The index was outside the range of elements in the list. - - - - The input list was empty. - The input list was empty. - - - - The input must be non-negative. - The input must be non-negative. - - - - The input must be positive. - The input must be positive. - - - - The input sequence was empty. - The input sequence was empty. - - - - This is not a valid tuple type for the F# reflection library. - This is not a valid tuple type for the F# reflection library. - - - - The item, key, or index was not found in the collection. - The item, key, or index was not found in the collection. - - - - The lists had different lengths. - The lists had different lengths. - - - - The MailboxProcessor has already been started. - The MailboxProcessor has already been started. - - - - MailboxProcessor.PostAndAsyncReply timed out. - MailboxProcessor.PostAndAsyncReply timed out. - - - - MailboxProcessor.PostAndReply timed out. - MailboxProcessor.PostAndReply timed out. - - - - Mailbox.Receive timed out. - Mailbox.Receive timed out. - - - - Mailbox.Scan timed out. - Mailbox.Scan timed out. - - - - Map values cannot be mutated. - Map values cannot be mutated. - - - - The IAsyncResult object provided does not match this 'Cancel' operation. - The IAsyncResult object provided does not match this 'Cancel' operation. - - - - The IAsyncResult object provided does not match this 'End' operation. - The IAsyncResult object provided does not match this 'End' operation. - - - - Negating the minimum value of a twos complement number is invalid. - Negating the minimum value of a twos complement number is invalid. - - - - The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized. - The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized. - - - - The static initialization of a file or type resulted in static data being accessed recursively before it was fully initialized. - The static initialization of a file or type resulted in static data being accessed recursively before it was fully initialized. - - - - Arrays with non-zero base cannot be created on this platform. - Arrays with non-zero base cannot be created on this platform. - - - - Type '{0}' is not a function type. - Type '{0}' is not a function type. - - - - Type '{0}' is not the representation of an F# exception declaration. - Type '{0}' is not the representation of an F# exception declaration. - - - - The function did not compute a permutation. - The function did not compute a permutation. - - - - Type '{0}' is not an F# record type. - Type '{0}' is not an F# record type. - - - - Type '{0}' is not a tuple type. - Type '{0}' is not a tuple type. - - - - Type '{0}' is not an F# union type. - Type '{0}' is not an F# union type. - - - - The two objects have different types and are not comparable. - The two objects have different types and are not comparable. - - - - The input sequence has an insufficient number of elements. - The input sequence has an insufficient number of elements. - - - - This object is for recursive equality calls and cannot be used for hashing. - This object is for recursive equality calls and cannot be used for hashing. - - - - One of the elements in the array is null. - One of the elements in the array is null. - - - - The object is not an F# record value. - The object is not an F# record value. - - - - The object is null and no type was given. Either pass a non-null object or a non-null type parameter. - The object is null and no type was given. Either pass a non-null object or a non-null type parameter. - - - - The index is outside the legal range. - The index is outside the legal range. - - - - The type '{0}' is the representation of an F# exception declaration but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. - The type '{0}' is the representation of an F# exception declaration but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. - - - - The type '{0}' is an F# record type but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. - The type '{0}' is an F# record type but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. - - - - The type '{0}' is an F# union type but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. - The type '{0}' is an F# union type but its representation is private. You must specify BindingFlags.NonPublic to access private type representations. - - - - Expected exactly one type argument. - Expected exactly one type argument. - - - - Expected exactly two type arguments. - Expected exactly two type arguments. - - - - Not a valid F# union case index. - Not a valid F# union case index. - - - - Type '{0}' did not have an F# record field named '{1}'. - Type '{0}' did not have an F# record field named '{1}'. - - - - Type '{0}' did not have an F# union case named '{1}'. - Type '{0}' did not have an F# union case named '{1}'. - - - - Type mismatch when building '{0}': the type of the field was incorrect. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': the type of the field was incorrect. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': body must return unit. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': body must return unit. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': condition expression must be of type bool. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': condition expression must be of type bool. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': expected function type in function application or let binding. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': expected function type in function application or let binding. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': expression doesn't match the tuple type. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': expression doesn't match the tuple type. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': types of expression does not match. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': types of expression does not match. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': function argument type doesn't match. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': function argument type doesn't match. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': guard must return boolean. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': guard must return boolean. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': incorrect argument type for an F# record. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': incorrect argument type for an F# record. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': incorrect argument type for an F# union. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': incorrect argument type for an F# union. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': initializer doesn't match array type. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': initializer doesn't match array type. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': invalid parameter for a method or indexer property. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': invalid parameter for a method or indexer property. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': body of the for loop must be lambda taking integer as an argument. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': body of the for loop must be lambda taking integer as an argument. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': lower and upper bounds must be integers. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': lower and upper bounds must be integers. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': types of true and false branches differ. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': types of true and false branches differ. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': mismatched type of argument and tuple element. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': mismatched type of argument and tuple element. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': the variable type doesn't match the type of the right-hand-side of a let binding. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': the variable type doesn't match the type of the right-hand-side of a let binding. Expected '{1}', but received type '{2}'. - - - - Unexpected quotation hole in expression. - Unexpected quotation hole in expression. - - - - The parameter is not a recognized method name. - The parameter is not a recognized method name. - - - - Reset is not supported on this enumerator. - Reset is not supported on this enumerator. - - - - The start of a range cannot be NaN. - The start of a range cannot be NaN. - - - - The step of a range cannot be NaN. - The step of a range cannot be NaN. - - - - The step of a range cannot be zero. - The step of a range cannot be zero. - - - - The System.Threading.SynchronizationContext.Current of the calling thread is null. - The System.Threading.SynchronizationContext.Current of the calling thread is null. - - - - The tuple index '{1}' was out of range for tuple type '{0}'. - The tuple index '{1}' was out of range for tuple type '{0}'. - - - - Failed to bind constructor - Failed to bind constructor - - - - Failed to bind field '{0}' - Failed to bind field '{0}' - - - - Failed to bind property '{0}' - Failed to bind property '{0}' - - - - Failed to bind type '{0}' in assembly '{1}' - Failed to bind type '{0}' in assembly '{1}' - - - - Incompatible record length - Incompatible record length - - - - Incorrect instance type - Incorrect instance type - - - - Incorrect number of arguments - Incorrect number of arguments - - - - Incorrect type - Incorrect type - - - - Invalid function type - Invalid function type - - - - The member is non-static (instance), but no receiver object was supplied - The member is non-static (instance), but no receiver object was supplied - - - - Parent type cannot be null - Parent type cannot be null - - - - Reading a set-only property - Reading a set-only property - - - - Receiver object was unexpected, as member is static - Receiver object was unexpected, as member is static - - - - Type mismatch when building '{0}': the expression has the wrong type. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': the expression has the wrong type. Expected '{1}', but received type '{2}'. - - - - Type mismatch when building '{0}': function type doesn't match delegate type. Expected '{1}', but received type '{2}'. - Type mismatch when building '{0}': function type doesn't match delegate type. Expected '{1}', but received type '{2}'. - - - - Type mismatch when splicing expression into quotation literal. The type of the expression tree being inserted doesn't match the type expected by the splicing operation. Expected '{0}', but received type '{1}'. Consider type-annotating with the expected expression type, e.g., (%% x : {0}) or (%x : {0}). - Type mismatch when splicing expression into quotation literal. The type of the expression tree being inserted doesn't match the type expected by the splicing operation. Expected '{0}', but received type '{1}'. Consider type-annotating with the expected expression type, e.g., (%% x : {0}) or (%x : {0}). - - - - Tuple access out of range - Tuple access out of range - - - - The tuple lengths are different - The tuple lengths are different - - - - F# union type requires different number of arguments - F# union type requires different number of arguments - - - - Writing a get-only property - Writing a get-only property - - - - The method '{0}' expects {1} type arguments but {2} were provided - The method '{0}' expects {1} type arguments but {2} were provided - - - - An index satisfying the predicate was not found in the collection. - An index satisfying the predicate was not found in the collection. - - - - The constructor method '{0}' for the union case could not be found - The constructor method '{0}' for the union case could not be found - - - - first class uses of '%' or '%%' are not permitted - first class uses of '%' or '%%' are not permitted - - - - MoveNext not called, or finished - MoveNext not called, or finished - - - - Multiple CompilationMappingAttributes, expected at most one - Multiple CompilationMappingAttributes, expected at most one - - - - Bad float value - Bad float value - - - - Bad format specifier:{0} - Bad format specifier:{0} - - - - Bad integer supplied to dynamic formatter - Bad integer supplied to dynamic formatter - - - - Expected a precision argument - Expected a precision argument - - - - Expected a width argument - Expected a width argument - - - - The # formatting modifier is invalid in F# - The # formatting modifier is invalid in F# - - - - Missing format specifier - Missing format specifier - - - - Not a function type - Not a function type - - - - Bad format specifier (precision) - Bad format specifier (precision) - - - - Bad format specifier (after {0}) - Bad format specifier (after {0}) - - - - Bad format specifier (width) - Bad format specifier (width) - - - - Could not bind function {0} in type {1} - Could not bind function {0} in type {1} - - - - Could not bind property {0} in type {1} - Could not bind property {0} in type {1} - - - - Could not bind to method - Could not bind to method - - - - Cannot take the address of this quotation - Cannot take the address of this quotation - - - - Failed to bind assembly '{0}' while processing quotation data - Failed to bind assembly '{0}' while processing quotation data - - - - ill formed expression: AppOp or LetOp - ill formed expression: AppOp or LetOp - - - - type argument out of range - type argument out of range - - - - This value cannot be mutated - This value cannot be mutated - - - - The option value was None - The option value was None - - - - A continuation provided by Async.FromContinuations was invoked multiple times - A continuation provided by Async.FromContinuations was invoked multiple times - - - - The record type '{0}' is invalid. Required constructor is not defined. - The record type '{0}' is invalid. Required constructor is not defined. - - - - The tuple type '{0}' is invalid. Required constructor is not defined. - The tuple type '{0}' is invalid. Required constructor is not defined. - - - - The input sequence contains more than one element. - The input sequence contains more than one element. - - - - 'thenBy' and 'thenByDescending' may only be used with an ordered input - 'thenBy' and 'thenByDescending' may only be used with an ordered input - - - - Unrecognized use of a 'sumBy' or 'averageBy' operator in a query. In queries whose original data is of static type IQueryable, these operators may only be used with result type int32, int64, single, double or decimal - Unrecognized use of a 'sumBy' or 'averageBy' operator in a query. In queries whose original data is of static type IQueryable, these operators may only be used with result type int32, int64, single, double or decimal - - - - An if/then/else conditional or pattern matching expression with multiple branches is not permitted in a query. An if/then/else conditional may be used. - An if/then/else conditional or pattern matching expression with multiple branches is not permitted in a query. An if/then/else conditional may be used. - - - - This is not a valid query expression. The following construct was used in a query but is not recognized by the F#-to-LINQ query translator:\n{0}\nCheck the specification of permitted queries and consider moving some of the operations out of the query expression. - This is not a valid query expression. The following construct was used in a query but is not recognized by the F#-to-LINQ query translator:\n{0}\nCheck the specification of permitted queries and consider moving some of the operations out of the query expression. - - - - This is not a valid query expression. The method '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression - This is not a valid query expression. The method '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression - - - - This is not a valid query expression. The property '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression. - This is not a valid query expression. The property '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression. - - - - This is not a valid query expression. The construct '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression. - This is not a valid query expression. The construct '{0}' was used in a query but is not recognized by the F#-to-LINQ query translator. Check the specification of permitted queries and consider moving some of the operations out of the query expression. - - - - - \ No newline at end of file diff --git a/src/fsharp/fsi/xlf/FSIstrings.txt.en.xlf b/src/fsharp/fsi/xlf/FSIstrings.txt.en.xlf deleted file mode 100644 index b34138d7721..00000000000 --- a/src/fsharp/fsi/xlf/FSIstrings.txt.en.xlf +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - Stopped due to error\n - Stopped due to error\n - - - - Usage: {0} <options> [script.fsx [<arguments>]] - Usage: {0} <options> [script.fsx [<arguments>]] - - - - - INPUT FILES - - - INPUT FILES - - - - - - CODE GENERATION - - - CODE GENERATION - - - - - - ERRORS AND WARNINGS - - - ERRORS AND WARNINGS - - - - - - LANGUAGE - - - LANGUAGE - - - - - - MISCELLANEOUS - - - MISCELLANEOUS - - - - - - ADVANCED - - - ADVANCED - - - - - Exception raised when starting remoting server.\n{0} - Exception raised when starting remoting server.\n{0} - - - - Use the given file on startup as initial input - Use the given file on startup as initial input - - - - #load the given file on startup - #load the given file on startup - - - - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - Treat remaining arguments as command line arguments, accessed using fsi.CommandLineArgs - - - - Display this usage message (Short form: -?) - Display this usage message (Short form: -?) - - - - Exit fsi after loading the files or running the .fsx script given on the command line - Exit fsi after loading the files or running the .fsx script given on the command line - - - - Execute interactions on a Windows Forms event loop (on by default) - Execute interactions on a Windows Forms event loop (on by default) - - - - Suppress fsi writing to stdout - Suppress fsi writing to stdout - - - - Support TAB completion in console (on by default) - Support TAB completion in console (on by default) - - - - Emit debug information in quotations - Emit debug information in quotations - - - - For help type #help;; - For help type #help;; - - - - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - A problem occurred starting the F# Interactive process. This may be due to a known problem with background process console support for Unicode-enabled applications on some Windows systems. Try selecting Tools->Options->F# Interactive for Visual Studio and enter '--fsi-server-no-unicode'. - - - - '{0}' is not a valid assembly name - '{0}' is not a valid assembly name - - - - Directory '{0}' doesn't exist - Directory '{0}' doesn't exist - - - - Invalid directive '#{0} {1}' - Invalid directive '#{0} {1}' - - - - Warning: line too long, ignoring some characters\n - Warning: line too long, ignoring some characters\n - - - - Real: {0}, CPU: {1}, GC {2} - Real: {0}, CPU: {1}, GC {2} - - - - gen - gen - - - - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - \n\nException raised during pretty printing.\nPlease report this so it can be fixed.\nTrace: {0}\n - - - - F# Interactive directives: - F# Interactive directives: - - - - Reference (dynamically load) the given DLL - Reference (dynamically load) the given DLL - - - - Add the given search path for referenced DLLs - Add the given search path for referenced DLLs - - - - Load the given file(s) as if compiled and referenced - Load the given file(s) as if compiled and referenced - - - - Toggle timing on/off - Toggle timing on/off - - - - Display help - Display help - - - - Exit - Exit - - - - F# Interactive command line options: - F# Interactive command line options: - - - - See '{0}' for options - See '{0}' for options - - - - Loading - Loading - - - - \n- Interrupt\n - \n- Interrupt\n - - - - \n- Exit...\n - \n- Exit...\n - - - - - Aborting main thread... - - Aborting main thread... - - - - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - Failed to install ctrl-c handler - Ctrl-C handling will not be available. Error was:\n\t{0} - - - - --> Referenced '{0}' - --> Referenced '{0}' - - - - --> Referenced '{0}' (file may be locked by F# Interactive process) - --> Referenced '{0}' (file may be locked by F# Interactive process) - - - - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - --> Referenced '{0}' (an assembly with a different timestamp has already been referenced from this location, reset fsi to load the updated assembly) - - - - --> Added '{0}' to library include path - --> Added '{0}' to library include path - - - - --> Timing now on - --> Timing now on - - - - --> Timing now off - --> Timing now off - - - - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - Unexpected ThreadAbortException (Ctrl-C) during event handling: Trying to restart... - - - - Failed to resolve assembly '{0}' - Failed to resolve assembly '{0}' - - - - Binding session to '{0}'... - Binding session to '{0}'... - - - - Microsoft (R) F# Interactive version {0} - Microsoft (R) F# Interactive version {0} - - - - F# Interactive for F# {0} - F# Interactive for F# {0} - - - - Prevents references from being locked by the F# Interactive process - Prevents references from being locked by the F# Interactive process - - - - - \ No newline at end of file diff --git a/src/fsharp/xlf/FSComp.txt.en.xlf b/src/fsharp/xlf/FSComp.txt.en.xlf deleted file mode 100644 index 4749ca38042..00000000000 --- a/src/fsharp/xlf/FSComp.txt.en.xlf +++ /dev/null @@ -1,7137 +0,0 @@ - - - - - - The namespace '{0}' is not defined. - The namespace '{0}' is not defined. - - - - The namespace or module '{0}' is not defined. - The namespace or module '{0}' is not defined. - - - - The field, constructor or member '{0}' is not defined. - The field, constructor or member '{0}' is not defined. - - - - The value, constructor, namespace or type '{0}' is not defined. - The value, constructor, namespace or type '{0}' is not defined. - - - - The value or constructor '{0}' is not defined. - The value or constructor '{0}' is not defined. - - - - The value, namespace, type or module '{0}' is not defined. - The value, namespace, type or module '{0}' is not defined. - - - - The constructor, module or namespace '{0}' is not defined. - The constructor, module or namespace '{0}' is not defined. - - - - The type '{0}' is not defined. - The type '{0}' is not defined. - - - - The type '{0}' is not defined in '{1}'. - The type '{0}' is not defined in '{1}'. - - - - The record label or namespace '{0}' is not defined. - The record label or namespace '{0}' is not defined. - - - - The record label '{0}' is not defined. - The record label '{0}' is not defined. - - - - Maybe you want one of the following: - Maybe you want one of the following: - - - - The type parameter {0} is not defined. - The type parameter {0} is not defined. - - - - The pattern discriminator '{0}' is not defined. - The pattern discriminator '{0}' is not defined. - - - - Replace with '{0}' - Replace with '{0}' - - - - Add . for indexer access. - Add . for indexer access. - - - - All elements of a list must be of the same type as the first element, which here is '{0}'. This element has type '{1}'. - All elements of a list must be of the same type as the first element, which here is '{0}'. This element has type '{1}'. - - - - All elements of an array must be of the same type as the first element, which here is '{0}'. This element has type '{1}'. - All elements of an array must be of the same type as the first element, which here is '{0}'. This element has type '{1}'. - - - - This 'if' expression is missing an 'else' branch. Because 'if' is an expression, and not a statement, add an 'else' branch which also returns a value of type '{0}'. - This 'if' expression is missing an 'else' branch. Because 'if' is an expression, and not a statement, add an 'else' branch which also returns a value of type '{0}'. - - - - The 'if' expression needs to have type '{0}' to satisfy context type requirements. It currently has type '{1}'. - The 'if' expression needs to have type '{0}' to satisfy context type requirements. It currently has type '{1}'. - - - - All branches of an 'if' expression must return values of the same type as the first branch, which here is '{0}'. This branch returns a value of type '{1}'. - All branches of an 'if' expression must return values of the same type as the first branch, which here is '{0}'. This branch returns a value of type '{1}'. - - - - All branches of a pattern match expression must return values of the same type as the first branch, which here is '{0}'. This branch returns a value of type '{1}'. - All branches of a pattern match expression must return values of the same type as the first branch, which here is '{0}'. This branch returns a value of type '{1}'. - - - - A pattern match guard must be of type 'bool', but this 'when' expression is of type '{0}'. - A pattern match guard must be of type 'bool', but this 'when' expression is of type '{0}'. - - - - A ';' is used to separate field values in records. Consider replacing ',' with ';'. - A ';' is used to separate field values in records. Consider replacing ',' with ';'. - - - - The '!' operator is used to dereference a ref cell. Consider using 'not expr' here. - The '!' operator is used to dereference a ref cell. Consider using 'not expr' here. - - - - The non-generic type '{0}' does not expect any type arguments, but here is given {1} type argument(s) - The non-generic type '{0}' does not expect any type arguments, but here is given {1} type argument(s) - - - - Consider using 'return!' instead of 'return'. - Consider using 'return!' instead of 'return'. - - - - Consider using 'yield!' instead of 'yield'. - Consider using 'yield!' instead of 'yield'. - - - - \nA tuple type is required for one or more arguments. Consider wrapping the given arguments in additional parentheses or review the definition of the interface. - \nA tuple type is required for one or more arguments. Consider wrapping the given arguments in additional parentheses or review the definition of the interface. - - - - Invalid warning number '{0}' - Invalid warning number '{0}' - - - - Invalid version string '{0}' - Invalid version string '{0}' - - - - Invalid version file '{0}' - Invalid version file '{0}' - - - - Microsoft (R) F# Compiler version {0} - Microsoft (R) F# Compiler version {0} - - - - F# Compiler for F# {0} - F# Compiler for F# {0} - - - - Problem with filename '{0}': {1} - Problem with filename '{0}': {1} - - - - No inputs specified - No inputs specified - - - - The '--pdb' option requires the '--debug' option to be used - The '--pdb' option requires the '--debug' option to be used - - - - The search directory '{0}' is invalid - The search directory '{0}' is invalid - - - - The search directory '{0}' could not be found - The search directory '{0}' could not be found - - - - '{0}' is not a valid filename - '{0}' is not a valid filename - - - - '{0}' is not a valid assembly name - '{0}' is not a valid assembly name - - - - Unrecognized privacy setting '{0}' for managed resource, valid options are 'public' and 'private' - Unrecognized privacy setting '{0}' for managed resource, valid options are 'public' and 'private' - - - - Multiple references to '{0}.dll' are not permitted - Multiple references to '{0}.dll' are not permitted - - - - Unable to read assembly '{0}' - Unable to read assembly '{0}' - - - - Assembly resolution failure at or near this location - Assembly resolution failure at or near this location - - - - The declarations in this file will be placed in an implicit module '{0}' based on the file name '{1}'. However this is not a valid F# identifier, so the contents will not be accessible from other files. Consider renaming the file or adding a 'module' or 'namespace' declaration at the top of the file. - The declarations in this file will be placed in an implicit module '{0}' based on the file name '{1}'. However this is not a valid F# identifier, so the contents will not be accessible from other files. Consider renaming the file or adding a 'module' or 'namespace' declaration at the top of the file. - - - - Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule'. Only the last source file of an application may omit such a declaration. - Files in libraries or multiple-file applications must begin with a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule'. Only the last source file of an application may omit such a declaration. - - - - Files in libraries or multiple-file applications must begin with a namespace or module declaration. When using a module declaration at the start of a file the '=' sign is not allowed. If this is a top-level module, consider removing the = to resolve this error. - Files in libraries or multiple-file applications must begin with a namespace or module declaration. When using a module declaration at the start of a file the '=' sign is not allowed. If this is a top-level module, consider removing the = to resolve this error. - - - - This file contains multiple declarations of the form 'module SomeNamespace.SomeModule'. Only one declaration of this form is permitted in a file. Change your file to use an initial namespace declaration and/or use 'module ModuleName = ...' to define your modules. - This file contains multiple declarations of the form 'module SomeNamespace.SomeModule'. Only one declaration of this form is permitted in a file. Change your file to use an initial namespace declaration and/or use 'module ModuleName = ...' to define your modules. - - - - Option requires parameter: {0} - Option requires parameter: {0} - - - - Source file '{0}' could not be found - Source file '{0}' could not be found - - - - The file extension of '{0}' is not recognized. Source files must have extension .fs, .fsi, .fsx, .fsscript, .ml or .mli. - The file extension of '{0}' is not recognized. Source files must have extension .fs, .fsi, .fsx, .fsscript, .ml or .mli. - - - - Could not resolve assembly '{0}' - Could not resolve assembly '{0}' - - - - Could not resolve assembly '{0}' required by '{1}' - Could not resolve assembly '{0}' required by '{1}' - - - - Error opening binary file '{0}': {1} - Error opening binary file '{0}': {1} - - - - The F#-compiled DLL '{0}' needs to be recompiled to be used with this version of F# - The F#-compiled DLL '{0}' needs to be recompiled to be used with this version of F# - - - - Invalid directive. Expected '#I \"<path>\"'. - Invalid directive. Expected '#I \"<path>\"'. - - - - Invalid directive. Expected '#r \"<file-or-assembly>\"'. - Invalid directive. Expected '#r \"<file-or-assembly>\"'. - - - - Invalid directive. Expected '#load \"<file>\" ... \"<file>\"'. - Invalid directive. Expected '#load \"<file>\" ... \"<file>\"'. - - - - Invalid directive. Expected '#time', '#time \"on\"' or '#time \"off\"'. - Invalid directive. Expected '#time', '#time \"on\"' or '#time \"off\"'. - - - - Directives inside modules are ignored - Directives inside modules are ignored - - - - A signature for the file or module '{0}' has already been specified - A signature for the file or module '{0}' has already been specified - - - - An implementation of file or module '{0}' has already been given. Compilation order is significant in F# because of type inference. You may need to adjust the order of your files to place the signature file before the implementation. In Visual Studio files are type-checked in the order they appear in the project file, which can be edited manually or adjusted using the solution explorer. - An implementation of file or module '{0}' has already been given. Compilation order is significant in F# because of type inference. You may need to adjust the order of your files to place the signature file before the implementation. In Visual Studio files are type-checked in the order they appear in the project file, which can be edited manually or adjusted using the solution explorer. - - - - An implementation of the file or module '{0}' has already been given - An implementation of the file or module '{0}' has already been given - - - - The signature file '{0}' does not have a corresponding implementation file. If an implementation file exists then check the 'module' and 'namespace' declarations in the signature and implementation files match. - The signature file '{0}' does not have a corresponding implementation file. If an implementation file exists then check the 'module' and 'namespace' declarations in the signature and implementation files match. - - - - '{0}' is not a valid integer argument - '{0}' is not a valid integer argument - - - - '{0}' is not a valid floating point argument - '{0}' is not a valid floating point argument - - - - Unrecognized option: '{0}' - Unrecognized option: '{0}' - - - - Invalid module or namespace name - Invalid module or namespace name - - - - Error reading/writing metadata for the F# compiled DLL '{0}'. Was the DLL compiled with an earlier version of the F# compiler? (error: '{1}'). - Error reading/writing metadata for the F# compiled DLL '{0}'. Was the DLL compiled with an earlier version of the F# compiler? (error: '{1}'). - - - - The type/module '{0}' is not a concrete module or type - The type/module '{0}' is not a concrete module or type - - - - The type '{0}' has an inline assembly code representation - The type '{0}' has an inline assembly code representation - - - - A namespace and a module named '{0}' both occur in two parts of this assembly - A namespace and a module named '{0}' both occur in two parts of this assembly - - - - Two modules named '{0}' occur in two parts of this assembly - Two modules named '{0}' occur in two parts of this assembly - - - - Two type definitions named '{0}' occur in namespace '{1}' in two parts of this assembly - Two type definitions named '{0}' occur in namespace '{1}' in two parts of this assembly - - - - A module and a type definition named '{0}' occur in namespace '{1}' in two parts of this assembly - A module and a type definition named '{0}' occur in namespace '{1}' in two parts of this assembly - - - - Invalid member signature encountered because of an earlier error - Invalid member signature encountered because of an earlier error - - - - This value does not have a valid property setter type - This value does not have a valid property setter type - - - - Invalid form for a property getter. At least one '()' argument is required when using the explicit syntax. - Invalid form for a property getter. At least one '()' argument is required when using the explicit syntax. - - - - Invalid form for a property setter. At least one argument is required. - Invalid form for a property setter. At least one argument is required. - - - - Unexpected use of a byref-typed variable - Unexpected use of a byref-typed variable - - - - Invalid mutation of a constant expression. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...'. - Invalid mutation of a constant expression. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...'. - - - - The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed - The value has been copied to ensure the original is not mutated by this operation or because the copy is implicit when returning a struct from a member and another member is then accessed - - - - Recursively defined values cannot appear directly as part of the construction of a tuple value within a recursive binding - Recursively defined values cannot appear directly as part of the construction of a tuple value within a recursive binding - - - - Recursive values cannot appear directly as a construction of the type '{0}' within a recursive binding. This feature has been removed from the F# language. Consider using a record instead. - Recursive values cannot appear directly as a construction of the type '{0}' within a recursive binding. This feature has been removed from the F# language. Consider using a record instead. - - - - Recursive values cannot be directly assigned to the non-mutable field '{0}' of the type '{1}' within a recursive binding. Consider using a mutable field instead. - Recursive values cannot be directly assigned to the non-mutable field '{0}' of the type '{1}' within a recursive binding. Consider using a mutable field instead. - - - - Unexpected decode of AutoOpenAttribute - Unexpected decode of AutoOpenAttribute - - - - Unexpected decode of InternalsVisibleToAttribute - Unexpected decode of InternalsVisibleToAttribute - - - - Unexpected decode of InterfaceDataVersionAttribute - Unexpected decode of InterfaceDataVersionAttribute - - - - Active patterns cannot return more than 7 possibilities - Active patterns cannot return more than 7 possibilities - - - - This is not a valid constant expression or custom attribute value - This is not a valid constant expression or custom attribute value - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe mutability attributes differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe mutability attributes differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe names differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe names differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe compiled names differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe compiled names differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe display names differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe display names differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe accessibility specified in the signature is more than that specified in the implementation - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe accessibility specified in the signature is more than that specified in the implementation - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe inline flags differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe inline flags differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe literal constant values and/or attributes differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe literal constant values and/or attributes differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is a type function and the other is not. The signature requires explicit type parameters if they are present in the implementation. - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is a type function and the other is not. The signature requires explicit type parameters if they are present in the implementation. - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe respective type parameter counts differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe respective type parameter counts differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe types differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe types differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is an extension member and the other is not - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is an extension member and the other is not - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nAn arity was not inferred for this value - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nAn arity was not inferred for this value - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe number of generic parameters in the signature and implementation differ (the signature declares {3} but the implementation declares {4} - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe number of generic parameters in the signature and implementation differ (the signature declares {3} but the implementation declares {4} - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe generic parameters in the signature and implementation have different kinds. Perhaps there is a missing [<Measure>] attribute. - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe generic parameters in the signature and implementation have different kinds. Perhaps there is a missing [<Measure>] attribute. - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe arities in the signature and implementation differ. The signature specifies that '{3}' is function definition or lambda expression accepting at least {4} argument(s), but the implementation is a computed function value. To declare that a computed function value is a permitted implementation simply parenthesize its type in the signature, e.g.\n\tval {5}: int -> (int -> int)\ninstead of\n\tval {6}: int -> int -> int. - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe arities in the signature and implementation differ. The signature specifies that '{3}' is function definition or lambda expression accepting at least {4} argument(s), but the implementation is a computed function value. To declare that a computed function value is a permitted implementation simply parenthesize its type in the signature, e.g.\n\tval {5}: int -> (int -> int)\ninstead of\n\tval {6}: int -> int -> int. - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe CLI member names differ - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe CLI member names differ - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is static and the other isn't - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is static and the other isn't - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is virtual and the other isn't - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is virtual and the other isn't - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is abstract and the other isn't - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is abstract and the other isn't - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is final and the other isn't - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is final and the other isn't - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is marked as an override and the other isn't - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is marked as an override and the other isn't - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is a constructor/property and the other is not - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nOne is a constructor/property and the other is not - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe compiled representation of this method is as a static member but the signature indicates its compiled representation is as an instance member - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe compiled representation of this method is as a static member but the signature indicates its compiled representation is as an instance member - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe compiled representation of this method is as an instance member, but the signature indicates its compiled representation is as a static member - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \nThe compiled representation of this method is as an instance member, but the signature indicates its compiled representation is as a static member - - - - The {0} definitions in the signature and implementation are not compatible because the names differ. The type is called '{1}' in the signature file but '{2}' in implementation. - The {0} definitions in the signature and implementation are not compatible because the names differ. The type is called '{1}' in the signature file but '{2}' in implementation. - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the respective type parameter counts differ - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the respective type parameter counts differ - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the accessibility specified in the signature is more than that specified in the implementation - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the accessibility specified in the signature is more than that specified in the implementation - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature requires that the type supports the interface {2} but the interface has not been implemented - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature requires that the type supports the interface {2} but the interface has not been implemented - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation says this type may use nulls as a representation but the signature does not - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation says this type may use nulls as a representation but the signature does not - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation says this type may use nulls as an extra value but the signature does not - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation says this type may use nulls as an extra value but the signature does not - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature says this type may use nulls as a representation but the implementation does not - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature says this type may use nulls as a representation but the implementation does not - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature says this type may use nulls as an extra value but the implementation does not - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature says this type may use nulls as an extra value but the implementation does not - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation type is sealed but the signature implies it is not. Consider adding the [<Sealed>] attribute to the signature. - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation type is sealed but the signature implies it is not. Consider adding the [<Sealed>] attribute to the signature. - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation type is not sealed but signature implies it is. Consider adding the [<Sealed>] attribute to the implementation. - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation type is not sealed but signature implies it is. Consider adding the [<Sealed>] attribute to the implementation. - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation is an abstract class but the signature is not. Consider adding the [<AbstractClass>] attribute to the signature. - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation is an abstract class but the signature is not. Consider adding the [<AbstractClass>] attribute to the signature. - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature is an abstract class but the implementation is not. Consider adding the [<AbstractClass>] attribute to the implementation. - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature is an abstract class but the implementation is not. Consider adding the [<AbstractClass>] attribute to the implementation. - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the types have different base types - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the types have different base types - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the number of {2}s differ - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the number of {2}s differ - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature defines the {2} '{3}' but the implementation does not (or does, but not in the same order) - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature defines the {2} '{3}' but the implementation does not (or does, but not in the same order) - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation defines the {2} '{3}' but the signature does not (or does, but not in the same order) - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation defines the {2} '{3}' but the signature does not (or does, but not in the same order) - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation defines a struct but the signature defines a type with a hidden representation - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the implementation defines a struct but the signature defines a type with a hidden representation - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because a CLI type representation is being hidden by a signature - The {0} definitions for type '{1}' in the signature and implementation are not compatible because a CLI type representation is being hidden by a signature - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because a type representation is being hidden by a signature - The {0} definitions for type '{1}' in the signature and implementation are not compatible because a type representation is being hidden by a signature - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the types are of different kinds - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the types are of different kinds - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the IL representations differ - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the IL representations differ - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the representations differ - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the representations differ - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the field {2} was present in the implementation but not in the signature - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the field {2} was present in the implementation but not in the signature - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the order of the fields is different in the signature and implementation - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the order of the fields is different in the signature and implementation - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the field {2} was required by the signature but was not specified by the implementation - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the field {2} was required by the signature but was not specified by the implementation - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the field '{2}' was present in the implementation but not in the signature. Struct types must now reveal their fields in the signature for the type, though the fields may still be labelled 'private' or 'internal'. - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the field '{2}' was present in the implementation but not in the signature. Struct types must now reveal their fields in the signature for the type, though the fields may still be labelled 'private' or 'internal'. - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the abstract member '{2}' was required by the signature but was not specified by the implementation - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the abstract member '{2}' was required by the signature but was not specified by the implementation - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the abstract member '{2}' was present in the implementation but not in the signature - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the abstract member '{2}' was present in the implementation but not in the signature - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature declares a {2} while the implementation declares a {3} - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature declares a {2} while the implementation declares a {3} - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the abbreviations differ: {2} versus {3} - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the abbreviations differ: {2} versus {3} - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because an abbreviation is being hidden by a signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. - The {0} definitions for type '{1}' in the signature and implementation are not compatible because an abbreviation is being hidden by a signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. - - - - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature has an abbreviation while the implementation does not - The {0} definitions for type '{1}' in the signature and implementation are not compatible because the signature has an abbreviation while the implementation does not - - - - The module contains the constructor\n {0} \nbut its signature specifies\n {1} \nThe names differ - The module contains the constructor\n {0} \nbut its signature specifies\n {1} \nThe names differ - - - - The module contains the constructor\n {0} \nbut its signature specifies\n {1} \nThe respective number of data fields differ - The module contains the constructor\n {0} \nbut its signature specifies\n {1} \nThe respective number of data fields differ - - - - The module contains the constructor\n {0} \nbut its signature specifies\n {1} \nThe types of the fields differ - The module contains the constructor\n {0} \nbut its signature specifies\n {1} \nThe types of the fields differ - - - - The module contains the constructor\n {0} \nbut its signature specifies\n {1} \nthe accessibility specified in the signature is more than that specified in the implementation - The module contains the constructor\n {0} \nbut its signature specifies\n {1} \nthe accessibility specified in the signature is more than that specified in the implementation - - - - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe names differ - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe names differ - - - - The module contains the field\n {0} \nbut its signature specifies\n {1} \nthe accessibility specified in the signature is more than that specified in the implementation - The module contains the field\n {0} \nbut its signature specifies\n {1} \nthe accessibility specified in the signature is more than that specified in the implementation - - - - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe 'static' modifiers differ - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe 'static' modifiers differ - - - - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe 'mutable' modifiers differ - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe 'mutable' modifiers differ - - - - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe 'literal' modifiers differ - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe 'literal' modifiers differ - - - - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe types differ - The module contains the field\n {0} \nbut its signature specifies\n {1} \nThe types differ - - - - The implicit instantiation of a generic construct at or near this point could not be resolved because it could resolve to multiple unrelated types, e.g. '{0}' and '{1}'. Consider using type annotations to resolve the ambiguity - The implicit instantiation of a generic construct at or near this point could not be resolved because it could resolve to multiple unrelated types, e.g. '{0}' and '{1}'. Consider using type annotations to resolve the ambiguity - - - - Could not resolve the ambiguity inherent in the use of a 'printf'-style format string - Could not resolve the ambiguity inherent in the use of a 'printf'-style format string - - - - Could not resolve the ambiguity in the use of a generic construct with an 'enum' constraint at or near this position - Could not resolve the ambiguity in the use of a generic construct with an 'enum' constraint at or near this position - - - - Could not resolve the ambiguity in the use of a generic construct with a 'delegate' constraint at or near this position - Could not resolve the ambiguity in the use of a generic construct with a 'delegate' constraint at or near this position - - - - Invalid value - Invalid value - - - - The signature and implementation are not compatible because the respective type parameter counts differ - The signature and implementation are not compatible because the respective type parameter counts differ - - - - The signature and implementation are not compatible because the type parameter in the class/signature has a different compile-time requirement to the one in the member/implementation - The signature and implementation are not compatible because the type parameter in the class/signature has a different compile-time requirement to the one in the member/implementation - - - - The signature and implementation are not compatible because the declaration of the type parameter '{0}' requires a constraint of the form {1} - The signature and implementation are not compatible because the declaration of the type parameter '{0}' requires a constraint of the form {1} - - - - The signature and implementation are not compatible because the type parameter '{0}' has a constraint of the form {1} but the implementation does not. Either remove this constraint from the signature or add it to the implementation. - The signature and implementation are not compatible because the type parameter '{0}' has a constraint of the form {1} but the implementation does not. Either remove this constraint from the signature or add it to the implementation. - - - - The type '{0}' implements 'System.IComparable'. Consider also adding an explicit override for 'Object.Equals' - The type '{0}' implements 'System.IComparable'. Consider also adding an explicit override for 'Object.Equals' - - - - The type '{0}' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'. An implementation of 'Object.Equals' has been automatically provided, implemented via 'System.IComparable'. Consider implementing the override 'Object.Equals' explicitly - The type '{0}' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'. An implementation of 'Object.Equals' has been automatically provided, implemented via 'System.IComparable'. Consider implementing the override 'Object.Equals' explicitly - - - - The struct, record or union type '{0}' has an explicit implementation of 'Object.GetHashCode' or 'Object.Equals'. You must apply the 'CustomEquality' attribute to the type - The struct, record or union type '{0}' has an explicit implementation of 'Object.GetHashCode' or 'Object.Equals'. You must apply the 'CustomEquality' attribute to the type - - - - The struct, record or union type '{0}' has an explicit implementation of 'Object.GetHashCode'. Consider implementing a matching override for 'Object.Equals(obj)' - The struct, record or union type '{0}' has an explicit implementation of 'Object.GetHashCode'. Consider implementing a matching override for 'Object.Equals(obj)' - - - - The struct, record or union type '{0}' has an explicit implementation of 'Object.Equals'. Consider implementing a matching override for 'Object.GetHashCode()' - The struct, record or union type '{0}' has an explicit implementation of 'Object.Equals'. Consider implementing a matching override for 'Object.GetHashCode()' - - - - The exception definitions are not compatible because a CLI exception mapping is being hidden by a signature. The exception mapping must be visible to other modules. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1} - The exception definitions are not compatible because a CLI exception mapping is being hidden by a signature. The exception mapping must be visible to other modules. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1} - - - - The exception definitions are not compatible because the CLI representations differ. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1} - The exception definitions are not compatible because the CLI representations differ. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1} - - - - The exception definitions are not compatible because the exception abbreviation is being hidden by the signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1}. - The exception definitions are not compatible because the exception abbreviation is being hidden by the signature. The abbreviation must be visible to other CLI languages. Consider making the abbreviation visible in the signature. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1}. - - - - The exception definitions are not compatible because the exception abbreviations in the signature and implementation differ. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1}. - The exception definitions are not compatible because the exception abbreviations in the signature and implementation differ. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1}. - - - - The exception definitions are not compatible because the exception declarations differ. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1}. - The exception definitions are not compatible because the exception declarations differ. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1}. - - - - The exception definitions are not compatible because the field '{0}' was required by the signature but was not specified by the implementation. The module contains the exception definition\n {1} \nbut its signature specifies\n\t{2}. - The exception definitions are not compatible because the field '{0}' was required by the signature but was not specified by the implementation. The module contains the exception definition\n {1} \nbut its signature specifies\n\t{2}. - - - - The exception definitions are not compatible because the field '{0}' was present in the implementation but not in the signature. The module contains the exception definition\n {1} \nbut its signature specifies\n\t{2}. - The exception definitions are not compatible because the field '{0}' was present in the implementation but not in the signature. The module contains the exception definition\n {1} \nbut its signature specifies\n\t{2}. - - - - The exception definitions are not compatible because the order of the fields is different in the signature and implementation. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1}. - The exception definitions are not compatible because the order of the fields is different in the signature and implementation. The module contains the exception definition\n {0} \nbut its signature specifies\n\t{1}. - - - - The namespace or module attributes differ between signature and implementation - The namespace or module attributes differ between signature and implementation - - - - This method is over-constrained in its type parameters - This method is over-constrained in its type parameters - - - - No implementations of '{0}' had the correct number of arguments and type parameters. The required signature is '{1}'. - No implementations of '{0}' had the correct number of arguments and type parameters. The required signature is '{1}'. - - - - The override for '{0}' was ambiguous - The override for '{0}' was ambiguous - - - - More than one override implements '{0}' - More than one override implements '{0}' - - - - The method '{0}' is sealed and cannot be overridden - The method '{0}' is sealed and cannot be overridden - - - - The override '{0}' implements more than one abstract slot, e.g. '{1}' and '{2}' - The override '{0}' implements more than one abstract slot, e.g. '{1}' and '{2}' - - - - Duplicate or redundant interface - Duplicate or redundant interface - - - - The interface '{0}' is included in multiple explicitly implemented interface types. Add an explicit implementation of this interface. - The interface '{0}' is included in multiple explicitly implemented interface types. Add an explicit implementation of this interface. - - - - A named argument has been assigned more than one value - A named argument has been assigned more than one value - - - - No implementation was given for '{0}' - No implementation was given for '{0}' - - - - No implementation was given for '{0}'. Note that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'. - No implementation was given for '{0}'. Note that all interface members must be implemented and listed under an appropriate 'interface' declaration, e.g. 'interface ... with member ...'. - - - - The member '{0}' does not have the correct number of arguments. The required signature is '{1}'. - The member '{0}' does not have the correct number of arguments. The required signature is '{1}'. - - - - The member '{0}' does not have the correct number of method type parameters. The required signature is '{1}'. - The member '{0}' does not have the correct number of method type parameters. The required signature is '{1}'. - - - - The member '{0}' does not have the correct kinds of generic parameters. The required signature is '{1}'. - The member '{0}' does not have the correct kinds of generic parameters. The required signature is '{1}'. - - - - The member '{0}' cannot be used to implement '{1}'. The required signature is '{2}'. - The member '{0}' cannot be used to implement '{1}'. The required signature is '{2}'. - - - - Error while parsing embedded IL - Error while parsing embedded IL - - - - Error while parsing embedded IL type - Error while parsing embedded IL type - - - - This indexer notation has been removed from the F# language - This indexer notation has been removed from the F# language - - - - Invalid expression on left of assignment - Invalid expression on left of assignment - - - - The 'ReferenceEquality' attribute cannot be used on structs. Consider using the 'StructuralEquality' attribute instead, or implement an override for 'System.Object.Equals(obj)'. - The 'ReferenceEquality' attribute cannot be used on structs. Consider using the 'StructuralEquality' attribute instead, or implement an override for 'System.Object.Equals(obj)'. - - - - This type uses an invalid mix of the attributes 'NoEquality', 'ReferenceEquality', 'StructuralEquality', 'NoComparison' and 'StructuralComparison' - This type uses an invalid mix of the attributes 'NoEquality', 'ReferenceEquality', 'StructuralEquality', 'NoComparison' and 'StructuralComparison' - - - - The 'NoEquality' attribute must be used in conjunction with the 'NoComparison' attribute - The 'NoEquality' attribute must be used in conjunction with the 'NoComparison' attribute - - - - The 'StructuralComparison' attribute must be used in conjunction with the 'StructuralEquality' attribute - The 'StructuralComparison' attribute must be used in conjunction with the 'StructuralEquality' attribute - - - - The 'StructuralEquality' attribute must be used in conjunction with the 'NoComparison' or 'StructuralComparison' attributes - The 'StructuralEquality' attribute must be used in conjunction with the 'NoComparison' or 'StructuralComparison' attributes - - - - A type cannot have both the 'ReferenceEquality' and 'StructuralEquality' or 'StructuralComparison' attributes - A type cannot have both the 'ReferenceEquality' and 'StructuralEquality' or 'StructuralComparison' attributes - - - - Only record, union, exception and struct types may be augmented with the 'ReferenceEquality', 'StructuralEquality' and 'StructuralComparison' attributes - Only record, union, exception and struct types may be augmented with the 'ReferenceEquality', 'StructuralEquality' and 'StructuralComparison' attributes - - - - A type with attribute 'ReferenceEquality' cannot have an explicit implementation of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable' - A type with attribute 'ReferenceEquality' cannot have an explicit implementation of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable' - - - - A type with attribute 'CustomEquality' must have an explicit implementation of at least one of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable' - A type with attribute 'CustomEquality' must have an explicit implementation of at least one of 'Object.Equals(obj)', 'System.IEquatable<_>' or 'System.Collections.IStructuralEquatable' - - - - A type with attribute 'CustomComparison' must have an explicit implementation of at least one of 'System.IComparable' or 'System.Collections.IStructuralComparable' - A type with attribute 'CustomComparison' must have an explicit implementation of at least one of 'System.IComparable' or 'System.Collections.IStructuralComparable' - - - - A type with attribute 'NoEquality' should not usually have an explicit implementation of 'Object.Equals(obj)'. Disable this warning if this is intentional for interoperability purposes - A type with attribute 'NoEquality' should not usually have an explicit implementation of 'Object.Equals(obj)'. Disable this warning if this is intentional for interoperability purposes - - - - A type with attribute 'NoComparison' should not usually have an explicit implementation of 'System.IComparable', 'System.IComparable<_>' or 'System.Collections.IStructuralComparable'. Disable this warning if this is intentional for interoperability purposes - A type with attribute 'NoComparison' should not usually have an explicit implementation of 'System.IComparable', 'System.IComparable<_>' or 'System.Collections.IStructuralComparable'. Disable this warning if this is intentional for interoperability purposes - - - - The 'CustomEquality' attribute must be used in conjunction with the 'NoComparison' or 'CustomComparison' attributes - The 'CustomEquality' attribute must be used in conjunction with the 'NoComparison' or 'CustomComparison' attributes - - - - Positional specifiers are not permitted in format strings - Positional specifiers are not permitted in format strings - - - - Missing format specifier - Missing format specifier - - - - '{0}' flag set twice - '{0}' flag set twice - - - - Prefix flag (' ' or '+') set twice - Prefix flag (' ' or '+') set twice - - - - The # formatting modifier is invalid in F# - The # formatting modifier is invalid in F# - - - - Bad precision in format specifier - Bad precision in format specifier - - - - Bad width in format specifier - Bad width in format specifier - - - - '{0}' format does not support '0' flag - '{0}' format does not support '0' flag - - - - Precision missing after the '.' - Precision missing after the '.' - - - - '{0}' format does not support precision - '{0}' format does not support precision - - - - Bad format specifier (after l or L): Expected ld,li,lo,lu,lx or lX. In F# code you can use %d, %x, %o or %u instead, which are overloaded to work with all basic integer types. - Bad format specifier (after l or L): Expected ld,li,lo,lu,lx or lX. In F# code you can use %d, %x, %o or %u instead, which are overloaded to work with all basic integer types. - - - - The 'l' or 'L' in this format specifier is unnecessary. In F# code you can use %d, %x, %o or %u instead, which are overloaded to work with all basic integer types. - The 'l' or 'L' in this format specifier is unnecessary. In F# code you can use %d, %x, %o or %u instead, which are overloaded to work with all basic integer types. - - - - The 'h' or 'H' in this format specifier is unnecessary. You can use %d, %x, %o or %u instead, which are overloaded to work with all basic integer types. - The 'h' or 'H' in this format specifier is unnecessary. You can use %d, %x, %o or %u instead, which are overloaded to work with all basic integer types. - - - - '{0}' does not support prefix '{1}' flag - '{0}' does not support prefix '{1}' flag - - - - Bad format specifier: '{0}' - Bad format specifier: '{0}' - - - - System.Environment.Exit did not exit - System.Environment.Exit did not exit - - - - The treatment of this operator is now handled directly by the F# compiler and its meaning cannot be redefined - The treatment of this operator is now handled directly by the F# compiler and its meaning cannot be redefined - - - - A protected member is called or 'base' is being used. This is only allowed in the direct implementation of members since they could escape their object scope. - A protected member is called or 'base' is being used. This is only allowed in the direct implementation of members since they could escape their object scope. - - - - The byref-typed variable '{0}' is used in an invalid way. Byrefs cannot be captured by closures or passed to inner functions. - The byref-typed variable '{0}' is used in an invalid way. Byrefs cannot be captured by closures or passed to inner functions. - - - - The 'base' keyword is used in an invalid way. Base calls cannot be used in closures. Consider using a private member to make base calls. - The 'base' keyword is used in an invalid way. Base calls cannot be used in closures. Consider using a private member to make base calls. - - - - The variable '{0}' is used in an invalid way - The variable '{0}' is used in an invalid way - - - - The type '{0}' is less accessible than the value, member or type '{1}' it is used in. - The type '{0}' is less accessible than the value, member or type '{1}' it is used in. - - - - 'System.Void' can only be used as 'typeof<System.Void>' in F# - 'System.Void' can only be used as 'typeof<System.Void>' in F# - - - - A type instantiation involves a byref type. This is not permitted by the rules of Common IL. - A type instantiation involves a byref type. This is not permitted by the rules of Common IL. - - - - Calls to 'reraise' may only occur directly in a handler of a try-with - Calls to 'reraise' may only occur directly in a handler of a try-with - - - - Expression-splicing operators may only be used within quotations - Expression-splicing operators may only be used within quotations - - - - First-class uses of the expression-splicing operator are not permitted - First-class uses of the expression-splicing operator are not permitted - - - - First-class uses of the address-of operators are not permitted - First-class uses of the address-of operators are not permitted - - - - First-class uses of the 'reraise' function is not permitted - First-class uses of the 'reraise' function is not permitted - - - - The byref typed value '{0}' cannot be used at this point - The byref typed value '{0}' cannot be used at this point - - - - 'base' values may only be used to make direct calls to the base implementations of overridden members - 'base' values may only be used to make direct calls to the base implementations of overridden members - - - - Object constructors cannot directly use try/with and try/finally prior to the initialization of the object. This includes constructs such as 'for x in ...' that may elaborate to uses of these constructs. This is a limitation imposed by Common IL. - Object constructors cannot directly use try/with and try/finally prior to the initialization of the object. This includes constructs such as 'for x in ...' that may elaborate to uses of these constructs. This is a limitation imposed by Common IL. - - - - The address of the variable '{0}' cannot be used at this point - The address of the variable '{0}' cannot be used at this point - - - - The address of the static field '{0}' cannot be used at this point - The address of the static field '{0}' cannot be used at this point - - - - The address of the field '{0}' cannot be used at this point - The address of the field '{0}' cannot be used at this point - - - - The address of an array element cannot be used at this point - The address of an array element cannot be used at this point - - - - The type of a first-class function cannot contain byrefs - The type of a first-class function cannot contain byrefs - - - - A method return type would contain byrefs which is not permitted - A method return type would contain byrefs which is not permitted - - - - Invalid custom attribute value (not a constant or literal) - Invalid custom attribute value (not a constant or literal) - - - - The attribute type '{0}' has 'AllowMultiple=false'. Multiple instances of this attribute cannot be attached to a single language element. - The attribute type '{0}' has 'AllowMultiple=false'. Multiple instances of this attribute cannot be attached to a single language element. - - - - The member '{0}' is used in an invalid way. A use of '{1}' has been inferred prior to its definition at or near '{2}'. This is an invalid forward reference. - The member '{0}' is used in an invalid way. A use of '{1}' has been inferred prior to its definition at or near '{2}'. This is an invalid forward reference. - - - - A byref typed value would be stored here. Top-level let-bound byref values are not permitted. - A byref typed value would be stored here. Top-level let-bound byref values are not permitted. - - - - [<ReflectedDefinition>] terms cannot contain uses of the prefix splice operator '%' - [<ReflectedDefinition>] terms cannot contain uses of the prefix splice operator '%' - - - - A function labeled with the 'EntryPointAttribute' attribute must be the last declaration in the last file in the compilation sequence. - A function labeled with the 'EntryPointAttribute' attribute must be the last declaration in the last file in the compilation sequence. - - - - compiled form of the union case - compiled form of the union case - - - - default augmentation of the union case - default augmentation of the union case - - - - The property '{0}' has the same name as a method in type '{1}'. - The property '{0}' has the same name as a method in type '{1}'. - - - - The property '{0}' of type '{1}' has a getter and a setter that do not match. If one is abstract then the other must be as well. - The property '{0}' of type '{1}' has a getter and a setter that do not match. If one is abstract then the other must be as well. - - - - The property '{0}' has the same name as another property in type '{1}', but one takes indexer arguments and the other does not. You may be missing an indexer argument to one of your properties. - The property '{0}' has the same name as another property in type '{1}', but one takes indexer arguments and the other does not. You may be missing an indexer argument to one of your properties. - - - - A type would store a byref typed value. This is not permitted by Common IL. - A type would store a byref typed value. This is not permitted by Common IL. - - - - Duplicate method. The method '{0}' has the same name and signature as another method in type '{1}'. - Duplicate method. The method '{0}' has the same name and signature as another method in type '{1}'. - - - - Duplicate method. The method '{0}' has the same name and signature as another method in type '{1}' once tuples, functions, units of measure and/or provided types are erased. - Duplicate method. The method '{0}' has the same name and signature as another method in type '{1}' once tuples, functions, units of measure and/or provided types are erased. - - - - The method '{0}' has curried arguments but has the same name as another method in type '{1}'. Methods with curried arguments cannot be overloaded. Consider using a method taking tupled arguments. - The method '{0}' has curried arguments but has the same name as another method in type '{1}'. Methods with curried arguments cannot be overloaded. Consider using a method taking tupled arguments. - - - - Methods with curried arguments cannot declare 'out', 'ParamArray', 'optional', 'ReflectedDefinition', 'byref', 'CallerLineNumber', 'CallerMemberName', or 'CallerFilePath' arguments - Methods with curried arguments cannot declare 'out', 'ParamArray', 'optional', 'ReflectedDefinition', 'byref', 'CallerLineNumber', 'CallerMemberName', or 'CallerFilePath' arguments - - - - Duplicate property. The property '{0}' has the same name and signature as another property in type '{1}'. - Duplicate property. The property '{0}' has the same name and signature as another property in type '{1}'. - - - - Duplicate property. The property '{0}' has the same name and signature as another property in type '{1}' once tuples, functions, units of measure and/or provided types are erased. - Duplicate property. The property '{0}' has the same name and signature as another property in type '{1}' once tuples, functions, units of measure and/or provided types are erased. - - - - Duplicate method. The abstract method '{0}' has the same name and signature as an abstract method in an inherited type. - Duplicate method. The abstract method '{0}' has the same name and signature as an abstract method in an inherited type. - - - - Duplicate method. The abstract method '{0}' has the same name and signature as an abstract method in an inherited type once tuples, functions, units of measure and/or provided types are erased. - Duplicate method. The abstract method '{0}' has the same name and signature as an abstract method in an inherited type once tuples, functions, units of measure and/or provided types are erased. - - - - This type implements the same interface at different generic instantiations '{0}' and '{1}'. This is not permitted in this version of F#. - This type implements the same interface at different generic instantiations '{0}' and '{1}'. This is not permitted in this version of F#. - - - - The type of a field using the 'DefaultValue' attribute must admit default initialization, i.e. have 'null' as a proper value or be a struct type whose fields all admit default initialization. You can use 'DefaultValue(false)' to disable this check - The type of a field using the 'DefaultValue' attribute must admit default initialization, i.e. have 'null' as a proper value or be a struct type whose fields all admit default initialization. You can use 'DefaultValue(false)' to disable this check - - - - The type abbreviation contains byrefs. This is not permitted by F#. - The type abbreviation contains byrefs. This is not permitted by F#. - - - - The variable '{0}' is bound in a quotation but is used as part of a spliced expression. This is not permitted since it may escape its scope. - The variable '{0}' is bound in a quotation but is used as part of a spliced expression. This is not permitted since it may escape its scope. - - - - Quotations cannot contain uses of generic expressions - Quotations cannot contain uses of generic expressions - - - - Quotations cannot contain function definitions that are inferred or declared to be generic. Consider adding some type constraints to make this a valid quoted expression. - Quotations cannot contain function definitions that are inferred or declared to be generic. Consider adding some type constraints to make this a valid quoted expression. - - - - Quotations cannot contain object expressions - Quotations cannot contain object expressions - - - - Quotations cannot contain expressions that take the address of a field - Quotations cannot contain expressions that take the address of a field - - - - Quotations cannot contain expressions that fetch static fields - Quotations cannot contain expressions that fetch static fields - - - - Quotations cannot contain inline assembly code or pattern matching on arrays - Quotations cannot contain inline assembly code or pattern matching on arrays - - - - Quotations cannot contain descending for loops - Quotations cannot contain descending for loops - - - - Quotations cannot contain expressions that fetch union case indexes - Quotations cannot contain expressions that fetch union case indexes - - - - Quotations cannot contain expressions that set union case fields - Quotations cannot contain expressions that set union case fields - - - - Quotations cannot contain expressions that set fields in exception values - Quotations cannot contain expressions that set fields in exception values - - - - Quotations cannot contain expressions that require byref pointers - Quotations cannot contain expressions that require byref pointers - - - - Quotations cannot contain expressions that make member constraint calls, or uses of operators that implicitly resolve to a member constraint call - Quotations cannot contain expressions that make member constraint calls, or uses of operators that implicitly resolve to a member constraint call - - - - Quotations cannot contain this kind of constant - Quotations cannot contain this kind of constant - - - - Quotations cannot contain this kind of pattern match - Quotations cannot contain this kind of pattern match - - - - Quotations cannot contain array pattern matching - Quotations cannot contain array pattern matching - - - - Quotations cannot contain this kind of type - Quotations cannot contain this kind of type - - - - The declared type parameter '{0}' cannot be used here since the type parameter cannot be resolved at compile time - The declared type parameter '{0}' cannot be used here since the type parameter cannot be resolved at compile time - - - - This code is less generic than indicated by its annotations. A unit-of-measure specified using '_' has been determined to be '1', i.e. dimensionless. Consider making the code generic, or removing the use of '_'. - This code is less generic than indicated by its annotations. A unit-of-measure specified using '_' has been determined to be '1', i.e. dimensionless. Consider making the code generic, or removing the use of '_'. - - - - Type inference problem too complicated (maximum iteration depth reached). Consider adding further type annotations. - Type inference problem too complicated (maximum iteration depth reached). Consider adding further type annotations. - - - - Expected arguments to an instance member - Expected arguments to an instance member - - - - This indexer expects {0} arguments but is here given {1} - This indexer expects {0} arguments but is here given {1} - - - - Expecting a type supporting the operator '{0}' but given a function type. You may be missing an argument to a function. - Expecting a type supporting the operator '{0}' but given a function type. You may be missing an argument to a function. - - - - Expecting a type supporting the operator '{0}' but given a tuple type - Expecting a type supporting the operator '{0}' but given a tuple type - - - - None of the types '{0}' support the operator '{1}' - None of the types '{0}' support the operator '{1}' - - - - The type '{0}' does not support the operator '{1}' - The type '{0}' does not support the operator '{1}' - - - - None of the types '{0}' support the operator '{1}'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - None of the types '{0}' support the operator '{1}'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - - - - The type '{0}' does not support the operator '{1}'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - The type '{0}' does not support the operator '{1}'. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - - - - The type '{0}' does not support a conversion to the type '{1}' - The type '{0}' does not support a conversion to the type '{1}' - - - - The type '{0}' has a method '{1}' (full name '{2}'), but the method is static - The type '{0}' has a method '{1}' (full name '{2}'), but the method is static - - - - The type '{0}' has a method '{1}' (full name '{2}'), but the method is not static - The type '{0}' has a method '{1}' (full name '{2}'), but the method is not static - - - - The constraints 'struct' and 'not struct' are inconsistent - The constraints 'struct' and 'not struct' are inconsistent - - - - The type '{0}' does not have 'null' as a proper value - The type '{0}' does not have 'null' as a proper value - - - - The type '{0}' does not have 'null' as a proper value. To create a null value for a Nullable type use 'System.Nullable()'. - The type '{0}' does not have 'null' as a proper value. To create a null value for a Nullable type use 'System.Nullable()'. - - - - The type '{0}' does not support the 'comparison' constraint because it has the 'NoComparison' attribute - The type '{0}' does not support the 'comparison' constraint because it has the 'NoComparison' attribute - - - - The type '{0}' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface - The type '{0}' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface - - - - The type '{0}' does not support the 'comparison' constraint because it is a record, union or struct with one or more structural element types which do not support the 'comparison' constraint. Either avoid the use of comparison with this type, or add the 'StructuralComparison' attribute to the type to determine which field type does not support comparison - The type '{0}' does not support the 'comparison' constraint because it is a record, union or struct with one or more structural element types which do not support the 'comparison' constraint. Either avoid the use of comparison with this type, or add the 'StructuralComparison' attribute to the type to determine which field type does not support comparison - - - - The type '{0}' does not support the 'equality' constraint because it has the 'NoEquality' attribute - The type '{0}' does not support the 'equality' constraint because it has the 'NoEquality' attribute - - - - The type '{0}' does not support the 'equality' constraint because it is a function type - The type '{0}' does not support the 'equality' constraint because it is a function type - - - - The type '{0}' does not support the 'equality' constraint because it is a record, union or struct with one or more structural element types which do not support the 'equality' constraint. Either avoid the use of equality with this type, or add the 'StructuralEquality' attribute to the type to determine which field type does not support equality - The type '{0}' does not support the 'equality' constraint because it is a record, union or struct with one or more structural element types which do not support the 'equality' constraint. Either avoid the use of equality with this type, or add the 'StructuralEquality' attribute to the type to determine which field type does not support equality - - - - The type '{0}' is not a CLI enum type - The type '{0}' is not a CLI enum type - - - - The type '{0}' has a non-standard delegate type - The type '{0}' has a non-standard delegate type - - - - The type '{0}' is not a CLI delegate type - The type '{0}' is not a CLI delegate type - - - - This type parameter cannot be instantiated to 'Nullable'. This is a restriction imposed in order to ensure the meaning of 'null' in some CLI languages is not confusing when used in conjunction with 'Nullable' values. - This type parameter cannot be instantiated to 'Nullable'. This is a restriction imposed in order to ensure the meaning of 'null' in some CLI languages is not confusing when used in conjunction with 'Nullable' values. - - - - A generic construct requires that the type '{0}' is a CLI or F# struct type - A generic construct requires that the type '{0}' is a CLI or F# struct type - - - - A generic construct requires that the type '{0}' is an unmanaged type - A generic construct requires that the type '{0}' is an unmanaged type - - - - The type '{0}' is not compatible with any of the types {1}, arising from the use of a printf-style format string - The type '{0}' is not compatible with any of the types {1}, arising from the use of a printf-style format string - - - - A generic construct requires that the type '{0}' have reference semantics, but it does not, i.e. it is a struct - A generic construct requires that the type '{0}' have reference semantics, but it does not, i.e. it is a struct - - - - A generic construct requires that the type '{0}' be non-abstract - A generic construct requires that the type '{0}' be non-abstract - - - - A generic construct requires that the type '{0}' have a public default constructor - A generic construct requires that the type '{0}' have a public default constructor - - - - Type instantiation length mismatch - Type instantiation length mismatch - - - - Optional arguments not permitted here - Optional arguments not permitted here - - - - {0} is not a static member - {0} is not a static member - - - - {0} is not an instance member - {0} is not an instance member - - - - Argument length mismatch - Argument length mismatch - - - - The argument types don't match - The argument types don't match - - - - This method expects a CLI 'params' parameter in this position. 'params' is a way of passing a variable number of arguments to a method in languages such as C#. Consider passing an array for this argument - This method expects a CLI 'params' parameter in this position. 'params' is a way of passing a variable number of arguments to a method in languages such as C#. Consider passing an array for this argument - - - - The member or object constructor '{0}' is not {1} - The member or object constructor '{0}' is not {1} - - - - The member or object constructor '{0}' is not {1}. Private members may only be accessed from within the declaring type. Protected members may only be accessed from an extending type and cannot be accessed from inner lambda expressions. - The member or object constructor '{0}' is not {1}. Private members may only be accessed from within the declaring type. Protected members may only be accessed from an extending type and cannot be accessed from inner lambda expressions. - - - - {0} is not a static method - {0} is not a static method - - - - {0} is not an instance method - {0} is not an instance method - - - - The member or object constructor '{0}' has no argument or settable return property '{1}'. {2}. - The member or object constructor '{0}' has no argument or settable return property '{1}'. {2}. - - - - The object constructor '{0}' has no argument or settable return property '{1}'. {2}. - The object constructor '{0}' has no argument or settable return property '{1}'. {2}. - - - - The required signature is {0} - The required signature is {0} - - - - The member or object constructor '{0}' requires {1} argument(s). The required signature is '{2}'. - The member or object constructor '{0}' requires {1} argument(s). The required signature is '{2}'. - - - - The member or object constructor '{0}' requires {1} additional argument(s). The required signature is '{2}'. - The member or object constructor '{0}' requires {1} additional argument(s). The required signature is '{2}'. - - - - The member or object constructor '{0}' requires {1} argument(s). The required signature is '{2}'. Some names for missing arguments are {3}. - The member or object constructor '{0}' requires {1} argument(s). The required signature is '{2}'. Some names for missing arguments are {3}. - - - - The member or object constructor '{0}' requires {1} additional argument(s). The required signature is '{2}'. Some names for missing arguments are {3}. - The member or object constructor '{0}' requires {1} additional argument(s). The required signature is '{2}'. Some names for missing arguments are {3}. - - - - The member or object constructor '{0}' requires {1} argument(s) but is here given {2} unnamed and {3} named argument(s). The required signature is '{4}'. - The member or object constructor '{0}' requires {1} argument(s) but is here given {2} unnamed and {3} named argument(s). The required signature is '{4}'. - - - - The member or object constructor '{0}' takes {1} argument(s) but is here given {2}. The required signature is '{3}'. - The member or object constructor '{0}' takes {1} argument(s) but is here given {2}. The required signature is '{3}'. - - - - The object constructor '{0}' takes {1} argument(s) but is here given {2}. The required signature is '{3}'. - The object constructor '{0}' takes {1} argument(s) but is here given {2}. The required signature is '{3}'. - - - - The object constructor '{0}' takes {1} argument(s) but is here given {2}. The required signature is '{3}'. If some of the arguments are meant to assign values to properties, consider separating those arguments with a comma (','). - The object constructor '{0}' takes {1} argument(s) but is here given {2}. The required signature is '{3}'. If some of the arguments are meant to assign values to properties, consider separating those arguments with a comma (','). - - - - The member or object constructor '{0}' takes {1} type argument(s) but is here given {2}. The required signature is '{3}'. - The member or object constructor '{0}' takes {1} type argument(s) but is here given {2}. The required signature is '{3}'. - - - - A member or object constructor '{0}' taking {1} arguments is not accessible from this code location. All accessible versions of method '{2}' take {3} arguments. - A member or object constructor '{0}' taking {1} arguments is not accessible from this code location. All accessible versions of method '{2}' take {3} arguments. - - - - Incorrect generic instantiation. No {0} member named '{1}' takes {2} generic arguments. - Incorrect generic instantiation. No {0} member named '{1}' takes {2} generic arguments. - - - - The member or object constructor '{0}' does not take {1} argument(s). An overload was found taking {2} arguments. - The member or object constructor '{0}' does not take {1} argument(s). An overload was found taking {2} arguments. - - - - No {0} member or object constructor named '{1}' takes {2} arguments - No {0} member or object constructor named '{1}' takes {2} arguments - - - - No {0} member or object constructor named '{1}' takes {2} arguments. Note the call to this member also provides {3} named arguments. - No {0} member or object constructor named '{1}' takes {2} arguments. Note the call to this member also provides {3} named arguments. - - - - No {0} member or object constructor named '{1}' takes {2} arguments. The named argument '{3}' doesn't correspond to any argument or settable return property for any overload. - No {0} member or object constructor named '{1}' takes {2} arguments. The named argument '{3}' doesn't correspond to any argument or settable return property for any overload. - - - - Method or object constructor '{0}' not found - Method or object constructor '{0}' not found - - - - No overloads match for method '{0}'. - No overloads match for method '{0}'. - - - - A unique overload for method '{0}' could not be determined based on type information prior to this program point. A type annotation may be needed. - A unique overload for method '{0}' could not be determined based on type information prior to this program point. A type annotation may be needed. - - - - Candidates: {0} - Candidates: {0} - - - - The available overloads are shown below. - The available overloads are shown below. - - - - Accessibility modifiers are not permitted on 'do' bindings, but '{0}' was given. - Accessibility modifiers are not permitted on 'do' bindings, but '{0}' was given. - - - - End of file in #if section begun at or after here - End of file in #if section begun at or after here - - - - End of file in string begun at or before here - End of file in string begun at or before here - - - - End of file in verbatim string begun at or before here - End of file in verbatim string begun at or before here - - - - End of file in comment begun at or before here - End of file in comment begun at or before here - - - - End of file in string embedded in comment begun at or before here - End of file in string embedded in comment begun at or before here - - - - End of file in verbatim string embedded in comment begun at or before here - End of file in verbatim string embedded in comment begun at or before here - - - - End of file in IF-OCAML section begun at or before here - End of file in IF-OCAML section begun at or before here - - - - End of file in directive begun at or before here - End of file in directive begun at or before here - - - - No #endif found for #if or #else - No #endif found for #if or #else - - - - Attributes have been ignored in this construct - Attributes have been ignored in this construct - - - - 'use' bindings are not permitted in primary constructors - 'use' bindings are not permitted in primary constructors - - - - 'use' bindings are not permitted in modules and are treated as 'let' bindings - 'use' bindings are not permitted in modules and are treated as 'let' bindings - - - - An integer for loop must use a simple identifier - An integer for loop must use a simple identifier - - - - At most one 'with' augmentation is permitted - At most one 'with' augmentation is permitted - - - - A semicolon is not expected at this point - A semicolon is not expected at this point - - - - Unexpected end of input - Unexpected end of input - - - - Accessibility modifiers are not permitted here, but '{0}' was given. - Accessibility modifiers are not permitted here, but '{0}' was given. - - - - Only '#' compiler directives may occur prior to the first 'namespace' declaration - Only '#' compiler directives may occur prior to the first 'namespace' declaration - - - - Accessibility modifiers should come immediately prior to the identifier naming a construct - Accessibility modifiers should come immediately prior to the identifier naming a construct - - - - Files should begin with either a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule', but not both. To define a module within a namespace use 'module SomeModule = ...' - Files should begin with either a namespace or module declaration, e.g. 'namespace SomeNamespace.SubNamespace' or 'module SomeNamespace.SomeModule', but not both. To define a module within a namespace use 'module SomeModule = ...' - - - - A module abbreviation must be a simple name, not a path - A module abbreviation must be a simple name, not a path - - - - Ignoring attributes on module abbreviation - Ignoring attributes on module abbreviation - - - - The '{0}' accessibility attribute is not allowed on module abbreviation. Module abbreviations are always private. - The '{0}' accessibility attribute is not allowed on module abbreviation. Module abbreviations are always private. - - - - The '{0}' visibility attribute is not allowed on module abbreviation. Module abbreviations are always private. - The '{0}' visibility attribute is not allowed on module abbreviation. Module abbreviations are always private. - - - - Unclosed block - Unclosed block - - - - Unmatched 'begin' or 'struct' - Unmatched 'begin' or 'struct' - - - - A module name must be a simple name, not a path - A module name must be a simple name, not a path - - - - Unexpected empty type moduleDefn list - Unexpected empty type moduleDefn list - - - - Attributes should be placed before 'val' - Attributes should be placed before 'val' - - - - Attributes are not permitted on interface implementations - Attributes are not permitted on interface implementations - - - - Syntax error - Syntax error - - - - Augmentations are not permitted on delegate type moduleDefns - Augmentations are not permitted on delegate type moduleDefns - - - - Unmatched 'class', 'interface' or 'struct' - Unmatched 'class', 'interface' or 'struct' - - - - A type definition requires one or more members or other declarations. If you intend to define an empty class, struct or interface, then use 'type ... = class end', 'interface end' or 'struct end'. - A type definition requires one or more members or other declarations. If you intend to define an empty class, struct or interface, then use 'type ... = class end', 'interface end' or 'struct end'. - - - - Unmatched 'with' or badly formatted 'with' block - Unmatched 'with' or badly formatted 'with' block - - - - 'get', 'set' or 'get,set' required - 'get', 'set' or 'get,set' required - - - - Only class types may take value arguments - Only class types may take value arguments - - - - Unmatched 'begin' - Unmatched 'begin' - - - - Invalid declaration syntax - Invalid declaration syntax - - - - 'get' and/or 'set' required - 'get' and/or 'set' required - - - - Type annotations on property getters and setters must be given after the 'get()' or 'set(v)', e.g. 'with get() : string = ...' - Type annotations on property getters and setters must be given after the 'get()' or 'set(v)', e.g. 'with get() : string = ...' - - - - A getter property is expected to be a function, e.g. 'get() = ...' or 'get(index) = ...' - A getter property is expected to be a function, e.g. 'get() = ...' or 'get(index) = ...' - - - - Multiple accessibilities given for property getter or setter - Multiple accessibilities given for property getter or setter - - - - Property setters must be defined using 'set value = ', 'set idx value = ' or 'set (idx1,...,idxN) value = ... ' - Property setters must be defined using 'set value = ', 'set idx value = ' or 'set (idx1,...,idxN) value = ... ' - - - - Interfaces always have the same visibility as the enclosing type - Interfaces always have the same visibility as the enclosing type - - - - Accessibility modifiers are not allowed on this member. Abstract slots always have the same visibility as the enclosing type. - Accessibility modifiers are not allowed on this member. Abstract slots always have the same visibility as the enclosing type. - - - - Attributes are not permitted on 'inherit' declarations - Attributes are not permitted on 'inherit' declarations - - - - Accessibility modifiers are not permitted on an 'inherits' declaration - Accessibility modifiers are not permitted on an 'inherits' declaration - - - - 'inherit' declarations cannot have 'as' bindings. To access members of the base class when overriding a method, the syntax 'base.SomeMember' may be used; 'base' is a keyword. Remove this 'as' binding. - 'inherit' declarations cannot have 'as' bindings. To access members of the base class when overriding a method, the syntax 'base.SomeMember' may be used; 'base' is a keyword. Remove this 'as' binding. - - - - Attributes are not allowed here - Attributes are not allowed here - - - - Accessibility modifiers are not permitted in this position for type abbreviations - Accessibility modifiers are not permitted in this position for type abbreviations - - - - Accessibility modifiers are not permitted in this position for enum types - Accessibility modifiers are not permitted in this position for enum types - - - - All enum fields must be given values - All enum fields must be given values - - - - Accessibility modifiers are not permitted on inline assembly code types - Accessibility modifiers are not permitted on inline assembly code types - - - - Unexpected identifier: '{0}' - Unexpected identifier: '{0}' - - - - Accessibility modifiers are not permitted on union cases. Use 'type U = internal ...' or 'type U = private ...' to give an accessibility to the whole representation. - Accessibility modifiers are not permitted on union cases. Use 'type U = internal ...' or 'type U = private ...' to give an accessibility to the whole representation. - - - - Accessibility modifiers are not permitted on enumeration fields - Accessibility modifiers are not permitted on enumeration fields - - - - Consider using a separate record type instead - Consider using a separate record type instead - - - - Accessibility modifiers are not permitted on record fields. Use 'type R = internal ...' or 'type R = private ...' to give an accessibility to the whole representation. - Accessibility modifiers are not permitted on record fields. Use 'type R = internal ...' or 'type R = private ...' to give an accessibility to the whole representation. - - - - The declaration form 'let ... and ...' for non-recursive bindings is not used in F# code. Consider using a sequence of 'let' bindings - The declaration form 'let ... and ...' for non-recursive bindings is not used in F# code. Consider using a sequence of 'let' bindings - - - - Unmatched '(' - Unmatched '(' - - - - Successive patterns should be separated by spaces or tupled - Successive patterns should be separated by spaces or tupled - - - - No matching 'in' found for this 'let' - No matching 'in' found for this 'let' - - - - Error in the return expression for this 'let'. Possible incorrect indentation. - Error in the return expression for this 'let'. Possible incorrect indentation. - - - - The block following this '{0}' is unfinished. Every code block is an expression and must have a result. '{1}' cannot be the final code element in a block. Consider giving this block an explicit result. - The block following this '{0}' is unfinished. Every code block is an expression and must have a result. '{1}' cannot be the final code element in a block. Consider giving this block an explicit result. - - - - Incomplete conditional. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - Incomplete conditional. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - - - - 'assert' may not be used as a first class value. Use 'assert <expr>' instead. - 'assert' may not be used as a first class value. Use 'assert <expr>' instead. - - - - Identifier expected - Identifier expected - - - - 'in' or '=' expected - 'in' or '=' expected - - - - The use of '->' in sequence and computation expressions is limited to the form 'for pat in expr -> expr'. Use the syntax 'for ... in ... do ... yield...' to generate elements in more complex sequence expressions. - The use of '->' in sequence and computation expressions is limited to the form 'for pat in expr -> expr'. Use the syntax 'for ... in ... do ... yield...' to generate elements in more complex sequence expressions. - - - - Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized - Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized - - - - Unmatched '[' - Unmatched '[' - - - - Missing qualification after '.' - Missing qualification after '.' - - - - In F# code you may use 'expr.[expr]'. A type annotation may be required to indicate the first expression is an array - In F# code you may use 'expr.[expr]'. A type annotation may be required to indicate the first expression is an array - - - - Mismatched quotation, beginning with '{0}' - Mismatched quotation, beginning with '{0}' - - - - Unmatched '{0}' - Unmatched '{0}' - - - - Unmatched '[|' - Unmatched '[|' - - - - Unmatched '{{' - Unmatched '{{' - - - - Field bindings must have the form 'id = expr;' - Field bindings must have the form 'id = expr;' - - - - This member is not permitted in an object implementation - This member is not permitted in an object implementation - - - - Missing function body - Missing function body - - - - Syntax error in labelled type argument - Syntax error in labelled type argument - - - - Unexpected infix operator in type expression - Unexpected infix operator in type expression - - - - The syntax '(typ,...,typ) ident' is not used in F# code. Consider using 'ident<typ,...,typ>' instead - The syntax '(typ,...,typ) ident' is not used in F# code. Consider using 'ident<typ,...,typ>' instead - - - - Invalid literal in type - Invalid literal in type - - - - Unexpected infix operator in unit-of-measure expression. Legal operators are '*', '/' and '^'. - Unexpected infix operator in unit-of-measure expression. Legal operators are '*', '/' and '^'. - - - - Unexpected integer literal in unit-of-measure expression - Unexpected integer literal in unit-of-measure expression - - - - Syntax error: unexpected type parameter specification - Syntax error: unexpected type parameter specification - - - - Mismatched quotation operator name, beginning with '{0}' - Mismatched quotation operator name, beginning with '{0}' - - - - Active pattern case identifiers must begin with an uppercase letter - Active pattern case identifiers must begin with an uppercase letter - - - - The '|' character is not permitted in active pattern case identifiers - The '|' character is not permitted in active pattern case identifiers - - - - Denominator must not be 0 in unit-of-measure exponent - Denominator must not be 0 in unit-of-measure exponent - - - - No '=' symbol should follow a 'namespace' declaration - No '=' symbol should follow a 'namespace' declaration - - - - The syntax 'module ... = struct .. end' is not used in F# code. Consider using 'module ... = begin .. end' - The syntax 'module ... = struct .. end' is not used in F# code. Consider using 'module ... = begin .. end' - - - - The syntax 'module ... : sig .. end' is not used in F# code. Consider using 'module ... = begin .. end' - The syntax 'module ... : sig .. end' is not used in F# code. Consider using 'module ... = begin .. end' - - - - A static field was used where an instance field is expected - A static field was used where an instance field is expected - - - - Method '{0}' is not accessible from this code location - Method '{0}' is not accessible from this code location - - - - Implicit product of measures following / - Implicit product of measures following / - - - - Unexpected SynMeasure.Anon - Unexpected SynMeasure.Anon - - - - Non-zero constants cannot have generic units. For generic zero, write 0.0<_>. - Non-zero constants cannot have generic units. For generic zero, write 0.0<_>. - - - - In sequence expressions, results are generated using 'yield' - In sequence expressions, results are generated using 'yield' - - - - Unexpected big rational constant - Unexpected big rational constant - - - - Units-of-measure supported only on float, float32, decimal and signed integer types - Units-of-measure supported only on float, float32, decimal and signed integer types - - - - Unexpected Const_uint16array - Unexpected Const_uint16array - - - - Unexpected Const_bytearray - Unexpected Const_bytearray - - - - A parameter with attributes must also be given a name, e.g. '[<Attribute>] Name : Type' - A parameter with attributes must also be given a name, e.g. '[<Attribute>] Name : Type' - - - - Return values cannot have names - Return values cannot have names - - - - MemberKind.PropertyGetSet only expected in parse trees - MemberKind.PropertyGetSet only expected in parse trees - - - - Namespaces cannot contain values. Consider using a module to hold your value declarations. - Namespaces cannot contain values. Consider using a module to hold your value declarations. - - - - Namespaces cannot contain extension members except in the same file and namespace declaration group where the type is defined. Consider using a module to hold declarations of extension members. - Namespaces cannot contain extension members except in the same file and namespace declaration group where the type is defined. Consider using a module to hold declarations of extension members. - - - - Multiple visibility attributes have been specified for this identifier - Multiple visibility attributes have been specified for this identifier - - - - Multiple visibility attributes have been specified for this identifier. 'let' bindings in classes are always private, as are any 'let' bindings inside expressions. - Multiple visibility attributes have been specified for this identifier. 'let' bindings in classes are always private, as are any 'let' bindings inside expressions. - - - - The name '({0})' should not be used as a member name. To define comparison semantics for a type, implement the 'System.IComparable' interface. If defining a static member for use from other CLI languages then use the name '{1}' instead. - The name '({0})' should not be used as a member name. To define comparison semantics for a type, implement the 'System.IComparable' interface. If defining a static member for use from other CLI languages then use the name '{1}' instead. - - - - The name '({0})' should not be used as a member name. To define equality semantics for a type, override the 'Object.Equals' member. If defining a static member for use from other CLI languages then use the name '{1}' instead. - The name '({0})' should not be used as a member name. To define equality semantics for a type, override the 'Object.Equals' member. If defining a static member for use from other CLI languages then use the name '{1}' instead. - - - - The name '({0})' should not be used as a member name. If defining a static member for use from other CLI languages then use the name '{1}' instead. - The name '({0})' should not be used as a member name. If defining a static member for use from other CLI languages then use the name '{1}' instead. - - - - The name '({0})' should not be used as a member name because it is given a standard definition in the F# library over fixed types - The name '({0})' should not be used as a member name because it is given a standard definition in the F# library over fixed types - - - - The '{0}' operator should not normally be redefined. To define overloaded comparison semantics for a particular type, implement the 'System.IComparable' interface in the definition of that type. - The '{0}' operator should not normally be redefined. To define overloaded comparison semantics for a particular type, implement the 'System.IComparable' interface in the definition of that type. - - - - The '{0}' operator should not normally be redefined. To define equality semantics for a type, override the 'Object.Equals' member in the definition of that type. - The '{0}' operator should not normally be redefined. To define equality semantics for a type, override the 'Object.Equals' member in the definition of that type. - - - - The '{0}' operator should not normally be redefined. Consider using a different operator name - The '{0}' operator should not normally be redefined. Consider using a different operator name - - - - The '{0}' operator cannot be redefined. Consider using a different operator name - The '{0}' operator cannot be redefined. Consider using a different operator name - - - - Expected module or namespace parent {0} - Expected module or namespace parent {0} - - - - The struct, record or union type '{0}' implements the interface 'System.IComparable' explicitly. You must apply the 'CustomComparison' attribute to the type. - The struct, record or union type '{0}' implements the interface 'System.IComparable' explicitly. You must apply the 'CustomComparison' attribute to the type. - - - - The struct, record or union type '{0}' implements the interface 'System.IComparable<_>' explicitly. You must apply the 'CustomComparison' attribute to the type, and should also provide a consistent implementation of the non-generic interface System.IComparable. - The struct, record or union type '{0}' implements the interface 'System.IComparable<_>' explicitly. You must apply the 'CustomComparison' attribute to the type, and should also provide a consistent implementation of the non-generic interface System.IComparable. - - - - The struct, record or union type '{0}' implements the interface 'System.IStructuralComparable' explicitly. Apply the 'CustomComparison' attribute to the type. - The struct, record or union type '{0}' implements the interface 'System.IStructuralComparable' explicitly. Apply the 'CustomComparison' attribute to the type. - - - - This record contains fields from inconsistent types - This record contains fields from inconsistent types - - - - DLLImport stubs cannot be inlined - DLLImport stubs cannot be inlined - - - - Structs may only bind a 'this' parameter at member declarations - Structs may only bind a 'this' parameter at member declarations - - - - Unexpected expression at recursive inference point - Unexpected expression at recursive inference point - - - - This code is less generic than required by its annotations because the explicit type variable '{0}' could not be generalized. It was constrained to be '{1}'. - This code is less generic than required by its annotations because the explicit type variable '{0}' could not be generalized. It was constrained to be '{1}'. - - - - One or more of the explicit class or function type variables for this binding could not be generalized, because they were constrained to other types - One or more of the explicit class or function type variables for this binding could not be generalized, because they were constrained to other types - - - - A generic type parameter has been used in a way that constrains it to always be '{0}' - A generic type parameter has been used in a way that constrains it to always be '{0}' - - - - This type parameter has been used in a way that constrains it to always be '{0}' - This type parameter has been used in a way that constrains it to always be '{0}' - - - - The type parameters inferred for this value are not stable under the erasure of type abbreviations. This is due to the use of type abbreviations which drop or reorder type parameters, e.g. \n\ttype taggedInt<'a> = int or\n\ttype swap<'a,'b> = 'b * 'a.\nConsider declaring the type parameters for this value explicitly, e.g.\n\tlet f<'a,'b> ((x,y) : swap<'b,'a>) : swap<'a,'b> = (y,x). - The type parameters inferred for this value are not stable under the erasure of type abbreviations. This is due to the use of type abbreviations which drop or reorder type parameters, e.g. \n\ttype taggedInt<'a> = int or\n\ttype swap<'a,'b> = 'b * 'a.\nConsider declaring the type parameters for this value explicitly, e.g.\n\tlet f<'a,'b> ((x,y) : swap<'b,'a>) : swap<'a,'b> = (y,x). - - - - Explicit type parameters may only be used on module or member bindings - Explicit type parameters may only be used on module or member bindings - - - - You must explicitly declare either all or no type parameters when overriding a generic abstract method - You must explicitly declare either all or no type parameters when overriding a generic abstract method - - - - The field labels and expected type of this record expression or pattern do not uniquely determine a corresponding record type - The field labels and expected type of this record expression or pattern do not uniquely determine a corresponding record type - - - - The field '{0}' appears twice in this record expression or pattern - The field '{0}' appears twice in this record expression or pattern - - - - Unknown union case - Unknown union case - - - - This code is not sufficiently generic. The type variable {0} could not be generalized because it would escape its scope. - This code is not sufficiently generic. The type variable {0} could not be generalized because it would escape its scope. - - - - A property cannot have explicit type parameters. Consider using a method instead. - A property cannot have explicit type parameters. Consider using a method instead. - - - - A constructor cannot have explicit type parameters. Consider using a static construction method instead. - A constructor cannot have explicit type parameters. Consider using a static construction method instead. - - - - This instance member needs a parameter to represent the object being invoked. Make the member static or use the notation 'member x.Member(args) = ...'. - This instance member needs a parameter to represent the object being invoked. Make the member static or use the notation 'member x.Member(args) = ...'. - - - - Unexpected source-level property specification in syntax tree - Unexpected source-level property specification in syntax tree - - - - A static initializer requires an argument - A static initializer requires an argument - - - - An object constructor requires an argument - An object constructor requires an argument - - - - This static member should not have a 'this' parameter. Consider using the notation 'member Member(args) = ...'. - This static member should not have a 'this' parameter. Consider using the notation 'member Member(args) = ...'. - - - - An explicit static initializer should use the syntax 'static new(args) = expr' - An explicit static initializer should use the syntax 'static new(args) = expr' - - - - An explicit object constructor should use the syntax 'new(args) = expr' - An explicit object constructor should use the syntax 'new(args) = expr' - - - - Unexpected source-level property specification - Unexpected source-level property specification - - - - This form of object expression is not used in F#. Use 'member this.MemberName ... = ...' to define member implementations in object expressions. - This form of object expression is not used in F#. Use 'member this.MemberName ... = ...' to define member implementations in object expressions. - - - - Invalid declaration - Invalid declaration - - - - Attributes are not allowed within patterns - Attributes are not allowed within patterns - - - - The generic function '{0}' must be given explicit type argument(s) - The generic function '{0}' must be given explicit type argument(s) - - - - The method or function '{0}' should not be given explicit type argument(s) because it does not declare its type parameters explicitly - The method or function '{0}' should not be given explicit type argument(s) because it does not declare its type parameters explicitly - - - - This value, type or method expects {0} type parameter(s) but was given {1} - This value, type or method expects {0} type parameter(s) but was given {1} - - - - The default, zero-initializing constructor of a struct type may only be used if all the fields of the struct type admit default initialization - The default, zero-initializing constructor of a struct type may only be used if all the fields of the struct type admit default initialization - - - - Couldn't find Dispose on IDisposable, or it was overloaded - Couldn't find Dispose on IDisposable, or it was overloaded - - - - This value is not a literal and cannot be used in a pattern - This value is not a literal and cannot be used in a pattern - - - - This field is readonly - This field is readonly - - - - Named arguments must appear after all other arguments - Named arguments must appear after all other arguments - - - - This function value is being used to construct a delegate type whose signature includes a byref argument. You must use an explicit lambda expression taking {0} arguments. - This function value is being used to construct a delegate type whose signature includes a byref argument. You must use an explicit lambda expression taking {0} arguments. - - - - The type '{0}' is not a type whose values can be enumerated with this syntax, i.e. is not compatible with either seq<_>, IEnumerable<_> or IEnumerable and does not have a GetEnumerator method - The type '{0}' is not a type whose values can be enumerated with this syntax, i.e. is not compatible with either seq<_>, IEnumerable<_> or IEnumerable and does not have a GetEnumerator method - - - - This recursive binding uses an invalid mixture of recursive forms - This recursive binding uses an invalid mixture of recursive forms - - - - This is not a valid object construction expression. Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor. - This is not a valid object construction expression. Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor. - - - - Invalid constraint - Invalid constraint - - - - Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution - Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution - - - - An 'enum' constraint must be of the form 'enum<type>' - An 'enum' constraint must be of the form 'enum<type>' - - - - 'new' constraints must take one argument of type 'unit' and return the constructed type - 'new' constraints must take one argument of type 'unit' and return the constructed type - - - - This property has an invalid type. Properties taking multiple indexer arguments should have types of the form 'ty1 * ty2 -> ty3'. Properties returning functions should have types of the form '(ty1 -> ty2)'. - This property has an invalid type. Properties taking multiple indexer arguments should have types of the form 'ty1 * ty2 -> ty3'. Properties returning functions should have types of the form '(ty1 -> ty2)'. - - - - Expected unit-of-measure parameter, not type parameter. Explicit unit-of-measure parameters must be marked with the [<Measure>] attribute. - Expected unit-of-measure parameter, not type parameter. Explicit unit-of-measure parameters must be marked with the [<Measure>] attribute. - - - - Expected type parameter, not unit-of-measure parameter - Expected type parameter, not unit-of-measure parameter - - - - Expected type, not unit-of-measure - Expected type, not unit-of-measure - - - - Expected unit-of-measure, not type - Expected unit-of-measure, not type - - - - Units-of-measure cannot be used as prefix arguments to a type. Rewrite as postfix arguments in angle brackets. - Units-of-measure cannot be used as prefix arguments to a type. Rewrite as postfix arguments in angle brackets. - - - - Unit-of-measure cannot be used in type constructor application - Unit-of-measure cannot be used in type constructor application - - - - This control construct may only be used if the computation expression builder defines a '{0}' method - This control construct may only be used if the computation expression builder defines a '{0}' method - - - - This type has no nested types - This type has no nested types - - - - Unexpected {0} in type expression - Unexpected {0} in type expression - - - - Type parameter cannot be used as type constructor - Type parameter cannot be used as type constructor - - - - Illegal syntax in type expression - Illegal syntax in type expression - - - - Anonymous unit-of-measure cannot be nested inside another unit-of-measure expression - Anonymous unit-of-measure cannot be nested inside another unit-of-measure expression - - - - Anonymous type variables are not permitted in this declaration - Anonymous type variables are not permitted in this declaration - - - - Unexpected / in type - Unexpected / in type - - - - Unexpected type arguments - Unexpected type arguments - - - - Optional arguments are only permitted on type members - Optional arguments are only permitted on type members - - - - Name '{0}' not bound in pattern context - Name '{0}' not bound in pattern context - - - - Non-primitive numeric literal constants cannot be used in pattern matches because they can be mapped to multiple different types through the use of a NumericLiteral module. Consider using replacing with a variable, and use 'when <variable> = <constant>' at the end of the match clause. - Non-primitive numeric literal constants cannot be used in pattern matches because they can be mapped to multiple different types through the use of a NumericLiteral module. Consider using replacing with a variable, and use 'when <variable> = <constant>' at the end of the match clause. - - - - Type arguments cannot be specified here - Type arguments cannot be specified here - - - - Only active patterns returning exactly one result may accept arguments - Only active patterns returning exactly one result may accept arguments - - - - Invalid argument to parameterized pattern label - Invalid argument to parameterized pattern label - - - - Internal error. Invalid index into active pattern array - Internal error. Invalid index into active pattern array - - - - This union case does not take arguments - This union case does not take arguments - - - - This union case takes one argument - This union case takes one argument - - - - This union case expects {0} arguments in tupled form - This union case expects {0} arguments in tupled form - - - - Field '{0}' is not static - Field '{0}' is not static - - - - This field is not a literal and cannot be used in a pattern - This field is not a literal and cannot be used in a pattern - - - - This is not a variable, constant, active recognizer or literal - This is not a variable, constant, active recognizer or literal - - - - This is not a valid pattern - This is not a valid pattern - - - - Character range matches have been removed in F#. Consider using a 'when' pattern guard instead. - Character range matches have been removed in F#. Consider using a 'when' pattern guard instead. - - - - Illegal pattern - Illegal pattern - - - - Syntax error - unexpected '?' symbol - Syntax error - unexpected '?' symbol - - - - Expected {0} expressions, got {1} - Expected {0} expressions, got {1} - - - - TcExprUndelayed: delayed - TcExprUndelayed: delayed - - - - This expression form may only be used in sequence and computation expressions - This expression form may only be used in sequence and computation expressions - - - - Invalid object expression. Objects without overrides or interfaces should use the expression form 'new Type(args)' without braces. - Invalid object expression. Objects without overrides or interfaces should use the expression form 'new Type(args)' without braces. - - - - Invalid object, sequence or record expression - Invalid object, sequence or record expression - - - - Invalid record, sequence or computation expression. Sequence expressions should be of the form 'seq {{ ... }}' - Invalid record, sequence or computation expression. Sequence expressions should be of the form 'seq {{ ... }}' - - - - This list or array expression includes an element of the form 'if ... then ... else'. Parenthesize this expression to indicate it is an individual element of the list or array, to disambiguate this from a list generated using a sequence expression - This list or array expression includes an element of the form 'if ... then ... else'. Parenthesize this expression to indicate it is an individual element of the list or array, to disambiguate this from a list generated using a sequence expression - - - - Unable to parse format string '{0}' - Unable to parse format string '{0}' - - - - This list expression exceeds the maximum size for list literals. Use an array for larger literals and call Array.ToList. - This list expression exceeds the maximum size for list literals. Use an array for larger literals and call Array.ToList. - - - - The expression form 'expr then expr' may only be used as part of an explicit object constructor - The expression form 'expr then expr' may only be used as part of an explicit object constructor - - - - Named arguments cannot be given to member trait calls - Named arguments cannot be given to member trait calls - - - - This is not a valid name for an enumeration case - This is not a valid name for an enumeration case - - - - This field is not mutable - This field is not mutable - - - - This construct may only be used within list, array and sequence expressions, e.g. expressions of the form 'seq {{ ... }}', '[ ... ]' or '[| ... |]'. These use the syntax 'for ... in ... do ... yield...' to generate elements - This construct may only be used within list, array and sequence expressions, e.g. expressions of the form 'seq {{ ... }}', '[ ... ]' or '[| ... |]'. These use the syntax 'for ... in ... do ... yield...' to generate elements - - - - This construct may only be used within computation expressions. To return a value from an ordinary function simply write the expression without 'return'. - This construct may only be used within computation expressions. To return a value from an ordinary function simply write the expression without 'return'. - - - - This construct may only be used within sequence or computation expressions - This construct may only be used within sequence or computation expressions - - - - This construct may only be used within computation expressions - This construct may only be used within computation expressions - - - - Invalid indexer expression - Invalid indexer expression - - - - The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints - The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints - - - - Cannot inherit from a variable type - Cannot inherit from a variable type - - - - Calls to object constructors on type parameters cannot be given arguments - Calls to object constructors on type parameters cannot be given arguments - - - - The 'CompiledName' attribute cannot be used with this language element - The 'CompiledName' attribute cannot be used with this language element - - - - '{0}' may only be used with named types - '{0}' may only be used with named types - - - - 'inherit' cannot be used on interface types. Consider implementing the interface by using 'interface ... with ... end' instead. - 'inherit' cannot be used on interface types. Consider implementing the interface by using 'interface ... with ... end' instead. - - - - 'new' cannot be used on interface types. Consider using an object expression '{{ new ... with ... }}' instead. - 'new' cannot be used on interface types. Consider using an object expression '{{ new ... with ... }}' instead. - - - - Instances of this type cannot be created since it has been marked abstract or not all methods have been given implementations. Consider using an object expression '{{ new ... with ... }}' instead. - Instances of this type cannot be created since it has been marked abstract or not all methods have been given implementations. Consider using an object expression '{{ new ... with ... }}' instead. - - - - It is recommended that objects supporting the IDisposable interface are created using the syntax 'new Type(args)', rather than 'Type(args)' or 'Type' as a function value representing the constructor, to indicate that resources may be owned by the generated value - It is recommended that objects supporting the IDisposable interface are created using the syntax 'new Type(args)', rather than 'Type(args)' or 'Type' as a function value representing the constructor, to indicate that resources may be owned by the generated value - - - - '{0}' may only be used to construct object types - '{0}' may only be used to construct object types - - - - Constructors for the type '{0}' must directly or indirectly call its implicit object constructor. Use a call to the implicit object constructor instead of a record expression. - Constructors for the type '{0}' must directly or indirectly call its implicit object constructor. Use a call to the implicit object constructor instead of a record expression. - - - - The field '{0}' has been given a value, but is not present in the type '{1}' - The field '{0}' has been given a value, but is not present in the type '{1}' - - - - No assignment given for field '{0}' of type '{1}' - No assignment given for field '{0}' of type '{1}' - - - - Extraneous fields have been given values - Extraneous fields have been given values - - - - Only overrides of abstract and virtual members may be specified in object expressions - Only overrides of abstract and virtual members may be specified in object expressions - - - - The member '{0}' does not correspond to any abstract or virtual method available to override or implement. - The member '{0}' does not correspond to any abstract or virtual method available to override or implement. - - - - The type {0} contains the member '{1}' but it is not a virtual or abstract method that is available to override or implement. - The type {0} contains the member '{1}' but it is not a virtual or abstract method that is available to override or implement. - - - - The member '{0}' does not accept the correct number of arguments. {1} argument(s) are expected, but {2} were given. The required signature is '{3}'.{4} - The member '{0}' does not accept the correct number of arguments. {1} argument(s) are expected, but {2} were given. The required signature is '{3}'.{4} - - - - The member '{0}' does not accept the correct number of arguments. One overload accepts {1} arguments, but {2} were given. The required signature is '{3}'.{4} - The member '{0}' does not accept the correct number of arguments. One overload accepts {1} arguments, but {2} were given. The required signature is '{3}'.{4} - - - - A simple method name is required here - A simple method name is required here - - - - The types System.ValueType, System.Enum, System.Delegate, System.MulticastDelegate and System.Array cannot be used as super types in an object expression or class - The types System.ValueType, System.Enum, System.Delegate, System.MulticastDelegate and System.Array cannot be used as super types in an object expression or class - - - - 'new' must be used with a named type - 'new' must be used with a named type - - - - Cannot create an extension of a sealed type - Cannot create an extension of a sealed type - - - - No arguments may be given when constructing a record value - No arguments may be given when constructing a record value - - - - Interface implementations cannot be given on construction expressions - Interface implementations cannot be given on construction expressions - - - - Object construction expressions may only be used to implement constructors in class types - Object construction expressions may only be used to implement constructors in class types - - - - Only simple bindings of the form 'id = expr' can be used in construction expressions - Only simple bindings of the form 'id = expr' can be used in construction expressions - - - - Objects must be initialized by an object construction expression that calls an inherited object constructor and assigns a value to each field - Objects must be initialized by an object construction expression that calls an inherited object constructor and assigns a value to each field - - - - Expected an interface type - Expected an interface type - - - - Constructor expressions for interfaces do not take arguments - Constructor expressions for interfaces do not take arguments - - - - This object constructor requires arguments - This object constructor requires arguments - - - - 'new' may only be used with object constructors - 'new' may only be used with object constructors - - - - At least one override did not correctly implement its corresponding abstract member - At least one override did not correctly implement its corresponding abstract member - - - - This numeric literal requires that a module '{0}' defining functions FromZero, FromOne, FromInt32, FromInt64 and FromString be in scope - This numeric literal requires that a module '{0}' defining functions FromZero, FromOne, FromInt32, FromInt64 and FromString be in scope - - - - Invalid record construction - Invalid record construction - - - - The expression form {{ expr with ... }} may only be used with record types. To build object types use {{ new Type(...) with ... }} - The expression form {{ expr with ... }} may only be used with record types. To build object types use {{ new Type(...) with ... }} - - - - The inherited type is not an object model type - The inherited type is not an object model type - - - - Object construction expressions (i.e. record expressions with inheritance specifications) may only be used to implement constructors in object model types. Use 'new ObjectType(args)' to construct instances of object model types outside of constructors - Object construction expressions (i.e. record expressions with inheritance specifications) may only be used to implement constructors in object model types. Use 'new ObjectType(args)' to construct instances of object model types outside of constructors - - - - '{{ }}' is not a valid expression. Records must include at least one field. Empty sequences are specified by using Seq.empty or an empty list '[]'. - '{{ }}' is not a valid expression. Records must include at least one field. Empty sequences are specified by using Seq.empty or an empty list '[]'. - - - - This type is not a record type. Values of class and struct types must be created using calls to object constructors. - This type is not a record type. Values of class and struct types must be created using calls to object constructors. - - - - This type is not a record type - This type is not a record type - - - - This construct is ambiguous as part of a computation expression. Nested expressions may be written using 'let _ = (...)' and nested computations using 'let! res = builder {{ ... }}'. - This construct is ambiguous as part of a computation expression. Nested expressions may be written using 'let _ = (...)' and nested computations using 'let! res = builder {{ ... }}'. - - - - This construct is ambiguous as part of a sequence expression. Nested expressions may be written using 'let _ = (...)' and nested sequences using 'yield! seq {{... }}'. - This construct is ambiguous as part of a sequence expression. Nested expressions may be written using 'let _ = (...)' and nested sequences using 'yield! seq {{... }}'. - - - - 'do!' cannot be used within sequence expressions - 'do!' cannot be used within sequence expressions - - - - The use of 'let! x = coll' in sequence expressions is not permitted. Use 'for x in coll' instead. - The use of 'let! x = coll' in sequence expressions is not permitted. Use 'for x in coll' instead. - - - - 'try'/'with' cannot be used within sequence expressions - 'try'/'with' cannot be used within sequence expressions - - - - In sequence expressions, multiple results are generated using 'yield!' - In sequence expressions, multiple results are generated using 'yield!' - - - - Invalid assignment - Invalid assignment - - - - Invalid use of a type name - Invalid use of a type name - - - - This type has no accessible object constructors - This type has no accessible object constructors - - - - Invalid use of an interface type - Invalid use of an interface type - - - - Invalid use of a delegate constructor. Use the syntax 'new Type(args)' or just 'Type(args)'. - Invalid use of a delegate constructor. Use the syntax 'new Type(args)' or just 'Type(args)'. - - - - Property '{0}' is not static - Property '{0}' is not static - - - - Property '{0}' is not readable - Property '{0}' is not readable - - - - This lookup cannot be used here - This lookup cannot be used here - - - - Property '{0}' is static - Property '{0}' is static - - - - Property '{0}' cannot be set - Property '{0}' cannot be set - - - - Constructors must be applied to arguments and cannot be used as first-class values. If necessary use an anonymous function '(fun arg1 ... argN -> new Type(arg1,...,argN))'. - Constructors must be applied to arguments and cannot be used as first-class values. If necessary use an anonymous function '(fun arg1 ... argN -> new Type(arg1,...,argN))'. - - - - The syntax 'expr.id' may only be used with record labels, properties and fields - The syntax 'expr.id' may only be used with record labels, properties and fields - - - - Event '{0}' is static - Event '{0}' is static - - - - Event '{0}' is not static - Event '{0}' is not static - - - - The named argument '{0}' did not match any argument or mutable property - The named argument '{0}' did not match any argument or mutable property - - - - One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. - One or more of the overloads of this method has curried arguments. Consider redesigning these members to take arguments in tupled form. - - - - The unnamed arguments do not form a prefix of the arguments of the method called - The unnamed arguments do not form a prefix of the arguments of the method called - - - - Static optimization conditionals are only for use within the F# library - Static optimization conditionals are only for use within the F# library - - - - The corresponding formal argument is not optional - The corresponding formal argument is not optional - - - - Invalid optional assignment to a property or field - Invalid optional assignment to a property or field - - - - A delegate constructor must be passed a single function value - A delegate constructor must be passed a single function value - - - - A binding cannot be marked both 'use' and 'rec' - A binding cannot be marked both 'use' and 'rec' - - - - The 'VolatileField' attribute may only be used on 'let' bindings in classes - The 'VolatileField' attribute may only be used on 'let' bindings in classes - - - - Attributes are not permitted on 'let' bindings in expressions - Attributes are not permitted on 'let' bindings in expressions - - - - The 'DefaultValue' attribute may only be used on 'val' declarations - The 'DefaultValue' attribute may only be used on 'val' declarations - - - - The 'ConditionalAttribute' attribute may only be used on members - The 'ConditionalAttribute' attribute may only be used on members - - - - This is not a valid name for an active pattern - This is not a valid name for an active pattern - - - - The 'EntryPointAttribute' attribute may only be used on function definitions in modules - The 'EntryPointAttribute' attribute may only be used on function definitions in modules - - - - Mutable values cannot be marked 'inline' - Mutable values cannot be marked 'inline' - - - - Mutable values cannot have generic parameters - Mutable values cannot have generic parameters - - - - Mutable function values should be written 'let mutable f = (fun args -> ...)' - Mutable function values should be written 'let mutable f = (fun args -> ...)' - - - - Only functions may be marked 'inline' - Only functions may be marked 'inline' - - - - A literal value cannot be given the [<ThreadStatic>] or [<ContextStatic>] attributes - A literal value cannot be given the [<ThreadStatic>] or [<ContextStatic>] attributes - - - - A literal value cannot be marked 'mutable' - A literal value cannot be marked 'mutable' - - - - A literal value cannot be marked 'inline' - A literal value cannot be marked 'inline' - - - - Literal values cannot have generic parameters - Literal values cannot have generic parameters - - - - This is not a valid constant expression - This is not a valid constant expression - - - - This type is not accessible from this code location - This type is not accessible from this code location - - - - Unexpected condition in imported assembly: failed to decode AttributeUsage attribute - Unexpected condition in imported assembly: failed to decode AttributeUsage attribute - - - - Unrecognized attribute target. Valid attribute targets are 'assembly', 'module', 'type', 'method', 'property', 'return', 'param', 'field', 'event', 'constructor'. - Unrecognized attribute target. Valid attribute targets are 'assembly', 'module', 'type', 'method', 'property', 'return', 'param', 'field', 'event', 'constructor'. - - - - This attribute is not valid for use on this language element. Assembly attributes should be attached to a 'do ()' declaration, if necessary within an F# module. - This attribute is not valid for use on this language element. Assembly attributes should be attached to a 'do ()' declaration, if necessary within an F# module. - - - - This attribute is not valid for use on this language element - This attribute is not valid for use on this language element - - - - Optional arguments cannot be used in custom attributes - Optional arguments cannot be used in custom attributes - - - - This property cannot be set - This property cannot be set - - - - This property or field was not found on this custom attribute type - This property or field was not found on this custom attribute type - - - - A custom attribute must be a reference type - A custom attribute must be a reference type - - - - The number of args for a custom attribute does not match the expected number of args for the attribute constructor - The number of args for a custom attribute does not match the expected number of args for the attribute constructor - - - - A custom attribute must invoke an object constructor - A custom attribute must invoke an object constructor - - - - Attribute expressions must be calls to object constructors - Attribute expressions must be calls to object constructors - - - - This attribute cannot be used in this version of F# - This attribute cannot be used in this version of F# - - - - Invalid inline specification - Invalid inline specification - - - - 'use' bindings must be of the form 'use <var> = <expr>' - 'use' bindings must be of the form 'use <var> = <expr>' - - - - Abstract members are not permitted in an augmentation - they must be defined as part of the type itself - Abstract members are not permitted in an augmentation - they must be defined as part of the type itself - - - - Method overrides and interface implementations are not permitted here - Method overrides and interface implementations are not permitted here - - - - No abstract or interface member was found that corresponds to this override - No abstract or interface member was found that corresponds to this override - - - - This override takes a different number of arguments to the corresponding abstract member. The following abstract members were found:{0} - This override takes a different number of arguments to the corresponding abstract member. The following abstract members were found:{0} - - - - This method already has a default implementation - This method already has a default implementation - - - - The method implemented by this default is ambiguous - The method implemented by this default is ambiguous - - - - No abstract property was found that corresponds to this override - No abstract property was found that corresponds to this override - - - - This property overrides or implements an abstract property but the abstract property doesn't have a corresponding {0} - This property overrides or implements an abstract property but the abstract property doesn't have a corresponding {0} - - - - Invalid signature for set member - Invalid signature for set member - - - - This new member hides the abstract member '{0}'. Rename the member or use 'override' instead. - This new member hides the abstract member '{0}'. Rename the member or use 'override' instead. - - - - This new member hides the abstract member '{0}' once tuples, functions, units of measure and/or provided types are erased. Rename the member or use 'override' instead. - This new member hides the abstract member '{0}' once tuples, functions, units of measure and/or provided types are erased. Rename the member or use 'override' instead. - - - - Interfaces cannot contain definitions of static initializers - Interfaces cannot contain definitions of static initializers - - - - Interfaces cannot contain definitions of object constructors - Interfaces cannot contain definitions of object constructors - - - - Interfaces cannot contain definitions of member overrides - Interfaces cannot contain definitions of member overrides - - - - Interfaces cannot contain definitions of concrete members. You may need to define a constructor on your type to indicate that the type is a class. - Interfaces cannot contain definitions of concrete members. You may need to define a constructor on your type to indicate that the type is a class. - - - - Constructors cannot be specified in exception augmentations - Constructors cannot be specified in exception augmentations - - - - Structs cannot have an object constructor with no arguments. This is a restriction imposed on all CLI languages as structs automatically support a default constructor. - Structs cannot have an object constructor with no arguments. This is a restriction imposed on all CLI languages as structs automatically support a default constructor. - - - - Constructors cannot be defined for this type - Constructors cannot be defined for this type - - - - Recursive bindings that include member specifications can only occur as a direct augmentation of a type - Recursive bindings that include member specifications can only occur as a direct augmentation of a type - - - - Only simple variable patterns can be bound in 'let rec' constructs - Only simple variable patterns can be bound in 'let rec' constructs - - - - Only record fields and simple, non-recursive 'let' bindings may be marked mutable - Only record fields and simple, non-recursive 'let' bindings may be marked mutable - - - - This member is not sufficiently generic - This member is not sufficiently generic - - - - A declaration may only be the [<Literal>] attribute if a constant value is also given, e.g. 'val x : int = 1' - A declaration may only be the [<Literal>] attribute if a constant value is also given, e.g. 'val x : int = 1' - - - - A declaration may only be given a value in a signature if the declaration has the [<Literal>] attribute - A declaration may only be given a value in a signature if the declaration has the [<Literal>] attribute - - - - Thread-static and context-static variables must be static and given the [<DefaultValue>] attribute to indicate that the value is initialized to the default value on each new thread - Thread-static and context-static variables must be static and given the [<DefaultValue>] attribute to indicate that the value is initialized to the default value on each new thread - - - - Volatile fields must be marked 'mutable' and cannot be thread-static - Volatile fields must be marked 'mutable' and cannot be thread-static - - - - Uninitialized 'val' fields must be mutable and marked with the '[<DefaultValue>]' attribute. Consider using a 'let' binding instead of a 'val' field. - Uninitialized 'val' fields must be mutable and marked with the '[<DefaultValue>]' attribute. Consider using a 'let' binding instead of a 'val' field. - - - - Static 'val' fields in types must be mutable, private and marked with the '[<DefaultValue>]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type. - Static 'val' fields in types must be mutable, private and marked with the '[<DefaultValue>]' attribute. They are initialized to the 'null' or 'zero' value for their type. Consider also using a 'static let mutable' binding in a class type. - - - - This field requires a name - This field requires a name - - - - Invalid namespace, module, type or union case name - Invalid namespace, module, type or union case name - - - - Explicit type declarations for constructors must be of the form 'ty1 * ... * tyN -> resTy'. Parentheses may be required around 'resTy' - Explicit type declarations for constructors must be of the form 'ty1 * ... * tyN -> resTy'. Parentheses may be required around 'resTy' - - - - Return types of union cases must be identical to the type being defined, up to abbreviations - Return types of union cases must be identical to the type being defined, up to abbreviations - - - - This is not a valid value for an enumeration literal - This is not a valid value for an enumeration literal - - - - The type '{0}' is not an interface type - The type '{0}' is not an interface type - - - - Duplicate specification of an interface - Duplicate specification of an interface - - - - A field/val declaration is not permitted here - A field/val declaration is not permitted here - - - - A inheritance declaration is not permitted here - A inheritance declaration is not permitted here - - - - This declaration opens the module '{0}', which is marked as 'RequireQualifiedAccess'. Adjust your code to use qualified references to the elements of the module instead, e.g. 'List.map' instead of 'map'. This change will ensure that your code is robust as new constructs are added to libraries. - This declaration opens the module '{0}', which is marked as 'RequireQualifiedAccess'. Adjust your code to use qualified references to the elements of the module instead, e.g. 'List.map' instead of 'map'. This change will ensure that your code is robust as new constructs are added to libraries. - - - - This declaration opens the namespace or module '{0}' through a partially qualified path. Adjust this code to use the full path of the namespace. This change will make your code more robust as new constructs are added to the F# and CLI libraries. - This declaration opens the namespace or module '{0}' through a partially qualified path. Adjust this code to use the full path of the namespace. This change will make your code more robust as new constructs are added to the F# and CLI libraries. - - - - Local class bindings cannot be marked inline. Consider lifting the definition out of the class or else do not mark it as inline. - Local class bindings cannot be marked inline. Consider lifting the definition out of the class or else do not mark it as inline. - - - - Type abbreviations cannot have members - Type abbreviations cannot have members - - - - As of F# 4.1, the accessibility of type abbreviations is checked at compile-time. Consider changing the accessibility of the type abbreviation. Ignoring this warning might lead to runtime errors. - As of F# 4.1, the accessibility of type abbreviations is checked at compile-time. Consider changing the accessibility of the type abbreviation. Ignoring this warning might lead to runtime errors. - - - - Enumerations cannot have members - Enumerations cannot have members - - - - Measure declarations may have only static members - Measure declarations may have only static members - - - - Structs cannot contain 'do' bindings because the default constructor for structs would not execute these bindings - Structs cannot contain 'do' bindings because the default constructor for structs would not execute these bindings - - - - Structs cannot contain value definitions because the default constructor for structs will not execute these bindings. Consider adding additional arguments to the primary constructor for the type. - Structs cannot contain value definitions because the default constructor for structs will not execute these bindings. Consider adding additional arguments to the primary constructor for the type. - - - - Static value definitions may only be used in types with a primary constructor. Consider adding arguments to the type definition, e.g. 'type X(args) = ...'. - Static value definitions may only be used in types with a primary constructor. Consider adding arguments to the type definition, e.g. 'type X(args) = ...'. - - - - Measure declarations may have only static members: constructors are not available - Measure declarations may have only static members: constructors are not available - - - - A member and a local class binding both have the name '{0}' - A member and a local class binding both have the name '{0}' - - - - Type abbreviations cannot have interface declarations - Type abbreviations cannot have interface declarations - - - - Enumerations cannot have interface declarations - Enumerations cannot have interface declarations - - - - This type is not an interface type - This type is not an interface type - - - - All implemented interfaces should be declared on the initial declaration of the type - All implemented interfaces should be declared on the initial declaration of the type - - - - A default implementation of this interface has already been added because the explicit implementation of the interface was not specified at the definition of the type - A default implementation of this interface has already been added because the explicit implementation of the interface was not specified at the definition of the type - - - - This member is not permitted in an interface implementation - This member is not permitted in an interface implementation - - - - This declaration element is not permitted in an augmentation - This declaration element is not permitted in an augmentation - - - - Types cannot contain nested type definitions - Types cannot contain nested type definitions - - - - type, exception or module - type, exception or module - - - - type or module - type or module - - - - The struct, record or union type '{0}' implements the interface 'System.IStructuralEquatable' explicitly. Apply the 'CustomEquality' attribute to the type. - The struct, record or union type '{0}' implements the interface 'System.IStructuralEquatable' explicitly. Apply the 'CustomEquality' attribute to the type. - - - - The struct, record or union type '{0}' implements the interface 'System.IEquatable<_>' explicitly. Apply the 'CustomEquality' attribute to the type and provide a consistent implementation of the non-generic override 'System.Object.Equals(obj)'. - The struct, record or union type '{0}' implements the interface 'System.IEquatable<_>' explicitly. Apply the 'CustomEquality' attribute to the type and provide a consistent implementation of the non-generic override 'System.Object.Equals(obj)'. - - - - Explicit type specifications cannot be used for exception constructors - Explicit type specifications cannot be used for exception constructors - - - - Exception abbreviations should not have argument lists - Exception abbreviations should not have argument lists - - - - Abbreviations for Common IL exceptions cannot take arguments - Abbreviations for Common IL exceptions cannot take arguments - - - - Exception abbreviations must refer to existing exceptions or F# types deriving from System.Exception - Exception abbreviations must refer to existing exceptions or F# types deriving from System.Exception - - - - Abbreviations for Common IL exception types must have a matching object constructor - Abbreviations for Common IL exception types must have a matching object constructor - - - - Not an exception - Not an exception - - - - Invalid module name - Invalid module name - - - - Invalid type extension - Invalid type extension - - - - The attributes of this type specify multiple kinds for the type - The attributes of this type specify multiple kinds for the type - - - - The kind of the type specified by its attributes does not match the kind implied by its definition - The kind of the type specified by its attributes does not match the kind implied by its definition - - - - Measure definitions cannot have type parameters - Measure definitions cannot have type parameters - - - - This type requires a definition - This type requires a definition - - - - This type abbreviation has one or more declared type parameters that do not appear in the type being abbreviated. Type abbreviations must use all declared type parameters in the type being abbreviated. Consider removing one or more type parameters, or use a concrete type definition that wraps an underlying type, such as 'type C<'a> = C of ...'. - This type abbreviation has one or more declared type parameters that do not appear in the type being abbreviated. Type abbreviations must use all declared type parameters in the type being abbreviated. Consider removing one or more type parameters, or use a concrete type definition that wraps an underlying type, such as 'type C<'a> = C of ...'. - - - - Structs, interfaces, enums and delegates cannot inherit from other types - Structs, interfaces, enums and delegates cannot inherit from other types - - - - Types cannot inherit from multiple concrete types - Types cannot inherit from multiple concrete types - - - - Records, union, abbreviations and struct types cannot have the 'AllowNullLiteral' attribute - Records, union, abbreviations and struct types cannot have the 'AllowNullLiteral' attribute - - - - Types with the 'AllowNullLiteral' attribute may only inherit from or implement types which also allow the use of the null literal - Types with the 'AllowNullLiteral' attribute may only inherit from or implement types which also allow the use of the null literal - - - - Generic types cannot be given the 'StructLayout' attribute - Generic types cannot be given the 'StructLayout' attribute - - - - Only structs and classes without primary constructors may be given the 'StructLayout' attribute - Only structs and classes without primary constructors may be given the 'StructLayout' attribute - - - - The representation of this type is hidden by the signature. It must be given an attribute such as [<Sealed>], [<Class>] or [<Interface>] to indicate the characteristics of the type. - The representation of this type is hidden by the signature. It must be given an attribute such as [<Sealed>], [<Class>] or [<Interface>] to indicate the characteristics of the type. - - - - Only classes may be given the 'AbstractClass' attribute - Only classes may be given the 'AbstractClass' attribute - - - - Only types representing units-of-measure may be given the 'Measure' attribute - Only types representing units-of-measure may be given the 'Measure' attribute - - - - Accessibility modifiers are not permitted on overrides or interface implementations - Accessibility modifiers are not permitted on overrides or interface implementations - - - - Discriminated union types are always sealed - Discriminated union types are always sealed - - - - Record types are always sealed - Record types are always sealed - - - - Assembly code types are always sealed - Assembly code types are always sealed - - - - Struct types are always sealed - Struct types are always sealed - - - - Delegate types are always sealed - Delegate types are always sealed - - - - Enum types are always sealed - Enum types are always sealed - - - - Interface types and delegate types cannot contain fields - Interface types and delegate types cannot contain fields - - - - Abbreviated types cannot be given the 'Sealed' attribute - Abbreviated types cannot be given the 'Sealed' attribute - - - - Cannot inherit a sealed type - Cannot inherit a sealed type - - - - Cannot inherit from interface type. Use interface ... with instead. - Cannot inherit from interface type. Use interface ... with instead. - - - - Struct types cannot contain abstract members - Struct types cannot contain abstract members - - - - Interface types cannot be sealed - Interface types cannot be sealed - - - - Delegate specifications must be of the form 'typ -> typ' - Delegate specifications must be of the form 'typ -> typ' - - - - Delegate specifications must not be curried types. Use 'typ * ... * typ -> typ' for multi-argument delegates, and 'typ -> (typ -> typ)' for delegates returning function values. - Delegate specifications must not be curried types. Use 'typ * ... * typ -> typ' for multi-argument delegates, and 'typ -> (typ -> typ)' for delegates returning function values. - - - - Literal enumerations must have type int, uint, int16, uint16, int64, uint64, byte, sbyte or char - Literal enumerations must have type int, uint, int16, uint16, int64, uint64, byte, sbyte or char - - - - This type definition involves an immediate cyclic reference through an abbreviation - This type definition involves an immediate cyclic reference through an abbreviation - - - - This type definition involves an immediate cyclic reference through a struct field or inheritance relation - This type definition involves an immediate cyclic reference through a struct field or inheritance relation - - - - The syntax 'type X with ...' is reserved for augmentations. Types whose representations are hidden but which have members are now declared in signatures using 'type X = ...'. You may also need to add the '[<Sealed>] attribute to the type definition in the signature - The syntax 'type X with ...' is reserved for augmentations. Types whose representations are hidden but which have members are now declared in signatures using 'type X = ...'. You may also need to add the '[<Sealed>] attribute to the type definition in the signature - - - - Members that extend interface, delegate or enum types must be placed in a module separate to the definition of the type. This module must either have the AutoOpen attribute or be opened explicitly by client code to bring the extension members into scope. - Members that extend interface, delegate or enum types must be placed in a module separate to the definition of the type. This module must either have the AutoOpen attribute or be opened explicitly by client code to bring the extension members into scope. - - - - One or more of the declared type parameters for this type extension have a missing or wrong type constraint not matching the original type constraints on '{0}' - One or more of the declared type parameters for this type extension have a missing or wrong type constraint not matching the original type constraints on '{0}' - - - - Type definitions may only have one 'inherit' specification and it must be the first declaration - Type definitions may only have one 'inherit' specification and it must be the first declaration - - - - 'let' and 'do' bindings must come before member and interface definitions in type definitions - 'let' and 'do' bindings must come before member and interface definitions in type definitions - - - - This 'inherit' declaration specifies the inherited type but no arguments. Consider supplying arguments, e.g. 'inherit BaseType(args)'. - This 'inherit' declaration specifies the inherited type but no arguments. Consider supplying arguments, e.g. 'inherit BaseType(args)'. - - - - This 'inherit' declaration has arguments, but is not in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - This 'inherit' declaration has arguments, but is not in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - - - - This definition may only be used in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - This definition may only be used in a type with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - - - - Type abbreviations cannot have augmentations - Type abbreviations cannot have augmentations - - - - The path '{0}' is a namespace. A module abbreviation may not abbreviate a namespace. - The path '{0}' is a namespace. A module abbreviation may not abbreviate a namespace. - - - - The type '{0}' is used in an invalid way. A value prior to '{1}' has an inferred type involving '{2}', which is an invalid forward reference. - The type '{0}' is used in an invalid way. A value prior to '{1}' has an inferred type involving '{2}', which is an invalid forward reference. - - - - The member '{0}' is used in an invalid way. A use of '{1}' has been inferred prior to the definition of '{2}', which is an invalid forward reference. - The member '{0}' is used in an invalid way. A use of '{1}' has been inferred prior to the definition of '{2}', which is an invalid forward reference. - - - - The attribute 'AutoOpen(\"{0}\")' in the assembly '{1}' did not refer to a valid module or namespace in that assembly and has been ignored - The attribute 'AutoOpen(\"{0}\")' in the assembly '{1}' did not refer to a valid module or namespace in that assembly and has been ignored - - - - Undefined value '{0}' - Undefined value '{0}' - - - - Label {0} not found - Label {0} not found - - - - Incorrect number of type arguments to local call - Incorrect number of type arguments to local call - - - - Dynamic invocation of {0} is not supported - Dynamic invocation of {0} is not supported - - - - Taking the address of a literal field is invalid - Taking the address of a literal field is invalid - - - - This operation involves taking the address of a value '{0}' represented using a local variable or other special representation. This is invalid. - This operation involves taking the address of a value '{0}' represented using a local variable or other special representation. This is invalid. - - - - Custom marshallers cannot be specified in F# code. Consider using a C# helper function. - Custom marshallers cannot be specified in F# code. Consider using a C# helper function. - - - - The MarshalAs attribute could not be decoded - The MarshalAs attribute could not be decoded - - - - The signature for this external function contains type parameters. Constrain the argument and return types to indicate the types of the corresponding C function. - The signature for this external function contains type parameters. Constrain the argument and return types to indicate the types of the corresponding C function. - - - - The DllImport attribute could not be decoded - The DllImport attribute could not be decoded - - - - Literal fields cannot be set - Literal fields cannot be set - - - - GenSetStorage: {0} was represented as a static method but was not an appropriate lambda expression - GenSetStorage: {0} was represented as a static method but was not an appropriate lambda expression - - - - Mutable variables cannot escape their method - Mutable variables cannot escape their method - - - - Compiler error: unexpected unrealized value - Compiler error: unexpected unrealized value - - - - Main module of program is empty: nothing will happen when it is run - Main module of program is empty: nothing will happen when it is run - - - - This type cannot be used for a literal field - This type cannot be used for a literal field - - - - Unexpected GetSet annotation on a property - Unexpected GetSet annotation on a property - - - - The FieldOffset attribute could not be decoded - The FieldOffset attribute could not be decoded - - - - The StructLayout attribute could not be decoded - The StructLayout attribute could not be decoded - - - - The DefaultAugmentation attribute could not be decoded - The DefaultAugmentation attribute could not be decoded - - - - Reflected definitions cannot contain uses of the prefix splice operator '%' - Reflected definitions cannot contain uses of the prefix splice operator '%' - - - - Problem with codepage '{0}': {1} - Problem with codepage '{0}': {1} - - - - Copyright (c) Microsoft Corporation. All Rights Reserved. - Copyright (c) Microsoft Corporation. All Rights Reserved. - - - - Freely distributed under the MIT Open Source License. https://github.com/Microsoft/visualfsharp/blob/master/License.txt - Freely distributed under the MIT Open Source License. https://github.com/Microsoft/visualfsharp/blob/master/License.txt - - - - Name of the output file (Short form: -o) - Name of the output file (Short form: -o) - - - - Build a console executable - Build a console executable - - - - Build a Windows executable - Build a Windows executable - - - - Build a library (Short form: -a) - Build a library (Short form: -a) - - - - Build a module that can be added to another assembly - Build a module that can be added to another assembly - - - - Delay-sign the assembly using only the public portion of the strong name key - Delay-sign the assembly using only the public portion of the strong name key - - - - Public-sign the assembly using only the public portion of the strong name key, and mark the assembly as signed - Public-sign the assembly using only the public portion of the strong name key, and mark the assembly as signed - - - - Write the xmldoc of the assembly to the given file - Write the xmldoc of the assembly to the given file - - - - Specify a strong name key file - Specify a strong name key file - - - - Specify a strong name key container - Specify a strong name key container - - - - Limit which platforms this code can run on: x86, Itanium, x64, anycpu32bitpreferred, or anycpu. The default is anycpu. - Limit which platforms this code can run on: x86, Itanium, x64, anycpu32bitpreferred, or anycpu. The default is anycpu. - - - - Only include optimization information essential for implementing inlined constructs. Inhibits cross-module inlining but improves binary compatibility. - Only include optimization information essential for implementing inlined constructs. Inhibits cross-module inlining but improves binary compatibility. - - - - Don't add a resource to the generated assembly containing F#-specific metadata - Don't add a resource to the generated assembly containing F#-specific metadata - - - - Print the inferred interface of the assembly to a file - Print the inferred interface of the assembly to a file - - - - Reference an assembly (Short form: -r) - Reference an assembly (Short form: -r) - - - - Specify a Win32 resource file (.res) - Specify a Win32 resource file (.res) - - - - Specify a Win32 manifest file - Specify a Win32 manifest file - - - - Do not include the default Win32 manifest - Do not include the default Win32 manifest - - - - Embed all source files in the portable PDB file - Embed all source files in the portable PDB file - - - - Embed specific source files in the portable PDB file - Embed specific source files in the portable PDB file - - - - Source link information file to embed in the portable PDB file - Source link information file to embed in the portable PDB file - - - - --embed switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded) - --embed switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded) - - - - --sourcelink switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded) - --sourcelink switch only supported when emitting a Portable PDB (--debug:portable or --debug:embedded) - - - - Source file is too large to embed in a portable PDB - Source file is too large to embed in a portable PDB - - - - Embed the specified managed resource - Embed the specified managed resource - - - - Link the specified resource to this assembly where the resinfo format is <file>[,<string name>[,public|private]] - Link the specified resource to this assembly where the resinfo format is <file>[,<string name>[,public|private]] - - - - Emit debug information (Short form: -g) - Emit debug information (Short form: -g) - - - - Specify debugging type: full, portable, embedded, pdbonly. ('{0}' is the default if no debuggging type specified and enables attaching a debugger to a running program, 'portable' is a cross-platform format, 'embedded' is a cross-platform format embedded into the output file). - Specify debugging type: full, portable, embedded, pdbonly. ('{0}' is the default if no debuggging type specified and enables attaching a debugger to a running program, 'portable' is a cross-platform format, 'embedded' is a cross-platform format embedded into the output file). - - - - Enable optimizations (Short form: -O) - Enable optimizations (Short form: -O) - - - - Enable or disable tailcalls - Enable or disable tailcalls - - - - Produce a deterministic assembly (including module version GUID and timestamp) - Produce a deterministic assembly (including module version GUID and timestamp) - - - - Enable or disable cross-module optimizations - Enable or disable cross-module optimizations - - - - Report all warnings as errors - Report all warnings as errors - - - - Report specific warnings as errors - Report specific warnings as errors - - - - Set a warning level (0-5) - Set a warning level (0-5) - - - - Disable specific warning messages - Disable specific warning messages - - - - Enable specific warnings that may be off by default - Enable specific warnings that may be off by default - - - - Generate overflow checks - Generate overflow checks - - - - Define conditional compilation symbols (Short form: -d) - Define conditional compilation symbols (Short form: -d) - - - - Ignore ML compatibility warnings - Ignore ML compatibility warnings - - - - - Display this usage message (Short form: -?) - Display this usage message (Short form: -?) - - - - Read response file for more options - Read response file for more options - - - - Specify the codepage used to read source files - Specify the codepage used to read source files - - - - Output messages in UTF-8 encoding - Output messages in UTF-8 encoding - - - - Output messages with fully qualified paths - Output messages with fully qualified paths - - - - Specify a directory for the include path which is used to resolve source files and assemblies (Short form: -I) - Specify a directory for the include path which is used to resolve source files and assemblies (Short form: -I) - - - - Base address for the library to be built - Base address for the library to be built - - - - Do not reference the default CLI assemblies by default - Do not reference the default CLI assemblies by default - - - - Statically link the F# library and all referenced DLLs that depend on it into the assembly being generated - Statically link the F# library and all referenced DLLs that depend on it into the assembly being generated - - - - Statically link the given assembly and all referenced DLLs that depend on this assembly. Use an assembly name e.g. mylib, not a DLL name. - Statically link the given assembly and all referenced DLLs that depend on this assembly. Use an assembly name e.g. mylib, not a DLL name. - - - - Use a resident background compilation service to improve compiler startup times. - Use a resident background compilation service to improve compiler startup times. - - - - Name the output debug file - Name the output debug file - - - - Resolve assembly references using directory-based rules rather than MSBuild resolution - Resolve assembly references using directory-based rules rather than MSBuild resolution - - - - Unrecognized target '{0}', expected 'exe', 'winexe', 'library' or 'module' - Unrecognized target '{0}', expected 'exe', 'winexe', 'library' or 'module' - - - - Unrecognized debug type '{0}', expected 'pdbonly' or 'full' - Unrecognized debug type '{0}', expected 'pdbonly' or 'full' - - - - Invalid warning level '{0}' - Invalid warning level '{0}' - - - - Short form of '{0}' - Short form of '{0}' - - - - The command-line option '--cliroot' has been deprecated. Use an explicit reference to a specific copy of mscorlib.dll instead. - The command-line option '--cliroot' has been deprecated. Use an explicit reference to a specific copy of mscorlib.dll instead. - - - - Use to override where the compiler looks for mscorlib.dll and framework components - Use to override where the compiler looks for mscorlib.dll and framework components - - - - - OUTPUT FILES - - - OUTPUT FILES - - - - - - INPUT FILES - - - INPUT FILES - - - - - - RESOURCES - - - RESOURCES - - - - - - CODE GENERATION - - - CODE GENERATION - - - - - - ADVANCED - - - ADVANCED - - - - - - MISCELLANEOUS - - - MISCELLANEOUS - - - - - - LANGUAGE - - - LANGUAGE - - - - - - ERRORS AND WARNINGS - - - ERRORS AND WARNINGS - - - - - Unknown --test argument: '{0}' - Unknown --test argument: '{0}' - - - - Unrecognized platform '{0}', valid values are 'x86', 'x64', 'Itanium', 'anycpu32bitpreferred', and 'anycpu' - Unrecognized platform '{0}', valid values are 'x86', 'x64', 'Itanium', 'anycpu32bitpreferred', and 'anycpu' - - - - The command-line option '{0}' is for test purposes only - The command-line option '{0}' is for test purposes only - - - - The command-line option '{0}' has been deprecated - The command-line option '{0}' has been deprecated - - - - The command-line option '{0}' has been deprecated. Use '{1}' instead. - The command-line option '{0}' has been deprecated. Use '{1}' instead. - - - - The command-line option '{0}' has been deprecated. HTML document generation is now part of the F# Power Pack, via the tool FsHtmlDoc.exe. - The command-line option '{0}' has been deprecated. HTML document generation is now part of the F# Power Pack, via the tool FsHtmlDoc.exe. - - - - Output warning and error messages in color - Output warning and error messages in color - - - - Enable high-entropy ASLR - Enable high-entropy ASLR - - - - Specify subsystem version of this assembly - Specify subsystem version of this assembly - - - - Specify target framework profile of this assembly. Valid values are mscorlib, netcore or netstandard. Default - mscorlib - Specify target framework profile of this assembly. Valid values are mscorlib, netcore or netstandard. Default - mscorlib - - - - Emit debug information in quotations - Emit debug information in quotations - - - - Specify the preferred output language culture name (e.g. es-ES, ja-JP) - Specify the preferred output language culture name (e.g. es-ES, ja-JP) - - - - Don't copy FSharp.Core.dll along the produced binaries - Don't copy FSharp.Core.dll along the produced binaries - - - - Invalid version '{0}' for '--subsystemversion'. The version must be 4.00 or greater. - Invalid version '{0}' for '--subsystemversion'. The version must be 4.00 or greater. - - - - Invalid value '{0}' for '--targetprofile', valid values are 'mscorlib', 'netcore' or 'netstandard'. - Invalid value '{0}' for '--targetprofile', valid values are 'mscorlib', 'netcore' or 'netstandard'. - - - - Full name - Full name - - - - and {0} other overloads - and {0} other overloads - - - - union case - union case - - - - active pattern result - active pattern result - - - - active recognizer - active recognizer - - - - field - field - - - - event - event - - - - property - property - - - - extension - extension - - - - custom operation - custom operation - - - - argument - argument - - - - patvar - patvar - - - - namespace - namespace - - - - module - module - - - - namespace/module - namespace/module - - - - from {0} - from {0} - - - - also from {0} - also from {0} - - - - generated property - generated property - - - - generated type - generated type - - - - Found by AssemblyFolders registry key - Found by AssemblyFolders registry key - - - - Found by AssemblyFoldersEx registry key - Found by AssemblyFoldersEx registry key - - - - .NET Framework - .NET Framework - - - - Global Assembly Cache - Global Assembly Cache - - - - Recursive class hierarchy in type '{0}' - Recursive class hierarchy in type '{0}' - - - - Invalid recursive reference to an abstract slot - Invalid recursive reference to an abstract slot - - - - The event '{0}' has a non-standard type. If this event is declared in another CLI language, you may need to access this event using the explicit {1} and {2} methods for the event. If this event is declared in F#, make the type of the event an instantiation of either 'IDelegateEvent<_>' or 'IEvent<_,_>'. - The event '{0}' has a non-standard type. If this event is declared in another CLI language, you may need to access this event using the explicit {1} and {2} methods for the event. If this event is declared in F#, make the type of the event an instantiation of either 'IDelegateEvent<_>' or 'IEvent<_,_>'. - - - - The type '{0}' is not accessible from this code location - The type '{0}' is not accessible from this code location - - - - The union cases or fields of the type '{0}' are not accessible from this code location - The union cases or fields of the type '{0}' are not accessible from this code location - - - - The value '{0}' is not accessible from this code location - The value '{0}' is not accessible from this code location - - - - The union case '{0}' is not accessible from this code location - The union case '{0}' is not accessible from this code location - - - - The record, struct or class field '{0}' is not accessible from this code location - The record, struct or class field '{0}' is not accessible from this code location - - - - The struct or class field '{0}' is not accessible from this code location - The struct or class field '{0}' is not accessible from this code location - - - - This construct is experimental - This construct is experimental - - - - No Invoke methods found for delegate type - No Invoke methods found for delegate type - - - - More than one Invoke method found for delegate type - More than one Invoke method found for delegate type - - - - Delegates are not allowed to have curried signatures - Delegates are not allowed to have curried signatures - - - - Unexpected Expr.TyChoose - Unexpected Expr.TyChoose - - - - Note: Lambda-lifting optimizations have not been applied because of the use of this local constrained generic function as a first class value. Adding type constraints may resolve this condition. - Note: Lambda-lifting optimizations have not been applied because of the use of this local constrained generic function as a first class value. Adding type constraints may resolve this condition. - - - - Identifiers containing '@' are reserved for use in F# code generation - Identifiers containing '@' are reserved for use in F# code generation - - - - The identifier '{0}' is reserved for future use by F# - The identifier '{0}' is reserved for future use by F# - - - - Missing variable '{0}' - Missing variable '{0}' - - - - Partial active patterns may only generate one result - Partial active patterns may only generate one result - - - - The type '{0}' is required here and is unavailable. You must add a reference to assembly '{1}'. - The type '{0}' is required here and is unavailable. You must add a reference to assembly '{1}'. - - - - A reference to the type '{0}' in assembly '{1}' was found, but the type could not be found in that assembly - A reference to the type '{0}' in assembly '{1}' was found, but the type could not be found in that assembly - - - - Internal error or badly formed metadata: not enough type parameters were in scope while importing - Internal error or badly formed metadata: not enough type parameters were in scope while importing - - - - A reference to the DLL {0} is required by assembly {1}. The imported type {2} is located in the first assembly and could not be resolved. - A reference to the DLL {0} is required by assembly {1}. The imported type {2} is located in the first assembly and could not be resolved. - - - - An imported assembly uses the type '{0}' but that type is not public - An imported assembly uses the type '{0}' but that type is not public - - - - The value '{0}' was marked inline but its implementation makes use of an internal or private function which is not sufficiently accessible - The value '{0}' was marked inline but its implementation makes use of an internal or private function which is not sufficiently accessible - - - - The value '{0}' was marked inline but was not bound in the optimization environment - The value '{0}' was marked inline but was not bound in the optimization environment - - - - Local value {0} not found during optimization - Local value {0} not found during optimization - - - - A value marked as 'inline' has an unexpected value - A value marked as 'inline' has an unexpected value - - - - A value marked as 'inline' could not be inlined - A value marked as 'inline' could not be inlined - - - - Failed to inline the value '{0}' marked 'inline', perhaps because a recursive value was marked 'inline' - Failed to inline the value '{0}' marked 'inline', perhaps because a recursive value was marked 'inline' - - - - Recursive ValValue {0} - Recursive ValValue {0} - - - - The indentation of this 'in' token is incorrect with respect to the corresponding 'let' - The indentation of this 'in' token is incorrect with respect to the corresponding 'let' - - - - Possible incorrect indentation: this token is offside of context started at position {0}. Try indenting this token further or using standard formatting conventions. - Possible incorrect indentation: this token is offside of context started at position {0}. Try indenting this token further or using standard formatting conventions. - - - - The '|' tokens separating rules of this pattern match are misaligned by one column. Consider realigning your code or using further indentation. - The '|' tokens separating rules of this pattern match are misaligned by one column. Consider realigning your code or using further indentation. - - - - Invalid module/expression/type - Invalid module/expression/type - - - - Multiple types exist called '{0}', taking different numbers of generic parameters. Provide a type instantiation to disambiguate the type resolution, e.g. '{1}'. - Multiple types exist called '{0}', taking different numbers of generic parameters. Provide a type instantiation to disambiguate the type resolution, e.g. '{1}'. - - - - The instantiation of the generic type '{0}' is missing and can't be inferred from the arguments or return type of this member. Consider providing a type instantiation when accessing this type, e.g. '{1}'. - The instantiation of the generic type '{0}' is missing and can't be inferred from the arguments or return type of this member. Consider providing a type instantiation when accessing this type, e.g. '{1}'. - - - - 'global' may only be used as the first name in a qualified path - 'global' may only be used as the first name in a qualified path - - - - This is not a constructor or literal, or a constructor is being used incorrectly - This is not a constructor or literal, or a constructor is being used incorrectly - - - - Unexpected empty long identifier - Unexpected empty long identifier - - - - The record type '{0}' does not contain a label '{1}'. - The record type '{0}' does not contain a label '{1}'. - - - - Invalid field label - Invalid field label - - - - Invalid expression '{0}' - Invalid expression '{0}' - - - - No constructors are available for the type '{0}' - No constructors are available for the type '{0}' - - - - The union type for union case '{0}' was defined with the RequireQualifiedAccessAttribute. Include the name of the union type ('{1}') in the name you are using. - The union type for union case '{0}' was defined with the RequireQualifiedAccessAttribute. Include the name of the union type ('{1}') in the name you are using. - - - - The record type for the record field '{0}' was defined with the RequireQualifiedAccessAttribute. Include the name of the record type ('{1}') in the name you are using. - The record type for the record field '{0}' was defined with the RequireQualifiedAccessAttribute. Include the name of the record type ('{1}') in the name you are using. - - - - Unexpected error creating debug information file '{0}' - Unexpected error creating debug information file '{0}' - - - - This number is outside the allowable range for this integer type - This number is outside the allowable range for this integer type - - - - '{0}' is not permitted as a character in operator names and is reserved for future use - '{0}' is not permitted as a character in operator names and is reserved for future use - - - - Unexpected character '{0}' - Unexpected character '{0}' - - - - This byte array literal contains characters that do not encode as a single byte - This byte array literal contains characters that do not encode as a single byte - - - - Identifiers followed by '{0}' are reserved for future use - Identifiers followed by '{0}' are reserved for future use - - - - This number is outside the allowable range for 8-bit signed integers - This number is outside the allowable range for 8-bit signed integers - - - - This number is outside the allowable range for hexadecimal 8-bit signed integers - This number is outside the allowable range for hexadecimal 8-bit signed integers - - - - This number is outside the allowable range for 8-bit unsigned integers - This number is outside the allowable range for 8-bit unsigned integers - - - - This number is outside the allowable range for 16-bit signed integers - This number is outside the allowable range for 16-bit signed integers - - - - This number is outside the allowable range for 16-bit unsigned integers - This number is outside the allowable range for 16-bit unsigned integers - - - - This number is outside the allowable range for 32-bit signed integers - This number is outside the allowable range for 32-bit signed integers - - - - This number is outside the allowable range for 32-bit unsigned integers - This number is outside the allowable range for 32-bit unsigned integers - - - - This number is outside the allowable range for 64-bit signed integers - This number is outside the allowable range for 64-bit signed integers - - - - This number is outside the allowable range for 64-bit unsigned integers - This number is outside the allowable range for 64-bit unsigned integers - - - - This number is outside the allowable range for signed native integers - This number is outside the allowable range for signed native integers - - - - This number is outside the allowable range for unsigned native integers - This number is outside the allowable range for unsigned native integers - - - - Invalid floating point number - Invalid floating point number - - - - This number is outside the allowable range for decimal literals - This number is outside the allowable range for decimal literals - - - - This number is outside the allowable range for 32-bit floats - This number is outside the allowable range for 32-bit floats - - - - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - This is not a valid numeric literal. Valid numeric literals include 1, 0x1, 0b0001 (int), 1u (uint32), 1L (int64), 1UL (uint64), 1s (int16), 1y (sbyte), 1uy (byte), 1.0 (float), 1.0f (float32), 1.0m (decimal), 1I (BigInteger). - - - - This is not a valid byte literal - This is not a valid byte literal - - - - This is not a valid character literal - This is not a valid character literal - - - - This Unicode encoding is only valid in string literals - This Unicode encoding is only valid in string literals - - - - This token is reserved for future use - This token is reserved for future use - - - - TABs are not allowed in F# code unless the #indent \"off\" option is used - TABs are not allowed in F# code unless the #indent \"off\" option is used - - - - Invalid line number: '{0}' - Invalid line number: '{0}' - - - - #if directive must appear as the first non-whitespace character on a line - #if directive must appear as the first non-whitespace character on a line - - - - #else has no matching #if - #else has no matching #if - - - - #endif required for #else - #endif required for #else - - - - #else directive must appear as the first non-whitespace character on a line - #else directive must appear as the first non-whitespace character on a line - - - - #endif has no matching #if - #endif has no matching #if - - - - #endif directive must appear as the first non-whitespace character on a line - #endif directive must appear as the first non-whitespace character on a line - - - - #if directive should be immediately followed by an identifier - #if directive should be immediately followed by an identifier - - - - Syntax error. Wrong nested #endif, unexpected tokens before it. - Syntax error. Wrong nested #endif, unexpected tokens before it. - - - - #! may only appear as the first line at the start of a file. - #! may only appear as the first line at the start of a file. - - - - Expected single line comment or end of line - Expected single line comment or end of line - - - - Infix operator member '{0}' has no arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - Infix operator member '{0}' has no arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - - - - Infix operator member '{0}' has {1} initial argument(s). Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - Infix operator member '{0}' has {1} initial argument(s). Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - - - - Infix operator member '{0}' has extra curried arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - Infix operator member '{0}' has extra curried arguments. Expected a tuple of 2 arguments, e.g. static member (+) (x,y) = ... - - - - All record, union and struct types in FSharp.Core.dll must be explicitly labelled with 'StructuralComparison' or 'NoComparison' - All record, union and struct types in FSharp.Core.dll must be explicitly labelled with 'StructuralComparison' or 'NoComparison' - - - - The struct, record or union type '{0}' has the 'StructuralComparison' attribute but the type parameter '{1}' does not satisfy the 'comparison' constraint. Consider adding the 'comparison' constraint to the type parameter - The struct, record or union type '{0}' has the 'StructuralComparison' attribute but the type parameter '{1}' does not satisfy the 'comparison' constraint. Consider adding the 'comparison' constraint to the type parameter - - - - The struct, record or union type '{0}' has the 'StructuralComparison' attribute but the component type '{1}' does not satisfy the 'comparison' constraint - The struct, record or union type '{0}' has the 'StructuralComparison' attribute but the component type '{1}' does not satisfy the 'comparison' constraint - - - - The struct, record or union type '{0}' is not structurally comparable because the type parameter {1} does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '{2}' to clarify that the type is not comparable - The struct, record or union type '{0}' is not structurally comparable because the type parameter {1} does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '{2}' to clarify that the type is not comparable - - - - The struct, record or union type '{0}' is not structurally comparable because the type '{1}' does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '{2}' to clarify that the type is not comparable - The struct, record or union type '{0}' is not structurally comparable because the type '{1}' does not satisfy the 'comparison' constraint. Consider adding the 'NoComparison' attribute to the type '{2}' to clarify that the type is not comparable - - - - The struct, record or union type '{0}' does not support structural equality because the type parameter {1} does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '{2}' to clarify that the type does not support structural equality - The struct, record or union type '{0}' does not support structural equality because the type parameter {1} does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '{2}' to clarify that the type does not support structural equality - - - - The struct, record or union type '{0}' does not support structural equality because the type '{1}' does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '{2}' to clarify that the type does not support structural equality - The struct, record or union type '{0}' does not support structural equality because the type '{1}' does not satisfy the 'equality' constraint. Consider adding the 'NoEquality' attribute to the type '{2}' to clarify that the type does not support structural equality - - - - The struct, record or union type '{0}' has the 'StructuralEquality' attribute but the type parameter '{1}' does not satisfy the 'equality' constraint. Consider adding the 'equality' constraint to the type parameter - The struct, record or union type '{0}' has the 'StructuralEquality' attribute but the type parameter '{1}' does not satisfy the 'equality' constraint. Consider adding the 'equality' constraint to the type parameter - - - - The struct, record or union type '{0}' has the 'StructuralEquality' attribute but the component type '{1}' does not satisfy the 'equality' constraint - The struct, record or union type '{0}' has the 'StructuralEquality' attribute but the component type '{1}' does not satisfy the 'equality' constraint - - - - Each argument of the primary constructor for a struct must be given a type, for example 'type S(x1:int, x2: int) = ...'. These arguments determine the fields of the struct. - Each argument of the primary constructor for a struct must be given a type, for example 'type S(x1:int, x2: int) = ...'. These arguments determine the fields of the struct. - - - - The value '{0}' is unused - The value '{0}' is unused - - - - The recursive object reference '{0}' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference. - The recursive object reference '{0}' is unused. The presence of a recursive object reference adds runtime initialization checks to members in this and derived types. Consider removing this recursive object reference. - - - - A getter property may have at most one argument group - A getter property may have at most one argument group - - - - A setter property may have at most two argument groups - A setter property may have at most two argument groups - - - - Invalid property getter or setter - Invalid property getter or setter - - - - An indexer property must be given at least one argument - An indexer property must be given at least one argument - - - - This operation accesses a mutable top-level value defined in another assembly in an unsupported way. The value cannot be accessed through its address. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...', and if necessary assigning the value back after the completion of the operation - This operation accesses a mutable top-level value defined in another assembly in an unsupported way. The value cannot be accessed through its address. Consider copying the expression to a mutable local, e.g. 'let mutable x = ...', and if necessary assigning the value back after the completion of the operation - - - - Remove spaces between the type name and type parameter, e.g. \"type C<'T>\", not type \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - Remove spaces between the type name and type parameter, e.g. \"type C<'T>\", not type \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - - - - Remove spaces between the type name and type parameter, e.g. \"C<'T>\", not \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - Remove spaces between the type name and type parameter, e.g. \"C<'T>\", not \"C <'T>\". Type parameters must be placed directly adjacent to the type name. - - - - The use of the type syntax 'int C' and 'C <int>' is not permitted here. Consider adjusting this type to be written in the form 'C<int>' - The use of the type syntax 'int C' and 'C <int>' is not permitted here. Consider adjusting this type to be written in the form 'C<int>' - - - - The module/namespace '{0}' from compilation unit '{1}' did not contain the module/namespace '{2}' - The module/namespace '{0}' from compilation unit '{1}' did not contain the module/namespace '{2}' - - - - The module/namespace '{0}' from compilation unit '{1}' did not contain the val '{2}' - The module/namespace '{0}' from compilation unit '{1}' did not contain the val '{2}' - - - - The module/namespace '{0}' from compilation unit '{1}' did not contain the namespace, module or type '{2}' - The module/namespace '{0}' from compilation unit '{1}' did not contain the namespace, module or type '{2}' - - - - The 'UseNullAsTrueValue' attribute flag may only be used with union types that have one nullary case and at least one non-nullary case - The 'UseNullAsTrueValue' attribute flag may only be used with union types that have one nullary case and at least one non-nullary case - - - - The parameter '{0}' was inferred to have byref type. Parameters of byref type must be given an explicit type annotation, e.g. 'x1: byref<int>'. When used, a byref parameter is implicitly dereferenced. - The parameter '{0}' was inferred to have byref type. Parameters of byref type must be given an explicit type annotation, e.g. 'x1: byref<int>'. When used, a byref parameter is implicitly dereferenced. - - - - The generic member '{0}' has been used at a non-uniform instantiation prior to this program point. Consider reordering the members so this member occurs first. Alternatively, specify the full type of the member explicitly, including argument types, return type and any additional generic parameters and constraints. - The generic member '{0}' has been used at a non-uniform instantiation prior to this program point. Consider reordering the members so this member occurs first. Alternatively, specify the full type of the member explicitly, including argument types, return type and any additional generic parameters and constraints. - - - - The attribute '{0}' appears in both the implementation and the signature, but the attribute arguments differ. Only the attribute from the signature will be included in the compiled code. - The attribute '{0}' appears in both the implementation and the signature, but the attribute arguments differ. Only the attribute from the signature will be included in the compiled code. - - - - Cannot call an abstract base member: '{0}' - Cannot call an abstract base member: '{0}' - - - - Could not resolve the ambiguity in the use of a generic construct with an 'unmanaged' constraint at or near this position - Could not resolve the ambiguity in the use of a generic construct with an 'unmanaged' constraint at or near this position - - - - This construct is for ML compatibility. {0}. You can disable this warning by using '--mlcompatibility' or '--nowarn:62'. - This construct is for ML compatibility. {0}. You can disable this warning by using '--mlcompatibility' or '--nowarn:62'. - - - - The type '{0}' has been marked as having an Explicit layout, but the field '{1}' has not been marked with the 'FieldOffset' attribute - The type '{0}' has been marked as having an Explicit layout, but the field '{1}' has not been marked with the 'FieldOffset' attribute - - - - Interfaces inherited by other interfaces should be declared using 'inherit ...' instead of 'interface ...' - Interfaces inherited by other interfaces should be declared using 'inherit ...' instead of 'interface ...' - - - - Invalid prefix operator - Invalid prefix operator - - - - Invalid operator definition. Prefix operator definitions must use a valid prefix operator name. - Invalid operator definition. Prefix operator definitions must use a valid prefix operator name. - - - - The file extensions '.ml' and '.mli' are for ML compatibility - The file extensions '.ml' and '.mli' are for ML compatibility - - - - Consider using a file with extension '.ml' or '.mli' instead - Consider using a file with extension '.ml' or '.mli' instead - - - - Active pattern '{0}' is not a function - Active pattern '{0}' is not a function - - - - Active pattern '{0}' has a result type containing type variables that are not determined by the input. The common cause is a when a result case is not mentioned, e.g. 'let (|A|B|) (x:int) = A x'. This can be fixed with a type constraint, e.g. 'let (|A|B|) (x:int) : Choice<int,unit> = A x' - Active pattern '{0}' has a result type containing type variables that are not determined by the input. The common cause is a when a result case is not mentioned, e.g. 'let (|A|B|) (x:int) = A x'. This can be fixed with a type constraint, e.g. 'let (|A|B|) (x:int) : Choice<int,unit> = A x' - - - - The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) - The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit) - - - - Optional arguments must come at the end of the argument list, after any non-optional arguments - Optional arguments must come at the end of the argument list, after any non-optional arguments - - - - Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes - Attribute 'System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes - - - - Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead. - Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead. - - - - The name of the MDB file must be <assembly-file-name>.mdb. The --pdb option will be ignored. - The name of the MDB file must be <assembly-file-name>.mdb. The --pdb option will be ignored. - - - - MDB generation failed. Could not find compatible member {0} - MDB generation failed. Could not find compatible member {0} - - - - Cannot generate MDB debug information. Failed to load the 'MonoSymbolWriter' type from the 'Mono.CompilerServices.SymbolWriter.dll' assembly. - Cannot generate MDB debug information. Failed to load the 'MonoSymbolWriter' type from the 'Mono.CompilerServices.SymbolWriter.dll' assembly. - - - - The union case named '{0}' conflicts with the generated type '{1}' - The union case named '{0}' conflicts with the generated type '{1}' - - - - ReflectedDefinitionAttribute may not be applied to an instance member on a struct type, because the instance member takes an implicit 'this' byref parameter - ReflectedDefinitionAttribute may not be applied to an instance member on a struct type, because the instance member takes an implicit 'this' byref parameter - - - - DLLImport bindings must be static members in a class or function definitions in a module - DLLImport bindings must be static members in a class or function definitions in a module - - - - When mscorlib.dll or FSharp.Core.dll is explicitly referenced the {0} option must also be passed - When mscorlib.dll or FSharp.Core.dll is explicitly referenced the {0} option must also be passed - - - - FSharp.Core.sigdata not found alongside FSharp.Core. File expected in {0}. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required. - FSharp.Core.sigdata not found alongside FSharp.Core. File expected in {0}. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required. - - - - File '{0}' not found alongside FSharp.Core. File expected in {1}. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required. - File '{0}' not found alongside FSharp.Core. File expected in {1}. Consider upgrading to a more recent version of FSharp.Core, where this file is no longer be required. - - - - Filename '{0}' contains invalid character '{1}' - Filename '{0}' contains invalid character '{1}' - - - - 'use!' bindings must be of the form 'use! <var> = <expr>' - 'use!' bindings must be of the form 'use! <var> = <expr>' - - - - Inner generic functions are not permitted in quoted expressions. Consider adding some type constraints until this function is no longer generic. - Inner generic functions are not permitted in quoted expressions. Consider adding some type constraints until this function is no longer generic. - - - - The type '{0}' is not a valid enumerator type , i.e. does not have a 'MoveNext()' method returning a bool, and a 'Current' property - The type '{0}' is not a valid enumerator type , i.e. does not have a 'MoveNext()' method returning a bool, and a 'Current' property - - - - End of file in triple-quote string begun at or before here - End of file in triple-quote string begun at or before here - - - - End of file in triple-quote string embedded in comment begun at or before here - End of file in triple-quote string embedded in comment begun at or before here - - - - This type test or downcast will ignore the unit-of-measure '{0}' - This type test or downcast will ignore the unit-of-measure '{0}' - - - - Expected type argument or static argument - Expected type argument or static argument - - - - Unmatched '<'. Expected closing '>' - Unmatched '<'. Expected closing '>' - - - - Unexpected quotation operator '<@' in type definition. If you intend to pass a verbatim string as a static argument to a type provider, put a space between the '<' and '@' characters. - Unexpected quotation operator '<@' in type definition. If you intend to pass a verbatim string as a static argument to a type provider, put a space between the '<' and '@' characters. - - - - Attempted to parse this as an operator name, but failed - Attempted to parse this as an operator name, but failed - - - - \U{0} is not a valid Unicode character escape sequence - \U{0} is not a valid Unicode character escape sequence - - - - '{0}' must be applied to an argument of type '{1}', but has been applied to an argument of type '{2}' - '{0}' must be applied to an argument of type '{1}', but has been applied to an argument of type '{2}' - - - - '{0}' can only be applied to optional arguments - '{0}' can only be applied to optional arguments - - - - The specified .NET Framework version '{0}' is not supported. Please specify a value from the enumeration Microsoft.Build.Utilities.TargetDotNetFrameworkVersion. - The specified .NET Framework version '{0}' is not supported. Please specify a value from the enumeration Microsoft.Build.Utilities.TargetDotNetFrameworkVersion. - - - - Invalid Magic value in CLR Header - Invalid Magic value in CLR Header - - - - Bad image format - Bad image format - - - - Private key expected - Private key expected - - - - RSA key expected - RSA key expected - - - - Invalid bit Length - Invalid bit Length - - - - Invalid RSAParameters structure - '{{0}}' expected - Invalid RSAParameters structure - '{{0}}' expected - - - - Invalid algId - 'Exponent' expected - Invalid algId - 'Exponent' expected - - - - Invalid signature size - Invalid signature size - - - - No signature directory - No signature directory - - - - Invalid Public Key blob - Invalid Public Key blob - - - - Exiting - too many errors - Exiting - too many errors - - - - The documentation file has no .xml suffix - The documentation file has no .xml suffix - - - - No implementation files specified - No implementation files specified - - - - The attribute {0} specified version '{1}', but this value is invalid and has been ignored - The attribute {0} specified version '{1}', but this value is invalid and has been ignored - - - - Conflicting options specified: 'win32manifest' and 'win32res'. Only one of these can be used. - Conflicting options specified: 'win32manifest' and 'win32res'. Only one of these can be used. - - - - The code in assembly '{0}' makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0. - The code in assembly '{0}' makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0. - - - - Code in this assembly makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0. - Code in this assembly makes uses of quotation literals. Static linking may not include components that make use of quotation literals unless all assemblies are compiled with at least F# 4.0. - - - - Static linking may not include a .EXE - Static linking may not include a .EXE - - - - Static linking may not include a mixed managed/unmanaged DLL - Static linking may not include a mixed managed/unmanaged DLL - - - - Ignoring mixed managed/unmanaged assembly '{0}' during static linking - Ignoring mixed managed/unmanaged assembly '{0}' during static linking - - - - Assembly '{0}' was referenced transitively and the assembly could not be resolved automatically. Static linking will assume this DLL has no dependencies on the F# library or other statically linked DLLs. Consider adding an explicit reference to this DLL. - Assembly '{0}' was referenced transitively and the assembly could not be resolved automatically. Static linking will assume this DLL has no dependencies on the F# library or other statically linked DLLs. Consider adding an explicit reference to this DLL. - - - - Assembly '{0}' not found in dependency set of target binary. Statically linked roots should be specified using an assembly name, without a DLL or EXE extension. If this assembly was referenced explicitly then it is possible the assembly was not actually required by the generated binary, in which case it should not be statically linked. - Assembly '{0}' not found in dependency set of target binary. Statically linked roots should be specified using an assembly name, without a DLL or EXE extension. If this assembly was referenced explicitly then it is possible the assembly was not actually required by the generated binary, in which case it should not be statically linked. - - - - The key file '{0}' could not be opened - The key file '{0}' could not be opened - - - - A problem occurred writing the binary '{0}': {1} - A problem occurred writing the binary '{0}': {1} - - - - The 'AssemblyVersionAttribute' has been ignored because a version was given using a command line option - The 'AssemblyVersionAttribute' has been ignored because a version was given using a command line option - - - - Error emitting 'System.Reflection.AssemblyCultureAttribute' attribute -- 'Executables cannot be satellite assemblies, Culture should always be empty' - Error emitting 'System.Reflection.AssemblyCultureAttribute' attribute -- 'Executables cannot be satellite assemblies, Culture should always be empty' - - - - Option '--delaysign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module - Option '--delaysign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module - - - - Option '--keyfile' overrides attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file or added module - Option '--keyfile' overrides attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file or added module - - - - Option '--keycontainer' overrides attribute 'System.Reflection.AssemblyNameAttribute' given in a source file or added module - Option '--keycontainer' overrides attribute 'System.Reflection.AssemblyNameAttribute' given in a source file or added module - - - - The assembly '{0}' is listed on the command line. Assemblies should be referenced using a command line flag such as '-r'. - The assembly '{0}' is listed on the command line. Assemblies should be referenced using a command line flag such as '-r'. - - - - The resident compilation service was not used because a problem occured in communicating with the server. - The resident compilation service was not used because a problem occured in communicating with the server. - - - - Problem with filename '{0}': Illegal characters in path. - Problem with filename '{0}': Illegal characters in path. - - - - Passing a .resx file ({0}) as a source file to the compiler is deprecated. Use resgen.exe to transform the .resx file into a .resources file to pass as a --resource option. If you are using MSBuild, this can be done via an <EmbeddedResource> item in the .fsproj project file. - Passing a .resx file ({0}) as a source file to the compiler is deprecated. Use resgen.exe to transform the .resx file into a .resources file to pass as a --resource option. If you are using MSBuild, this can be done via an <EmbeddedResource> item in the .fsproj project file. - - - - Static linking may not be used on an assembly referencing mscorlib (e.g. a .NET Framework assembly) when generating an assembly that references System.Runtime (e.g. a .NET Core or Portable assembly). - Static linking may not be used on an assembly referencing mscorlib (e.g. a .NET Framework assembly) when generating an assembly that references System.Runtime (e.g. a .NET Core or Portable assembly). - - - - An {0} specified version '{1}', but this value is a wildcard, and you have requested a deterministic build, these are in conflict. - An {0} specified version '{1}', but this value is a wildcard, and you have requested a deterministic build, these are in conflict. - - - - Determinstic builds only support portable PDBs (--debug:portable or --debug:embedded) - Determinstic builds only support portable PDBs (--debug:portable or --debug:embedded) - - - - Character '{0}' is not allowed in provided namespace name '{1}' - Character '{0}' is not allowed in provided namespace name '{1}' - - - - The provided type '{0}' returned a member with a null or empty member name - The provided type '{0}' returned a member with a null or empty member name - - - - The provided type '{0}' returned a null member - The provided type '{0}' returned a null member - - - - The provided type '{0}' member info '{1}' has null declaring type - The provided type '{0}' member info '{1}' has null declaring type - - - - The provided type '{0}' has member '{1}' which has declaring type '{2}'. Expected declaring type to be the same as provided type. - The provided type '{0}' has member '{1}' which has declaring type '{2}'. Expected declaring type to be the same as provided type. - - - - Referenced assembly '{0}' has assembly level attribute '{1}' but no public type provider classes were found - Referenced assembly '{0}' has assembly level attribute '{1}' but no public type provider classes were found - - - - Type '{0}' from type provider '{1}' has an empty namespace. Use 'null' for the global namespace. - Type '{0}' from type provider '{1}' has an empty namespace. Use 'null' for the global namespace. - - - - Empty namespace found from the type provider '{0}'. Use 'null' for the global namespace. - Empty namespace found from the type provider '{0}'. Use 'null' for the global namespace. - - - - Provided type '{0}' has 'IsGenericType' as true, but generic types are not supported. - Provided type '{0}' has 'IsGenericType' as true, but generic types are not supported. - - - - Provided type '{0}' has 'IsArray' as true, but array types are not supported. - Provided type '{0}' has 'IsArray' as true, but array types are not supported. - - - - Invalid member '{0}' on provided type '{1}'. Provided type members must be public, and not be generic, virtual, or abstract. - Invalid member '{0}' on provided type '{1}'. Provided type members must be public, and not be generic, virtual, or abstract. - - - - Invalid member '{0}' on provided type '{1}'. Only properties, methods and constructors are allowed - Invalid member '{0}' on provided type '{1}'. Only properties, methods and constructors are allowed - - - - Property '{0}' on provided type '{1}' has CanRead=true but there was no value from GetGetMethod() - Property '{0}' on provided type '{1}' has CanRead=true but there was no value from GetGetMethod() - - - - Property '{0}' on provided type '{1}' has CanRead=false but GetGetMethod() returned a method - Property '{0}' on provided type '{1}' has CanRead=false but GetGetMethod() returned a method - - - - Property '{0}' on provided type '{1}' has CanWrite=true but there was no value from GetSetMethod() - Property '{0}' on provided type '{1}' has CanWrite=true but there was no value from GetSetMethod() - - - - Property '{0}' on provided type '{1}' has CanWrite=false but GetSetMethod() returned a method - Property '{0}' on provided type '{1}' has CanWrite=false but GetSetMethod() returned a method - - - - One or more errors seen during provided type setup - One or more errors seen during provided type setup - - - - Unexpected exception from provided type '{0}' member '{1}': {2} - Unexpected exception from provided type '{0}' member '{1}': {2} - - - - Unsupported constant type '{0}'. Quotations provided by type providers can only contain simple constants. The implementation of the type provider may need to be adjusted by moving a value declared outside a provided quotation literal to be a 'let' binding inside the quotation literal. - Unsupported constant type '{0}'. Quotations provided by type providers can only contain simple constants. The implementation of the type provider may need to be adjusted by moving a value declared outside a provided quotation literal to be a 'let' binding inside the quotation literal. - - - - Unsupported expression '{0}' from type provider. If you are the author of this type provider, consider adjusting it to provide a different provided expression. - Unsupported expression '{0}' from type provider. If you are the author of this type provider, consider adjusting it to provide a different provided expression. - - - - Expected provided type named '{0}' but provided type has 'Name' with value '{1}' - Expected provided type named '{0}' but provided type has 'Name' with value '{1}' - - - - Event '{0}' on provided type '{1}' has no value from GetAddMethod() - Event '{0}' on provided type '{1}' has no value from GetAddMethod() - - - - Event '{0}' on provided type '{1}' has no value from GetRemoveMethod() - Event '{0}' on provided type '{1}' has no value from GetRemoveMethod() - - - - Assembly attribute '{0}' refers to a designer assembly '{1}' which cannot be loaded or doesn't exist. {2} - Assembly attribute '{0}' refers to a designer assembly '{1}' which cannot be loaded or doesn't exist. {2} - - - - The type provider does not have a valid constructor. A constructor taking either no arguments or one argument of type 'TypeProviderConfig' was expected. - The type provider does not have a valid constructor. A constructor taking either no arguments or one argument of type 'TypeProviderConfig' was expected. - - - - The type provider '{0}' reported an error: {1} - The type provider '{0}' reported an error: {1} - - - - The type provider '{0}' used an invalid parameter in the ParameterExpression: {1} - The type provider '{0}' used an invalid parameter in the ParameterExpression: {1} - - - - The type provider '{0}' provided a method with a name '{1}' and metadata token '{2}', which is not reported among its methods of its declaring type '{3}' - The type provider '{0}' provided a method with a name '{1}' and metadata token '{2}', which is not reported among its methods of its declaring type '{3}' - - - - The type provider '{0}' provided a constructor which is not reported among the constructors of its declaring type '{1}' - The type provider '{0}' provided a constructor which is not reported among the constructors of its declaring type '{1}' - - - - A direct reference to the generated type '{0}' is not permitted. Instead, use a type definition, e.g. 'type TypeAlias = <path>'. This indicates that a type provider adds generated types to your assembly. - A direct reference to the generated type '{0}' is not permitted. Instead, use a type definition, e.g. 'type TypeAlias = <path>'. This indicates that a type provider adds generated types to your assembly. - - - - Expected provided type with path '{0}' but provided type has path '{1}' - Expected provided type with path '{0}' but provided type has path '{1}' - - - - Unexpected 'null' return value from provided type '{0}' member '{1}' - Unexpected 'null' return value from provided type '{0}' member '{1}' - - - - Unexpected exception from member '{0}' of provided type '{1}' member '{2}': {3} - Unexpected exception from member '{0}' of provided type '{1}' member '{2}': {3} - - - - Nested provided types do not take static arguments or generic parameters - Nested provided types do not take static arguments or generic parameters - - - - Invalid static argument to provided type. Expected an argument of kind '{0}'. - Invalid static argument to provided type. Expected an argument of kind '{0}'. - - - - An error occured applying the static arguments to a provided type - An error occured applying the static arguments to a provided type - - - - Unknown static argument kind '{0}' when resolving a reference to a provided type or method '{1}' - Unknown static argument kind '{0}' when resolving a reference to a provided type or method '{1}' - - - - invalid namespace for provided type - invalid namespace for provided type - - - - invalid full name for provided type - invalid full name for provided type - - - - The type provider returned 'null', which is not a valid return value from '{0}' - The type provider returned 'null', which is not a valid return value from '{0}' - - - - The type provider constructor has thrown an exception: {0} - The type provider constructor has thrown an exception: {0} - - - - Type provider '{0}' returned null from GetInvokerExpression. - Type provider '{0}' returned null from GetInvokerExpression. - - - - The type provider '{0}' returned an invalid type from 'ApplyStaticArguments'. A type with name '{1}' was expected, but a type with name '{2}' was returned. - The type provider '{0}' returned an invalid type from 'ApplyStaticArguments'. A type with name '{1}' was expected, but a type with name '{2}' was returned. - - - - The type provider '{0}' returned an invalid method from 'ApplyStaticArgumentsForMethod'. A method with name '{1}' was expected, but a method with name '{2}' was returned. - The type provider '{0}' returned an invalid method from 'ApplyStaticArgumentsForMethod'. A method with name '{1}' was expected, but a method with name '{2}' was returned. - - - - This type test or downcast will erase the provided type '{0}' to the type '{1}' - This type test or downcast will erase the provided type '{0}' to the type '{1}' - - - - This downcast will erase the provided type '{0}' to the type '{1}'. - This downcast will erase the provided type '{0}' to the type '{1}'. - - - - This type test with a provided type '{0}' is not allowed because this provided type will be erased to '{1}' at runtime. - This type test with a provided type '{0}' is not allowed because this provided type will be erased to '{1}' at runtime. - - - - Cannot inherit from erased provided type - Cannot inherit from erased provided type - - - - Assembly '{0}' hase TypeProviderAssembly attribute with invalid value '{1}'. The value should be a valid assembly name - Assembly '{0}' hase TypeProviderAssembly attribute with invalid value '{1}'. The value should be a valid assembly name - - - - Invalid member name. Members may not have name '.ctor' or '.cctor' - Invalid member name. Members may not have name '.ctor' or '.cctor' - - - - The function or member '{0}' is used in a way that requires further type annotations at its definition to ensure consistency of inferred types. The inferred signature is '{1}'. - The function or member '{0}' is used in a way that requires further type annotations at its definition to ensure consistency of inferred types. The inferred signature is '{1}'. - - - - The number of type arguments did not match: '{0}' given, '{1}' expected. This may be related to a previously reported error. - The number of type arguments did not match: '{0}' given, '{1}' expected. This may be related to a previously reported error. - - - - Cannot override inherited member '{0}' because it is sealed - Cannot override inherited member '{0}' because it is sealed - - - - The type provider '{0}' reported an error in the context of provided type '{1}', member '{2}'. The error: {3} - The type provider '{0}' reported an error in the context of provided type '{1}', member '{2}'. The error: {3} - - - - An exception occurred when accessing the '{0}' of a provided type: {1} - An exception occurred when accessing the '{0}' of a provided type: {1} - - - - The '{0}' of a provided type was null or empty. - The '{0}' of a provided type was null or empty. - - - - Character '{0}' is not allowed in provided type name '{1}' - Character '{0}' is not allowed in provided type name '{1}' - - - - In queries, '{0}' must use a simple pattern - In queries, '{0}' must use a simple pattern - - - - A custom query operation for '{0}' is required but not specified - A custom query operation for '{0}' is required but not specified - - - - Named static arguments must come after all unnamed static arguments - Named static arguments must come after all unnamed static arguments - - - - The static parameter '{0}' of the provided type or method '{1}' requires a value. Static parameters to type providers may be optionally specified using named arguments, e.g. '{2}<{3}=...>'. - The static parameter '{0}' of the provided type or method '{1}' requires a value. Static parameters to type providers may be optionally specified using named arguments, e.g. '{2}<{3}=...>'. - - - - No static parameter exists with name '{0}' - No static parameter exists with name '{0}' - - - - The static parameter '{0}' has already been given a value - The static parameter '{0}' has already been given a value - - - - Multiple static parameters exist with name '{0}' - Multiple static parameters exist with name '{0}' - - - - A custom operation may not be used in conjunction with a non-value or recursive 'let' binding in another part of this computation expression - A custom operation may not be used in conjunction with a non-value or recursive 'let' binding in another part of this computation expression - - - - A custom operation may not be used in conjunction with 'use', 'try/with', 'try/finally', 'if/then/else' or 'match' operators within this computation expression - A custom operation may not be used in conjunction with 'use', 'try/with', 'try/finally', 'if/then/else' or 'match' operators within this computation expression - - - - The custom operation '{0}' refers to a method which is overloaded. The implementations of custom operations may not be overloaded. - The custom operation '{0}' refers to a method which is overloaded. The implementations of custom operations may not be overloaded. - - - - An if/then/else expression may not be used within queries. Consider using either an if/then expression, or use a sequence expression instead. - An if/then/else expression may not be used within queries. Consider using either an if/then expression, or use a sequence expression instead. - - - - Invalid argument to 'methodhandleof' during codegen - Invalid argument to 'methodhandleof' during codegen - - - - A reference to a provided type was missing a value for the static parameter '{0}'. You may need to recompile one or more referenced assemblies. - A reference to a provided type was missing a value for the static parameter '{0}'. You may need to recompile one or more referenced assemblies. - - - - A reference to a provided type had an invalid value '{0}' for a static parameter. You may need to recompile one or more referenced assemblies. - A reference to a provided type had an invalid value '{0}' for a static parameter. You may need to recompile one or more referenced assemblies. - - - - '{0}' is not used correctly. This is a custom operation in this query or computation expression. - '{0}' is not used correctly. This is a custom operation in this query or computation expression. - - - - '{0}' is not used correctly. Usage: {1}. This is a custom operation in this query or computation expression. - '{0}' is not used correctly. Usage: {1}. This is a custom operation in this query or computation expression. - - - - {0} var in collection {1} (outerKey = innerKey). Note that parentheses are required after '{2}' - {0} var in collection {1} (outerKey = innerKey). Note that parentheses are required after '{2}' - - - - {0} var in collection {1} (outerKey = innerKey) into group. Note that parentheses are required after '{2}' - {0} var in collection {1} (outerKey = innerKey) into group. Note that parentheses are required after '{2}' - - - - {0} var in collection - {0} var in collection - - - - '{0}' must be followed by a variable name. Usage: {1}. - '{0}' must be followed by a variable name. Usage: {1}. - - - - Incorrect syntax for '{0}'. Usage: {1}. - Incorrect syntax for '{0}'. Usage: {1}. - - - - '{0}' must come after a 'for' selection clause and be followed by the rest of the query. Syntax: ... {1} ... - '{0}' must come after a 'for' selection clause and be followed by the rest of the query. Syntax: ... {1} ... - - - - '{0}' is used with an incorrect number of arguments. This is a custom operation in this query or computation expression. Expected {1} argument(s), but given {2}. - '{0}' is used with an incorrect number of arguments. This is a custom operation in this query or computation expression. Expected {1} argument(s), but given {2}. - - - - Expected an expression after this point - Expected an expression after this point - - - - Expected a type after this point - Expected a type after this point - - - - Unmatched '[<'. Expected closing '>]' - Unmatched '[<'. Expected closing '>]' - - - - Unexpected end of input in 'match' expression. Expected 'match <expr> with | <pat> -> <expr> | <pat> -> <expr> ...'. - Unexpected end of input in 'match' expression. Expected 'match <expr> with | <pat> -> <expr> | <pat> -> <expr> ...'. - - - - Unexpected end of input in 'try' expression. Expected 'try <expr> with <rules>' or 'try <expr> finally <expr>'. - Unexpected end of input in 'try' expression. Expected 'try <expr> with <rules>' or 'try <expr> finally <expr>'. - - - - Unexpected end of input in 'while' expression. Expected 'while <expr> do <expr>'. - Unexpected end of input in 'while' expression. Expected 'while <expr> do <expr>'. - - - - Unexpected end of input in 'for' expression. Expected 'for <pat> in <expr> do <expr>'. - Unexpected end of input in 'for' expression. Expected 'for <pat> in <expr> do <expr>'. - - - - Unexpected end of input in 'match' or 'try' expression - Unexpected end of input in 'match' or 'try' expression - - - - Unexpected end of input in 'then' branch of conditional expression. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - Unexpected end of input in 'then' branch of conditional expression. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - - - - Unexpected end of input in 'else' branch of conditional expression. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - Unexpected end of input in 'else' branch of conditional expression. Expected 'if <expr> then <expr>' or 'if <expr> then <expr> else <expr>'. - - - - Unexpected end of input in body of lambda expression. Expected 'fun <pat> ... <pat> -> <expr>'. - Unexpected end of input in body of lambda expression. Expected 'fun <pat> ... <pat> -> <expr>'. - - - - Unexpected end of input in type arguments - Unexpected end of input in type arguments - - - - Unexpected end of input in type signature - Unexpected end of input in type signature - - - - Unexpected end of input in type definition - Unexpected end of input in type definition - - - - Unexpected end of input in object members - Unexpected end of input in object members - - - - Unexpected end of input in value, function or member definition - Unexpected end of input in value, function or member definition - - - - Unexpected end of input in expression - Unexpected end of input in expression - - - - Unexpected end of type. Expected a name after this point. - Unexpected end of type. Expected a name after this point. - - - - Incomplete value or function definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let' keyword. - Incomplete value or function definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let' keyword. - - - - Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let!' keyword. - Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'let!' keyword. - - - - Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use!' keyword. - Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use!' keyword. - - - - Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use' keyword. - Incomplete value definition. If this is in an expression, the body of the expression must be indented to the same column as the 'use' keyword. - - - - Missing 'do' in 'while' expression. Expected 'while <expr> do <expr>'. - Missing 'do' in 'while' expression. Expected 'while <expr> do <expr>'. - - - - Missing 'do' in 'for' expression. Expected 'for <pat> in <expr> do <expr>'. - Missing 'do' in 'for' expression. Expected 'for <pat> in <expr> do <expr>'. - - - - Invalid join relation in '{0}'. Expected 'expr <op> expr', where <op> is =, =?, ?= or ?=?. - Invalid join relation in '{0}'. Expected 'expr <op> expr', where <op> is =, =?, ?= or ?=?. - - - - Calls - Calls - - - - Invalid number of generic arguments to type '{0}' in provided type. Expected '{1}' arguments, given '{2}'. - Invalid number of generic arguments to type '{0}' in provided type. Expected '{1}' arguments, given '{2}'. - - - - Invalid value '{0}' for unit-of-measure parameter '{1}' - Invalid value '{0}' for unit-of-measure parameter '{1}' - - - - Invalid value unit-of-measure parameter '{0}' - Invalid value unit-of-measure parameter '{0}' - - - - Property '{0}' on provided type '{1}' is neither readable nor writable as it has CanRead=false and CanWrite=false - Property '{0}' on provided type '{1}' is neither readable nor writable as it has CanRead=false and CanWrite=false - - - - A use of 'into' must be followed by the remainder of the computation - A use of 'into' must be followed by the remainder of the computation - - - - The operator '{0}' does not accept the use of 'into' - The operator '{0}' does not accept the use of 'into' - - - - The definition of the custom operator '{0}' does not use a valid combination of attribute flags - The definition of the custom operator '{0}' does not use a valid combination of attribute flags - - - - This type definition may not have the 'CLIMutable' attribute. Only record types may have this attribute. - This type definition may not have the 'CLIMutable' attribute. Only record types may have this attribute. - - - - 'member val' definitions are only permitted in types with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - 'member val' definitions are only permitted in types with a primary constructor. Consider adding arguments to your type definition, e.g. 'type X(args) = ...'. - - - - Property definitions may not be declared mutable. To indicate that this property can be set, use 'member val PropertyName = expr with get,set'. - Property definitions may not be declared mutable. To indicate that this property can be set, use 'member val PropertyName = expr with get,set'. - - - - To indicate that this property can be set, use 'member val PropertyName = expr with get,set'. - To indicate that this property can be set, use 'member val PropertyName = expr with get,set'. - - - - Type '{0}' is illegal because in byref<T>, T cannot contain byref types. - Type '{0}' is illegal because in byref<T>, T cannot contain byref types. - - - - F# supports array ranks between 1 and 32. The value {0} is not allowed. - F# supports array ranks between 1 and 32. The value {0} is not allowed. - - - - In queries, use the form 'for x in n .. m do ...' for ranging over integers - In queries, use the form 'for x in n .. m do ...' for ranging over integers - - - - 'while' expressions may not be used in queries - 'while' expressions may not be used in queries - - - - 'try/finally' expressions may not be used in queries - 'try/finally' expressions may not be used in queries - - - - 'use' expressions may not be used in queries - 'use' expressions may not be used in queries - - - - 'let!', 'use!' and 'do!' expressions may not be used in queries - 'let!', 'use!' and 'do!' expressions may not be used in queries - - - - 'return' and 'return!' may not be used in queries - 'return' and 'return!' may not be used in queries - - - - This is not a known query operator. Query operators are identifiers such as 'select', 'where', 'sortBy', 'thenBy', 'groupBy', 'groupValBy', 'join', 'groupJoin', 'sumBy' and 'averageBy', defined using corresponding methods on the 'QueryBuilder' type. - This is not a known query operator. Query operators are identifiers such as 'select', 'where', 'sortBy', 'thenBy', 'groupBy', 'groupValBy', 'join', 'groupJoin', 'sumBy' and 'averageBy', defined using corresponding methods on the 'QueryBuilder' type. - - - - 'try/with' expressions may not be used in queries - 'try/with' expressions may not be used in queries - - - - This 'let' definition may not be used in a query. Only simple value definitions may be used in queries. - This 'let' definition may not be used in a query. Only simple value definitions may be used in queries. - - - - Too many static parameters. Expected at most {0} parameters, but got {1} unnamed and {2} named parameters. - Too many static parameters. Expected at most {0} parameters, but got {1} unnamed and {2} named parameters. - - - - Invalid provided literal value '{0}' - Invalid provided literal value '{0}' - - - - The 'anycpu32bitpreferred' platform can only be used with EXE targets. You must use 'anycpu' instead. - The 'anycpu32bitpreferred' platform can only be used with EXE targets. You must use 'anycpu' instead. - - - - This member, function or value declaration may not be declared 'inline' - This member, function or value declaration may not be declared 'inline' - - - - The provider '{0}' returned a non-generated type '{1}' in the context of a set of generated types. Consider adjusting the type provider to only return generated types. - The provider '{0}' returned a non-generated type '{1}' in the context of a set of generated types. Consider adjusting the type provider to only return generated types. - - - - Arguments to query operators may require parentheses, e.g. 'where (x > y)' or 'groupBy (x.Length / 10)' - Arguments to query operators may require parentheses, e.g. 'where (x > y)' or 'groupBy (x.Length / 10)' - - - - A quotation may not involve an assignment to or taking the address of a captured local variable - A quotation may not involve an assignment to or taking the address of a captured local variable - - - - + 1 overload - + 1 overload - - - - + {0} overloads - + {0} overloads - - - - Erased to - Erased to - - - - Unexpected token '{0}' or incomplete expression - Unexpected token '{0}' or incomplete expression - - - - Cannot find code target for this attribute, possibly because the code after the attribute is incomplete. - Cannot find code target for this attribute, possibly because the code after the attribute is incomplete. - - - - Type name cannot be empty. - Type name cannot be empty. - - - - Problem reading assembly '{0}': {1} - Problem reading assembly '{0}': {1} - - - - Invalid provided field. Provided fields of erased provided types must be literals. - Invalid provided field. Provided fields of erased provided types must be literals. - - - - (loading description...) - (loading description...) - - - - (description unavailable...) - (description unavailable...) - - - - A type variable has been constrained by multiple different class types. A type variable may only have one class constraint. - A type variable has been constrained by multiple different class types. A type variable may only have one class constraint. - - - - 'match' expressions may not be used in queries - 'match' expressions may not be used in queries - - - - Infix operator member '{0}' has {1} initial argument(s). Expected a tuple of 3 arguments - Infix operator member '{0}' has {1} initial argument(s). Expected a tuple of 3 arguments - - - - The operator '{0}' cannot be resolved. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - The operator '{0}' cannot be resolved. Consider opening the module 'Microsoft.FSharp.Linq.NullableOperators'. - - - - '{0}' must be followed by 'in'. Usage: {1}. - '{0}' must be followed by 'in'. Usage: {1}. - - - - Neither 'member val' nor 'override val' definitions are permitted in object expressions. - Neither 'member val' nor 'override val' definitions are permitted in object expressions. - - - - Copy-and-update record expressions must include at least one field. - Copy-and-update record expressions must include at least one field. - - - - '_' cannot be used as field name - '_' cannot be used as field name - - - - The provided types generated by this use of a type provider may not be used from other F# assemblies and should be marked internal or private. Consider using 'type internal TypeName = ...' or 'type private TypeName = ...'. - The provided types generated by this use of a type provider may not be used from other F# assemblies and should be marked internal or private. Consider using 'type internal TypeName = ...' or 'type private TypeName = ...'. - - - - A property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - A property's getter and setter must have the same type. Property '{0}' has getter of type '{1}' but setter of type '{2}'. - - - - Array method '{0}' is supplied by the runtime and cannot be directly used in code. For operations with array elements consider using family of GetArray/SetArray functions from LanguagePrimitives.IntrinsicFunctions module. - Array method '{0}' is supplied by the runtime and cannot be directly used in code. For operations with array elements consider using family of GetArray/SetArray functions from LanguagePrimitives.IntrinsicFunctions module. - - - - The union case '{0}' does not have a field named '{1}'. - The union case '{0}' does not have a field named '{1}'. - - - - Union case/exception field '{0}' cannot be used more than once. - Union case/exception field '{0}' cannot be used more than once. - - - - Named field '{0}' is used more than once. - Named field '{0}' is used more than once. - - - - Named field '{0}' conflicts with autogenerated name for anonymous field. - Named field '{0}' conflicts with autogenerated name for anonymous field. - - - - This literal expression or attribute argument results in an arithmetic overflow. - This literal expression or attribute argument results in an arithmetic overflow. - - - - This is not valid literal expression. The [<Literal>] attribute will be ignored. - This is not valid literal expression. The [<Literal>] attribute will be ignored. - - - - System.Runtime.InteropServices assembly is required to use UnknownWrapper\DispatchWrapper classes. - System.Runtime.InteropServices assembly is required to use UnknownWrapper\DispatchWrapper classes. - - - - The mutable local '{0}' is implicitly allocated as a reference cell because it has been captured by a closure. This warning is for informational purposes only to indicate where implicit allocations are performed. - The mutable local '{0}' is implicitly allocated as a reference cell because it has been captured by a closure. This warning is for informational purposes only to indicate where implicit allocations are performed. - - - - A type provider implemented GetStaticParametersForMethod, but ApplyStaticArgumentsForMethod was not implemented or invalid - A type provider implemented GetStaticParametersForMethod, but ApplyStaticArgumentsForMethod was not implemented or invalid - - - - An error occured applying the static arguments to a provided method - An error occured applying the static arguments to a provided method - - - - Unexpected character '{0}' in preprocessor expression - Unexpected character '{0}' in preprocessor expression - - - - Unexpected token '{0}' in preprocessor expression - Unexpected token '{0}' in preprocessor expression - - - - Incomplete preprocessor expression - Incomplete preprocessor expression - - - - Missing token '{0}' in preprocessor expression - Missing token '{0}' in preprocessor expression - - - - An error occurred while reading the F# metadata node at position {0} in table '{1}' of assembly '{2}'. The node had no matching declaration. Please report this warning. You may need to recompile the F# assembly you are using. - An error occurred while reading the F# metadata node at position {0} in table '{1}' of assembly '{2}'. The node had no matching declaration. Please report this warning. You may need to recompile the F# assembly you are using. - - - - Type inference caused the type variable {0} to escape its scope. Consider adding an explicit type parameter declaration or adjusting your code to be less generic. - Type inference caused the type variable {0} to escape its scope. Consider adding an explicit type parameter declaration or adjusting your code to be less generic. - - - - Type inference caused an inference type variable to escape its scope. Consider adding type annotations to make your code less generic. - Type inference caused an inference type variable to escape its scope. Consider adding type annotations to make your code less generic. - - - - Redundant arguments are being ignored in function '{0}'. Expected {1} but got {2} arguments. - Redundant arguments are being ignored in function '{0}'. Expected {1} but got {2} arguments. - - - - Lowercase literal '{0}' is being shadowed by a new pattern with the same name. Only uppercase and module-prefixed literals can be used as named patterns. - Lowercase literal '{0}' is being shadowed by a new pattern with the same name. Only uppercase and module-prefixed literals can be used as named patterns. - - - - This literal pattern does not take arguments - This literal pattern does not take arguments - - - - Constructors are not permitted as extension members - they must be defined as part of the original definition of the type - Constructors are not permitted as extension members - they must be defined as part of the original definition of the type - - - - Invalid response file '{0}' ( '{1}' ) - Invalid response file '{0}' ( '{1}' ) - - - - Response file '{0}' not found in '{1}' - Response file '{0}' not found in '{1}' - - - - Response file name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long - Response file name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long - - - - Cannot find FSharp.Core.dll in compiler's directory - Cannot find FSharp.Core.dll in compiler's directory - - - - One tuple type is a struct tuple, the other is a reference tuple - One tuple type is a struct tuple, the other is a reference tuple - - - - This provided method requires static parameters - This provided method requires static parameters - - - - The conversion from {0} to {1} is a compile-time safe upcast, not a downcast. Consider using 'upcast' instead of 'downcast'. - The conversion from {0} to {1} is a compile-time safe upcast, not a downcast. Consider using 'upcast' instead of 'downcast'. - - - - The conversion from {0} to {1} is a compile-time safe upcast, not a downcast. Consider using the :> (upcast) operator instead of the :?> (downcast) operator. - The conversion from {0} to {1} is a compile-time safe upcast, not a downcast. Consider using the :> (upcast) operator instead of the :?> (downcast) operator. - - - - The 'rec' on this module is implied by an outer 'rec' declaration and is being ignored - The 'rec' on this module is implied by an outer 'rec' declaration and is being ignored - - - - In a recursive declaration group, 'open' declarations must come first in each module - In a recursive declaration group, 'open' declarations must come first in each module - - - - In a recursive declaration group, module abbreviations must come after all 'open' declarations and before other declarations - In a recursive declaration group, module abbreviations must come after all 'open' declarations and before other declarations - - - - This declaration is not supported in recursive declaration groups - This declaration is not supported in recursive declaration groups - - - - Invalid use of 'rec' keyword - Invalid use of 'rec' keyword - - - - If a union type has more than one case and is a struct, then all fields within the union type must be given unique names. - If a union type has more than one case and is a struct, then all fields within the union type must be given unique names. - - - - The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute. - The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute. - - - - Invalid use of 'fixed'. 'fixed' may only be used in a declaration of the form 'use x = fixed expr' where the expression is an array, the address of a field, the address of an array element or a string' - Invalid use of 'fixed'. 'fixed' may only be used in a declaration of the form 'use x = fixed expr' where the expression is an array, the address of a field, the address of an array element or a string' - - - - Could not find method System.Runtime.CompilerServices.OffsetToStringData in references when building 'fixed' expression. - Could not find method System.Runtime.CompilerServices.OffsetToStringData in references when building 'fixed' expression. - - - - {0} is an active pattern and cannot be treated as a discriminated union case with named fields. - {0} is an active pattern and cannot be treated as a discriminated union case with named fields. - - - - The default value does not have the same type as the argument. The DefaultParameterValue attribute and any Optional attribute will be ignored. Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'. - The default value does not have the same type as the argument. The DefaultParameterValue attribute and any Optional attribute will be ignored. Note: 'null' needs to be annotated with the correct type, e.g. 'DefaultParameterValue(null:obj)'. - - - - The system type '{0}' was required but no referenced system DLL contained this type - The system type '{0}' was required but no referenced system DLL contained this type - - - - The member '{0}' matches multiple overloads of the same method.\nPlease restrict it to one of the following:{1}. - The member '{0}' matches multiple overloads of the same method.\nPlease restrict it to one of the following:{1}. - - - - Method or object constructor '{0}' is not static - Method or object constructor '{0}' is not static - - - - Unexpected symbol '=' in expression. Did you intend to use 'for x in y .. z do' instead? - Unexpected symbol '=' in expression. Did you intend to use 'for x in y .. z do' instead? - - - - Indicates a method that either has no implementation in the type in which it is declared or that is virtual and has a default implementation. - Indicates a method that either has no implementation in the type in which it is declared or that is virtual and has a default implementation. - - - - Used in mutually recursive bindings, in property declarations, and with multiple constraints on generic parameters. - Used in mutually recursive bindings, in property declarations, and with multiple constraints on generic parameters. - - - - Used to give the current class object an object name. Also used to give a name to a whole pattern within a pattern match. - Used to give the current class object an object name. Also used to give a name to a whole pattern within a pattern match. - - - - Used to verify code during debugging. - Used to verify code during debugging. - - - - Used as the name of the base class object. - Used as the name of the base class object. - - - - In verbose syntax, indicates the start of a code block. - In verbose syntax, indicates the start of a code block. - - - - In verbose syntax, indicates the start of a class definition. - In verbose syntax, indicates the start of a class definition. - - - - Indicates an implementation of an abstract method; used together with an abstract method declaration to create a virtual method. - Indicates an implementation of an abstract method; used together with an abstract method declaration to create a virtual method. - - - - Used to declare a delegate. - Used to declare a delegate. - - - - Used in looping constructs or to execute imperative code. - Used in looping constructs or to execute imperative code. - - - - In verbose syntax, indicates the end of a block of code in a looping expression. - In verbose syntax, indicates the end of a block of code in a looping expression. - - - - Used to convert to a type that is lower in the inheritance chain. - Used to convert to a type that is lower in the inheritance chain. - - - - In a for expression, used when counting in reverse. - In a for expression, used when counting in reverse. - - - - Used in conditional branching. A short form of else if. - Used in conditional branching. A short form of else if. - - - - Used in conditional branching. - Used in conditional branching. - - - - In type definitions and type extensions, indicates the end of a section of member definitions. In verbose syntax, used to specify the end of a code block that starts with the begin keyword. - In type definitions and type extensions, indicates the end of a section of member definitions. In verbose syntax, used to specify the end of a code block that starts with the begin keyword. - - - - Used to declare an exception type. - Used to declare an exception type. - - - - Indicates that a declared program element is defined in another binary or assembly. - Indicates that a declared program element is defined in another binary or assembly. - - - - Used as a Boolean literal. - Used as a Boolean literal. - - - - Used together with try to introduce a block of code that executes regardless of whether an exception occurs. - Used together with try to introduce a block of code that executes regardless of whether an exception occurs. - - - - Used in looping constructs. - Used in looping constructs. - - - - Used in lambda expressions, also known as anonymous functions. - Used in lambda expressions, also known as anonymous functions. - - - - Used as a shorter alternative to the fun keyword and a match expression in a lambda expression that has pattern matching on a single argument. - Used as a shorter alternative to the fun keyword and a match expression in a lambda expression that has pattern matching on a single argument. - - - - Used to reference the top-level .NET namespace. - Used to reference the top-level .NET namespace. - - - - Used in conditional branching constructs. - Used in conditional branching constructs. - - - - Used for sequence expressions and, in verbose syntax, to separate expressions from bindings. - Used for sequence expressions and, in verbose syntax, to separate expressions from bindings. - - - - Used to specify a base class or base interface. - Used to specify a base class or base interface. - - - - Used to indicate a function that should be integrated directly into the caller's code. - Used to indicate a function that should be integrated directly into the caller's code. - - - - Used to declare and implement interfaces. - Used to declare and implement interfaces. - - - - Used to specify that a member is visible inside an assembly but not outside it. - Used to specify that a member is visible inside an assembly but not outside it. - - - - Used to specify a computation that is to be performed only when a result is needed. - Used to specify a computation that is to be performed only when a result is needed. - - - - Used to associate, or bind, a name to a value or function. - Used to associate, or bind, a name to a value or function. - - - - Used in computation expressions to bind a name to the result of another computation expression. - Used in asynchronous workflows to bind a name to the result of an asynchronous computation, or, in other computation expressions, used to bind a name to a result, which is of the computation type. - - - - Used to branch by comparing a value to a pattern. - Used to branch by comparing a value to a pattern. - - - - Used to declare a property or method in an object type. - Used to declare a property or method in an object type. - - - - Used to associate a name with a group of related types, values, and functions, to logically separate it from other code. - Used to associate a name with a group of related types, values, and functions, to logically separate it from other code. - - - - Used to declare a variable, that is, a value that can be changed. - Used to declare a variable, that is, a value that can be changed. - - - - Used to associate a name with a group of related types and modules, to logically separate it from other code. - Used to associate a name with a group of related types and modules, to logically separate it from other code. - - - - Used to declare, define, or invoke a constructor that creates or that can create an object. Also used in generic parameter constraints to indicate that a type must have a certain constructor. - Used to declare, define, or invoke a constructor that creates or that can create an object. Also used in generic parameter constraints to indicate that a type must have a certain constructor. - - - - Not actually a keyword. However, not struct in combination is used as a generic parameter constraint. - Not actually a keyword. However, not struct in combination is used as a generic parameter constraint. - - - - Indicates the absence of an object. Also used in generic parameter constraints. - Indicates the absence of an object. Also used in generic parameter constraints. - - - - Used in discriminated unions to indicate the type of categories of values, and in delegate and exception declarations. - Used in discriminated unions to indicate the type of categories of values, and in delegate and exception declarations. - - - - Used to make the contents of a namespace or module available without qualification. - Used to make the contents of a namespace or module available without qualification. - - - - Used with Boolean conditions as a Boolean or operator. Equivalent to ||. Also used in member constraints. - Used with Boolean conditions as a Boolean or operator. Equivalent to ||. Also used in member constraints. - - - - Used to implement a version of an abstract or virtual method that differs from the base version. - Used to implement a version of an abstract or virtual method that differs from the base version. - - - - Restricts access to a member to code in the same type or module. - Restricts access to a member to code in the same type or module. - - - - Allows access to a member from outside the type. - Allows access to a member from outside the type. - - - - Used to indicate that a function is recursive. - Used to indicate that a function is recursive. - - - - Used to provide a value for the result of the containing computation expression. - Used to indicate a value to provide as the result of a computation expression. - - - - Used to provide a value for the result of the containing computation expression, where that value itself comes from the result another computation expression. - Used to indicate a computation expression that, when evaluated, provides the result of the containing computation expression. - - - - Used in query expressions to specify what fields or columns to extract. Note that this is a contextual keyword, which means that it is not actually a reserved word and it only acts like a keyword in appropriate context. - Used in query expressions to specify what fields or columns to extract. Note that this is a contextual keyword, which means that it is not actually a reserved word and it only acts like a keyword in appropriate context. - - - - Used to indicate a method or property that can be called without an instance of a type, or a value member that is shared among all instances of a type. - Used to indicate a method or property that can be called without an instance of a type, or a value member that is shared among all instances of a type. - - - - Used to declare a structure type. Also used in generic parameter constraints. Used for OCaml compatibility in module definitions. - Used to declare a structure type. Also used in generic parameter constraints. Used for OCaml compatibility in module definitions. - - - - Used in conditional expressions. Also used to perform side effects after object construction. - Used in conditional expressions. Also used to perform side effects after object construction. - - - - Used in for loops to indicate a range. - Used in for loops to indicate a range. - - - - Used to introduce a block of code that might generate an exception. Used together with with or finally. - Used to introduce a block of code that might generate an exception. Used together with with or finally. - - - - Used to declare a class, record, structure, discriminated union, enumeration type, unit of measure, or type abbreviation. - Used to declare a class, record, structure, discriminated union, enumeration type, unit of measure, or type abbreviation. - - - - Used to convert to a type that is higher in the inheritance chain. - Used to convert to a type that is higher in the inheritance chain. - - - - Used instead of let for values that implement IDisposable - Used instead of let for values that implement IDisposable - - - - Used instead of let! in computation expressions for computation expression results that implement IDisposable. - Used instead of let! in computation expressions for computation expression results that implement IDisposable. - - - - Used in a signature to indicate a value, or in a type to declare a member, in limited situations. - Used in a signature to indicate a value, or in a type to declare a member, in limited situations. - - - - Indicates the .NET void type. Used when interoperating with other .NET languages. - Indicates the .NET void type. Used when interoperating with other .NET languages. - - - - Used for Boolean conditions (when guards) on pattern matches and to introduce a constraint clause for a generic type parameter. - Used for Boolean conditions (when guards) on pattern matches and to introduce a constraint clause for a generic type parameter. - - - - Introduces a looping construct. - Introduces a looping construct. - - - - Used together with the match keyword in pattern matching expressions. Also used in object expressions, record copying expressions, and type extensions to introduce member definitions, and to introduce exception handlers. - Used together with the match keyword in pattern matching expressions. Also used in object expressions, record copying expressions, and type extensions to introduce member definitions, and to introduce exception handlers. - - - - Used in a sequence expression to produce a value for a sequence. - Used in a sequence expression to produce a value for a sequence. - - - - Used in a computation expression to append the result of a given computation expression to a collection of results for the containing computation expression. - Used in a computation expression to append the result of a given computation expression to a collection of results for the containing computation expression. - - - - In function types, delimits arguments and return values. Yields an expression (in sequence expressions); equivalent to the yield keyword. Used in match expressions - In function types, delimits arguments and return values. Yields an expression (in sequence expressions); equivalent to the yield keyword. Used in match expressions - - - - Assigns a value to a variable. - Assigns a value to a variable. - - - - Converts a type to type that is higher in the hierarchy. - Converts a type to type that is higher in the hierarchy. - - - - Converts a type to a type that is lower in the hierarchy. - Converts a type to a type that is lower in the hierarchy. - - - - Delimits a typed code quotation. - Delimits a typed code quotation. - - - - Delimits a untyped code quotation. - Delimits a untyped code quotation. - - - - {0} '{1}' not found in assembly '{2}'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version. - {0} '{1}' not found in assembly '{2}'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version. - - - - {0} '{1}' not found in type '{2}' from assembly '{3}'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version. - {0} '{1}' not found in type '{2}' from assembly '{3}'. A possible cause may be a version incompatibility. You may need to explicitly reference the correct version of this assembly to allow all referenced components to use the correct version. - - - - is - is - - - - This value is not a function and cannot be applied. - This value is not a function and cannot be applied. - - - - This value is not a function and cannot be applied. Did you intend to access the indexer via {0}.[index] instead? - This value is not a function and cannot be applied. Did you intend to access the indexer via {0}.[index] instead? - - - - This expression is not a function and cannot be applied. Did you intend to access the indexer via expr.[index] instead? - This expression is not a function and cannot be applied. Did you intend to access the indexer via expr.[index] instead? - - - - This value is not a function and cannot be applied. Did you forget to terminate a declaration? - This value is not a function and cannot be applied. Did you forget to terminate a declaration? - - - - The argument names in the signature '{0}' and implementation '{1}' do not match. The argument name from the signature file will be used. This may cause problems when debugging or profiling. - The argument names in the signature '{0}' and implementation '{1}' do not match. The argument name from the signature file will be used. This may cause problems when debugging or profiling. - - - - An error occurred while reading the F# metadata of assembly '{0}'. A reserved construct was utilized. You may need to upgrade your F# compiler or use an earlier version of the assembly that doesn't make use of a specific construct. - An error occurred while reading the F# metadata of assembly '{0}'. A reserved construct was utilized. You may need to upgrade your F# compiler or use an earlier version of the assembly that doesn't make use of a specific construct. - - - - This method or property is not normally used from F# code, use an explicit tuple pattern for deconstruction instead. - This method or property is not normally used from F# code, use an explicit tuple pattern for deconstruction instead. - - - - This expression returns a value of type '{0}' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield'. - This expression returns a value of type '{0}' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield'. - - - - This expression returns a value of type '{0}' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield!'. - This expression returns a value of type '{0}' but is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to use the expression as a value in the sequence then use an explicit 'yield!'. - - - - Used in computation expressions to pattern match directly over the result of another computation expression. - Used in computation expressions to pattern match directly over the result of another computation expression. - - - - The file '{0}' changed on disk unexpectedly, please reload. - The file '{0}' changed on disk unexpectedly, please reload. - - - - The byref pointer is readonly, so this write is not permitted. - The byref pointer is readonly, so this write is not permitted. - - - - A value must be mutable in order to mutate the contents or take the address of a value type, e.g. 'let mutable x = ...' - A value must be mutable in order to mutate the contents or take the address of a value type, e.g. 'let mutable x = ...' - - - - A ReadOnly attribute has been applied to a struct type with a mutable field. - A ReadOnly attribute has been applied to a struct type with a mutable field. - - - - A byref pointer returned by a function or method is implicitly dereferenced as of F# 4.5. To acquire the return value as a pointer, use the address-of operator, e.g. '&f(x)' or '&obj.Method(arg1, arg2)'. - A byref pointer returned by a function or method is implicitly dereferenced as of F# 4.5. To acquire the return value as a pointer, use the address-of operator, e.g. '&f(x)' or '&obj.Method(arg1, arg2)'. - - - - A type annotated with IsByRefLike must also be a struct. Consider adding the [<Struct>] attribute to the type. - A type annotated with IsByRefLike must also be a struct. Consider adding the [<Struct>] attribute to the type. - - - - The address of the variable '{0}' or a related expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - The address of the variable '{0}' or a related expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - - - - This value can't be assigned because the target '{0}' may refer to non-stack-local memory, while the expression being assigned is assessed to potentially refer to stack-local memory. This is to help prevent pointers to stack-bound memory escaping their scope. - This value can't be assigned because the target '{0}' may refer to non-stack-local memory, while the expression being assigned is assessed to potentially refer to stack-local memory. This is to help prevent pointers to stack-bound memory escaping their scope. - - - - A value defined in a module must be mutable in order to take its address, e.g. 'let mutable x = ...' - A value defined in a module must be mutable in order to take its address, e.g. 'let mutable x = ...' - - - - A type annotated with IsReadOnly must also be a struct. Consider adding the [<Struct>] attribute to the type. - A type annotated with IsReadOnly must also be a struct. Consider adding the [<Struct>] attribute to the type. - - - - Struct members cannot return the address of fields of the struct by reference - Struct members cannot return the address of fields of the struct by reference - - - - The function or method call cannot be used at this point, because one argument that is a byref of a non-stack-local Span or IsByRefLike type is used with another argument that is a stack-local Span or IsByRefLike type. This is to ensure the address of the local value does not escape its scope. - The function or method call cannot be used at this point, because one argument that is a byref of a non-stack-local Span or IsByRefLike type is used with another argument that is a stack-local Span or IsByRefLike type. This is to ensure the address of the local value does not escape its scope. - - - - The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - The address of a value returned from the expression cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - - - - The Span or IsByRefLike variable '{0}' cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - The Span or IsByRefLike variable '{0}' cannot be used at this point. This is to ensure the address of the local value does not escape its scope. - - - - A Span or IsByRefLike value returned from the expression cannot be used at ths point. This is to ensure the address of the local value does not escape its scope. - A Span or IsByRefLike value returned from the expression cannot be used at ths point. This is to ensure the address of the local value does not escape its scope. - - - - Cannot take the address of the value returned from the expression. Assign the returned value to a let-bound value before taking the address. - Cannot take the address of the value returned from the expression. Assign the returned value to a let-bound value before taking the address. - - - - Unmatched '{{|' - Unmatched '{{|' - - - - anonymous record field - anonymous record field - - - - The exception '{0}' does not have a field named '{1}'. - The exception '{0}' does not have a field named '{1}'. - - - - Active patterns do not have fields. This syntax is invalid. - Active patterns do not have fields. This syntax is invalid. - - - - The constructor does not have a field named '{0}'. - The constructor does not have a field named '{0}'. - - - - Two anonymous record types are from different assemblies '{0}' and '{1}' - Two anonymous record types are from different assemblies '{0}' and '{1}' - - - - Two anonymous record types have mismatched sets of field names '{0}' and '{1}' - Two anonymous record types have mismatched sets of field names '{0}' and '{1}' - - - - Cannot call the byref extension method '{0}. The first parameter requires the value to be mutable or a non-readonly byref type. - Cannot call the byref extension method '{0}. The first parameter requires the value to be mutable or a non-readonly byref type. - - - - Byref types are not allowed to have optional type extensions. - Byref types are not allowed to have optional type extensions. - - - - Cannot partially apply the extension method '{0}' because the first parameter is a byref type. - Cannot partially apply the extension method '{0}' because the first parameter is a byref type. - - - - This type does not inherit Attribute, it will not work correctly with other .NET languages. - This type does not inherit Attribute, it will not work correctly with other .NET languages. - - - - Invalid anonymous record expression - Invalid anonymous record expression - - - - Invalid anonymous record type - Invalid anonymous record type - - - - The input to a copy-and-update expression that creates an anonymous record must be either an anonymous record or a record - The input to a copy-and-update expression that creates an anonymous record must be either an anonymous record or a record - - - - The parameter '{0}' has an invalid type '{1}'. This is not permitted by the rules of Common IL. - The parameter '{0}' has an invalid type '{1}'. This is not permitted by the rules of Common IL. - - - - The function or method has an invalid return type '{0}'. This is not permitted by the rules of Common IL. - The function or method has an invalid return type '{0}'. This is not permitted by the rules of Common IL. - - - - - \ No newline at end of file diff --git a/src/fsharp/xlf/FSInteractiveSettings.txt.en.xlf b/src/fsharp/xlf/FSInteractiveSettings.txt.en.xlf deleted file mode 100644 index 10fa30b41f5..00000000000 --- a/src/fsharp/xlf/FSInteractiveSettings.txt.en.xlf +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/fsharp/xlf/FSStrings.en.xlf b/src/fsharp/xlf/FSStrings.en.xlf deleted file mode 100644 index 63b0d8034ca..00000000000 --- a/src/fsharp/xlf/FSStrings.en.xlf +++ /dev/null @@ -1,1632 +0,0 @@ - - - - - - . See also {0}. - . See also {0}. - - - - The tuples have differing lengths of {0} and {1} - The tuples have differing lengths of {0} and {1} - - - - The types '{0}' and '{1}' cannot be unified. - The types '{0}' and '{1}' cannot be unified. - - - - A type parameter is missing a constraint '{0}' - A type parameter is missing a constraint '{0}' - - - - The unit of measure '{0}' does not match the unit of measure '{1}' - The unit of measure '{0}' does not match the unit of measure '{1}' - - - - The type '{0}' does not match the type '{1}' - The type '{0}' does not match the type '{1}' - - - - The type '{0}' is not compatible with the type '{1}'{2} - The type '{0}' is not compatible with the type '{1}'{2} - - - - This expression was expected to have type\n '{1}' \nbut here has type\n '{0}' {2} - This expression was expected to have type\n '{1}' \nbut here has type\n '{0}' {2} - - - - Type mismatch. Expecting a\n '{0}' \nbut given a\n '{1}' {2}\n - Type mismatch. Expecting a\n '{0}' \nbut given a\n '{1}' {2}\n - - - - Type constraint mismatch when applying the default type '{0}' for a type inference variable. - Type constraint mismatch when applying the default type '{0}' for a type inference variable. - - - - Consider adding further type constraints - Consider adding further type constraints - - - - Type constraint mismatch. The type \n '{0}' \nis not compatible with type\n '{1}' {2}\n - Type constraint mismatch. The type \n '{0}' \nis not compatible with type\n '{1}' {2}\n - - - - Uppercase variable identifiers should not generally be used in patterns, and may indicate a misspelt pattern name. - Uppercase variable identifiers should not generally be used in patterns, and may indicate a misspelt pattern name. - - - - Discriminated union cases and exception labels must be uppercase identifiers - Discriminated union cases and exception labels must be uppercase identifiers - - - - Possible overload: '{0}'. {1}. - Possible overload: '{0}'. {1}. - - - - \n\nPossible best overload: '{0}'. - \n\nPossible best overload: '{0}'. - - - - This function takes too many arguments, or is used in a context where a function is not expected - This function takes too many arguments, or is used in a context where a function is not expected - - - - Member constraints with the name '{0}' are given special status by the F# compiler as certain .NET types are implicitly augmented with this member. This may result in runtime failures if you attempt to invoke the member constraint from your own code. - Member constraints with the name '{0}' are given special status by the F# compiler as certain .NET types are implicitly augmented with this member. This may result in runtime failures if you attempt to invoke the member constraint from your own code. - - - - A definition to be compiled as a .NET event does not have the expected form. Only property members can be compiled as .NET events. - A definition to be compiled as a .NET event does not have the expected form. Only property members can be compiled as .NET events. - - - - Implicit object constructors for structs must take at least one argument - Implicit object constructors for structs must take at least one argument - - - - The type implements the interface '{0}' but this is not revealed by the signature. You should list the interface in the signature, as the interface will be discoverable via dynamic type casts and/or reflection. - The type implements the interface '{0}' but this is not revealed by the signature. You should list the interface in the signature, as the interface will be discoverable via dynamic type casts and/or reflection. - - - - The type '{0}' expects {1} type argument(s) but is given {2} - The type '{0}' expects {1} type argument(s) but is given {2} - - - - Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved. - Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved. - - - - Duplicate definition of {0} '{1}' - Duplicate definition of {0} '{1}' - - - - The {0} '{1}' can not be defined because the name '{2}' clashes with the {3} '{4}' in this type or module - The {0} '{1}' can not be defined because the name '{2}' clashes with the {3} '{4}' in this type or module - - - - Two members called '{0}' have the same signature - Two members called '{0}' have the same signature - - - - Duplicate definition of {0} '{1}' - Duplicate definition of {0} '{1}' - - - - A construct with this name was found in FSharp.PowerPack.dll, which contains some modules and types that were implicitly referenced in some previous versions of F#. You may need to add an explicit reference to this DLL in order to compile this code. - A construct with this name was found in FSharp.PowerPack.dll, which contains some modules and types that were implicitly referenced in some previous versions of F#. You may need to add an explicit reference to this DLL in order to compile this code. - - - - This field is not mutable - This field is not mutable - - - - The fields '{0}' and '{1}' are from different types - The fields '{0}' and '{1}' are from different types - - - - '{0}' is bound twice in this pattern - '{0}' is bound twice in this pattern - - - - A use of the function '{0}' does not match a type inferred elsewhere. The inferred type of the function is\n {1}. \nThe type of the function required at this point of use is\n {2} {3}\nThis error may be due to limitations associated with generic recursion within a 'let rec' collection or within a group of classes. Consider giving a full type signature for the targets of recursive calls including type annotations for both argument and return types. - A use of the function '{0}' does not match a type inferred elsewhere. The inferred type of the function is\n {1}. \nThe type of the function required at this point of use is\n {2} {3}\nThis error may be due to limitations associated with generic recursion within a 'let rec' collection or within a group of classes. Consider giving a full type signature for the targets of recursive calls including type annotations for both argument and return types. - - - - Invalid runtime coercion or type test from type {0} to {1}\n{2} - Invalid runtime coercion or type test from type {0} to {1}\n{2} - - - - This runtime coercion or type test from type\n {0} \n to \n {1} \ninvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed. - This runtime coercion or type test from type\n {0} \n to \n {1} \ninvolves an indeterminate type based on information prior to this program point. Runtime type tests are not allowed on some types. Further type annotations are needed. - - - - The static coercion from type\n {0} \nto \n {1} \n involves an indeterminate type based on information prior to this program point. Static coercions are not allowed on some types. Further type annotations are needed. - The static coercion from type\n {0} \nto \n {1} \n involves an indeterminate type based on information prior to this program point. Static coercions are not allowed on some types. Further type annotations are needed. - - - - A coercion from the value type \n {0} \nto the type \n {1} \nwill involve boxing. Consider using 'box' instead - A coercion from the value type \n {0} \nto the type \n {1} \nwill involve boxing. Consider using 'box' instead - - - - This type is 'abstract' since some abstract members have not been given an implementation. If this is intentional then add the '[<AbstractClass>]' attribute to your type. - This type is 'abstract' since some abstract members have not been given an implementation. If this is intentional then add the '[<AbstractClass>]' attribute to your type. - - - - This construct causes code to be less generic than indicated by its type annotations. The type variable implied by the use of a '#', '_' or other type annotation at or near '{0}' has been constrained to be type '{1}'. - This construct causes code to be less generic than indicated by its type annotations. The type variable implied by the use of a '#', '_' or other type annotation at or near '{0}' has been constrained to be type '{1}'. - - - - This construct causes code to be less generic than indicated by the type annotations. The unit-of-measure variable '{0} has been constrained to be measure '{1}'. - This construct causes code to be less generic than indicated by the type annotations. The unit-of-measure variable '{0} has been constrained to be measure '{1}'. - - - - This construct causes code to be less generic than indicated by the type annotations. The type variable '{0} has been constrained to be type '{1}'. - This construct causes code to be less generic than indicated by the type annotations. The type variable '{0} has been constrained to be type '{1}'. - - - - identifier - identifier - - - - integer literal - integer literal - - - - floating point literal - floating point literal - - - - decimal literal - decimal literal - - - - character literal - character literal - - - - keyword 'base' - keyword 'base' - - - - symbol '(*)' - symbol '(*)' - - - - symbol '$' - symbol '$' - - - - infix operator - infix operator - - - - infix operator - infix operator - - - - symbol ':>' - symbol ':>' - - - - symbol '::' - symbol '::' - - - - symbol '{0} - symbol '{0} - - - - infix operator - infix operator - - - - infix operator - infix operator - - - - infix operator - infix operator - - - - prefix operator - prefix operator - - - - symbol ':?>' - symbol ':?>' - - - - infix operator - infix operator - - - - infix operator - infix operator - - - - symbol '&' - symbol '&' - - - - symbol '&&' - symbol '&&' - - - - symbol '||' - symbol '||' - - - - symbol '<' - symbol '<' - - - - symbol '>' - symbol '>' - - - - symbol '?' - symbol '?' - - - - symbol '??' - symbol '??' - - - - symbol ':?' - symbol ':?' - - - - integer.. - integer.. - - - - symbol '..' - symbol '..' - - - - quote symbol - quote symbol - - - - symbol '*' - symbol '*' - - - - type application - type application - - - - symbol ':' - symbol ':' - - - - symbol ':=' - symbol ':=' - - - - symbol '<-' - symbol '<-' - - - - symbol '=' - symbol '=' - - - - symbol '>|]' - symbol '>|]' - - - - symbol '-' - symbol '-' - - - - prefix operator - prefix operator - - - - operator name - operator name - - - - symbol ',' - symbol ',' - - - - symbol '.' - symbol '.' - - - - symbol '|' - symbol '|' - - - - symbol # - symbol # - - - - symbol '_' - symbol '_' - - - - symbol ';' - symbol ';' - - - - symbol ';;' - symbol ';;' - - - - symbol '(' - symbol '(' - - - - symbol ')' - symbol ')' - - - - symbol 'splice' - symbol 'splice' - - - - start of quotation - start of quotation - - - - symbol '[' - symbol '[' - - - - symbol '[|' - symbol '[|' - - - - symbol '[<' - symbol '[<' - - - - symbol '{' - symbol '{' - - - - symbol '{<' - symbol '{<' - - - - symbol '|]' - symbol '|]' - - - - symbol '>}' - symbol '>}' - - - - symbol '>]' - symbol '>]' - - - - end of quotation - end of quotation - - - - symbol ']' - symbol ']' - - - - symbol '}' - symbol '}' - - - - keyword 'public' - keyword 'public' - - - - keyword 'private' - keyword 'private' - - - - keyword 'internal' - keyword 'internal' - - - - keyword 'fixed' - keyword 'fixed' - - - - keyword 'constraint' - keyword 'constraint' - - - - keyword 'instance' - keyword 'instance' - - - - keyword 'delegate' - keyword 'delegate' - - - - keyword 'inherit' - keyword 'inherit' - - - - keyword 'constructor' - keyword 'constructor' - - - - keyword 'default' - keyword 'default' - - - - keyword 'override' - keyword 'override' - - - - keyword 'abstract' - keyword 'abstract' - - - - keyword 'class' - keyword 'class' - - - - keyword 'member' - keyword 'member' - - - - keyword 'static' - keyword 'static' - - - - keyword 'namespace' - keyword 'namespace' - - - - start of structured construct - start of structured construct - - - - incomplete structured construct at or before this point - incomplete structured construct at or before this point - - - - Incomplete structured construct at or before this point - Incomplete structured construct at or before this point - - - - keyword 'then' - keyword 'then' - - - - keyword 'else' - keyword 'else' - - - - keyword 'let' or 'use' - keyword 'let' or 'use' - - - - binder keyword - binder keyword - - - - keyword 'do' - keyword 'do' - - - - keyword 'const' - keyword 'const' - - - - keyword 'with' - keyword 'with' - - - - keyword 'function' - keyword 'function' - - - - keyword 'fun' - keyword 'fun' - - - - end of input - end of input - - - - internal dummy token - internal dummy token - - - - keyword 'do!' - keyword 'do!' - - - - yield - yield - - - - yield! - yield! - - - - keyword 'interface' - keyword 'interface' - - - - keyword 'elif' - keyword 'elif' - - - - symbol '->' - symbol '->' - - - - keyword 'sig' - keyword 'sig' - - - - keyword 'struct' - keyword 'struct' - - - - keyword 'upcast' - keyword 'upcast' - - - - keyword 'downcast' - keyword 'downcast' - - - - keyword 'null' - keyword 'null' - - - - reserved keyword - reserved keyword - - - - keyword 'module' - keyword 'module' - - - - keyword 'and' - keyword 'and' - - - - keyword 'as' - keyword 'as' - - - - keyword 'assert' - keyword 'assert' - - - - keyword 'asr' - keyword 'asr' - - - - keyword 'downto' - keyword 'downto' - - - - keyword 'exception' - keyword 'exception' - - - - keyword 'false' - keyword 'false' - - - - keyword 'for' - keyword 'for' - - - - keyword 'fun' - keyword 'fun' - - - - keyword 'function' - keyword 'function' - - - - keyword 'finally' - keyword 'finally' - - - - keyword 'lazy' - keyword 'lazy' - - - - keyword 'match' - keyword 'match' - - - - keyword 'match!' - keyword 'match!' - - - - keyword 'mutable' - keyword 'mutable' - - - - keyword 'new' - keyword 'new' - - - - keyword 'of' - keyword 'of' - - - - keyword 'open' - keyword 'open' - - - - keyword 'or' - keyword 'or' - - - - keyword 'void' - keyword 'void' - - - - keyword 'extern' - keyword 'extern' - - - - keyword 'interface' - keyword 'interface' - - - - keyword 'rec' - keyword 'rec' - - - - keyword 'to' - keyword 'to' - - - - keyword 'true' - keyword 'true' - - - - keyword 'try' - keyword 'try' - - - - keyword 'type' - keyword 'type' - - - - keyword 'val' - keyword 'val' - - - - keyword 'inline' - keyword 'inline' - - - - keyword 'when' - keyword 'when' - - - - keyword 'while' - keyword 'while' - - - - keyword 'with' - keyword 'with' - - - - keyword 'if' - keyword 'if' - - - - keyword 'do' - keyword 'do' - - - - keyword 'global' - keyword 'global' - - - - keyword 'done' - keyword 'done' - - - - keyword 'in' - keyword 'in' - - - - symbol '(' - symbol '(' - - - - symbol'[' - symbol'[' - - - - keyword 'begin' - keyword 'begin' - - - - keyword 'end' - keyword 'end' - - - - directive - directive - - - - inactive code - inactive code - - - - lex failure - lex failure - - - - whitespace - whitespace - - - - comment - comment - - - - line comment - line comment - - - - string text - string text - - - - compiler generated literal - compiler generated literal - - - - byte array literal - byte array literal - - - - string literal - string literal - - - - end of input - end of input - - - - Unexpected end of input - Unexpected end of input - - - - Unexpected {0} - Unexpected {0} - - - - in interaction - in interaction - - - - in directive - in directive - - - - in field declaration - in field declaration - - - - in discriminated union case declaration - in discriminated union case declaration - - - - in binding - in binding - - - - in binding - in binding - - - - in member definition - in member definition - - - - in definitions - in definitions - - - - in member signature - in member signature - - - - in value signature - in value signature - - - - in type signature - in type signature - - - - in lambda expression - in lambda expression - - - - in union case - in union case - - - - in extern declaration - in extern declaration - - - - in object expression - in object expression - - - - in if/then/else expression - in if/then/else expression - - - - in open declaration - in open declaration - - - - in module or namespace signature - in module or namespace signature - - - - in pattern matching - in pattern matching - - - - in begin/end expression - in begin/end expression - - - - in record expression - in record expression - - - - in type definition - in type definition - - - - in exception definition - in exception definition - - - - in type name - in type name - - - - in attribute list - in attribute list - - - - in quotation literal - in quotation literal - - - - in type constraint - in type constraint - - - - in implementation file - in implementation file - - - - in definition - in definition - - - - in signature file - in signature file - - - - in pattern - in pattern - - - - in expression - in expression - - - - in type - in type - - - - in type arguments - in type arguments - - - - keyword - keyword - - - - symbol - symbol - - - - (due to indentation-aware syntax) - (due to indentation-aware syntax) - - - - . Expected {0} or other token. - . Expected {0} or other token. - - - - . Expected {0}, {1} or other token. - . Expected {0}, {1} or other token. - - - - . Expected {0}, {1}, {2} or other token. - . Expected {0}, {1}, {2} or other token. - - - - The type '{0}' cannot be used as the source of a type test or runtime coercion - The type '{0}' cannot be used as the source of a type test or runtime coercion - - - - The type '{0}' does not have any proper subtypes and cannot be used as the source of a type test or runtime coercion. - The type '{0}' does not have any proper subtypes and cannot be used as the source of a type test or runtime coercion. - - - - The type '{0}' does not have any proper subtypes and need not be used as the target of a static coercion - The type '{0}' does not have any proper subtypes and need not be used as the target of a static coercion - - - - This upcast is unnecessary - the types are identical - This upcast is unnecessary - the types are identical - - - - This type test or downcast will always hold - This type test or downcast will always hold - - - - The member '{0}' does not have the correct type to override any given virtual method - The member '{0}' does not have the correct type to override any given virtual method - - - - The member '{0}' does not have the correct type to override the corresponding abstract method. - The member '{0}' does not have the correct type to override the corresponding abstract method. - - - - The required signature is '{0}'. - The required signature is '{0}'. - - - - The member '{0}' is specialized with 'unit' but 'unit' can't be used as return type of an abstract method parameterized on return type. - The member '{0}' is specialized with 'unit' but 'unit' can't be used as return type of an abstract method parameterized on return type. - - - - This constructor is applied to {0} argument(s) but expects {1} - This constructor is applied to {0} argument(s) but expects {1} - - - - The two sides of this 'or' pattern bind different sets of variables - The two sides of this 'or' pattern bind different sets of variables - - - - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \n{3}. - Module '{0}' contains\n {1} \nbut its signature specifies\n {2} \n{3}. - - - - Module '{0}' requires a {1} '{2}' - Module '{0}' requires a {1} '{2}' - - - - The use of native pointers may result in unverifiable .NET IL code - The use of native pointers may result in unverifiable .NET IL code - - - - {0} - {0} - - - - Thread static and context static 'let' bindings are deprecated. Instead use a declaration of the form 'static val mutable <ident> : <type>' in a class. Add the 'DefaultValue' attribute to this declaration to indicate that the value is initialized to the default value on each new thread. - Thread static and context static 'let' bindings are deprecated. Instead use a declaration of the form 'static val mutable <ident> : <type>' in a class. Add the 'DefaultValue' attribute to this declaration to indicate that the value is initialized to the default value on each new thread. - - - - This expression is a function value, i.e. is missing arguments. Its type is {0}. - This expression is a function value, i.e. is missing arguments. Its type is {0}. - - - - The result of this expression has type '{0}' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. - The result of this expression has type '{0}' and is implicitly ignored. Consider using 'ignore' to discard this value explicitly, e.g. 'expr |> ignore', or 'let' to bind the result to a name, e.g. 'let result = expr'. - - - - The result of this equality expression has type '{0}' and is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. - The result of this equality expression has type '{0}' and is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. - - - - The result of this equality expression has type '{0}' and is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to set a value to a property, then use the '<-' operator e.g. '{1}.{2} <- expression'. - The result of this equality expression has type '{0}' and is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to set a value to a property, then use the '<-' operator e.g. '{1}.{2} <- expression'. - - - - The result of this equality expression has type '{0}' and is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to mutate a value, then mark the value 'mutable' and use the '<-' operator e.g. '{1} <- expression'. - The result of this equality expression has type '{0}' and is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to mutate a value, then mark the value 'mutable' and use the '<-' operator e.g. '{1} <- expression'. - - - - The result of this equality expression has type '{0}' and is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to mutate a value, then use the '<-' operator e.g. '{1} <- expression'. - The result of this equality expression has type '{0}' and is implicitly discarded. Consider using 'let' to bind the result to a name, e.g. 'let result = expression'. If you intended to mutate a value, then use the '<-' operator e.g. '{1} <- expression'. - - - - This recursive use will be checked for initialization-soundness at runtime. This warning is usually harmless, and may be suppressed by using '#nowarn "21"' or '--nowarn:21'. - This recursive use will be checked for initialization-soundness at runtime. This warning is usually harmless, and may be suppressed by using '#nowarn "21"' or '--nowarn:21'. - - - - The value '{0}' will be evaluated as part of its own definition - The value '{0}' will be evaluated as part of its own definition - - - - This value will be eventually evaluated as part of its own definition. You may need to make the value lazy or a function. Value '{0}'{1}. - This value will be eventually evaluated as part of its own definition. You may need to make the value lazy or a function. Value '{0}'{1}. - - - - will evaluate '{0}' - will evaluate '{0}' - - - - Bindings may be executed out-of-order because of this forward reference. - Bindings may be executed out-of-order because of this forward reference. - - - - This and other recursive references to the object(s) being defined will be checked for initialization-soundness at runtime through the use of a delayed reference. This is because you are defining one or more recursive objects, rather than recursive functions. This warning may be suppressed by using '#nowarn "40"' or '--nowarn:40'. - This and other recursive references to the object(s) being defined will be checked for initialization-soundness at runtime through the use of a delayed reference. This is because you are defining one or more recursive objects, rather than recursive functions. This warning may be suppressed by using '#nowarn "40"' or '--nowarn:40'. - - - - Recursive references to the object being defined will be checked for initialization soundness at runtime through the use of a delayed reference. Consider placing self-references in members or within a trailing expression of the form '<ctor-expr> then <expr>'. - Recursive references to the object being defined will be checked for initialization soundness at runtime through the use of a delayed reference. Consider placing self-references in members or within a trailing expression of the form '<ctor-expr> then <expr>'. - - - - Recursive references to the object being defined will be checked for initialization soundness at runtime through the use of a delayed reference. Consider placing self-references within 'do' statements after the last 'let' binding in the construction sequence. - Recursive references to the object being defined will be checked for initialization soundness at runtime through the use of a delayed reference. Consider placing self-references within 'do' statements after the last 'let' binding in the construction sequence. - - - - The containing type can use 'null' as a representation value for its nullary union case. Invoking an abstract or virtual member or an interface implementation on a null value will lead to an exception. If necessary add a dummy data value to the nullary constructor to avoid 'null' being used as a representation for this type. - The containing type can use 'null' as a representation value for its nullary union case. Invoking an abstract or virtual member or an interface implementation on a null value will lead to an exception. If necessary add a dummy data value to the nullary constructor to avoid 'null' being used as a representation for this type. - - - - The containing type can use 'null' as a representation value for its nullary union case. This member will be compiled as a static member. - The containing type can use 'null' as a representation value for its nullary union case. This member will be compiled as a static member. - - - - The member '{0}' doesn't correspond to a unique abstract slot based on name and argument count alone - The member '{0}' doesn't correspond to a unique abstract slot based on name and argument count alone - - - - . Multiple implemented interfaces have a member with this name and argument count - . Multiple implemented interfaces have a member with this name and argument count - - - - . Consider implementing interfaces '{0}' and '{1}' explicitly. - . Consider implementing interfaces '{0}' and '{1}' explicitly. - - - - . Additional type annotations may be required to indicate the relevant override. This warning can be disabled using '#nowarn "70"' or '--nowarn:70'. - . Additional type annotations may be required to indicate the relevant override. This warning can be disabled using '#nowarn "70"' or '--nowarn:70'. - - - - parse error - parse error - - - - parse error: unexpected end of file - parse error: unexpected end of file - - - - {0} - {0} - - - - internal error: {0} - internal error: {0} - - - - {0} - {0} - - - - Incomplete pattern matches on this expression. - Incomplete pattern matches on this expression. - - - - For example, the value '{0}' may indicate a case not covered by the pattern(s). - For example, the value '{0}' may indicate a case not covered by the pattern(s). - - - - For example, the value '{0}' may indicate a case not covered by the pattern(s). However, a pattern rule with a 'when' clause might successfully match this value. - For example, the value '{0}' may indicate a case not covered by the pattern(s). However, a pattern rule with a 'when' clause might successfully match this value. - - - - Unmatched elements will be ignored. - Unmatched elements will be ignored. - - - - Enums may take values outside known cases. - Enums may take values outside known cases. - - - - This rule will never be matched - This rule will never be matched - - - - This value is not mutable. Consider using the mutable keyword, e.g. 'let mutable {0} = expression'. - This value is not mutable. Consider using the mutable keyword, e.g. 'let mutable {0} = expression'. - - - - This value is not local - This value is not local - - - - This construct is deprecated - This construct is deprecated - - - - . {0} - . {0} - - - - {0}. This warning can be disabled using '--nowarn:57' or '#nowarn "57"'. - {0}. This warning can be disabled using '--nowarn:57' or '#nowarn "57"'. - - - - Uses of this construct may result in the generation of unverifiable .NET IL code. This warning can be disabled using '--nowarn:9' or '#nowarn "9"'. - Uses of this construct may result in the generation of unverifiable .NET IL code. This warning can be disabled using '--nowarn:9' or '#nowarn "9"'. - - - - This construct is deprecated: {0} - This construct is deprecated: {0} - - - - This construct is deprecated: it is only for use in the F# library - This construct is deprecated: it is only for use in the F# library - - - - The following fields require values: {0} - The following fields require values: {0} - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Value restriction. The value '{0}' has generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - - - - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Value restriction. The value '{0}' has generic type\n {1} \nEither make '{2}' into a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - - - - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - Value restriction. This member has been inferred to have generic type\n {0} \nConstructors and property getters/setters cannot be more generic than the enclosing type. Add a type annotation to indicate the exact types involved. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither make the arguments to '{2}' explicit or, if you do not intend for it to be generic, add a type annotation. - - - - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - Value restriction. The value '{0}' has been inferred to have generic type\n {1} \nEither define '{2}' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation. - - - - syntax error - syntax error - - - - {0} - {0} - - - - {0} - {0} - - - - Override implementations in augmentations are now deprecated. Override implementations should be given as part of the initial declaration of a type. - Override implementations in augmentations are now deprecated. Override implementations should be given as part of the initial declaration of a type. - - - - Override implementations should be given as part of the initial declaration of a type. - Override implementations should be given as part of the initial declaration of a type. - - - - Interface implementations in augmentations are now deprecated. Interface implementations should be given on the initial declaration of a type. - Interface implementations in augmentations are now deprecated. Interface implementations should be given on the initial declaration of a type. - - - - Interface implementations should be given on the initial declaration of a type. - Interface implementations should be given on the initial declaration of a type. - - - - A required assembly reference is missing. You must add a reference to assembly '{0}'. - A required assembly reference is missing. You must add a reference to assembly '{0}'. - - - - The type referenced through '{0}' is defined in an assembly that is not referenced. You must add a reference to assembly '{1}'. - The type referenced through '{0}' is defined in an assembly that is not referenced. You must add a reference to assembly '{1}'. - - - - #I directives may only occur in F# script files (extensions .fsx or .fsscript). Either move this code to a script file, add a '-I' compiler option for this reference or delimit the directive with delimit it with '#if INTERACTIVE'/'#endif'. - #I directives may only occur in F# script files (extensions .fsx or .fsscript). Either move this code to a script file, add a '-I' compiler option for this reference or delimit the directive with delimit it with '#if INTERACTIVE'/'#endif'. - - - - #r directives may only occur in F# script files (extensions .fsx or .fsscript). Either move this code to a script file or replace this reference with the '-r' compiler option. If this directive is being executed as user input, you may delimit it with '#if INTERACTIVE'/'#endif'. - #r directives may only occur in F# script files (extensions .fsx or .fsscript). Either move this code to a script file or replace this reference with the '-r' compiler option. If this directive is being executed as user input, you may delimit it with '#if INTERACTIVE'/'#endif'. - - - - This directive may only be used in F# script files (extensions .fsx or .fsscript). Either remove the directive, move this code to a script file or delimit the directive with '#if INTERACTIVE'/'#endif'. - This directive may only be used in F# script files (extensions .fsx or .fsscript). Either remove the directive, move this code to a script file or delimit the directive with '#if INTERACTIVE'/'#endif'. - - - - Unable to find the file '{0}' in any of\n {1} - Unable to find the file '{0}' in any of\n {1} - - - - Assembly reference '{0}' was not found or is invalid - Assembly reference '{0}' was not found or is invalid - - - - One or more warnings in loaded file.\n - One or more warnings in loaded file.\n - - - - One or more errors in loaded file.\n - One or more errors in loaded file.\n - - - - Loaded files may only be F# source files (extension .fs). This F# script file (.fsx or .fsscript) will be treated as an F# source file - Loaded files may only be F# source files (extension .fs). This F# script file (.fsx or .fsscript) will be treated as an F# source file - - - - Invalid assembly name '{0}' from InternalsVisibleTo attribute in {1} - Invalid assembly name '{0}' from InternalsVisibleTo attribute in {1} - - - - Invalid assembly name '{0}' from InternalsVisibleTo attribute (assembly filename not available) - Invalid assembly name '{0}' from InternalsVisibleTo attribute (assembly filename not available) - - - - Could not load file '{0}' because it does not exist or is inaccessible - Could not load file '{0}' because it does not exist or is inaccessible - - - - {0} (Code={1}) - {0} (Code={1}) - - - - internal error: {0} - internal error: {0} - - - - symbol '{|' - symbol '{|' - - - - symbol '|}' - symbol '|}' - - - - - \ No newline at end of file diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/AssemblyInfo.fs.en.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/AssemblyInfo.fs.en.xlf deleted file mode 100644 index d89f01d4d8f..00000000000 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/AssemblyInfo.fs.en.xlf +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - General Information about an assembly is controlled through the following - General Information about an assembly is controlled through the following - - - - set of attributes. Change these attribute values to modify the information - set of attributes. Change these attribute values to modify the information - - - - associated with an assembly. - associated with an assembly. - - - - Setting ComVisible to false makes the types in this assembly not visible - Setting ComVisible to false makes the types in this assembly not visible - - - - to COM components. If you need to access a type in this assembly from - to COM components. If you need to access a type in this assembly from - - - - COM, set the ComVisible attribute to true on that type. - COM, set the ComVisible attribute to true on that type. - - - - The following GUID is for the ID of the typelib if this project is exposed to COM - The following GUID is for the ID of the typelib if this project is exposed to COM - - - - Version information for an assembly consists of the following four values: - Version information for an assembly consists of the following four values: - - - - Major Version - Major Version - - - - Minor Version - Minor Version - - - - Build Number - Build Number - - - - Revision - Revision - - - - You can specify all the values or you can default the Build and Revision Numbers - You can specify all the values or you can default the Build and Revision Numbers - - - - by using the '*' as shown below: - by using the '*' as shown below: - - - - - \ No newline at end of file diff --git a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.en.xlf b/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.en.xlf deleted file mode 100644 index e0811e33c3e..00000000000 --- a/vsintegration/ProjectTemplates/ConsoleProject/Template/xlf/Program.fs.en.xlf +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - Learn more about F# at http://fsharp.org - Learn more about F# at http://fsharp.org - - - - See the 'F# Tutorial' project for more help. - See the 'F# Tutorial' project for more help. - - - - return an integer exit code - return an integer exit code - - - - - \ No newline at end of file diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/AssemblyInfo.fs.en.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/AssemblyInfo.fs.en.xlf deleted file mode 100644 index d89f01d4d8f..00000000000 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/AssemblyInfo.fs.en.xlf +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - General Information about an assembly is controlled through the following - General Information about an assembly is controlled through the following - - - - set of attributes. Change these attribute values to modify the information - set of attributes. Change these attribute values to modify the information - - - - associated with an assembly. - associated with an assembly. - - - - Setting ComVisible to false makes the types in this assembly not visible - Setting ComVisible to false makes the types in this assembly not visible - - - - to COM components. If you need to access a type in this assembly from - to COM components. If you need to access a type in this assembly from - - - - COM, set the ComVisible attribute to true on that type. - COM, set the ComVisible attribute to true on that type. - - - - The following GUID is for the ID of the typelib if this project is exposed to COM - The following GUID is for the ID of the typelib if this project is exposed to COM - - - - Version information for an assembly consists of the following four values: - Version information for an assembly consists of the following four values: - - - - Major Version - Major Version - - - - Minor Version - Minor Version - - - - Build Number - Build Number - - - - Revision - Revision - - - - You can specify all the values or you can default the Build and Revision Numbers - You can specify all the values or you can default the Build and Revision Numbers - - - - by using the '*' as shown below: - by using the '*' as shown below: - - - - - \ No newline at end of file diff --git a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.en.xlf b/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.en.xlf deleted file mode 100644 index 38e4a1659c3..00000000000 --- a/vsintegration/ProjectTemplates/LibraryProject/Template/xlf/Script.fsx.en.xlf +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - Learn more about F# at http://fsharp.org - Learn more about F# at http://fsharp.org - - - - See the 'F# Tutorial' project for more help. - See the 'F# Tutorial' project for more help. - - - - Define your library scripting code here - Define your library scripting code here - - - - - \ No newline at end of file diff --git a/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.en.xlf b/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.en.xlf deleted file mode 100644 index b3f0d951c55..00000000000 --- a/vsintegration/ProjectTemplates/TutorialProject/Template/xlf/Tutorial.fsx.en.xlf +++ /dev/null @@ -1,1637 +0,0 @@ - - - - - - This sample will guide you through elements of the F# language. - This sample will guide you through elements of the F# language. - - - - To execute the code in F# Interactive, highlight a section of code and press Alt-Enter or right-click - To execute the code in F# Interactive, highlight a section of code and press Alt-Enter or right-click - - - - and select "Execute in Interactive". You can open the F# Interactive Window from the "View" menu. - and select "Execute in Interactive". You can open the F# Interactive Window from the "View" menu. - - - - For more about F#, see: - For more about F#, see: - - - - To see this tutorial in documentation form, see: - To see this tutorial in documentation form, see: - - - - To learn more about applied F# programming, use - To learn more about applied F# programming, use - - - - To install the Visual F# Power Tools, use - To install the Visual F# Power Tools, use - - - - 'Tools' --> 'Extensions and Updates' --> `Online` and search - 'Tools' --> 'Extensions and Updates' --> `Online` and search - - - - For additional templates to use with F#, see the 'Online Templates' in Visual Studio, - For additional templates to use with F#, see the 'Online Templates' in Visual Studio, - - - - 'New Project' --> 'Online Templates' - 'New Project' --> 'Online Templates' - - - - F# supports three kinds of comments: - F# supports three kinds of comments: - - - - 1. Double-slash comments. These are used in most situations. - 1. Double-slash comments. These are used in most situations. - - - - 2. ML-style Block comments. These aren't used that often. - 2. ML-style Block comments. These aren't used that often. - - - - 3. Triple-slash comments. These are used for documenting functions, types, and so on. - 3. Triple-slash comments. These are used for documenting functions, types, and so on. - - - - They will appear as text when you hover over something which is decorated with these comments. - They will appear as text when you hover over something which is decorated with these comments. - - - - They also support .NET-style XML comments, which allow you to generate reference documentation, - They also support .NET-style XML comments, which allow you to generate reference documentation, - - - - and they also allow editors (such as Visual Studio) to extract information from them. - and they also allow editors (such as Visual Studio) to extract information from them. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/xml-documentation - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/xml-documentation - - - - Open namespaces using the 'open' keyword. - Open namespaces using the 'open' keyword. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/import-declarations-the-open-keyword - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/import-declarations-the-open-keyword - - - - A module is a grouping of F# code, such as values, types, and function values. - A module is a grouping of F# code, such as values, types, and function values. - - - - Grouping code in modules helps keep related code together and helps avoid name conflicts in your program. - Grouping code in modules helps keep related code together and helps avoid name conflicts in your program. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/modules - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/modules - - - - This is a sample integer. - This is a sample integer. - - - - This is a sample floating point number. - This is a sample floating point number. - - - - This computed a new number by some arithmetic. Numeric types are converted using - This computed a new number by some arithmetic. Numeric types are converted using - - - - functions 'int', 'double' and so on. - functions 'int', 'double' and so on. - - - - This is a list of the numbers from 0 to 99. - This is a list of the numbers from 0 to 99. - - - - This is a list of all tuples containing all the numbers from 0 to 99 and their squares. - This is a list of all tuples containing all the numbers from 0 to 99 and their squares. - - - - The next line prints a list that includes tuples, using '%A' for generic printing. - The next line prints a list that includes tuples, using '%A' for generic printing. - - - - This is a sample integer with a type annotation - This is a sample integer with a type annotation - - - - Values in F# are immutable by default. They cannot be changed - Values in F# are immutable by default. They cannot be changed - - - - in the course of a program's execution unless explicitly marked as mutable. - in the course of a program's execution unless explicitly marked as mutable. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/values/index#why-immutable - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/values/index#why-immutable - - - - Binding a value to a name via 'let' makes it immutable. - Binding a value to a name via 'let' makes it immutable. - - - - The second line of code fails to compile because 'number' is immutable and bound. - The second line of code fails to compile because 'number' is immutable and bound. - - - - Re-defining 'number' to be a different value is not allowed in F#. - Re-defining 'number' to be a different value is not allowed in F#. - - - - A mutable binding. This is required to be able to mutate the value of 'otherNumber'. - A mutable binding. This is required to be able to mutate the value of 'otherNumber'. - - - - When mutating a value, use '<-' to assign a new value. - When mutating a value, use '<-' to assign a new value. - - - - You could not use '=' here for this purpose since it is used for equality - You could not use '=' here for this purpose since it is used for equality - - - - or other contexts such as 'let' or 'module' - or other contexts such as 'let' or 'module' - - - - Much of F# programming consists of defining functions that transform input data to produce - Much of F# programming consists of defining functions that transform input data to produce - - - - useful results. - useful results. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/functions/ - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/functions/ - - - - You use 'let' to define a function. This one accepts an integer argument and returns an integer. - You use 'let' to define a function. This one accepts an integer argument and returns an integer. - - - - Parentheses are optional for function arguments, except for when you use an explicit type annotation. - Parentheses are optional for function arguments, except for when you use an explicit type annotation. - - - - Apply the function, naming the function return result using 'let'. - Apply the function, naming the function return result using 'let'. - - - - The variable type is inferred from the function return type. - The variable type is inferred from the function return type. - - - - This line uses '%d' to print the result as an integer. This is type-safe. - This line uses '%d' to print the result as an integer. This is type-safe. - - - - If 'result1' were not of type 'int', then the line would fail to compile. - If 'result1' were not of type 'int', then the line would fail to compile. - - - - When needed, annotate the type of a parameter name using '(argument:type)'. Parentheses are required. - When needed, annotate the type of a parameter name using '(argument:type)'. Parentheses are required. - - - - Conditionals use if/then/elid/elif/else. - Conditionals use if/then/elid/elif/else. - - - - Note that F# uses whitespace indentation-aware syntax, similar to languages like Python. - Note that F# uses whitespace indentation-aware syntax, similar to languages like Python. - - - - This line uses '%f' to print the result as a float. As with '%d' above, this is type-safe. - This line uses '%f' to print the result as a float. As with '%d' above, this is type-safe. - - - - Booleans are fundamental data types in F#. Here are some examples of Booleans and conditional logic. - Booleans are fundamental data types in F#. Here are some examples of Booleans and conditional logic. - - - - To learn more, see: - To learn more, see: - - - - and - and - - - - Booleans values are 'true' and 'false'. - Booleans values are 'true' and 'false'. - - - - Operators on booleans are 'not', '&&' and '||'. - Operators on booleans are 'not', '&&' and '||'. - - - - This line uses '%b'to print a boolean value. This is type-safe. - This line uses '%b'to print a boolean value. This is type-safe. - - - - Strings are fundamental data types in F#. Here are some examples of Strings and basic String manipulation. - Strings are fundamental data types in F#. Here are some examples of Strings and basic String manipulation. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/strings - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/strings - - - - Strings use double quotes. - Strings use double quotes. - - - - Strings can also use @ to create a verbatim string literal. - Strings can also use @ to create a verbatim string literal. - - - - This will ignore escape characters such as '\', '\n', '\t', etc. - This will ignore escape characters such as '\', '\n', '\t', etc. - - - - String literals can also use triple-quotes. - String literals can also use triple-quotes. - - - - String concatenation is normally done with the '+' operator. - String concatenation is normally done with the '+' operator. - - - - This line uses '%s' to print a string value. This is type-safe. - This line uses '%s' to print a string value. This is type-safe. - - - - Substrings use the indexer notation. This line extracts the first 7 characters as a substring. - Substrings use the indexer notation. This line extracts the first 7 characters as a substring. - - - - Note that like many languages, Strings are zero-indexed in F#. - Note that like many languages, Strings are zero-indexed in F#. - - - - Tuples are simple combinations of data values into a combined value. - Tuples are simple combinations of data values into a combined value. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/tuples - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/tuples - - - - A simple tuple of integers. - A simple tuple of integers. - - - - A function that swaps the order of two values in a tuple. - A function that swaps the order of two values in a tuple. - - - - F# Type Inference will automatically generalize the function to have a generic type, - F# Type Inference will automatically generalize the function to have a generic type, - - - - meaning that it will work with any type. - meaning that it will work with any type. - - - - A tuple consisting of an integer, a string, - A tuple consisting of an integer, a string, - - - - and a double-precision floating point number. - and a double-precision floating point number. - - - - A simple tuple of integers with a type annotation. - A simple tuple of integers with a type annotation. - - - - Type annotations for tuples use the * symbol to separate elements - Type annotations for tuples use the * symbol to separate elements - - - - Tuples are normally objects, but they can also be represented as structs. - Tuples are normally objects, but they can also be represented as structs. - - - - These interoperate completely with structs in C# and Visual Basic.NET; however, - These interoperate completely with structs in C# and Visual Basic.NET; however, - - - - struct tuples are not implicitly convertable with object tuples (often called reference tuples). - struct tuples are not implicitly convertable with object tuples (often called reference tuples). - - - - The second line below will fail to compile because of this. Uncomment it to see what happens. - The second line below will fail to compile because of this. Uncomment it to see what happens. - - - - Although you cannot implicitly convert between struct tuples and reference tuples, - Although you cannot implicitly convert between struct tuples and reference tuples, - - - - you can explicitly convert via pattern matching, as demonstrated below. - you can explicitly convert via pattern matching, as demonstrated below. - - - - The F# pipe operators ('|>', '<|', etc.) and F# composition operators ('>>', '<<') - The F# pipe operators ('|>', '<|', etc.) and F# composition operators ('>>', '<<') - - - - are used extensively when processing data. These operators are themselves functions - are used extensively when processing data. These operators are themselves functions - - - - which make use of Partial Application. - which make use of Partial Application. - - - - To learn more about these operators, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/functions/#function-composition-and-pipelining - To learn more about these operators, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/functions/#function-composition-and-pipelining - - - - To learn more about Partial Application, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/functions/#partial-application-of-arguments - To learn more about Partial Application, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/functions/#partial-application-of-arguments - - - - Squares a value. - Squares a value. - - - - Adds 1 to a value. - Adds 1 to a value. - - - - Tests if an integer value is odd via modulo. - Tests if an integer value is odd via modulo. - - - - A list of 5 numbers. More on lists later. - A list of 5 numbers. More on lists later. - - - - Given a list of integers, it filters out the even numbers, - Given a list of integers, it filters out the even numbers, - - - - squares the resulting odds, and adds 1 to the squared odds. - squares the resulting odds, and adds 1 to the squared odds. - - - - A shorter way to write 'squareOddValuesAndAddOne' is to nest each - A shorter way to write 'squareOddValuesAndAddOne' is to nest each - - - - sub-result into the function calls themselves. - sub-result into the function calls themselves. - - - - This makes the function much shorter, but it's difficult to see the - This makes the function much shorter, but it's difficult to see the - - - - order in which the data is processed. - order in which the data is processed. - - - - A preferred way to write 'squareOddValuesAndAddOne' is to use F# pipe operators. - A preferred way to write 'squareOddValuesAndAddOne' is to use F# pipe operators. - - - - This allows you to avoid creating intermediate results, but is much more readable - This allows you to avoid creating intermediate results, but is much more readable - - - - than nesting function calls like 'squareOddValuesAndAddOneNested' - than nesting function calls like 'squareOddValuesAndAddOneNested' - - - - You can shorten 'squareOddValuesAndAddOnePipeline' by moving the second `List.map` call - You can shorten 'squareOddValuesAndAddOnePipeline' by moving the second `List.map` call - - - - into the first, using a Lambda Function. - into the first, using a Lambda Function. - - - - Note that pipelines are also being used inside the lambda function. F# pipe operators - Note that pipelines are also being used inside the lambda function. F# pipe operators - - - - can be used for single values as well. This makes them very powerful for processing data. - can be used for single values as well. This makes them very powerful for processing data. - - - - Lastly, you can eliminate the need to explicitly take 'values' in as a parameter by using '>>' - Lastly, you can eliminate the need to explicitly take 'values' in as a parameter by using '>>' - - - - to compose the two core operations: filtering out even numbers, then squaring and adding one. - to compose the two core operations: filtering out even numbers, then squaring and adding one. - - - - Likewise, the 'fun x -> ...' bit of the lambda expression is also not needed, because 'x' is simply - Likewise, the 'fun x -> ...' bit of the lambda expression is also not needed, because 'x' is simply - - - - being defined in that scope so that it can be passed to a functional pipeline. Thus, '>>' can be used - being defined in that scope so that it can be passed to a functional pipeline. Thus, '>>' can be used - - - - there as well. - there as well. - - - - The result of 'squareOddValuesAndAddOneComposition' is itself another function which takes a - The result of 'squareOddValuesAndAddOneComposition' is itself another function which takes a - - - - list of integers as its input. If you execute 'squareOddValuesAndAddOneComposition' with a list - list of integers as its input. If you execute 'squareOddValuesAndAddOneComposition' with a list - - - - of integers, you'll notice that it produces the same results as previous functions. - of integers, you'll notice that it produces the same results as previous functions. - - - - This is using what is known as function composition. This is possible because functions in F# - This is using what is known as function composition. This is possible because functions in F# - - - - use Partial Application and the input and output types of each data processing operation match - use Partial Application and the input and output types of each data processing operation match - - - - the signatures of the functions we're using. - the signatures of the functions we're using. - - - - Lists are ordered, immutable, singly-linked lists. They are eager in their evaluation. - Lists are ordered, immutable, singly-linked lists. They are eager in their evaluation. - - - - This module shows various ways to generate lists and process lists with some functions - This module shows various ways to generate lists and process lists with some functions - - - - in the 'List' module in the F# Core Library. - in the 'List' module in the F# Core Library. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/lists - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/lists - - - - Lists are defined using [ ... ]. This is an empty list. - Lists are defined using [ ... ]. This is an empty list. - - - - This is a list with 3 elements. ';' is used to separate elements on the same line. - This is a list with 3 elements. ';' is used to separate elements on the same line. - - - - You can also separate elements by placing them on their own lines. - You can also separate elements by placing them on their own lines. - - - - This is a list of integers from 1 to 1000 - This is a list of integers from 1 to 1000 - - - - Lists can also be generated by computations. This is a list containing - Lists can also be generated by computations. This is a list containing - - - - all the days of the year. - all the days of the year. - - - - Print the first 5 elements of 'daysList' using 'List.take'. - Print the first 5 elements of 'daysList' using 'List.take'. - - - - Computations can include conditionals. This is a list containing the tuples - Computations can include conditionals. This is a list containing the tuples - - - - which are the coordinates of the black squares on a chess board. - which are the coordinates of the black squares on a chess board. - - - - Lists can be transformed using 'List.map' and other functional programming combinators. - Lists can be transformed using 'List.map' and other functional programming combinators. - - - - This definition produces a new list by squaring the numbers in numberList, using the pipeline - This definition produces a new list by squaring the numbers in numberList, using the pipeline - - - - operator to pass an argument to List.map. - operator to pass an argument to List.map. - - - - There are many other list combinations. The following computes the sum of the squares of the - There are many other list combinations. The following computes the sum of the squares of the - - - - numbers divisible by 3. - numbers divisible by 3. - - - - Arrays are fixed-size, mutable collections of elements of the same type. - Arrays are fixed-size, mutable collections of elements of the same type. - - - - Although they are similar to Lists (they support enumeration and have similar combinators for data processing), - Although they are similar to Lists (they support enumeration and have similar combinators for data processing), - - - - they are generally faster and support fast random access. This comes at the cost of being less safe by being mutable. - they are generally faster and support fast random access. This comes at the cost of being less safe by being mutable. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/arrays - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/arrays - - - - This is The empty array. Note that the syntax is similar to that of Lists, but uses `[| ... |]` instead. - This is The empty array. Note that the syntax is similar to that of Lists, but uses `[| ... |]` instead. - - - - Arrays are specified using the same range of constructs as lists. - Arrays are specified using the same range of constructs as lists. - - - - This is an array of numbers from 1 to 1000. - This is an array of numbers from 1 to 1000. - - - - This is an array containing only the words "hello" and "world". - This is an array containing only the words "hello" and "world". - - - - This is an array initialized by index and containing the even numbers from 0 to 2000. - This is an array initialized by index and containing the even numbers from 0 to 2000. - - - - Sub-arrays are extracted using slicing notation. - Sub-arrays are extracted using slicing notation. - - - - You can loop over arrays and lists using 'for' loops. - You can loop over arrays and lists using 'for' loops. - - - - You can modify the contents of an an array element by using the left arrow assignment operator. - You can modify the contents of an an array element by using the left arrow assignment operator. - - - - To learn more about this operator, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/values/index#mutable-variables - To learn more about this operator, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/values/index#mutable-variables - - - - You can transform arrays using 'Array.map' and other functional programming operations. - You can transform arrays using 'Array.map' and other functional programming operations. - - - - The following calculates the sum of the lengths of the words that start with 'h'. - The following calculates the sum of the lengths of the words that start with 'h'. - - - - Sequences are a logical series of elements, all of the same type. These are a more general type than Lists and Arrays. - Sequences are a logical series of elements, all of the same type. These are a more general type than Lists and Arrays. - - - - Sequences are evaluated on-demand and are re-evaluated each time they are iterated. - Sequences are evaluated on-demand and are re-evaluated each time they are iterated. - - - - An F# sequence is an alias for a .NET System.Collections.Generic.IEnumerable<'T>. - An F# sequence is an alias for a .NET System.Collections.Generic.IEnumerable<'T>. - - - - Sequence processing functions can be applied to Lists and Arrays as well. - Sequence processing functions can be applied to Lists and Arrays as well. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/sequences - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/sequences - - - - This is the empty sequence. - This is the empty sequence. - - - - This a sequence of values. - This a sequence of values. - - - - This is an on-demand sequence from 1 to 1000. - This is an on-demand sequence from 1 to 1000. - - - - This is a sequence producing the words "hello" and "world" - This is a sequence producing the words "hello" and "world" - - - - This sequence producing the even numbers up to 2000. - This sequence producing the even numbers up to 2000. - - - - This is an infinite sequence which is a random walk. - This is an infinite sequence which is a random walk. - - - - This example uses yield! to return each element of a subsequence. - This example uses yield! to return each element of a subsequence. - - - - This example shows the first 100 elements of the random walk. - This example shows the first 100 elements of the random walk. - - - - Recursive functions can call themselves. In F#, functions are only recursive - Recursive functions can call themselves. In F#, functions are only recursive - - - - when declared using 'let rec'. - when declared using 'let rec'. - - - - Recursion is the preferred way to process sequences or collections in F#. - Recursion is the preferred way to process sequences or collections in F#. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/functions/index#recursive-functions - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/functions/index#recursive-functions - - - - This example shows a recursive function that computes the factorial of an - This example shows a recursive function that computes the factorial of an - - - - integer. It uses 'let rec' to define a recursive function. - integer. It uses 'let rec' to define a recursive function. - - - - Computes the greatest common factor of two integers. - Computes the greatest common factor of two integers. - - - - Since all of the recursive calls are tail calls, - Since all of the recursive calls are tail calls, - - - - the compiler will turn the function into a loop, - the compiler will turn the function into a loop, - - - - which improves performance and reduces memory consumption. - which improves performance and reduces memory consumption. - - - - This example computes the sum of a list of integers using recursion. - This example computes the sum of a list of integers using recursion. - - - - This makes 'sumList' tail recursive, using a helper function with a result accumulator. - This makes 'sumList' tail recursive, using a helper function with a result accumulator. - - - - This invokes the tail recursive helper function, providing '0' as a seed accumulator. - This invokes the tail recursive helper function, providing '0' as a seed accumulator. - - - - An approach like this is common in F#. - An approach like this is common in F#. - - - - Records are an aggregate of named values, with optional members (such as methods). - Records are an aggregate of named values, with optional members (such as methods). - - - - They are immutable and have structural equality semantics. - They are immutable and have structural equality semantics. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/records - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/records - - - - This example shows how to define a new record type. - This example shows how to define a new record type. - - - - This example shows how to instantiate a record type. - This example shows how to instantiate a record type. - - - - You can also do this on the same line with ';' separators. - You can also do this on the same line with ';' separators. - - - - This example shows how to use "copy-and-update" on record values. It creates - This example shows how to use "copy-and-update" on record values. It creates - - - - a new record value that is a copy of contact1, but has different values for - a new record value that is a copy of contact1, but has different values for - - - - the 'Phone' and 'Verified' fields. - the 'Phone' and 'Verified' fields. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/copy-and-update-record-expressions - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/copy-and-update-record-expressions - - - - This example shows how to write a function that processes a record value. - This example shows how to write a function that processes a record value. - - - - It converts a 'ContactCard' object to a string. - It converts a 'ContactCard' object to a string. - - - - This is an example of a Record with a member. - This is an example of a Record with a member. - - - - Members can implement object-oriented members. - Members can implement object-oriented members. - - - - Members are accessed via the '.' operator on an instantiated type. - Members are accessed via the '.' operator on an instantiated type. - - - - Records can also be represented as structs via the 'Struct' attribute. - Records can also be represented as structs via the 'Struct' attribute. - - - - This is helpful in situations where the performance of structs outweighs - This is helpful in situations where the performance of structs outweighs - - - - the flexibility of reference types. - the flexibility of reference types. - - - - Discriminated Unions (DU for short) are values which could be a number of named forms or cases. - Discriminated Unions (DU for short) are values which could be a number of named forms or cases. - - - - Data stored in DUs can be one of several distinct values. - Data stored in DUs can be one of several distinct values. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/discriminated-unions - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/discriminated-unions - - - - The following represents the suit of a playing card. - The following represents the suit of a playing card. - - - - A Disciminated Union can also be used to represent the rank of a playing card. - A Disciminated Union can also be used to represent the rank of a playing card. - - - - Represents the rank of cards 2 .. 10 - Represents the rank of cards 2 .. 10 - - - - Discriminated Unions can also implement object-oriented members. - Discriminated Unions can also implement object-oriented members. - - - - This is a record type that combines a Suit and a Rank. - This is a record type that combines a Suit and a Rank. - - - - It's common to use both Records and Disciminated Unions when representing data. - It's common to use both Records and Disciminated Unions when representing data. - - - - This computes a list representing all the cards in the deck. - This computes a list representing all the cards in the deck. - - - - This example converts a 'Card' object to a string. - This example converts a 'Card' object to a string. - - - - This example prints all the cards in a playing deck. - This example prints all the cards in a playing deck. - - - - Single-case DUs are often used for domain modeling. This can buy you extra type safety - Single-case DUs are often used for domain modeling. This can buy you extra type safety - - - - over primitive types such as strings and ints. - over primitive types such as strings and ints. - - - - Single-case DUs cannot be implicitly converted to or from the type they wrap. - Single-case DUs cannot be implicitly converted to or from the type they wrap. - - - - For example, a function which takes in an Address cannot accept a string as that input, - For example, a function which takes in an Address cannot accept a string as that input, - - - - or vive/versa. - or vive/versa. - - - - You can easily instantiate a single-case DU as follows. - You can easily instantiate a single-case DU as follows. - - - - When you need the value, you can unwrap the underlying value with a simple function. - When you need the value, you can unwrap the underlying value with a simple function. - - - - Printing single-case DUs is simple with unwrapping functions. - Printing single-case DUs is simple with unwrapping functions. - - - - Disciminated Unions also support recursive definitions. - Disciminated Unions also support recursive definitions. - - - - This represents a Binary Search Tree, with one case being the Empty tree, - This represents a Binary Search Tree, with one case being the Empty tree, - - - - and the other being a Node with a value and two subtrees. - and the other being a Node with a value and two subtrees. - - - - Check if an item exists in the binary search tree. - Check if an item exists in the binary search tree. - - - - Searches recursively using Pattern Matching. Returns true if it exists; otherwise, false. - Searches recursively using Pattern Matching. Returns true if it exists; otherwise, false. - - - - Check the left subtree. - Check the left subtree. - - - - Check the right subtree. - Check the right subtree. - - - - Inserts an item in the Binary Search Tree. - Inserts an item in the Binary Search Tree. - - - - Finds the place to insert recursively using Pattern Matching, then inserts a new node. - Finds the place to insert recursively using Pattern Matching, then inserts a new node. - - - - If the item is already present, it does not insert anything. - If the item is already present, it does not insert anything. - - - - No need to insert, it already exists; return the node. - No need to insert, it already exists; return the node. - - - - Call into left subtree. - Call into left subtree. - - - - Call into right subtree. - Call into right subtree. - - - - Discriminated Unions can also be represented as structs via the 'Struct' attribute. - Discriminated Unions can also be represented as structs via the 'Struct' attribute. - - - - This is helpful in situations where the performance of structs outweighs - This is helpful in situations where the performance of structs outweighs - - - - the flexibility of reference types. - the flexibility of reference types. - - - - However, there are two important things to know when doing this: - However, there are two important things to know when doing this: - - - - 1. A struct DU cannot be recursively-defined. - 1. A struct DU cannot be recursively-defined. - - - - 2. A struct DU must have unique names for each of its cases. - 2. A struct DU must have unique names for each of its cases. - - - - Pattern Matching is a feature of F# that allows you to utilize Patterns, - Pattern Matching is a feature of F# that allows you to utilize Patterns, - - - - which are a way to compare data with a logical structure or structures, - which are a way to compare data with a logical structure or structures, - - - - decompose data into constituent parts, or extract information from data in various ways. - decompose data into constituent parts, or extract information from data in various ways. - - - - You can then dispatch on the "shape" of a pattern via Pattern Matching. - You can then dispatch on the "shape" of a pattern via Pattern Matching. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/pattern-matching - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/pattern-matching - - - - A record for a person's first and last name - A record for a person's first and last name - - - - A Discriminated Union of 3 different kinds of employees - A Discriminated Union of 3 different kinds of employees - - - - Count everyone underneath the employee in the management hierarchy, - Count everyone underneath the employee in the management hierarchy, - - - - including the employee. - including the employee. - - - - Find all managers/executives named "Dave" who do not have any reports. - Find all managers/executives named "Dave" who do not have any reports. - - - - This uses the 'function' shorthand to as a lambda expression. - This uses the 'function' shorthand to as a lambda expression. - - - - [] matches an empty list. - [] matches an empty list. - - - - '_' is a wildcard pattern that matches anything. - '_' is a wildcard pattern that matches anything. - - - - This handles the "or else" case. - This handles the "or else" case. - - - - You can also use the shorthand function construct for pattern matching, - You can also use the shorthand function construct for pattern matching, - - - - which is useful when you're writing functions which make use of Partial Application. - which is useful when you're writing functions which make use of Partial Application. - - - - Define some more functions which parse with the helper function. - Define some more functions which parse with the helper function. - - - - Active Patterns are another powerful construct to use with pattern matching. - Active Patterns are another powerful construct to use with pattern matching. - - - - They allow you to partition input data into custom forms, decomposing them at the pattern match call site. - They allow you to partition input data into custom forms, decomposing them at the pattern match call site. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/active-patterns - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/active-patterns - - - - Pattern Matching via 'function' keyword and Active Patterns often looks like this. - Pattern Matching via 'function' keyword and Active Patterns often looks like this. - - - - Call the printer with some different values to parse. - Call the printer with some different values to parse. - - - - Option values are any kind of value tagged with either 'Some' or 'None'. - Option values are any kind of value tagged with either 'Some' or 'None'. - - - - They are used extensively in F# code to represent the cases where many other - They are used extensively in F# code to represent the cases where many other - - - - languages would use null references. - languages would use null references. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/options - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/options - - - - First, define a zipcode defined via Single-case Discriminated Union. - First, define a zipcode defined via Single-case Discriminated Union. - - - - Next, define a type where the ZipCode is optional. - Next, define a type where the ZipCode is optional. - - - - Next, define an interface type that represents an object to compute the shipping zone for the customer's zip code, - Next, define an interface type that represents an object to compute the shipping zone for the customer's zip code, - - - - given implementations for the 'getState' and 'getShippingZone' abstract methods. - given implementations for the 'getState' and 'getShippingZone' abstract methods. - - - - Next, calculate a shipping zone for a customer using a calculator instance. - Next, calculate a shipping zone for a customer using a calculator instance. - - - - This uses combinators in the Option module to allow a functional pipeline for - This uses combinators in the Option module to allow a functional pipeline for - - - - transforming data with Optionals. - transforming data with Optionals. - - - - Units of measure are a way to annotate primitive numeric types in a type-safe way. - Units of measure are a way to annotate primitive numeric types in a type-safe way. - - - - You can then perform type-safe arithmetic on these values. - You can then perform type-safe arithmetic on these values. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/units-of-measure - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/units-of-measure - - - - First, open a collection of common unit names - First, open a collection of common unit names - - - - Define a unitized constant - Define a unitized constant - - - - Next, define a new unit type - Next, define a new unit type - - - - Conversion factor mile to meter. - Conversion factor mile to meter. - - - - Define a unitized constant - Define a unitized constant - - - - Compute metric-system constant - Compute metric-system constant - - - - Values using Units of Measure can be used just like the primitive numeric type for things like printing. - Values using Units of Measure can be used just like the primitive numeric type for things like printing. - - - - Classes are a way of defining new object types in F#, and support standard Object-oriented constructs. - Classes are a way of defining new object types in F#, and support standard Object-oriented constructs. - - - - They can have a variety of members (methods, properties, events, etc.) - They can have a variety of members (methods, properties, events, etc.) - - - - To learn more about Classes, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/classes - To learn more about Classes, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/classes - - - - To learn more about Members, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/members - To learn more about Members, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/members - - - - A simple two-dimensional Vector class. - A simple two-dimensional Vector class. - - - - The class's constructor is on the first line, - The class's constructor is on the first line, - - - - and takes two arguments: dx and dy, both of type 'double'. - and takes two arguments: dx and dy, both of type 'double'. - - - - This internal field stores the length of the vector, computed when the - This internal field stores the length of the vector, computed when the - - - - object is constructed - object is constructed - - - - 'this' specifies a name for the object's self identifier. - 'this' specifies a name for the object's self identifier. - - - - In instance methods, it must appear before the member name. - In instance methods, it must appear before the member name. - - - - This member is a method. The previous members were properties. - This member is a method. The previous members were properties. - - - - This is how you instantiate the Vector2D class. - This is how you instantiate the Vector2D class. - - - - Get a new scaled vector object, without modifying the original object. - Get a new scaled vector object, without modifying the original object. - - - - Generic classes allow types to be defined with respect to a set of type parameters. - Generic classes allow types to be defined with respect to a set of type parameters. - - - - In the following, 'T is the type parameter for the class. - In the following, 'T is the type parameter for the class. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/generics/ - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/generics/ - - - - This internal field store the states in a list. - This internal field store the states in a list. - - - - Add a new element to the list of states. - Add a new element to the list of states. - - - - use the '<-' operator to mutate the value. - use the '<-' operator to mutate the value. - - - - Get the entire list of historical states. - Get the entire list of historical states. - - - - Get the latest state. - Get the latest state. - - - - An 'int' instance of the state tracker class. Note that the type parameter is inferred. - An 'int' instance of the state tracker class. Note that the type parameter is inferred. - - - - Add a state - Add a state - - - - Interfaces are object types with only 'abstract' members. - Interfaces are object types with only 'abstract' members. - - - - Object types and object expressions can implement interfaces. - Object types and object expressions can implement interfaces. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/interfaces - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/interfaces - - - - This is a type that implements IDisposable. - This is a type that implements IDisposable. - - - - This is the implementation of IDisposable members. - This is the implementation of IDisposable members. - - - - This is an object that implements IDisposable via an Object Expression - This is an object that implements IDisposable via an Object Expression - - - - Unlike other languages such as C# or Java, a new type definition is not needed - Unlike other languages such as C# or Java, a new type definition is not needed - - - - to implement an interface. - to implement an interface. - - - - The FSharp.Core library defines a range of parallel processing functions. Here - The FSharp.Core library defines a range of parallel processing functions. Here - - - - you use some functions for parallel processing over arrays. - you use some functions for parallel processing over arrays. - - - - To learn more, see: https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/array.parallel-module-%5Bfsharp%5D - To learn more, see: https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/array.parallel-module-%5Bfsharp%5D - - - - First, an array of inputs. - First, an array of inputs. - - - - Next, define a functions that does some CPU intensive computation. - Next, define a functions that does some CPU intensive computation. - - - - Next, do a parallel map over a large input array. - Next, do a parallel map over a large input array. - - - - Next, print the results. - Next, print the results. - - - - Events are a common idiom for .NET programming, especially with WinForms or WPF applications. - Events are a common idiom for .NET programming, especially with WinForms or WPF applications. - - - - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/members/events - To learn more, see: https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/members/events - - - - First, create instance of Event object that consists of subscription point (event.Publish) and event trigger (event.Trigger). - First, create instance of Event object that consists of subscription point (event.Publish) and event trigger (event.Trigger). - - - - Next, add handler to the event. - Next, add handler to the event. - - - - Next, trigger the event. - Next, trigger the event. - - - - Next, create an instance of Event that follows standard .NET convention: (sender, EventArgs). - Next, create an instance of Event that follows standard .NET convention: (sender, EventArgs). - - - - Next, add a handler for this new event. - Next, add a handler for this new event. - - - - Next, trigger this event (note that sender argument should be set). - Next, trigger this event (note that sender argument should be set). - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.en.xlf b/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.en.xlf deleted file mode 100644 index ce6a404fc97..00000000000 --- a/vsintegration/src/FSharp.Editor/xlf/FSharp.Editor.en.xlf +++ /dev/null @@ -1,167 +0,0 @@ - - - - - - Add 'new' keyword - Add 'new' keyword - - - - Implement interface - Implement interface - - - - Implement interface without type annotation - Implement interface without type annotation - - - - Prefix '{0}' with underscore - Prefix '{0}' with underscore - - - - Rename '{0}' to '_' - Rename '{0}' to '_' - - - - Simplify name - Simplify name - - - - Name can be simplified. - Name can be simplified. - - - - F# Functions / Methods - F# Functions / Methods - - - - F# Mutable Variables / Reference Cells - F# Mutable Variables / Reference Cells - - - - F# Printf Format - F# Printf Format - - - - F# Properties - F# Properties - - - - F# Disposable Types - F# Disposable Types - - - - Remove unused open declarations - Remove unused open declarations - - - - Open declaration can be removed. - Open declaration can be removed. - - - - IntelliSense - IntelliSense - - - - QuickInfo - QuickInfo - - - - Add an assembly reference to '{0}' - Add an assembly reference to '{0}' - - - - Add a project reference to '{0}' - Add a project reference to '{0}' - - - - Code Fixes - Code Fixes - - - - Performance - Performance - - - - The value is unused - The value is unused - - - - Cannot determine the symbol under the caret - Cannot determine the symbol under the caret - - - - Cannot navigate to the requested location - Cannot navigate to the requested location - - - - Locating the symbol under the caret... - Locating the symbol under the caret... - - - - Navigating to symbol... - Navigating to symbol... - - - - Navigate to symbol failed: {0} - Navigate to symbol failed: {0} - - - - Exceptions: - Exceptions: - - - - Generic parameters: - Generic parameters: - - - - Rename '{0}' to '__' - Rename '{0}' to '__' - - - - Advanced - Advanced - - - - CodeLens - CodeLens - - - - Formatting - Formatting - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.LanguageService.Base/xlf/Microsoft.VisualStudio.Package.LanguageService.en.xlf b/vsintegration/src/FSharp.LanguageService.Base/xlf/Microsoft.VisualStudio.Package.LanguageService.en.xlf deleted file mode 100644 index d535b12bff1..00000000000 --- a/vsintegration/src/FSharp.LanguageService.Base/xlf/Microsoft.VisualStudio.Package.LanguageService.en.xlf +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - Matches: {0} - Matches: {0} - This is shown in status bar when ctrl-] brace matching is done. - - - The buffer has changed since the EditArray was created, so edits cannot be applied. - The buffer has changed since the EditArray was created, so edits cannot be applied. - InvalidOperationException - - - Members - Members - Tooltip for the drop down combo at top of document window showing list of known members. - - - Types - Types - Tooltip for the drop down combo at top of document window showing list of known types. - - - Comment Selection - Comment Selection - IVsCompoundAction::OpenCompoundAction description - - - Existing edit number {0} intersects 'editSpan' argument. - Existing edit number {0} intersects 'editSpan' argument. - ArgumentException. - - - Format Span - Format Span - IVsCompoundAction::OpenCompoundAction description. - - - The maximum number of errors or warnings has been reached. - The maximum number of errors or warnings has been reached. - Shown in Error List window - - - There is no active expansion session. - There is no active expansion session. - InvalidOperationException - - - {0}... - {0}... - Adds an ellipsis for text that is truncated before displaying to the user. - - - Uncomment Selection - Uncomment Selection - IVsCompoundAction::OpenCompoundAction description - - - The file cannot be opened with the selected editor. Please choose another editor. - The file cannot be opened with the selected editor. Please choose another editor. - Message returned when Open With... is used, and editor does not support the specified file type. - - - PrepareTemplate has not been called. - PrepareTemplate has not been called. - InvalidOperationException - - - IVsTextLines buffer does not match the expected buffer - IVsTextLines buffer does not match the expected buffer - ArgumentException - - - Unrecognized filter format: {0} - Unrecognized filter format: {0} - ArgumentException - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.en.xlf b/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.en.xlf deleted file mode 100644 index a1637f05fa5..00000000000 --- a/vsintegration/src/FSharp.LanguageService/xlf/FSLangSvcStrings.en.xlf +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - (The documentation cache is still being constructed. Please try again in a few seconds.) - (The documentation cache is still being constructed. Please try again in a few seconds.) - - - - Exceptions: - Exceptions: - - - - Loading... - Loading... - displayed when waiting for IntelliSense to load - - - Cannot navigate to definition. - Cannot navigate to definition. - - - - Cannot navigate to definition. Cursor is not on identifier. - Cannot navigate to definition. Cursor is not on identifier. - - - - Cannot navigate to the provided member '{0}'. - Cannot navigate to the provided member '{0}'. - - - - Cannot navigate to the provided type '{0}'. - Cannot navigate to the provided type '{0}'. - - - - Cannot navigate to definition. Type check information is not available, please try later. - Cannot navigate to definition. Type check information is not available, please try later. - - - - Cannot navigate to definition. Source code is not available. - Cannot navigate to definition. Source code is not available. - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.en.xlf b/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.en.xlf deleted file mode 100644 index 04cca560cc6..00000000000 --- a/vsintegration/src/FSharp.LanguageService/xlf/VSPackage.en.xlf +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - F# - F# - lock - - - Excluded Code - Excluded Code - - - - Preprocessor Keyword - Preprocessor Keyword - - - - Operator - Operator - - - - F# File (*.fs) - F# File (*.fs) - - - - F# Interface File (*.fsi) - F# Interface File (*.fsi) - - - - F# Script File (*.fsx) - F# Script File (*.fsx) - - - - F# Script File (*.fsscript) - F# Script File (*.fsscript) - - - - Comment - Comment - - - - Identifier - Identifier - - - - Keyword - Keyword - - - - Number - Number - - - - String - String - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.en.xlf b/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.en.xlf deleted file mode 100644 index beada53988c..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/xlf/Microsoft.VisualStudio.Package.Project.en.xlf +++ /dev/null @@ -1,820 +0,0 @@ - - - - - - Failed to add file '{0}' to project as project is null. - Failed to add file '{0}' to project as project is null. - - - - Advanced - Advanced - Project Property Page Caption - - - A reference to '{0}' could not be added. - A reference to '{0}' could not be added. - ReferenceCouldNotBeAdded error message - - - A reference to '{0}' could not be added. A reference to the component '{1}' already exists in the project. - A reference to '{0}' could not be added. A reference to the component '{1}' already exists in the project. - ReferenceAlreadyExists error message - - - A reference to '{0}' (with assembly name '{1}') could not be added. A reference to the component '{2}' with the same assembly name already exists in the project. - A reference to '{0}' (with assembly name '{1}') could not be added. A reference to the component '{2}' with the same assembly name already exists in the project. - ReferenceAlreadyExists error message - - - Could not load attribute '{0}' from project file '{1}'. - Could not load attribute '{0}' from project file '{1}'. - - - - Build Action - Build Action - Project Build Property Name - - - How the file relates to the build and deployment process - How the file relates to the build and deployment process - Project Build Property Description - - - Verbosity - Verbosity - - - - Specify how much information is included in the build output - Specify how much information is included in the build output - - - - ECMA-335 CLI compatible framework (location must be provided) - ECMA-335 CLI compatible framework (location must be provided) - Target platform drop down option - - - Compile - Compile - Build Action - drop down option - - - If you change a file name extension, the file may become unusable. Are you sure you want to change it? - If you change a file name extension, the file may become unusable. Are you sure you want to change it? - - - - A file with name '{0}' already exists and is open in an editor. Please give a unique name to the item you are adding, or delete the existing item first. - A file with name '{0}' already exists and is open in an editor. Please give a unique name to the item you are adding, or delete the existing item first. - - - - Cannot save '{0}' as it is not open in the editor. - Cannot save '{0}' as it is not open in the editor. - - - - Content - Content - Build Action - drop down option - - - Copy Local - Copy Local - File property - - - Indicates whether the reference will be copied to the output directory. - Indicates whether the reference will be copied to the output directory. - - - - Detailed - Detailed - - - - Diagnostic - Diagnostic - - - - Directory already exists - Directory already exists - - - - Error opening specified view '{0}' using editor '{1}' - Error opening specified view '{0}' using editor '{1}' - - - - Embedded Resource - Embedded Resource - Build Action - drop down option - - - error - error - - - - Files and folders cannot be: -- Empty strings -- System reserved names, including 'CON', 'AUX', PRN', 'COM1' or 'LPT2' -- contain only '.' -- have any of the following characters: / ? : & \ * " < > | # % - Files and folders cannot be: -- Empty strings -- System reserved names, including 'CON', 'AUX', PRN', 'COM1' or 'LPT2' -- contain only '.' -- have any of the following characters: / ? : & \ * " < > | # % - - - - The name you provided is not a valid project name. - The name you provided is not a valid project name. - - - - MSBuild path not found in registry. Please reinstall to fix the problem. - MSBuild path not found in registry. Please reinstall to fix the problem. - - - - Error Saving File - Error Saving File - - - - Console Application - Console Application - - - - Expecting object of type {0}. - Expecting object of type {0}. - - - - Failed to retrieve msbuild property {0} from the project file. - Failed to retrieve msbuild property {0} from the project file. - The exception message thrown when getting a property from msbuild fails. - - - A file with the same name '{0}' already exists. Do you want to overwrite it? - A file with the same name '{0}' already exists. Do you want to overwrite it? - - - - A file with the same name '{0}' already exists. - A file with the same name '{0}' already exists. - - - - Destination File Exists - Destination File Exists - - - - A file of this name is already part of the project. Do you want to overwrite it? - A file of this name is already part of the project. Do you want to overwrite it? - - - - Destination File Exists - Destination File Exists - - - - A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. - A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. - - - - Error Copying File - Error Copying File - - - - File Name - File Name - - - - File and folder names cannot contain a leading period. - File and folder names cannot contain a leading period. - - - - The name of the file or folder - The name of the file or folder - - - - Folder Name - Folder Name - - - - Name of this folder - Name of this folder - - - - Full Path - Full Path - - - - Location of the file - Location of the file - - - - The item '{0}' does not exist in the project directory. It may have been moved, renamed or deleted. - The item '{0}' does not exist in the project directory. It may have been moved, renamed or deleted. - - - - Cannot save '{0}' outside the project directory. Linked items are not supported. - Cannot save '{0}' outside the project directory. Linked items are not supported. - - - - Class Library - Class Library - - - - Minimal - Minimal - - - - Misc - Misc - - - - None - None - - - - Normal - Normal - - - - Item is not available or corrupted and thus cannot be pasted. - Item is not available or corrupted and thus cannot be pasted. - - - - Program - Program - - - - Project - Project - - - - A reference to library '{0}' cannot be added. Adding this project as a reference would cause a circular dependency. - A reference to library '{0}' cannot be added. Adding this project as a reference would cause a circular dependency. - - - - Project File - Project File - - - - The name of the file containing build, configuration, and other information about the project. - The name of the file containing build, configuration, and other information about the project. - - - - Project Folder - Project Folder - - - - The absolute location of the project. - The absolute location of the project. - - - - Quiet - Quiet - - - - (Name) - (Name) - - - - References - References - - - - Display name of the reference - Display name of the reference - - - - Rename directory failed. {0} - Rename directory failed. {0} - - - - RTL_False - RTL_False - - - - Save? - Save? - - - - Do you want to save modified documents? - Do you want to save modified documents? - - - - The project file can only be saved into the project location '{0}'. - The project file can only be saved into the project location '{0}'. - - - - Error opening specified view '{0}' using standard editor. - Error opening specified view '{0}' using standard editor. - - - - URL - URL - - - - You are trying to use an item that has already been deleted or that does not exist. - You are trying to use an item that has already been deleted or that does not exist. - - - - Microsoft .Net Framework v1.0 - Microsoft .Net Framework v1.0 - - - - Microsoft .Net Framework v1.1 - Microsoft .Net Framework v1.1 - - - - Microsoft .Net Framework v2.0 - Microsoft .Net Framework v2.0 - - - - warning - warning - - - - Windows Application - Windows Application - - - - Automation object invalid. - Automation object invalid. - - - - The command you are attempting cannot be completed because the file '{0}' that must be modified cannot be changed. If the file is under source control, you may want to check it out; if the file is read-only on disk, you may want to change its attributes. - The command you are attempting cannot be completed because the file '{0}' that must be modified cannot be changed. If the file is under source control, you may want to check it out; if the file is read-only on disk, you may want to change its attributes. - MsgBox - - - Parameter must be a valid guid. - Parameter must be a valid guid. - Error message in the ArgumentException for a parameter that is not a valid guid. - - - Invalid logger type\nExpected: {0}\nReceived: {1} - Invalid logger type\nExpected: {0}\nReceived: {1} - Error message thrown for when an invalid logger type is set. - - - InvalidParameter - InvalidParameter - Generic error message for invalid parameters. - - - ParameterCannotBeNullOEmpty - ParameterCannotBeNullOEmpty - Error message for string parameters that cannot be null or empty. - - - Parameter must be a valid item identifier. - Parameter must be a valid item identifier. - Error message thrown when an invalid item id is retrieved. - - - File Properties - File Properties - - - - Folder Properties - Folder Properties - - - - Project Properties - Project Properties - - - - Reference Properties - Reference Properties - - - - A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. - A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. - - - - This folder cannot be renamed to '{0}' as it already exists on disk.\n\nOnly empty folders can be renamed to existing folders. This folder contains files within it on disk. - This folder cannot be renamed to '{0}' as it already exists on disk.\n\nOnly empty folders can be renamed to existing folders. This folder contains files within it on disk. - - - - Build - Build - - - - Output Path - Output Path - - - - The path to the primary output - The path to the primary output - - - - The complete path to '{0}' exceeds the maximum number of characters permitted by the file system. - The complete path to '{0}' exceeds the maximum number of characters permitted by the file system. - - - - Custom Tool - Custom Tool - - - - Specifies the tool that transforms a file at design time and places the output of that transformation into another file. For example, a dataset (.xsd) file comes with a default custom tool. - Specifies the tool that transforms a file at design time and places the output of that transformation into another file. For example, a dataset (.xsd) file comes with a default custom tool. - - - - Custom Tool Namespace - Custom Tool Namespace - - - - The namespace into which the output of the custom tool is placed. - The namespace into which the output of the custom tool is placed. - - - - Primary Output - Primary Output - - - - Content Files - Content Files - - - - Documentation Files - Documentation Files - - - - Localized Resources - Localized Resources - - - - Source Files - Source Files - - - - Debug Symbols - Debug Symbols - - - - XML Serialization Assemblies - XML Serialization Assemblies - - - - Contains the DLL or EXE built by the project. - Contains the DLL or EXE built by the project. - - - - Contains all content files in the project. - Contains all content files in the project. - - - - Contains the XML Documentation files for the project. - Contains the XML Documentation files for the project. - - - - Contains the satellite assemblies for each culture's resources. - Contains the satellite assemblies for each culture's resources. - - - - Contains all source files in the project. - Contains all source files in the project. - - - - Contains the debugging files for the project. - Contains the debugging files for the project. - - - - Contains the XML serialization assemblies for the project. - Contains the XML serialization assemblies for the project. - - - - The project file '{0}' has been modified outside of Visual Studio. Do you want to reload the project? - The project file '{0}' has been modified outside of Visual Studio. Do you want to reload the project? - - - - The nested project has failed to reload. - The nested project has failed to reload. - - - - The item '{0}' cannot be found on disk, either because it has been renamed, deleted, or moved to a new location. - The item '{0}' cannot be found on disk, either because it has been renamed, deleted, or moved to a new location. - - - - A reference to {0} could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component. - A reference to {0} could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component. - - - - An 'Import' of the file '{1}' was found in the project file '{0}'. This file is not registered as a safe file to import, and could contain targets and tasks that are harmful. If this imported file is indeed considered safe, then it can be registered by writing to the registry key {2}. - An 'Import' of the file '{1}' was found in the project file '{0}'. This file is not registered as a safe file to import, and could contain targets and tasks that are harmful. If this imported file is indeed considered safe, then it can be registered by writing to the registry key {2}. - - - - An 'Import' of the file '{1}' was found in the user project file '{0}'. All imports in user project files are considered unsafe. - An 'Import' of the file '{1}' was found in the user project file '{0}'. All imports in user project files are considered unsafe. - - - - One or more items named '{1}' were found in the project file '{0}'. These items normally should not be specified in the project file. They can change the way targets and tasks are executed during project load, and this could have harmful effects. - One or more items named '{1}' were found in the project file '{0}'. These items normally should not be specified in the project file. They can change the way targets and tasks are executed during project load, and this could have harmful effects. - - - - A property named '{1}' was found in the project file '{0}'. This property normally should not be specified in the project file. Its value can change the way targets and tasks are executed during project load, and this could have harmful effects. - A property named '{1}' was found in the project file '{0}'. This property normally should not be specified in the project file. Its value can change the way targets and tasks are executed during project load, and this could have harmful effects. - - - - A 'UsingTask' tag which registers the '{1}' task was found in the project file '{0}'. 'UsingTask' tags in the project file take precedence over those in the imported .TARGETS files, and therefore could be used to execute arbitrary code during an otherwise unmodified build process. - A 'UsingTask' tag which registers the '{1}' task was found in the project file '{0}'. 'UsingTask' tags in the project file take precedence over those in the imported .TARGETS files, and therefore could be used to execute arbitrary code during an otherwise unmodified build process. - - - - A 'Target' named '{1}' was found in the project file '{0}'. The tasks within this target could contain arbitrary code and may get executed as soon as the project is loaded in the IDE. - A 'Target' named '{1}' was found in the project file '{0}'. The tasks within this target could contain arbitrary code and may get executed as soon as the project is loaded in the IDE. - - - - An item referring to the file '{1}' was found in the project file '{0}'. Since this file is located within a system directory, root directory, or network share, it could be harmful to write to this file. - An item referring to the file '{1}' was found in the project file '{0}'. Since this file is located within a system directory, root directory, or network share, it could be harmful to write to this file. - - - - The project location is not trusted:{0}{0}{1}{0}{0}Running the application may result in security exceptions when it attempts to perform actions which require full trust.{0}{0}Click OK to ignore and continue. - The project location is not trusted:{0}{0}{1}{0}{0}Running the application may result in security exceptions when it attempts to perform actions which require full trust.{0}{0}Click OK to ignore and continue. - - - - Exception was thrown during BuildBegin event\n{0} - Exception was thrown during BuildBegin event\n{0} - - - - Copy always - Copy always - CopyToOutputDirectory - drop down option - - - Copy to Output Directory - Copy to Output Directory - - - - Specifies the source file will be copied to the output directory - Specifies the source file will be copied to the output directory - - - - Copy if newer - Copy if newer - CopyToOutputDirectory - drop down option - - - Do not copy - Do not copy - CopyToOutputDirectory - drop down option - - - Specific Version - Specific Version - - - - Indicates whether this reference is to a specific version of an assembly. - Indicates whether this reference is to a specific version of an assembly. - - - - Microsoft Visual F# does not support zero-impact projects. To create an F# project from this project template, either go to the Visual Studio menu 'Tools, Options..., Projects and Solutions, General' and check the box marked 'Save new projects when created', or specify <PromptForSaveOnCreation>true</PromptForSaveOnCreation> in the <TemplateData> section of this project template's .vstemplate file, and then retry this operation. - Microsoft Visual F# does not support zero-impact projects. To create an F# project from this project template, either go to the Visual Studio menu 'Tools, Options..., Projects and Solutions, General' and check the box marked 'Save new projects when created', or specify <PromptForSaveOnCreation>true</PromptForSaveOnCreation> in the <TemplateData> section of this project template's .vstemplate file, and then retry this operation. - - - - "Cannot open F# project '{0}'. \nThis project uses wildcards in item specification: \n'{2}' for item type '{1}'\n\nWildcards in F# projects are not currently supported. - "Cannot open F# project '{0}'. \nThis project uses wildcards in item specification: \n'{2}' for item type '{1}'\n\nWildcards in F# projects are not currently supported. - - - - "Cannot add file {3} to F# project '{0}'. \nThis project uses wildcards in item specification: \n'{2}' for item type '{1}'\n\nWildcards in F# projects are not currently supported. - "Cannot add file {3} to F# project '{0}'. \nThis project uses wildcards in item specification: \n'{2}' for item type '{1}'\n\nWildcards in F# projects are not currently supported. - - - - Cannot open project file for edit. - Cannot open project file for edit. - - - - Project file was checked out and is already upgraded. - Project file was checked out and is already upgraded. - - - - A project with an Output Type of Class Library cannot be started directly.\n\nIn order to debug this project, add an executable project to this solution which references the library project. Set the executable project as the startup project. - A project with an Output Type of Class Library cannot be started directly.\n\nIn order to debug this project, add an executable project to this solution which references the library project. Set the executable project as the startup project. - - - - The entered path is not a valid output path - The entered path is not a valid output path - - - - The project {0} cannot be referenced. An assembly must have a 'dll' or 'exe' extension in order to be referenced. - The project {0} cannot be referenced. An assembly must have a 'dll' or 'exe' extension in order to be referenced. - - - - Cannot start a build, because another build is already in progress. - Cannot start a build, because another build is already in progress. - - - - The working directory does not exist:\n'{0}'. - The working directory does not exist:\n'{0}'. - - - - A reference to library '{0}' cannot be added. This project targets a different framework ({2}) from the current project ({1}). - A reference to library '{0}' cannot be added. This project targets a different framework ({2}) from the current project ({1}). - - - - The project '{0}' is targeting '{1}'; however, the target framework is not installed on the machine. - The project '{0}' is targeting '{1}'; however, the target framework is not installed on the machine. - - - - F# - F# - - - - The referenced project '{0}' is targeting a higher framework version ({1}) than this project’s current target framework version ({2}). This may lead to build failures if types from assemblies outside this project’s target framework are used by any project in the dependency chain. - The referenced project '{0}' is targeting a higher framework version ({1}) than this project’s current target framework version ({2}). This may lead to build failures if types from assemblies outside this project’s target framework are used by any project in the dependency chain. - - - - The project file does not require conversion. - The project file does not require conversion. - - - - No Conversion Required - No Conversion Required - - - - Error creating backup of project file: {0} - Error creating backup of project file: {0} - - - - Project file successfully backed up as {0} - Project file successfully backed up as {0} - - - - Backup file name conflict. Renaming file to: {0} - Backup file name conflict. Renaming file to: {0} - - - - Backed up project may not build. Project contains linked file: {0} - Backed up project may not build. Project contains linked file: {0} - - - - Failed to backup file as {0} - Failed to backup file as {0} - - - - File successfully backed up as {0} - File successfully backed up as {0} - - - - Identity - Identity - - - - Security identity of the referenced assembly. - Security identity of the referenced assembly. - - - - Path - Path - - - - Location of file being referenced. - Location of file being referenced. - - - - Version - Version - - - - Copy of {0} - Copy of {0} - - - - Copy ({0}) of {1} - Copy ({0}) of {1} - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/MenusAndCommands.vsct.en.xlf b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/MenusAndCommands.vsct.en.xlf deleted file mode 100644 index b65740091c2..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/MenusAndCommands.vsct.en.xlf +++ /dev/null @@ -1,252 +0,0 @@ - - - - - - FSI Console Context - FSI Console Context - - - - FSI Console Context - FSI Console Context - - - - Add &Below - Add &Below - - - - Add &Below - Add &Below - - - - Add &Below - Add &Below - - - - Add &Above - Add &Above - - - - Add &Above - Add &Above - - - - Add &Above - Add &Above - - - - FSharp.Interactive.ToolWindow - FSharp.Interactive.ToolWindow - - - - F# Interactive - F# Interactive - - - - FSharp.Interactive.AttachDebugger - FSharp.Interactive.AttachDebugger - - - - Start Debugging - Start Debugging - - - - FSharp.Interactive.DetachDebugger - FSharp.Interactive.DetachDebugger - - - - Stop Debugging - Stop Debugging - - - - Debug In Interactive - Debug In Interactive - - - - Interactive.Debug.Selection.Context - Interactive.Debug.Selection.Context - - - - &Send to F# Interactive - &Send to F# Interactive - - - - &Send to F# Interactive - &Send to F# Interactive - - - - SendThisReferenceToInteractive - SendThisReferenceToInteractive - - - - &Send References to F# Interactive - &Send References to F# Interactive - - - - &Send References to F# Interactive - &Send References to F# Interactive - - - - SendReferencesToInteractive - SendReferencesToInteractive - - - - &Send Project Output to F# Interactive - &Send Project Output to F# Interactive - - - - &Send Project Output to F# Interactive - &Send Project Output to F# Interactive - - - - FSharpSendProjectOutputToInteractive - FSharpSendProjectOutputToInteractive - - - - Move &Up - Move &Up - - - - Move &Up - Move &Up - - - - MoveFileUp - MoveFileUp - - - - Mo&ve Down - Mo&ve Down - - - - Mo&ve Down - Mo&ve Down - - - - MoveFileDown - MoveFileDown - - - - Add Ne&w Item... - Add Ne&w Item... - - - - Ne&w Item... - Ne&w Item... - - - - Add New Item - Add New Item - - - - Add New Item - Add New Item - - - - Add Existin&g Item... - Add Existin&g Item... - - - - Existin&g Item... - Existin&g Item... - - - - Add Existing Item - Add Existing Item - - - - Add Existing Item - Add Existing Item - - - - Add Ne&w Item... - Add Ne&w Item... - - - - Ne&w Item... - Ne&w Item... - - - - Add New Item - Add New Item - - - - Add New Item - Add New Item - - - - Add Existin&g Item... - Add Existin&g Item... - - - - Existin&g Item... - Existin&g Item... - - - - Add Existing Item - Add Existing Item - - - - Add Existing Item - Add Existing Item - - - - New Fol&der - New Fol&der - - - - New Fol&der - New Fol&der - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.en.xlf b/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.en.xlf deleted file mode 100644 index c0a30e568f6..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.FSharp/xlf/VSPackage.en.xlf +++ /dev/null @@ -1,582 +0,0 @@ - - - - - - You must build the target project before it can be referenced. - You must build the target project before it can be referenced. - - - - Application - Application - - - - General - General - - - - Assembly Name - Assembly Name - - - - The name of the output file that will hold assembly metadata. - The name of the output file that will hold assembly metadata. - - - - Output Type - Output Type - - - - The type of application to build. - The type of application to build. - - - - Default Namespace - Default Namespace - - - - Specifies the default namespace for added items, such as classes, that are added via the Add New Item Dialog Box. - Specifies the default namespace for added items, such as classes, that are added via the Add New Item Dialog Box. - - - - Startup Object - Startup Object - - - - The name of the class that contains the static Main method that you want called when you launch your application. - The name of the class that contains the static Main method that you want called when you launch your application. - - - - Application Icon - Application Icon - - - - Sets the .ico file to use as your application icon. - Sets the .ico file to use as your application icon. - - - - Project - Project - - - - Project File - Project File - - - - The name of the file containing build, configuration, and other information about the project. - The name of the file containing build, configuration, and other information about the project. - - - - Project Folder - Project Folder - - - - The absolute location of the project. - The absolute location of the project. - - - - Output File - Output File - - - - The name of the project's primary output file. - The name of the project's primary output file. - - - - Target Platform - Target Platform - - - - The version of the Common Language Runtime to use for output assembly - The version of the Common Language Runtime to use for output assembly - - - - Target Platform Location - Target Platform Location - - - - The location of the target platform - The location of the target platform - - - - F# Project File (*.fsproj) - F# Project File (*.fsproj) - - - - Component File (*.dll;*.exe) - Component File (*.dll;*.exe) - - - - Other Flags - Other Flags - - - - Other compiler flags - Other compiler flags - - - - Build - Build - - - - F# Script File - F# Script File - - - - A blank F# script file (.fsx) - A blank F# script file (.fsx) - - - - Script.fsx - Script.fsx - - - - FSharp Text Editor - FSharp Text Editor - - - - Code - Code - - - - General - General - - - - Windows - Windows - - - - Silverlight - Silverlight - - - - F# Source File - F# Source File - - - - A blank F# source file (.fs) - A blank F# source file (.fs) - - - - File.fs - File.fs - - - - Console Application (.NET Framework) - Console Application (.NET Framework) - - - - A project for creating a command-line application - A project for creating a command-line application - - - - Library (.NET Framework) - Library (.NET Framework) - - - - A project for creating an F# library - A project for creating an F# library - - - - Tutorial (.NET Framework) - Tutorial (.NET Framework) - - - - A tutorial project providing a walkthrough of the F# language - A tutorial project providing a walkthrough of the F# language - - - - Silverlight Library - Silverlight Library - - - - A project for creating an F# Silverlight library - A project for creating an F# Silverlight library - - - - Application Configuration File - Application Configuration File - - - - A file for storing application configuration and settings values - A file for storing application configuration and settings values - - - - Source File - Source File - - - - A blank F# source file (.fs) - A blank F# source file (.fs) - - - - Script File - Script File - - - - A blank F# script file (.fsx) - A blank F# script file (.fsx) - - - - Signature File - Signature File - - - - A blank F# signature file (.fsi) - A blank F# signature file (.fsi) - - - - Text File - Text File - - - - An empty text file - An empty text file - - - - XML File - XML File - - - - A blank XML file - A blank XML file - - - - Portable Library (.NET 4.5, Windows Store, Silverlight 5, Xamarin) - Portable Library (.NET 4.5, Windows Store, Silverlight 5, Xamarin) - - - - A project for creating an F# library (.dll) that can run on .NET Framework 4.5, Windows Store, Silverlight 5, Xamarin.iOS, Xamarin.Android and Xamarin.iOS(Classic). Profile 47 - A project for creating an F# library (.dll) that can run on .NET Framework 4.5, Windows Store, Silverlight 5, Xamarin.iOS, Xamarin.Android and Xamarin.iOS(Classic). Profile 47 - - - - Data - Data - - - - OData Service Connection (LINQ, type provider) - OData Service Connection (LINQ, type provider) - - - - A project item for consuming a Open Data Protocol (OData) web service using ODataService type provider. - A project item for consuming a Open Data Protocol (OData) web service using ODataService type provider. - - - - A project item for consuming a .NET Managed Resources File (Resx) using ResxFile type provider. - A project item for consuming a .NET Managed Resources File (Resx) using ResxFile type provider. - - - - SQL Database Connection (LINQ to SQL, type provider) - SQL Database Connection (LINQ to SQL, type provider) - - - - A project item for using the SqlDataConnection (LINQ to SQL) type provider to generate types and consume data in a live SQL database. - A project item for using the SqlDataConnection (LINQ to SQL) type provider to generate types and consume data in a live SQL database. - - - - SQL Database Connection (LINQ to Entities, type provider) - SQL Database Connection (LINQ to Entities, type provider) - - - - A project item for using the SqlEntityConnection (Entity Data Model) type provider to generate types and consume data in a live SQL database. - A project item for using the SqlEntityConnection (Entity Data Model) type provider to generate types and consume data in a live SQL database. - - - - WSDL Service Connection (type provider) - WSDL Service Connection (type provider) - - - - A project item for consuming a Web Service using WsdlService type provider. - A project item for consuming a Web Service using WsdlService type provider. - - - - Portable Library (.NET 4.5, Windows Store, Xamarin) - Portable Library (.NET 4.5, Windows Store, Xamarin) - - - - A project for creating an F# library (.dll) that can run on .NET Framework 4.5, Windows Store, Xamarin.iOS, Xamarin.Android and Xamarin.iOS(Classic). Profile 7 - A project for creating an F# library (.dll) that can run on .NET Framework 4.5, Windows Store, Xamarin.iOS, Xamarin.Android and Xamarin.iOS(Classic). Profile 7 - - - - Portable Library (.NET 4.5, Windows Store, Windows Phone 8 Silverlight, Xamarin) - Portable Library (.NET 4.5, Windows Store, Windows Phone 8 Silverlight, Xamarin) - - - - A project for creating an F# library (.dll) that can run on .NET Framework 4.5, Windows Store, Windows Phone 8 Silverlight, Xamarin.iOS, Xamarin.Android and Xamarin.iOS(Classic). Profile 78 - A project for creating an F# library (.dll) that can run on .NET Framework 4.5, Windows Store, Windows Phone 8 Silverlight, Xamarin.iOS, Xamarin.Android and Xamarin.iOS(Classic). Profile 78 - - - - Portable Library (.NET 4.5, Windows Store, Windows Phone 8.1, Windows Phone Silverlight 8, Xamarin) - Portable Library (.NET 4.5, Windows Store, Windows Phone 8.1, Windows Phone Silverlight 8, Xamarin) - - - - A project for creating an F# library (.dll) that can run on .NET Framework 4.5, Windows Store, Windows Phone 8.1, Windows Phone Silverlight 8, Xamarin.iOS, Xamarin.Android and Xamarin.iOS(Classic). Profile 259 - A project for creating an F# library (.dll) that can run on .NET Framework 4.5, Windows Store, Windows Phone 8.1, Windows Phone Silverlight 8, Xamarin.iOS, Xamarin.Android and Xamarin.iOS(Classic). Profile 259 - - - - Resources File - Resources File - - - - A file for storing resources - A file for storing resources - - - - F# Tools - F# Tools - - - - F# Interactive - F# Interactive - - - - F# Project Files (*.fsproj);*.fsproj - F# Project Files (*.fsproj);*.fsproj - - - - Visual F# Files (*.fs,*.fsi,*.fsx,*.fsscript);*.fs,*.fsi,*.fsx,*.fsscript - Visual F# Files (*.fs,*.fsi,*.fsx,*.fsscript);*.fs,*.fsi,*.fsx,*.fsscript - - - - Visual F# - Visual F# - - - - Customizes the environment to maximize code editor screen space and improve the visibility of F# commands and tool windows. - Customizes the environment to maximize code editor screen space and improve the visibility of F# commands and tool windows. - - - - Microsoft Visual F# Tools 10.2 for F# 4.5 - Microsoft Visual F# Tools 10.2 for F# 4.5 - - - - Microsoft Visual F# Tools 10.2 for F# 4.5 - Microsoft Visual F# Tools 10.2 for F# 4.5 - - - - 1.0 - 1.0 - - - - Microsoft Visual F# Tools - Microsoft Visual F# Tools - - - - Visual F# Tools 10.2 for F# 4.5 - Visual F# Tools 10.2 for F# 4.5 - - - - F# Interactive - F# Interactive - - - - Microsoft Visual F# - Microsoft Visual F# - - - - Invalid OutputType value - Invalid OutputType value - - - - Invalid RunPostBuildEvent value - Invalid RunPostBuildEvent value - - - - Invalid TargetFrameworkVersion number - Invalid TargetFrameworkVersion number - - - - The project '{0}' could not be opened because opening it would cause a folder to be rendered multiple times in the solution explorer. One such problematic item is '{1}'. To open this project in Visual Studio, first edit the project file and fix the problem. - The project '{0}' could not be opened because opening it would cause a folder to be rendered multiple times in the solution explorer. One such problematic item is '{1}'. To open this project in Visual Studio, first edit the project file and fix the problem. - - - - Default Namespace:\nThe string for the default namespace must be a valid identifier - Default Namespace:\nThe string for the default namespace must be a valid identifier - - - - Template file not found: {0} - Template file not found: {0} - - - - Changing the Target Framework requires that the current project be closed and then reopened.\nAny unsaved changes within the project will be automatically saved.\n\nChanging Target Framework may require manual modification of project files in order to build.\n\nAre you sure you want to change the Target Framework for this project? - Changing the Target Framework requires that the current project be closed and then reopened.\nAny unsaved changes within the project will be automatically saved.\n\nChanging Target Framework may require manual modification of project files in order to build.\n\nAre you sure you want to change the Target Framework for this project? - - - - Add Reference - Add Reference - - - - Change path and command line arguments passed to the F# Interactive - Change path and command line arguments passed to the F# Interactive - - - - Enable or disable Type Providers - Enable or disable Type Providers - - - - Visual F# Items - Visual F# Items - - - - Reference Manager - {0} - Reference Manager - {0} - - - - F# projects in the current version of Visual Studio support only Silverlight 5. - F# projects in the current version of Visual Studio support only Silverlight 5. - - - - The project will be retargeted, and its targeted frameworks will be reduced. - The project will be retargeted, and its targeted frameworks will be reduced. - - - - All of the Framework assemblies are already referenced. Please use the Object Browser to explore the references in the Framework. - All of the Framework assemblies are already referenced. Please use the Object Browser to explore the references in the Framework. - - - - Referencing this version of FSharp.Core will cause your project to be incompatible with older versions of Visual Studio. Do you want to continue? - Referencing this version of FSharp.Core will cause your project to be incompatible with older versions of Visual Studio. Do you want to continue? - - - - Updating compilation sources and flags... - Updating compilation sources and flags... - - - - Updating solution configuration... - Updating solution configuration... - - - - The file '{0}' cannot be placed above '{1}' in the Solution Explorer.\n\n{2}. - The file '{0}' cannot be placed above '{1}' in the Solution Explorer.\n\n{2}. - - - - The file '{0}' cannot be placed below '{1}' in the Solution Explorer.\n\n{2}. - The file '{0}' cannot be placed below '{1}' in the Solution Explorer.\n\n{2}. - - - - The file is in a different subtree - The file is in a different subtree - - - - The '{0}' folder cannot be moved as it already exists in the Solution Explorer in a different location - The '{0}' folder cannot be moved as it already exists in the Solution Explorer in a different location - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPage.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPage.en.xlf deleted file mode 100644 index 1bdd57c3a46..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPage.en.xlf +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - Assembly &name: - Assembly &name: - - - - ... - ... - - - - Specify how application resources will be managed: - Specify how application resources will be managed: - - - - &Resource File: - &Resource File: - - - - U&se standard resource names - U&se standard resource names - - - - Resources - Resources - - - - O&utput type: - O&utput type: - - - - Tar&get Framework: - Tar&get Framework: - - - - Target F# runtime: - Target F# runtime: - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPageBase.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPageBase.en.xlf deleted file mode 100644 index 29119615113..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ApplicationPropPageBase.en.xlf +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildEventCommandLineDialog.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildEventCommandLineDialog.en.xlf deleted file mode 100644 index fd5c67b581b..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildEventCommandLineDialog.en.xlf +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - I&nsert - I&nsert - - - - OK - OK - - - - Cancel - Cancel - - - - Build Command Line - Build Command Line - - - - &Macros >> - &Macros >> - - - - << &Macros - << &Macros - - - - Macro List - Macro List - - - - Macro - Macro - - - - Value - Value - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildEventsPropPage.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildEventsPropPage.en.xlf deleted file mode 100644 index 4758373726e..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildEventsPropPage.en.xlf +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - P&re-build event command line: - P&re-build event command line: - - - - Pre-build event command line - Pre-build event command line - - - - Edit Pre-build ... - Edit Pre-build ... - - - - Ed&it Pre-build ... - Ed&it Pre-build ... - - - - P&ost-build event command line: - P&ost-build event command line: - - - - Post-build event command line - Post-build event command line - - - - Edit Post-build ... - Edit Post-build ... - - - - Edit Post-b&uild ... - Edit Post-b&uild ... - - - - Ru&n the post-build event: - Ru&n the post-build event: - - - - Always - Always - - - - On successful build - On successful build - - - - When the build updates the project output - When the build updates the project output - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildPropPage.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildPropPage.en.xlf deleted file mode 100644 index 8323c6ee177..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/BuildPropPage.en.xlf +++ /dev/null @@ -1,137 +0,0 @@ - - - - - - Conditional compilation s&ymbols: - Conditional compilation s&ymbols: - - - - &Prefer 32-bit - &Prefer 32-bit - - - - Output - Output - - - - General - General - - - - Treat warnings as errors - Treat warnings as errors - - - - Errors and warnings - Errors and warnings - - - - &XML documentation file: - &XML documentation file: - - - - B&rowse... - B&rowse... - - - - &Output path: - &Output path: - - - - A&ll - A&ll - - - - Specif&ic warnings: - Specif&ic warnings: - - - - &None - &None - - - - &Suppress warnings: - &Suppress warnings: - - - - 0 - 0 - - - - 1 - 1 - - - - 2 - 2 - - - - 3 - 3 - - - - 4 - 4 - - - - 5 - 5 - - - - &Warning level: - &Warning level: - - - - Optimi&ze code - Optimi&ze code - - - - G&enerate tail calls - G&enerate tail calls - - - - Define TR&ACE constant - Define TR&ACE constant - - - - Platform tar&get: - Platform tar&get: - - - - Other &flags: - Other &flags: - - - - Define DEB&UG constant - Define DEB&UG constant - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/DebugPropPage.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/DebugPropPage.en.xlf deleted file mode 100644 index cfce05c9552..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/DebugPropPage.en.xlf +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - Start Action - Start Action - - - - &Start project - &Start project - - - - Start e&xternal program: - Start e&xternal program: - - - - Program to start - Program to start - - - - Browse for external program - Browse for external program - - - - ... - ... - - - - Start Options - Start Options - - - - Comma&nd line arguments: - Comma&nd line arguments: - - - - Wor&king directory: - Wor&king directory: - - - - Use remote m&achine - Use remote m&achine - - - - Remote Machine Name: - Remote Machine Name: - - - - Browse for working directory - Browse for working directory - - - - ... - ... - - - - Enable Debuggers - Enable Debuggers - - - - Enable SQ&L Server debugging - Enable SQ&L Server debugging - - - - Enable the Visual Studio h&osting process - Enable the Visual Studio h&osting process - - - - Enable &unmanaged code debugging - Enable &unmanaged code debugging - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/FSharpApplicationPropPage.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/FSharpApplicationPropPage.en.xlf deleted file mode 100644 index c5f95fd86ec..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/FSharpApplicationPropPage.en.xlf +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/PropPageHostDialog.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/PropPageHostDialog.en.xlf deleted file mode 100644 index dc4b04c9e09..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/PropPageHostDialog.en.xlf +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - OK - OK - - - - Cancel - Cancel - - - - PropPageHostDialog - PropPageHostDialog - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/PropPageUserControlBase.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/PropPageUserControlBase.en.xlf deleted file mode 100644 index 62d55cf3f27..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/PropPageUserControlBase.en.xlf +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - PropPageUserControlBase - PropPageUserControlBase - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ReferencePathsPropPage.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ReferencePathsPropPage.en.xlf deleted file mode 100644 index 434bd5f5883..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/PropertyPages/xlf/ReferencePathsPropPage.en.xlf +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - &Add Folder - &Add Folder - - - - &Update - &Update - - - - Reference &paths: - Reference &paths: - - - - Browse - Browse - - - - ... - ... - - - - Move up - Move up - - - - Move down - Move down - - - - Delete - Delete - - - - &Folder: - &Folder: - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.en.xlf deleted file mode 100644 index 8f158b4e155..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/Microsoft.VisualStudio.Editors.Designer.en.xlf +++ /dev/null @@ -1,2938 +0,0 @@ - - - - - - All Files - All Files - - - - Property Page - Property Page - - - - References - References - - - - Version - Version - - - - Signing - Signing - - - - Application - Application - - - - Compile - Compile - - - - Debug - Debug - - - - Deploy - Deploy - - - - Database - Database - - - - Security - Security - - - - Build - Build - - - - Build Events - Build Events - - - - Reference Paths - Reference Paths - - - - Pre-build Event Command Line - Pre-build Event Command Line - - - - Post-build Event Command Line - Post-build Event Command Line - - - - The output path is not trusted. -The application may throw security exceptions when it attempts to perform actions which require full trust. -Click OK to ignore and continue. Click CANCEL to choose a different output path. - The output path is not trusted. -The application may throw security exceptions when it attempts to perform actions which require full trust. -Click OK to ignore and continue. Click CANCEL to choose a different output path. - - - - <Browse...> - <Browse...> - - - - (None) - (None) - - - - <New...> - <New...> - - - - <Browse...> - <Browse...> - - - - (None) - (None) - - - - Active ({0}) - Active ({0}) - - - - All Configurations - All Configurations - - - - All Platforms - All Platforms - - - - N/A - N/A - This is used in the platform and configuration comboboxes when showing pages that don't care about the current platform/configuration - - - Could not find the configuration '{0}' for platform '{1}'. - Could not find the configuration '{0}' for platform '{1}'. - - - - (None) - (None) - - - - Select File - Select File - - - - Add existing file to project - Add existing file to project - - - - Icon Files - Icon Files - - - - Executable Files - Executable Files - - - - Select Working Directory - Select Working Directory - - - - Select Output Path - Select Output Path - - - - Select Reference Path - Select Reference Path - - - - Win32 Resource Files - Win32 Resource Files - - - - Add Win32 resource file to project - Add Win32 resource file to project - - - - Folder path does not exist. -Please select a valid folder path. - Folder path does not exist. -Please select a valid folder path. - - - - Advanced Compiler Settings - Advanced Compiler Settings - - - - Advanced Build Settings - Advanced Build Settings - - - - Compiler Warnings - Compiler Warnings - - - - Reference Paths - Reference Paths - - - - Compatible Settings - Compatible Settings - - - - Assembly Information - Assembly Information - - - - Invalid version format, expected "[Major]", "[Major].[Minor]", "[Major].[Minor].[Build]" or "[Major].[Minor].[Build].[Revision]" - Invalid version format, expected "[Major]", "[Major].[Minor]", "[Major].[Minor].[Build]" or "[Major].[Minor].[Build].[Revision]" - - - - A wildcard ("*") is not allowed in this field. - A wildcard ("*") is not allowed in this field. - - - - Each part of the version number for '{0}' must be an integer between 0 and {1}. - Each part of the version number for '{0}' must be an integer between 0 and {1}. - - - - (Default Icon) - (Default Icon) - - - - Startup object must be a form when 'Enable application framework' is checked. - Startup object must be a form when 'Enable application framework' is checked. - - - - (Not set) - (Not set) - - - - Icon could not be added to the project. - Icon could not be added to the project. - - - - Invalid icon file. - Invalid icon file. - - - - {0} is not a valid icon file. - {0} is not a valid icon file. - - - - The GUID should match the format dddddddd-dddd-dddd-dddd-dddddddddddd. - The GUID should match the format dddddddd-dddd-dddd-dddd-dddddddddddd. - - - - NOTE: This file is auto-generated; do not modify it directly. To make changes, - NOTE: This file is auto-generated; do not modify it directly. To make changes, - These comments are placed in the ApplicationEvents.vb file if it is generated by the project designer. The same comments appear in the templates, under vsproject\Templates\Windows\VisualBasic\ProjectTemplates\WindowsApplication\MyEvents.vb (MyEvents.vb is renamed to ApplicationEvents.vb after project creation), and these comments should be kept in sync - - - or if you encounter build errors in this file, go to the Project Designer - or if you encounter build errors in this file, go to the Project Designer - - - - (go to Project Properties or double-click the My Project node in - (go to Project Properties or double-click the My Project node in - - - - Solution Explorer), and make changes on the Application tab. - Solution Explorer), and make changes on the Application tab. - - - - '{0}' is not a valid identifier. Please select a different Startup form. - '{0}' is not a valid identifier. Please select a different Startup form. - - - - '{0}' is not a valid identifier. Please select a different Splash screen form. - '{0}' is not a valid identifier. Please select a different Splash screen form. - - - - The splash screen form cannot be the start-up form. - The splash screen form cannot be the start-up form. - - - - Startup f&orm: - Startup f&orm: - - - - The following events are available for MyApplication: - The following events are available for MyApplication: - - - - Startup: Raised when the application starts, before the startup form is created. - Startup: Raised when the application starts, before the startup form is created. - - - - Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally. - Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally. - - - - UnhandledException: Raised if the application encounters an unhandled exception. - UnhandledException: Raised if the application encounters an unhandled exception. - - - - StartupNextInstance: Raised when launching a single-instance application and the application is already active. - StartupNextInstance: Raised when launching a single-instance application and the application is already active. - - - - NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. - NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected. - - - - Base address must be a hexadecimal number with less than or equal to 8 digits, for example, 0x11000000. - Base address must be a hexadecimal number with less than or equal to 8 digits, for example, 0x11000000. - - - - None - None - - - - Warning - Warning - - - - Error - Error - - - - (custom) - (custom) - - - - Implicit conversion - Implicit conversion - - - - Late binding; call could fail at run time - Late binding; call could fail at run time - - - - Implicit type; object assumed - Implicit type; object assumed - - - - Use of variable prior to assignment - Use of variable prior to assignment - - - - Function/Operator without return value - Function/Operator without return value - - - - Unused local variable - Unused local variable - - - - Instance variable accesses shared member - Instance variable accesses shared member - - - - Recursive operator or property access - Recursive operator or property access - - - - Duplicate or overlapping catch blocks - Duplicate or overlapping catch blocks - - - - The warning settings for one or more configurations conflict. -Changing this setting will reset the settings in all configurations. - The warning settings for one or more configurations conflict. -Changing this setting will reset the settings in all configurations. - - - - When startup form closes - When startup form closes - - - - When last form closes - When last form closes - - - - Windows - Windows - Authentication modes - - - Application-defined - Application-defined - Authentication modes - - - Cancel - Cancel - - - - &Calculate Permissions - &Calculate Permissions - - - - Stopped... - Stopped... - - - - Starting... - Starting... - - - - Building... - Building... - - - - Analyzing... - Analyzing... - - - - Analyze Failed - Analyze Failed - - - - Aborting... - Aborting... - - - - Canceling... - Canceling... - - - - Internet - Internet - - - - Local Intranet - Local Intranet - - - - (Custom) - (Custom) - Don't use - - - (Zone Default) - (Zone Default) - - - - Include - Include - - - - Exclude - Exclude - - - - The application will require elevated permissions to run in the selected zone. Click the help link above for more info. - The application will require elevated permissions to run in the selected zone. Click the help link above for more info. - - - - This permission could not be loaded. Press the delete key to remove it from your project. - This permission could not be loaded. Press the delete key to remove it from your project. - Don't use - - - Included - Included - - - - Permission - Permission - - - - Setting - Setting - - - - Specify the code access security permissions that your ClickOnce application requires in order to run. Learn more about code access security... - Specify the code access security permissions that your ClickOnce application requires in order to run. Learn more about code access security... - - - - Learn more about code access security... - Learn more about code access security... - - - - Invalid value - Invalid value - - - - The SecurityPermission must be included in your application with the Execute flag set or your application will not run. Mark this permission as "Zone Default" or "Include." - The SecurityPermission must be included in your application with the Execute flag set or your application will not run. Mark this permission as "Zone Default" or "Include." - - - - The SecurityPermission must be included in your application with the Execute flag set or your application will not run. The Execute flag has been added to the SecurityPermission in your manifest. - The SecurityPermission must be included in your application with the Execute flag set or your application will not run. The Execute flag has been added to the SecurityPermission in your manifest. - - - - This application requires full trust to run correctly. Would you like to set this as a full trust application? - This application requires full trust to run correctly. Would you like to set this as a full trust application? - - - - Full Trust Required - Full Trust Required - - - - An error occurred and the app.manifest file could not be saved. -Error: - An error occurred and the app.manifest file could not be saved. -Error: - - - - An error occurred and the app.manifest file could not be loaded. Please remove any changes you have made to the file and reload the Security property page again. - An error occurred and the app.manifest file could not be loaded. Please remove any changes you have made to the file and reload the Security property page again. - - - - Included - Included - - - - Not Included - Not Included - - - - Included with warning - Included with warning - - - - Calculating permissions failed. - Calculating permissions failed. - - - - Error - Error - - - - Advanced Security Settings - Advanced Security Settings - - - - Build Failed. Click CANCEL and correct the build failure before analyzing again. - Build Failed. Click CANCEL and correct the build failure before analyzing again. - - - - Build completed... - Build completed... - - - - Unable to start the build. - Unable to start the build. - - - - Serious error. The build must begin in order to analyze permissions. It has not started. - Serious error. The build must begin in order to analyze permissions. It has not started. - Don't use - - - (Custom) - (Custom) - Don't use - - - (None) - (None) - - - - Selecting existing key file - Selecting existing key file - - - - Key Files - Key Files - - - - Create key file - Create key file - - - - The old password is invalid. - The old password is invalid. - - - - Enter the old password. - Enter the old password. - - - - Enter a new password. - Enter a new password. - - - - The new passwords do not match. Enter the password again. - The new passwords do not match. Enter the password again. - - - - The new password must be at least 6 characters in length. Enter the password again. - The new password must be at least 6 characters in length. Enter the password again. - - - - Select a Certificate - Select a Certificate - - - - Select a certificate to sign your ClickOnce manifests - Select a certificate to sign your ClickOnce manifests - - - - Certificate Files - Certificate Files - - - - Issued To - Issued To - - - - Issued By - Issued By - - - - Intended Purpose - Intended Purpose - - - - Expiration Date - Expiration Date - - - - The password is invalid. - The password is invalid. - - - - Invalid password - Invalid password - - - - The selected file does not contain a private key. You must choose a certificate that contains a private key. - The selected file does not contain a private key. You must choose a certificate that contains a private key. - - - - Invalid key - Invalid key - - - - Certificate Creation Error - Certificate Creation Error - - - - <All> - <All> - - - - The passwords do not match. - The passwords do not match. - - - - Enter a password. - Enter a password. - - - - Confirm the password. - Confirm the password. - - - - (none) - (none) - - - - Enter password to open file - Enter password to open file - - - - Enter &password to open file {0} - Enter &password to open file {0} - - - - Enter &password for new file {0} - Enter &password for new file {0} - - - - The project already contains a file with that name. Choose another certificate file or rename the file in your project. - The project already contains a file with that name. Choose another certificate file or rename the file in your project. - - - - The file '{0}' could not be imported: {1} - The file '{0}' could not be imported: {1} - - - - _TemporaryKey.pfx - _TemporaryKey.pfx - - - - The selected certificate is not valid for code signing. Choose another certificate file. - The selected certificate is not valid for code signing. Choose another certificate file. - - - - Change property: {0} - Change property: {0} - - - - Windows Application - Windows Application - - - - Windows Service - Windows Service - - - - Class Library - Class Library - - - - Console Application - Console Application - - - - Web Control Library - Web Control Library - - - - Cannot remove '{0}'. {1} - - Cannot remove '{0}'. {1} - - - - - Adding or removing '{0}' as a project import failed because of an unexpected error from the project system. The error returned was: '{1}'. - Adding or removing '{0}' as a project import failed because of an unexpected error from the project system. The error returned was: '{1}'. - - - - Adding web reference failed. {0} - - Adding web reference failed. {0} - - - - - Updating web reference '{0}' failed. -{1} - Updating web reference '{0}' failed. -{1} - - - - Web Reference Properties - Web Reference Properties - - - - Static - Static - - - - Dynamic - Dynamic - - - - Name of the web reference - Name of the web reference - - - - URL Behavior - URL Behavior - - - - Web reference URL behavior - Web reference URL behavior - - - - Web Reference URL - Web Reference URL - - - - Web Reference URL - Web Reference URL - - - - Reference Properties - Reference Properties - - - - The remote machine name cannot be blank. Please specify the name of the machine to debug remotely. - The remote machine name cannot be blank. Please specify the name of the machine to debug remotely. - - - - The external program cannot be found. Please enter a valid executable file. - The external program cannot be found. Please enter a valid executable file. - - - - The external program property cannot be empty. Please enter a valid executable file. - The external program property cannot be empty. Please enter a valid executable file. - - - - We can only debug an EXE file. Please enter a valid executable file. - We can only debug an EXE file. Please enter a valid executable file. - - - - The URL property cannot be empty. Please enter a valid URL. - The URL property cannot be empty. Please enter a valid URL. - - - - The URL is invalid. Please enter a valid URL like "http://www.microsoft.com/" - The URL is invalid. Please enter a valid URL like "http://www.microsoft.com/" - - - - The working directory you entered does not exist. Please enter a valid working directory. - The working directory you entered does not exist. Please enter a valid working directory. - - - - <The system cannot find the reference specified> - <The system cannot find the reference specified> - - - - Unused References - Unused References - - - - &Remove - &Remove - - - - No unused references - No unused references - - - - Project compilation failed. Cannot determine unused references. - Project compilation failed. Cannot determine unused references. - - - - Gathering list of unused references... - Gathering list of unused references... - - - - Error getting unused references. - Error getting unused references. - - - - Base address must be a hexadecimal number with less than or equal to 8 digits, for example, &H11000000. - Base address must be a hexadecimal number with less than or equal to 8 digits, for example, &H11000000. - - - - "Resource files must have a .res file extension. Please enter a valid resource file name." - "Resource files must have a .res file extension. Please enter a valid resource file name." - - - - "The resource file entered does not exist." - "The resource file entered does not exist." - - - - Project Designer - Project Designer - - - - Settings - Settings - - - - Resources - Resources - - - - An error occurred trying to load the project properties window. Close the window and try again. -{0} - An error occurred trying to load the project properties window. Close the window and try again. -{0} - - - - An error occurred trying to load the page. - An error occurred trying to load the page. - - - - The designer cannot be shown because the document for it was never loaded. - The designer cannot be shown because the document for it was never loaded. - - - - This project does not contain a default resources file. Click here to create one. - This project does not contain a default resources file. Click here to create one. - - - - This project does not contain a default settings file. Click here to create one. - This project does not contain a default settings file. Click here to create one. - - - - Could not find the file '{0}'. - Could not find the file '{0}'. - - - - The file '{0}' is already open in an editor. Please close the file and try again. - The file '{0}' is already open in an editor. Please close the file and try again. - - - - All Project Designer Pages - All Project Designer Pages - - - - More Settings - More Settings - - - - The requested file type is not supported in projects of this type. - The requested file type is not supported in projects of this type. - - - - Assembly Name - Assembly Name - - - - Root Namespace - Root Namespace - - - - Startup Object - Startup Object - - - - Application Icon - Application Icon - Property Friendly Names (for transaction names) - NOTE: All of these are optional - - - Assembly Version - Assembly Version - - - - Assembly File Version - Assembly File Version - - - - Assembly GUID - Assembly GUID - - - - Enable application framework - Enable application framework - - - - External Program Path - External Program Path - - - - Start Browser With URL - Start Browser With URL - - - - Working Directory - Working Directory - - - - Remote Machine Name - Remote Machine Name - - - - Project Designer Page Container - Project Designer Page Container - - - - Switch Project Designer Page - Switch Project Designer Page - - - - Allow switching between active pages of the project designer (use Ctrl+PageUp and Ctrl+PageDown) - Allow switching between active pages of the project designer (use Ctrl+PageUp and Ctrl+PageDown) - - - - {0} page: - {0} page: - {0} = sub page name - - - {0} [Read Only] - {0} [Read Only] - Attach a readonly to the designer caption {0}=Designer caption - - - The editor could not get the IVsTextStream for file {0}. - The editor could not get the IVsTextStream for file {0}. - #exception {0}=filename - - - The editor could not get the IVsTextStream. - The editor could not get the IVsTextStream. - #exception (no file name) - - - No DesignerService for file '{0}'. - No DesignerService for file '{0}'. - #{0}=file name - - - Invalid physical view name. - Invalid physical view name. - - - - Unable to create text buffer. - Unable to create text buffer. - # com exception - - - No LocalRegistry service. - No LocalRegistry service. - #exception - - - Replacing text stream failed:{0} - Replacing text stream failed:{0} - #exception {0}=err msg - - - Buffer is read only. - Buffer is read only. - - - - File is already opened in an incompatible editor. - File is already opened in an incompatible editor. - - - - Unsupported format. - Unsupported format. - - - - Unknown Error. - Unknown Error. - - - - Unable to create the designer. {0} - Unable to create the designer. {0} - # {0}=inner exception - - - Unable to check out the current file. The file may be read-only or locked, or you may need to check the file out manually. - Unable to check out the current file. The file may be read-only or locked, or you may need to check the file out manually. - # General checkout exception message - - - Microsoft Visual Studio - Microsoft Visual Studio - Error reporting - - - Please enter an integer between 1 and 60. - Please enter an integer between 1 and 60. - - - - Please enter an integer between 1 and 60. - Please enter an integer between 1 and 60. - - - - Show empty environment - Show empty environment - These are items in a combobox (and so they don't need periods) - - - Load last loaded solution - Load last loaded solution - These are items in a combobox (and so they don't need periods) - - - Show New Project dialog box - Show New Project dialog box - These are items in a combobox (and so they don't need periods) - - - Show Open Project dialog box - Show Open Project dialog box - These are items in a combobox (and so they don't need periods) - - - Changes in Help Options will not take effect until the environment is restarted. - Changes in Help Options will not take effect until the environment is restarted. - - - - The location specified is on an invalid or read-only disk, or contains a device name reserved for the system. - The location specified is on an invalid or read-only disk, or contains a device name reserved for the system. - - - - COM - COM - - - - Component Design - Component Design - - - - Serialization - Serialization - - - - Web - Web - - - - COMClass - COMClass - - - - Expose {0} to COM. - Expose {0} to COM. - - - - COM Class - COM Class - - - - COMVisible - COMVisible - - - - Make {0} visible through COM. - Make {0} visible through COM. - - - - COM Visible - COM Visible - - - - DispId - DispId - - - - Set explicit DispId to this {0}. - Set explicit DispId to this {0}. - - - - DispId - DispId - - - - Value - Value - - - - Explicit DispId value for this {0}. - Explicit DispId value for this {0}. - - - - Value - Value - - - - DispId value should be an integer greater than or equal to 1. - DispId value should be an integer greater than or equal to 1. - - - - Category - Category - - - - Category group for the property. - Category group for the property. - - - - Category - Category - - - - Default Event - Default Event - - - - Default event for the class. - Default event for the class. - - - - Default Event - Default Event - - - - Default Value - Default Value - - - - Default value for the property. - Default value for the property. - - - - Default Value - Default Value - - - - NonSerialized - NonSerialized - - - - Field should not be serialized. - Field should not be serialized. - - - - Non Serialized - Non Serialized - - - - Serializable - Serializable - - - - Enable serialization for this {0} and its members. - Enable serialization for this {0} and its members. - - - - Serializable - Serializable - - - - WebMethod - WebMethod - - - - Expose method via web services. - Expose method via web services. - - - - Web Method - Web Method - - - - Description - Description - - - - Description for the Web Method. - Description for the Web Method. - - - - Description - Description - - - - EnableSession - EnableSession - - - - Maintain session state. - Maintain session state. - - - - Enable Session - Enable Session - - - - TransactionOptions - TransactionOptions - - - - Set transaction options. - Set transaction options. - - - - Transaction Options - Transaction Options - - - - WebService - WebService - - - - Configure the Web Service settings. - Configure the Web Service settings. - - - - Web Service - Web Service - - - - Name - Name - - - - Name for the web service. - Name for the web service. - - - - Name - Name - - - - Description - Description - - - - Description for the web service. - Description for the web service. - - - - Description - Description - - - - Namespace - Namespace - - - - Namespace for the web service. - Namespace for the web service. - - - - Namespace - Namespace - - - - Default - Default - - - - Action - Action - - - - Appearance - Appearance - - - - Behavior - Behavior - - - - Data - Data - - - - DragDrop - DragDrop - - - - Focus - Focus - - - - Format - Format - - - - Key - Key - - - - Layout - Layout - - - - Mouse - Mouse - - - - WindowStyle - WindowStyle - - - - (None) - (None) - Default Event - - - Requires: - Requires: - - - - Name - Name - Column names for the string table - - - Type - Type - Column names for the string table - - - Value - Value - Column names for the string table - - - Comment - Comment - Column names for the string table - - - Failed to generate file: {0} - Failed to generate file: {0} - - - - Editing embedded resources directly is not supported. Do you wish to convert this item to a linked resource in order to edit it? - Editing embedded resources directly is not supported. Do you wish to convert this item to a linked resource in order to edit it? - - - - The current object is auto-generated and only supports renaming through the Managed Resources Editor. - The current object is auto-generated and only supports renaming through the Managed Resources Editor. - - - - Cannot find the file '{0}'. It may have been moved or deleted. - Cannot find the file '{0}'. It may have been moved or deleted. - {0} = file name and path - - - Unable to load resource from file '{0}'. - Unable to load resource from file '{0}'. - {0} = file name and path - - - The resource name cannot be empty. - The resource name cannot be empty. - - - - There is already another resource with the name '{0}'. - There is already another resource with the name '{0}'. - {0} = Resource name - - - The resource was not of the expected type. - The resource was not of the expected type. - This error can happen if, for example, you try to add foo.bmp to the resource editor, but foo.bmp is really a metafile. - - - Unable to create new resource file '{0}'. {1} - Unable to create new resource file '{0}'. {1} - {0} = file name and path, {1} = additional error information - - - Unable to play the audio resource. {0} - Unable to play the audio resource. {0} - {0} = Additional error information. - - - Resource '{0}' cannot be saved to a file. - Resource '{0}' cannot be saved to a file. - {0} = Resource name - - - The operation has been canceled by the user. - The operation has been canceled by the user. - - - - The resource value contains invalid data or has an incorrect format. - The resource value contains invalid data or has an incorrect format. - - - - The name of the resource '{0}' cannot be used as a valid identifier, because it contains one or more invalid characters: '{1}'. Please remove or replace those characters and try again. - The name of the resource '{0}' cannot be used as a valid identifier, because it contains one or more invalid characters: '{1}'. Please remove or replace those characters and try again. - {0} = Resource name - - - Too many files specified. Please select fewer files and try again. - Too many files specified. Please select fewer files and try again. - - - - Unexpected error. - Unexpected error. - Theoretically possible but we really don't expect to happen. Unexpected, internal error. - - - Unable to load internal localized resource '{0}'. - Unable to load internal localized resource '{0}'. - Theoretically possible but we really don't expect to happen. Unexpected, internal error. - - - The value could not be converted into a resource of type {0}. - -{1} - The value could not be converted into a resource of type {0}. - -{1} - {0} = the type that was expected by the resource editor (e.g. System.Drawing.Point) -{1} = more specific additional error message from the system - - - The value cannot be empty in a resource of type {0}. - The value cannot be empty in a resource of type {0}. - {0} = the type that was expected by the resource editor (e.g. System.Drawing.Point) - - - One or more of the selected resource values could not be cleared. - One or more of the selected resource values could not be cleared. - - - - The resource file cannot be modified at this time. - The resource file cannot be modified at this time. - - - - You are trying to edit a resource file that is a part of another project item (such as a form or a control). Editing this item could corrupt the project item, and you will have to recover it by hand. In addition, changes made to this resource file may be lost if further changes are made to the project item. - -Do you really want to edit this file? - You are trying to edit a resource file that is a part of another project item (such as a form or a control). Editing this item could corrupt the project item, and you will have to recover it by hand. In addition, changes made to this resource file may be lost if further changes are made to the project item. - -Do you really want to edit this file? - - - - The resource '{0}' cannot be added. - The resource '{0}' cannot be added. - {0} - name of the resource - - - The device does not support '{0}' files. - The device does not support '{0}' files. - {0} - the extension of the file name like 'tiff' - - - The resource item uses the type '{0}', which is not supported in this project. - The resource item uses the type '{0}', which is not supported in this project. - {0} - name of the type - - - The resource item(s) {0} cannot be saved correctly. The item(s) will be discarded. - The resource item(s) {0} cannot be saved correctly. The item(s) will be discarded. - {0} - name list of the resource - - - '{0}' - '{0}' - {0} - name - - - {0}, '{1}' - {0}, '{1}' - # {0} - name list -# {1} - another name - - - (Nothing/null) - (Nothing/null) - Displayed in a string table for values of Nothing/null -CONSIDER: get this from CodeDom - - - (Unknown type) - (Unknown type) - This actually shouldn't be needed, but if we get an exception trying to get the type name of an entry in the resx file (not supposed to happen), then we'll display this as its type. - - - (Value cannot be displayed) - (Value cannot be displayed) - Displayed in a string table for values which cannot be edited by the user - - - Name - Name - Columns for the "Details" view of the resource editor - - - Filename - Filename - Columns for the "Details" view of the resource editor - - - Type - Type - Columns for the "Details" view of the resource editor - - - Size - Size - Columns for the "Details" view of the resource editor - - - Comment - Comment - Columns for the "Details" view of the resource editor - - - Text Encoding - Text Encoding - Columns for the "Details" view of the resource editor - - - {0} x {1} - {0} x {1} - Format string for showing a graphic's size - -# {0} = width (as an integer) -# {1} = height (as an integer) -#Example, for a bitmap of width=123, height = 456, the English version of this string would be "123x456" - - - {0} KB - {0} KB - #Format string for showing a file's size -# {0} = length in kilobytes - - - {0} byte(s) - {0} byte(s) - Format string for showing a file's size. -{0} = length in bytes - - - Strings - Strings - Resource category names (these show up in the category buttons in the ToolStrip at the top of the resource editor) - - - Images - Images - Resource category names (these show up in the category buttons in the ToolStrip at the top of the resource editor) - - - Icons - Icons - Resource category names (these show up in the category buttons in the ToolStrip at the top of the resource editor) - - - Audio - Audio - Resource category names (these show up in the category buttons in the ToolStrip at the top of the resource editor) - - - Files - Files - Resource category names (these show up in the category buttons in the ToolStrip at the top of the resource editor) - - - Other - Other - Resource category names (these show up in the category buttons in the ToolStrip at the top of the resource editor) - - - &Add - &Add - Add, Delete and Views button text in the main ToolStrip - - - &Remove - &Remove - Add, Delete and Views button text in the main ToolStrip - - - &Views - &Views - Add, Delete and Views button text in the main ToolStrip - - - &Existing File... - &Existing File... - Menu items under the "Add" button - - - New &String - New &String - Menu items under the "Add" button - - - New &Image - New &Image - Menu items under the "Add" button - - - &PNG Image... - &PNG Image... - Menu items under the "Add" button - - - &BMP Image... - &BMP Image... - Menu items under the "Add" button - - - &GIF Image... - &GIF Image... - Menu items under the "Add" button - - - &JPEG Image... - &JPEG Image... - Menu items under the "Add" button - - - &TIFF Image... - &TIFF Image... - Menu items under the "Add" button - - - New I&con... - New I&con... - Menu items under the "Add" button - - - New &Text File... - New &Text File... - Menu items under the "Add" button - - - Windows Bitmap - Windows Bitmap - Friendly Image types - - - EXIF Image - EXIF Image - Friendly Image types - - - Graphics Interchange Format - Graphics Interchange Format - Friendly Image types - - - JPEG File Interchange Format - JPEG File Interchange Format - Friendly Image types - - - Windows Bitmap - Windows Bitmap - Friendly Image types - - - Portable Network Graphics - Portable Network Graphics - Friendly Image types - - - Tag Image File Format - Tag Image File Format - Friendly Image types - - - Icon - Icon - Friendly Image types - - - Text File - Text File - Friendly Image types - - - Binary File - Binary File - - - - Wave Sound - Wave Sound - Friendly Image types - - - Linked at compile time - Linked at compile time - File Persistence Mode - - - Embedded in .resx - Embedded in .resx - File Persistence Mode - - - Bitmaps - Bitmaps - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - Icons - Icons - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - Audio - Audio - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - Text Files - Text Files - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - All Files - All Files - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - Windows Bitmap - Windows Bitmap - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - Portable Network Graphics - Portable Network Graphics - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - Graphics Interchange Format - Graphics Interchange Format - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - JPEG File Interchange Format - JPEG File Interchange Format - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - Tag Image File Format - Tag Image File Format - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - Icon - Icon - # File dialog filters -# -# E.g., for icons, the actual filter created would look like "Icons (*.ico)". These resources -# represent the first part of that filter -# - - - &List - &List - Resource editor listview view styles (like changing the view style of a folder in Windows XP) - - - &Details - &Details - Resource editor listview view styles (like changing the view style of a folder in Windows XP) - - - &Thumbnail - &Thumbnail - Resource editor listview view styles (like changing the view style of a folder in Windows XP) - - - Managed Resources Editor - Managed Resources Editor - - - - Add existing file to resources - Add existing file to resources - - - - Import file into resource '{0}' - Import file into resource '{0}' - {0} = Name of resource being imported into - - - Export resource '{0}' to file - Export resource '{0}' to file - {0} = Name of resource being exported from - - - Please specify where to save the new file - Please specify where to save the new file - - - - The file '{0}' already exists. Do you want to replace it? - The file '{0}' already exists. Do you want to replace it? - {0} = full file path and name - - - The following files already exist. Do you want to replace them? - The following files already exist. Do you want to replace them? - - - - Select a folder in which to export the resources. - Select a folder in which to export the resources. - - - - Do you want to continue anyway? - Do you want to continue anyway? - - - - Do you want to enable strongly-typed resource generation for this file? - Do you want to enable strongly-typed resource generation for this file? - - - - Resource '{0}' could not be loaded because the file to which it is linked could not be found: {1}. - Resource '{0}' could not be loaded because the file to which it is linked could not be found: {1}. - {0} = resource name that had the error, {1} = file path/name that could not be found - - - Resource '{0}' could not be instantiated. {1} - Resource '{0}' could not be instantiated. {1} - {0} = resource name that had the error, {1} = extended error information - - - Resource '{0}' has a name that is not recommended and that may cause compilation errors in your code. Please choose another name. - Resource '{0}' has a name that is not recommended and that may cause compilation errors in your code. Please choose another name. - {0} = resource name that had the error - - - Unable to set the Custom Tool or Custom Tool Namespace properties of this file in order to change strongly-typed resource generation options. If the project file is checked in, try checking it out. - Unable to set the Custom Tool or Custom Tool Namespace properties of this file in order to change strongly-typed resource generation options. If the project file is checked in, try checking it out. - One possible source for this error is that source code control checkout failed or was canceled. - - - Double-click here to enable strongly-typed resources for this file. - Double-click here to enable strongly-typed resources for this file. - - - - The resource name '{0}' is not a valid identifier. - The resource name '{0}' is not a valid identifier. - - - - {0} - Codepage {1} - {0} - Codepage {1} - {0} = encoding name (e.g., "Western European (Windows)"), {1} = code page # (e.g., 85001) - - - (Default) - (Default) - - - - Change resource name - Change resource name - - - - Add {0} new resource(s) - Add {0} new resource(s) - {0} = number of resources added - - - Remove {0} resource(s) - Remove {0} resource(s) - {0} = number of resources removed - - - Delete values in {0} cell(s) - Delete values in {0} cell(s) - {0} = number of cells cleared - - - &Categories: - &Categories: - The label in the menu strip for the combobox that holds the categories of resources to display - - - Name used to identify the resource in code. - Name used to identify the resource in code. - - - - Additional information about the resource. This property is only meaningful at design time. - Additional information about the resource. This property is only meaningful at design time. - - - - Character encoding of the file. - Character encoding of the file. - - - - The path to the linked resource. - The path to the linked resource. - - - - Specifies whether the file resource is text or binary. - Specifies whether the file resource is text or binary. - - - - Specifies whether the resource is embedded or linked. Embedded resources are saved in the resource file. Linked resources reside in an external location on disk. - Specifies whether the resource is embedded or linked. Embedded resources are saved in the resource file. Linked resources reside in an external location on disk. - - - - The resource will be generated as this type in the strongly-typed resource class. For example, the resource might be generated as a String or Bitmap object. - The resource will be generated as this type in the strongly-typed resource class. For example, the resource might be generated as a String or Bitmap object. - - - - The value of the resource. - The value of the resource. - - - - Unable to add a '{0}' folder to this project. - -{1} - Unable to add a '{0}' folder to this project. - -{1} - {0} = name of folder trying to add (by default, this will be "Resources"), {1} = additional error information - - - Unable to add '{0}' to the project. - -{1} - Unable to add '{0}' to the project. - -{1} - {0} = file name and path, {1} = additional error information. - - - Unable to add '{0}' to the project. - Unable to add '{0}' to the project. - {0} = file name and path - - - A file with the name '{0}' already exists. Do you want to replace it? - A file with the name '{0}' already exists. Do you want to replace it? - {0} = file name and path - - - {0} - Destination File Exists - {0} - Destination File Exists - {0} = Name of the editor, e.g. "Managed Resources Editor" or "Resource Picker" - - - There is already a linked file with the name "{0}" in the project folder "{1}". Do you want to remove it? - There is already a linked file with the name "{0}" in the project folder "{1}". Do you want to remove it? - {0} = file name (no path), {1} = Path of resource folder - - - {0} - Destination File Exists - {0} - Destination File Exists - {0} = Name of the editor, e.g. "Managed Resources Editor" or "Resource Picker" - - - Cannot find the file '{0}'. It may have been moved or deleted. - Cannot find the file '{0}'. It may have been moved or deleted. - {0} = file name and path - - - Connection string - Connection string - Added as the last item in the list of available types to let the user browse for a new type - - - Web Service URL - Web Service URL - Added as the last item in the list of available types to let the user browse for a new type - - - Browse... - Browse... - Added as the last item in the list of available types to let the user browse for a new type - - - Application - Application - - - - User - User - - - - Name - Name - - - - Type - Type - - - - Scope - Scope - - - - Value - Value - - - - Type '{0}' is not defined. - Type '{0}' is not defined. - - - - Name changed - Name changed - - - - Type changed - Type changed - - - - Scope changed - Scope changed - - - - Roaming changed - Roaming changed - - - - Description changed - Description changed - - - - Provider changed - Provider changed - - - - Value changed - Value changed - - - - Generate default value in code changed - Generate default value in code changed - - - - Remove {0} setting(s) - Remove {0} setting(s) - - - - Unable to load settings file. It might be corrupted or contain invalid XML or contain duplicate identifiers. - Unable to load settings file. It might be corrupted or contain invalid XML or contain duplicate identifiers. - - - - New values from the app.config file were automatically added - New values from the app.config file were automatically added - - - - Value of setting '{0}' was changed in the app.config file. - Value of setting '{0}' was changed in the app.config file. - - - - The current value in the .settings file is '{0}' -The new value in the app.config file is '{1}' - -Do you want to update the value in the .settings file? - The current value in the .settings file is '{0}' -The new value in the app.config file is '{1}' - -Do you want to update the value in the .settings file? - - - - An error occurred while reading the app.config file. The file might be corrupted or contain invalid XML. - An error occurred while reading the app.config file. The file might be corrupted or contain invalid XML. - - - - An error occurred while saving values to the app.config file. The file might be corrupted or contain invalid XML. - An error occurred while saving values to the app.config file. The file might be corrupted or contain invalid XML. - - - - There is already another setting with the name '{0}'. - There is already another setting with the name '{0}'. - - - - '{0}' is not a valid identifier. - '{0}' is not a valid identifier. - - - - '{0}' is not a valid type name. - '{0}' is not a valid type name. - - - - The setting name cannot be empty. - The setting name cannot be empty. - - - - '{0}' cannot be converted to an instance of type '{1}'. - '{0}' cannot be converted to an instance of type '{1}'. - - - - Generic types are not supported. - Generic types are not supported. - - - - Abstract types are not supported. - Abstract types are not supported. - - - - The current object is auto-generated and only supports renaming through the Settings Designer. - The current object is auto-generated and only supports renaming through the Settings Designer. - - - - The current object is auto-generated and does not support modifying parameters. - The current object is auto-generated and does not support modifying parameters. - - - - The settings file cannot be modified at this time. - The settings file cannot be modified at this time. - - - - &Add Setting - &Add Setting - - - - R&emove Setting - R&emove Setting - - - - Application settings allow you to store and retrieve property settings and other information for your application dynamically. For example, the application can save a user's color preferences, then retrieve them the next time it runs. - Application settings allow you to store and retrieve property settings and other information for your application dynamically. For example, the application can save a user's color preferences, then retrieve them the next time it runs. - - - - Learn more about application settings... - Learn more about application settings... - - - - This connection string appears to contain sensitive data (for example, a password), which is required to connect to the database. However, storing sensitive data in the connection string can be a security risk. Do you want to include sensitive data in the connection string? - This connection string appears to contain sensitive data (for example, a password), which is required to connect to the database. However, storing sensitive data in the connection string can be a security risk. Do you want to include sensitive data in the connection string? - - - - Select a Type - Select a Type - - - - This class allows you to handle specific events on the settings class: - This class allows you to handle specific events on the settings class: - Comments for user part of extending generated settings class - - - The SettingChanging event is raised before a setting's value is changed. - The SettingChanging event is raised before a setting's value is changed. - - - - The PropertyChanged event is raised after a setting's value is changed. - The PropertyChanged event is raised after a setting's value is changed. - - - - The SettingsLoaded event is raised after the setting values are loaded. - The SettingsLoaded event is raised after the setting values are loaded. - - - - The SettingsSaving event is raised before the setting values are saved. - The SettingsSaving event is raised before the setting values are saved. - - - - To add event handlers for saving and changing settings, uncomment the lines below: - To add event handlers for saving and changing settings, uncomment the lines below: - - - - Add code to handle the SettingChangingEvent event here. - Add code to handle the SettingChangingEvent event here. - - - - Add code to handle the SettingsSaving event here. - Add code to handle the SettingsSaving event here. - - - - Failed to create or open file. - Failed to create or open file. - - - - Description of the setting. - Description of the setting. - - - - Specifies whether or not the default setting value should be generated in the strongly-typed settings class. - Specifies whether or not the default setting value should be generated in the strongly-typed settings class. - - - - Specifies the group to which this Settings file belongs. - Specifies the group to which this Settings file belongs. - - - - Description of the group to which this Settings file belongs. - Description of the group to which this Settings file belongs. - - - - Indicates whether the setting should roam when Windows roaming profiles are enabled. - Indicates whether the setting should roam when Windows roaming profiles are enabled. - - - - Name used to identify the setting. - Name used to identify the setting. - - - - The provider (System.Configuration.Provider.ProviderBase) used to manage the setting. - The provider (System.Configuration.Provider.ProviderBase) used to manage the setting. - - - - Specifies whether the setting is per-application (read-only) or per-user (read-write). - Specifies whether the setting is per-application (read-only) or per-user (read-write). - - - - The setting will be generated as this type in the strongly-typed settings class. For example, the setting might be generated as a String or Integer object. - The setting will be generated as this type in the strongly-typed settings class. For example, the setting might be generated as a String or Integer object. - - - - The current value for the setting. - The current value for the setting. - - - - The following files will be deleted: - -{0} - The following files will be deleted: - -{0} - Synchronize with user.config file - - - No user.config files were found in any of the following locations: - -{0} - No user.config files were found in any of the following locations: - -{0} - - - - One or more user.config files was not removed. - One or more user.config files was not removed. - - - - My.Settings Auto-Save Functionality - My.Settings Auto-Save Functionality - in-code comment used to generate a region that hides My.Settings AutoSave functionality - - - Unable to find service '{0}'. Ensure that the application is installed correctly. - Unable to find service '{0}'. Ensure that the application is installed correctly. - Settings Global-Object-Provider Strings - - - Default pac&kage: - Default pac&kage: - J# Specific String for Root Namespace - - - (Custom) - (Custom) - Entry in the "Accessibility dropdown" - - - No code generation - No code generation - Entry in the "Accessibility dropdown" - - - WPF Application - WPF Application - - - - (Invalid value: "{0}") - (Invalid value: "{0}") - Goes into the ShutdownMode combobox - - - On explicit shutdown - On explicit shutdown - - - - On last window close - On last window close - - - - On main window close - On main window close - - - - Could not find the expected root element "{0}" in the application definition file. - Could not find the expected root element "{0}" in the application definition file. - - - - The .xaml file was in an unexpected format, near line {0} column {1}. - The .xaml file was in an unexpected format, near line {0} column {1}. - - - - Startup &object: - Startup &object: - - - - Startup &URI: - Startup &URI: - - - - The application definition file is already opened in an incompatible editor. Please close the other editor and reload the project properties page. - The application definition file is already opened in an incompatible editor. Please close the other editor and reload the project properties page. - - - - There was an error trying to open or create the application definition file for this project. {0} - There was an error trying to open or create the application definition file for this project. {0} - - - - An error occurred trying to load the application definition file for this project. The file '{0}' could not be parsed. Please edit the file in the XAML editor to fix the error. - An error occurred trying to load the application definition file for this project. The file '{0}' could not be parsed. Please edit the file in the XAML editor to fix the error. - - - - (Error) - (Error) - Used inside UI elements when there is an error (e.g. combobox text) - - - An unspecified error has occurred. - An unspecified error has occurred. - - - - This project does not contain an application definition file. - This project does not contain an application definition file. - - - - An error occurred trying to create the application events file. {0} - An error occurred trying to create the application events file. {0} - - - - Invalid argument '{0}' - Invalid argument '{0}' - {0} = name of invalid argument - - - WPF Console Application - WPF Console Application - - - - WPF Class Library - WPF Class Library - - - - Embed manifest with default settings - Embed manifest with default settings - - - - Create application without a manifest - Create application without a manifest - - - - Invalid manifest file. - Invalid manifest file. - - - - Services - Services - - - - Client application services enable your Windows-based applications to use the ASP.NET login (authentication), roles, and profile (settings) services. - Client application services enable your Windows-based applications to use the ASP.NET login (authentication), roles, and profile (settings) services. - - - - Learn more about client application services... - Learn more about client application services... - - - - Advanced Settings for Services - Advanced Settings for Services - - - - Disabling application services will clear the default services for Authentication, Roles, and Settings. Click OK to disable application services. - Disabling application services will clear the default services for Authentication, Roles, and Settings. Click OK to disable application services. - - - - Disable Application Services - Disable Application Services - - - - seconds - seconds - - - - minutes - minutes - - - - hours - hours - - - - days - days - - - - To enable client application services, you must set the Target Framework for your application to .NET Framework 3.5 or later. In C#, you can do this on the Application property page. In Visual Basic, you can do this one the Compile property page by clicking Advanced Compile Options. - To enable client application services, you must set the Target Framework for your application to .NET Framework 3.5 or later. In C#, you can do this on the Application property page. In Visual Basic, you can do this one the Compile property page by clicking Advanced Compile Options. - - - - An error occurred while reading the Application configuration file. The file might be corrupted or contain invalid XML. - An error occurred while reading the Application configuration file. The file might be corrupted or contain invalid XML. - - - - The URL is invalid. Please enter a valid URL like http://microsoft.com/services - The URL is invalid. Please enter a valid URL like http://microsoft.com/services - - - - A service URL in the application configuration file is not in the expected format. - A service URL in the application configuration file is not in the expected format. - - - - Authentication, Roles and Web Settings providers have been configured via the Application configuration file such that they do not share a common connection string. - Authentication, Roles and Web Settings providers have been configured via the Application configuration file such that they do not share a common connection string. - - - - Specify a connection string to a SQL Server database, or use the special connection string "Data Source = |SQL/CE|", which causes SQL Server Compact to generate local database files for offline storage. - Specify a connection string to a SQL Server database, or use the special connection string "Data Source = |SQL/CE|", which causes SQL Server Compact to generate local database files for offline storage. - - - - The following type names were not understood: '{0}'. Make sure you have references to these types. - The following type names were not understood: '{0}'. Make sure you have references to these types. - - - - There are already settings with the following names: {0}. - There are already settings with the following names: {0}. - - - - The username/password combination cannot be authenticated. - The username/password combination cannot be authenticated. - - - - Windows Forms Application - Windows Forms Application - The "Windows Forms" distinguishes it from a WPF application - - - Namespace of the service reference. - Namespace of the service reference. - - - - Service Reference Properties - Service Reference Properties - - - - Metadata Location Url - Metadata Location Url - - - - Metadata Location - Metadata Location - - - - A service reference with multiple source urls is not supported. - A service reference with multiple source urls is not supported. - - - - Cannot change reference Url to empty. The reference url must be a valid URL. - Cannot change reference Url to empty. The reference url must be a valid URL. - - - - One or more files were reloaded during the checkout. Please retry your operation. - One or more files were reloaded during the checkout. Please retry your operation. - - - - The project was reloaded, and some changes on this page may have been lost. - The project was reloaded, and some changes on this page may have been lost. - - - - The application will fail to run in the selected zone because of this requested elevated permission. Click the help link above for more info. - The application will fail to run in the selected zone because of this requested elevated permission. Click the help link above for more info. - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/MyExtensibilityRes.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/MyExtensibilityRes.en.xlf deleted file mode 100644 index 6796c7696e6..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/MyExtensibilityRes.en.xlf +++ /dev/null @@ -1,107 +0,0 @@ - - - - - - The following My Namespace extensions are associated with assembly '{0}'. Do you want to add them to your project? - The following My Namespace extensions are associated with assembly '{0}'. Do you want to add them to your project? - Label of the add My extensions dialog. - - - Add My Namespace Extensions - Add My Namespace Extensions - Text (caption) of the add My extensions dialog. - - - &Remember my decision for '{0}'. - &Remember my decision for '{0}'. - Text for the option on add / remove My extensions dialog. - - - Removing the reference to '{0}' will make the following My Namespace extensions stop functioning. Do you want to remove them as well? - Removing the reference to '{0}' will make the following My Namespace extensions stop functioning. Do you want to remove them as well? - Label of the remove My extensions dialog. - - - Remove My Namespace Extensions - Remove My Namespace Extensions - Text (caption) of the remove My extensions dialog. - - - No project items were added to the current project from My Namespace extension '{0}'. The extension will not be added to the project. - No project items were added to the current project from My Namespace extension '{0}'. The extension will not be added to the project. - Error message when there is no project items being added to the project from the My Namespace extension template. - - - Failed to Add Project Item - Failed to Add Project Item - Text (caption)for the error message when there is no project items being added to the project from the My Namespace extension template. - - - No project items could be associated with My Namespace extension '{0}'. The extension will not be added to the project. - No project items could be associated with My Namespace extension '{0}'. The extension will not be added to the project. - Error message when we could not set build attributes on any of the project items in My Namespace extension template. - - - Project item '{0}' was added to the current project but could not be associated with My Namespace extension '{1}'. It will not be removed with the extension. - Project item '{0}' was added to the current project but could not be associated with My Namespace extension '{1}'. It will not be removed with the extension. - Error message when we could not set build attributes on one of the project items in My Namespace extension template. - - - Failed to Set Extension Attributes - Failed to Set Extension Attributes - Text (caption) of the error message when we could not set build attributes on one of or any of the project items in My Namespace extension template. - - - Version '{0}' of My Namespace extension '{1}' already exists in the current project. Do you want to overwrite it with version '{2}'? - Version '{0}' of My Namespace extension '{1}' already exists in the current project. Do you want to overwrite it with version '{2}'? - Question to replace an existing My extension in the project. - - - Extension File Already Exists - Extension File Already Exists - Title (caption) for the question to replace an existing My extension in the project. - - - My Extensions - My Extensions - Caption for "My Extensions" property page. - - - My Namespace extensions added: '{0}'. - My Namespace extensions added: '{0}'. - Status bar text listing all My extension templates added. - - - My Namespace extension added: '{0}'. - My Namespace extension added: '{0}'. - Status bar text for each My extension template added. - - - My Namespace extensions added: '{0}'. My Namespace extensions removed: '{1}'. - My Namespace extensions added: '{0}'. My Namespace extensions removed: '{1}'. - Status bar text listing all My extensions added and removed to a project. This is a rare case but may happen if user adds / removes assemblies real fast. - - - Adding My Namespace extensions... - Adding My Namespace extensions... - Status bar text when starting to add My extension templates. - - - My Namespace extensions removed: '{0}'. - My Namespace extensions removed: '{0}'. - Status bar text listing all My extension code files removed. - - - My Namespace extension removed: '{0}'. - My Namespace extension removed: '{0}'. - Status bar text for each My extension code file removed. - - - Removing My Namespace extensions... - Removing My Namespace extensions... - Status bar text when starting to remove My extensions. - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.en.xlf b/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.en.xlf deleted file mode 100644 index be23fe5ce07..00000000000 --- a/vsintegration/src/FSharp.ProjectSystem.PropertyPages/Resources/xlf/WCF.en.xlf +++ /dev/null @@ -1,312 +0,0 @@ - - - - - - Add Service Reference - Add Service Reference - Title for the "Add Service Reference" dialog - - - Unable to find a code generator (CodeDomProvider). - Unable to find a code generator (CodeDomProvider). - - - - Configuration could not be saved. Make sure the configuration file exists and can be edited. - Configuration could not be saved. Make sure the configuration file exists and can be edited. - - - - The current project does not support configuration files. - The current project does not support configuration files. - - - - No services found in the solution. - No services found in the solution. - - - - There was an error downloading metadata from the address. Please verify that you have entered a valid address. - There was an error downloading metadata from the address. Please verify that you have entered a valid address. - - - - {0} service(s) found at address '{1}'. - {0} service(s) found at address '{1}'. - {0} = count, {1} = URL where the services were found - - - {0} service(s) found in the solution. - {0} service(s) found in the solution. - {0} = # of services - - - It is only possible to access the default (ITEMID_ROOT) configuration file. - It is only possible to access the default (ITEMID_ROOT) configuration file. - - - - '{0}' is not a valid namespace for the service reference. - '{0}' is not a valid namespace for the service reference. - - - - Cannot create a service reference with namespace '{0}' because the name is already in use by an existing service reference, folder or file. - Cannot create a service reference with namespace '{0}' because the name is already in use by an existing service reference, folder or file. - - - - Unable to add a new reference. One or more references already exists or the 'Metadata' section is not empty in the .svcmap file. Edit the .svcmap file and clear all the entries from the 'Metadata' section. - Unable to add a new reference. One or more references already exists or the 'Metadata' section is not empty in the .svcmap file. Edit the .svcmap file and clear all the entries from the 'Metadata' section. - - - - A namespace needs to be specified for this service reference. - A namespace needs to be specified for this service reference. - - - - {0}' is not a valid name for a service reference. - {0}' is not a valid name for a service reference. - - - - Empty string is not a valid name for a reference group. - Empty string is not a valid name for a reference group. - - - - Cannot create a reference group named '{0}' because the name is already being used by an existing reference group, folder or file. - Cannot create a reference group named '{0}' because the name is already being used by an existing reference group, folder or file. - - - - Cannot create a reference group with namespace or name with leading or trailing whitespace characters. - Cannot create a reference group with namespace or name with leading or trailing whitespace characters. - - - - The .svcmap file cannot be found. It may have been moved or deleted. To generate a new .svcmap file, delete the service reference and add it again. - The .svcmap file cannot be found. It may have been moved or deleted. To generate a new .svcmap file, delete the service reference and add it again. - - - - The current project does not support service references. To enable Windows Communication Foundation support, change the target version of the Microsoft .NET Framework. - The current project does not support service references. To enable Windows Communication Foundation support, change the target version of the Microsoft .NET Framework. - - - - The configuration for the service reference could not be deleted due to the following issue: {0} - The configuration for the service reference could not be deleted due to the following issue: {0} - - - - The configuration for the service reference could not be updated due to the following issue: {0} - The configuration for the service reference could not be updated due to the following issue: {0} - - - - The configuration for the service reference could not be added due to the following issue: {0} - The configuration for the service reference could not be added due to the following issue: {0} - - - - Please enter the address for a service. - Please enter the address for a service. - - - - An error occurred while attempting to find services at '{0}'. - An error occurred while attempting to find services at '{0}'. - {0} = a URL path - - - An error occurred while searching for services in the solution. - An error occurred while searching for services in the solution. - - - - An error occurred while attempting to start services at '{0}'". - An error occurred while attempting to start services at '{0}'". - {0} = a URL path - - - Please wait for service information to be downloaded or click Stop. - Please wait for service information to be downloaded or click Stop. - - - - Cannot get referenced assemblies from the project system. - Cannot get referenced assemblies from the project system. - - - - The service reference is invalid, because the .svcmap file ('{0}') cannot be found. It may have been moved, deleted or excluded from the project. To generate a new .svcmap file, delete the service reference and add it again. - The service reference is invalid, because the .svcmap file ('{0}') cannot be found. It may have been moved, deleted or excluded from the project. To generate a new .svcmap file, delete the service reference and add it again. - - - - The service reference is invalid. The .svcmap file ('{0}') cannot be loaded. It may be corrupted or in a bad format: {1} - The service reference is invalid. The .svcmap file ('{0}') cannot be loaded. It may be corrupted or in a bad format: {1} - - - - (Details) - (Details) - This is the text for a link to additional error information. - - - Select a service contract to view its operations. - Select a service contract to view its operations. - This is the message displayed when user selects non-cotract nodes. - - - Service Reference Settings - Service Reference Settings - - - - ( Custom ) - ( Custom ) - - - - The assembly '{0}' could not be found. - The assembly '{0}' could not be found. - - - - Address should be a valid non-empty URL. - Address should be a valid non-empty URL. - Error message to display when user enters empty URL in the address change text box - - - {0} service(s) found. - {0} service(s) found. - {0} = count - - - The operation was cancelled. - The operation was cancelled. - - - - Updating Service Reference '{0}' - Updating Service Reference '{0}' - - - - Service reference update complete. - Service reference update complete. - - - - Generating service reference client code... - Generating service reference client code... - - - - Generation of service reference client code complete. - Generation of service reference client code complete. - - - - Updating service reference '{0}'... - Updating service reference '{0}'... - - - - Updating configuration... - Updating configuration... - - - - Configuration update complete. - Configuration update complete. - - - - Service reference update was cancelled. - Service reference update was cancelled. - - - - Service reference update failed. - Service reference update failed. - - - - Add service reference complete. - Add service reference complete. - - - - Add service reference failed. - Add service reference failed. - - - - Creating new service reference to '{0}'... - Creating new service reference to '{0}'... - {0}=URL - - - No assembly is selected. - No assembly is selected. - - - - The requested operation is not valid while an asynchronous operation is in progress. - The requested operation is not valid while an asynchronous operation is in progress. - - - - Multiple addresses (editable in .svcmap file) - Multiple addresses (editable in .svcmap file) - - - - {0} contract(s) found at address '{1}'. - {0} contract(s) found at address '{1}'. - {0} = count, {1} = URL where the contracts were found - - - Unable to create temporary configuration file for downloading service information. - Unable to create temporary configuration file for downloading service information. - - - - The file is already opened in an incompatible editor. - The file is already opened in an incompatible editor. - - - - Downloading service information... - Downloading service information... - - - - The current version of the software does not support adding a service reference to an existing service reference group. - The current version of the software does not support adding a service reference to an existing service reference group. - - - - If the service is defined in the current solution, try building the solution and adding the service reference again. - If the service is defined in the current solution, try building the solution and adding the service reference again. - - - - Mismatching Begin/EndBatch calls. You have called EndBatch more times than BeginBatch. - Mismatching Begin/EndBatch calls. You have called EndBatch more times than BeginBatch. - - - - Failed to generate code for the service reference '{0}'. Please check other error and warning messages for details. - Failed to generate code for the service reference '{0}'. Please check other error and warning messages for details. - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.UIResources/xlf/Strings.en.xlf b/vsintegration/src/FSharp.UIResources/xlf/Strings.en.xlf deleted file mode 100644 index d37ed25e390..00000000000 --- a/vsintegration/src/FSharp.UIResources/xlf/Strings.en.xlf +++ /dev/null @@ -1,192 +0,0 @@ - - - - - - Always place open statements at the top level - Always place open statements at the top level - - - - CodeLens - CodeLens - - - - Show annotations to the right instead of above the line - Show annotations to the right instead of above the line - - - - Enable CodeLens (Experimental) - Enable CodeLens (Experimental) - - - - Annotation prefix - Annotation prefix - - - - Use colors in annotations - Use colors in annotations - - - - Code Fixes - Code Fixes - - - - Completion Lists - Completion Lists - - - - Performance - Performance - - - - D_ash underline - D_ash underline - - - - D_ot underline - D_ot underline - - - - Navigation links - Navigation links - - - - Show s_ymbols in unopened namespaces - Show s_ymbols in unopened namespaces - - - - Show completion list after a character is _deleted - Show completion list after a character is _deleted - - - - _Show completion list after a character is typed - _Show completion list after a character is typed - - - - _Enable in-memory cross project references - _Enable in-memory cross project references - - - - Number of projects whose data is cached in memory - Number of projects whose data is cached in memory - - - - S_how navigation links as - S_how navigation links as - - - - Simplify names (remove unnecessary qualifiers) - Simplify names (remove unnecessary qualifiers) - - - - _Solid underline - _Solid underline - - - - Remove unused open statements - Remove unused open statements - - - - Analyze and suggest fixes for unused values - Analyze and suggest fixes for unused values - - - - Block Structure Guides - Block Structure Guides - - - - Show structure guidelines for F# code - Show structure guidelines for F# code - - - - Outlining - Outlining - - - - Show outlining and collapsible nodes for F# code - Show outlining and collapsible nodes for F# code - - - - Time until stale results are used (in milliseconds) - Time until stale results are used (in milliseconds) - - - - IntelliSense Performance Options - IntelliSense Performance Options - - - - F# Project and Caching Performance Options - F# Project and Caching Performance Options - - - - Enable stale data for IntelliSense features - Enable stale data for IntelliSense features - - - - In-memory cross-project references store project-level data in memory to allow IDE features to work across projects. - In-memory cross-project references store project-level data in memory to allow IDE features to work across projects. - - - - Project data is cached for IDE features. Higher values use more memory because more projects are cached. Tuning this value should not affect small or medium-sized solutions. - Project data is cached for IDE features. Higher values use more memory because more projects are cached. Tuning this value should not affect small or medium-sized solutions. - - - - Always add new line on enter - Always add new line on enter - - - - Never add new line on enter - Never add new line on enter - - - - Only add new line on enter after end of fully typed word - Only add new line on enter after end of fully typed word - - - - Enter key behavior - Enter key behavior - - - - Re-format indentation on paste - Re-format indentation on paste - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.VS.FSI/xlf/Properties.en.xlf b/vsintegration/src/FSharp.VS.FSI/xlf/Properties.en.xlf deleted file mode 100644 index 78bd986fab5..00000000000 --- a/vsintegration/src/FSharp.VS.FSI/xlf/Properties.en.xlf +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - 64-bit F# Interactive - 64-bit F# Interactive - - - - If set to true, and the current machine is 64-bit, then run F# Interactive as a 64-bit process. (Otherwise, F# Interactive is a 32-bit process.) - If set to true, and the current machine is 64-bit, then run F# Interactive as a 64-bit process. (Otherwise, F# Interactive is a 32-bit process.) - - - - F# Interactive options - F# Interactive options - - - - Additional command line arguments passed to the F# Interactive executable by Visual Studio. (optimization and debug flags are ignored if script debugging is enabled) - Additional command line arguments passed to the F# Interactive executable by Visual Studio. (optimization and debug flags are ignored if script debugging is enabled) - - - - Misc - Misc - - - - Shadow copy assemblies - Shadow copy assemblies - - - - Prevents referenced assemblies from being locked by the F# Interactive process. - Prevents referenced assemblies from being locked by the F# Interactive process. - - - - Enable script debugging - Enable script debugging - - - - Enable debugging of F# scripts (may impact script performance, requires reset of F# Interactive) - Enable debugging of F# scripts (may impact script performance, requires reset of F# Interactive) - - - - Debugging - Debugging - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.en.xlf b/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.en.xlf deleted file mode 100644 index 500b07c52cb..00000000000 --- a/vsintegration/src/FSharp.VS.FSI/xlf/VFSIstrings.txt.en.xlf +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - Cannot create window F# Interactive ToolWindow - Cannot create window F# Interactive ToolWindow - - - - Exception raised when creating remoting client for launched fsi.exe\n{0} - Exception raised when creating remoting client for launched fsi.exe\n{0} - - - - Exception raised when requesting FSI ToolWindow.\n{0} - Exception raised when requesting FSI ToolWindow.\n{0} - - - - Could not load F# language service - Could not load F# language service - - - - Session termination detected. Press Enter to restart. - Session termination detected. Press Enter to restart. - - - - F# Interactive - F# Interactive - - - - Could not find fsi.exe, the F# Interactive executable.\nThis file does not exist:\n\n{0}\n - Could not find fsi.exe, the F# Interactive executable.\nThis file does not exist:\n\n{0}\n - - - - Killing process raised exception:\n{0} - Killing process raised exception:\n{0} - - - - The current F# Interactive session is not configured for debugging. For the best experience, enable debugging in F# Interactive settings, then reset the session.\n\nAttempt debugging with current settings? - The current F# Interactive session is not configured for debugging. For the best experience, enable debugging in F# Interactive settings, then reset the session.\n\nAttempt debugging with current settings? - - - - Don't show this warning again - Don't show this warning again - - - - - \ No newline at end of file diff --git a/vsintegration/src/FSharp.VS.FSI/xlf/VSPackage.en.xlf b/vsintegration/src/FSharp.VS.FSI/xlf/VSPackage.en.xlf deleted file mode 100644 index dd67c3bec33..00000000000 --- a/vsintegration/src/FSharp.VS.FSI/xlf/VSPackage.en.xlf +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - J1H0RTAZRQRKDEJ2I3A2PCIAPQQRQIDZI3CTKAIAQPJIE3EPHAMRRKAJCHI1PJM2CPDIRZKMMJHKPHJ9E1HDZHZDC1DEHHR0QIARA8RKA3PICCHAA3QKA1QMJZMKKZKZ - J1H0RTAZRQRKDEJ2I3A2PCIAPQQRQIDZI3CTKAIAQPJIE3EPHAMRRKAJCHI1PJM2CPDIRZKMMJHKPHJ9E1HDZHZDC1DEHHR0QIARA8RKA3PICCHAA3QKA1QMJZMKKZKZ - - - - - \ No newline at end of file From 87cbf6f2faf76e0f4fbbbc4eee0a5bb6efe0786a Mon Sep 17 00:00:00 2001 From: Don Syme Date: Tue, 26 Mar 2019 23:06:10 +0000 Subject: [PATCH 12/27] whitespace cleanup (#6354) --- src/absil/il.fs | 740 +++++----- src/absil/ilbinary.fs | 498 +++---- src/absil/illib.fs | 4 +- src/absil/ilmorph.fs | 2 +- src/absil/ilread.fs | 897 ++++++------- src/absil/ilreflect.fs | 742 +++++----- src/absil/ilsupp.fs | 6 +- src/absil/ilwrite.fs | 654 ++++----- src/fsharp/AugmentWithHashCompare.fs | 38 +- src/fsharp/CompileOps.fs | 518 +++---- src/fsharp/CompileOptions.fs | 34 +- src/fsharp/ConstraintSolver.fs | 28 +- src/fsharp/DetupleArgs.fs | 24 +- src/fsharp/ExtensionTyping.fs | 2 +- src/fsharp/FSharp.Build/Fsc.fs | 4 +- src/fsharp/FSharp.Core/Query.fs | 2 +- src/fsharp/FSharp.Core/array.fs | 2 +- src/fsharp/FSharp.Core/array2.fs | 4 +- src/fsharp/FSharp.Core/map.fs | 16 +- src/fsharp/FSharp.Core/prim-types.fs | 51 +- src/fsharp/FSharp.Core/prim-types.fsi | 2 +- src/fsharp/FSharp.Core/printf.fs | 6 +- src/fsharp/FSharp.Core/quotations.fs | 6 +- src/fsharp/FSharp.Core/reflect.fs | 20 +- src/fsharp/FSharp.Core/set.fs | 8 +- src/fsharp/IlxGen.fs | 692 +++++----- src/fsharp/InfoReader.fs | 6 +- src/fsharp/InnerLambdasToTopLevelFuncs.fs | 8 +- src/fsharp/LexFilter.fs | 278 ++-- src/fsharp/MethodCalls.fs | 6 +- src/fsharp/NameResolution.fs | 2 +- src/fsharp/NicePrint.fs | 2 +- src/fsharp/Optimizer.fs | 562 ++++---- src/fsharp/PatternMatchCompilation.fs | 10 +- src/fsharp/PostInferenceChecks.fs | 6 +- src/fsharp/QuotationPickler.fs | 2 +- src/fsharp/QuotationTranslator.fs | 2 +- src/fsharp/SignatureConformance.fs | 10 +- src/fsharp/TastOps.fs | 1006 +++++++------- src/fsharp/TastPickle.fs | 6 +- src/fsharp/TypeChecker.fs | 1194 ++++++++--------- src/fsharp/TypeRelations.fs | 24 +- src/fsharp/ast.fs | 10 +- src/fsharp/fsc.fs | 4 +- src/fsharp/fsi/fsi.fs | 10 +- src/fsharp/layout.fs | 8 +- src/fsharp/pars.fsy | 10 +- src/fsharp/range.fs | 2 +- src/fsharp/service/IncrementalBuild.fs | 4 +- .../service/ServiceInterfaceStubGenerator.fs | 35 +- src/fsharp/service/ServiceLexing.fs | 2 +- src/fsharp/service/ServiceUntypedParse.fs | 2 +- src/fsharp/symbols/Symbols.fs | 2 +- src/fsharp/tast.fs | 1018 +++++++------- tests/scripts/codingConventions.fsx | 16 + 55 files changed, 4652 insertions(+), 4595 deletions(-) diff --git a/src/absil/il.fs b/src/absil/il.fs index c1a8bc55b03..751e21f64de 100644 --- a/src/absil/il.fs +++ b/src/absil/il.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 FSharp.Compiler.AbstractIL.IL @@ -6,7 +6,6 @@ module FSharp.Compiler.AbstractIL.IL #nowarn "343" // The type 'ILAssemblyRef' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'. #nowarn "346" // The struct, record or union type 'IlxExtensionType' has an explicit implementation of 'Object.Equals'. ... - open System open System.Diagnostics open System.IO @@ -50,7 +49,7 @@ let int_order = LanguagePrimitives.FastGenericComparer 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 +/// 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<_>) = if x.IsValueCreated then notlazy (f (x.Force())) else lazy (f (x.Force())) @@ -196,20 +195,20 @@ type LazyOrderedMultiMap<'Key, 'Data when 'Key : equality>(keyf : 'Data -> 'Key, //--------------------------------------------------------------------- -// SHA1 hash-signing algorithm. Used to get the public key token from +// SHA1 hash-signing algorithm. Used to get the public key token from // the public key. //--------------------------------------------------------------------- -let b0 n = (n &&& 0xFF) -let b1 n = ((n >>> 8) &&& 0xFF) -let b2 n = ((n >>> 16) &&& 0xFF) -let b3 n = ((n >>> 24) &&& 0xFF) +let b0 n = (n &&& 0xFF) +let b1 n = ((n >>> 8) &&& 0xFF) +let b2 n = ((n >>> 16) &&& 0xFF) +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) @@ -232,19 +231,19 @@ module SHA1 = type SHAStream = { stream: byte[] mutable pos: int - mutable eof: bool } + mutable eof: bool } - let rotLeft32 x n = (x <<< n) ||| (x >>>& (32-n)) + let rotLeft32 x n = (x <<< n) ||| (x >>>& (32-n)) // padding and length (in bits!) recorded at end - let shaAfterEof sha = + let shaAfterEof sha = let n = sha.pos let len = sha.stream.Length if n = len then 0x80 else let padded_len = (((len + 9 + 63) / 64) * 64) - 8 - if n < padded_len - 8 then 0x0 + if n < padded_len - 8 then 0x0 elif (n &&& 63) = 56 then int32 ((int64 len * int64 8) >>> 56) &&& 0xff elif (n &&& 63) = 57 then int32 ((int64 len * int64 8) >>> 48) &&& 0xff elif (n &&& 63) = 58 then int32 ((int64 len * int64 8) >>> 40) &&& 0xff @@ -261,7 +260,7 @@ module SHA1 = sha.pos <- sha.pos + 1 b - let shaRead32 sha = + let shaRead32 sha = let b0 = shaRead8 sha let b1 = shaRead8 sha let b2 = shaRead8 sha @@ -307,11 +306,11 @@ module SHA1 = let sha1HashBytes s = let (_h0, _h1, _h2, h3, h4) = sha1Hash { stream = s; pos = 0; eof = false } // the result of the SHA algorithm is stored in registers 3 and 4 - Array.map byte [| b0 h4; b1 h4; b2 h4; b3 h4; b0 h3; b1 h3; b2 h3; b3 h3; |] + Array.map byte [| b0 h4; b1 h4; b2 h4; b3 h4; b0 h3; b1 h3; b2 h3; b3 h3; |] let sha1HashInt64 s = let (_h0,_h1,_h2,h3,h4) = sha1Hash { stream = s; pos = 0; eof = false } // the result of the SHA algorithm is stored in registers 3 and 4 - (int64 h3 <<< 32) ||| int64 h4 + (int64 h3 <<< 32) ||| int64 h4 let sha1HashBytes s = SHA1.sha1HashBytes s let sha1HashInt64 s = SHA1.sha1HashInt64 s @@ -362,7 +361,7 @@ let isMscorlib data = data.assemRefName = "mscorlib" [] -type ILAssemblyRef(data) = +type ILAssemblyRef(data) = let uniqueStamp = AssemblyRefUniqueStampGenerator.Encode(data) member x.Name=data.assemRefName @@ -400,9 +399,9 @@ type ILAssemblyRef(data) = let locale = None let publicKey = - match aname.GetPublicKey() with + match aname.GetPublicKey() with | null | [| |] -> - match aname.GetPublicKeyToken() with + match aname.GetPublicKeyToken() with | null | [| |] -> None | bytes -> Some (PublicKeyToken bytes) | bytes -> @@ -445,7 +444,7 @@ type ILAssemblyRef(data) = let convDigit(digit) = let digitc = if digit < 10 - then System.Convert.ToInt32 '0' + digit + then System.Convert.ToInt32 '0' + digit else System.Convert.ToInt32 'a' + (digit - 10) System.Convert.ToChar(digitc) for i = 0 to pkt.Length-1 do @@ -482,15 +481,15 @@ type ILScopeRef = | Module of ILModuleRef | Assembly of ILAssemblyRef - member x.IsLocalRef = match x with ILScopeRef.Local -> true | _ -> false + member x.IsLocalRef = match x with ILScopeRef.Local -> true | _ -> false - member x.IsModuleRef = match x with ILScopeRef.Module _ -> true | _ -> false + member x.IsModuleRef = match x with ILScopeRef.Module _ -> true | _ -> false member x.IsAssemblyRef= match x with ILScopeRef.Assembly _ -> true | _ -> false - member x.ModuleRef = match x with ILScopeRef.Module x -> x | _ -> failwith "not a module reference" + member x.ModuleRef = match x with ILScopeRef.Module x -> x | _ -> failwith "not a module reference" - member x.AssemblyRef = match x with ILScopeRef.Assembly x -> x | _ -> failwith "not an assembly reference" + member x.AssemblyRef = match x with ILScopeRef.Assembly x -> x | _ -> failwith "not an assembly reference" member x.QualifiedName = match x with @@ -541,15 +540,15 @@ type ILCallingConv = | Callconv of ILThisConvention * ILArgConvention - member x.ThisConv = let (Callconv(a, _b)) = x in a + member x.ThisConv = let (Callconv(a, _b)) = x in a - member x.BasicConv = let (Callconv(_a, b)) = x in b + member x.BasicConv = let (Callconv(_a, b)) = x in b - member x.IsInstance = match x.ThisConv with ILThisConvention.Instance -> true | _ -> false + member x.IsInstance = match x.ThisConv with ILThisConvention.Instance -> true | _ -> false member x.IsInstanceExplicit = match x.ThisConv with ILThisConvention.InstanceExplicit -> true | _ -> false - member x.IsStatic = match x.ThisConv with ILThisConvention.Static -> true | _ -> false + member x.IsStatic = match x.ThisConv with ILThisConvention.Static -> true | _ -> false static member Instance = ILCallingConvStatics.Instance @@ -560,7 +559,7 @@ and ILCallingConvStatics() = static let instanceCallConv = Callconv(ILThisConvention.Instance, ILArgConvention.Default) - static let staticCallConv = Callconv(ILThisConvention.Static, ILArgConvention.Default) + static let staticCallConv = Callconv(ILThisConvention.Static, ILArgConvention.Default) static member Instance = instanceCallConv @@ -687,13 +686,13 @@ and [] ILType = | Void - | Array of ILArrayShape * ILType - | Value of ILTypeSpec - | Boxed of ILTypeSpec - | Ptr of ILType - | Byref of ILType - | FunctionPointer of ILCallingSignature - | TypeVar of uint16 + | Array of ILArrayShape * ILType + | Value of ILTypeSpec + | Boxed of ILTypeSpec + | Ptr of ILType + | Byref of ILType + | FunctionPointer of ILCallingSignature + | TypeVar of uint16 | Modified of bool * ILTypeRef * ILType member x.BasicQualifiedName = @@ -855,9 +854,9 @@ type ILFieldSpec = { FieldRef: ILFieldRef DeclaringType: ILType } - member x.FormalType = x.FieldRef.Type + member x.FormalType = x.FieldRef.Type - member x.Name = x.FieldRef.Name + member x.Name = x.FieldRef.Name member x.DeclaringTypeRef = x.FieldRef.DeclaringTypeRef @@ -871,7 +870,7 @@ type ILFieldSpec = // Debug info. // -------------------------------------------------------------------- -type ILGuid = byte[] +type ILGuid = byte[] type ILPlatform = | X86 @@ -930,7 +929,7 @@ type ILSourceMarker = override x.ToString() = sprintf "(%d, %d)-(%d, %d)" x.Line x.Column x.EndLine x.EndColumn type ILAttribElem = - | String of string option + | String of string option | Bool of bool | Char of char | SByte of int8 @@ -948,7 +947,7 @@ type ILAttribElem = | TypeRef of ILTypeRef option | Array of ILType * ILAttribElem list -type ILAttributeNamedArg = (string * ILType * bool * ILAttribElem) +type ILAttributeNamedArg = (string * ILType * bool * ILAttribElem) [] type ILAttribute = @@ -1005,7 +1004,7 @@ let mkILCustomAttrs l = match l with [] -> emptyILCustomAttrs | _ -> mkILCustomA let emptyILCustomAttrsStored = ILAttributesStored.Given emptyILCustomAttrs -let storeILCustomAttrs (attrs: ILAttributes) = if attrs.AsArray.Length = 0 then emptyILCustomAttrsStored else ILAttributesStored.Given attrs +let storeILCustomAttrs (attrs: ILAttributes) = if attrs.AsArray.Length = 0 then emptyILCustomAttrsStored else ILAttributesStored.Given attrs let mkILCustomAttrsReader f = ILAttributesStored.Reader f @@ -1093,9 +1092,9 @@ type ILInstr = | AI_cgt_un | AI_clt | AI_clt_un - | AI_conv of ILBasicType - | AI_conv_ovf of ILBasicType - | AI_conv_ovf_un of ILBasicType + | AI_conv of ILBasicType + | AI_conv_ovf of ILBasicType + | AI_conv_ovf_un of ILBasicType | AI_mul | AI_mul_ovf | AI_mul_ovf_un @@ -1117,66 +1116,66 @@ type ILInstr = | AI_ckfinite | AI_nop | AI_ldc of ILBasicType * ILConst - | I_ldarg of uint16 - | I_ldarga of uint16 - | I_ldind of ILAlignment * ILVolatility * ILBasicType - | I_ldloc of uint16 - | I_ldloca of uint16 - | I_starg of uint16 - | I_stind of ILAlignment * ILVolatility * ILBasicType - | I_stloc of uint16 - - | I_br of ILCodeLabel - | I_jmp of ILMethodSpec + | I_ldarg of uint16 + | I_ldarga of uint16 + | I_ldind of ILAlignment * ILVolatility * ILBasicType + | I_ldloc of uint16 + | I_ldloca of uint16 + | I_starg of uint16 + | I_stind of ILAlignment * ILVolatility * ILBasicType + | I_stloc of uint16 + + | I_br of ILCodeLabel + | I_jmp of ILMethodSpec | I_brcmp of ILComparisonInstr * ILCodeLabel - | I_switch of ILCodeLabel list + | I_switch of ILCodeLabel list | I_ret - | I_call of ILTailcall * ILMethodSpec * ILVarArgs + | I_call of ILTailcall * ILMethodSpec * ILVarArgs | I_callvirt of ILTailcall * ILMethodSpec * ILVarArgs | I_callconstraint of ILTailcall * ILType * ILMethodSpec * ILVarArgs - | I_calli of ILTailcall * ILCallingSignature * ILVarArgs - | I_ldftn of ILMethodSpec - | I_newobj of ILMethodSpec * ILVarArgs + | I_calli of ILTailcall * ILCallingSignature * ILVarArgs + | I_ldftn of ILMethodSpec + | I_newobj of ILMethodSpec * ILVarArgs | I_throw | I_endfinally | I_endfilter - | I_leave of ILCodeLabel + | I_leave of ILCodeLabel | I_rethrow - | I_ldsfld of ILVolatility * ILFieldSpec - | I_ldfld of ILAlignment * ILVolatility * ILFieldSpec - | I_ldsflda of ILFieldSpec - | I_ldflda of ILFieldSpec - | I_stsfld of ILVolatility * ILFieldSpec - | I_stfld of ILAlignment * ILVolatility * ILFieldSpec - | I_ldstr of string - | I_isinst of ILType - | I_castclass of ILType - | I_ldtoken of ILToken - | I_ldvirtftn of ILMethodSpec - - | I_cpobj of ILType - | I_initobj of ILType - | I_ldobj of ILAlignment * ILVolatility * ILType - | I_stobj of ILAlignment * ILVolatility * ILType - | I_box of ILType - | I_unbox of ILType - | I_unbox_any of ILType - | I_sizeof of ILType - - | I_ldelem of ILBasicType - | I_stelem of ILBasicType - | I_ldelema of ILReadonly * bool * ILArrayShape * ILType - | I_ldelem_any of ILArrayShape * ILType - | I_stelem_any of ILArrayShape * ILType - | I_newarr of ILArrayShape * ILType + | I_ldsfld of ILVolatility * ILFieldSpec + | I_ldfld of ILAlignment * ILVolatility * ILFieldSpec + | I_ldsflda of ILFieldSpec + | I_ldflda of ILFieldSpec + | I_stsfld of ILVolatility * ILFieldSpec + | I_stfld of ILAlignment * ILVolatility * ILFieldSpec + | I_ldstr of string + | I_isinst of ILType + | I_castclass of ILType + | I_ldtoken of ILToken + | I_ldvirtftn of ILMethodSpec + + | I_cpobj of ILType + | I_initobj of ILType + | I_ldobj of ILAlignment * ILVolatility * ILType + | I_stobj of ILAlignment * ILVolatility * ILType + | I_box of ILType + | I_unbox of ILType + | I_unbox_any of ILType + | I_sizeof of ILType + + | I_ldelem of ILBasicType + | I_stelem of ILBasicType + | I_ldelema of ILReadonly * bool * ILArrayShape * ILType + | I_ldelem_any of ILArrayShape * ILType + | I_stelem_any of ILArrayShape * ILType + | I_newarr of ILArrayShape * ILType | I_ldlen - | I_mkrefany of ILType + | I_mkrefany of ILType | I_refanytype - | I_refanyval of ILType + | I_refanyval of ILType | I_break | I_seqpoint of ILSourceMarker @@ -1185,17 +1184,17 @@ type ILInstr = | I_localloc | I_cpblk of ILAlignment * ILVolatility - | I_initblk of ILAlignment * ILVolatility + | I_initblk of ILAlignment * ILVolatility (* FOR EXTENSIONS, e.g. MS-ILX *) | EI_ilzero of ILType - | EI_ldlen_multi of int32 * int32 + | EI_ldlen_multi of int32 * int32 [] type ILExceptionClause = | Finally of (ILCodeLabel * ILCodeLabel) - | Fault of (ILCodeLabel * ILCodeLabel) + | Fault of (ILCodeLabel * ILCodeLabel) | FilterCatch of (ILCodeLabel * ILCodeLabel) * (ILCodeLabel * ILCodeLabel) | TypeCatch of ILType * (ILCodeLabel * ILCodeLabel) @@ -1239,7 +1238,7 @@ type ILMethodBody = NoInlining: bool AggressiveInlining: bool Locals: ILLocals - Code: ILCode + Code: ILCode SourceMarker: ILSourceMarker option } [] @@ -1419,7 +1418,7 @@ let storeILSecurityDecls (x: ILSecurityDecls) = if x.AsArray.Length = 0 then emp let mkILSecurityDeclsReader f = ILSecurityDeclsStored.Reader f [] -type PInvokeCharBestFit = +type PInvokeCharBestFit = | UseAssembly | Enabled | Disabled @@ -1467,7 +1466,7 @@ type ILParameter = IsOut: bool IsOptional: bool CustomAttrsStored: ILAttributesStored - MetadataIndex: int32 } + MetadataIndex: int32 } member x.CustomAttrs = x.CustomAttrsStored.GetCustomAttrs x.MetadataIndex @@ -1478,7 +1477,7 @@ type ILReturn = { Marshal: ILNativeType option Type: ILType CustomAttrsStored: ILAttributesStored - MetadataIndex: int32 } + MetadataIndex: int32 } member x.CustomAttrs = x.CustomAttrsStored.GetCustomAttrs x.MetadataIndex @@ -1507,7 +1506,7 @@ type MethodKind = [] type MethodBody = | IL of ILMethodBody - | PInvoke of PInvokeMethod (* platform invoke to native *) + | PInvoke of PInvokeMethod (* platform invoke to native *) | Abstract | Native | NotAvailable @@ -1558,23 +1557,23 @@ type ILGenericParameterDefs = ILGenericParameterDef list let memberAccessOfFlags flags = let f = (flags &&& 0x00000007) - if f = 0x00000001 then ILMemberAccess.Private - elif f = 0x00000006 then ILMemberAccess.Public - elif f = 0x00000004 then ILMemberAccess.Family - elif f = 0x00000002 then ILMemberAccess.FamilyAndAssembly - elif f = 0x00000005 then ILMemberAccess.FamilyOrAssembly - elif f = 0x00000003 then ILMemberAccess.Assembly + if f = 0x00000001 then ILMemberAccess.Private + elif f = 0x00000006 then ILMemberAccess.Public + elif f = 0x00000004 then ILMemberAccess.Family + elif f = 0x00000002 then ILMemberAccess.FamilyAndAssembly + elif f = 0x00000005 then ILMemberAccess.FamilyOrAssembly + elif f = 0x00000003 then ILMemberAccess.Assembly else ILMemberAccess.CompilerControlled let convertMemberAccess (ilMemberAccess: ILMemberAccess) = match ilMemberAccess with - | ILMemberAccess.Public -> MethodAttributes.Public - | ILMemberAccess.Private -> MethodAttributes.Private - | ILMemberAccess.Assembly -> MethodAttributes.Assembly - | ILMemberAccess.FamilyAndAssembly -> MethodAttributes.FamANDAssem - | ILMemberAccess.CompilerControlled -> MethodAttributes.PrivateScope - | ILMemberAccess.FamilyOrAssembly -> MethodAttributes.FamORAssem - | ILMemberAccess.Family -> MethodAttributes.Family + | ILMemberAccess.Public -> MethodAttributes.Public + | ILMemberAccess.Private -> MethodAttributes.Private + | ILMemberAccess.Assembly -> MethodAttributes.Assembly + | ILMemberAccess.FamilyAndAssembly -> MethodAttributes.FamANDAssem + | ILMemberAccess.CompilerControlled -> MethodAttributes.PrivateScope + | ILMemberAccess.FamilyOrAssembly -> MethodAttributes.FamORAssem + | ILMemberAccess.Family -> MethodAttributes.Family let inline conditionalAdd condition flagToAdd source = if condition then source ||| flagToAdd else source &&& ~~~flagToAdd @@ -1650,37 +1649,37 @@ type ILMethodDef (name: string, attributes: MethodAttributes, implAttributes: Me member x.SourceMarker = x.MethodBody.SourceMarker - member x.MaxStack = x.MethodBody.MaxStack + member x.MaxStack = x.MethodBody.MaxStack - member x.IsZeroInit = x.MethodBody.IsZeroInit + member x.IsZeroInit = x.MethodBody.IsZeroInit - member md.CallingSignature = mkILCallSig (md.CallingConv, md.ParameterTypes, md.Return.Type) + member md.CallingSignature = mkILCallSig (md.CallingConv, md.ParameterTypes, md.Return.Type) - member x.IsClassInitializer = x.Name = ".cctor" - member x.IsConstructor = x.Name = ".ctor" + member x.IsClassInitializer = x.Name = ".cctor" + member x.IsConstructor = x.Name = ".ctor" - member x.Access = memberAccessOfFlags (int x.Attributes) - member x.IsStatic = x.Attributes &&& MethodAttributes.Static <> enum 0 - member x.IsNonVirtualInstance = not x.IsStatic && not x.IsVirtual - member x.IsVirtual = x.Attributes &&& MethodAttributes.Virtual <> enum 0 - member x.IsFinal = x.Attributes &&& MethodAttributes.Final <> enum 0 - member x.IsNewSlot = x.Attributes &&& MethodAttributes.NewSlot <> enum 0 + member x.Access = memberAccessOfFlags (int x.Attributes) + member x.IsStatic = x.Attributes &&& MethodAttributes.Static <> enum 0 + member x.IsNonVirtualInstance = not x.IsStatic && not x.IsVirtual + member x.IsVirtual = x.Attributes &&& MethodAttributes.Virtual <> enum 0 + member x.IsFinal = x.Attributes &&& MethodAttributes.Final <> enum 0 + member x.IsNewSlot = x.Attributes &&& MethodAttributes.NewSlot <> enum 0 member x.IsCheckAccessOnOverride= x.Attributes &&& MethodAttributes.CheckAccessOnOverride <> enum 0 - member x.IsAbstract = x.Attributes &&& MethodAttributes.Abstract <> enum 0 - member x.IsHideBySig = x.Attributes &&& MethodAttributes.HideBySig <> enum 0 - member x.IsSpecialName = x.Attributes &&& MethodAttributes.SpecialName <> enum 0 - member x.IsUnmanagedExport = x.Attributes &&& MethodAttributes.UnmanagedExport <> enum 0 - member x.IsReqSecObj = x.Attributes &&& MethodAttributes.RequireSecObject <> enum 0 - member x.HasSecurity = x.Attributes &&& MethodAttributes.HasSecurity <> enum 0 - - member x.IsManaged = x.ImplAttributes &&& MethodImplAttributes.Managed <> enum 0 - member x.IsForwardRef = x.ImplAttributes &&& MethodImplAttributes.ForwardRef <> enum 0 - member x.IsInternalCall = x.ImplAttributes &&& MethodImplAttributes.InternalCall <> enum 0 - member x.IsPreserveSig = x.ImplAttributes &&& MethodImplAttributes.PreserveSig <> enum 0 - member x.IsSynchronized = x.ImplAttributes &&& MethodImplAttributes.Synchronized <> enum 0 - member x.IsNoInline = x.ImplAttributes &&& MethodImplAttributes.NoInlining <> enum 0 + member x.IsAbstract = x.Attributes &&& MethodAttributes.Abstract <> enum 0 + member x.IsHideBySig = x.Attributes &&& MethodAttributes.HideBySig <> enum 0 + member x.IsSpecialName = x.Attributes &&& MethodAttributes.SpecialName <> enum 0 + member x.IsUnmanagedExport = x.Attributes &&& MethodAttributes.UnmanagedExport <> enum 0 + member x.IsReqSecObj = x.Attributes &&& MethodAttributes.RequireSecObject <> enum 0 + member x.HasSecurity = x.Attributes &&& MethodAttributes.HasSecurity <> enum 0 + + member x.IsManaged = x.ImplAttributes &&& MethodImplAttributes.Managed <> enum 0 + member x.IsForwardRef = x.ImplAttributes &&& MethodImplAttributes.ForwardRef <> enum 0 + member x.IsInternalCall = x.ImplAttributes &&& MethodImplAttributes.InternalCall <> enum 0 + member x.IsPreserveSig = x.ImplAttributes &&& MethodImplAttributes.PreserveSig <> enum 0 + member x.IsSynchronized = x.ImplAttributes &&& MethodImplAttributes.Synchronized <> enum 0 + member x.IsNoInline = x.ImplAttributes &&& MethodImplAttributes.NoInlining <> enum 0 member x.IsAggressiveInline= x.ImplAttributes &&& MethodImplAttributes.AggressiveInlining <> enum 0 - member x.IsMustRun = x.ImplAttributes &&& MethodImplAttributes.NoOptimization <> enum 0 + member x.IsMustRun = x.ImplAttributes &&& MethodImplAttributes.NoOptimization <> enum 0 member x.WithSpecialName = x.With(attributes = (x.Attributes ||| MethodAttributes.SpecialName)) member x.WithHideBySig() = @@ -1831,17 +1830,17 @@ type ILPropertyDefs = let convertFieldAccess (ilMemberAccess: ILMemberAccess) = match ilMemberAccess with - | ILMemberAccess.Assembly -> FieldAttributes.Assembly - | ILMemberAccess.CompilerControlled -> enum(0) - | ILMemberAccess.FamilyAndAssembly -> FieldAttributes.FamANDAssem - | ILMemberAccess.FamilyOrAssembly -> FieldAttributes.FamORAssem - | ILMemberAccess.Family -> FieldAttributes.Family - | ILMemberAccess.Private -> FieldAttributes.Private - | ILMemberAccess.Public -> FieldAttributes.Public + | ILMemberAccess.Assembly -> FieldAttributes.Assembly + | ILMemberAccess.CompilerControlled -> enum(0) + | ILMemberAccess.FamilyAndAssembly -> FieldAttributes.FamANDAssem + | ILMemberAccess.FamilyOrAssembly -> FieldAttributes.FamORAssem + | ILMemberAccess.Family -> FieldAttributes.Family + | ILMemberAccess.Private -> FieldAttributes.Private + | ILMemberAccess.Public -> FieldAttributes.Public [] type ILFieldDef(name: string, fieldType: ILType, attributes: FieldAttributes, data: byte[] option, - literalValue: ILFieldInit option, offset: int32 option, marshal: ILNativeType option, + literalValue: ILFieldInit option, offset: int32 option, marshal: ILNativeType option, customAttrsStored: ILAttributesStored, metadataIndex: int32) = new (name, fieldType, attributes, data, literalValue, offset, marshal, customAttrs) = @@ -1857,7 +1856,7 @@ type ILFieldDef(name: string, fieldType: ILType, attributes: FieldAttributes, da member x.CustomAttrs = customAttrsStored.GetCustomAttrs x.MetadataIndex member x.MetadataIndex = metadataIndex - member x.With(?name: string, ?fieldType: ILType, ?attributes: FieldAttributes, ?data: byte[] option, ?literalValue: ILFieldInit option, ?offset: int32 option, ?marshal: ILNativeType option, ?customAttrs: ILAttributes) = + member x.With(?name: string, ?fieldType: ILType, ?attributes: FieldAttributes, ?data: byte[] option, ?literalValue: ILFieldInit option, ?offset: int32 option, ?marshal: ILNativeType option, ?customAttrs: ILAttributes) = ILFieldDef(name=defaultArg name x.Name, fieldType=defaultArg fieldType x.FieldType, attributes=defaultArg attributes x.Attributes, @@ -1881,7 +1880,7 @@ type ILFieldDef(name: string, fieldType: ILType, attributes: FieldAttributes, da member x.WithFieldMarshal(marshal) = x.With(marshal = marshal, attributes = (x.Attributes |> conditionalAdd marshal.IsSome FieldAttributes.HasFieldMarshal)) -// Index table by name. Keep a canonical list to make sure field order is not disturbed for binary manipulation. +// Index table by name. Keep a canonical list to make sure field order is not disturbed for binary manipulation. type ILFieldDefs = | ILFields of LazyOrderedMultiMap @@ -1957,7 +1956,7 @@ let typeKindOfFlags nm _mdefs _fdefs (super: ILType option) flags = else let isEnum, isDelegate, isMulticastDelegate, isValueType = match super with - | None -> false , false, false, false + | None -> false, false, false, false | Some ty -> ty.TypeSpec.Name = "System.Enum", ty.TypeSpec.Name = "System.Delegate", @@ -1965,17 +1964,17 @@ let typeKindOfFlags nm _mdefs _fdefs (super: ILType option) flags = ty.TypeSpec.Name = "System.ValueType" && nm <> "System.Enum" let selfIsMulticastDelegate = nm = "System.MulticastDelegate" if isEnum then ILTypeDefKind.Enum - elif (isDelegate && not selfIsMulticastDelegate) || isMulticastDelegate then ILTypeDefKind.Delegate + elif (isDelegate && not selfIsMulticastDelegate) || isMulticastDelegate then ILTypeDefKind.Delegate elif isValueType then ILTypeDefKind.ValueType else ILTypeDefKind.Class let convertTypeAccessFlags access = match access with | ILTypeDefAccess.Public -> TypeAttributes.Public - | ILTypeDefAccess.Private -> TypeAttributes.NotPublic + | ILTypeDefAccess.Private -> TypeAttributes.NotPublic | ILTypeDefAccess.Nested ILMemberAccess.Public -> TypeAttributes.NestedPublic - | ILTypeDefAccess.Nested ILMemberAccess.Private -> TypeAttributes.NestedPrivate - | ILTypeDefAccess.Nested ILMemberAccess.Family -> TypeAttributes.NestedFamily + | ILTypeDefAccess.Nested ILMemberAccess.Private -> TypeAttributes.NestedPrivate + | ILTypeDefAccess.Nested ILMemberAccess.Family -> TypeAttributes.NestedFamily | ILTypeDefAccess.Nested ILMemberAccess.CompilerControlled -> TypeAttributes.NestedPrivate | ILTypeDefAccess.Nested ILMemberAccess.FamilyAndAssembly -> TypeAttributes.NestedFamANDAssem | ILTypeDefAccess.Nested ILMemberAccess.FamilyOrAssembly -> TypeAttributes.NestedFamORAssem @@ -2003,13 +2002,13 @@ let convertEncoding encoding = let convertToNestedTypeAccess (ilMemberAccess: ILMemberAccess) = match ilMemberAccess with - | ILMemberAccess.Assembly -> TypeAttributes.NestedAssembly - | ILMemberAccess.CompilerControlled -> failwith "Method access compiler controlled." - | ILMemberAccess.FamilyAndAssembly -> TypeAttributes.NestedFamANDAssem - | ILMemberAccess.FamilyOrAssembly -> TypeAttributes.NestedFamORAssem - | ILMemberAccess.Family -> TypeAttributes.NestedFamily - | ILMemberAccess.Private -> TypeAttributes.NestedPrivate - | ILMemberAccess.Public -> TypeAttributes.NestedPublic + | ILMemberAccess.Assembly -> TypeAttributes.NestedAssembly + | ILMemberAccess.CompilerControlled -> failwith "Method access compiler controlled." + | ILMemberAccess.FamilyAndAssembly -> TypeAttributes.NestedFamANDAssem + | ILMemberAccess.FamilyOrAssembly -> TypeAttributes.NestedFamORAssem + | ILMemberAccess.Family -> TypeAttributes.NestedFamily + | ILMemberAccess.Private -> TypeAttributes.NestedPrivate + | ILMemberAccess.Public -> TypeAttributes.NestedPublic let convertInitSemantics (init: ILTypeInit) = match init with @@ -2069,11 +2068,11 @@ type ILTypeDef(name: string, attributes: TypeAttributes, layout: ILTypeDefLayout member x.SecurityDecls = x.SecurityDeclsStored.GetSecurityDecls x.MetadataIndex - member x.IsClass = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Class - member x.IsStruct = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.ValueType + member x.IsClass = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Class + member x.IsStruct = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.ValueType member x.IsInterface = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Interface - member x.IsEnum = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Enum - member x.IsDelegate = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Delegate + member x.IsEnum = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Enum + member x.IsDelegate = (typeKindOfFlags x.Name x.Methods x.Fields x.Extends (int x.Attributes)) = ILTypeDefKind.Delegate member x.Access = typeAccessOfFlags (int x.Attributes) member x.IsAbstract = x.Attributes &&& TypeAttributes.Abstract <> enum 0 member x.IsSealed = x.Attributes &&& TypeAttributes.Sealed <> enum 0 @@ -2121,7 +2120,7 @@ and [] ILTypeDefs(f : unit -> ILPreTypeDef[]) = member x.AsArrayOfPreTypeDefs = array.Value - member x.FindByName nm = + member x.FindByName nm = let ns, n = splitILTypeName nm dict.Value.[(ns, n)].GetTypeDef() @@ -2314,15 +2313,15 @@ let emptyILGenericArgsList = ([]: ILType list) // -------------------------------------------------------------------- -let mkILNestedTyRef (scope, l, nm) = ILTypeRef.Create(scope, l, nm) +let mkILNestedTyRef (scope, l, nm) = ILTypeRef.Create(scope, l, nm) -let mkILTyRef (scope, nm) = mkILNestedTyRef (scope, [], nm) +let mkILTyRef (scope, nm) = mkILNestedTyRef (scope, [], nm) type ILGenericArgsList = ILType list -let mkILTySpec (tref, inst) = ILTypeSpec.Create(tref, inst) +let mkILTySpec (tref, inst) = ILTypeSpec.Create(tref, inst) -let mkILNonGenericTySpec tref = mkILTySpec (tref, []) +let mkILNonGenericTySpec tref = mkILTySpec (tref, []) let mkILTyRefInTyRef (tref: ILTypeRef, nm) = mkILNestedTyRef (tref.Scope, tref.Enclosing@[tref.Name], nm) @@ -2428,14 +2427,14 @@ let generateCodeLabel() = System.Threading.Interlocked.Increment(codeLabelCount) let instrIsRet i = match i with - | I_ret -> true + | I_ret -> true | _ -> false let nonBranchingInstrsToCode instrs : ILCode = let instrs = Array.ofList instrs let instrs = if instrs.Length <> 0 && instrIsRet (Array.last instrs) then instrs - else Array.append instrs [| I_ret |] + else Array.append instrs [| I_ret |] { Labels = Dictionary() Instrs = instrs @@ -2463,7 +2462,7 @@ 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,7 +2473,7 @@ 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) // -------------------------------------------------------------------- @@ -2491,8 +2490,8 @@ let mkILPreTypeDefRead (ns, n, idx, f) = let addILTypeDef td (tdefs: ILTypeDefs) = ILTypeDefs (fun () -> [| yield mkILPreTypeDef td; yield! tdefs.AsArrayOfPreTypeDefs |]) -let mkILTypeDefsFromArray (l: ILTypeDef[]) = ILTypeDefs (fun () -> Array.map mkILPreTypeDef l) -let mkILTypeDefs l = mkILTypeDefsFromArray (Array.ofList l) +let mkILTypeDefsFromArray (l: ILTypeDef[]) = ILTypeDefs (fun () -> Array.map mkILPreTypeDef l) +let mkILTypeDefs l = mkILTypeDefsFromArray (Array.ofList l) let mkILTypeDefsComputed f = ILTypeDefs f let emptyILTypeDefs = mkILTypeDefsFromArray [| |] @@ -2500,9 +2499,9 @@ let emptyILTypeDefs = mkILTypeDefsFromArray [| |] // Operations on method tables. // -------------------------------------------------------------------- -let mkILMethodsFromArray xs = ILMethodDefs (fun () -> xs) -let mkILMethods xs = xs |> Array.ofList |> mkILMethodsFromArray -let mkILMethodsComputed f = ILMethodDefs f +let mkILMethodsFromArray xs = ILMethodDefs (fun () -> xs) +let mkILMethods xs = xs |> Array.ofList |> mkILMethodsFromArray +let mkILMethodsComputed f = ILMethodDefs f let emptyILMethods = mkILMethodsFromArray [| |] let filterILMethodDefs f (mdefs: ILMethodDefs) = @@ -2612,26 +2611,26 @@ type ILGlobals(primaryScopeRef) = let m_typ_IntPtr = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_IntPtr)) let m_typ_UIntPtr = ILType.Value (mkILNonGenericTySpec (m_mkSysILTypeRef tname_UIntPtr)) - member x.primaryAssemblyScopeRef = m_typ_Object.TypeRef.Scope - member x.primaryAssemblyName = m_typ_Object.TypeRef.Scope.AssemblyRef.Name - member x.typ_Object = m_typ_Object - member x.typ_String = m_typ_String - member x.typ_Array = m_typ_Array - member x.typ_Type = m_typ_Type - member x.typ_IntPtr = m_typ_IntPtr - member x.typ_UIntPtr = m_typ_UIntPtr - member x.typ_Byte = m_typ_Byte - member x.typ_Int16 = m_typ_Int16 - member x.typ_Int32 = m_typ_Int32 - member x.typ_Int64 = m_typ_Int64 - member x.typ_SByte = m_typ_SByte - member x.typ_UInt16 = m_typ_UInt16 - member x.typ_UInt32 = m_typ_UInt32 - member x.typ_UInt64 = m_typ_UInt64 - member x.typ_Single = m_typ_Single - member x.typ_Double = m_typ_Double - member x.typ_Bool = m_typ_Bool - member x.typ_Char = m_typ_Char + member x.primaryAssemblyScopeRef = m_typ_Object.TypeRef.Scope + member x.primaryAssemblyName = m_typ_Object.TypeRef.Scope.AssemblyRef.Name + member x.typ_Object = m_typ_Object + member x.typ_String = m_typ_String + member x.typ_Array = m_typ_Array + member x.typ_Type = m_typ_Type + member x.typ_IntPtr = m_typ_IntPtr + member x.typ_UIntPtr = m_typ_UIntPtr + member x.typ_Byte = m_typ_Byte + member x.typ_Int16 = m_typ_Int16 + member x.typ_Int32 = m_typ_Int32 + member x.typ_Int64 = m_typ_Int64 + member x.typ_SByte = m_typ_SByte + member x.typ_UInt16 = m_typ_UInt16 + member x.typ_UInt32 = m_typ_UInt32 + member x.typ_UInt64 = m_typ_UInt64 + member x.typ_Single = m_typ_Single + member x.typ_Double = m_typ_Double + member x.typ_Bool = m_typ_Bool + member x.typ_Char = m_typ_Char /// For debugging [] @@ -2647,12 +2646,12 @@ let mkNormalCallvirt mspec = I_callvirt (Normalcall, mspec, None) let mkNormalCallconstraint (ty, mspec) = I_callconstraint (Normalcall, ty, mspec, None) -let mkNormalNewobj mspec = I_newobj (mspec, None) +let mkNormalNewobj mspec = I_newobj (mspec, None) /// Comment on common object cache sizes: /// mkLdArg - I can't imagine any IL method we generate needing more than this /// mkLdLoc - I tried 256, and there were LdLoc allocations left, so I upped it o 512. I didn't check again. -/// mkStLoc - it should be the same as LdLoc (where there's a LdLoc there must be a StLoc) +/// mkStLoc - it should be the same as LdLoc (where there's a LdLoc there must be a StLoc) /// mkLdcInt32 - just a guess let ldargs = [| for i in 0 .. 128 -> I_ldarg (uint16 i) |] @@ -2699,39 +2698,39 @@ let isILBoxedPrimaryAssemblyTy (ty: ILType) n = let isILValuePrimaryAssemblyTy (ty: ILType) n = isILValueTy ty && isPrimaryAssemblyTySpec ty.TypeSpec n -let isILObjectTy ty = isILBoxedPrimaryAssemblyTy ty tname_Object +let isILObjectTy ty = isILBoxedPrimaryAssemblyTy ty tname_Object -let isILStringTy ty = isILBoxedPrimaryAssemblyTy ty tname_String +let isILStringTy ty = isILBoxedPrimaryAssemblyTy ty tname_String -let isILTypedReferenceTy ty = isILValuePrimaryAssemblyTy ty "System.TypedReference" +let isILTypedReferenceTy ty = isILValuePrimaryAssemblyTy ty "System.TypedReference" -let isILSByteTy ty = isILValuePrimaryAssemblyTy ty tname_SByte +let isILSByteTy ty = isILValuePrimaryAssemblyTy ty tname_SByte -let isILByteTy ty = isILValuePrimaryAssemblyTy ty tname_Byte +let isILByteTy ty = isILValuePrimaryAssemblyTy ty tname_Byte -let isILInt16Ty ty = isILValuePrimaryAssemblyTy ty tname_Int16 +let isILInt16Ty ty = isILValuePrimaryAssemblyTy ty tname_Int16 -let isILUInt16Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt16 +let isILUInt16Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt16 -let isILInt32Ty ty = isILValuePrimaryAssemblyTy ty tname_Int32 +let isILInt32Ty ty = isILValuePrimaryAssemblyTy ty tname_Int32 -let isILUInt32Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt32 +let isILUInt32Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt32 -let isILInt64Ty ty = isILValuePrimaryAssemblyTy ty tname_Int64 +let isILInt64Ty ty = isILValuePrimaryAssemblyTy ty tname_Int64 -let isILUInt64Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt64 +let isILUInt64Ty ty = isILValuePrimaryAssemblyTy ty tname_UInt64 -let isILIntPtrTy ty = isILValuePrimaryAssemblyTy ty tname_IntPtr +let isILIntPtrTy ty = isILValuePrimaryAssemblyTy ty tname_IntPtr -let isILUIntPtrTy ty = isILValuePrimaryAssemblyTy ty tname_UIntPtr +let isILUIntPtrTy ty = isILValuePrimaryAssemblyTy ty tname_UIntPtr -let isILBoolTy ty = isILValuePrimaryAssemblyTy ty tname_Bool +let isILBoolTy ty = isILValuePrimaryAssemblyTy ty tname_Bool -let isILCharTy ty = isILValuePrimaryAssemblyTy ty tname_Char +let isILCharTy ty = isILValuePrimaryAssemblyTy ty tname_Char -let isILSingleTy ty = isILValuePrimaryAssemblyTy ty tname_Single +let isILSingleTy ty = isILValuePrimaryAssemblyTy ty tname_Single -let isILDoubleTy ty = isILValuePrimaryAssemblyTy ty tname_Double +let isILDoubleTy ty = isILValuePrimaryAssemblyTy ty tname_Double // -------------------------------------------------------------------- // Rescoping @@ -2793,7 +2792,7 @@ and rescopeILTypes scoref i = if isNil i then i else List.mapq (rescopeILType scoref) i -and rescopeILCallSig scoref csig = +and rescopeILCallSig scoref csig = mkILCallSig (csig.CallingConv, rescopeILTypes scoref csig.ArgTypes, rescopeILType scoref csig.ReturnType) let rescopeILMethodRef scoref (x: ILMethodRef) = @@ -2818,13 +2817,13 @@ let rec instILTypeSpecAux numFree inst (tspec: ILTypeSpec) = 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) + | ILType.Ptr t -> ILType.Ptr (instILTypeAux numFree inst t) + | ILType.FunctionPointer t -> ILType.FunctionPointer (instILCallSigAux numFree inst t) | ILType.Array (a, t) -> ILType.Array (a, instILTypeAux numFree inst t) - | ILType.Byref t -> ILType.Byref (instILTypeAux numFree inst t) - | ILType.Boxed cr -> mkILBoxedType (instILTypeSpecAux numFree inst cr) - | ILType.Value cr -> ILType.Value (instILTypeSpecAux numFree inst cr) - | ILType.TypeVar v -> + | ILType.Byref t -> ILType.Byref (instILTypeAux numFree inst t) + | ILType.Boxed cr -> mkILBoxedType (instILTypeSpecAux numFree inst cr) + | ILType.Value cr -> ILType.Value (instILTypeSpecAux numFree inst cr) + | ILType.TypeVar v -> let v = int v let top = inst.Length if v < numFree then ty else @@ -2836,10 +2835,10 @@ and instILTypeAux numFree (inst: ILGenericArgs) ty = and instILGenericArgsAux numFree inst i = List.map (instILTypeAux numFree inst) i -and instILCallSigAux numFree inst csig = - mkILCallSig (csig.CallingConv, List.map (instILTypeAux numFree inst) csig.ArgTypes, instILTypeAux numFree inst csig.ReturnType) +and instILCallSigAux numFree inst csig = + mkILCallSig (csig.CallingConv, List.map (instILTypeAux numFree inst) csig.ArgTypes, instILTypeAux numFree inst csig.ReturnType) -let instILType i t = instILTypeAux 0 i t +let instILType i t = instILTypeAux 0 i t // -------------------------------------------------------------------- // MS-IL: Parameters, Return types and Locals @@ -2854,7 +2853,7 @@ let mkILParam (name, ty) : ILParameter = IsOptional=false Type=ty CustomAttrsStored=storeILCustomAttrs emptyILCustomAttrs - MetadataIndex = NoMetadataIdx } + MetadataIndex = NoMetadataIdx } let mkILParamNamed (s, ty) = mkILParam (Some s, ty) @@ -3022,14 +3021,14 @@ let mkILNonGenericInstanceMethod (nm, access, args, ret, impl) = // -------------------------------------------------------------------- -// Add some code to the end of the .cctor for a type. Create a .cctor +// Add some code to the end of the .cctor for a type. Create a .cctor // if one doesn't exist already. // -------------------------------------------------------------------- -let ilmbody_code2code f (il: ILMethodBody) = +let ilmbody_code2code f (il: ILMethodBody) = {il with Code = f il.Code} -let mdef_code2code f (md: ILMethodDef) = +let mdef_code2code f (md: ILMethodDef) = let il = match md.Body.Contents with | MethodBody.IL il-> il @@ -3057,7 +3056,7 @@ let prependInstrsToCode (instrs: ILInstr list) (c2: ILCode) = { c2 with Labels = labels Instrs = Array.append instrs c2.Instrs } -let prependInstrsToMethod new_code md = +let prependInstrsToMethod new_code md = mdef_code2code (prependInstrsToCode new_code) md // Creates cctor if needed @@ -3081,7 +3080,7 @@ 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) @@ -3126,29 +3125,29 @@ 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) +let mkILFields l = mkILFieldsLazy (notlazy l) let emptyILFields = mkILFields [] -let mkILEventsLazy l = ILEvents (LazyOrderedMultiMap((fun (e: ILEventDef) -> e.Name), l)) +let mkILEventsLazy l = ILEvents (LazyOrderedMultiMap((fun (e: ILEventDef) -> e.Name), l)) -let mkILEvents l = mkILEventsLazy (notlazy l) +let mkILEvents l = mkILEventsLazy (notlazy l) -let emptyILEvents = mkILEvents [] +let emptyILEvents = mkILEvents [] -let mkILPropertiesLazy l = ILProperties (LazyOrderedMultiMap((fun (p: ILPropertyDef) -> p.Name), l) ) +let mkILPropertiesLazy l = ILProperties (LazyOrderedMultiMap((fun (p: ILPropertyDef) -> p.Name), l) ) -let mkILProperties l = mkILPropertiesLazy (notlazy l) +let mkILProperties l = mkILPropertiesLazy (notlazy l) -let emptyILProperties = mkILProperties [] +let emptyILProperties = mkILProperties [] let addExportedTypeToTable (y: ILExportedTypeOrForwarder) tab = Map.add y.Name y tab -let mkILExportedTypes l = ILExportedTypesAndForwarders (notlazy (List.foldBack addExportedTypeToTable l Map.empty)) +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 @@ -3167,21 +3166,21 @@ let mkILNestedExportedTypes l = let mkILNestedExportedTypesLazy (l: Lazy<_>) = ILNestedExportedTypes (lazy (List.foldBack addNestedExportedTypeToTable (l.Force()) Map.empty)) -let mkILResources l = ILResources l +let mkILResources l = ILResources l let addMethodImplToTable y tab = let key = (y.Overrides.MethodRef.Name, y.Overrides.MethodRef.ArgTypes.Length) let prev = Map.tryFindMulti key tab Map.add key (y::prev) tab -let mkILMethodImpls l = ILMethodImpls (notlazy (List.foldBack addMethodImplToTable l Map.empty)) +let mkILMethodImpls l = ILMethodImpls (notlazy (List.foldBack addMethodImplToTable l Map.empty)) -let mkILMethodImplsLazy l = ILMethodImpls (lazy (List.foldBack addMethodImplToTable (Lazy.force l) Map.empty)) +let mkILMethodImplsLazy l = ILMethodImpls (lazy (List.foldBack addMethodImplToTable (Lazy.force l) Map.empty)) -let emptyILMethodImpls = mkILMethodImpls [] +let emptyILMethodImpls = mkILMethodImpls [] /// Make a constructor that simply takes its arguments and stuffs -/// them in fields. preblock is how to call the superclass constructor.... +/// them in fields. preblock is how to call the superclass constructor.... let mkILStorageCtorWithParamNames(tag, preblock, ty, extraParams, flds, access) = mkILCtor(access, (flds |> List.map (fun (pnm, _, ty) -> mkILParamNamed (pnm, ty))) @ extraParams, @@ -3195,7 +3194,7 @@ let mkILStorageCtorWithParamNames(tag, preblock, ty, extraParams, flds, access) [ mkLdarg0 mkLdarg (uint16 (n+1)) mkNormalStfld (mkILFieldSpecInTy (ty, nm, fieldTy)) - ]) flds) + ]) flds) end, tag)) let mkILSimpleStorageCtorWithParamNames(tag, baseTySpec, ty, extraParams, flds, access) = @@ -3223,7 +3222,7 @@ let mkILGenericClass (nm, access, genparams, extends, impl, methods, fields, nes implements = impl, layout=ILTypeDefLayout.Auto, extends = Some extends, - methods= methods , + methods= methods, fields= fields, nestedTypes=nestedTypes, customAttrs=attrs, @@ -3305,7 +3304,7 @@ let mkILSimpleModule assemblyName modname dll subsystemVersion useHighEntropyVA //----------------------------------------------------------------------- // [instructions_to_code] makes the basic block structure of code from -// a primitive array of instructions. We +// a primitive array of instructions. We // do this be iterating over the instructions, pushing new basic blocks // everytime we encounter an address that has been recorded // [bbstartToCodeLabelMap]. @@ -3355,12 +3354,12 @@ let computeILEnumInfo (mdName, mdFields: ILFieldDefs) = 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"))) } + enumValues = staticFields |> List.map (fun fd -> (fd.Name, match fd.LiteralValue with Some i -> i | None -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": static field does not have an default value"))) } | _, [] -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": no non-static field found") | _, _ -> failwith ("info_of_enum_tdef: badly formed enum "+mdName+": more than one non-static field found") //--------------------------------------------------------------------- -// Primitives to help read signatures. These do not use the file cursor, but +// Primitives to help read signatures. These do not use the file cursor, but // pass around an int index //--------------------------------------------------------------------- @@ -3369,7 +3368,7 @@ let sigptr_get_byte bytes sigptr = let sigptr_get_bool bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr - (b0 = 0x01) , sigptr + (b0 = 0x01), sigptr let sigptr_get_u8 bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr @@ -3436,7 +3435,7 @@ let sigptr_get_intarray n (bytes: byte[]) sigptr = let sigptr_get_string n bytes sigptr = let intarray, sigptr = sigptr_get_intarray n bytes sigptr - System.Text.Encoding.UTF8.GetString(intarray , 0, intarray.Length), sigptr + System.Text.Encoding.UTF8.GetString(intarray, 0, intarray.Length), sigptr let sigptr_get_z_i32 bytes sigptr = let b0, sigptr = sigptr_get_byte bytes sigptr @@ -3452,15 +3451,15 @@ let sigptr_get_z_i32 bytes sigptr = let b3, sigptr = sigptr_get_byte bytes sigptr (b0 <<< 24) ||| (b1 <<< 16) ||| (b2 <<< 8) ||| b3, sigptr -let sigptr_get_serstring bytes sigptr = +let sigptr_get_serstring bytes sigptr = let len, sigptr = sigptr_get_z_i32 bytes sigptr sigptr_get_string ( len) bytes sigptr -let sigptr_get_serstring_possibly_null bytes sigptr = +let sigptr_get_serstring_possibly_null bytes sigptr = let b0, new_sigptr = sigptr_get_byte bytes sigptr if b0 = 0xFF then // null case None, new_sigptr - else // throw away new_sigptr, getting length & text advance + else // throw away new_sigptr, getting length & text advance let len, sigptr = sigptr_get_z_i32 bytes sigptr let s, sigptr = sigptr_get_string len bytes sigptr Some(s), sigptr @@ -3478,7 +3477,7 @@ let z_unsigned_int_size n = else 3 let z_unsigned_int n = - if n >= 0 && n <= 0x7F then [| byte n |] + if n >= 0 && n <= 0x7F then [| byte n |] elif n >= 0x80 && n <= 0x3FFF then [| byte (0x80 ||| (n >>>& 8)); byte (n &&& 0xFF) |] else [| byte (0xc0 ||| (n >>>& 24)) byte ((n >>>& 16) &&& 0xFF) @@ -3500,13 +3499,13 @@ let dw3 n = byte ((n >>> 24) &&& 0xFFL) let dw2 n = byte ((n >>> 16) &&& 0xFFL) -let dw1 n = byte ((n >>> 8) &&& 0xFFL) +let dw1 n = byte ((n >>> 8) &&& 0xFFL) -let dw0 n = byte (n &&& 0xFFL) +let dw0 n = byte (n &&& 0xFFL) let u8AsBytes (i: byte) = [| i |] -let u16AsBytes x = let n = (int x) in [| byte (b0 n); byte (b1 n) |] +let u16AsBytes x = let n = (int x) in [| byte (b0 n); byte (b1 n) |] let i32AsBytes i = [| byte (b0 i); byte (b1 i); byte (b2 i); byte (b3 i) |] @@ -3545,20 +3544,20 @@ let et_R8 = 0x0Duy let et_STRING = 0x0Euy let et_PTR = 0x0Fuy let et_BYREF = 0x10uy -let et_VALUETYPE = 0x11uy -let et_CLASS = 0x12uy -let et_VAR = 0x13uy -let et_ARRAY = 0x14uy -let et_WITH = 0x15uy -let et_TYPEDBYREF = 0x16uy -let et_I = 0x18uy -let et_U = 0x19uy -let et_FNPTR = 0x1Buy -let et_OBJECT = 0x1Cuy -let et_SZARRAY = 0x1Duy -let et_MVAR = 0x1Euy -let et_CMOD_REQD = 0x1Fuy -let et_CMOD_OPT = 0x20uy +let et_VALUETYPE = 0x11uy +let et_CLASS = 0x12uy +let et_VAR = 0x13uy +let et_ARRAY = 0x14uy +let et_WITH = 0x15uy +let et_TYPEDBYREF = 0x16uy +let et_I = 0x18uy +let et_U = 0x19uy +let et_FNPTR = 0x1Buy +let et_OBJECT = 0x1Cuy +let et_SZARRAY = 0x1Duy +let et_MVAR = 0x1Euy +let et_CMOD_REQD = 0x1Fuy +let et_CMOD_OPT = 0x20uy let formatILVersion ((a, b, c, d):ILVersionInfo) = sprintf "%d.%d.%d.%d" (int a) (int b) (int c) (int d) @@ -3568,69 +3567,69 @@ let encodeCustomAttrString s = let rec encodeCustomAttrElemType x = match x with - | ILType.Value tspec when tspec.Name = tname_SByte -> [| et_I1 |] - | ILType.Value tspec when tspec.Name = tname_Byte -> [| et_U1 |] - | ILType.Value tspec when tspec.Name = tname_Int16 -> [| et_I2 |] - | ILType.Value tspec when tspec.Name = tname_UInt16 -> [| et_U2 |] - | ILType.Value tspec when tspec.Name = tname_Int32 -> [| et_I4 |] - | ILType.Value tspec when tspec.Name = tname_UInt32 -> [| et_U4 |] - | ILType.Value tspec when tspec.Name = tname_Int64 -> [| et_I8 |] - | ILType.Value tspec when tspec.Name = tname_UInt64 -> [| et_U8 |] - | ILType.Value tspec when tspec.Name = tname_Double -> [| et_R8 |] - | ILType.Value tspec when tspec.Name = tname_Single -> [| et_R4 |] - | ILType.Value tspec when tspec.Name = tname_Char -> [| et_CHAR |] - | ILType.Value tspec when tspec.Name = tname_Bool -> [| et_BOOLEAN |] - | ILType.Boxed tspec when tspec.Name = tname_String -> [| et_STRING |] - | ILType.Boxed tspec when tspec.Name = tname_Object -> [| 0x51uy |] - | ILType.Boxed tspec when tspec.Name = tname_Type -> [| 0x50uy |] - | ILType.Value tspec -> Array.append [| 0x55uy |] (encodeCustomAttrString tspec.TypeRef.QualifiedName) + | ILType.Value tspec when tspec.Name = tname_SByte -> [| et_I1 |] + | ILType.Value tspec when tspec.Name = tname_Byte -> [| et_U1 |] + | ILType.Value tspec when tspec.Name = tname_Int16 -> [| et_I2 |] + | ILType.Value tspec when tspec.Name = tname_UInt16 -> [| et_U2 |] + | ILType.Value tspec when tspec.Name = tname_Int32 -> [| et_I4 |] + | ILType.Value tspec when tspec.Name = tname_UInt32 -> [| et_U4 |] + | ILType.Value tspec when tspec.Name = tname_Int64 -> [| et_I8 |] + | ILType.Value tspec when tspec.Name = tname_UInt64 -> [| et_U8 |] + | ILType.Value tspec when tspec.Name = tname_Double -> [| et_R8 |] + | ILType.Value tspec when tspec.Name = tname_Single -> [| et_R4 |] + | ILType.Value tspec when tspec.Name = tname_Char -> [| et_CHAR |] + | ILType.Value tspec when tspec.Name = tname_Bool -> [| et_BOOLEAN |] + | ILType.Boxed tspec when tspec.Name = tname_String -> [| et_STRING |] + | ILType.Boxed tspec when tspec.Name = tname_Object -> [| 0x51uy |] + | ILType.Boxed tspec when tspec.Name = tname_Type -> [| 0x50uy |] + | ILType.Value tspec -> Array.append [| 0x55uy |] (encodeCustomAttrString tspec.TypeRef.QualifiedName) | ILType.Array (shape, elemType) when shape = ILArrayShape.SingleDimensional -> Array.append [| et_SZARRAY |] (encodeCustomAttrElemType elemType) - | _ -> failwith "encodeCustomAttrElemType: unrecognized custom element type" + | _ -> failwith "encodeCustomAttrElemType: unrecognized custom element type" /// Given a custom attribute element, work out the type of the .NET argument for that element. let rec encodeCustomAttrElemTypeForObject x = match x with - | ILAttribElem.String _ -> [| et_STRING |] - | ILAttribElem.Bool _ -> [| et_BOOLEAN |] - | ILAttribElem.Char _ -> [| et_CHAR |] - | ILAttribElem.SByte _ -> [| et_I1 |] - | ILAttribElem.Int16 _ -> [| et_I2 |] - | ILAttribElem.Int32 _ -> [| et_I4 |] - | ILAttribElem.Int64 _ -> [| et_I8 |] - | ILAttribElem.Byte _ -> [| et_U1 |] - | ILAttribElem.UInt16 _ -> [| et_U2 |] - | ILAttribElem.UInt32 _ -> [| et_U4 |] - | ILAttribElem.UInt64 _ -> [| et_U8 |] - | ILAttribElem.Type _ -> [| 0x50uy |] + | ILAttribElem.String _ -> [| et_STRING |] + | ILAttribElem.Bool _ -> [| et_BOOLEAN |] + | ILAttribElem.Char _ -> [| et_CHAR |] + | ILAttribElem.SByte _ -> [| et_I1 |] + | ILAttribElem.Int16 _ -> [| et_I2 |] + | ILAttribElem.Int32 _ -> [| et_I4 |] + | ILAttribElem.Int64 _ -> [| et_I8 |] + | ILAttribElem.Byte _ -> [| et_U1 |] + | ILAttribElem.UInt16 _ -> [| et_U2 |] + | ILAttribElem.UInt32 _ -> [| et_U4 |] + | ILAttribElem.UInt64 _ -> [| et_U8 |] + | ILAttribElem.Type _ -> [| 0x50uy |] | ILAttribElem.TypeRef _ -> [| 0x50uy |] - | ILAttribElem.Null _ -> [| et_STRING |]// yes, the 0xe prefix is used when passing a "null" to a property or argument of type "object" here - | ILAttribElem.Single _ -> [| et_R4 |] - | ILAttribElem.Double _ -> [| et_R8 |] + | ILAttribElem.Null _ -> [| et_STRING |]// yes, the 0xe prefix is used when passing a "null" to a property or argument of type "object" here + | ILAttribElem.Single _ -> [| et_R4 |] + | ILAttribElem.Double _ -> [| et_R8 |] | ILAttribElem.Array (elemTy, _) -> [| yield et_SZARRAY; yield! encodeCustomAttrElemType elemTy |] let rec decodeCustomAttrElemType (ilg: ILGlobals) bytes sigptr x = match x with - | x when x = et_I1 -> ilg.typ_SByte, sigptr + | x when x = et_I1 -> ilg.typ_SByte, sigptr | x when x = et_U1 -> ilg.typ_Byte, sigptr - | x when x = et_I2 -> ilg.typ_Int16, sigptr - | x when x = et_U2 -> ilg.typ_UInt16, sigptr - | x when x = et_I4 -> ilg.typ_Int32, sigptr - | x when x = et_U4 -> ilg.typ_UInt32, sigptr - | x when x = et_I8 -> ilg.typ_Int64, sigptr - | x when x = et_U8 -> ilg.typ_UInt64, sigptr - | x when x = et_R8 -> ilg.typ_Double, sigptr - | x when x = et_R4 -> ilg.typ_Single, sigptr + | x when x = et_I2 -> ilg.typ_Int16, sigptr + | x when x = et_U2 -> ilg.typ_UInt16, sigptr + | x when x = et_I4 -> ilg.typ_Int32, sigptr + | x when x = et_U4 -> ilg.typ_UInt32, sigptr + | x when x = et_I8 -> ilg.typ_Int64, sigptr + | x when x = et_U8 -> ilg.typ_UInt64, sigptr + | x when x = et_R8 -> ilg.typ_Double, sigptr + | x when x = et_R4 -> ilg.typ_Single, sigptr | x when x = et_CHAR -> ilg.typ_Char, sigptr - | x when x = et_BOOLEAN -> ilg.typ_Bool, sigptr - | x when x = et_STRING -> ilg.typ_String, sigptr - | x when x = et_OBJECT -> ilg.typ_Object, sigptr - | x when x = et_SZARRAY -> + | x when x = et_BOOLEAN -> ilg.typ_Bool, sigptr + | x when x = et_STRING -> ilg.typ_String, sigptr + | x when x = et_OBJECT -> ilg.typ_Object, sigptr + | x when x = et_SZARRAY -> let et, sigptr = sigptr_get_u8 bytes sigptr let elemTy, sigptr = decodeCustomAttrElemType ilg bytes sigptr et mkILArr1DTy elemTy, sigptr | x when x = 0x50uy -> ilg.typ_Type, sigptr - | _ -> failwithf "decodeCustomAttrElemType ilg: unrecognized custom element type: %A" x + | _ -> failwithf "decodeCustomAttrElemType ilg: unrecognized custom element type: %A" x /// Given a custom attribute element, encode it to a binary representation according to the rules in Ecma 335 Partition II. @@ -3642,7 +3641,7 @@ let rec encodeCustomAttrPrimValue ilg c = | ILAttribElem.TypeRef None | ILAttribElem.Null -> [| 0xFFuy |] | ILAttribElem.String (Some s) -> encodeCustomAttrString s - | ILAttribElem.Char x -> u16AsBytes (uint16 x) + | ILAttribElem.Char x -> u16AsBytes (uint16 x) | ILAttribElem.SByte x -> i8AsBytes x | ILAttribElem.Int16 x -> i16AsBytes x | ILAttribElem.Int32 x -> i32AsBytes x @@ -3754,7 +3753,7 @@ type ILTypeSigParser(tstring : string) = s // The format we accept is - // "{`[, +]}{}{}" E.g., + // "{`[, +]}{}{}" E.g., // // System.Collections.Generic.Dictionary // `2[ @@ -3768,7 +3767,7 @@ type ILTypeSigParser(tstring : string) = // Still needs testing with jagged arrays and byref parameters member private x.ParseType() = - // Does the type name start with a leading '['? If so, ignore it + // Does the type name start with a leading '['? If so, ignore it // (if the specialization type is in another module, it will be wrapped in bracket) if here() = '[' then drop() @@ -3829,7 +3828,7 @@ type ILTypeSigParser(tstring : string) = ILScopeRef.Local // strip any extraneous trailing brackets or commas - if (here() = ']') then drop() + if (here() = ']') then drop() if (here() = ',') then drop() // build the IL type @@ -3942,10 +3941,10 @@ let decodeILAttribData (ilg: ILGlobals) (ca: ILAttribute) = parseElems (v ::acc) (n-1) sigptr let elems, sigptr = parseElems [] n sigptr ILAttribElem.Array(elemTy, elems), sigptr - | ILType.Value _ -> (* assume it is an enumeration *) + | ILType.Value _ -> (* assume it is an enumeration *) let n, sigptr = sigptr_get_i32 bytes sigptr ILAttribElem.Int32 n, sigptr - | _ -> failwith "decodeILAttribData: attribute data involves an enum or System.Type value" + | _ -> failwith "decodeILAttribData: attribute data involves an enum or System.Type value" let rec parseFixed argtys sigptr = match argtys with [] -> [], sigptr @@ -3989,7 +3988,7 @@ let decodeILAttribData (ilg: ILGlobals) (ca: ILAttribute) = // -------------------------------------------------------------------- // Functions to collect up all the references in a full module or -// assembly manifest. The process also allocates +// assembly manifest. The process also allocates // a unique name to each unique internal assembly reference. // -------------------------------------------------------------------- @@ -4007,6 +4006,7 @@ let emptyILRefs = (* 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_scoref s x = @@ -4019,7 +4019,7 @@ let refs_of_tref s (x: ILTypeRef) = refs_of_scoref s x.Scope let rec refs_of_typ s x = match x with - | ILType.Void | ILType.TypeVar _ -> () + | ILType.Void | ILType.TypeVar _ -> () | ILType.Modified(_, ty1, ty2) -> refs_of_tref s ty1; refs_of_typ s ty2 | ILType.Array (_, ty) | ILType.Ptr ty | ILType.Byref ty -> refs_of_typ s ty @@ -4027,9 +4027,13 @@ 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_callsig s csig = refs_of_tys s csig.ArgTypes; refs_of_typ s csig.ReturnType + +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 @@ -4040,7 +4044,9 @@ and refs_of_mref s (x: ILMethodRef) = refs_of_typ s x.mrefReturn and refs_of_fref s x = refs_of_tref s x.DeclaringTypeRef; refs_of_typ s x.Type + and refs_of_ospec s (OverridesSpec(mref, ty)) = refs_of_mref s mref; refs_of_typ s ty + and refs_of_mspec s (x: ILMethodSpec) = refs_of_mref s x.MethodRef refs_of_typ s x.DeclaringType @@ -4061,7 +4067,9 @@ and refs_of_token s x = and refs_of_custom_attr s (cattr: ILAttribute) = refs_of_mspec s cattr.Method and refs_of_custom_attrs s (cas : ILAttributes) = Array.iter (refs_of_custom_attr s) cas.AsArray + and refs_of_varargs s tyso = Option.iter (refs_of_tys s) tyso + and refs_of_instr s x = match x with | I_call (_, mr, varargs) | I_newobj (mr, varargs) | I_callvirt (_, mr, varargs) -> @@ -4072,7 +4080,7 @@ and refs_of_instr s x = refs_of_mspec s mr refs_of_varargs s varargs | I_calli (_, callsig, varargs) -> - refs_of_callsig s callsig; refs_of_varargs s varargs + refs_of_callsig s callsig; refs_of_varargs s varargs | I_jmp mr | I_ldftn mr | I_ldvirtftn mr -> refs_of_mspec s mr | I_ldsfld (_, fr) | I_ldfld (_, _, fr) | I_ldsflda fr | I_ldflda fr | I_stsfld (_, fr) | I_stfld (_, _, fr) -> @@ -4081,7 +4089,7 @@ and refs_of_instr s x = | I_stobj (_, _, ty) | I_box ty |I_unbox ty | I_unbox_any ty | I_sizeof ty | I_ldelem_any (_, ty) | I_ldelema (_, _, _, ty) |I_stelem_any (_, ty) | I_newarr (_, ty) | I_mkrefany ty | I_refanyval ty - | EI_ilzero ty -> refs_of_typ s ty + | EI_ilzero ty -> refs_of_typ s ty | I_ldtoken token -> refs_of_token s token | I_stelem _|I_ldelem _|I_ldstr _|I_switch _|I_stloc _|I_stind _ | I_starg _|I_ldloca _|I_ldloc _|I_ldind _ @@ -4089,13 +4097,13 @@ and refs_of_instr s x = | I_brcmp _|I_rethrow|I_refanytype|I_ldlen|I_throw|I_initblk _ |I_cpblk _ | I_localloc|I_ret |I_endfilter|I_endfinally|I_arglist | I_break - | AI_add | AI_add_ovf | AI_add_ovf_un | AI_and | AI_div | AI_div_un | AI_ceq | AI_cgt | AI_cgt_un | AI_clt - | AI_clt_un | AI_conv _ | AI_conv_ovf _ | AI_conv_ovf_un _ | AI_mul | AI_mul_ovf | AI_mul_ovf_un | AI_rem | AI_rem_un - | AI_shl | AI_shr | AI_shr_un | AI_sub | AI_sub_ovf | AI_sub_ovf_un | AI_xor | AI_or | AI_neg | AI_not - | AI_ldnull | AI_dup | AI_pop | AI_ckfinite | AI_nop | AI_ldc _ - | I_seqpoint _ | EI_ldlen_multi _ -> () + | AI_add | AI_add_ovf | AI_add_ovf_un | AI_and | AI_div | AI_div_un | AI_ceq | AI_cgt | AI_cgt_un | AI_clt + | AI_clt_un | AI_conv _ | AI_conv_ovf _ | AI_conv_ovf_un _ | AI_mul | AI_mul_ovf | AI_mul_ovf_un | AI_rem | AI_rem_un + | AI_shl | AI_shr | AI_shr_un | AI_sub | AI_sub_ovf | AI_sub_ovf_un | AI_xor | AI_or | AI_neg | AI_not + | AI_ldnull | AI_dup | AI_pop | AI_ckfinite | AI_nop | AI_ldc _ + | I_seqpoint _ | EI_ldlen_multi _ -> () -and refs_of_il_code s (c: ILCode) = +and refs_of_il_code s (c: ILCode) = c.Instrs |> Array.iter (refs_of_instr s) c.Exceptions |> List.iter (fun e -> e.Clause |> (function | ILExceptionClause.TypeCatch (ilty, _) -> refs_of_typ s ilty @@ -4116,29 +4124,29 @@ and refs_of_mbody s x = and refs_of_mdef s (md: ILMethodDef) = List.iter (refs_of_param s) md.Parameters refs_of_return s md.Return - refs_of_mbody s md.Body.Contents - refs_of_custom_attrs s md.CustomAttrs - refs_of_genparams s md.GenericParams + refs_of_mbody s md.Body.Contents + refs_of_custom_attrs s md.CustomAttrs + refs_of_genparams s md.GenericParams and refs_of_param s p = refs_of_typ s p.Type and refs_of_return s (rt: ILReturn) = refs_of_typ s rt.Type -and refs_of_mdefs s x = Seq.iter (refs_of_mdef s) x +and refs_of_mdefs s x = Seq.iter (refs_of_mdef s) x and refs_of_event_def s (ed: ILEventDef) = - Option.iter (refs_of_typ s) ed.EventType + Option.iter (refs_of_typ s) ed.EventType refs_of_mref s ed.AddMethod refs_of_mref s ed.RemoveMethod Option.iter (refs_of_mref s) ed.FireMethod List.iter (refs_of_mref s) ed.OtherMethods refs_of_custom_attrs s ed.CustomAttrs -and refs_of_events s (x: ILEventDefs) = List.iter (refs_of_event_def s) x.AsList +and refs_of_events s (x: ILEventDefs) = List.iter (refs_of_event_def s) x.AsList and refs_of_property_def s (pd: ILPropertyDef) = - Option.iter (refs_of_mref s) pd.SetMethod - Option.iter (refs_of_mref s) pd.GetMethod + Option.iter (refs_of_mref s) pd.SetMethod + Option.iter (refs_of_mref s) pd.GetMethod refs_of_typ s pd.PropertyType refs_of_tys s pd.Args refs_of_custom_attrs s pd.CustomAttrs @@ -4146,35 +4154,35 @@ and refs_of_property_def s (pd: ILPropertyDef) = and refs_of_properties s (x: ILPropertyDefs) = List.iter (refs_of_property_def s) x.AsList and refs_of_fdef s (fd: ILFieldDef) = - refs_of_typ s fd.FieldType - refs_of_custom_attrs s fd.CustomAttrs + refs_of_typ s fd.FieldType + refs_of_custom_attrs s fd.CustomAttrs and refs_of_fields s fields = List.iter (refs_of_fdef s) fields -and refs_of_method_impls s mimpls = List.iter (refs_of_method_impl s) mimpls +and refs_of_method_impls s mimpls = List.iter (refs_of_method_impl s) mimpls and refs_of_method_impl s m = refs_of_ospec s m.Overrides refs_of_mspec s m.OverrideBy -and refs_of_tdef_kind _s _k = () +and refs_of_tdef_kind _s _k = () -and refs_of_tdef s (td : ILTypeDef) = +and refs_of_tdef s (td : ILTypeDef) = refs_of_types s td.NestedTypes - refs_of_genparams s td.GenericParams - refs_of_tys s td.Implements + refs_of_genparams s td.GenericParams + refs_of_tys s td.Implements Option.iter (refs_of_typ s) td.Extends - refs_of_mdefs s td.Methods - refs_of_fields s td.Fields.AsList + refs_of_mdefs s td.Methods + refs_of_fields s td.Fields.AsList refs_of_method_impls s td.MethodImpls.AsList - refs_of_events s td.Events - refs_of_tdef_kind s td + refs_of_events s td.Events + refs_of_tdef_kind s td refs_of_custom_attrs s td.CustomAttrs - refs_of_properties s td.Properties + refs_of_properties s td.Properties and refs_of_string _s _ = () -and refs_of_types s (types: ILTypeDefs) = Seq.iter (refs_of_tdef s) types +and refs_of_types s (types: ILTypeDefs) = Seq.iter (refs_of_tdef s) types and refs_of_exported_type s (c: ILExportedTypeOrForwarder) = refs_of_custom_attrs s c.CustomAttrs @@ -4210,7 +4218,7 @@ let computeILRefs modul = refs_of_modul s modul { AssemblyReferences = Seq.fold (fun acc x -> x::acc) [] s.refsA - ModuleReferences = Seq.fold (fun acc x -> x::acc) [] s.refsM } + ModuleReferences = Seq.fold (fun acc x -> x::acc) [] s.refsM } let tspan = System.TimeSpan(System.DateTime.UtcNow.Ticks - System.DateTime(2000, 1, 1).Ticks) @@ -4292,12 +4300,12 @@ let resolveILMethodRefWithRescope r (td: ILTypeDef) (mref: ILMethodRef) = match possibles |> List.filter (fun md -> mref.CallingConv = md.CallingConv && - // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct - (md.Parameters, argTypes) ||> List.lengthsEqAndForall2 (fun p1 p2 -> r p1.Type = p2) && - // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct - r md.Return.Type = retType) with + // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct + (md.Parameters, argTypes) ||> List.lengthsEqAndForall2 (fun p1 p2 -> r p1.Type = p2) && + // REVIEW: this uses equality on ILType. For CMOD_OPTIONAL this is not going to be correct + r md.Return.Type = retType) with | [] -> failwith ("no method named "+nm+" with appropriate argument types found in type "+td.Name) - | [mdef] -> mdef + | [mdef] -> mdef | _ -> failwith ("multiple methods named "+nm+" appear with identical argument types in type "+td.Name) let resolveILMethodRef td mref = resolveILMethodRefWithRescope id td mref diff --git a/src/absil/ilbinary.fs b/src/absil/ilbinary.fs index 41297d117ef..2b22b4cbabb 100644 --- a/src/absil/ilbinary.fs +++ b/src/absil/ilbinary.fs @@ -508,155 +508,155 @@ let i_leave = 0xdd let i_leave_s = 0xde let i_stind_i = 0xdf let i_conv_u = 0xe0 -let i_arglist = 0xfe00 -let i_ceq = 0xfe01 -let i_cgt = 0xfe02 +let i_arglist = 0xfe00 +let i_ceq = 0xfe01 +let i_cgt = 0xfe02 let i_cgt_un = 0xfe03 -let i_clt = 0xfe04 +let i_clt = 0xfe04 let i_clt_un = 0xfe05 -let i_ldftn = 0xfe06 -let i_ldvirtftn = 0xfe07 -let i_ldarg = 0xfe09 -let i_ldarga = 0xfe0a -let i_starg = 0xfe0b -let i_ldloc = 0xfe0c -let i_ldloca = 0xfe0d -let i_stloc = 0xfe0e -let i_localloc = 0xfe0f -let i_endfilter = 0xfe11 -let i_unaligned = 0xfe12 -let i_volatile = 0xfe13 -let i_constrained = 0xfe16 -let i_readonly = 0xfe1e -let i_tail = 0xfe14 -let i_initobj = 0xfe15 -let i_cpblk = 0xfe17 -let i_initblk = 0xfe18 -let i_rethrow = 0xfe1a -let i_sizeof = 0xfe1c -let i_refanytype = 0xfe1d - -let i_ldelem_any = 0xa3 -let i_stelem_any = 0xa4 -let i_unbox_any = 0xa5 +let i_ldftn = 0xfe06 +let i_ldvirtftn = 0xfe07 +let i_ldarg = 0xfe09 +let i_ldarga = 0xfe0a +let i_starg = 0xfe0b +let i_ldloc = 0xfe0c +let i_ldloca = 0xfe0d +let i_stloc = 0xfe0e +let i_localloc = 0xfe0f +let i_endfilter = 0xfe11 +let i_unaligned = 0xfe12 +let i_volatile = 0xfe13 +let i_constrained = 0xfe16 +let i_readonly = 0xfe1e +let i_tail = 0xfe14 +let i_initobj = 0xfe15 +let i_cpblk = 0xfe17 +let i_initblk = 0xfe18 +let i_rethrow = 0xfe1a +let i_sizeof = 0xfe1c +let i_refanytype = 0xfe1d +let i_ldelem_any = 0xa3 +let i_stelem_any = 0xa4 +let i_unbox_any = 0xa5 let mk_ldc i = mkLdcInt32 i + let noArgInstrs = - lazy [ i_ldc_i4_0, mk_ldc 0 - i_ldc_i4_1, mk_ldc 1 - i_ldc_i4_2, mk_ldc 2 - i_ldc_i4_3, mk_ldc 3 - i_ldc_i4_4, mk_ldc 4 - i_ldc_i4_5, mk_ldc 5 - i_ldc_i4_6, mk_ldc 6 - i_ldc_i4_7, mk_ldc 7 - i_ldc_i4_8, mk_ldc 8 - i_ldc_i4_m1, mk_ldc -1 - 0x0a, mkStloc 0us - 0x0b, mkStloc 1us - 0x0c, mkStloc 2us - 0x0d, mkStloc 3us - 0x06, mkLdloc 0us - 0x07, mkLdloc 1us - 0x08, mkLdloc 2us - 0x09, mkLdloc 3us - 0x02, mkLdarg 0us - 0x03, mkLdarg 1us - 0x04, mkLdarg 2us - 0x05, mkLdarg 3us - 0x2a, I_ret - 0x58, AI_add - 0xd6, AI_add_ovf - 0xd7, AI_add_ovf_un - 0x5f, AI_and - 0x5b, AI_div - 0x5c, AI_div_un - 0xfe01, AI_ceq - 0xfe02, AI_cgt - 0xfe03, AI_cgt_un - 0xfe04, AI_clt - 0xfe05, AI_clt_un - 0x67, AI_conv DT_I1 - 0x68, AI_conv DT_I2 - 0x69, AI_conv DT_I4 - 0x6a, AI_conv DT_I8 - 0xd3, AI_conv DT_I - 0x6b, AI_conv DT_R4 - 0x6c, AI_conv DT_R8 - 0xd2, AI_conv DT_U1 - 0xd1, AI_conv DT_U2 - 0x6d, AI_conv DT_U4 - 0x6e, AI_conv DT_U8 - 0xe0, AI_conv DT_U - 0x76, AI_conv DT_R - 0xb3, AI_conv_ovf DT_I1 - 0xb5, AI_conv_ovf DT_I2 - 0xb7, AI_conv_ovf DT_I4 - 0xb9, AI_conv_ovf DT_I8 - 0xd4, AI_conv_ovf DT_I - 0xb4, AI_conv_ovf DT_U1 - 0xb6, AI_conv_ovf DT_U2 - 0xb8, AI_conv_ovf DT_U4 - 0xba, AI_conv_ovf DT_U8 - 0xd5, AI_conv_ovf DT_U - 0x82, AI_conv_ovf_un DT_I1 - 0x83, AI_conv_ovf_un DT_I2 - 0x84, AI_conv_ovf_un DT_I4 - 0x85, AI_conv_ovf_un DT_I8 - 0x8a, AI_conv_ovf_un DT_I - 0x86, AI_conv_ovf_un DT_U1 - 0x87, AI_conv_ovf_un DT_U2 - 0x88, AI_conv_ovf_un DT_U4 - 0x89, AI_conv_ovf_un DT_U8 - 0x8b, AI_conv_ovf_un DT_U - 0x9c, I_stelem DT_I1 - 0x9d, I_stelem DT_I2 - 0x9e, I_stelem DT_I4 - 0x9f, I_stelem DT_I8 - 0xa0, I_stelem DT_R4 - 0xa1, I_stelem DT_R8 - 0x9b, I_stelem DT_I - 0xa2, I_stelem DT_REF - 0x90, I_ldelem DT_I1 - 0x92, I_ldelem DT_I2 - 0x94, I_ldelem DT_I4 - 0x96, I_ldelem DT_I8 - 0x91, I_ldelem DT_U1 - 0x93, I_ldelem DT_U2 - 0x95, I_ldelem DT_U4 - 0x98, I_ldelem DT_R4 - 0x99, I_ldelem DT_R8 - 0x97, I_ldelem DT_I - 0x9a, I_ldelem DT_REF - 0x5a, AI_mul - 0xd8, AI_mul_ovf - 0xd9, AI_mul_ovf_un - 0x5d, AI_rem - 0x5e, AI_rem_un - 0x62, AI_shl - 0x63, AI_shr - 0x64, AI_shr_un - 0x59, AI_sub - 0xda, AI_sub_ovf - 0xdb, AI_sub_ovf_un - 0x61, AI_xor - 0x60, AI_or - 0x65, AI_neg - 0x66, AI_not - i_ldnull, AI_ldnull - i_dup, AI_dup - i_pop, AI_pop - i_ckfinite, AI_ckfinite - i_nop, AI_nop - i_break, I_break - i_arglist, I_arglist - i_endfilter, I_endfilter + lazy [ i_ldc_i4_0, mk_ldc 0 + i_ldc_i4_1, mk_ldc 1 + i_ldc_i4_2, mk_ldc 2 + i_ldc_i4_3, mk_ldc 3 + i_ldc_i4_4, mk_ldc 4 + i_ldc_i4_5, mk_ldc 5 + i_ldc_i4_6, mk_ldc 6 + i_ldc_i4_7, mk_ldc 7 + i_ldc_i4_8, mk_ldc 8 + i_ldc_i4_m1, mk_ldc -1 + 0x0a, mkStloc 0us + 0x0b, mkStloc 1us + 0x0c, mkStloc 2us + 0x0d, mkStloc 3us + 0x06, mkLdloc 0us + 0x07, mkLdloc 1us + 0x08, mkLdloc 2us + 0x09, mkLdloc 3us + 0x02, mkLdarg 0us + 0x03, mkLdarg 1us + 0x04, mkLdarg 2us + 0x05, mkLdarg 3us + 0x2a, I_ret + 0x58, AI_add + 0xd6, AI_add_ovf + 0xd7, AI_add_ovf_un + 0x5f, AI_and + 0x5b, AI_div + 0x5c, AI_div_un + 0xfe01, AI_ceq + 0xfe02, AI_cgt + 0xfe03, AI_cgt_un + 0xfe04, AI_clt + 0xfe05, AI_clt_un + 0x67, AI_conv DT_I1 + 0x68, AI_conv DT_I2 + 0x69, AI_conv DT_I4 + 0x6a, AI_conv DT_I8 + 0xd3, AI_conv DT_I + 0x6b, AI_conv DT_R4 + 0x6c, AI_conv DT_R8 + 0xd2, AI_conv DT_U1 + 0xd1, AI_conv DT_U2 + 0x6d, AI_conv DT_U4 + 0x6e, AI_conv DT_U8 + 0xe0, AI_conv DT_U + 0x76, AI_conv DT_R + 0xb3, AI_conv_ovf DT_I1 + 0xb5, AI_conv_ovf DT_I2 + 0xb7, AI_conv_ovf DT_I4 + 0xb9, AI_conv_ovf DT_I8 + 0xd4, AI_conv_ovf DT_I + 0xb4, AI_conv_ovf DT_U1 + 0xb6, AI_conv_ovf DT_U2 + 0xb8, AI_conv_ovf DT_U4 + 0xba, AI_conv_ovf DT_U8 + 0xd5, AI_conv_ovf DT_U + 0x82, AI_conv_ovf_un DT_I1 + 0x83, AI_conv_ovf_un DT_I2 + 0x84, AI_conv_ovf_un DT_I4 + 0x85, AI_conv_ovf_un DT_I8 + 0x8a, AI_conv_ovf_un DT_I + 0x86, AI_conv_ovf_un DT_U1 + 0x87, AI_conv_ovf_un DT_U2 + 0x88, AI_conv_ovf_un DT_U4 + 0x89, AI_conv_ovf_un DT_U8 + 0x8b, AI_conv_ovf_un DT_U + 0x9c, I_stelem DT_I1 + 0x9d, I_stelem DT_I2 + 0x9e, I_stelem DT_I4 + 0x9f, I_stelem DT_I8 + 0xa0, I_stelem DT_R4 + 0xa1, I_stelem DT_R8 + 0x9b, I_stelem DT_I + 0xa2, I_stelem DT_REF + 0x90, I_ldelem DT_I1 + 0x92, I_ldelem DT_I2 + 0x94, I_ldelem DT_I4 + 0x96, I_ldelem DT_I8 + 0x91, I_ldelem DT_U1 + 0x93, I_ldelem DT_U2 + 0x95, I_ldelem DT_U4 + 0x98, I_ldelem DT_R4 + 0x99, I_ldelem DT_R8 + 0x97, I_ldelem DT_I + 0x9a, I_ldelem DT_REF + 0x5a, AI_mul + 0xd8, AI_mul_ovf + 0xd9, AI_mul_ovf_un + 0x5d, AI_rem + 0x5e, AI_rem_un + 0x62, AI_shl + 0x63, AI_shr + 0x64, AI_shr_un + 0x59, AI_sub + 0xda, AI_sub_ovf + 0xdb, AI_sub_ovf_un + 0x61, AI_xor + 0x60, AI_or + 0x65, AI_neg + 0x66, AI_not + i_ldnull, AI_ldnull + i_dup, AI_dup + i_pop, AI_pop + i_ckfinite, AI_ckfinite + i_nop, AI_nop + i_break, I_break + i_arglist, I_arglist + i_endfilter, I_endfilter i_endfinally, I_endfinally i_refanytype, I_refanytype - i_localloc, I_localloc - i_throw, I_throw - i_ldlen, I_ldlen - i_rethrow, I_rethrow ] + i_localloc, I_localloc + i_throw, I_throw + i_ldlen, I_ldlen + i_rethrow, I_rethrow ] let isNoArgInstr i = match i with @@ -760,36 +760,36 @@ let isNoArgInstr i = let ILCmpInstrMap = lazy ( let dict = Dictionary.newWithSize 12 - dict.Add (BI_beq , i_beq ) - dict.Add (BI_bgt , i_bgt ) - dict.Add (BI_bgt_un , i_bgt_un ) - dict.Add (BI_bge , i_bge ) - dict.Add (BI_bge_un , i_bge_un ) - dict.Add (BI_ble , i_ble ) - dict.Add (BI_ble_un , i_ble_un ) - dict.Add (BI_blt , i_blt ) - dict.Add (BI_blt_un , i_blt_un ) - dict.Add (BI_bne_un , i_bne_un ) - dict.Add (BI_brfalse , i_brfalse ) - dict.Add (BI_brtrue , i_brtrue ) + dict.Add (BI_beq, i_beq ) + dict.Add (BI_bgt, i_bgt ) + dict.Add (BI_bgt_un, i_bgt_un ) + dict.Add (BI_bge, i_bge ) + dict.Add (BI_bge_un, i_bge_un ) + dict.Add (BI_ble, i_ble ) + dict.Add (BI_ble_un, i_ble_un ) + dict.Add (BI_blt, i_blt ) + dict.Add (BI_blt_un, i_blt_un ) + dict.Add (BI_bne_un, i_bne_un ) + dict.Add (BI_brfalse, i_brfalse ) + dict.Add (BI_brtrue, i_brtrue ) dict ) let ILCmpInstrRevMap = lazy ( let dict = Dictionary.newWithSize 12 - dict.Add ( BI_beq , i_beq_s ) - dict.Add ( BI_bgt , i_bgt_s ) - dict.Add ( BI_bgt_un , i_bgt_un_s ) - dict.Add ( BI_bge , i_bge_s ) - dict.Add ( BI_bge_un , i_bge_un_s ) - dict.Add ( BI_ble , i_ble_s ) - dict.Add ( BI_ble_un , i_ble_un_s ) - dict.Add ( BI_blt , i_blt_s ) - dict.Add ( BI_blt_un , i_blt_un_s ) - dict.Add ( BI_bne_un , i_bne_un_s ) - dict.Add ( BI_brfalse , i_brfalse_s ) - dict.Add ( BI_brtrue , i_brtrue_s ) + dict.Add ( BI_beq, i_beq_s ) + dict.Add ( BI_bgt, i_bgt_s ) + dict.Add ( BI_bgt_un, i_bgt_un_s ) + dict.Add ( BI_bge, i_bge_s ) + dict.Add ( BI_bge_un, i_bge_un_s ) + dict.Add ( BI_ble, i_ble_s ) + dict.Add ( BI_ble_un, i_ble_un_s ) + dict.Add ( BI_blt, i_blt_s ) + dict.Add ( BI_blt_un, i_blt_un_s ) + dict.Add ( BI_bne_un, i_bne_un_s ) + dict.Add ( BI_brfalse, i_brfalse_s ) + dict.Add ( BI_brtrue, i_brtrue_s ) dict ) @@ -890,106 +890,106 @@ let vt_BYREF = 0x4000 let ILNativeTypeMap = - lazy [ nt_CURRENCY , ILNativeType.Currency - nt_BSTR , (* COM interop *) ILNativeType.BSTR - nt_LPSTR , ILNativeType.LPSTR - nt_LPWSTR , ILNativeType.LPWSTR + lazy [ nt_CURRENCY, ILNativeType.Currency + nt_BSTR, (* COM interop *) ILNativeType.BSTR + nt_LPSTR, ILNativeType.LPSTR + nt_LPWSTR, ILNativeType.LPWSTR nt_LPTSTR, ILNativeType.LPTSTR nt_LPUTF8STR, ILNativeType.LPUTF8STR - nt_IUNKNOWN , (* COM interop *) ILNativeType.IUnknown - nt_IDISPATCH , (* COM interop *) ILNativeType.IDispatch - nt_BYVALSTR , ILNativeType.ByValStr - nt_TBSTR , ILNativeType.TBSTR - nt_LPSTRUCT , ILNativeType.LPSTRUCT - nt_INTF , (* COM interop *) ILNativeType.Interface - nt_STRUCT , ILNativeType.Struct - nt_ERROR , (* COM interop *) ILNativeType.Error - nt_VOID , ILNativeType.Void - nt_BOOLEAN , ILNativeType.Bool - nt_I1 , ILNativeType.Int8 - nt_I2 , ILNativeType.Int16 - nt_I4 , ILNativeType.Int32 + nt_IUNKNOWN, (* COM interop *) ILNativeType.IUnknown + nt_IDISPATCH, (* COM interop *) ILNativeType.IDispatch + nt_BYVALSTR, ILNativeType.ByValStr + nt_TBSTR, ILNativeType.TBSTR + nt_LPSTRUCT, ILNativeType.LPSTRUCT + nt_INTF, (* COM interop *) ILNativeType.Interface + nt_STRUCT, ILNativeType.Struct + nt_ERROR, (* COM interop *) ILNativeType.Error + nt_VOID, ILNativeType.Void + nt_BOOLEAN, ILNativeType.Bool + nt_I1, ILNativeType.Int8 + nt_I2, ILNativeType.Int16 + nt_I4, ILNativeType.Int32 nt_I8, ILNativeType.Int64 - nt_R4 , ILNativeType.Single - nt_R8 , ILNativeType.Double - nt_U1 , ILNativeType.Byte - nt_U2 , ILNativeType.UInt16 - nt_U4 , ILNativeType.UInt32 + nt_R4, ILNativeType.Single + nt_R8, ILNativeType.Double + nt_U1, ILNativeType.Byte + nt_U2, ILNativeType.UInt16 + nt_U4, ILNativeType.UInt32 nt_U8, ILNativeType.UInt64 - nt_INT , ILNativeType.Int + nt_INT, ILNativeType.Int nt_UINT, ILNativeType.UInt nt_ANSIBSTR, (* COM interop *) ILNativeType.ANSIBSTR nt_VARIANTBOOL, (* COM interop *) ILNativeType.VariantBool - nt_FUNC , ILNativeType.Method + nt_FUNC, ILNativeType.Method nt_ASANY, ILNativeType.AsAny ] let ILNativeTypeRevMap = lazy (List.map (fun (x,y) -> (y,x)) (Lazy.force ILNativeTypeMap)) let ILVariantTypeMap = - lazy [ ILNativeVariant.Empty , vt_EMPTY - ILNativeVariant.Null , vt_NULL - ILNativeVariant.Variant , vt_VARIANT - ILNativeVariant.Currency , vt_CY - ILNativeVariant.Decimal , vt_DECIMAL - ILNativeVariant.Date , vt_DATE - ILNativeVariant.BSTR , vt_BSTR - ILNativeVariant.LPSTR , vt_LPSTR - ILNativeVariant.LPWSTR , vt_LPWSTR - ILNativeVariant.IUnknown , vt_UNKNOWN - ILNativeVariant.IDispatch , vt_DISPATCH - ILNativeVariant.SafeArray , vt_SAFEARRAY - ILNativeVariant.Error , vt_ERROR - ILNativeVariant.HRESULT , vt_HRESULT - ILNativeVariant.CArray , vt_CARRAY - ILNativeVariant.UserDefined , vt_USERDEFINED - ILNativeVariant.Record , vt_RECORD - ILNativeVariant.FileTime , vt_FILETIME - ILNativeVariant.Blob , vt_BLOB - ILNativeVariant.Stream , vt_STREAM - ILNativeVariant.Storage , vt_STORAGE - ILNativeVariant.StreamedObject , vt_STREAMED_OBJECT - ILNativeVariant.StoredObject , vt_STORED_OBJECT - ILNativeVariant.BlobObject , vt_BLOB_OBJECT - ILNativeVariant.CF , vt_CF - ILNativeVariant.CLSID , vt_CLSID - ILNativeVariant.Void , vt_VOID - ILNativeVariant.Bool , vt_BOOL - ILNativeVariant.Int8 , vt_I1 - ILNativeVariant.Int16 , vt_I2 - ILNativeVariant.Int32 , vt_I4 - ILNativeVariant.Int64 , vt_I8 - ILNativeVariant.Single , vt_R4 - ILNativeVariant.Double , vt_R8 - ILNativeVariant.UInt8 , vt_UI1 - ILNativeVariant.UInt16 , vt_UI2 - ILNativeVariant.UInt32 , vt_UI4 - ILNativeVariant.UInt64 , vt_UI8 - ILNativeVariant.PTR , vt_PTR - ILNativeVariant.Int , vt_INT - ILNativeVariant.UInt , vt_UINT ] + lazy [ ILNativeVariant.Empty, vt_EMPTY + ILNativeVariant.Null, vt_NULL + ILNativeVariant.Variant, vt_VARIANT + ILNativeVariant.Currency, vt_CY + ILNativeVariant.Decimal, vt_DECIMAL + ILNativeVariant.Date, vt_DATE + ILNativeVariant.BSTR, vt_BSTR + ILNativeVariant.LPSTR, vt_LPSTR + ILNativeVariant.LPWSTR, vt_LPWSTR + ILNativeVariant.IUnknown, vt_UNKNOWN + ILNativeVariant.IDispatch, vt_DISPATCH + ILNativeVariant.SafeArray, vt_SAFEARRAY + ILNativeVariant.Error, vt_ERROR + ILNativeVariant.HRESULT, vt_HRESULT + ILNativeVariant.CArray, vt_CARRAY + ILNativeVariant.UserDefined, vt_USERDEFINED + ILNativeVariant.Record, vt_RECORD + ILNativeVariant.FileTime, vt_FILETIME + ILNativeVariant.Blob, vt_BLOB + ILNativeVariant.Stream, vt_STREAM + ILNativeVariant.Storage, vt_STORAGE + ILNativeVariant.StreamedObject, vt_STREAMED_OBJECT + ILNativeVariant.StoredObject, vt_STORED_OBJECT + ILNativeVariant.BlobObject, vt_BLOB_OBJECT + ILNativeVariant.CF, vt_CF + ILNativeVariant.CLSID, vt_CLSID + ILNativeVariant.Void, vt_VOID + ILNativeVariant.Bool, vt_BOOL + ILNativeVariant.Int8, vt_I1 + ILNativeVariant.Int16, vt_I2 + ILNativeVariant.Int32, vt_I4 + ILNativeVariant.Int64, vt_I8 + ILNativeVariant.Single, vt_R4 + ILNativeVariant.Double, vt_R8 + ILNativeVariant.UInt8, vt_UI1 + ILNativeVariant.UInt16, vt_UI2 + ILNativeVariant.UInt32, vt_UI4 + ILNativeVariant.UInt64, vt_UI8 + ILNativeVariant.PTR, vt_PTR + ILNativeVariant.Int, vt_INT + ILNativeVariant.UInt, vt_UINT ] let ILVariantTypeRevMap = lazy (List.map (fun (x,y) -> (y,x)) (Lazy.force ILVariantTypeMap)) let ILSecurityActionMap = lazy - [ ILSecurityAction.Request , 0x0001 - ILSecurityAction.Demand , 0x0002 - ILSecurityAction.Assert , 0x0003 - ILSecurityAction.Deny , 0x0004 - ILSecurityAction.PermitOnly , 0x0005 - ILSecurityAction.LinkCheck , 0x0006 - ILSecurityAction.InheritCheck , 0x0007 - ILSecurityAction.ReqMin , 0x0008 - ILSecurityAction.ReqOpt , 0x0009 - ILSecurityAction.ReqRefuse , 0x000a - ILSecurityAction.PreJitGrant , 0x000b - ILSecurityAction.PreJitDeny , 0x000c - ILSecurityAction.NonCasDemand , 0x000d - ILSecurityAction.NonCasLinkDemand , 0x000e - ILSecurityAction.NonCasInheritance , 0x000f - ILSecurityAction.LinkDemandChoice , 0x0010 - ILSecurityAction.InheritanceDemandChoice , 0x0011 - ILSecurityAction.DemandChoice , 0x0012 ] + [ ILSecurityAction.Request, 0x0001 + ILSecurityAction.Demand, 0x0002 + ILSecurityAction.Assert, 0x0003 + ILSecurityAction.Deny, 0x0004 + ILSecurityAction.PermitOnly, 0x0005 + ILSecurityAction.LinkCheck, 0x0006 + ILSecurityAction.InheritCheck, 0x0007 + ILSecurityAction.ReqMin, 0x0008 + ILSecurityAction.ReqOpt, 0x0009 + ILSecurityAction.ReqRefuse, 0x000a + ILSecurityAction.PreJitGrant, 0x000b + ILSecurityAction.PreJitDeny, 0x000c + ILSecurityAction.NonCasDemand, 0x000d + ILSecurityAction.NonCasLinkDemand, 0x000e + ILSecurityAction.NonCasInheritance, 0x000f + ILSecurityAction.LinkDemandChoice, 0x0010 + ILSecurityAction.InheritanceDemandChoice, 0x0011 + ILSecurityAction.DemandChoice, 0x0012 ] let ILSecurityActionRevMap = lazy (List.map (fun (x,y) -> (y,x)) (Lazy.force ILSecurityActionMap)) diff --git a/src/absil/illib.fs b/src/absil/illib.fs index 71946a24910..da0b39dfb1c 100644 --- a/src/absil/illib.fs +++ b/src/absil/illib.fs @@ -1348,9 +1348,9 @@ module Shim = 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 diff --git a/src/absil/ilmorph.fs b/src/absil/ilmorph.fs index 1281007041a..ffd86aa504b 100644 --- a/src/absil/ilmorph.fs +++ b/src/absil/ilmorph.fs @@ -113,7 +113,7 @@ let mref_ty2ty (f: ILType -> ILType) (x:ILMethodRef) = type formal_scopeCtxt = Choice -let mspec_ty2ty (((factualty : ILType -> ILType) , (fformalty: formal_scopeCtxt -> ILType -> ILType))) (x: ILMethodSpec) = +let mspec_ty2ty (((factualty : ILType -> ILType), (fformalty: formal_scopeCtxt -> ILType -> ILType))) (x: ILMethodSpec) = mkILMethSpecForMethRefInTy(mref_ty2ty (fformalty (Choice1Of2 x)) x.MethodRef, factualty x.DeclaringType, tys_ty2ty factualty x.GenericArgs) diff --git a/src/absil/ilread.fs b/src/absil/ilread.fs index 7bb25a58363..165f97948dd 100644 --- a/src/absil/ilread.fs +++ b/src/absil/ilread.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. //--------------------------------------------------------------------- // The big binary reader @@ -50,7 +50,7 @@ let align alignment n = ((n + alignment - 0x1) / alignment) * alignment let uncodedToken (tab: TableName) idx = ((tab.Index <<< 24) ||| idx) -let i32ToUncodedToken tok = +let i32ToUncodedToken tok = let idx = tok &&& 0xffffff let tab = tok >>>& 24 (TableName.FromIndex tab, idx) @@ -107,8 +107,8 @@ let stats = let GetStatistics() = stats [] -/// 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. These objects should never need explicit disposal - they must either +/// 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. These objects should never need explicit disposal - they must either /// not hold resources of clean up after themselves when collected. type BinaryView() = @@ -130,11 +130,11 @@ type BinaryView() = /// Read a UTF8 string from the file abstract ReadUTF8String: addr: int -> string -/// An abstraction over how we access the contents of .NET binaries. May be backed by managed or unmanaged memory, +/// 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. 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 + /// 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 @@ -191,7 +191,7 @@ type RawMemoryFile(fileName: string, obj: obj, addr: nativeint, length: int) = module MemoryMapping = type HANDLE = nativeint - type ADDR = nativeint + type ADDR = nativeint type SIZE_T = nativeint [] @@ -216,25 +216,25 @@ module MemoryMapping = [] extern ADDR MapViewOfFile (HANDLE _hFileMappingObject, - int _dwDesiredAccess, - int _dwFileOffsetHigh, - int _dwFileOffsetLow, + int _dwDesiredAccess, + int _dwFileOffsetHigh, + int _dwFileOffsetLow, SIZE_T _dwNumBytesToMap) [] extern bool UnmapViewOfFile (ADDR _lpBaseAddress) let INVALID_HANDLE = new IntPtr(-1) - let MAP_READ = 0x0004 + let MAP_READ = 0x0004 let GENERIC_READ = 0x80000000 let NULL_HANDLE = IntPtr.Zero let FILE_SHARE_NONE = 0x0000 let FILE_SHARE_READ = 0x0001 let FILE_SHARE_WRITE = 0x0002 let FILE_SHARE_READ_WRITE = 0x0003 - let CREATE_ALWAYS = 0x0002 - let OPEN_EXISTING = 0x0003 - let OPEN_ALWAYS = 0x0004 + let CREATE_ALWAYS = 0x0002 + let OPEN_EXISTING = 0x0003 + let OPEN_ALWAYS = 0x0004 /// A view over a raw pointer to memory given by a memory mapped file. /// NOTE: we should do more checking of validity here. @@ -274,8 +274,8 @@ type MemoryMapFile(fileName: string, view: MemoryMapView, hMap: MemoryMapping.HA do stats.memoryMapFileOpenedCount <- stats.memoryMapFileOpenedCount + 1 let mutable closed = false - static member Create fileName = - let hFile = MemoryMapping.CreateFile (fileName, MemoryMapping.GENERIC_READ, MemoryMapping.FILE_SHARE_READ_WRITE, IntPtr.Zero, MemoryMapping.OPEN_EXISTING, 0, IntPtr.Zero ) + static member Create fileName = + let hFile = MemoryMapping.CreateFile (fileName, MemoryMapping.GENERIC_READ, MemoryMapping.FILE_SHARE_READ_WRITE, IntPtr.Zero, MemoryMapping.OPEN_EXISTING, 0, IntPtr.Zero ) if hFile.Equals(MemoryMapping.INVALID_HANDLE) then failwithf "CreateFile(0x%08x)" (Marshal.GetHRForLastWin32Error()) let protection = 0x00000002 @@ -345,7 +345,7 @@ type ByteFile(fileName: string, bytes: byte[]) = override bf.GetView() = view :> BinaryView /// Same as ByteFile but holds the bytes weakly. The bytes will be re-read from the backing file when a view is requested. -/// This is the default implementation used by F# Compiler Services when accessing "stable" binaries. It is not used +/// This is the default implementation used by F# Compiler Services when accessing "stable" binaries. It is not used /// by Visual Studio, where tryGetMetadataSnapshot provides a RawMemoryFile backed by Roslyn data. [] type WeakByteFile(fileName: string, chunk: (int * int) option) = @@ -442,14 +442,14 @@ let seekReadUserString mdv addr = let bytes = seekReadBytes mdv addr (len - 1) Encoding.Unicode.GetString(bytes, 0, bytes.Length) -let seekReadGuid mdv addr = seekReadBytes mdv addr 0x10 +let seekReadGuid mdv addr = seekReadBytes mdv addr 0x10 -let seekReadUncodedToken mdv addr = +let seekReadUncodedToken mdv addr = i32ToUncodedToken (seekReadInt32 mdv addr) //--------------------------------------------------------------------- -// Primitives to help read signatures. These do not use the file cursor +// Primitives to help read signatures. These do not use the file cursor //--------------------------------------------------------------------- let sigptrCheck (bytes: byte[]) sigptr = @@ -467,7 +467,7 @@ let sigptrGetByte (bytes: byte[]) sigptr = let sigptrGetBool bytes sigptr = let b0, sigptr = sigptrGetByte bytes sigptr - (b0 = 0x01uy) , sigptr + (b0 = 0x01uy), sigptr let sigptrGetSByte bytes sigptr = let i, sigptr = sigptrGetByte bytes sigptr @@ -524,7 +524,7 @@ let sigptrGetZInt32 bytes sigptr = let b1, sigptr = sigptrGetByte bytes sigptr let b2, sigptr = sigptrGetByte bytes sigptr let b3, sigptr = sigptrGetByte bytes sigptr - (int b0 <<< 24) ||| (int b1 <<< 16) ||| (int b2 <<< 8) ||| int b3, sigptr + (int b0 <<< 24) ||| (int b1 <<< 16) ||| (int b2 <<< 8) ||| int b3, sigptr let rec sigptrFoldAcc f n (bytes: byte[]) (sigptr: int) i acc = if i < n then @@ -618,8 +618,8 @@ type ILInstrDecoder = | I_r8_instr of (ILInstrPrefixesRegister -> double -> ILInstr) | I_field_instr of (ILInstrPrefixesRegister -> ILFieldSpec -> ILInstr) | I_method_instr of (ILInstrPrefixesRegister -> ILMethodSpec * ILVarArgs -> ILInstr) - | I_unconditional_i32_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr) - | I_unconditional_i8_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr) + | I_unconditional_i32_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr) + | I_unconditional_i8_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr) | I_conditional_i32_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr) | I_conditional_i8_instr of (ILInstrPrefixesRegister -> ILCodeLabel -> ILInstr) | I_string_instr of (ILInstrPrefixesRegister -> string -> ILInstr) @@ -633,19 +633,19 @@ let mkStind dt = volatileOrUnalignedPrefix (fun (x, y) -> I_stind(x, y, dt)) let mkLdind dt = volatileOrUnalignedPrefix (fun (x, y) -> I_ldind(x, y, dt)) let instrs () = - [ i_ldarg_s, I_u16_u8_instr (noPrefixes mkLdarg) - i_starg_s, I_u16_u8_instr (noPrefixes I_starg) + [ i_ldarg_s, I_u16_u8_instr (noPrefixes mkLdarg) + i_starg_s, I_u16_u8_instr (noPrefixes I_starg) i_ldarga_s, I_u16_u8_instr (noPrefixes I_ldarga) - i_stloc_s, I_u16_u8_instr (noPrefixes mkStloc) - i_ldloc_s, I_u16_u8_instr (noPrefixes mkLdloc) + i_stloc_s, I_u16_u8_instr (noPrefixes mkStloc) + i_ldloc_s, I_u16_u8_instr (noPrefixes mkLdloc) i_ldloca_s, I_u16_u8_instr (noPrefixes I_ldloca) - i_ldarg, I_u16_u16_instr (noPrefixes mkLdarg) - i_starg, I_u16_u16_instr (noPrefixes I_starg) - i_ldarga, I_u16_u16_instr (noPrefixes I_ldarga) - i_stloc, I_u16_u16_instr (noPrefixes mkStloc) - i_ldloc, I_u16_u16_instr (noPrefixes mkLdloc) - i_ldloca, I_u16_u16_instr (noPrefixes I_ldloca) - i_stind_i, I_none_instr (mkStind DT_I) + i_ldarg, I_u16_u16_instr (noPrefixes mkLdarg) + i_starg, I_u16_u16_instr (noPrefixes I_starg) + i_ldarga, I_u16_u16_instr (noPrefixes I_ldarga) + i_stloc, I_u16_u16_instr (noPrefixes mkStloc) + i_ldloc, I_u16_u16_instr (noPrefixes mkLdloc) + i_ldloca, I_u16_u16_instr (noPrefixes I_ldloca) + i_stind_i, I_none_instr (mkStind DT_I) i_stind_i1, I_none_instr (mkStind DT_I1) i_stind_i2, I_none_instr (mkStind DT_I2) i_stind_i4, I_none_instr (mkStind DT_I4) @@ -653,7 +653,7 @@ let instrs () = i_stind_r4, I_none_instr (mkStind DT_R4) i_stind_r8, I_none_instr (mkStind DT_R8) i_stind_ref, I_none_instr (mkStind DT_REF) - i_ldind_i, I_none_instr (mkLdind DT_I) + i_ldind_i, I_none_instr (mkLdind DT_I) i_ldind_i1, I_none_instr (mkLdind DT_I1) i_ldind_i2, I_none_instr (mkLdind DT_I2) i_ldind_i4, I_none_instr (mkLdind DT_I4) @@ -672,7 +672,7 @@ let instrs () = i_ldc_r4, I_r4_instr (noPrefixes (fun x -> (AI_ldc (DT_R4, ILConst.R4 x)))) i_ldc_r8, I_r8_instr (noPrefixes (fun x -> (AI_ldc (DT_R8, ILConst.R8 x)))) i_ldfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_ldfld(x, y, fspec))) - i_stfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_stfld(x, y, fspec))) + i_stfld, I_field_instr (volatileOrUnalignedPrefix(fun (x, y) fspec -> I_stfld(x, y, fspec))) i_ldsfld, I_field_instr (volatilePrefix (fun x fspec -> I_ldsfld (x, fspec))) i_stsfld, I_field_instr (volatilePrefix (fun x fspec -> I_stsfld (x, fspec))) i_ldflda, I_field_instr (noPrefixes I_ldflda) @@ -741,7 +741,7 @@ let fillInstrs () = let addInstr (i, f) = if i > 0xff then assert (i >>>& 8 = 0xfe) - let i = (i &&& 0xff) + let i = (i &&& 0xff) match twoByteInstrTable.[i] with | I_invalid_instr -> () | _ -> dprintn ("warning: duplicate decode entries for "+string i) @@ -773,7 +773,7 @@ let rec getTwoByteInstr i = type ImageChunk = { size: int32; addr: int32 } let chunk sz next = ({addr=next; size=sz}, next + sz) -let nochunk next = ({addr= 0x0;size= 0x0; } , next) +let nochunk next = ({addr= 0x0;size= 0x0; }, next) type RowElementKind = | UShort @@ -800,47 +800,47 @@ type RowElementKind = type RowKind = RowKind of RowElementKind list -let kindAssemblyRef = RowKind [ UShort; UShort; UShort; UShort; ULong; Blob; SString; SString; Blob; ] -let kindModuleRef = RowKind [ SString ] -let kindFileRef = RowKind [ ULong; SString; Blob ] -let kindTypeRef = RowKind [ ResolutionScope; SString; SString ] -let kindTypeSpec = RowKind [ Blob ] -let kindTypeDef = RowKind [ ULong; SString; SString; TypeDefOrRefOrSpec; SimpleIndex TableNames.Field; SimpleIndex TableNames.Method ] -let kindPropertyMap = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.Property ] -let kindEventMap = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.Event ] -let kindInterfaceImpl = RowKind [ SimpleIndex TableNames.TypeDef; TypeDefOrRefOrSpec ] -let kindNested = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.TypeDef ] -let kindCustomAttribute = RowKind [ HasCustomAttribute; CustomAttributeType; Blob ] -let kindDeclSecurity = RowKind [ UShort; HasDeclSecurity; Blob ] -let kindMemberRef = RowKind [ MemberRefParent; SString; Blob ] -let kindStandAloneSig = RowKind [ Blob ] -let kindFieldDef = RowKind [ UShort; SString; Blob ] -let kindFieldRVA = RowKind [ Data; SimpleIndex TableNames.Field ] -let kindFieldMarshal = RowKind [ HasFieldMarshal; Blob ] -let kindConstant = RowKind [ UShort;HasConstant; Blob ] -let kindFieldLayout = RowKind [ ULong; SimpleIndex TableNames.Field ] -let kindParam = RowKind [ UShort; UShort; SString ] -let kindMethodDef = RowKind [ ULong; UShort; UShort; SString; Blob; SimpleIndex TableNames.Param ] -let kindMethodImpl = RowKind [ SimpleIndex TableNames.TypeDef; MethodDefOrRef; MethodDefOrRef ] -let kindImplMap = RowKind [ UShort; MemberForwarded; SString; SimpleIndex TableNames.ModuleRef ] -let kindMethodSemantics = RowKind [ UShort; SimpleIndex TableNames.Method; HasSemantics ] -let kindProperty = RowKind [ UShort; SString; Blob ] -let kindEvent = RowKind [ UShort; SString; TypeDefOrRefOrSpec ] -let kindManifestResource = RowKind [ ULong; ULong; SString; Implementation ] -let kindClassLayout = RowKind [ UShort; ULong; SimpleIndex TableNames.TypeDef ] -let kindExportedType = RowKind [ ULong; ULong; SString; SString; Implementation ] -let kindAssembly = RowKind [ ULong; UShort; UShort; UShort; UShort; ULong; Blob; SString; SString ] -let kindGenericParam_v1_1 = RowKind [ UShort; UShort; TypeOrMethodDef; SString; TypeDefOrRefOrSpec ] -let kindGenericParam_v2_0 = RowKind [ UShort; UShort; TypeOrMethodDef; SString ] -let kindMethodSpec = RowKind [ MethodDefOrRef; Blob ] +let kindAssemblyRef = RowKind [ UShort; UShort; UShort; UShort; ULong; Blob; SString; SString; Blob; ] +let kindModuleRef = RowKind [ SString ] +let kindFileRef = RowKind [ ULong; SString; Blob ] +let kindTypeRef = RowKind [ ResolutionScope; SString; SString ] +let kindTypeSpec = RowKind [ Blob ] +let kindTypeDef = RowKind [ ULong; SString; SString; TypeDefOrRefOrSpec; SimpleIndex TableNames.Field; SimpleIndex TableNames.Method ] +let kindPropertyMap = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.Property ] +let kindEventMap = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.Event ] +let kindInterfaceImpl = RowKind [ SimpleIndex TableNames.TypeDef; TypeDefOrRefOrSpec ] +let kindNested = RowKind [ SimpleIndex TableNames.TypeDef; SimpleIndex TableNames.TypeDef ] +let kindCustomAttribute = RowKind [ HasCustomAttribute; CustomAttributeType; Blob ] +let kindDeclSecurity = RowKind [ UShort; HasDeclSecurity; Blob ] +let kindMemberRef = RowKind [ MemberRefParent; SString; Blob ] +let kindStandAloneSig = RowKind [ Blob ] +let kindFieldDef = RowKind [ UShort; SString; Blob ] +let kindFieldRVA = RowKind [ Data; SimpleIndex TableNames.Field ] +let kindFieldMarshal = RowKind [ HasFieldMarshal; Blob ] +let kindConstant = RowKind [ UShort;HasConstant; Blob ] +let kindFieldLayout = RowKind [ ULong; SimpleIndex TableNames.Field ] +let kindParam = RowKind [ UShort; UShort; SString ] +let kindMethodDef = RowKind [ ULong; UShort; UShort; SString; Blob; SimpleIndex TableNames.Param ] +let kindMethodImpl = RowKind [ SimpleIndex TableNames.TypeDef; MethodDefOrRef; MethodDefOrRef ] +let kindImplMap = RowKind [ UShort; MemberForwarded; SString; SimpleIndex TableNames.ModuleRef ] +let kindMethodSemantics = RowKind [ UShort; SimpleIndex TableNames.Method; HasSemantics ] +let kindProperty = RowKind [ UShort; SString; Blob ] +let kindEvent = RowKind [ UShort; SString; TypeDefOrRefOrSpec ] +let kindManifestResource = RowKind [ ULong; ULong; SString; Implementation ] +let kindClassLayout = RowKind [ UShort; ULong; SimpleIndex TableNames.TypeDef ] +let kindExportedType = RowKind [ ULong; ULong; SString; SString; Implementation ] +let kindAssembly = RowKind [ ULong; UShort; UShort; UShort; UShort; ULong; Blob; SString; SString ] +let kindGenericParam_v1_1 = RowKind [ UShort; UShort; TypeOrMethodDef; SString; TypeDefOrRefOrSpec ] +let kindGenericParam_v2_0 = RowKind [ UShort; UShort; TypeOrMethodDef; SString ] +let kindMethodSpec = RowKind [ MethodDefOrRef; Blob ] let kindGenericParamConstraint = RowKind [ SimpleIndex TableNames.GenericParam; TypeDefOrRefOrSpec ] -let kindModule = RowKind [ UShort; SString; GGuid; GGuid; GGuid ] -let kindIllegal = RowKind [ ] +let kindModule = RowKind [ UShort; SString; GGuid; GGuid; GGuid ] +let kindIllegal = RowKind [ ] //--------------------------------------------------------------------- -// Used for binary searches of sorted tables. Each function that reads +// Used for binary searches of sorted tables. Each function that reads // a table row returns a tuple that contains the elements of the row. -// One of these elements may be a key for a sorted table. These +// One of these elements may be a key for a sorted table. These // keys can be compared using the functions below depending on the // kind of element in that column. //--------------------------------------------------------------------- @@ -879,8 +879,8 @@ type BlobAsMethodSigIdx = BlobAsMethodSigIdx of int * int32 type BlobAsFieldSigIdx = BlobAsFieldSigIdx of int * int32 type BlobAsPropSigIdx = BlobAsPropSigIdx of int * int32 type BlobAsLocalSigIdx = BlobAsLocalSigIdx of int * int32 -type MemberRefAsMspecIdx = MemberRefAsMspecIdx of int * int -type MethodSpecAsMspecIdx = MethodSpecAsMspecIdx of int * int +type MemberRefAsMspecIdx = MemberRefAsMspecIdx of int * int +type MethodSpecAsMspecIdx = MethodSpecAsMspecIdx of int * int type MemberRefAsFspecIdx = MemberRefAsFspecIdx of int * int type CustomAttrIdx = CustomAttrIdx of CustomAttributeTypeTag * int * int32 type GenericParamsIdx = GenericParamsIdx of int * TypeOrMethodDefTag * int @@ -889,7 +889,7 @@ type GenericParamsIdx = GenericParamsIdx of int * TypeOrMethodDefTag * int // Polymorphic caches for row and heap readers //--------------------------------------------------------------------- -let mkCacheInt32 lowMem _inbase _nm _sz = +let mkCacheInt32 lowMem _inbase _nm _sz = if lowMem then (fun f x -> f x) else let cache = ref null let count = ref 0 @@ -899,7 +899,7 @@ let mkCacheInt32 lowMem _inbase _nm _sz = fun f (idx: int32) -> let cache = match !cache with - | null -> cache := new Dictionary(11) + | null -> cache := new Dictionary(11) | _ -> () !cache let mutable res = Unchecked.defaultof<_> @@ -912,7 +912,7 @@ let mkCacheInt32 lowMem _inbase _nm _sz = cache.[idx] <- res res -let mkCacheGeneric lowMem _inbase _nm _sz = +let mkCacheGeneric lowMem _inbase _nm _sz = if lowMem then (fun f x -> f x) else let cache = ref null let count = ref 0 @@ -940,7 +940,7 @@ let mkCacheGeneric lowMem _inbase _nm _sz = let seekFindRow numRows rowChooser = let mutable i = 1 - while (i <= numRows && not (rowChooser i)) do + while (i <= numRows && not (rowChooser i)) do i <- i + 1 if i > numRows then dprintn "warning: seekFindRow: row not found" i @@ -953,7 +953,7 @@ let seekReadIndexedRows (numRows, rowReader, keyFunc, keyComparer, binaryChop, r begin let mutable fin = false while not fin do - if high - low <= 1 then + if high - low <= 1 then fin <- true else let mid = (low + high) / 2 @@ -1169,18 +1169,18 @@ let seekReadUntaggedIdx (tab: TableName) (ctxt: ILMetadataReader) mdv (addr: byr seekReadIdx ctxt.tableBigness.[tab.Index] mdv &addr -let seekReadResolutionScopeIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkResolutionScopeTag 2 ctxt.rsBigness mdv &addr -let seekReadTypeDefOrRefOrSpecIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkTypeDefOrRefOrSpecTag 2 ctxt.tdorBigness mdv &addr -let seekReadTypeOrMethodDefIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkTypeOrMethodDefTag 1 ctxt.tomdBigness mdv &addr -let seekReadHasConstantIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasConstantTag 2 ctxt.hcBigness mdv &addr -let seekReadHasCustomAttributeIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasCustomAttributeTag 5 ctxt.hcaBigness mdv &addr -let seekReadHasFieldMarshalIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasFieldMarshalTag 1 ctxt.hfmBigness mdv &addr -let seekReadHasDeclSecurityIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasDeclSecurityTag 2 ctxt.hdsBigness mdv &addr -let seekReadMemberRefParentIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkMemberRefParentTag 3 ctxt.mrpBigness mdv &addr -let seekReadHasSemanticsIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasSemanticsTag 1 ctxt.hsBigness mdv &addr -let seekReadMethodDefOrRefIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkMethodDefOrRefTag 1 ctxt.mdorBigness mdv &addr -let seekReadMemberForwardedIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkMemberForwardedTag 1 ctxt.mfBigness mdv &addr -let seekReadImplementationIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkImplementationTag 2 ctxt.iBigness mdv &addr +let seekReadResolutionScopeIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkResolutionScopeTag 2 ctxt.rsBigness mdv &addr +let seekReadTypeDefOrRefOrSpecIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkTypeDefOrRefOrSpecTag 2 ctxt.tdorBigness mdv &addr +let seekReadTypeOrMethodDefIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkTypeOrMethodDefTag 1 ctxt.tomdBigness mdv &addr +let seekReadHasConstantIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasConstantTag 2 ctxt.hcBigness mdv &addr +let seekReadHasCustomAttributeIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasCustomAttributeTag 5 ctxt.hcaBigness mdv &addr +let seekReadHasFieldMarshalIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasFieldMarshalTag 1 ctxt.hfmBigness mdv &addr +let seekReadHasDeclSecurityIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasDeclSecurityTag 2 ctxt.hdsBigness mdv &addr +let seekReadMemberRefParentIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkMemberRefParentTag 3 ctxt.mrpBigness mdv &addr +let seekReadHasSemanticsIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkHasSemanticsTag 1 ctxt.hsBigness mdv &addr +let seekReadMethodDefOrRefIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkMethodDefOrRefTag 1 ctxt.mdorBigness mdv &addr +let seekReadMemberForwardedIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkMemberForwardedTag 1 ctxt.mfBigness mdv &addr +let seekReadImplementationIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkImplementationTag 2 ctxt.iBigness mdv &addr let seekReadCustomAttributeTypeIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadTaggedIdx mkILCustomAttributeTypeTag 3 ctxt.catBigness mdv &addr let seekReadStringIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadIdx ctxt.stringsBigness mdv &addr let seekReadGuidIdx (ctxt: ILMetadataReader) mdv (addr: byref) = seekReadIdx ctxt.guidsBigness mdv &addr @@ -1205,7 +1205,7 @@ let seekReadTypeRefRow (ctxt: ILMetadataReader) mdv idx = (scopeIdx, nameIdx, namespaceIdx) /// Read Table ILTypeDef. -let seekReadTypeDefRow (ctxt: ILMetadataReader) idx = ctxt.seekReadTypeDefRow idx +let seekReadTypeDefRow (ctxt: ILMetadataReader) idx = ctxt.seekReadTypeDefRow idx let seekReadTypeDefRowUncached ctxtH idx = let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() @@ -1219,7 +1219,7 @@ let seekReadTypeDefRowUncached ctxtH idx = (flags, nameIdx, namespaceIdx, extendsIdx, fieldsIdx, methodsIdx) /// Read Table Field. -let seekReadFieldRow (ctxt: ILMetadataReader) mdv idx = +let seekReadFieldRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.Field idx let flags = seekReadUInt16AsInt32Adv mdv &addr let nameIdx = seekReadStringIdx ctxt mdv &addr @@ -1227,7 +1227,7 @@ let seekReadFieldRow (ctxt: ILMetadataReader) mdv idx = (flags, nameIdx, typeIdx) /// Read Table Method. -let seekReadMethodRow (ctxt: ILMetadataReader) mdv idx = +let seekReadMethodRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.Method idx let codeRVA = seekReadInt32Adv mdv &addr let implflags = seekReadUInt16AsInt32Adv mdv &addr @@ -1238,22 +1238,22 @@ let seekReadMethodRow (ctxt: ILMetadataReader) mdv idx = (codeRVA, implflags, flags, nameIdx, typeIdx, paramIdx) /// Read Table Param. -let seekReadParamRow (ctxt: ILMetadataReader) mdv idx = +let seekReadParamRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.Param idx let flags = seekReadUInt16AsInt32Adv mdv &addr - let seq = seekReadUInt16AsInt32Adv mdv &addr + let seq = seekReadUInt16AsInt32Adv mdv &addr let nameIdx = seekReadStringIdx ctxt mdv &addr (flags, seq, nameIdx) /// Read Table InterfaceImpl. -let seekReadInterfaceImplRow (ctxt: ILMetadataReader) mdv idx = +let seekReadInterfaceImplRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.InterfaceImpl idx let tidx = seekReadUntaggedIdx TableNames.TypeDef ctxt mdv &addr let intfIdx = seekReadTypeDefOrRefOrSpecIdx ctxt mdv &addr (tidx, intfIdx) /// Read Table MemberRef. -let seekReadMemberRefRow (ctxt: ILMetadataReader) mdv idx = +let seekReadMemberRefRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.MemberRef idx let mrpIdx = seekReadMemberRefParentIdx ctxt mdv &addr let nameIdx = seekReadStringIdx ctxt mdv &addr @@ -1261,9 +1261,9 @@ let seekReadMemberRefRow (ctxt: ILMetadataReader) mdv idx = (mrpIdx, nameIdx, typeIdx) /// Read Table Constant. -let seekReadConstantRow (ctxt: ILMetadataReader) idx = ctxt.seekReadConstantRow idx +let seekReadConstantRow (ctxt: ILMetadataReader) idx = ctxt.seekReadConstantRow idx let seekReadConstantRowUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let mutable addr = ctxt.rowAddr TableNames.Constant idx let kind = seekReadUInt16Adv mdv &addr @@ -1272,7 +1272,7 @@ let seekReadConstantRowUncached ctxtH idx = (kind, parentIdx, valIdx) /// Read Table CustomAttribute. -let seekReadCustomAttributeRow (ctxt: ILMetadataReader) idx = +let seekReadCustomAttributeRow (ctxt: ILMetadataReader) idx = let mdv = ctxt.mdfile.GetView() let mutable addr = ctxt.rowAddr TableNames.CustomAttribute idx let parentIdx = seekReadHasCustomAttributeIdx ctxt mdv &addr @@ -1281,14 +1281,14 @@ let seekReadCustomAttributeRow (ctxt: ILMetadataReader) idx = (parentIdx, typeIdx, valIdx) /// Read Table FieldMarshal. -let seekReadFieldMarshalRow (ctxt: ILMetadataReader) mdv idx = +let seekReadFieldMarshalRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.FieldMarshal idx let parentIdx = seekReadHasFieldMarshalIdx ctxt mdv &addr let typeIdx = seekReadBlobIdx ctxt mdv &addr (parentIdx, typeIdx) /// Read Table Permission. -let seekReadPermissionRow (ctxt: ILMetadataReader) mdv idx = +let seekReadPermissionRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.Permission idx let action = seekReadUInt16Adv mdv &addr let parentIdx = seekReadHasDeclSecurityIdx ctxt mdv &addr @@ -1296,7 +1296,7 @@ let seekReadPermissionRow (ctxt: ILMetadataReader) mdv idx = (action, parentIdx, typeIdx) /// Read Table ClassLayout. -let seekReadClassLayoutRow (ctxt: ILMetadataReader) mdv idx = +let seekReadClassLayoutRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.ClassLayout idx let pack = seekReadUInt16Adv mdv &addr let size = seekReadInt32Adv mdv &addr @@ -1304,27 +1304,27 @@ let seekReadClassLayoutRow (ctxt: ILMetadataReader) mdv idx = (pack, size, tidx) /// Read Table FieldLayout. -let seekReadFieldLayoutRow (ctxt: ILMetadataReader) mdv idx = +let seekReadFieldLayoutRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.FieldLayout idx let offset = seekReadInt32Adv mdv &addr let fidx = seekReadUntaggedIdx TableNames.Field ctxt mdv &addr (offset, fidx) //// Read Table StandAloneSig. -let seekReadStandAloneSigRow (ctxt: ILMetadataReader) mdv idx = +let seekReadStandAloneSigRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.StandAloneSig idx let sigIdx = seekReadBlobIdx ctxt mdv &addr sigIdx /// Read Table EventMap. -let seekReadEventMapRow (ctxt: ILMetadataReader) mdv idx = +let seekReadEventMapRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.EventMap idx let tidx = seekReadUntaggedIdx TableNames.TypeDef ctxt mdv &addr let eventsIdx = seekReadUntaggedIdx TableNames.Event ctxt mdv &addr (tidx, eventsIdx) /// Read Table Event. -let seekReadEventRow (ctxt: ILMetadataReader) mdv idx = +let seekReadEventRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.Event idx let flags = seekReadUInt16AsInt32Adv mdv &addr let nameIdx = seekReadStringIdx ctxt mdv &addr @@ -1332,14 +1332,14 @@ let seekReadEventRow (ctxt: ILMetadataReader) mdv idx = (flags, nameIdx, typIdx) /// Read Table PropertyMap. -let seekReadPropertyMapRow (ctxt: ILMetadataReader) mdv idx = +let seekReadPropertyMapRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.PropertyMap idx let tidx = seekReadUntaggedIdx TableNames.TypeDef ctxt mdv &addr let propsIdx = seekReadUntaggedIdx TableNames.Property ctxt mdv &addr (tidx, propsIdx) /// Read Table Property. -let seekReadPropertyRow (ctxt: ILMetadataReader) mdv idx = +let seekReadPropertyRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.Property idx let flags = seekReadUInt16AsInt32Adv mdv &addr let nameIdx = seekReadStringIdx ctxt mdv &addr @@ -1347,9 +1347,9 @@ let seekReadPropertyRow (ctxt: ILMetadataReader) mdv idx = (flags, nameIdx, typIdx) /// Read Table MethodSemantics. -let seekReadMethodSemanticsRow (ctxt: ILMetadataReader) idx = ctxt.seekReadMethodSemanticsRow idx +let seekReadMethodSemanticsRow (ctxt: ILMetadataReader) idx = ctxt.seekReadMethodSemanticsRow idx let seekReadMethodSemanticsRowUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let mutable addr = ctxt.rowAddr TableNames.MethodSemantics idx let flags = seekReadUInt16AsInt32Adv mdv &addr @@ -1358,7 +1358,7 @@ let seekReadMethodSemanticsRowUncached ctxtH idx = (flags, midx, assocIdx) /// Read Table MethodImpl. -let seekReadMethodImplRow (ctxt: ILMetadataReader) mdv idx = +let seekReadMethodImplRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.MethodImpl idx let tidx = seekReadUntaggedIdx TableNames.TypeDef ctxt mdv &addr let mbodyIdx = seekReadMethodDefOrRefIdx ctxt mdv &addr @@ -1366,19 +1366,19 @@ let seekReadMethodImplRow (ctxt: ILMetadataReader) mdv idx = (tidx, mbodyIdx, mdeclIdx) /// Read Table ILModuleRef. -let seekReadModuleRefRow (ctxt: ILMetadataReader) mdv idx = +let seekReadModuleRefRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.ModuleRef idx let nameIdx = seekReadStringIdx ctxt mdv &addr nameIdx /// Read Table ILTypeSpec. -let seekReadTypeSpecRow (ctxt: ILMetadataReader) mdv idx = +let seekReadTypeSpecRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.TypeSpec idx let blobIdx = seekReadBlobIdx ctxt mdv &addr blobIdx /// Read Table ImplMap. -let seekReadImplMapRow (ctxt: ILMetadataReader) mdv idx = +let seekReadImplMapRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.ImplMap idx let flags = seekReadUInt16AsInt32Adv mdv &addr let forwrdedIdx = seekReadMemberForwardedIdx ctxt mdv &addr @@ -1387,14 +1387,14 @@ let seekReadImplMapRow (ctxt: ILMetadataReader) mdv idx = (flags, forwrdedIdx, nameIdx, scopeIdx) /// Read Table FieldRVA. -let seekReadFieldRVARow (ctxt: ILMetadataReader) mdv idx = +let seekReadFieldRVARow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.FieldRVA idx let rva = seekReadInt32Adv mdv &addr let fidx = seekReadUntaggedIdx TableNames.Field ctxt mdv &addr (rva, fidx) /// Read Table Assembly. -let seekReadAssemblyRow (ctxt: ILMetadataReader) mdv idx = +let seekReadAssemblyRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.Assembly idx let hash = seekReadInt32Adv mdv &addr let v1 = seekReadUInt16Adv mdv &addr @@ -1408,7 +1408,7 @@ let seekReadAssemblyRow (ctxt: ILMetadataReader) mdv idx = (hash, v1, v2, v3, v4, flags, publicKeyIdx, nameIdx, localeIdx) /// Read Table ILAssemblyRef. -let seekReadAssemblyRefRow (ctxt: ILMetadataReader) mdv idx = +let seekReadAssemblyRefRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.AssemblyRef idx let v1 = seekReadUInt16Adv mdv &addr let v2 = seekReadUInt16Adv mdv &addr @@ -1422,7 +1422,7 @@ let seekReadAssemblyRefRow (ctxt: ILMetadataReader) mdv idx = (v1, v2, v3, v4, flags, publicKeyOrTokenIdx, nameIdx, localeIdx, hashValueIdx) /// Read Table File. -let seekReadFileRow (ctxt: ILMetadataReader) mdv idx = +let seekReadFileRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.File idx let flags = seekReadInt32Adv mdv &addr let nameIdx = seekReadStringIdx ctxt mdv &addr @@ -1430,7 +1430,7 @@ let seekReadFileRow (ctxt: ILMetadataReader) mdv idx = (flags, nameIdx, hashValueIdx) /// Read Table ILExportedTypeOrForwarder. -let seekReadExportedTypeRow (ctxt: ILMetadataReader) mdv idx = +let seekReadExportedTypeRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.ExportedType idx let flags = seekReadInt32Adv mdv &addr let tok = seekReadInt32Adv mdv &addr @@ -1440,7 +1440,7 @@ let seekReadExportedTypeRow (ctxt: ILMetadataReader) mdv idx = (flags, tok, nameIdx, namespaceIdx, implIdx) /// Read Table ManifestResource. -let seekReadManifestResourceRow (ctxt: ILMetadataReader) mdv idx = +let seekReadManifestResourceRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.ManifestResource idx let offset = seekReadInt32Adv mdv &addr let flags = seekReadInt32Adv mdv &addr @@ -1449,9 +1449,9 @@ let seekReadManifestResourceRow (ctxt: ILMetadataReader) mdv idx = (offset, flags, nameIdx, implIdx) /// Read Table Nested. -let seekReadNestedRow (ctxt: ILMetadataReader) idx = ctxt.seekReadNestedRow idx +let seekReadNestedRow (ctxt: ILMetadataReader) idx = ctxt.seekReadNestedRow idx let seekReadNestedRowUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let mutable addr = ctxt.rowAddr TableNames.Nested idx let nestedIdx = seekReadUntaggedIdx TableNames.TypeDef ctxt mdv &addr @@ -1459,7 +1459,7 @@ let seekReadNestedRowUncached ctxtH idx = (nestedIdx, enclIdx) /// Read Table GenericParam. -let seekReadGenericParamRow (ctxt: ILMetadataReader) mdv idx = +let seekReadGenericParamRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.GenericParam idx let seq = seekReadUInt16Adv mdv &addr let flags = seekReadUInt16Adv mdv &addr @@ -1468,14 +1468,14 @@ let seekReadGenericParamRow (ctxt: ILMetadataReader) mdv idx = (idx, seq, flags, ownerIdx, nameIdx) // Read Table GenericParamConstraint. -let seekReadGenericParamConstraintRow (ctxt: ILMetadataReader) mdv idx = +let seekReadGenericParamConstraintRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.GenericParamConstraint idx let pidx = seekReadUntaggedIdx TableNames.GenericParam ctxt mdv &addr let constraintIdx = seekReadTypeDefOrRefOrSpecIdx ctxt mdv &addr (pidx, constraintIdx) /// Read Table ILMethodSpec. -let seekReadMethodSpecRow (ctxt: ILMetadataReader) mdv idx = +let seekReadMethodSpecRow (ctxt: ILMetadataReader) mdv idx = let mutable addr = ctxt.rowAddr TableNames.MethodSpec idx let mdorIdx = seekReadMethodDefOrRefIdx ctxt mdv &addr let instIdx = seekReadBlobIdx ctxt mdv &addr @@ -1483,44 +1483,44 @@ let seekReadMethodSpecRow (ctxt: ILMetadataReader) mdv idx = let readUserStringHeapUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() seekReadUserString mdv (ctxt.userStringsStreamPhysicalLoc + idx) -let readUserStringHeap (ctxt: ILMetadataReader) idx = ctxt.readUserStringHeap idx +let readUserStringHeap (ctxt: ILMetadataReader) idx = ctxt.readUserStringHeap idx let readStringHeapUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() seekReadUTF8String mdv (ctxt.stringsStreamPhysicalLoc + idx) -let readStringHeap (ctxt: ILMetadataReader) idx = ctxt.readStringHeap idx +let readStringHeap (ctxt: ILMetadataReader) idx = ctxt.readStringHeap idx -let readStringHeapOption (ctxt: ILMetadataReader) idx = if idx = 0 then None else Some (readStringHeap ctxt idx) +let readStringHeapOption (ctxt: ILMetadataReader) idx = if idx = 0 then None else Some (readStringHeap ctxt idx) let emptyByteArray: byte[] = [||] let readBlobHeapUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() // valid index lies in range [1..streamSize) // NOTE: idx cannot be 0 - Blob\String heap has first empty element that mdv one byte 0 if idx <= 0 || idx >= ctxt.blobsStreamSize then emptyByteArray else seekReadBlob mdv (ctxt.blobsStreamPhysicalLoc + idx) -let readBlobHeap (ctxt: ILMetadataReader) idx = ctxt.readBlobHeap idx +let readBlobHeap (ctxt: ILMetadataReader) idx = ctxt.readBlobHeap idx let readBlobHeapOption ctxt idx = if idx = 0 then None else Some (readBlobHeap ctxt idx) //let readGuidHeap ctxt idx = seekReadGuid ctxt.mdv (ctxt.guidsStreamPhysicalLoc + idx) // read a single value out of a blob heap using the given function -let readBlobHeapAsBool ctxt vidx = fst (sigptrGetBool (readBlobHeap ctxt vidx) 0) -let readBlobHeapAsSByte ctxt vidx = fst (sigptrGetSByte (readBlobHeap ctxt vidx) 0) -let readBlobHeapAsInt16 ctxt vidx = fst (sigptrGetInt16 (readBlobHeap ctxt vidx) 0) -let readBlobHeapAsInt32 ctxt vidx = fst (sigptrGetInt32 (readBlobHeap ctxt vidx) 0) -let readBlobHeapAsInt64 ctxt vidx = fst (sigptrGetInt64 (readBlobHeap ctxt vidx) 0) -let readBlobHeapAsByte ctxt vidx = fst (sigptrGetByte (readBlobHeap ctxt vidx) 0) +let readBlobHeapAsBool ctxt vidx = fst (sigptrGetBool (readBlobHeap ctxt vidx) 0) +let readBlobHeapAsSByte ctxt vidx = fst (sigptrGetSByte (readBlobHeap ctxt vidx) 0) +let readBlobHeapAsInt16 ctxt vidx = fst (sigptrGetInt16 (readBlobHeap ctxt vidx) 0) +let readBlobHeapAsInt32 ctxt vidx = fst (sigptrGetInt32 (readBlobHeap ctxt vidx) 0) +let readBlobHeapAsInt64 ctxt vidx = fst (sigptrGetInt64 (readBlobHeap ctxt vidx) 0) +let readBlobHeapAsByte ctxt vidx = fst (sigptrGetByte (readBlobHeap ctxt vidx) 0) let readBlobHeapAsUInt16 ctxt vidx = fst (sigptrGetUInt16 (readBlobHeap ctxt vidx) 0) let readBlobHeapAsUInt32 ctxt vidx = fst (sigptrGetUInt32 (readBlobHeap ctxt vidx) 0) let readBlobHeapAsUInt64 ctxt vidx = fst (sigptrGetUInt64 (readBlobHeap ctxt vidx) 0) @@ -1529,8 +1529,8 @@ let readBlobHeapAsDouble ctxt vidx = fst (sigptrGetDouble (readBlobHeap ctxt vid //----------------------------------------------------------------------- // Some binaries have raw data embedded their text sections, e.g. mscorlib, for -// field inits. And there is no information that definitively tells us the extent of -// the text section that may be interesting data. But we certainly don't want to duplicate +// field inits. And there is no information that definitively tells us the extent of +// the text section that may be interesting data. But we certainly don't want to duplicate // the entire text section as data! // // So, we assume: @@ -1548,7 +1548,7 @@ let readBlobHeapAsDouble ctxt vidx = fst (sigptrGetDouble (readBlobHeap ctxt vid // For example the assembly came from a type provider // In this case we eagerly read the native resources into memory let readNativeResources (pectxt: PEReader) = - [ if pectxt.nativeResourcesSize <> 0x0 && pectxt.nativeResourcesAddr <> 0x0 then + [ if pectxt.nativeResourcesSize <> 0x0 && pectxt.nativeResourcesAddr <> 0x0 then let start = pectxt.anyV2P (pectxt.fileName + ": native resources", pectxt.nativeResourcesAddr) if pectxt.noFileOnDisk then #if !FX_NO_LINKEDRESOURCES @@ -1565,7 +1565,7 @@ let readNativeResources (pectxt: PEReader) = let getDataEndPointsDelayed (pectxt: PEReader) ctxtH = lazy - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let dataStartPoints = let res = ref [] @@ -1688,9 +1688,9 @@ and seekReadAssemblyManifest (ctxt: ILMetadataReader) pectxt idx = JitTracking = 0 <> (flags &&& 0x8000) IgnoreSymbolStoreSequencePoints = 0 <> (flags &&& 0x2000) } -and seekReadAssemblyRef (ctxt: ILMetadataReader) idx = ctxt.seekReadAssemblyRef idx +and seekReadAssemblyRef (ctxt: ILMetadataReader) idx = ctxt.seekReadAssemblyRef idx and seekReadAssemblyRefUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let (v1, v2, v3, v4, flags, publicKeyOrTokenIdx, nameIdx, localeIdx, hashValueIdx) = seekReadAssemblyRefRow ctxt mdv idx let nm = readStringHeap ctxt nameIdx @@ -1707,15 +1707,15 @@ and seekReadAssemblyRefUncached ctxtH idx = version=Some(v1, v2, v3, v4), locale=readStringHeapOption ctxt localeIdx) -and seekReadModuleRef (ctxt: ILMetadataReader) mdv idx = +and seekReadModuleRef (ctxt: ILMetadataReader) mdv idx = let (nameIdx) = seekReadModuleRefRow ctxt mdv idx - ILModuleRef.Create(name = readStringHeap ctxt nameIdx, hasMetadata=true, hash=None) + ILModuleRef.Create(name = readStringHeap ctxt nameIdx, hasMetadata=true, hash=None) -and seekReadFile (ctxt: ILMetadataReader) mdv idx = +and seekReadFile (ctxt: ILMetadataReader) mdv idx = let (flags, nameIdx, hashValueIdx) = seekReadFileRow ctxt mdv idx - ILModuleRef.Create(name = readStringHeap ctxt nameIdx, hasMetadata= ((flags &&& 0x0001) = 0x0), hash= readBlobHeapOption ctxt hashValueIdx) + ILModuleRef.Create(name = readStringHeap ctxt nameIdx, hasMetadata= ((flags &&& 0x0001) = 0x0), hash= readBlobHeapOption ctxt hashValueIdx) -and seekReadClassLayout (ctxt: ILMetadataReader) mdv idx = +and seekReadClassLayout (ctxt: ILMetadataReader) mdv idx = match seekReadOptionalIndexedRow (ctxt.getNumRows TableNames.ClassLayout, seekReadClassLayoutRow ctxt mdv, (fun (_, _, tidx) -> tidx), simpleIndexCompare idx, isSorted ctxt TableNames.ClassLayout, (fun (pack, size, _) -> pack, size)) with | None -> { Size = None; Pack = None } | Some (pack, size) -> { Size = Some size; Pack = Some pack } @@ -1731,15 +1731,15 @@ and typeAccessOfFlags flags = elif f = 0x00000005 then ILTypeDefAccess.Nested ILMemberAccess.Assembly else ILTypeDefAccess.Private -and typeLayoutOfFlags (ctxt: ILMetadataReader) mdv flags tidx = +and typeLayoutOfFlags (ctxt: ILMetadataReader) mdv flags tidx = let f = (flags &&& 0x00000018) if f = 0x00000008 then ILTypeDefLayout.Sequential (seekReadClassLayout ctxt mdv tidx) - elif f = 0x00000010 then ILTypeDefLayout.Explicit (seekReadClassLayout ctxt mdv tidx) + elif f = 0x00000010 then ILTypeDefLayout.Explicit (seekReadClassLayout ctxt mdv tidx) else ILTypeDefLayout.Auto and isTopTypeDef flags = - (typeAccessOfFlags flags = ILTypeDefAccess.Private) || - typeAccessOfFlags flags = ILTypeDefAccess.Public + (typeAccessOfFlags flags = ILTypeDefAccess.Private) || + typeAccessOfFlags flags = ILTypeDefAccess.Public and seekIsTopTypeDefOfIdx ctxt idx = let (flags, _, _, _, _, _) = seekReadTypeDefRow ctxt 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 @@ -1798,12 +1798,12 @@ and typeDefReader ctxtH: ILTypeDefStored = let mdefs = seekReadMethods ctxt numtypars methodsIdx endMethodsIdx let fdefs = seekReadFields ctxt (numtypars, hasLayout) fieldsIdx endFieldsIdx let nested = seekReadNestedTypeDefs ctxt idx - let impls = seekReadInterfaceImpls ctxt mdv numtypars idx + let impls = seekReadInterfaceImpls ctxt mdv numtypars idx let mimpls = seekReadMethodImpls ctxt numtypars idx - let props = seekReadProperties ctxt numtypars idx + let props = seekReadProperties ctxt numtypars idx let events = seekReadEvents ctxt numtypars idx ILTypeDef(name=nm, - genericParams=typars , + genericParams=typars, attributes= enum(flags), layout = layout, nestedTypes= nested, @@ -1819,13 +1819,13 @@ and typeDefReader ctxtH: ILTypeDefStored = metadataIndex=idx) ) -and seekReadTopTypeDefs (ctxt: ILMetadataReader) = +and seekReadTopTypeDefs (ctxt: ILMetadataReader) = [| for i = 1 to ctxt.getNumRows TableNames.TypeDef do - match seekReadPreTypeDef ctxt true i with + match seekReadPreTypeDef ctxt true i with | None -> () | Some td -> yield td |] -and seekReadNestedTypeDefs (ctxt: ILMetadataReader) tidx = +and seekReadNestedTypeDefs (ctxt: ILMetadataReader) tidx = mkILTypeDefsComputed (fun () -> let nestedIdxs = seekReadIndexedRows (ctxt.getNumRows TableNames.Nested, seekReadNestedRow ctxt, snd, simpleIndexCompare tidx, false, fst) [| for i in nestedIdxs do @@ -1833,7 +1833,7 @@ and seekReadNestedTypeDefs (ctxt: ILMetadataReader) tidx = | None -> () | Some td -> yield td |]) -and seekReadInterfaceImpls (ctxt: ILMetadataReader) mdv numtypars tidx = +and seekReadInterfaceImpls (ctxt: ILMetadataReader) mdv numtypars tidx = seekReadIndexedRows (ctxt.getNumRows TableNames.InterfaceImpl, seekReadInterfaceImplRow ctxt mdv, fst, @@ -1845,7 +1845,7 @@ and seekReadGenericParams ctxt numtypars (a, b): ILGenericParameterDefs = ctxt.seekReadGenericParams (GenericParamsIdx(numtypars, a, b)) and seekReadGenericParamsUncached ctxtH (GenericParamsIdx(numtypars, a, b)) = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let pars = seekReadIndexedRows @@ -1872,23 +1872,23 @@ and seekReadGenericParamsUncached ctxtH (GenericParamsIdx(numtypars, a, b)) = HasDefaultConstructorConstraint=(flags &&& 0x0010) <> 0 })) pars |> List.sortBy fst |> List.map snd -and seekReadGenericParamConstraints (ctxt: ILMetadataReader) mdv numtypars gpidx = +and seekReadGenericParamConstraints (ctxt: ILMetadataReader) mdv numtypars gpidx = seekReadIndexedRows (ctxt.getNumRows TableNames.GenericParamConstraint, seekReadGenericParamConstraintRow ctxt mdv, fst, simpleIndexCompare gpidx, isSorted ctxt TableNames.GenericParamConstraint, - (snd >> seekReadTypeDefOrRef ctxt numtypars AsObject (*ok*) List.empty)) + (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)) = let ctxt = getHole ctxtH mkILTy boxity (ILTypeSpec.Create(seekReadTypeDefAsTypeRef ctxt idx, ginst)) -and seekReadTypeDefAsTypeRef (ctxt: ILMetadataReader) idx = +and seekReadTypeDefAsTypeRef (ctxt: ILMetadataReader) idx = let enc = if seekIsTopTypeDefOfIdx ctxt idx then [] else @@ -1899,21 +1899,21 @@ and seekReadTypeDefAsTypeRef (ctxt: ILMetadataReader) idx = let nm = readBlobHeapAsTypeName ctxt (nameIdx, namespaceIdx) ILTypeRef.Create(scope=ILScopeRef.Local, enclosing=enc, name = nm ) -and seekReadTypeRef (ctxt: ILMetadataReader) idx = ctxt.seekReadTypeRef idx +and seekReadTypeRef (ctxt: ILMetadataReader) idx = ctxt.seekReadTypeRef idx and seekReadTypeRefUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let scopeIdx, nameIdx, namespaceIdx = seekReadTypeRefRow ctxt mdv idx let scope, enc = seekReadTypeRefScope ctxt mdv scopeIdx let nm = readBlobHeapAsTypeName ctxt (nameIdx, namespaceIdx) ILTypeRef.Create(scope=scope, enclosing=enc, name = nm) -and seekReadTypeRefAsType (ctxt: ILMetadataReader) boxity ginst idx = ctxt.seekReadTypeRefAsType (TypeRefAsTypIdx (boxity, ginst, idx)) +and seekReadTypeRefAsType (ctxt: ILMetadataReader) boxity ginst idx = ctxt.seekReadTypeRefAsType (TypeRefAsTypIdx (boxity, ginst, idx)) 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 @@ -1923,7 +1923,7 @@ and seekReadTypeDefOrRef (ctxt: ILMetadataReader) numtypars boxity (ginst: ILTy readBlobHeapAsType ctxt numtypars (seekReadTypeSpecRow ctxt mdv idx) | _ -> failwith "seekReadTypeDefOrRef ctxt" -and seekReadTypeDefOrRefAsTypeRef (ctxt: ILMetadataReader) (TaggedIndex(tag, idx) ) = +and seekReadTypeDefOrRefAsTypeRef (ctxt: ILMetadataReader) (TaggedIndex(tag, idx) ) = match tag with | tag when tag = tdor_TypeDef -> seekReadTypeDefAsTypeRef ctxt idx | tag when tag = tdor_TypeRef -> seekReadTypeRef ctxt idx @@ -1932,7 +1932,7 @@ and seekReadTypeDefOrRefAsTypeRef (ctxt: ILMetadataReader) (TaggedIndex(tag, id ctxt.ilg.typ_Object.TypeRef | _ -> failwith "seekReadTypeDefOrRefAsTypeRef_readTypeDefOrRefOrSpec" -and seekReadMethodRefParent (ctxt: ILMetadataReader) mdv numtypars (TaggedIndex(tag, idx)) = +and seekReadMethodRefParent (ctxt: ILMetadataReader) mdv numtypars (TaggedIndex(tag, idx)) = match tag with | tag when tag = mrp_TypeRef -> seekReadTypeRefAsType ctxt AsObject (* not ok - no way to tell if a member ref parent is a value type or not *) List.empty idx | tag when tag = mrp_ModuleRef -> mkILTypeForGlobalFunctions (ILScopeRef.Module (seekReadModuleRef ctxt mdv idx)) @@ -1943,7 +1943,7 @@ and seekReadMethodRefParent (ctxt: ILMetadataReader) mdv numtypars (TaggedIndex | tag when tag = mrp_TypeSpec -> readBlobHeapAsType ctxt numtypars (seekReadTypeSpecRow ctxt mdv idx) | _ -> failwith "seekReadMethodRefParent" -and seekReadMethodDefOrRef (ctxt: ILMetadataReader) numtypars (TaggedIndex(tag, idx)) = +and seekReadMethodDefOrRef (ctxt: ILMetadataReader) numtypars (TaggedIndex(tag, idx)) = match tag with | tag when tag = mdor_MethodDef -> let (MethodData(enclTy, cc, nm, argtys, retty, minst)) = seekReadMethodDefAsMethodData ctxt idx @@ -1952,12 +1952,12 @@ and seekReadMethodDefOrRef (ctxt: ILMetadataReader) numtypars (TaggedIndex(tag, seekReadMemberRefAsMethodData ctxt numtypars idx | _ -> failwith "seekReadMethodDefOrRef" -and seekReadMethodDefOrRefNoVarargs (ctxt: ILMetadataReader) numtypars x = - let (VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, minst)) = seekReadMethodDefOrRef ctxt numtypars x +and seekReadMethodDefOrRefNoVarargs (ctxt: ILMetadataReader) numtypars x = + let (VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, minst)) = seekReadMethodDefOrRef ctxt numtypars x if varargs <> None then dprintf "ignoring sentinel and varargs in ILMethodDef token signature" MethodData(enclTy, cc, nm, argtys, retty, minst) -and seekReadCustomAttrType (ctxt: ILMetadataReader) (TaggedIndex(tag, idx) ) = +and seekReadCustomAttrType (ctxt: ILMetadataReader) (TaggedIndex(tag, idx) ) = match tag with | tag when tag = cat_MethodDef -> let (MethodData(enclTy, cc, nm, argtys, retty, minst)) = seekReadMethodDefAsMethodData ctxt idx @@ -1967,7 +1967,7 @@ and seekReadCustomAttrType (ctxt: ILMetadataReader) (TaggedIndex(tag, idx) ) = mkILMethSpecInTy (enclTy, cc, nm, argtys, retty, minst) | _ -> failwith "seekReadCustomAttrType ctxt" -and seekReadImplAsScopeRef (ctxt: ILMetadataReader) mdv (TaggedIndex(tag, idx) ) = +and seekReadImplAsScopeRef (ctxt: ILMetadataReader) mdv (TaggedIndex(tag, idx) ) = if idx = 0 then ILScopeRef.Local else match tag with @@ -1976,7 +1976,7 @@ and seekReadImplAsScopeRef (ctxt: ILMetadataReader) mdv (TaggedIndex(tag, idx) | tag when tag = i_ExportedType -> failwith "seekReadImplAsScopeRef" | _ -> failwith "seekReadImplAsScopeRef" -and seekReadTypeRefScope (ctxt: ILMetadataReader) mdv (TaggedIndex(tag, idx) ) = +and seekReadTypeRefScope (ctxt: ILMetadataReader) mdv (TaggedIndex(tag, idx) ) = match tag with | tag when tag = rs_Module -> ILScopeRef.Local, [] | tag when tag = rs_ModuleRef -> ILScopeRef.Module (seekReadModuleRef ctxt mdv idx), [] @@ -1986,7 +1986,7 @@ and seekReadTypeRefScope (ctxt: ILMetadataReader) mdv (TaggedIndex(tag, idx) ) tref.Scope, (tref.Enclosing@[tref.Name]) | _ -> failwith "seekReadTypeRefScope" -and seekReadOptionalTypeDefOrRef (ctxt: ILMetadataReader) numtypars boxity idx = +and seekReadOptionalTypeDefOrRef (ctxt: ILMetadataReader) numtypars boxity idx = if idx = TaggedIndex(tdor_TypeDef, 0) then None else Some (seekReadTypeDefOrRef ctxt numtypars boxity List.empty idx) @@ -2023,14 +2023,14 @@ and seekReadField ctxt mdv (numtypars, hasLayout) (idx: int) = customAttrsStored=ctxt.customAttrsReader_FieldDef, metadataIndex = idx) -and seekReadFields (ctxt: ILMetadataReader) (numtypars, hasLayout) fidx1 fidx2 = +and seekReadFields (ctxt: ILMetadataReader) (numtypars, hasLayout) fidx1 fidx2 = mkILFieldsLazy (lazy let mdv = ctxt.mdfile.GetView() [ for i = fidx1 to fidx2 - 1 do yield seekReadField ctxt mdv (numtypars, hasLayout) i ]) -and seekReadMethods (ctxt: ILMetadataReader) numtypars midx1 midx2 = +and seekReadMethods (ctxt: ILMetadataReader) numtypars midx1 midx2 = mkILMethodsComputed (fun () -> let mdv = ctxt.mdfile.GetView() [| for i = midx1 to midx2 - 1 do @@ -2043,9 +2043,9 @@ and sigptrGetTypeDefOrRefOrSpecIdx bytes sigptr = else (* Type Ref *) TaggedIndex(tdor_TypeRef, (n >>>& 2)), sigptr -and sigptrGetTy (ctxt: ILMetadataReader) numtypars bytes sigptr = +and sigptrGetTy (ctxt: ILMetadataReader) numtypars bytes sigptr = let b0, sigptr = sigptrGetByte bytes sigptr - if b0 = et_OBJECT then ctxt.ilg.typ_Object , sigptr + if b0 = et_OBJECT then ctxt.ilg.typ_Object, sigptr elif b0 = et_STRING then ctxt.ilg.typ_String, sigptr elif b0 = et_I1 then ctxt.ilg.typ_SByte, sigptr elif b0 = et_I2 then ctxt.ilg.typ_Int16, sigptr @@ -2099,8 +2099,8 @@ and sigptrGetTy (ctxt: ILMetadataReader) numtypars bytes sigptr = let lobounds, sigptr = sigptrFold sigptrGetZInt32 numLoBounded bytes sigptr let shape = let dim i = - (if i < numLoBounded then Some (List.item i lobounds) else None), - (if i < numSized then Some (List.item i sizes) else None) + (if i < numLoBounded then Some (List.item i lobounds) else None), + (if i < numSized then Some (List.item i sizes) else None) ILArrayShape (List.init rank dim) mkILArrTy (ty, shape), sigptr @@ -2108,7 +2108,7 @@ and sigptrGetTy (ctxt: ILMetadataReader) numtypars bytes sigptr = elif b0 = et_TYPEDBYREF then let t = mkILNonGenericValueTy(mkILTyRef(ctxt.ilg.primaryAssemblyScopeRef, "System.TypedReference")) t, sigptr - elif b0 = et_CMOD_REQD || b0 = et_CMOD_OPT then + elif b0 = et_CMOD_REQD || b0 = et_CMOD_OPT then let tdorIdx, sigptr = sigptrGetTypeDefOrRefOrSpecIdx bytes sigptr let ty, sigptr = sigptrGetTy ctxt numtypars bytes sigptr ILType.Modified((b0 = et_CMOD_REQD), seekReadTypeDefOrRefAsTypeRef ctxt tdorIdx, ty), sigptr @@ -2119,18 +2119,19 @@ and sigptrGetTy (ctxt: ILMetadataReader) numtypars bytes sigptr = let numparams, sigptr = sigptrGetZInt32 bytes sigptr let retty, sigptr = sigptrGetTy ctxt numtypars bytes sigptr let argtys, sigptr = sigptrFold (sigptrGetTy ctxt numtypars) ( numparams) bytes sigptr - ILType.FunctionPointer - { CallingConv=cc - ArgTypes = argtys - ReturnType=retty } - , sigptr + let typ = + ILType.FunctionPointer + { CallingConv=cc + ArgTypes = argtys + ReturnType=retty } + typ, sigptr elif b0 = et_SENTINEL then failwith "varargs NYI" - else ILType.Void , sigptr + else ILType.Void, sigptr -and sigptrGetVarArgTys (ctxt: ILMetadataReader) n numtypars bytes sigptr = +and sigptrGetVarArgTys (ctxt: ILMetadataReader) n numtypars bytes sigptr = sigptrFold (sigptrGetTy ctxt numtypars) n bytes sigptr -and sigptrGetArgTys (ctxt: ILMetadataReader) n numtypars bytes sigptr acc = +and sigptrGetArgTys (ctxt: ILMetadataReader) n numtypars bytes sigptr acc = if n <= 0 then (List.rev acc, None), sigptr else let b0, sigptr2 = sigptrGetByte bytes sigptr @@ -2141,7 +2142,7 @@ and sigptrGetArgTys (ctxt: ILMetadataReader) n numtypars bytes sigptr acc = let x, sigptr = sigptrGetTy ctxt numtypars bytes sigptr sigptrGetArgTys ctxt (n-1) numtypars bytes sigptr (x::acc) -and sigptrGetLocal (ctxt: ILMetadataReader) numtypars bytes sigptr = +and sigptrGetLocal (ctxt: ILMetadataReader) numtypars bytes sigptr = let pinned, sigptr = let b0, sigptr' = sigptrGetByte bytes sigptr if b0 = et_PINNED then @@ -2152,11 +2153,11 @@ and sigptrGetLocal (ctxt: ILMetadataReader) numtypars bytes sigptr = let loc: ILLocal = { IsPinned = pinned; Type = ty; DebugInfo = None } loc, sigptr -and readBlobHeapAsMethodSig (ctxt: ILMetadataReader) numtypars blobIdx = +and readBlobHeapAsMethodSig (ctxt: ILMetadataReader) numtypars blobIdx = ctxt.readBlobHeapAsMethodSig (BlobAsMethodSigIdx (numtypars, blobIdx)) and readBlobHeapAsMethodSigUncached ctxtH (BlobAsMethodSigIdx (numtypars, blobIdx)) = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let bytes = readBlobHeap ctxt blobIdx let sigptr = 0 let ccByte, sigptr = sigptrGetByte bytes sigptr @@ -2172,7 +2173,7 @@ and readBlobHeapAsType ctxt numtypars blobIdx = let ty, _sigptr = sigptrGetTy ctxt numtypars bytes 0 ty -and readBlobHeapAsFieldSig ctxt numtypars blobIdx = +and readBlobHeapAsFieldSig ctxt numtypars blobIdx = ctxt.readBlobHeapAsFieldSig (BlobAsFieldSigIdx (numtypars, blobIdx)) and readBlobHeapAsFieldSigUncached ctxtH (BlobAsFieldSigIdx (numtypars, blobIdx)) = @@ -2185,10 +2186,10 @@ and readBlobHeapAsFieldSigUncached ctxtH (BlobAsFieldSigIdx (numtypars, blobIdx) retty -and readBlobHeapAsPropertySig (ctxt: ILMetadataReader) numtypars blobIdx = +and readBlobHeapAsPropertySig (ctxt: ILMetadataReader) numtypars blobIdx = ctxt.readBlobHeapAsPropertySig (BlobAsPropSigIdx (numtypars, blobIdx)) -and readBlobHeapAsPropertySigUncached ctxtH (BlobAsPropSigIdx (numtypars, blobIdx)) = +and readBlobHeapAsPropertySigUncached ctxtH (BlobAsPropSigIdx (numtypars, blobIdx)) = let ctxt = getHole ctxtH let bytes = readBlobHeap ctxt blobIdx let sigptr = 0 @@ -2201,7 +2202,7 @@ and readBlobHeapAsPropertySigUncached ctxtH (BlobAsPropSigIdx (numtypars, blobId let argtys, _sigptr = sigptrFold (sigptrGetTy ctxt numtypars) ( numparams) bytes sigptr hasthis, retty, argtys -and readBlobHeapAsLocalsSig (ctxt: ILMetadataReader) numtypars blobIdx = +and readBlobHeapAsLocalsSig (ctxt: ILMetadataReader) numtypars blobIdx = ctxt.readBlobHeapAsLocalsSig (BlobAsLocalSigIdx (numtypars, blobIdx)) and readBlobHeapAsLocalsSigUncached ctxtH (BlobAsLocalSigIdx (numtypars, blobIdx)) = @@ -2223,12 +2224,12 @@ and byteAsHasThis b = and byteAsCallConv b = let cc = let ccMaxked = b &&& 0x0Fuy - if ccMaxked = e_IMAGE_CEE_CS_CALLCONV_FASTCALL then ILArgConvention.FastCall + if ccMaxked = e_IMAGE_CEE_CS_CALLCONV_FASTCALL then ILArgConvention.FastCall elif ccMaxked = e_IMAGE_CEE_CS_CALLCONV_STDCALL then ILArgConvention.StdCall elif ccMaxked = e_IMAGE_CEE_CS_CALLCONV_THISCALL then ILArgConvention.ThisCall elif ccMaxked = e_IMAGE_CEE_CS_CALLCONV_CDECL then ILArgConvention.CDecl elif ccMaxked = e_IMAGE_CEE_CS_CALLCONV_VARARG then ILArgConvention.VarArg - else ILArgConvention.Default + else ILArgConvention.Default let generic = (b &&& e_IMAGE_CEE_CS_CALLCONV_GENERIC) <> 0x0uy generic, Callconv (byteAsHasThis b, cc) @@ -2236,17 +2237,17 @@ and seekReadMemberRefAsMethodData ctxt numtypars idx: VarArgMethodData = ctxt.seekReadMemberRefAsMethodData (MemberRefAsMspecIdx (numtypars, idx)) and seekReadMemberRefAsMethodDataUncached ctxtH (MemberRefAsMspecIdx (numtypars, idx)) = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let (mrpIdx, nameIdx, typeIdx) = seekReadMemberRefRow ctxt mdv idx let nm = readStringHeap ctxt nameIdx let enclTy = seekReadMethodRefParent ctxt mdv numtypars mrpIdx let _generic, genarity, cc, retty, argtys, varargs = readBlobHeapAsMethodSig ctxt enclTy.GenericArgs.Length typeIdx - let minst = List.init genarity (fun n -> mkILTyvarTy (uint16 (numtypars+n))) + 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 = - let (VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, minst)) = seekReadMemberRefAsMethodData ctxt numtypars idx + 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)) @@ -2254,7 +2255,7 @@ and seekReadMethodSpecAsMethodData (ctxt: ILMetadataReader) numtypars idx = ctxt.seekReadMethodSpecAsMethodData (MethodSpecAsMspecIdx (numtypars, idx)) and seekReadMethodSpecAsMethodDataUncached ctxtH (MethodSpecAsMspecIdx (numtypars, idx)) = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let (mdorIdx, instIdx) = seekReadMethodSpecRow ctxt mdv idx let (VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, _)) = seekReadMethodDefOrRef ctxt numtypars mdorIdx @@ -2268,11 +2269,11 @@ and seekReadMethodSpecAsMethodDataUncached ctxtH (MethodSpecAsMspecIdx (numtypar argtys VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, minst) -and seekReadMemberRefAsFieldSpec (ctxt: ILMetadataReader) numtypars idx = +and seekReadMemberRefAsFieldSpec (ctxt: ILMetadataReader) numtypars idx = ctxt.seekReadMemberRefAsFieldSpec (MemberRefAsFspecIdx (numtypars, idx)) and seekReadMemberRefAsFieldSpecUncached ctxtH (MemberRefAsFspecIdx (numtypars, idx)) = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let (mrpIdx, nameIdx, typeIdx) = seekReadMemberRefRow ctxt mdv idx let nm = readStringHeap ctxt nameIdx @@ -2282,7 +2283,7 @@ and seekReadMemberRefAsFieldSpecUncached ctxtH (MemberRefAsFspecIdx (numtypars, // One extremely annoying aspect of the MD format is that given a // ILMethodDef token it is non-trivial to find which ILTypeDef it belongs -// to. So we do a binary chop through the ILTypeDef table +// to. So we do a binary chop through the ILTypeDef table // looking for which ILTypeDef has the ILMethodDef within its range. // Although the ILTypeDef table is not "sorted", it is effectively sorted by // method-range and field-range start/finish indexes @@ -2290,7 +2291,7 @@ and seekReadMethodDefAsMethodData ctxt idx = ctxt.seekReadMethodDefAsMethodData idx and seekReadMethodDefAsMethodDataUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() // Look for the method def parent. let tidx = @@ -2298,7 +2299,7 @@ and seekReadMethodDefAsMethodDataUncached ctxtH idx = (fun i -> i, seekReadTypeDefRowWithExtents ctxt i), (fun r -> r), (fun (_, ((_, _, _, _, _, methodsIdx), - (_, endMethodsIdx))) -> + (_, endMethodsIdx))) -> if endMethodsIdx <= idx then 1 elif methodsIdx <= idx && idx < endMethodsIdx then 0 else -1), @@ -2326,11 +2327,11 @@ and seekReadMethodDefAsMethodDataUncached ctxtH idx = MethodData(enclTy, cc, nm, argtys, retty, minst) -and seekReadFieldDefAsFieldSpec (ctxt: ILMetadataReader) idx = +and seekReadFieldDefAsFieldSpec (ctxt: ILMetadataReader) idx = ctxt.seekReadFieldDefAsFieldSpec idx and seekReadFieldDefAsFieldSpecUncached ctxtH idx = - let (ctxt: ILMetadataReader) = getHole ctxtH + let (ctxt: ILMetadataReader) = getHole ctxtH let mdv = ctxt.mdfile.GetView() let (_flags, nameIdx, typeIdx) = seekReadFieldRow ctxt mdv idx let nm = readStringHeap ctxt nameIdx @@ -2339,7 +2340,7 @@ and seekReadFieldDefAsFieldSpecUncached ctxtH idx = seekReadIndexedRow (ctxt.getNumRows TableNames.TypeDef, (fun i -> i, seekReadTypeDefRowWithExtents ctxt i), (fun r -> r), - (fun (_, ((_, _, _, _, fieldsIdx, _), (endFieldsIdx, _))) -> + (fun (_, ((_, _, _, _, fieldsIdx, _), (endFieldsIdx, _))) -> if endFieldsIdx <= idx then 1 elif fieldsIdx <= idx && idx < endFieldsIdx then 0 else -1), @@ -2356,7 +2357,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 @@ -2408,14 +2409,14 @@ and seekReadMethod (ctxt: ILMetadataReader) mdv numtypars (idx: int) = metadataIndex=idx) -and seekReadParams (ctxt: ILMetadataReader) mdv (retty, argtys) pidx1 pidx2 = +and seekReadParams (ctxt: ILMetadataReader) mdv (retty, argtys) pidx1 pidx2 = let retRes = ref (mkILReturn retty) let paramsRes = argtys |> List.toArray |> Array.map mkILParamAnon for i = pidx1 to pidx2 - 1 do 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 @@ -2439,7 +2440,7 @@ and seekReadParamExtras (ctxt: ILMetadataReader) mdv (retRes, paramsRes) (idx: CustomAttrsStored = ctxt.customAttrsReader_ParamDef MetadataIndex = idx } -and seekReadMethodImpls (ctxt: ILMetadataReader) numtypars tidx = +and seekReadMethodImpls (ctxt: ILMetadataReader) numtypars tidx = mkILMethodImplsLazy (lazy let mdv = ctxt.mdfile.GetView() @@ -2453,9 +2454,9 @@ and seekReadMethodImpls (ctxt: ILMetadataReader) numtypars tidx = let mspec = mkILMethSpecInTy (enclTy, cc, nm, argtys, retty, minst) OverridesSpec(mspec.MethodRef, mspec.DeclaringType) })) -and seekReadMultipleMethodSemantics (ctxt: ILMetadataReader) (flags, id) = +and seekReadMultipleMethodSemantics (ctxt: ILMetadataReader) (flags, id) = seekReadIndexedRows - (ctxt.getNumRows TableNames.MethodSemantics , + (ctxt.getNumRows TableNames.MethodSemantics, seekReadMethodSemanticsRow ctxt, (fun (_flags, _, c) -> c), hsCompare id, @@ -2491,7 +2492,7 @@ and seekReadEvent ctxt mdv numtypars idx = metadataIndex = idx ) (* REVIEW: can substantially reduce numbers of EventMap and PropertyMap reads by first checking if the whole table mdv sorted according to ILTypeDef tokens and then doing a binary chop *) -and seekReadEvents (ctxt: ILMetadataReader) numtypars tidx = +and seekReadEvents (ctxt: ILMetadataReader) numtypars tidx = mkILEventsLazy (lazy let mdv = ctxt.mdfile.GetView() @@ -2520,7 +2521,7 @@ and seekReadProperty ctxt mdv numtypars idx = | Some mref -> mref.CallingConv.ThisConv | None -> match setter with - | Some mref -> mref.CallingConv .ThisConv + | Some mref -> mref.CallingConv .ThisConv | None -> cc ILPropertyDef(name=readStringHeap ctxt nameIdx, @@ -2534,7 +2535,7 @@ and seekReadProperty ctxt mdv numtypars idx = customAttrsStored=ctxt.customAttrsReader_Property, metadataIndex = idx ) -and seekReadProperties (ctxt: ILMetadataReader) numtypars tidx = +and seekReadProperties (ctxt: ILMetadataReader) numtypars tidx = mkILPropertiesLazy (lazy let mdv = ctxt.mdfile.GetView() @@ -2592,7 +2593,7 @@ and seekReadSecurityDecl ctxt (act, ty) = ILSecurityDecl ((if List.memAssoc (int act) (Lazy.force ILSecurityActionRevMap) then List.assoc (int act) (Lazy.force ILSecurityActionRevMap) else failwith "unknown security action"), readBlobHeap ctxt ty) -and seekReadConstant (ctxt: ILMetadataReader) idx = +and seekReadConstant (ctxt: ILMetadataReader) idx = let kind, vidx = seekReadIndexedRow (ctxt.getNumRows TableNames.Constant, seekReadConstantRow ctxt, (fun (_, key, _) -> key), @@ -2614,10 +2615,10 @@ and seekReadConstant (ctxt: ILMetadataReader) idx = | x when x = uint16 et_U8 -> ILFieldInit.UInt64 (readBlobHeapAsUInt64 ctxt vidx) | x when x = uint16 et_R4 -> ILFieldInit.Single (readBlobHeapAsSingle ctxt vidx) | x when x = uint16 et_R8 -> ILFieldInit.Double (readBlobHeapAsDouble ctxt vidx) - | x when x = uint16 et_CLASS || x = uint16 et_OBJECT -> ILFieldInit.Null + | x when x = uint16 et_CLASS || x = uint16 et_OBJECT -> ILFieldInit.Null | _ -> ILFieldInit.Null -and seekReadImplMap (ctxt: ILMetadataReader) nm midx = +and seekReadImplMap (ctxt: ILMetadataReader) nm midx = mkMethBodyLazyAux (lazy let mdv = ctxt.mdfile.GetView() @@ -2671,7 +2672,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 = @@ -2717,7 +2718,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start // Insert any sequence points into the instruction sequence while (match !seqPointsRemaining with - | (i, _tag) :: _rest when i <= !curr -> true + | (i, _tag) :: _rest when i <= !curr -> true | _ -> false) do // Emitting one sequence point @@ -2725,7 +2726,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start seqPointsRemaining := List.tail !seqPointsRemaining ibuf.Add (I_seqpoint tag) - // Read the prefixes. Leave lastb and lastb2 holding the instruction byte(s) + // Read the prefixes. Leave lastb and lastb2 holding the instruction byte(s) begin prefixes.al <- Aligned prefixes.tl <- Normalcall @@ -2748,7 +2749,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start if unal = 0x1 then Unaligned1 elif unal = 0x2 then Unaligned2 elif unal = 0x4 then Unaligned4 - else (dprintn "bad alignment for unaligned"; Aligned) + else (dprintn "bad alignment for unaligned"; Aligned) elif !b = (i_volatile &&& 0xff) then prefixes.vol <- Volatile elif !b = (i_readonly &&& 0xff) then prefixes.ro <- ReadonlyAddress elif !b = (i_constrained &&& 0xff) then @@ -2814,7 +2815,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start let (tab, idx) = seekReadUncodedToken pev (start + (!curr)) curr := !curr + 4 - let (VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, minst)) = + let (VarArgMethodData(enclTy, cc, nm, argtys, varargs, retty, minst)) = if tab = TableNames.Method then seekReadMethodDefOrRef ctxt numtypars (TaggedIndex(mdor_MethodDef, idx)) elif tab = TableNames.MemberRef then @@ -2826,9 +2827,9 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start | ILType.Array (shape, ty) -> match nm with | "Get" -> I_ldelem_any(shape, ty) - | "Set" -> I_stelem_any(shape, ty) - | "Address" -> I_ldelema(prefixes.ro, false, shape, ty) - | ".ctor" -> I_newarr(shape, ty) + | "Set" -> I_stelem_any(shape, ty) + | "Address" -> I_ldelema(prefixes.ro, false, shape, ty) + | ".ctor" -> I_newarr(shape, ty) | _ -> failwith "bad method on array type" | _ -> let mspec = mkILMethSpecInTy (enclTy, cc, nm, argtys, retty, minst) @@ -2845,7 +2846,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start f prefixes (readUserStringHeap ctxt (idx)) | I_conditional_i32_instr f -> - let offsDest = (seekReadInt32 pev (start + (!curr))) + let offsDest = (seekReadInt32 pev (start + (!curr))) curr := !curr + 4 let dest = !curr + offsDest f prefixes (rawToLabel dest) @@ -2855,7 +2856,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start let dest = !curr + offsDest f prefixes (rawToLabel dest) | I_unconditional_i32_instr f -> - let offsDest = (seekReadInt32 pev (start + (!curr))) + let offsDest = (seekReadInt32 pev (start + (!curr))) curr := !curr + 4 let dest = !curr + offsDest f prefixes (rawToLabel dest) @@ -2877,7 +2878,7 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start ILToken.ILMethod (mkILMethSpecInTy (enclTy, cc, nm, argtys, retty, minst)) elif tab = TableNames.Field then ILToken.ILField (seekReadFieldDefAsFieldSpec ctxt idx) - elif tab = TableNames.TypeDef || tab = TableNames.TypeRef || tab = TableNames.TypeSpec then + elif tab = TableNames.TypeDef || tab = TableNames.TypeRef || tab = TableNames.TypeSpec then ILToken.ILType (seekReadTypeDefOrRef ctxt numtypars AsObject [] (uncodedTokenToTypeDefOrRefOrSpec (tab, idx))) else failwith "bad token for ldtoken" f prefixes token_info @@ -2889,11 +2890,11 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start if generic then failwith "bad image: a generic method signature is begin used at a calli instruction" f prefixes (mkILCallSig (cc, argtys, retty), varargs) | I_switch_instr f -> - let n = (seekReadInt32 pev (start + (!curr))) + let n = (seekReadInt32 pev (start + (!curr))) curr := !curr + 4 let offsets = List.init n (fun _ -> - let i = (seekReadInt32 pev (start + (!curr))) + let i = (seekReadInt32 pev (start + (!curr))) curr := !curr + 4 i) let dests = List.map (fun offs -> rawToLabel (!curr + offs)) offsets @@ -2906,16 +2907,16 @@ and seekReadTopCode (ctxt: ILMetadataReader) pev mdv numtypars (sz: int) start let lab2pc = ilOffsetsOfLabels // Some offsets used in debug info refer to the end of an instruction, rather than the - // start of the subsequent instruction. But all labels refer to instruction starts, - // apart from a final label which refers to the end of the method. This function finds + // start of the subsequent instruction. But all labels refer to instruction starts, + // apart from a final label which refers to the end of the method. This function finds // the start of the next instruction referred to by the raw offset. let raw2nextLab rawOffset = let isInstrStart x = match tryRawToLabel x with | None -> false | Some lab -> ilOffsetsOfLabels.ContainsKey lab - if isInstrStart rawOffset then rawToLabel rawOffset - elif isInstrStart (rawOffset+1) then rawToLabel (rawOffset+1) + if isInstrStart rawOffset then rawToLabel rawOffset + elif isInstrStart (rawOffset+1) then rawToLabel (rawOffset+1) else failwith ("the bytecode raw offset "+string rawOffset+" did not refer either to the start or end of an instruction") let instrs = ibuf.ToArray() instrs, rawToLabel, lab2pc, raw2nextLab @@ -2946,12 +2947,12 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int let pdbm = pdbReaderGetMethod pdbr (uncodedToken TableNames.Method idx) let sps = pdbMethodGetSequencePoints pdbm - (*dprintf "#sps for 0x%x = %d\n" (uncodedToken TableNames.Method idx) (Array.length sps) *) - (* let roota, rootb = pdbScopeGetOffsets rootScope in *) + (*dprintf "#sps for 0x%x = %d\n" (uncodedToken TableNames.Method idx) (Array.length sps) *) + (* let roota, rootb = pdbScopeGetOffsets rootScope in *) let seqpoints = let arr = sps |> Array.map (fun sp -> - (* It is VERY annoying to have to call GetURL for the document for each sequence point. This appears to be a short coming of the PDB reader API. They should return an index into the array of documents for the reader *) + (* It is VERY annoying to have to call GetURL for the document for each sequence point. This appears to be a short coming of the PDB reader API. They should return an index into the array of documents for the reader *) let sourcedoc = get_doc (pdbDocumentGetURL sp.pdbSeqPointDocument) let source = ILSourceMarker.Create(document = sourcedoc, @@ -2966,7 +2967,7 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int Array.toList arr let rec scopes scp = let a, b = pdbScopeGetOffsets scp - let lvs = pdbScopeGetLocals scp + let lvs = pdbScopeGetLocals scp let ilvs = lvs |> Array.toList @@ -2977,7 +2978,7 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int ilvs |> List.map (fun ilv -> let _k, idx = pdbVariableGetAddressAttributes ilv let n = pdbVariableGetName ilv - { LocalIndex= idx + { LocalIndex= idx LocalName=n}) let thisOne = @@ -2986,8 +2987,8 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int DebugMappings = ilinfos }: ILLocalDebugInfo ) let others = List.foldBack (scopes >> (@)) (Array.toList (pdbScopeGetChildren scp)) [] thisOne :: others - let localPdbInfos = [] (* scopes fail for mscorlib scopes rootScope *) - // REVIEW: look through sps to get ranges? Use GetRanges?? Change AbsIL?? + let localPdbInfos = [] (* scopes fail for mscorlib scopes rootScope *) + // REVIEW: look through sps to get ranges? Use GetRanges?? Change AbsIL?? (localPdbInfos, None, seqpoints) with e -> // "* Warning: PDB info for method "+nm+" could not be read and will be ignored: "+e.Message @@ -2999,7 +3000,7 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int let b = seekReadByte pev baseRVA if (b &&& e_CorILMethod_FormatMask) = e_CorILMethod_TinyFormat then let codeBase = baseRVA + 1 - let codeSize = (int32 b >>>& 2) + let codeSize = (int32 b >>>& 2) // tiny format for "+nm+", code size = " + string codeSize) let instrs, _, lab2pc, raw2nextLab = seekReadTopCode ctxt pev mdv numtypars codeSize codeBase seqpoints (* Convert the linear code format to the nested code format *) @@ -3048,9 +3049,9 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int let clauses = if (sectionFlag &&& e_CorILMethod_Sect_EHTable) <> 0x0uy then // WORKAROUND: The ECMA spec says this should be - // let numClauses = ((bigSize - 4) / 24) in + // let numClauses = ((bigSize - 4) / 24) in // but the CCI IL generator generates multiples of 24 - let numClauses = (bigSize / 24) + let numClauses = (bigSize / 24) List.init numClauses (fun i -> let clauseBase = sectionBase + 4 + (i * 24) @@ -3068,9 +3069,9 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int let clauses = if (sectionFlag &&& e_CorILMethod_Sect_EHTable) <> 0x0uy then // WORKAROUND: The ECMA spec says this should be - // let numClauses = ((smallSize - 4) / 12) in + // let numClauses = ((smallSize - 4) / 12) in // but the C# compiler (or some IL generator) generates multiples of 12 - let numClauses = (smallSize / 12) + let numClauses = (smallSize / 12) // dprintn (nm+" has " + string numClauses + " tiny seh clauses") List.init numClauses (fun i -> let clauseBase = sectionBase + 4 + (i * 12) @@ -3112,12 +3113,12 @@ and seekReadMethodRVA (pectxt: PEReader) (ctxt: ILMetadataReader) (idx, nm, _int ILExceptionClause.Finally(handlerStart, handlerFinish) end - let key = (tryStart, tryFinish) + let key = (tryStart, tryFinish) match sehMap.TryGetValue(key) with | 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 +3142,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))) @@ -3162,24 +3163,24 @@ and sigptrGetILNativeType ctxt bytes sigptr = List.assoc ntbyte (Lazy.force ILNativeTypeMap), sigptr elif ntbyte = 0x0uy then ILNativeType.Empty, sigptr elif ntbyte = nt_CUSTOMMARSHALER then - // reading native type blob (CM1) , sigptr= "+string sigptr+ ", bytes.Length = "+string bytes.Length) + // reading native type blob (CM1), sigptr= "+string sigptr+ ", bytes.Length = "+string bytes.Length) let guidLen, sigptr = sigptrGetZInt32 bytes sigptr - // reading native type blob (CM2) , sigptr= "+string sigptr+", guidLen = "+string ( guidLen)) + // reading native type blob (CM2), sigptr= "+string sigptr+", guidLen = "+string ( guidLen)) let guid, sigptr = sigptrGetBytes ( guidLen) bytes sigptr - // reading native type blob (CM3) , sigptr= "+string sigptr) + // reading native type blob (CM3), sigptr= "+string sigptr) let nativeTypeNameLen, sigptr = sigptrGetZInt32 bytes sigptr - // reading native type blob (CM4) , sigptr= "+string sigptr+", nativeTypeNameLen = "+string ( nativeTypeNameLen)) + // reading native type blob (CM4), sigptr= "+string sigptr+", nativeTypeNameLen = "+string ( nativeTypeNameLen)) let nativeTypeName, sigptr = sigptrGetString ( nativeTypeNameLen) bytes sigptr - // reading native type blob (CM4) , sigptr= "+string sigptr+", nativeTypeName = "+nativeTypeName) - // reading native type blob (CM5) , sigptr= "+string sigptr) + // reading native type blob (CM4), sigptr= "+string sigptr+", nativeTypeName = "+nativeTypeName) + // reading native type blob (CM5), sigptr= "+string sigptr) let custMarshallerNameLen, sigptr = sigptrGetZInt32 bytes sigptr - // reading native type blob (CM6) , sigptr= "+string sigptr+", custMarshallerNameLen = "+string ( custMarshallerNameLen)) + // reading native type blob (CM6), sigptr= "+string sigptr+", custMarshallerNameLen = "+string ( custMarshallerNameLen)) let custMarshallerName, sigptr = sigptrGetString ( custMarshallerNameLen) bytes sigptr - // reading native type blob (CM7) , sigptr= "+string sigptr+", custMarshallerName = "+custMarshallerName) + // reading native type blob (CM7), sigptr= "+string sigptr+", custMarshallerName = "+custMarshallerName) let cookieStringLen, sigptr = sigptrGetZInt32 bytes sigptr - // reading native type blob (CM8) , sigptr= "+string sigptr+", cookieStringLen = "+string ( cookieStringLen)) + // reading native type blob (CM8), sigptr= "+string sigptr+", cookieStringLen = "+string ( cookieStringLen)) let cookieString, sigptr = sigptrGetBytes ( cookieStringLen) bytes sigptr - // reading native type blob (CM9) , sigptr= "+string sigptr) + // reading native type blob (CM9), sigptr= "+string sigptr) ILNativeType.Custom (guid, nativeTypeName, custMarshallerName, cookieString), sigptr elif ntbyte = nt_FIXEDSYSSTRING then let i, sigptr = sigptrGetZInt32 bytes sigptr @@ -3265,10 +3266,10 @@ and seekReadNestedExportedTypes ctxt (exported: _ []) (nested: Lazy<_ []>) paren | _ -> failwith "non-nested access for a nested type described as being in an auxiliary module") Nested = seekReadNestedExportedTypes ctxt exported nested i CustomAttrsStored = ctxt.customAttrsReader_ExportedType - MetadataIndex = i } + MetadataIndex = i } )) -and seekReadTopExportedTypes (ctxt: ILMetadataReader) = +and seekReadTopExportedTypes (ctxt: ILMetadataReader) = mkILExportedTypesLazy (lazy let mdv = ctxt.mdfile.GetView() @@ -3310,7 +3311,7 @@ let getPdbReader pdbDirPath fileName = let pdbdocs = pdbReaderGetDocuments pdbr let tab = new Dictionary<_, _>(Array.length pdbdocs) - pdbdocs |> Array.iter (fun pdbdoc -> + pdbdocs |> Array.iter (fun pdbdoc -> let url = pdbDocumentGetURL pdbdoc tab.[url] <- ILSourceDocument.Create(language=Some (pdbDocumentGetLanguage pdbdoc), @@ -3366,13 +3367,13 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p let findStream name = match tryFindStream name with | None -> (0x0, 0x0) - | Some positions -> positions + | Some positions -> positions let (tablesStreamPhysLoc, _tablesStreamSize) = match tryFindStream [| 0x23; 0x7e |] (* #~ *) with | Some res -> res | None -> - match tryFindStream [| 0x23; 0x2d |] (* #-: at least one DLL I've seen uses this! *) with + match tryFindStream [| 0x23; 0x2d |] (* #-: at least one DLL I've seen uses this! *) with | Some res -> res | None -> let firstStreamOffset = seekReadInt32 mdv (streamHeadersStart + 0) @@ -3385,70 +3386,70 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p let (blobsStreamPhysicalLoc, blobsStreamSize) = findStream [| 0x23; 0x42; 0x6c; 0x6f; 0x62; |] (* #Blob *) let tableKinds = - [|kindModule (* Table 0 *) - kindTypeRef (* Table 1 *) - kindTypeDef (* Table 2 *) - kindIllegal (* kindFieldPtr *) (* Table 3 *) - kindFieldDef (* Table 4 *) - kindIllegal (* kindMethodPtr *) (* Table 5 *) - kindMethodDef (* Table 6 *) - kindIllegal (* kindParamPtr *) (* Table 7 *) - kindParam (* Table 8 *) - kindInterfaceImpl (* Table 9 *) - kindMemberRef (* Table 10 *) - kindConstant (* Table 11 *) - kindCustomAttribute (* Table 12 *) - kindFieldMarshal (* Table 13 *) - kindDeclSecurity (* Table 14 *) - kindClassLayout (* Table 15 *) - kindFieldLayout (* Table 16 *) - kindStandAloneSig (* Table 17 *) - kindEventMap (* Table 18 *) - kindIllegal (* kindEventPtr *) (* Table 19 *) - kindEvent (* Table 20 *) - kindPropertyMap (* Table 21 *) - kindIllegal (* kindPropertyPtr *) (* Table 22 *) - kindProperty (* Table 23 *) - kindMethodSemantics (* Table 24 *) - kindMethodImpl (* Table 25 *) - kindModuleRef (* Table 26 *) - kindTypeSpec (* Table 27 *) - kindImplMap (* Table 28 *) - kindFieldRVA (* Table 29 *) - kindIllegal (* kindENCLog *) (* Table 30 *) - kindIllegal (* kindENCMap *) (* Table 31 *) - kindAssembly (* Table 32 *) - kindIllegal (* kindAssemblyProcessor *) (* Table 33 *) - kindIllegal (* kindAssemblyOS *) (* Table 34 *) - kindAssemblyRef (* Table 35 *) + [|kindModule (* Table 0 *) + kindTypeRef (* Table 1 *) + kindTypeDef (* Table 2 *) + kindIllegal (* kindFieldPtr *) (* Table 3 *) + kindFieldDef (* Table 4 *) + kindIllegal (* kindMethodPtr *) (* Table 5 *) + kindMethodDef (* Table 6 *) + kindIllegal (* kindParamPtr *) (* Table 7 *) + kindParam (* Table 8 *) + kindInterfaceImpl (* Table 9 *) + kindMemberRef (* Table 10 *) + kindConstant (* Table 11 *) + kindCustomAttribute (* Table 12 *) + kindFieldMarshal (* Table 13 *) + kindDeclSecurity (* Table 14 *) + kindClassLayout (* Table 15 *) + kindFieldLayout (* Table 16 *) + kindStandAloneSig (* Table 17 *) + kindEventMap (* Table 18 *) + kindIllegal (* kindEventPtr *) (* Table 19 *) + kindEvent (* Table 20 *) + kindPropertyMap (* Table 21 *) + kindIllegal (* kindPropertyPtr *) (* Table 22 *) + kindProperty (* Table 23 *) + kindMethodSemantics (* Table 24 *) + kindMethodImpl (* Table 25 *) + kindModuleRef (* Table 26 *) + kindTypeSpec (* Table 27 *) + kindImplMap (* Table 28 *) + kindFieldRVA (* Table 29 *) + kindIllegal (* kindENCLog *) (* Table 30 *) + kindIllegal (* kindENCMap *) (* Table 31 *) + kindAssembly (* Table 32 *) + kindIllegal (* kindAssemblyProcessor *) (* Table 33 *) + kindIllegal (* kindAssemblyOS *) (* Table 34 *) + kindAssemblyRef (* Table 35 *) kindIllegal (* kindAssemblyRefProcessor *) (* Table 36 *) - kindIllegal (* kindAssemblyRefOS *) (* Table 37 *) - kindFileRef (* Table 38 *) - kindExportedType (* Table 39 *) - kindManifestResource (* Table 40 *) - kindNested (* Table 41 *) - kindGenericParam_v2_0 (* Table 42 *) - kindMethodSpec (* Table 43 *) - kindGenericParamConstraint (* Table 44 *) - kindIllegal (* Table 45 *) - kindIllegal (* Table 46 *) - kindIllegal (* Table 47 *) - kindIllegal (* Table 48 *) - kindIllegal (* Table 49 *) - kindIllegal (* Table 50 *) - kindIllegal (* Table 51 *) - kindIllegal (* Table 52 *) - kindIllegal (* Table 53 *) - kindIllegal (* Table 54 *) - kindIllegal (* Table 55 *) - kindIllegal (* Table 56 *) - kindIllegal (* Table 57 *) - kindIllegal (* Table 58 *) - kindIllegal (* Table 59 *) - kindIllegal (* Table 60 *) - kindIllegal (* Table 61 *) - kindIllegal (* Table 62 *) - kindIllegal (* Table 63 *) + kindIllegal (* kindAssemblyRefOS *) (* Table 37 *) + kindFileRef (* Table 38 *) + kindExportedType (* Table 39 *) + kindManifestResource (* Table 40 *) + kindNested (* Table 41 *) + kindGenericParam_v2_0 (* Table 42 *) + kindMethodSpec (* Table 43 *) + kindGenericParamConstraint (* Table 44 *) + kindIllegal (* Table 45 *) + kindIllegal (* Table 46 *) + kindIllegal (* Table 47 *) + kindIllegal (* Table 48 *) + kindIllegal (* Table 49 *) + kindIllegal (* Table 50 *) + kindIllegal (* Table 51 *) + kindIllegal (* Table 52 *) + kindIllegal (* Table 53 *) + kindIllegal (* Table 54 *) + kindIllegal (* Table 55 *) + kindIllegal (* Table 56 *) + kindIllegal (* Table 57 *) + kindIllegal (* Table 58 *) + kindIllegal (* Table 59 *) + kindIllegal (* Table 60 *) + kindIllegal (* Table 61 *) + kindIllegal (* Table 62 *) + kindIllegal (* Table 63 *) |] let heapSizes = seekReadByteAsInt32 mdv (tablesStreamPhysLoc + 6) @@ -3459,9 +3460,9 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p let numRows = Array.create 64 0 let prevNumRowIdx = ref (tablesStreamPhysLoc + 24) for i = 0 to 63 do - if (valid &&& (int64 1 <<< i)) <> int64 0 then + if (valid &&& (int64 1 <<< i)) <> int64 0 then present := i :: !present - numRows.[i] <- (seekReadInt32 mdv !prevNumRowIdx) + numRows.[i] <- (seekReadInt32 mdv !prevNumRowIdx) prevNumRowIdx := !prevNumRowIdx + 4 List.rev !present, numRows, !prevNumRowIdx @@ -3498,7 +3499,7 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p let hcaBigness = codedBigness 5 TableNames.Method || codedBigness 5 TableNames.Field || - codedBigness 5 TableNames.TypeRef || + codedBigness 5 TableNames.TypeRef || codedBigness 5 TableNames.TypeDef || codedBigness 5 TableNames.Param || codedBigness 5 TableNames.InterfaceImpl || @@ -3559,7 +3560,7 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p let rsBigness = codedBigness 2 TableNames.Module || codedBigness 2 TableNames.ModuleRef || - codedBigness 2 TableNames.AssemblyRef || + codedBigness 2 TableNames.AssemblyRef || codedBigness 2 TableNames.TypeRef let rowKindSize (RowKind kinds) = @@ -3570,20 +3571,20 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p | Byte -> 1 | Data -> 4 | GGuid -> (if guidsBigness then 4 else 2) - | Blob -> (if blobsBigness then 4 else 2) - | SString -> (if stringsBigness then 4 else 2) + | Blob -> (if blobsBigness then 4 else 2) + | SString -> (if stringsBigness then 4 else 2) | SimpleIndex tab -> (if tableBigness.[tab.Index] then 4 else 2) | TypeDefOrRefOrSpec -> (if tdorBigness then 4 else 2) | TypeOrMethodDef -> (if tomdBigness then 4 else 2) - | HasConstant -> (if hcBigness then 4 else 2) + | HasConstant -> (if hcBigness then 4 else 2) | HasCustomAttribute -> (if hcaBigness then 4 else 2) - | HasFieldMarshal -> (if hfmBigness then 4 else 2) - | HasDeclSecurity -> (if hdsBigness then 4 else 2) - | MemberRefParent -> (if mrpBigness then 4 else 2) - | HasSemantics -> (if hsBigness then 4 else 2) + | HasFieldMarshal -> (if hfmBigness then 4 else 2) + | HasDeclSecurity -> (if hdsBigness then 4 else 2) + | MemberRefParent -> (if mrpBigness then 4 else 2) + | HasSemantics -> (if hsBigness then 4 else 2) | MethodDefOrRef -> (if mdorBigness then 4 else 2) | MemberForwarded -> (if mfBigness then 4 else 2) - | Implementation -> (if iBigness then 4 else 2) + | Implementation -> (if iBigness then 4 else 2) | CustomAttributeType -> (if catBigness then 4 else 2) | ResolutionScope -> (if rsBigness then 4 else 2)) @@ -3599,33 +3600,33 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p let inbase = Filename.fileNameOfPath fileName + ": " - // All the caches. The sizes are guesstimates for the rough sharing-density of the assembly - let cacheAssemblyRef = mkCacheInt32 reduceMemoryUsage inbase "ILAssemblyRef" (getNumRows TableNames.AssemblyRef) - let cacheMethodSpecAsMethodData = mkCacheGeneric reduceMemoryUsage inbase "MethodSpecAsMethodData" (getNumRows TableNames.MethodSpec / 20 + 1) - let cacheMemberRefAsMemberData = mkCacheGeneric reduceMemoryUsage inbase "MemberRefAsMemberData" (getNumRows TableNames.MemberRef / 20 + 1) - let cacheCustomAttr = mkCacheGeneric reduceMemoryUsage inbase "CustomAttr" (getNumRows TableNames.CustomAttribute / 50 + 1) - let cacheTypeRef = mkCacheInt32 reduceMemoryUsage inbase "ILTypeRef" (getNumRows TableNames.TypeRef / 20 + 1) - let cacheTypeRefAsType = mkCacheGeneric reduceMemoryUsage inbase "TypeRefAsType" (getNumRows TableNames.TypeRef / 20 + 1) - let cacheBlobHeapAsPropertySig = mkCacheGeneric reduceMemoryUsage inbase "BlobHeapAsPropertySig" (getNumRows TableNames.Property / 20 + 1) - let cacheBlobHeapAsFieldSig = mkCacheGeneric reduceMemoryUsage inbase "BlobHeapAsFieldSig" (getNumRows TableNames.Field / 20 + 1) - let cacheBlobHeapAsMethodSig = mkCacheGeneric reduceMemoryUsage inbase "BlobHeapAsMethodSig" (getNumRows TableNames.Method / 20 + 1) - let cacheTypeDefAsType = mkCacheGeneric reduceMemoryUsage inbase "TypeDefAsType" (getNumRows TableNames.TypeDef / 20 + 1) - let cacheMethodDefAsMethodData = mkCacheInt32 reduceMemoryUsage inbase "MethodDefAsMethodData" (getNumRows TableNames.Method / 20 + 1) - let cacheGenericParams = mkCacheGeneric reduceMemoryUsage inbase "GenericParams" (getNumRows TableNames.GenericParam / 20 + 1) - let cacheFieldDefAsFieldSpec = mkCacheInt32 reduceMemoryUsage inbase "FieldDefAsFieldSpec" (getNumRows TableNames.Field / 20 + 1) - let cacheUserStringHeap = mkCacheInt32 reduceMemoryUsage inbase "UserStringHeap" ( userStringsStreamSize / 20 + 1) + // All the caches. The sizes are guesstimates for the rough sharing-density of the assembly + let cacheAssemblyRef = mkCacheInt32 reduceMemoryUsage inbase "ILAssemblyRef" (getNumRows TableNames.AssemblyRef) + let cacheMethodSpecAsMethodData = mkCacheGeneric reduceMemoryUsage inbase "MethodSpecAsMethodData" (getNumRows TableNames.MethodSpec / 20 + 1) + let cacheMemberRefAsMemberData = mkCacheGeneric reduceMemoryUsage inbase "MemberRefAsMemberData" (getNumRows TableNames.MemberRef / 20 + 1) + let cacheCustomAttr = mkCacheGeneric reduceMemoryUsage inbase "CustomAttr" (getNumRows TableNames.CustomAttribute / 50 + 1) + let cacheTypeRef = mkCacheInt32 reduceMemoryUsage inbase "ILTypeRef" (getNumRows TableNames.TypeRef / 20 + 1) + let cacheTypeRefAsType = mkCacheGeneric reduceMemoryUsage inbase "TypeRefAsType" (getNumRows TableNames.TypeRef / 20 + 1) + let cacheBlobHeapAsPropertySig = mkCacheGeneric reduceMemoryUsage inbase "BlobHeapAsPropertySig" (getNumRows TableNames.Property / 20 + 1) + let cacheBlobHeapAsFieldSig = mkCacheGeneric reduceMemoryUsage inbase "BlobHeapAsFieldSig" (getNumRows TableNames.Field / 20 + 1) + let cacheBlobHeapAsMethodSig = mkCacheGeneric reduceMemoryUsage inbase "BlobHeapAsMethodSig" (getNumRows TableNames.Method / 20 + 1) + let cacheTypeDefAsType = mkCacheGeneric reduceMemoryUsage inbase "TypeDefAsType" (getNumRows TableNames.TypeDef / 20 + 1) + let cacheMethodDefAsMethodData = mkCacheInt32 reduceMemoryUsage inbase "MethodDefAsMethodData" (getNumRows TableNames.Method / 20 + 1) + let cacheGenericParams = mkCacheGeneric reduceMemoryUsage inbase "GenericParams" (getNumRows TableNames.GenericParam / 20 + 1) + let cacheFieldDefAsFieldSpec = mkCacheInt32 reduceMemoryUsage inbase "FieldDefAsFieldSpec" (getNumRows TableNames.Field / 20 + 1) + let cacheUserStringHeap = mkCacheInt32 reduceMemoryUsage inbase "UserStringHeap" ( userStringsStreamSize / 20 + 1) // nb. Lots and lots of cache hits on this cache, hence never optimize cache away - let cacheStringHeap = mkCacheInt32 false inbase "string heap" ( stringsStreamSize / 50 + 1) - let cacheBlobHeap = mkCacheInt32 reduceMemoryUsage inbase "blob heap" ( blobsStreamSize / 50 + 1) + let cacheStringHeap = mkCacheInt32 false inbase "string heap" ( stringsStreamSize / 50 + 1) + let cacheBlobHeap = mkCacheInt32 reduceMemoryUsage inbase "blob heap" ( blobsStreamSize / 50 + 1) // These tables are not required to enforce sharing fo the final data // structure, but are very useful as searching these tables gives rise to many reads // in standard applications. - let cacheNestedRow = mkCacheInt32 reduceMemoryUsage inbase "Nested Table Rows" (getNumRows TableNames.Nested / 20 + 1) - let cacheConstantRow = mkCacheInt32 reduceMemoryUsage inbase "Constant Rows" (getNumRows TableNames.Constant / 20 + 1) + let cacheNestedRow = mkCacheInt32 reduceMemoryUsage inbase "Nested Table Rows" (getNumRows TableNames.Nested / 20 + 1) + let cacheConstantRow = mkCacheInt32 reduceMemoryUsage inbase "Constant Rows" (getNumRows TableNames.Constant / 20 + 1) 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 cacheTypeDefRow = mkCacheInt32 reduceMemoryUsage inbase "ILTypeDef Rows" (getNumRows TableNames.TypeDef / 20 + 1) let rowAddr (tab: TableName) idx = tablePhysLocations.[tab.Index] + (idx - 1) * tableRowSizes.[tab.Index] @@ -3641,33 +3642,33 @@ let openMetadataReader (fileName, mdfile: BinaryFile, metadataPhysLoc, peinfo, p pectxtCaptured=pectxtCaptured entryPointToken=pectxtEager.entryPointToken fileName=fileName - userStringsStreamPhysicalLoc = userStringsStreamPhysicalLoc - stringsStreamPhysicalLoc = stringsStreamPhysicalLoc - blobsStreamPhysicalLoc = blobsStreamPhysicalLoc - blobsStreamSize = blobsStreamSize - memoizeString = Tables.memoize id - readUserStringHeap = cacheUserStringHeap (readUserStringHeapUncached ctxtH) - readStringHeap = cacheStringHeap (readStringHeapUncached ctxtH) - readBlobHeap = cacheBlobHeap (readBlobHeapUncached ctxtH) - seekReadNestedRow = cacheNestedRow (seekReadNestedRowUncached ctxtH) - seekReadConstantRow = cacheConstantRow (seekReadConstantRowUncached ctxtH) - seekReadMethodSemanticsRow = cacheMethodSemanticsRow (seekReadMethodSemanticsRowUncached ctxtH) - seekReadTypeDefRow = cacheTypeDefRow (seekReadTypeDefRowUncached ctxtH) - seekReadAssemblyRef = cacheAssemblyRef (seekReadAssemblyRefUncached ctxtH) - seekReadMethodSpecAsMethodData = cacheMethodSpecAsMethodData (seekReadMethodSpecAsMethodDataUncached ctxtH) - seekReadMemberRefAsMethodData = cacheMemberRefAsMemberData (seekReadMemberRefAsMethodDataUncached ctxtH) - seekReadMemberRefAsFieldSpec = seekReadMemberRefAsFieldSpecUncached ctxtH - seekReadCustomAttr = cacheCustomAttr (seekReadCustomAttrUncached ctxtH) - seekReadTypeRef = cacheTypeRef (seekReadTypeRefUncached ctxtH) - readBlobHeapAsPropertySig = cacheBlobHeapAsPropertySig (readBlobHeapAsPropertySigUncached ctxtH) - readBlobHeapAsFieldSig = cacheBlobHeapAsFieldSig (readBlobHeapAsFieldSigUncached ctxtH) - readBlobHeapAsMethodSig = cacheBlobHeapAsMethodSig (readBlobHeapAsMethodSigUncached ctxtH) - readBlobHeapAsLocalsSig = readBlobHeapAsLocalsSigUncached ctxtH - seekReadTypeDefAsType = cacheTypeDefAsType (seekReadTypeDefAsTypeUncached ctxtH) - seekReadTypeRefAsType = cacheTypeRefAsType (seekReadTypeRefAsTypeUncached ctxtH) - seekReadMethodDefAsMethodData = cacheMethodDefAsMethodData (seekReadMethodDefAsMethodDataUncached ctxtH) - seekReadGenericParams = cacheGenericParams (seekReadGenericParamsUncached ctxtH) - seekReadFieldDefAsFieldSpec = cacheFieldDefAsFieldSpec (seekReadFieldDefAsFieldSpecUncached ctxtH) + userStringsStreamPhysicalLoc = userStringsStreamPhysicalLoc + stringsStreamPhysicalLoc = stringsStreamPhysicalLoc + blobsStreamPhysicalLoc = blobsStreamPhysicalLoc + blobsStreamSize = blobsStreamSize + memoizeString = Tables.memoize id + readUserStringHeap = cacheUserStringHeap (readUserStringHeapUncached ctxtH) + readStringHeap = cacheStringHeap (readStringHeapUncached ctxtH) + readBlobHeap = cacheBlobHeap (readBlobHeapUncached ctxtH) + seekReadNestedRow = cacheNestedRow (seekReadNestedRowUncached ctxtH) + seekReadConstantRow = cacheConstantRow (seekReadConstantRowUncached ctxtH) + seekReadMethodSemanticsRow = cacheMethodSemanticsRow (seekReadMethodSemanticsRowUncached ctxtH) + seekReadTypeDefRow = cacheTypeDefRow (seekReadTypeDefRowUncached ctxtH) + seekReadAssemblyRef = cacheAssemblyRef (seekReadAssemblyRefUncached ctxtH) + seekReadMethodSpecAsMethodData = cacheMethodSpecAsMethodData (seekReadMethodSpecAsMethodDataUncached ctxtH) + seekReadMemberRefAsMethodData = cacheMemberRefAsMemberData (seekReadMemberRefAsMethodDataUncached ctxtH) + seekReadMemberRefAsFieldSpec = seekReadMemberRefAsFieldSpecUncached ctxtH + seekReadCustomAttr = cacheCustomAttr (seekReadCustomAttrUncached ctxtH) + seekReadTypeRef = cacheTypeRef (seekReadTypeRefUncached ctxtH) + readBlobHeapAsPropertySig = cacheBlobHeapAsPropertySig (readBlobHeapAsPropertySigUncached ctxtH) + readBlobHeapAsFieldSig = cacheBlobHeapAsFieldSig (readBlobHeapAsFieldSigUncached ctxtH) + readBlobHeapAsMethodSig = cacheBlobHeapAsMethodSig (readBlobHeapAsMethodSigUncached ctxtH) + readBlobHeapAsLocalsSig = readBlobHeapAsLocalsSigUncached ctxtH + seekReadTypeDefAsType = cacheTypeDefAsType (seekReadTypeDefAsTypeUncached ctxtH) + seekReadTypeRefAsType = cacheTypeRefAsType (seekReadTypeRefAsTypeUncached ctxtH) + seekReadMethodDefAsMethodData = cacheMethodDefAsMethodData (seekReadMethodDefAsMethodDataUncached ctxtH) + seekReadGenericParams = cacheGenericParams (seekReadGenericParamsUncached ctxtH) + seekReadFieldDefAsFieldSpec = cacheFieldDefAsFieldSpec (seekReadFieldDefAsFieldSpecUncached ctxtH) customAttrsReader_Module = customAttrsReader ctxtH hca_Module customAttrsReader_Assembly = customAttrsReader ctxtH hca_Assembly customAttrsReader_TypeDef = customAttrsReader ctxtH hca_TypeDef @@ -3723,17 +3724,17 @@ let openPEFileReader (fileName, pefile: BinaryFile, pdbDirPath, noFileOnDisk) = let peFileHeaderPhysLoc = peSignaturePhysLoc + 0x04 let peOptionalHeaderPhysLoc = peFileHeaderPhysLoc + 0x14 let peSignature = seekReadInt32 pev (peSignaturePhysLoc + 0) - if peSignature <> 0x4550 then failwithf "not a PE file - bad magic PE number 0x%08x, is = %A" peSignature pev + if peSignature <> 0x4550 then failwithf "not a PE file - bad magic PE number 0x%08x, is = %A" peSignature pev (* PE SIGNATURE *) let machine = seekReadUInt16AsInt32 pev (peFileHeaderPhysLoc + 0) let numSections = seekReadUInt16AsInt32 pev (peFileHeaderPhysLoc + 2) let optHeaderSize = seekReadUInt16AsInt32 pev (peFileHeaderPhysLoc + 16) - if optHeaderSize <> 0xe0 && + if optHeaderSize <> 0xe0 && optHeaderSize <> 0xf0 then failwith "not a PE file - bad optional header size" let x64adjust = optHeaderSize - 0xe0 - let only64 = (optHeaderSize = 0xf0) (* May want to read in the optional header Magic number and check that as well... *) + let only64 = (optHeaderSize = 0xf0) (* May want to read in the optional header Magic number and check that as well... *) let platform = match machine with | 0x8664 -> Some(AMD64) | 0x200 -> Some(IA64) | _ -> Some(X86) let sectionHeadersStartPhysLoc = peOptionalHeaderPhysLoc + optHeaderSize @@ -3741,30 +3742,30 @@ let openPEFileReader (fileName, pefile: BinaryFile, pdbDirPath, noFileOnDisk) = let isDll = (flags &&& 0x2000) <> 0x0 (* OPTIONAL PE HEADER *) - let _textPhysSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 4) (* Size of the code (text) section, or the sum of all code sections if there are multiple sections. *) + let _textPhysSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 4) (* Size of the code (text) section, or the sum of all code sections if there are multiple sections. *) (* x86: 000000a0 *) - let _initdataPhysSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 8) (* Size of the initialized data section, or the sum of all such sections if there are multiple data sections. *) + let _initdataPhysSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 8) (* Size of the initialized data section, or the sum of all such sections if there are multiple data sections. *) let _uninitdataPhysSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 12) (* Size of the uninitialized data section, or the sum of all such sections if there are multiple data sections. *) - let _entrypointAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 16) (* RVA of entry point , needs to point to bytes 0xFF 0x25 followed by the RVA+!0x4000000 in a section marked execute/read for EXEs or 0 for DLLs e.g. 0x0000b57e *) - let _textAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 20) (* e.g. 0x0002000 *) + let _entrypointAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 16) (* RVA of entry point, needs to point to bytes 0xFF 0x25 followed by the RVA+!0x4000000 in a section marked execute/read for EXEs or 0 for DLLs e.g. 0x0000b57e *) + let _textAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 20) (* e.g. 0x0002000 *) (* x86: 000000b0 *) - let dataSegmentAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 24) (* e.g. 0x0000c000 *) - (* REVIEW: For now, we'll use the DWORD at offset 24 for x64. This currently ok since fsc doesn't support true 64-bit image bases, + let dataSegmentAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 24) (* e.g. 0x0000c000 *) + (* REVIEW: For now, we'll use the DWORD at offset 24 for x64. This currently ok since fsc doesn't support true 64-bit image bases, but we'll have to fix this up when such support is added. *) let imageBaseReal = if only64 then dataSegmentAddr else seekReadInt32 pev (peOptionalHeaderPhysLoc + 28) // Image Base Always 0x400000 (see Section 23.1). - let alignVirt = seekReadInt32 pev (peOptionalHeaderPhysLoc + 32) // Section Alignment Always 0x2000 (see Section 23.1). - let alignPhys = seekReadInt32 pev (peOptionalHeaderPhysLoc + 36) // File Alignment Either 0x200 or 0x1000. + let alignVirt = seekReadInt32 pev (peOptionalHeaderPhysLoc + 32) // Section Alignment Always 0x2000 (see Section 23.1). + let alignPhys = seekReadInt32 pev (peOptionalHeaderPhysLoc + 36) // File Alignment Either 0x200 or 0x1000. (* x86: 000000c0 *) - let _osMajor = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 40) // OS Major Always 4 (see Section 23.1). - let _osMinor = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 42) // OS Minor Always 0 (see Section 23.1). - let _userMajor = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 44) // User Major Always 0 (see Section 23.1). - let _userMinor = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 46) // User Minor Always 0 (see Section 23.1). + let _osMajor = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 40) // OS Major Always 4 (see Section 23.1). + let _osMinor = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 42) // OS Minor Always 0 (see Section 23.1). + let _userMajor = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 44) // User Major Always 0 (see Section 23.1). + let _userMinor = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 46) // User Minor Always 0 (see Section 23.1). let subsysMajor = seekReadUInt16AsInt32 pev (peOptionalHeaderPhysLoc + 48) // SubSys Major Always 4 (see Section 23.1). let subsysMinor = seekReadUInt16AsInt32 pev (peOptionalHeaderPhysLoc + 50) // SubSys Minor Always 0 (see Section 23.1). (* x86: 000000d0 *) - let _imageEndAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 56) // Image Size: Size, in bytes, of image, including all headers and padding + let _imageEndAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 56) // Image Size: Size, in bytes, of image, including all headers and padding let _headerPhysSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 60) // Header Size Combined size of MS-DOS Header, PE Header, PE Optional Header and padding - let subsys = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 68) // SubSystem Subsystem required to run this image. + let subsys = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 68) // SubSystem Subsystem required to run this image. let useHighEnthropyVA = let n = seekReadUInt16 pev (peOptionalHeaderPhysLoc + 70) let highEnthropyVA = 0x20us @@ -3773,29 +3774,29 @@ let openPEFileReader (fileName, pefile: BinaryFile, pdbDirPath, noFileOnDisk) = (* x86: 000000e0 *) (* WARNING: THESE ARE 64 bit ON x64/ia64 *) - (* REVIEW: If we ever decide that we need these values for x64, we'll have to read them in as 64bit and fix up the rest of the offsets. + (* REVIEW: If we ever decide that we need these values for x64, we'll have to read them in as 64bit and fix up the rest of the offsets. Then again, it should suffice to just use the defaults, and still not bother... *) - (* let stackReserve = seekReadInt32 is (peOptionalHeaderPhysLoc + 72) in *) (* Stack Reserve Size Always 0x100000 (1Mb) (see Section 23.1). *) - (* let stackCommit = seekReadInt32 is (peOptionalHeaderPhysLoc + 76) in *) (* Stack Commit Size Always 0x1000 (4Kb) (see Section 23.1). *) - (* let heapReserve = seekReadInt32 is (peOptionalHeaderPhysLoc + 80) in *) (* Heap Reserve Size Always 0x100000 (1Mb) (see Section 23.1). *) - (* let heapCommit = seekReadInt32 is (peOptionalHeaderPhysLoc + 84) in *) (* Heap Commit Size Always 0x1000 (4Kb) (see Section 23.1). *) + (* let stackReserve = seekReadInt32 is (peOptionalHeaderPhysLoc + 72) in *) (* Stack Reserve Size Always 0x100000 (1Mb) (see Section 23.1). *) + (* let stackCommit = seekReadInt32 is (peOptionalHeaderPhysLoc + 76) in *) (* Stack Commit Size Always 0x1000 (4Kb) (see Section 23.1). *) + (* let heapReserve = seekReadInt32 is (peOptionalHeaderPhysLoc + 80) in *) (* Heap Reserve Size Always 0x100000 (1Mb) (see Section 23.1). *) + (* let heapCommit = seekReadInt32 is (peOptionalHeaderPhysLoc + 84) in *) (* Heap Commit Size Always 0x1000 (4Kb) (see Section 23.1). *) (* x86: 000000f0, x64: 00000100 *) - let _numDataDirectories = seekReadInt32 pev (peOptionalHeaderPhysLoc + 92 + x64adjust) (* Number of Data Directories: Always 0x10 (see Section 23.1). *) + let _numDataDirectories = seekReadInt32 pev (peOptionalHeaderPhysLoc + 92 + x64adjust) (* Number of Data Directories: Always 0x10 (see Section 23.1). *) (* 00000100 - these addresses are for x86 - for the x64 location, add x64adjust (0x10) *) - let _importTableAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 104 + x64adjust) (* Import Table RVA of Import Table, (see clause 24.3.1). e.g. 0000b530 *) - let _importTableSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 108 + x64adjust) (* Size of Import Table, (see clause 24.3.1). *) + let _importTableAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 104 + x64adjust) (* Import Table RVA of Import Table, (see clause 24.3.1). e.g. 0000b530 *) + let _importTableSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 108 + x64adjust) (* Size of Import Table, (see clause 24.3.1). *) let nativeResourcesAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 112 + x64adjust) let nativeResourcesSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 116 + x64adjust) (* 00000110 *) (* 00000120 *) - (* let base_relocTableNames.addr = seekReadInt32 is (peOptionalHeaderPhysLoc + 136) - let base_relocTableNames.size = seekReadInt32 is (peOptionalHeaderPhysLoc + 140) in *) + (* let base_relocTableNames.addr = seekReadInt32 is (peOptionalHeaderPhysLoc + 136) + let base_relocTableNames.size = seekReadInt32 is (peOptionalHeaderPhysLoc + 140) in *) (* 00000130 *) (* 00000140 *) (* 00000150 *) - let _importAddrTableAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 192 + x64adjust) (* RVA of Import Addr Table, (see clause 24.3.1). e.g. 0x00002000 *) - let _importAddrTableSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 196 + x64adjust) (* Size of Import Addr Table, (see clause 24.3.1). e.g. 0x00002000 *) + let _importAddrTableAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 192 + x64adjust) (* RVA of Import Addr Table, (see clause 24.3.1). e.g. 0x00002000 *) + let _importAddrTableSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 196 + x64adjust) (* Size of Import Addr Table, (see clause 24.3.1). e.g. 0x00002000 *) (* 00000160 *) let cliHeaderAddr = seekReadInt32 pev (peOptionalHeaderPhysLoc + 208 + x64adjust) let _cliHeaderSize = seekReadInt32 pev (peOptionalHeaderPhysLoc + 212 + x64adjust) @@ -3824,7 +3825,7 @@ let openPEFileReader (fileName, pefile: BinaryFile, pdbDirPath, noFileOnDisk) = let textHeaderStart = findSectionHeader cliHeaderAddr let dataHeaderStart = findSectionHeader dataSegmentAddr - (* let relocHeaderStart = findSectionHeader base_relocTableNames.addr in *) + (* let relocHeaderStart = findSectionHeader base_relocTableNames.addr in *) let _textSize = if textHeaderStart = 0x0 then 0x0 else seekReadInt32 pev (textHeaderStart + 8) let _textAddr = if textHeaderStart = 0x0 then 0x0 else seekReadInt32 pev (textHeaderStart + 12) @@ -3852,21 +3853,21 @@ let openPEFileReader (fileName, pefile: BinaryFile, pdbDirPath, noFileOnDisk) = let _majorRuntimeVersion = seekReadUInt16 pev (cliHeaderPhysLoc + 4) let _minorRuntimeVersion = seekReadUInt16 pev (cliHeaderPhysLoc + 6) - let metadataAddr = seekReadInt32 pev (cliHeaderPhysLoc + 8) - let metadataSize = seekReadInt32 pev (cliHeaderPhysLoc + 12) - let cliFlags = seekReadInt32 pev (cliHeaderPhysLoc + 16) + let metadataAddr = seekReadInt32 pev (cliHeaderPhysLoc + 8) + let metadataSize = seekReadInt32 pev (cliHeaderPhysLoc + 12) + let cliFlags = seekReadInt32 pev (cliHeaderPhysLoc + 16) - let ilOnly = (cliFlags &&& 0x01) <> 0x00 - let only32 = (cliFlags &&& 0x02) <> 0x00 - let is32bitpreferred = (cliFlags &&& 0x00020003) <> 0x00 - let _strongnameSigned = (cliFlags &&& 0x08) <> 0x00 - let _trackdebugdata = (cliFlags &&& 0x010000) <> 0x00 + let ilOnly = (cliFlags &&& 0x01) <> 0x00 + let only32 = (cliFlags &&& 0x02) <> 0x00 + let is32bitpreferred = (cliFlags &&& 0x00020003) <> 0x00 + let _strongnameSigned = (cliFlags &&& 0x08) <> 0x00 + let _trackdebugdata = (cliFlags &&& 0x010000) <> 0x00 let entryPointToken = seekReadUncodedToken pev (cliHeaderPhysLoc + 20) - let resourcesAddr = seekReadInt32 pev (cliHeaderPhysLoc + 24) - let resourcesSize = seekReadInt32 pev (cliHeaderPhysLoc + 28) - let strongnameAddr = seekReadInt32 pev (cliHeaderPhysLoc + 32) - let _strongnameSize = seekReadInt32 pev (cliHeaderPhysLoc + 36) + let resourcesAddr = seekReadInt32 pev (cliHeaderPhysLoc + 24) + let resourcesSize = seekReadInt32 pev (cliHeaderPhysLoc + 28) + let strongnameAddr = seekReadInt32 pev (cliHeaderPhysLoc + 32) + let _strongnameSize = seekReadInt32 pev (cliHeaderPhysLoc + 36) let vtableFixupsAddr = seekReadInt32 pev (cliHeaderPhysLoc + 40) let _vtableFixupsSize = seekReadInt32 pev (cliHeaderPhysLoc + 44) @@ -3952,7 +3953,7 @@ type ILModuleReader = abstract ILAssemblyRefs: ILAssemblyRef list /// ILModuleReader objects only need to be explicitly disposed if memory mapping is used, i.e. reduceMemoryUsage = false - inherit System.IDisposable + inherit System.IDisposable [] @@ -4041,7 +4042,7 @@ let OpenILModuleReader fileName opts = let mdfileOpt = match opts.tryGetMetadataSnapshot (fullPath, writeStamp) with | Some (obj, start, len) -> Some (RawMemoryFile(fullPath, obj, start, len) :> BinaryFile) - | None -> None + | None -> None // For metadata-only, always use a temporary, short-lived PE file reader, preferably over a memory mapped file. // Then use the metadata blob as the long-lived memory resource. @@ -4078,7 +4079,7 @@ let OpenILModuleReader fileName opts = // whole binary for the command-line compiler: address space is rarely an issue. // // We do however care about avoiding locks on files that prevent their deletion during a - // multi-proc build. So use memory mapping, but only for stable files. Other files + // multi-proc build. So use memory mapping, but only for stable files. Other files // still use an in-memory ByteFile let _disposer, pefile = if alwaysMemoryMapFSC || stableFileHeuristicApplies fullPath then @@ -4091,7 +4092,7 @@ let OpenILModuleReader fileName opts = let ilModule, ilAssemblyRefs, pdb = openPE (fullPath, pefile, opts.pdbDirPath, reduceMemoryUsage, opts.ilGlobals, false) let ilModuleReader = new ILModuleReaderImpl(ilModule, ilAssemblyRefs, (fun () -> ClosePdbReader pdb)) - // Readers with PDB reader disposal logic don't go in the cache. Note the PDB reader is only used in static linking. + // Readers with PDB reader disposal logic don't go in the cache. Note the PDB reader is only used in static linking. if keyOk && opts.pdbDirPath.IsNone then ilModuleReaderCacheLock.AcquireLock (fun ltok -> ilModuleReaderCache.Put(ltok, key, ilModuleReader)) diff --git a/src/absil/ilreflect.fs b/src/absil/ilreflect.fs index 0ff14a5696e..474997be4e7 100644 --- a/src/absil/ilreflect.fs +++ b/src/absil/ilreflect.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. //---------------------------------------------------------------------------- // Write Abstract IL structures at runtime using Reflection.Emit @@ -53,16 +53,16 @@ type System.Reflection.Emit.AssemblyBuilder with #endif modB - member asmB.SetCustomAttributeAndLog(cinfo, bytes) = + member asmB.SetCustomAttributeAndLog(cinfo, bytes) = if logRefEmitCalls then printfn "assemblyBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash asmB) cinfo bytes wrapCustomAttr asmB.SetCustomAttribute (cinfo, bytes) #if !FX_RESHAPED_REFEMIT - member asmB.AddResourceFileAndLog(nm1, nm2, attrs) = + member asmB.AddResourceFileAndLog(nm1, nm2, attrs) = if logRefEmitCalls then printfn "assemblyBuilder%d.AddResourceFile(%A, %A, enum %d)" (abs <| hash asmB) nm1 nm2 (LanguagePrimitives.EnumToValue attrs) asmB.AddResourceFile(nm1, nm2, attrs) #endif - member asmB.SetCustomAttributeAndLog(cab) = + member asmB.SetCustomAttributeAndLog(cab) = if logRefEmitCalls then printfn "assemblyBuilder%d.SetCustomAttribute(%A)" (abs <| hash asmB) cab asmB.SetCustomAttribute(cab) @@ -75,7 +75,7 @@ type System.Reflection.Emit.ModuleBuilder with #if !FX_RESHAPED_REFEMIT member modB.DefineDocumentAndLog(file, lang, vendor, doctype) = let symDoc = modB.DefineDocument(file, lang, vendor, doctype) - if logRefEmitCalls then printfn "let docWriter%d = moduleBuilder%d.DefineDocument(@%A, System.Guid(\"%A\"), System.Guid(\"%A\"), System.Guid(\"%A\"))" (abs <| hash symDoc) (abs <| hash modB) file lang vendor doctype + if logRefEmitCalls then printfn "let docWriter%d = moduleBuilder%d.DefineDocument(@%A, System.Guid(\"%A\"), System.Guid(\"%A\"), System.Guid(\"%A\"))" (abs <| hash symDoc) (abs <| hash modB) file lang vendor doctype symDoc #endif member modB.GetTypeAndLog(nameInModule, flag1, flag2) = @@ -92,7 +92,7 @@ type System.Reflection.Emit.ModuleBuilder with if logRefEmitCalls then printfn "moduleBuilder%d.DefineManifestResource(%A, %A, enum %d)" (abs <| hash modB) name stream (LanguagePrimitives.EnumToValue attrs) modB.DefineManifestResource(name, stream, attrs) #endif - member modB.SetCustomAttributeAndLog(cinfo, bytes) = + member modB.SetCustomAttributeAndLog(cinfo, bytes) = if logRefEmitCalls then printfn "moduleBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash modB) cinfo bytes wrapCustomAttr modB.SetCustomAttribute (cinfo, bytes) @@ -133,7 +133,7 @@ type System.Reflection.Emit.MethodBuilder with if logRefEmitCalls then printfn "let ilg%d = methodBuilder%d.GetILGenerator()" (abs <| hash ilG) (abs <| hash methB) ilG - member methB.SetCustomAttributeAndLog(cinfo, bytes) = + member methB.SetCustomAttributeAndLog(cinfo, bytes) = if logRefEmitCalls then printfn "methodBuilder%d.SetCustomAttribute(%A, %A)" (abs <| hash methB) cinfo bytes wrapCustomAttr methB.SetCustomAttribute (cinfo, bytes) @@ -204,7 +204,7 @@ type System.Reflection.Emit.TypeBuilder with type System.Reflection.Emit.OpCode with - member opcode.RefEmitName = (string (System.Char.ToUpper(opcode.Name.[0])) + opcode.Name.[1..]).Replace(".", "_").Replace("_i4", "_I4") + 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) = @@ -233,7 +233,7 @@ type System.Reflection.Emit.ILGenerator with ilG.BeginFinallyBlock() member ilG.BeginCatchBlockAndLog(ty) = - if logRefEmitCalls then printfn "ilg%d.BeginCatchBlock(%A)" (abs <| hash ilG) ty + if logRefEmitCalls then printfn "ilg%d.BeginCatchBlock(%A)" (abs <| hash ilG) ty ilG.BeginCatchBlock(ty) member ilG.BeginExceptFilterBlockAndLog() = @@ -282,7 +282,7 @@ type System.Reflection.Emit.ILGenerator with // misc //---------------------------------------------------------------------------- -let inline flagsIf b x = if b then x else enum 0 +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 @@ -292,7 +292,7 @@ let equalTypeLists ss tt = List.lengthsEqAndForall2 equalTypes ss tt let equalTypeArrays ss tt = Array.lengthsEqAndForall2 equalTypes ss tt let getGenericArgumentsOfType (typT: Type) = - if typT.IsGenericType then typT.GetGenericArguments() else [| |] + if typT.IsGenericType then typT.GetGenericArguments() else [| |] let getGenericArgumentsOfMethod (methI: MethodInfo) = if methI.IsGenericMethod then methI.GetGenericArguments() else [| |] @@ -305,10 +305,10 @@ let getTypeConstructor (ty: Type) = let convAssemblyRef (aref: ILAssemblyRef) = let asmName = new System.Reflection.AssemblyName() - asmName.Name <- aref.Name + asmName.Name <- aref.Name (match aref.PublicKey with | None -> () - | Some (PublicKey bytes) -> asmName.SetPublicKey(bytes) + | Some (PublicKey bytes) -> asmName.SetPublicKey(bytes) | Some (PublicKeyToken bytes) -> asmName.SetPublicKeyToken(bytes)) let setVersion (major, minor, build, rev) = asmName.Version <- System.Version (int32 major, int32 minor, int32 build, int32 rev) @@ -345,7 +345,7 @@ let convTypeRefAux (cenv: cenv) (tref: ILTypeRef) = | Some (Choice2Of2 assembly) -> assembly | None -> - let asmName = convAssemblyRef asmref + let asmName = convAssemblyRef asmref FileSystem.AssemblyLoad(asmName) let typT = assembly.GetType(qualifiedName) match typT with @@ -373,22 +373,22 @@ type emEnv = emLabels: Zmap emTyvars: Type[] list; // stack emEntryPts: (TypeBuilder * string) list - delayedFieldInits: (unit -> unit) list} + delayedFieldInits: (unit -> unit) list} -let orderILTypeRef = ComparisonIdentity.Structural -let orderILMethodRef = ComparisonIdentity.Structural -let orderILFieldRef = ComparisonIdentity.Structural -let orderILPropertyRef = ComparisonIdentity.Structural +let orderILTypeRef = ComparisonIdentity.Structural +let orderILMethodRef = ComparisonIdentity.Structural +let orderILFieldRef = ComparisonIdentity.Structural +let orderILPropertyRef = ComparisonIdentity.Structural let emEnv0 = - { emTypMap = Zmap.empty orderILTypeRef - emConsMap = Zmap.empty orderILMethodRef - emMethMap = Zmap.empty orderILMethodRef + { emTypMap = Zmap.empty orderILTypeRef + emConsMap = Zmap.empty orderILMethodRef + emMethMap = Zmap.empty orderILMethodRef emFieldMap = Zmap.empty orderILFieldRef emPropMap = Zmap.empty orderILPropertyRef - emLocals = [| |] - emLabels = Zmap.empty codeLabelOrder - emTyvars = [] + emLocals = [| |] + emLabels = Zmap.empty codeLabelOrder + emTyvars = [] emEntryPts = [] delayedFieldInits = [] } @@ -427,8 +427,8 @@ 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 - | Some (typT, _typB, _typeDef, _) -> typT - | None -> convTypeRefAux cenv tref + | Some (typT, _typB, _typeDef, _) -> typT + | None -> convTypeRefAux cenv tref match res with | null -> error(Error(FSComp.SR.itemNotFoundDuringDynamicCodeGen ("type", tref.QualifiedName, tref.Scope.QualifiedName), range0)) | _ -> res @@ -467,7 +467,7 @@ let envGetTypeDef emEnv (tref: ILTypeRef) = let envSetLocals emEnv locs = assert (emEnv.emLocals.Length = 0); // check "locals" is not yet set (scopes once only) {emEnv with emLocals = locs} -let envGetLocal emEnv i = emEnv.emLocals.[i] // implicit bounds checking +let envGetLocal emEnv i = emEnv.emLocals.[i] // implicit bounds checking let envSetLabel emEnv name lab = assert (not (Zmap.mem name emEnv.emLabels)) @@ -476,11 +476,11 @@ let envSetLabel emEnv name lab = let envGetLabel emEnv name = Zmap.find name emEnv.emLabels -let envPushTyvars emEnv tys = {emEnv with emTyvars = tys :: emEnv.emTyvars} -let envPopTyvars emEnv = {emEnv with emTyvars = List.tail emEnv.emTyvars} -let envGetTyvar emEnv u16 = +let envPushTyvars emEnv tys = {emEnv with emTyvars = tys :: emEnv.emTyvars} +let envPopTyvars emEnv = {emEnv with emTyvars = List.tail emEnv.emTyvars} +let envGetTyvar emEnv u16 = match emEnv.emTyvars with - | [] -> failwith "envGetTyvar: not scope of type vars" + | [] -> failwith "envGetTyvar: not scope of type vars" | tvs::_ -> let i = int32 u16 if i<0 || i>= Array.length tvs then @@ -490,23 +490,29 @@ let envGetTyvar emEnv u16 = let isEmittedTypeRef emEnv tref = Zmap.mem tref emEnv.emTypMap -let envAddEntryPt emEnv mref = {emEnv with emEntryPts = mref::emEnv.emEntryPts} -let envPopEntryPts emEnv = {emEnv with emEntryPts = []}, emEnv.emEntryPts +let envAddEntryPt emEnv mref = {emEnv with emEntryPts = mref::emEnv.emEntryPts} +let envPopEntryPts emEnv = {emEnv with emEntryPts = []}, emEnv.emEntryPts //---------------------------------------------------------------------------- // convCallConv //---------------------------------------------------------------------------- let convCallConv (Callconv (hasThis, basic)) = - let ccA = match hasThis with ILThisConvention.Static -> CallingConventions.Standard - | ILThisConvention.InstanceExplicit -> CallingConventions.ExplicitThis - | ILThisConvention.Instance -> CallingConventions.HasThis - let ccB = match basic with ILArgConvention.Default -> enum 0 - | ILArgConvention.CDecl -> enum 0 - | ILArgConvention.StdCall -> enum 0 - | ILArgConvention.ThisCall -> enum 0 // XXX: check all these - | ILArgConvention.FastCall -> enum 0 - | ILArgConvention.VarArg -> CallingConventions.VarArgs + let ccA = + match hasThis with + | ILThisConvention.Static -> CallingConventions.Standard + | ILThisConvention.InstanceExplicit -> CallingConventions.ExplicitThis + | ILThisConvention.Instance -> CallingConventions.HasThis + + let ccB = + match basic with + | ILArgConvention.Default -> enum 0 + | ILArgConvention.CDecl -> enum 0 + | ILArgConvention.StdCall -> enum 0 + | ILArgConvention.ThisCall -> enum 0 // XXX: check all these + | ILArgConvention.FastCall -> enum 0 + | ILArgConvention.VarArg -> CallingConventions.VarArgs + ccA ||| ccB @@ -515,24 +521,24 @@ let convCallConv (Callconv (hasThis, basic)) = //---------------------------------------------------------------------------- let rec convTypeSpec cenv emEnv preferCreated (tspec: ILTypeSpec) = - let typT = convTypeRef cenv emEnv preferCreated tspec.TypeRef + let typT = convTypeRef cenv emEnv preferCreated tspec.TypeRef let tyargs = List.map (convTypeAux cenv emEnv preferCreated) tspec.GenericArgs let res = match isNil tyargs, typT.IsGenericType with - | _ , true -> typT.MakeGenericType(List.toArray tyargs) + | _, true -> typT.MakeGenericType(List.toArray tyargs) | true, false -> typT - | _ , false -> null + | _, false -> null match res with | null -> error(Error(FSComp.SR.itemNotFoundDuringDynamicCodeGen ("type", tspec.TypeRef.QualifiedName, tspec.Scope.QualifiedName), range0)) | _ -> res and convTypeAux cenv emEnv preferCreated ty = match ty with - | ILType.Void -> Type.GetType("System.Void") + | ILType.Void -> Type.GetType("System.Void") | ILType.Array (shape, eltType) -> let baseT = convTypeAux cenv emEnv preferCreated eltType let nDims = shape.Rank - // MakeArrayType() returns "eltType[]" + // MakeArrayType() returns "eltType[]" // MakeArrayType(1) returns "eltType[*]" // MakeArrayType(2) returns "eltType[, ]" // MakeArrayType(3) returns "eltType[, , ]" @@ -540,17 +546,17 @@ and convTypeAux cenv emEnv preferCreated ty = if nDims=1 then baseT.MakeArrayType() else baseT.MakeArrayType shape.Rank - | ILType.Value tspec -> convTypeSpec cenv emEnv preferCreated tspec - | ILType.Boxed tspec -> convTypeSpec cenv emEnv preferCreated tspec - | ILType.Ptr eltType -> + | ILType.Value tspec -> convTypeSpec cenv emEnv preferCreated tspec + | ILType.Boxed tspec -> convTypeSpec cenv emEnv preferCreated tspec + | ILType.Ptr eltType -> let baseT = convTypeAux cenv emEnv preferCreated eltType baseT.MakePointerType() - | ILType.Byref eltType -> + | ILType.Byref eltType -> let baseT = convTypeAux cenv emEnv preferCreated eltType baseT.MakeByRefType() - | ILType.TypeVar tv -> envGetTyvar emEnv tv + | ILType.TypeVar tv -> envGetTyvar emEnv tv // Consider completing the following cases: - | ILType.Modified (_, _, modifiedTy) -> + | ILType.Modified (_, _, modifiedTy) -> // Note, "modreq" are not being emitted. This is convTypeAux cenv emEnv preferCreated modifiedTy @@ -592,7 +598,7 @@ let convCreatedTypeRef cenv emEnv ty = convTypeRef cenv emEnv true ty let rec convParamModifiersOfType cenv emEnv (pty: ILType) = [| match pty with - | ILType.Modified (modreq, ty, modifiedTy) -> + | ILType.Modified (modreq, ty, modifiedTy) -> yield (modreq, convTypeRef cenv emEnv false ty) yield! convParamModifiersOfType cenv emEnv modifiedTy | _ -> () |] @@ -616,27 +622,27 @@ let convReturnModifiers cenv emEnv (p: ILReturn) = let convFieldInit x = match x with - | ILFieldInit.String s -> box s - | ILFieldInit.Bool bool -> box bool - | ILFieldInit.Char u16 -> box (char (int u16)) - | ILFieldInit.Int8 i8 -> box i8 - | ILFieldInit.Int16 i16 -> box i16 - | ILFieldInit.Int32 i32 -> box i32 - | ILFieldInit.Int64 i64 -> box i64 - | ILFieldInit.UInt8 u8 -> box u8 - | ILFieldInit.UInt16 u16 -> box u16 - | ILFieldInit.UInt32 u32 -> box u32 - | ILFieldInit.UInt64 u64 -> box u64 + | ILFieldInit.String s -> box s + | ILFieldInit.Bool bool -> box bool + | ILFieldInit.Char u16 -> box (char (int u16)) + | ILFieldInit.Int8 i8 -> box i8 + | ILFieldInit.Int16 i16 -> box i16 + | ILFieldInit.Int32 i32 -> box i32 + | ILFieldInit.Int64 i64 -> box i64 + | ILFieldInit.UInt8 u8 -> box u8 + | ILFieldInit.UInt16 u16 -> box u16 + | ILFieldInit.UInt32 u32 -> box u32 + | ILFieldInit.UInt64 u64 -> box u64 | ILFieldInit.Single ieee32 -> box ieee32 | ILFieldInit.Double ieee64 -> box ieee64 - | ILFieldInit.Null -> (null :> Object) + | ILFieldInit.Null -> (null :> Object) //---------------------------------------------------------------------------- // Some types require hard work... //---------------------------------------------------------------------------- // This is gross. TypeBuilderInstantiation should really be a public type, since we -// have to use alternative means for various Method/Field/Constructor lookups. However since +// have to use alternative means for various Method/Field/Constructor lookups. However since // it isn't we resort to this technique... let TypeBuilderInstantiationT = let ty = @@ -662,7 +668,7 @@ 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)) @@ -689,7 +695,7 @@ let convFieldSpec cenv emEnv fspec = // Prior type. if typeIsNotQueryable parentTI then let parentT = getTypeConstructor parentTI - let fieldInfo = queryableTypeGetField emEnv parentT fref + let fieldInfo = queryableTypeGetField emEnv parentT fref nonQueryableTypeGetField parentTI fieldInfo else queryableTypeGetField emEnv parentTI fspec.FieldRef @@ -754,17 +760,17 @@ let queryableTypeGetMethodBySearch cenv emEnv parentT (mref: ILMethodRef) = let argTs, resT = let emEnv = envPushTyvars emEnv (Array.append tyargTs mtyargTIs) let argTs = convTypes cenv emEnv mref.ArgTypes - let resT = convType cenv emEnv mref.ReturnType + let resT = convType cenv emEnv mref.ReturnType argTs, resT - let haveResT = methInfo.ReturnType + let haveResT = methInfo.ReturnType (* check for match *) if argTs.Length <> methodParameters.Length then false (* method argument length mismatch *) else let res = equalTypes resT haveResT && equalTypeLists argTs (haveArgTs |> Array.toList) res match List.tryFind select methInfos with - | None -> + | None -> let methNames = methInfos |> List.map (fun m -> m.Name) |> List.distinct 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 *) @@ -776,7 +782,7 @@ let queryableTypeGetMethod cenv emEnv parentT (mref: ILMethodRef) = let argTs, resT = let emEnv = envPushTyvars emEnv tyargTs let argTs = convTypesToArray cenv emEnv mref.ArgTypes - let resT = convType cenv emEnv mref.ReturnType + let resT = convType cenv emEnv mref.ReturnType argTs, resT let stat = mref.CallingConv.IsStatic let cconv = (if stat then BindingFlags.Static else BindingFlags.Instance) @@ -830,13 +836,13 @@ let convMethodRef cenv emEnv (parentTI: Type) (mref: ILMethodRef) = //---------------------------------------------------------------------------- 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 typT = convType cenv emEnv mspec.DeclaringType (* (instanced) parent Type *) + let methInfo = convMethodRef cenv emEnv typT mspec.MethodRef (* (generic) method of (generic) parent *) let methInfo = if isNil mspec.GenericArgs then methInfo // non generic else - let minstTs = convTypesToArray cenv emEnv mspec.GenericArgs + let minstTs = convTypesToArray cenv emEnv mspec.GenericArgs let methInfo = methInfo.MakeGenericMethod minstTs // instantiate method methInfo methInfo @@ -845,9 +851,9 @@ let convMethodSpec cenv emEnv (mspec: ILMethodSpec) = // - QueryableTypeGetConstructors: get a constructor on a non-TypeBuilder type //---------------------------------------------------------------------------- -let queryableTypeGetConstructor cenv emEnv (parentT: Type) (mref: ILMethodRef) = - let tyargTs = getGenericArgumentsOfType parentT - let reqArgTs = +let queryableTypeGetConstructor cenv emEnv (parentT: Type) (mref: ILMethodRef) = + let tyargTs = getGenericArgumentsOfType parentT + let reqArgTs = let emEnv = envPushTyvars emEnv tyargTs convTypesToArray cenv emEnv mref.ArgTypes let res = parentT.GetConstructor(BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance, null, reqArgTs, null) @@ -864,7 +870,7 @@ let nonQueryableTypeGetConstructor (parentTI: Type) (consInfo: ConstructorInfo) //---------------------------------------------------------------------------- let convConstructorSpec cenv emEnv (mspec: ILMethodSpec) = - let mref = mspec.MethodRef + let mref = mspec.MethodRef let parentTI = convType cenv emEnv mspec.DeclaringType let res = if isEmittedTypeRef emEnv mref.DeclaringTypeRef then @@ -873,7 +879,7 @@ let convConstructorSpec cenv emEnv (mspec: ILMethodSpec) = else // Prior type. if typeIsNotQueryable parentTI then - let parentT = getTypeConstructor parentTI + let parentT = getTypeConstructor parentTI let ctorG = queryableTypeGetConstructor cenv emEnv parentT mref nonQueryableTypeGetConstructor parentTI ctorG else @@ -895,30 +901,30 @@ 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) - | BI_bge_un -> ilG.EmitAndLog(OpCodes.Bge_Un , envGetLabel emEnv targ) - | BI_bgt -> ilG.EmitAndLog(OpCodes.Bgt , envGetLabel emEnv targ) - | BI_bgt_un -> ilG.EmitAndLog(OpCodes.Bgt_Un , envGetLabel emEnv targ) - | BI_ble -> ilG.EmitAndLog(OpCodes.Ble , envGetLabel emEnv targ) - | BI_ble_un -> ilG.EmitAndLog(OpCodes.Ble_Un , envGetLabel emEnv targ) - | BI_blt -> ilG.EmitAndLog(OpCodes.Blt , envGetLabel emEnv targ) - | BI_blt_un -> ilG.EmitAndLog(OpCodes.Blt_Un , envGetLabel emEnv targ) - | BI_bne_un -> ilG.EmitAndLog(OpCodes.Bne_Un , envGetLabel emEnv targ) + | BI_beq -> ilG.EmitAndLog(OpCodes.Beq, envGetLabel emEnv targ) + | BI_bge -> ilG.EmitAndLog(OpCodes.Bge, envGetLabel emEnv targ) + | BI_bge_un -> ilG.EmitAndLog(OpCodes.Bge_Un, envGetLabel emEnv targ) + | BI_bgt -> ilG.EmitAndLog(OpCodes.Bgt, envGetLabel emEnv targ) + | BI_bgt_un -> ilG.EmitAndLog(OpCodes.Bgt_Un, envGetLabel emEnv targ) + | BI_ble -> ilG.EmitAndLog(OpCodes.Ble, envGetLabel emEnv targ) + | BI_ble_un -> ilG.EmitAndLog(OpCodes.Ble_Un, envGetLabel emEnv targ) + | BI_blt -> ilG.EmitAndLog(OpCodes.Blt, envGetLabel emEnv targ) + | BI_blt_un -> ilG.EmitAndLog(OpCodes.Blt_Un, envGetLabel emEnv targ) + | BI_bne_un -> ilG.EmitAndLog(OpCodes.Bne_Un, envGetLabel emEnv targ) | BI_brfalse -> ilG.EmitAndLog(OpCodes.Brfalse, envGetLabel emEnv targ) - | BI_brtrue -> ilG.EmitAndLog(OpCodes.Brtrue , envGetLabel emEnv targ) + | BI_brtrue -> ilG.EmitAndLog(OpCodes.Brtrue, envGetLabel emEnv targ) /// Emit the volatile. prefix let emitInstrVolatile (ilG: ILGenerator) = function - | Volatile -> ilG.EmitAndLog(OpCodes.Volatile) + | Volatile -> ilG.EmitAndLog(OpCodes.Volatile) | Nonvolatile -> () /// Emit the align. prefix let emitInstrAlign (ilG: ILGenerator) = function - | Aligned -> () + | 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) @@ -926,12 +932,12 @@ let emitInstrAlign (ilG: ILGenerator) = function /// Emit the tail. prefix if necessary let emitInstrTail (ilG: ILGenerator) tail emitTheCall = match tail with - | Tailcall -> ilG.EmitAndLog(OpCodes.Tailcall); emitTheCall(); ilG.EmitAndLog(OpCodes.Ret) + | Tailcall -> ilG.EmitAndLog(OpCodes.Tailcall); emitTheCall(); ilG.EmitAndLog(OpCodes.Ret) | Normalcall -> emitTheCall() let emitInstrNewobj cenv emEnv (ilG: ILGenerator) mspec varargs = match varargs with - | None -> ilG.EmitAndLog(OpCodes.Newobj, convConstructorSpec cenv emEnv mspec) + | None -> ilG.EmitAndLog(OpCodes.Newobj, convConstructorSpec cenv emEnv mspec) | Some _varargTys -> failwith "emit: pending new varargs" // XXX - gap let emitSilverlightCheck (ilG: ILGenerator) = @@ -943,7 +949,7 @@ let emitInstrCall cenv emEnv (ilG: ILGenerator) opCall tail (mspec: ILMethodSpec if mspec.MethodRef.Name = ".ctor" || mspec.MethodRef.Name = ".cctor" then let cinfo = convConstructorSpec cenv emEnv mspec match varargs with - | None -> ilG.EmitAndLog (opCall, cinfo) + | None -> ilG.EmitAndLog (opCall, cinfo) | Some _varargTys -> failwith "emitInstrCall: .ctor and varargs" else let minfo = convMethodSpec cenv emEnv mspec @@ -971,7 +977,7 @@ let setArrayMethInfo n ty = | 2 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.SetArray2D null 0 0 0 @@> ty | 3 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.SetArray3D null 0 0 0 0 @@> ty | 4 -> getGenericMethodDefinition <@@ LanguagePrimitives.IntrinsicFunctions.SetArray4D null 0 0 0 0 0 @@> ty - | _ -> invalidArg "n" "not expecting array dimension > 4" + | _ -> invalidArg "n" "not expecting array dimension > 4" //---------------------------------------------------------------------------- @@ -980,142 +986,142 @@ let setArrayMethInfo n ty = 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) - | AI_add_ovf_un -> ilG.EmitAndLog(OpCodes.Add_Ovf_Un) - | AI_and -> ilG.EmitAndLog(OpCodes.And) - | AI_div -> ilG.EmitAndLog(OpCodes.Div) - | AI_div_un -> ilG.EmitAndLog(OpCodes.Div_Un) - | AI_ceq -> ilG.EmitAndLog(OpCodes.Ceq) - | AI_cgt -> ilG.EmitAndLog(OpCodes.Cgt) - | AI_cgt_un -> ilG.EmitAndLog(OpCodes.Cgt_Un) - | AI_clt -> ilG.EmitAndLog(OpCodes.Clt) - | AI_clt_un -> ilG.EmitAndLog(OpCodes.Clt_Un) + | AI_add -> ilG.EmitAndLog(OpCodes.Add) + | AI_add_ovf -> ilG.EmitAndLog(OpCodes.Add_Ovf) + | AI_add_ovf_un -> ilG.EmitAndLog(OpCodes.Add_Ovf_Un) + | AI_and -> ilG.EmitAndLog(OpCodes.And) + | AI_div -> ilG.EmitAndLog(OpCodes.Div) + | AI_div_un -> ilG.EmitAndLog(OpCodes.Div_Un) + | AI_ceq -> ilG.EmitAndLog(OpCodes.Ceq) + | AI_cgt -> ilG.EmitAndLog(OpCodes.Cgt) + | AI_cgt_un -> ilG.EmitAndLog(OpCodes.Cgt_Un) + | AI_clt -> ilG.EmitAndLog(OpCodes.Clt) + | AI_clt_un -> ilG.EmitAndLog(OpCodes.Clt_Un) // conversion - | AI_conv dt -> + | AI_conv dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Conv_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_I8) - | DT_U -> ilG.EmitAndLog(OpCodes.Conv_U) - | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_U1) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_U2) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_U4) - | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_U8) - | DT_R -> ilG.EmitAndLog(OpCodes.Conv_R_Un) - | DT_R4 -> ilG.EmitAndLog(OpCodes.Conv_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Conv_R8) + | DT_I -> ilG.EmitAndLog(OpCodes.Conv_I) + | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_I1) + | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_I2) + | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_I4) + | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_I8) + | DT_U -> ilG.EmitAndLog(OpCodes.Conv_U) + | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_U1) + | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_U2) + | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_U4) + | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_U8) + | DT_R -> ilG.EmitAndLog(OpCodes.Conv_R_Un) + | DT_R4 -> ilG.EmitAndLog(OpCodes.Conv_R4) + | DT_R8 -> ilG.EmitAndLog(OpCodes.Conv_R8) | DT_REF -> failwith "AI_conv DT_REF?" // XXX - check // conversion - ovf checks - | AI_conv_ovf dt -> + | AI_conv_ovf dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I8) - | DT_U -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U) - | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U1) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U2) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U4) - | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U8) - | DT_R -> failwith "AI_conv_ovf DT_R?" // XXX - check - | DT_R4 -> failwith "AI_conv_ovf DT_R4?" // XXX - check - | DT_R8 -> failwith "AI_conv_ovf DT_R8?" // XXX - check + | DT_I -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I) + | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I1) + | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I2) + | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I4) + | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I8) + | DT_U -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U) + | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U1) + | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U2) + | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U4) + | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U8) + | DT_R -> failwith "AI_conv_ovf DT_R?" // XXX - check + | DT_R4 -> failwith "AI_conv_ovf DT_R4?" // XXX - check + | DT_R8 -> failwith "AI_conv_ovf DT_R8?" // XXX - check | DT_REF -> failwith "AI_conv_ovf DT_REF?" // XXX - check // conversion - ovf checks and unsigned - | AI_conv_ovf_un dt -> + | AI_conv_ovf_un dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I_Un) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I1_Un) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I2_Un) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I4_Un) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I8_Un) - | DT_U -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U_Un) - | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U1_Un) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U2_Un) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U4_Un) - | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U8_Un) - | DT_R -> failwith "AI_conv_ovf_un DT_R?" // XXX - check - | DT_R4 -> failwith "AI_conv_ovf_un DT_R4?" // XXX - check - | DT_R8 -> failwith "AI_conv_ovf_un DT_R8?" // XXX - check + | DT_I -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I_Un) + | DT_I1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I1_Un) + | DT_I2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I2_Un) + | DT_I4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I4_Un) + | DT_I8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_I8_Un) + | DT_U -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U_Un) + | DT_U1 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U1_Un) + | DT_U2 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U2_Un) + | DT_U4 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U4_Un) + | DT_U8 -> ilG.EmitAndLog(OpCodes.Conv_Ovf_U8_Un) + | DT_R -> failwith "AI_conv_ovf_un DT_R?" // XXX - check + | DT_R4 -> failwith "AI_conv_ovf_un DT_R4?" // XXX - check + | DT_R8 -> failwith "AI_conv_ovf_un DT_R8?" // XXX - check | DT_REF -> failwith "AI_conv_ovf_un DT_REF?" // XXX - check - | AI_mul -> ilG.EmitAndLog(OpCodes.Mul) - | AI_mul_ovf -> ilG.EmitAndLog(OpCodes.Mul_Ovf) - | AI_mul_ovf_un -> ilG.EmitAndLog(OpCodes.Mul_Ovf_Un) - | AI_rem -> ilG.EmitAndLog(OpCodes.Rem) - | AI_rem_un -> ilG.EmitAndLog(OpCodes.Rem_Un) - | AI_shl -> ilG.EmitAndLog(OpCodes.Shl) - | AI_shr -> ilG.EmitAndLog(OpCodes.Shr) - | AI_shr_un -> ilG.EmitAndLog(OpCodes.Shr_Un) - | AI_sub -> ilG.EmitAndLog(OpCodes.Sub) - | AI_sub_ovf -> ilG.EmitAndLog(OpCodes.Sub_Ovf) - | AI_sub_ovf_un -> ilG.EmitAndLog(OpCodes.Sub_Ovf_Un) - | AI_xor -> ilG.EmitAndLog(OpCodes.Xor) - | AI_or -> ilG.EmitAndLog(OpCodes.Or) - | AI_neg -> ilG.EmitAndLog(OpCodes.Neg) - | AI_not -> ilG.EmitAndLog(OpCodes.Not) - | AI_ldnull -> ilG.EmitAndLog(OpCodes.Ldnull) - | AI_dup -> ilG.EmitAndLog(OpCodes.Dup) - | AI_pop -> ilG.EmitAndLog(OpCodes.Pop) - | AI_ckfinite -> ilG.EmitAndLog(OpCodes.Ckfinite) - | AI_nop -> ilG.EmitAndLog(OpCodes.Nop) - | AI_ldc (DT_I4, ILConst.I4 i32) -> ilG.EmitAndLog(OpCodes.Ldc_I4, i32) - | AI_ldc (DT_I8, ILConst.I8 i64) -> ilG.Emit(OpCodes.Ldc_I8, i64) - | AI_ldc (DT_R4, ILConst.R4 r32) -> ilG.Emit(OpCodes.Ldc_R4, r32) - | AI_ldc (DT_R8, ILConst.R8 r64) -> ilG.Emit(OpCodes.Ldc_R8, r64) - | AI_ldc (_ , _ ) -> failwith "emitInstrI_arith (AI_ldc (ty, const)) iltyped" - | I_ldarg u16 -> ilG.EmitAndLog(OpCodes.Ldarg , int16 u16) - | I_ldarga u16 -> ilG.EmitAndLog(OpCodes.Ldarga, int16 u16) - | I_ldind (align, vol, dt) -> + | AI_mul -> ilG.EmitAndLog(OpCodes.Mul) + | AI_mul_ovf -> ilG.EmitAndLog(OpCodes.Mul_Ovf) + | AI_mul_ovf_un -> ilG.EmitAndLog(OpCodes.Mul_Ovf_Un) + | AI_rem -> ilG.EmitAndLog(OpCodes.Rem) + | AI_rem_un -> ilG.EmitAndLog(OpCodes.Rem_Un) + | AI_shl -> ilG.EmitAndLog(OpCodes.Shl) + | AI_shr -> ilG.EmitAndLog(OpCodes.Shr) + | AI_shr_un -> ilG.EmitAndLog(OpCodes.Shr_Un) + | AI_sub -> ilG.EmitAndLog(OpCodes.Sub) + | AI_sub_ovf -> ilG.EmitAndLog(OpCodes.Sub_Ovf) + | AI_sub_ovf_un -> ilG.EmitAndLog(OpCodes.Sub_Ovf_Un) + | AI_xor -> ilG.EmitAndLog(OpCodes.Xor) + | AI_or -> ilG.EmitAndLog(OpCodes.Or) + | AI_neg -> ilG.EmitAndLog(OpCodes.Neg) + | AI_not -> ilG.EmitAndLog(OpCodes.Not) + | AI_ldnull -> ilG.EmitAndLog(OpCodes.Ldnull) + | AI_dup -> ilG.EmitAndLog(OpCodes.Dup) + | AI_pop -> ilG.EmitAndLog(OpCodes.Pop) + | AI_ckfinite -> ilG.EmitAndLog(OpCodes.Ckfinite) + | AI_nop -> ilG.EmitAndLog(OpCodes.Nop) + | AI_ldc (DT_I4, ILConst.I4 i32) -> ilG.EmitAndLog(OpCodes.Ldc_I4, i32) + | AI_ldc (DT_I8, ILConst.I8 i64) -> ilG.Emit(OpCodes.Ldc_I8, i64) + | AI_ldc (DT_R4, ILConst.R4 r32) -> ilG.Emit(OpCodes.Ldc_R4, r32) + | AI_ldc (DT_R8, ILConst.R8 r64) -> ilG.Emit(OpCodes.Ldc_R8, r64) + | AI_ldc (_, _ ) -> failwith "emitInstrI_arith (AI_ldc (ty, const)) iltyped" + | I_ldarg u16 -> ilG.EmitAndLog(OpCodes.Ldarg, int16 u16) + | I_ldarga u16 -> ilG.EmitAndLog(OpCodes.Ldarga, int16 u16) + | I_ldind (align, vol, dt) -> emitInstrAlign ilG align emitInstrVolatile ilG vol match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Ldind_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Ldind_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Ldind_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Ldind_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Ldind_I8) - | DT_R -> failwith "emitInstr cenv: ldind R" - | DT_R4 -> ilG.EmitAndLog(OpCodes.Ldind_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Ldind_R8) - | DT_U -> failwith "emitInstr cenv: ldind U" - | DT_U1 -> ilG.EmitAndLog(OpCodes.Ldind_U1) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Ldind_U2) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Ldind_U4) - | DT_U8 -> failwith "emitInstr cenv: ldind U8" + | DT_I -> ilG.EmitAndLog(OpCodes.Ldind_I) + | DT_I1 -> ilG.EmitAndLog(OpCodes.Ldind_I1) + | DT_I2 -> ilG.EmitAndLog(OpCodes.Ldind_I2) + | DT_I4 -> ilG.EmitAndLog(OpCodes.Ldind_I4) + | DT_I8 -> ilG.EmitAndLog(OpCodes.Ldind_I8) + | DT_R -> failwith "emitInstr cenv: ldind R" + | DT_R4 -> ilG.EmitAndLog(OpCodes.Ldind_R4) + | DT_R8 -> ilG.EmitAndLog(OpCodes.Ldind_R8) + | DT_U -> failwith "emitInstr cenv: ldind U" + | DT_U1 -> ilG.EmitAndLog(OpCodes.Ldind_U1) + | DT_U2 -> ilG.EmitAndLog(OpCodes.Ldind_U2) + | DT_U4 -> ilG.EmitAndLog(OpCodes.Ldind_U4) + | DT_U8 -> failwith "emitInstr cenv: ldind U8" | DT_REF -> ilG.EmitAndLog(OpCodes.Ldind_Ref) - | I_ldloc u16 -> ilG.EmitAndLog(OpCodes.Ldloc , int16 u16) + | I_ldloc u16 -> ilG.EmitAndLog(OpCodes.Ldloc, int16 u16) | I_ldloca u16 -> ilG.EmitAndLog(OpCodes.Ldloca, int16 u16) - | I_starg u16 -> ilG.EmitAndLog(OpCodes.Starg , int16 u16) - | I_stind (align, vol, dt) -> + | I_starg u16 -> ilG.EmitAndLog(OpCodes.Starg, int16 u16) + | I_stind (align, vol, dt) -> emitInstrAlign ilG align emitInstrVolatile ilG vol match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Stind_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Stind_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Stind_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Stind_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Stind_I8) - | DT_R -> failwith "emitInstr cenv: stind R" - | DT_R4 -> ilG.EmitAndLog(OpCodes.Stind_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Stind_R8) - | DT_U -> ilG.EmitAndLog(OpCodes.Stind_I) // NOTE: unsigned -> int conversion - | DT_U1 -> ilG.EmitAndLog(OpCodes.Stind_I1) // NOTE: follows code ilwrite.fs - | DT_U2 -> ilG.EmitAndLog(OpCodes.Stind_I2) // NOTE: is it ok? - | DT_U4 -> ilG.EmitAndLog(OpCodes.Stind_I4) // NOTE: it is generated by bytearray tests - | DT_U8 -> ilG.EmitAndLog(OpCodes.Stind_I8) // NOTE: unsigned -> int conversion + | DT_I -> ilG.EmitAndLog(OpCodes.Stind_I) + | DT_I1 -> ilG.EmitAndLog(OpCodes.Stind_I1) + | DT_I2 -> ilG.EmitAndLog(OpCodes.Stind_I2) + | DT_I4 -> ilG.EmitAndLog(OpCodes.Stind_I4) + | DT_I8 -> ilG.EmitAndLog(OpCodes.Stind_I8) + | DT_R -> failwith "emitInstr cenv: stind R" + | DT_R4 -> ilG.EmitAndLog(OpCodes.Stind_R4) + | DT_R8 -> ilG.EmitAndLog(OpCodes.Stind_R8) + | DT_U -> ilG.EmitAndLog(OpCodes.Stind_I) // NOTE: unsigned -> int conversion + | DT_U1 -> ilG.EmitAndLog(OpCodes.Stind_I1) // NOTE: follows code ilwrite.fs + | DT_U2 -> ilG.EmitAndLog(OpCodes.Stind_I2) // NOTE: is it ok? + | DT_U4 -> ilG.EmitAndLog(OpCodes.Stind_I4) // NOTE: it is generated by bytearray tests + | DT_U8 -> ilG.EmitAndLog(OpCodes.Stind_I8) // NOTE: unsigned -> int conversion | DT_REF -> ilG.EmitAndLog(OpCodes.Stind_Ref) - | I_stloc u16 -> ilG.EmitAndLog(OpCodes.Stloc, int16 u16) - | I_br targ -> ilG.EmitAndLog(OpCodes.Br, envGetLabel emEnv targ) + | I_stloc u16 -> ilG.EmitAndLog(OpCodes.Stloc, int16 u16) + | I_br targ -> ilG.EmitAndLog(OpCodes.Br, envGetLabel emEnv targ) | I_jmp mspec -> ilG.EmitAndLog(OpCodes.Jmp, convMethodSpec cenv emEnv mspec) | I_brcmp (comp, targ) -> emitInstrCompare emEnv ilG comp targ | I_switch labels -> ilG.Emit(OpCodes.Switch, Array.ofList (List.map (envGetLabel emEnv) labels)) | I_ret -> ilG.EmitAndLog(OpCodes.Ret) - | I_call (tail, mspec, varargs) -> + | I_call (tail, mspec, varargs) -> emitSilverlightCheck ilG emitInstrCall cenv emEnv ilG OpCodes.Call tail mspec varargs @@ -1127,7 +1133,7 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = ilG.Emit(OpCodes.Constrained, convType cenv emEnv ty) emitInstrCall cenv emEnv ilG OpCodes.Callvirt tail mspec varargs - | I_calli (tail, callsig, None) -> + | I_calli (tail, callsig, None) -> emitInstrTail ilG tail (fun () -> ilG.EmitCalli(OpCodes.Calli, convCallConv callsig.CallingConv, @@ -1149,49 +1155,49 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = | I_newobj (mspec, varargs) -> emitInstrNewobj cenv emEnv ilG mspec varargs - | I_throw -> ilG.EmitAndLog(OpCodes.Throw) - | I_endfinally -> ilG.EmitAndLog(OpCodes.Endfinally) - | I_endfilter -> ilG.EmitAndLog(OpCodes.Endfilter) - | I_leave label -> ilG.EmitAndLog(OpCodes.Leave, envGetLabel emEnv label) - | I_ldsfld (vol, fspec) -> emitInstrVolatile ilG vol; ilG.EmitAndLog(OpCodes.Ldsfld , convFieldSpec cenv emEnv fspec) - | I_ldfld (align, vol, fspec) -> emitInstrAlign ilG align; emitInstrVolatile ilG vol; ilG.EmitAndLog(OpCodes.Ldfld , convFieldSpec cenv emEnv fspec) - | I_ldsflda fspec -> ilG.EmitAndLog(OpCodes.Ldsflda, convFieldSpec cenv emEnv fspec) - | I_ldflda fspec -> ilG.EmitAndLog(OpCodes.Ldflda , convFieldSpec cenv emEnv fspec) + | I_throw -> ilG.EmitAndLog(OpCodes.Throw) + | I_endfinally -> ilG.EmitAndLog(OpCodes.Endfinally) + | I_endfilter -> ilG.EmitAndLog(OpCodes.Endfilter) + | I_leave label -> ilG.EmitAndLog(OpCodes.Leave, envGetLabel emEnv label) + | I_ldsfld (vol, fspec) -> emitInstrVolatile ilG vol; ilG.EmitAndLog(OpCodes.Ldsfld, convFieldSpec cenv emEnv fspec) + | I_ldfld (align, vol, fspec) -> emitInstrAlign ilG align; emitInstrVolatile ilG vol; ilG.EmitAndLog(OpCodes.Ldfld, convFieldSpec cenv emEnv fspec) + | I_ldsflda fspec -> ilG.EmitAndLog(OpCodes.Ldsflda, convFieldSpec cenv emEnv fspec) + | I_ldflda fspec -> ilG.EmitAndLog(OpCodes.Ldflda, convFieldSpec cenv emEnv fspec) - | I_stsfld (vol, fspec) -> + | I_stsfld (vol, fspec) -> emitInstrVolatile ilG vol ilG.EmitAndLog(OpCodes.Stsfld, convFieldSpec cenv emEnv fspec) - | I_stfld (align, vol, fspec) -> + | I_stfld (align, vol, fspec) -> emitInstrAlign ilG align emitInstrVolatile ilG vol ilG.EmitAndLog(OpCodes.Stfld, convFieldSpec cenv emEnv fspec) - | I_ldstr s -> ilG.EmitAndLog(OpCodes.Ldstr, s) - | I_isinst ty -> ilG.EmitAndLog(OpCodes.Isinst, convType cenv emEnv ty) - | I_castclass ty -> ilG.EmitAndLog(OpCodes.Castclass, convType cenv emEnv ty) - | I_ldtoken (ILToken.ILType ty) -> ilG.EmitAndLog(OpCodes.Ldtoken, convTypeOrTypeDef cenv emEnv ty) + | I_ldstr s -> ilG.EmitAndLog(OpCodes.Ldstr, s) + | I_isinst ty -> ilG.EmitAndLog(OpCodes.Isinst, convType cenv emEnv ty) + | I_castclass ty -> ilG.EmitAndLog(OpCodes.Castclass, convType cenv emEnv ty) + | I_ldtoken (ILToken.ILType ty) -> ilG.EmitAndLog(OpCodes.Ldtoken, convTypeOrTypeDef cenv emEnv ty) | I_ldtoken (ILToken.ILMethod mspec) -> ilG.EmitAndLog(OpCodes.Ldtoken, convMethodSpec cenv emEnv mspec) - | I_ldtoken (ILToken.ILField fspec) -> ilG.EmitAndLog(OpCodes.Ldtoken, convFieldSpec cenv emEnv fspec) - | I_ldvirtftn mspec -> ilG.EmitAndLog(OpCodes.Ldvirtftn, convMethodSpec cenv emEnv mspec) + | I_ldtoken (ILToken.ILField fspec) -> ilG.EmitAndLog(OpCodes.Ldtoken, convFieldSpec cenv emEnv fspec) + | I_ldvirtftn mspec -> ilG.EmitAndLog(OpCodes.Ldvirtftn, convMethodSpec cenv emEnv mspec) // Value type instructions - | I_cpobj ty -> ilG.EmitAndLog(OpCodes.Cpobj , convType cenv emEnv ty) - | I_initobj ty -> ilG.EmitAndLog(OpCodes.Initobj , convType cenv emEnv ty) + | I_cpobj ty -> ilG.EmitAndLog(OpCodes.Cpobj, convType cenv emEnv ty) + | I_initobj ty -> ilG.EmitAndLog(OpCodes.Initobj, convType cenv emEnv ty) | I_ldobj (align, vol, ty) -> emitInstrAlign ilG align emitInstrVolatile ilG vol - ilG.EmitAndLog(OpCodes.Ldobj , convType cenv emEnv ty) + ilG.EmitAndLog(OpCodes.Ldobj, convType cenv emEnv ty) | I_stobj (align, vol, ty) -> emitInstrAlign ilG align emitInstrVolatile ilG vol - ilG.EmitAndLog(OpCodes.Stobj , convType cenv emEnv ty) + ilG.EmitAndLog(OpCodes.Stobj, convType cenv emEnv ty) - | I_box ty -> ilG.EmitAndLog(OpCodes.Box , convType cenv emEnv ty) - | I_unbox ty -> ilG.EmitAndLog(OpCodes.Unbox , convType cenv emEnv ty) - | I_unbox_any ty -> ilG.EmitAndLog(OpCodes.Unbox_Any, convType cenv emEnv ty) - | I_sizeof ty -> ilG.EmitAndLog(OpCodes.Sizeof , convType cenv emEnv ty) + | I_box ty -> ilG.EmitAndLog(OpCodes.Box, convType cenv emEnv ty) + | I_unbox ty -> ilG.EmitAndLog(OpCodes.Unbox, convType cenv emEnv ty) + | I_unbox_any ty -> ilG.EmitAndLog(OpCodes.Unbox_Any, convType cenv emEnv ty) + | I_sizeof ty -> ilG.EmitAndLog(OpCodes.Sizeof, convType cenv emEnv ty) // Generalized array instructions. // In AbsIL these instructions include @@ -1205,55 +1211,55 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = // generalized instruction with the corresponding ILArrayShape // argument. This is done to simplify the IL and make it more uniform. // The IL writer then reverses this when emitting the binary. - | I_ldelem dt -> + | I_ldelem dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Ldelem_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Ldelem_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Ldelem_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Ldelem_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Ldelem_I8) - | DT_R -> failwith "emitInstr cenv: ldelem R" - | DT_R4 -> ilG.EmitAndLog(OpCodes.Ldelem_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Ldelem_R8) - | DT_U -> failwith "emitInstr cenv: ldelem U" - | DT_U1 -> ilG.EmitAndLog(OpCodes.Ldelem_U1) - | DT_U2 -> ilG.EmitAndLog(OpCodes.Ldelem_U2) - | DT_U4 -> ilG.EmitAndLog(OpCodes.Ldelem_U4) - | DT_U8 -> failwith "emitInstr cenv: ldelem U8" + | DT_I -> ilG.EmitAndLog(OpCodes.Ldelem_I) + | DT_I1 -> ilG.EmitAndLog(OpCodes.Ldelem_I1) + | DT_I2 -> ilG.EmitAndLog(OpCodes.Ldelem_I2) + | DT_I4 -> ilG.EmitAndLog(OpCodes.Ldelem_I4) + | DT_I8 -> ilG.EmitAndLog(OpCodes.Ldelem_I8) + | DT_R -> failwith "emitInstr cenv: ldelem R" + | DT_R4 -> ilG.EmitAndLog(OpCodes.Ldelem_R4) + | DT_R8 -> ilG.EmitAndLog(OpCodes.Ldelem_R8) + | DT_U -> failwith "emitInstr cenv: ldelem U" + | DT_U1 -> ilG.EmitAndLog(OpCodes.Ldelem_U1) + | DT_U2 -> ilG.EmitAndLog(OpCodes.Ldelem_U2) + | DT_U4 -> ilG.EmitAndLog(OpCodes.Ldelem_U4) + | DT_U8 -> failwith "emitInstr cenv: ldelem U8" | DT_REF -> ilG.EmitAndLog(OpCodes.Ldelem_Ref) | I_stelem dt -> match dt with - | DT_I -> ilG.EmitAndLog(OpCodes.Stelem_I) - | DT_I1 -> ilG.EmitAndLog(OpCodes.Stelem_I1) - | DT_I2 -> ilG.EmitAndLog(OpCodes.Stelem_I2) - | DT_I4 -> ilG.EmitAndLog(OpCodes.Stelem_I4) - | DT_I8 -> ilG.EmitAndLog(OpCodes.Stelem_I8) - | DT_R -> failwith "emitInstr cenv: stelem R" - | DT_R4 -> ilG.EmitAndLog(OpCodes.Stelem_R4) - | DT_R8 -> ilG.EmitAndLog(OpCodes.Stelem_R8) - | DT_U -> failwith "emitInstr cenv: stelem U" - | DT_U1 -> failwith "emitInstr cenv: stelem U1" - | DT_U2 -> failwith "emitInstr cenv: stelem U2" - | DT_U4 -> failwith "emitInstr cenv: stelem U4" - | DT_U8 -> failwith "emitInstr cenv: stelem U8" + | DT_I -> ilG.EmitAndLog(OpCodes.Stelem_I) + | DT_I1 -> ilG.EmitAndLog(OpCodes.Stelem_I1) + | DT_I2 -> ilG.EmitAndLog(OpCodes.Stelem_I2) + | DT_I4 -> ilG.EmitAndLog(OpCodes.Stelem_I4) + | DT_I8 -> ilG.EmitAndLog(OpCodes.Stelem_I8) + | DT_R -> failwith "emitInstr cenv: stelem R" + | DT_R4 -> ilG.EmitAndLog(OpCodes.Stelem_R4) + | DT_R8 -> ilG.EmitAndLog(OpCodes.Stelem_R8) + | DT_U -> failwith "emitInstr cenv: stelem U" + | DT_U1 -> failwith "emitInstr cenv: stelem U1" + | DT_U2 -> failwith "emitInstr cenv: stelem U2" + | DT_U4 -> failwith "emitInstr cenv: stelem U4" + | DT_U8 -> failwith "emitInstr cenv: stelem U8" | DT_REF -> ilG.EmitAndLog(OpCodes.Stelem_Ref) - | I_ldelema (ro, _isNativePtr, shape, ty) -> + | I_ldelema (ro, _isNativePtr, shape, ty) -> if (ro = ReadonlyAddress) then ilG.EmitAndLog(OpCodes.Readonly) if (shape = ILArrayShape.SingleDimensional) - then ilG.EmitAndLog(OpCodes.Ldelema, convType cenv emEnv ty) + then ilG.EmitAndLog(OpCodes.Ldelema, convType cenv emEnv ty) else - let aty = convType cenv emEnv (ILType.Array(shape, ty)) + let aty = convType cenv emEnv (ILType.Array(shape, ty)) let ety = aty.GetElementType() let rty = ety.MakeByRefType() let meth = modB.GetArrayMethodAndLog(aty, "Address", System.Reflection.CallingConventions.HasThis, rty, Array.create shape.Rank (typeof) ) ilG.EmitAndLog(OpCodes.Call, meth) - | I_ldelem_any (shape, ty) -> - if (shape = ILArrayShape.SingleDimensional) then ilG.EmitAndLog(OpCodes.Ldelem, convType cenv emEnv ty) + | I_ldelem_any (shape, ty) -> + if (shape = ILArrayShape.SingleDimensional) then ilG.EmitAndLog(OpCodes.Ldelem, convType cenv emEnv ty) else - let aty = convType cenv emEnv (ILType.Array(shape, ty)) + let aty = convType cenv emEnv (ILType.Array(shape, ty)) let ety = aty.GetElementType() let meth = #if ENABLE_MONO_SUPPORT @@ -1265,10 +1271,10 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = modB.GetArrayMethodAndLog(aty, "Get", System.Reflection.CallingConventions.HasThis, ety, Array.create shape.Rank (typeof) ) ilG.EmitAndLog(OpCodes.Call, meth) - | I_stelem_any (shape, ty) -> - if (shape = ILArrayShape.SingleDimensional) then ilG.EmitAndLog(OpCodes.Stelem, convType cenv emEnv ty) + | I_stelem_any (shape, ty) -> + if (shape = ILArrayShape.SingleDimensional) then ilG.EmitAndLog(OpCodes.Stelem, convType cenv emEnv ty) else - let aty = convType cenv emEnv (ILType.Array(shape, ty)) + let aty = convType cenv emEnv (ILType.Array(shape, ty)) let ety = aty.GetElementType() let meth = #if ENABLE_MONO_SUPPORT @@ -1280,21 +1286,21 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = 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) -> + | I_newarr (shape, ty) -> if (shape = ILArrayShape.SingleDimensional) - then ilG.EmitAndLog(OpCodes.Newarr, convType cenv emEnv ty) + then ilG.EmitAndLog(OpCodes.Newarr, convType cenv emEnv ty) else - let aty = convType cenv emEnv (ILType.Array(shape, ty)) + 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)) ilG.EmitAndLog(OpCodes.Newobj, meth) - | I_ldlen -> ilG.EmitAndLog(OpCodes.Ldlen) - | I_mkrefany ty -> ilG.EmitAndLog(OpCodes.Mkrefany, convType cenv emEnv ty) - | I_refanytype -> ilG.EmitAndLog(OpCodes.Refanytype) - | I_refanyval ty -> ilG.EmitAndLog(OpCodes.Refanyval, convType cenv emEnv ty) - | I_rethrow -> ilG.EmitAndLog(OpCodes.Rethrow) - | I_break -> ilG.EmitAndLog(OpCodes.Break) - | I_seqpoint src -> + | I_ldlen -> ilG.EmitAndLog(OpCodes.Ldlen) + | I_mkrefany ty -> ilG.EmitAndLog(OpCodes.Mkrefany, convType cenv emEnv ty) + | I_refanytype -> ilG.EmitAndLog(OpCodes.Refanytype) + | I_refanyval ty -> ilG.EmitAndLog(OpCodes.Refanyval, convType cenv emEnv ty) + | I_rethrow -> ilG.EmitAndLog(OpCodes.Rethrow) + | I_break -> ilG.EmitAndLog(OpCodes.Break) + | I_seqpoint src -> #if FX_RESHAPED_REFEMIT ignore src () @@ -1304,15 +1310,15 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = 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 - | I_arglist -> ilG.EmitAndLog(OpCodes.Arglist) - | I_localloc -> ilG.EmitAndLog(OpCodes.Localloc) + | I_arglist -> ilG.EmitAndLog(OpCodes.Arglist) + | I_localloc -> ilG.EmitAndLog(OpCodes.Localloc) | I_cpblk (align, vol) -> emitInstrAlign ilG align emitInstrVolatile ilG vol ilG.EmitAndLog(OpCodes.Cpblk) - | I_initblk (align, vol) -> + | I_initblk (align, vol) -> emitInstrAlign ilG align emitInstrVolatile ilG vol ilG.EmitAndLog(OpCodes.Initblk) @@ -1327,7 +1333,7 @@ let rec emitInstr cenv (modB: ModuleBuilder) emEnv (ilG: ILGenerator) instr = let emitCode cenv modB emEnv (ilG: ILGenerator) (code: ILCode) = // Pre-define the labels pending determining their actual marks let pc2lab = Dictionary() - let emEnv = + let emEnv = (emEnv, code.Labels) ||> Seq.fold (fun emEnv (KeyValue(label, pc)) -> let lab = ilG.DefineLabelAndLog() pc2lab.[pc] <- @@ -1366,7 +1372,7 @@ let emitCode cenv modB emEnv (ilG: ILGenerator) (code: ILCode) = add endHandler ilG.EndExceptionBlockAndLog | ILExceptionClause.TypeCatch(ty, (startHandler, endHandler)) -> - add startHandler (fun () -> ilG.BeginCatchBlockAndLog (convType cenv emEnv ty)) + add startHandler (fun () -> ilG.BeginCatchBlockAndLog (convType cenv emEnv ty)) add endHandler ilG.EndExceptionBlockAndLog // Emit the instructions @@ -1392,7 +1398,7 @@ let emitCode cenv modB emEnv (ilG: ILGenerator) (code: ILCode) = let emitLocal cenv emEnv (ilG: ILGenerator) (local: ILLocal) = - let ty = convType cenv emEnv local.Type + let ty = convType cenv emEnv local.Type let locBuilder = ilG.DeclareLocalAndLog(ty, local.IsPinned) #if !FX_NO_PDB_WRITER match local.DebugInfo with @@ -1409,11 +1415,11 @@ let emitILMethodBody cenv modB emEnv (ilG: ILGenerator) (ilmbody: ILMethodBody) let emitMethodBody cenv modB emEnv ilG _name (mbody: ILLazyMethodBody) = match mbody.Contents with - | MethodBody.IL ilmbody -> emitILMethodBody cenv modB emEnv (ilG()) ilmbody - | MethodBody.PInvoke _pinvoke -> () - | MethodBody.Abstract -> () - | MethodBody.Native -> failwith "emitMethodBody: native" - | MethodBody.NotAvailable -> failwith "emitMethodBody: metadata only" + | MethodBody.IL ilmbody -> emitILMethodBody cenv modB emEnv (ilG()) ilmbody + | MethodBody.PInvoke _pinvoke -> () + | MethodBody.Abstract -> () + | MethodBody.Native -> failwith "emitMethodBody: native" + | MethodBody.NotAvailable -> failwith "emitMethodBody: metadata only" let convCustomAttr cenv emEnv (cattr: ILAttribute) = let methInfo = @@ -1423,7 +1429,7 @@ let convCustomAttr cenv emEnv (cattr: ILAttribute) = let data = getCustomAttrData cenv.ilg cattr (methInfo, data) -let emitCustomAttr cenv emEnv add cattr = add (convCustomAttr cenv emEnv cattr) +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 //---------------------------------------------------------------------------- @@ -1435,14 +1441,14 @@ let buildGenParamsPass1 _emEnv defineGenericParameters (gps: ILGenericParameterD | [] -> () | gps -> let gpsNames = gps |> List.map (fun gp -> gp.Name) - defineGenericParameters (Array.ofList gpsNames) |> ignore + defineGenericParameters (Array.ofList gpsNames) |> ignore let buildGenParamsPass1b cenv emEnv (genArgs: Type array) (gps: ILGenericParameterDefs) = #if FX_RESHAPED_REFLECTION - let genpBs = genArgs |> Array.map (fun x -> (x.GetTypeInfo() :?> GenericTypeParameterBuilder)) + let genpBs = genArgs |> Array.map (fun x -> (x.GetTypeInfo() :?> GenericTypeParameterBuilder)) #else - let genpBs = genArgs |> Array.map (fun x -> (x :?> GenericTypeParameterBuilder)) + let genpBs = genArgs |> Array.map (fun x -> (x :?> GenericTypeParameterBuilder)) #endif gps |> List.iteri (fun i (gp: ILGenericParameterDef) -> let gpB = genpBs.[i] @@ -1451,9 +1457,9 @@ let buildGenParamsPass1b cenv emEnv (genArgs: Type array) (gps: ILGenericParamet 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? + [ ] -> () // Q: should a baseType be set? It is in some samples. Should this be a failure case? | [ baseT ] -> gpB.SetBaseTypeConstraint(baseT) - | _ -> failwith "buildGenParam: multiple base types" + | _ -> failwith "buildGenParam: multiple base types" ) // set interface constraints (interfaces that instances of gp must meet) gpB.SetInterfaceConstraints(Array.ofList interfaceTs) @@ -1462,13 +1468,13 @@ let buildGenParamsPass1b cenv emEnv (genArgs: Type array) (gps: ILGenericParamet let flags = GenericParameterAttributes.None let flags = match gp.Variance with - | NonVariant -> flags - | CoVariant -> flags ||| GenericParameterAttributes.Covariant + | NonVariant -> flags + | CoVariant -> flags ||| GenericParameterAttributes.Covariant | ContraVariant -> flags ||| GenericParameterAttributes.Contravariant - let flags = if gp.HasReferenceTypeConstraint then flags ||| GenericParameterAttributes.ReferenceTypeConstraint else flags + let flags = if gp.HasReferenceTypeConstraint then flags ||| GenericParameterAttributes.ReferenceTypeConstraint else flags let flags = if gp.HasNotNullableValueTypeConstraint then flags ||| GenericParameterAttributes.NotNullableValueTypeConstraint else flags - let flags = if gp.HasDefaultConstructorConstraint then flags ||| GenericParameterAttributes.DefaultConstructorConstraint else flags + let flags = if gp.HasDefaultConstructorConstraint then flags ||| GenericParameterAttributes.DefaultConstructorConstraint else flags gpB.SetGenericParameterAttributes(flags) ) @@ -1480,13 +1486,13 @@ let emitParameter cenv emEnv (defineParameter: int * ParameterAttributes * strin // -Type: ty // -Default: ILFieldInit option // -Marshal: NativeType option; (* Marshalling map for parameters. COM Interop only. *) - let attrs = flagsIf param.IsIn ParameterAttributes.In ||| - flagsIf param.IsOut ParameterAttributes.Out ||| + let attrs = flagsIf param.IsIn ParameterAttributes.In ||| + flagsIf param.IsOut ParameterAttributes.Out ||| flagsIf param.IsOptional ParameterAttributes.Optional let name = match param.Name with | Some name -> name - | None -> "X" + string(i+1) + | None -> "X" + string(i+1) let parB = defineParameter(i, attrs, name) emitCustomAttrs cenv emEnv (wrapCustomAttr parB.SetCustomAttribute) param.CustomAttrs @@ -1507,9 +1513,9 @@ let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) emEnv match mdef.Body.Contents with #if !FX_RESHAPED_REFEMIT - | MethodBody.PInvoke p -> + | MethodBody.PInvoke p -> let argtys = convTypesToArray cenv emEnv mdef.ParameterTypes - let rty = convType cenv emEnv mdef.Return.Type + let rty = convType cenv emEnv mdef.Return.Type let pcc = match p.CallingConv with @@ -1541,7 +1547,7 @@ let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) let consB = typB.DefineConstructorAndLog(attrs, cconv, convTypesToArray cenv emEnv mdef.ParameterTypes) consB.SetImplementationFlagsAndLog(implflags) envBindConsRef emEnv mref consB - | _name -> + | _name -> // The return/argument types may involve the generic parameters let methB = typB.DefineMethodAndLog(mdef.Name, attrs, cconv) @@ -1560,7 +1566,7 @@ let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) |> Array.unzip let returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers = mdef.Return |> convReturnModifiers cenv emEnv - let returnType = convType cenv emEnv mdef.Return.Type + let returnType = convType cenv emEnv mdef.Return.Type methB.SetSignatureAndLog(returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers,parameterTypeOptionalCustomModifiers) @@ -1574,10 +1580,10 @@ let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) //---------------------------------------------------------------------------- let rec buildMethodPass3 cenv tref modB (typB: TypeBuilder) emEnv (mdef: ILMethodDef) = - let mref = mkRefToILMethod (tref, mdef) + let mref = mkRefToILMethod (tref, mdef) let isPInvoke = match mdef.Body.Contents with - | MethodBody.PInvoke _p -> true + | MethodBody.PInvoke _p -> true | _ -> false match mdef.Name with | ".cctor" | ".ctor" -> @@ -1618,7 +1624,7 @@ let rec buildMethodPass3 cenv tref modB (typB: TypeBuilder) emEnv (mdef: ILMetho let buildFieldPass2 cenv tref (typB: TypeBuilder) emEnv (fdef: ILFieldDef) = let attrs = fdef.Attributes - let fieldT = convType cenv emEnv fdef.FieldType + let fieldT = convType cenv emEnv fdef.FieldType let fieldB = match fdef.Data with | Some d -> typB.DefineInitializedData(fdef.Name, d, attrs) @@ -1642,7 +1648,7 @@ let buildFieldPass2 cenv tref (typB: TypeBuilder) emEnv (fdef: ILFieldDef) = // => here we cannot detect if underlying type is already set so as a conservative solution we delay initialization of fields // to the end of pass2 (types and members are already created but method bodies are yet not emitted) { emEnv with delayedFieldInits = (fun() -> fieldB.SetConstant(convFieldInit initial))::emEnv.delayedFieldInits } - fdef.Offset |> Option.iter (fun offset -> fieldB.SetOffset(offset)) + fdef.Offset |> Option.iter (fun offset -> fieldB.SetOffset(offset)) // custom attributes: done on pass 3 as they may reference attribute constructors generated on // pass 2. let fref = mkILFieldRef (tref, fdef.Name, fdef.FieldType) @@ -1659,9 +1665,9 @@ let buildFieldPass3 cenv tref (_typB: TypeBuilder) emEnv (fdef: ILFieldDef) = let buildPropertyPass2 cenv tref (typB: TypeBuilder) emEnv (prop: ILPropertyDef) = let attrs = flagsIf prop.IsRTSpecialName PropertyAttributes.RTSpecialName ||| - flagsIf prop.IsSpecialName PropertyAttributes.SpecialName + flagsIf prop.IsSpecialName PropertyAttributes.SpecialName - let propB = typB.DefinePropertyAndLog(prop.Name, attrs, convType cenv emEnv prop.PropertyType, convTypesToArray cenv emEnv prop.Args) + let propB = typB.DefinePropertyAndLog(prop.Name, attrs, convType cenv emEnv prop.PropertyType, convTypesToArray cenv emEnv prop.Args) prop.SetMethod |> Option.iter (fun mref -> propB.SetSetMethod(envGetMethB emEnv mref)) prop.GetMethod |> Option.iter (fun mref -> propB.SetGetMethod(envGetMethB emEnv mref)) @@ -1685,7 +1691,7 @@ let buildEventPass3 cenv (typB: TypeBuilder) emEnv (eventDef: ILEventDef) = let attrs = flagsIf eventDef.IsSpecialName EventAttributes.SpecialName ||| flagsIf eventDef.IsRTSpecialName EventAttributes.RTSpecialName assert eventDef.EventType.IsSome - let eventB = typB.DefineEventAndLog(eventDef.Name, attrs, convType cenv emEnv eventDef.EventType.Value) + let eventB = typB.DefineEventAndLog(eventDef.Name, attrs, convType cenv emEnv eventDef.EventType.Value) eventDef.AddMethod |> (fun mref -> eventB.SetAddOnMethod(envGetMethB emEnv mref)) eventDef.RemoveMethod |> (fun mref -> eventB.SetRemoveOnMethod(envGetMethB emEnv mref)) @@ -1700,7 +1706,7 @@ let buildEventPass3 cenv (typB: TypeBuilder) emEnv (eventDef: ILEventDef) = 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 + let declMethTI = convType cenv emEnv dtyp let declMethInfo = convMethodRef cenv emEnv declMethTI mref typB.DefineMethodOverride(bodyMethInfo, declMethInfo) emEnv @@ -1712,31 +1718,31 @@ let buildMethodImplsPass3 cenv _tref (typB: TypeBuilder) emEnv (mimpl: IL.ILMeth let typeAttrbutesOfTypeDefKind x = match x with // required for a TypeBuilder - | ILTypeDefKind.Class -> TypeAttributes.Class - | ILTypeDefKind.ValueType -> TypeAttributes.Class - | ILTypeDefKind.Interface -> TypeAttributes.Interface - | ILTypeDefKind.Enum -> TypeAttributes.Class - | ILTypeDefKind.Delegate -> TypeAttributes.Class + | ILTypeDefKind.Class -> TypeAttributes.Class + | ILTypeDefKind.ValueType -> TypeAttributes.Class + | ILTypeDefKind.Interface -> TypeAttributes.Interface + | ILTypeDefKind.Enum -> TypeAttributes.Class + | ILTypeDefKind.Delegate -> TypeAttributes.Class let typeAttrbutesOfTypeAccess x = match x with - | ILTypeDefAccess.Public -> TypeAttributes.Public - | ILTypeDefAccess.Private -> TypeAttributes.NotPublic - | ILTypeDefAccess.Nested macc -> + | ILTypeDefAccess.Public -> TypeAttributes.Public + | ILTypeDefAccess.Private -> TypeAttributes.NotPublic + | ILTypeDefAccess.Nested macc -> match macc with - | ILMemberAccess.Assembly -> TypeAttributes.NestedAssembly - | ILMemberAccess.CompilerControlled -> failwith "Nested compiler controled." - | ILMemberAccess.FamilyAndAssembly -> TypeAttributes.NestedFamANDAssem - | ILMemberAccess.FamilyOrAssembly -> TypeAttributes.NestedFamORAssem - | ILMemberAccess.Family -> TypeAttributes.NestedFamily - | ILMemberAccess.Private -> TypeAttributes.NestedPrivate - | ILMemberAccess.Public -> TypeAttributes.NestedPublic + | ILMemberAccess.Assembly -> TypeAttributes.NestedAssembly + | ILMemberAccess.CompilerControlled -> failwith "Nested compiler controled." + | ILMemberAccess.FamilyAndAssembly -> TypeAttributes.NestedFamANDAssem + | ILMemberAccess.FamilyOrAssembly -> TypeAttributes.NestedFamORAssem + | ILMemberAccess.Family -> TypeAttributes.NestedFamily + | ILMemberAccess.Private -> TypeAttributes.NestedPrivate + | ILMemberAccess.Public -> TypeAttributes.NestedPublic let typeAttributesOfTypeEncoding x = match x with - | ILDefaultPInvokeEncoding.Ansi -> TypeAttributes.AnsiClass + | ILDefaultPInvokeEncoding.Ansi -> TypeAttributes.AnsiClass | ILDefaultPInvokeEncoding.Auto -> TypeAttributes.AutoClass - | ILDefaultPInvokeEncoding.Unicode -> TypeAttributes.UnicodeClass + | ILDefaultPInvokeEncoding.Unicode -> TypeAttributes.UnicodeClass let typeAttributesOfTypeLayout cenv emEnv x = @@ -1750,12 +1756,12 @@ let typeAttributesOfTypeLayout cenv emEnv x = (tref1, [mkILNonGenericValueTy tref2 ], [ ILAttribElem.Int32 x ], - (p.Pack |> Option.toList |> List.map (fun x -> ("Pack", cenv.ilg.typ_Int32, false, ILAttribElem.Int32 (int32 x)))) @ + (p.Pack |> Option.toList |> List.map (fun x -> ("Pack", cenv.ilg.typ_Int32, false, ILAttribElem.Int32 (int32 x)))) @ (p.Size |> Option.toList |> List.map (fun x -> ("Size", cenv.ilg.typ_Int32, false, ILAttribElem.Int32 x)))))) | _ -> None match x with - | ILTypeDefLayout.Auto -> None - | ILTypeDefLayout.Explicit p -> (attr 0x02 p) + | ILTypeDefLayout.Auto -> None + | ILTypeDefLayout.Explicit p -> (attr 0x02 p) | ILTypeDefLayout.Sequential p -> (attr 0x00 p) @@ -1773,7 +1779,7 @@ let rec buildTypeDefPass1 cenv emEnv (modB: ModuleBuilder) rootTypeBuilder nesti 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 @@ -1801,12 +1807,12 @@ and buildTypeTypeDef cenv emEnv modB (typB: TypeBuilder) nesting tdef = let rec buildTypeDefPass1b cenv nesting emEnv (tdef: ILTypeDef) = let tref = mkRefForNestedILTypeDef ILScopeRef.Local (nesting, tdef) - let typB = envGetTypB emEnv tref + let typB = envGetTypB emEnv tref let genArgs = getGenericArgumentsOfType (typB.AsType()) let emEnv = envPushTyvars emEnv genArgs // Parent may reference types being defined, so has to come after it's Pass1 creation - tdef.Extends |> Option.iter (fun ty -> typB.SetParentAndLog(convType cenv emEnv ty)) - // build constraints on ILGenericParameterDefs. Constraints may reference types being defined, + tdef.Extends |> Option.iter (fun ty -> typB.SetParentAndLog(convType cenv emEnv ty)) + // build constraints on ILGenericParameterDefs. Constraints may reference types being defined, // so have to come after all types are created buildGenParamsPass1b cenv emEnv genArgs tdef.GenericParams let emEnv = envPopTyvars emEnv @@ -1819,14 +1825,14 @@ let rec buildTypeDefPass1b 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 typB = envGetTypB emEnv tref let emEnv = envPushTyvars emEnv (getGenericArgumentsOfType (typB.AsType())) // add interface impls tdef.Implements |> convTypes cenv emEnv |> List.iter (fun implT -> typB.AddInterfaceImplementationAndLog(implT)) // add methods, properties - let emEnv = Array.fold (buildMethodPass2 cenv tref typB) emEnv tdef.Methods.AsArray - let emEnv = List.fold (buildFieldPass2 cenv tref typB) emEnv tdef.Fields.AsList - let emEnv = List.fold (buildPropertyPass2 cenv tref typB) emEnv tdef.Properties.AsList + let emEnv = Array.fold (buildMethodPass2 cenv tref typB) emEnv tdef.Methods.AsArray + let emEnv = List.fold (buildFieldPass2 cenv tref typB) emEnv tdef.Fields.AsList + let emEnv = List.fold (buildPropertyPass2 cenv tref typB) emEnv tdef.Properties.AsList let emEnv = envPopTyvars emEnv // nested types let nesting = nesting @ [tdef] @@ -1861,9 +1867,9 @@ let rec buildTypeDefPass3 cenv nesting modB emEnv (tdef: ILTypeDef) = // The code in this phase is fragile. // // THe background is that System.Reflection.Emit implementations can be finnickity about the -// order that CreateType calls are made when types refer to each other. Some of these restrictions +// order that CreateType calls are made when types refer to each other. Some of these restrictions // are not well documented, or are related to historical bugs where the F# emit code worked around the -// underlying problems. Ideally the SRE implementation would just "work this out as it goes along" but +// underlying problems. Ideally the SRE implementation would just "work this out as it goes along" but // unfortunately that's not been the case. // // Here are some known cases: @@ -1888,7 +1894,7 @@ let rec buildTypeDefPass3 cenv nesting modB emEnv (tdef: ILTypeDef) = // // // There is also a case where generic parameter constraints were being checked before -// a generic method was called. This forced the loading of the types involved in the +// a generic method was called. This forced the loading of the types involved in the // constraints very early. // @@ -1906,7 +1912,7 @@ type CollectTypes = ValueTypesOnly | All let rec getTypeRefsInType (allTypes: CollectTypes) ty acc = match ty with | ILType.Void - | ILType.TypeVar _ -> acc + | ILType.TypeVar _ -> acc | ILType.Ptr eltType | ILType.Byref eltType -> getTypeRefsInType allTypes eltType acc | ILType.Array (_, eltType) -> @@ -1922,7 +1928,7 @@ let rec getTypeRefsInType (allTypes: CollectTypes) ty acc = | CollectTypes.ValueTypesOnly -> acc | CollectTypes.All -> tspec.TypeRef :: List.foldBack (getTypeRefsInType allTypes) tspec.GenericArgs acc | ILType.FunctionPointer _callsig -> failwith "getTypeRefsInType: fptr" - | ILType.Modified _ -> failwith "getTypeRefsInType: modified" + | ILType.Modified _ -> failwith "getTypeRefsInType: modified" let verbose2 = false @@ -1986,11 +1992,11 @@ let createTypeRef (visited: Dictionary<_, _>, created: Dictionary<_, _>) emEnv t let typeName = r.Name let typeRef = ILTypeRef.Create(ILScopeRef.Local, nestingToProbe, typeName) match emEnv.emTypMap.TryFind typeRef with - | Some(_, tb, _, _) -> + | Some(_, tb, _, _) -> if not (tb.IsCreated()) then tb.CreateTypeAndLog() |> ignore tb.Assembly - | None -> null + | None -> null ) // For some reason, the handler is installed while running 'traverseTypeDef' but not while defining the type // itself. @@ -2001,11 +2007,11 @@ let createTypeRef (visited: Dictionary<_, _>, created: Dictionary<_, _>) emEnv t System.AppDomain.CurrentDomain.remove_TypeResolve typeCreationHandler #endif // At this point, we've done everything we can to prepare the type for loading by eagerly forcing the - // load of other types. Everything else is up to the implementation of System.Reflection.Emit. + // load of other types. Everything else is up to the implementation of System.Reflection.Emit. if not (created.ContainsKey(tref)) then created.[tref] <- true if verbose2 then dprintf "- creating type %s\n" typB.FullName - typB.CreateTypeAndLog() |> ignore + typB.CreateTypeAndLog() |> ignore traverseTypeRef tref @@ -2026,10 +2032,10 @@ let rec buildTypeDefPass4 (visited, created) nesting 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 -let buildModuleTypePass2 cenv emEnv tdef = buildTypeDefPass2 cenv [] emEnv tdef +let buildModuleTypePass1b cenv emEnv tdef = buildTypeDefPass1b cenv [] emEnv tdef +let buildModuleTypePass2 cenv emEnv tdef = buildTypeDefPass2 cenv [] emEnv tdef let buildModuleTypePass3 cenv modB emEnv tdef = buildTypeDefPass3 cenv [] modB emEnv tdef -let buildModuleTypePass4 visited emEnv tdef = buildTypeDefPass4 visited [] emEnv tdef +let buildModuleTypePass4 visited emEnv tdef = buildTypeDefPass4 visited [] emEnv tdef //---------------------------------------------------------------------------- // buildModuleFragment - only the types the fragment get written @@ -2050,7 +2056,7 @@ let buildModuleFragment cenv emEnv (asmB: AssemblyBuilder) (modB: ModuleBuilder) let emEnv = (emEnv, tdefs) ||> List.fold (buildModuleTypePass3 cenv modB) let visited = new Dictionary<_, _>(10) let created = new Dictionary<_, _>(10) - tdefs |> List.iter (buildModuleTypePass4 (visited, created) emEnv) + tdefs |> List.iter (buildModuleTypePass4 (visited, created) emEnv) let emEnv = Seq.fold envUpdateCreatedTypeRef emEnv created.Keys // update typT with the created typT emitCustomAttrs cenv emEnv modB.SetCustomAttributeAndLog m.CustomAttrs #if FX_RESHAPED_REFEMIT @@ -2078,7 +2084,7 @@ let defineDynamicAssemblyAndLog(asmName, flags, asmDir: string) = #if FX_NO_APP_DOMAINS let asmB = AssemblyBuilder.DefineDynamicAssembly(asmName, flags) #else - let currentDom = System.AppDomain.CurrentDomain + let currentDom = System.AppDomain.CurrentDomain let asmB = currentDom.DefineDynamicAssembly(asmName, flags, asmDir) #endif if logRefEmitCalls then @@ -2090,7 +2096,7 @@ let defineDynamicAssemblyAndLog(asmName, flags, asmDir: string) = let mkDynamicAssemblyAndModule (assemblyName, optimize, debugInfo, collectible) = let filename = assemblyName + ".dll" - let asmDir = "." + let asmDir = "." let asmName = new AssemblyName() asmName.Name <- assemblyName let asmAccess = @@ -2104,7 +2110,7 @@ let mkDynamicAssemblyAndModule (assemblyName, optimize, debugInfo, collectible) if not optimize then let daType = typeof let daCtor = daType.GetConstructor [| typeof |] - let daBuilder = new CustomAttributeBuilder(daCtor, [| System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations ||| System.Diagnostics.DebuggableAttribute.DebuggingModes.Default |]) + let daBuilder = new CustomAttributeBuilder(daCtor, [| System.Diagnostics.DebuggableAttribute.DebuggingModes.DisableOptimizations ||| System.Diagnostics.DebuggableAttribute.DebuggingModes.Default |]) asmB.SetCustomAttributeAndLog(daBuilder) let modB = asmB.DefineDynamicModuleAndLog(assemblyName, filename, debugInfo) @@ -2144,10 +2150,10 @@ let emitModuleFragment (ilg, emEnv, asmB: AssemblyBuilder, modB: ModuleBuilder, // 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 -let LookupType cenv emEnv ty = convCreatedType cenv emEnv ty +let LookupTypeRef cenv emEnv tref = convCreatedTypeRef cenv emEnv tref +let LookupType cenv emEnv ty = convCreatedType cenv emEnv ty // Lookups of ILFieldRef and MethodRef may require a similar non-Builder-fixup post Type-creation. -let LookupFieldRef emEnv fref = Zmap.tryFind fref emEnv.emFieldMap |> Option.map (fun fieldBuilder -> fieldBuilder :> FieldInfo) -let LookupMethodRef emEnv mref = Zmap.tryFind mref emEnv.emMethMap |> Option.map (fun methodBuilder -> methodBuilder :> MethodInfo) +let LookupFieldRef emEnv fref = Zmap.tryFind fref emEnv.emFieldMap |> Option.map (fun fieldBuilder -> fieldBuilder :> FieldInfo) +let LookupMethodRef emEnv mref = Zmap.tryFind mref emEnv.emMethMap |> Option.map (fun methodBuilder -> methodBuilder :> MethodInfo) diff --git a/src/absil/ilsupp.fs b/src/absil/ilsupp.fs index 63ff3211f03..5f9932662d8 100644 --- a/src/absil/ilsupp.fs +++ b/src/absil/ilsupp.fs @@ -45,11 +45,11 @@ 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 diff --git a/src/absil/ilwrite.fs b/src/absil/ilwrite.fs index 74cbc5e43b1..a8b879ce2b4 100644 --- a/src/absil/ilwrite.fs +++ b/src/absil/ilwrite.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 internal FSharp.Compiler.AbstractIL.ILBinaryWriter @@ -34,10 +34,10 @@ let showEntryLookups = false //--------------------------------------------------------------------- // Little-endian encoding of int32 -let b0 n = byte (n &&& 0xFF) -let b1 n = byte ((n >>> 8) &&& 0xFF) -let b2 n = byte ((n >>> 16) &&& 0xFF) -let b3 n = byte ((n >>> 24) &&& 0xFF) +let b0 n = byte (n &&& 0xFF) +let b1 n = byte ((n >>> 8) &&& 0xFF) +let b2 n = byte ((n >>> 16) &&& 0xFF) +let b3 n = byte ((n >>> 24) &&& 0xFF) // Little-endian encoding of int64 let dw7 n = byte ((n >>> 56) &&& 0xFFL) @@ -46,7 +46,7 @@ let dw5 n = byte ((n >>> 40) &&& 0xFFL) let dw4 n = byte ((n >>> 32) &&& 0xFFL) let dw3 n = byte ((n >>> 24) &&& 0xFFL) let dw2 n = byte ((n >>> 16) &&& 0xFFL) -let dw1 n = byte ((n >>> 8) &&& 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) @@ -71,16 +71,16 @@ type ByteBuffer with /// Emit int32 as compressed unsigned integer member buf.EmitZ32 n = - if n >= 0 && n <= 0x7F then + if n >= 0 && n <= 0x7F then buf.EmitIntAsByte n elif n >= 0x80 && n <= 0x3FFF then buf.EmitIntAsByte (0x80 ||| (n >>> 8)) buf.EmitIntAsByte (n &&& 0xFF) else - buf.EmitIntAsByte (0xc0l ||| ((n >>> 24) &&& 0xFF)) - buf.EmitIntAsByte ( (n >>> 16) &&& 0xFF) - buf.EmitIntAsByte ( (n >>> 8) &&& 0xFF) - buf.EmitIntAsByte ( n &&& 0xFF) + buf.EmitIntAsByte (0xC0 ||| ((n >>> 24) &&& 0xFF)) + buf.EmitIntAsByte ((n >>> 16) &&& 0xFF) + buf.EmitIntAsByte ((n >>> 8) &&& 0xFF) + buf.EmitIntAsByte (n &&& 0xFF) member buf.EmitPadding n = for i = 0 to n-1 do @@ -144,7 +144,7 @@ let checkFixup32 (data: byte[]) offset exp = if data.[offset] <> b0 exp then failwith "fixup sanity check failed" let applyFixup32 (data: byte[]) offset v = - data.[offset] <- b0 v + data.[offset] <- b0 v data.[offset+1] <- b1 v data.[offset+2] <- b2 v data.[offset+3] <- b3 v @@ -222,59 +222,59 @@ module RowElementTags = let [] Blob = 5 let [] String = 6 let [] SimpleIndexMin = 7 - let SimpleIndex (t : TableName) = assert (t.Index <= 112); SimpleIndexMin + t.Index + let SimpleIndex (t : TableName) = assert (t.Index <= 112); SimpleIndexMin + t.Index let [] SimpleIndexMax = 119 let [] TypeDefOrRefOrSpecMin = 120 - let TypeDefOrRefOrSpec (t: TypeDefOrRefTag) = assert (t.Tag <= 2); TypeDefOrRefOrSpecMin + t.Tag (* + 111 + 1 = 0x70 + 1 = max TableName.Tndex + 1 *) + let TypeDefOrRefOrSpec (t: TypeDefOrRefTag) = assert (t.Tag <= 2); TypeDefOrRefOrSpecMin + t.Tag (* + 111 + 1 = 0x70 + 1 = max TableName.Tndex + 1 *) let [] TypeDefOrRefOrSpecMax = 122 let [] TypeOrMethodDefMin = 123 - let TypeOrMethodDef (t: TypeOrMethodDefTag) = assert (t.Tag <= 1); TypeOrMethodDefMin + t.Tag (* + 2 + 1 = max TypeDefOrRefOrSpec.Tag + 1 *) + let TypeOrMethodDef (t: TypeOrMethodDefTag) = assert (t.Tag <= 1); TypeOrMethodDefMin + t.Tag (* + 2 + 1 = max TypeDefOrRefOrSpec.Tag + 1 *) let [] TypeOrMethodDefMax = 124 let [] HasConstantMin = 125 - let HasConstant (t: HasConstantTag) = assert (t.Tag <= 2); HasConstantMin + t.Tag (* + 1 + 1 = max TypeOrMethodDef.Tag + 1 *) + let HasConstant (t: HasConstantTag) = assert (t.Tag <= 2); HasConstantMin + t.Tag (* + 1 + 1 = max TypeOrMethodDef.Tag + 1 *) let [] HasConstantMax = 127 let [] HasCustomAttributeMin = 128 - let HasCustomAttribute (t: HasCustomAttributeTag) = assert (t.Tag <= 21); HasCustomAttributeMin + t.Tag (* + 2 + 1 = max HasConstant.Tag + 1 *) + let HasCustomAttribute (t: HasCustomAttributeTag) = assert (t.Tag <= 21); HasCustomAttributeMin + t.Tag (* + 2 + 1 = max HasConstant.Tag + 1 *) let [] HasCustomAttributeMax = 149 let [] HasFieldMarshalMin = 150 - let HasFieldMarshal (t: HasFieldMarshalTag) = assert (t.Tag <= 1); HasFieldMarshalMin + t.Tag (* + 21 + 1 = max HasCustomAttribute.Tag + 1 *) + let HasFieldMarshal (t: HasFieldMarshalTag) = assert (t.Tag <= 1); HasFieldMarshalMin + t.Tag (* + 21 + 1 = max HasCustomAttribute.Tag + 1 *) let [] HasFieldMarshalMax = 151 let [] HasDeclSecurityMin = 152 - let HasDeclSecurity (t: HasDeclSecurityTag) = assert (t.Tag <= 2); HasDeclSecurityMin + t.Tag (* + 1 + 1 = max HasFieldMarshal.Tag + 1 *) + let HasDeclSecurity (t: HasDeclSecurityTag) = assert (t.Tag <= 2); HasDeclSecurityMin + t.Tag (* + 1 + 1 = max HasFieldMarshal.Tag + 1 *) let [] HasDeclSecurityMax = 154 let [] MemberRefParentMin = 155 - let MemberRefParent (t: MemberRefParentTag) = assert (t.Tag <= 4); MemberRefParentMin + t.Tag (* + 2 + 1 = max HasDeclSecurity.Tag + 1 *) + let MemberRefParent (t: MemberRefParentTag) = assert (t.Tag <= 4); MemberRefParentMin + t.Tag (* + 2 + 1 = max HasDeclSecurity.Tag + 1 *) let [] MemberRefParentMax = 159 let [] HasSemanticsMin = 160 - let HasSemantics (t: HasSemanticsTag) = assert (t.Tag <= 1); HasSemanticsMin + t.Tag (* + 4 + 1 = max MemberRefParent.Tag + 1 *) + let HasSemantics (t: HasSemanticsTag) = assert (t.Tag <= 1); HasSemanticsMin + t.Tag (* + 4 + 1 = max MemberRefParent.Tag + 1 *) let [] HasSemanticsMax = 161 let [] MethodDefOrRefMin = 162 - let MethodDefOrRef (t: MethodDefOrRefTag) = assert (t.Tag <= 2); MethodDefOrRefMin + t.Tag (* + 1 + 1 = max HasSemantics.Tag + 1 *) + let MethodDefOrRef (t: MethodDefOrRefTag) = assert (t.Tag <= 2); MethodDefOrRefMin + t.Tag (* + 1 + 1 = max HasSemantics.Tag + 1 *) let [] MethodDefOrRefMax = 164 let [] MemberForwardedMin = 165 - let MemberForwarded (t: MemberForwardedTag) = assert (t.Tag <= 1); MemberForwardedMin + t.Tag (* + 2 + 1 = max MethodDefOrRef.Tag + 1 *) + let MemberForwarded (t: MemberForwardedTag) = assert (t.Tag <= 1); MemberForwardedMin + t.Tag (* + 2 + 1 = max MethodDefOrRef.Tag + 1 *) let [] MemberForwardedMax = 166 let [] ImplementationMin = 167 - let Implementation (t: ImplementationTag) = assert (t.Tag <= 2); ImplementationMin + t.Tag (* + 1 + 1 = max MemberForwarded.Tag + 1 *) + let Implementation (t: ImplementationTag) = assert (t.Tag <= 2); ImplementationMin + t.Tag (* + 1 + 1 = max MemberForwarded.Tag + 1 *) let [] ImplementationMax = 169 let [] CustomAttributeTypeMin = 170 - let CustomAttributeType (t: CustomAttributeTypeTag) = assert (t.Tag <= 3); CustomAttributeTypeMin + t.Tag (* + 2 + 1 = max Implementation.Tag + 1 *) + let CustomAttributeType (t: CustomAttributeTypeTag) = assert (t.Tag <= 3); CustomAttributeTypeMin + t.Tag (* + 2 + 1 = max Implementation.Tag + 1 *) let [] CustomAttributeTypeMax = 173 let [] ResolutionScopeMin = 174 - let ResolutionScope (t: ResolutionScopeTag) = assert (t.Tag <= 4); ResolutionScopeMin + t.Tag (* + 3 + 1 = max CustomAttributeType.Tag + 1 *) + let ResolutionScope (t: ResolutionScopeTag) = assert (t.Tag <= 4); ResolutionScopeMin + t.Tag (* + 3 + 1 = max CustomAttributeType.Tag + 1 *) let [] ResolutionScopeMax = 178 [] @@ -284,37 +284,37 @@ type RowElement(tag: int32, idx: int32) = member x.Val = idx // These create RowElements -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 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) /// 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 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 ResolutionScope (t, x: int) = RowElement(RowElementTags.ResolutionScope t, x) (* type RowElement = | UShort of uint16 | ULong of int32 - | Data of int * bool // Index into cenv.data or cenv.resources. Will be adjusted later in writing once we fix an overall location for the data section. flag indicates if offset is relative to cenv.resources. + | Data of int * bool // Index into cenv.data or cenv.resources. Will be adjusted later in writing once we fix an overall location for the data section. flag indicates if offset is relative to cenv.resources. | Guid of int // pos. in guid array | Blob of int // pos. in blob array | String of int // pos. in string array @@ -328,7 +328,7 @@ type RowElement = | MemberRefParent of MemberRefParentTag * int | HasSemantics of HasSemanticsTag * int | MethodDefOrRef of MethodDefOrRefTag * int - | MemberForwarded of MemberForwardedTag * int + | MemberForwarded of MemberForwardedTag * int | Implementation of ImplementationTag * int | CustomAttributeType of CustomAttributeTypeTag * int | ResolutionScope of ResolutionScopeTag * int @@ -349,7 +349,7 @@ let hashRow (elems: RowElement[]) = acc let equalRows (elems: RowElement[]) (elems2: RowElement[]) = - if elems.Length <> elems2.Length then false else + if elems.Length <> elems2.Length then false else let mutable ok = true let n = elems.Length let mutable i = 0 @@ -383,7 +383,7 @@ let AssemblyRefRow(s1, s2, s3, s4, l1, b1, nameIdx, str2, b2) = /// Special representation the computes the hash more efficiently let MemberRefRow(mrp: RowElement, nmIdx: StringIndex, blobIdx: BlobIndex) = - let hashCode = combineHash (hash blobIdx) (combineHash (hash nmIdx) (hash mrp)) + let hashCode = combineHash (hash blobIdx) (combineHash (hash nmIdx) (hash mrp)) let genericRow = [| mrp; StringE nmIdx; Blob blobIdx |] new SharedRow(genericRow, hashCode) @@ -409,10 +409,10 @@ 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 envForNonGenericMethodRef _mref = { EnclosingTyparCount=System.Int32.MaxValue } -let envForFieldSpec (fspec: ILFieldSpec) = { EnclosingTyparCount=fspec.DeclaringType.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 } //--------------------------------------------------------------------- @@ -426,7 +426,7 @@ type MetadataTable<'T> = #if DEBUG mutable lookups: int #endif - mutable rows: ResizeArray<'T> } + mutable rows: ResizeArray<'T> } member x.Count = x.rows.Count static member New(nm, hashEq) = @@ -561,7 +561,7 @@ type cenv = showTimes: bool desiredMetadataVersion: ILVersionInfo requiredDataFixups: (int32 * (int * bool)) list ref - /// References to strings in codestreams: offset of code and a (fixup-location , string token) list) + /// References to strings in codestreams: offset of code and a (fixup-location, string token) list) mutable requiredStringFixups: (int32 * (int * int) list) list codeChunks: ByteBuffer mutable nextCodeAddr: int32 @@ -584,8 +584,8 @@ type cenv = tables: MetadataTable[] AssemblyRefs: MetadataTable fieldDefs: MetadataTable - methodDefIdxsByKey: MetadataTable - methodDefIdxs: Dictionary + methodDefIdxsByKey: MetadataTable + methodDefIdxs: Dictionary propertyDefs: MetadataTable eventDefs: MetadataTable typeDefs: MetadataTable @@ -620,7 +620,7 @@ let metadataSchemaVersionSupportedByCLRVersion v = // Later Whidbey versions are post 2.0.40607.0.. However we assume // internal builds such as 2.0.x86chk are Whidbey Beta 2 or later if compareILVersions v (parseILVersion ("2.0.40520.0")) >= 0 && - compareILVersions v (parseILVersion ("2.0.40608.0")) < 0 then 1, 1 + compareILVersions v (parseILVersion ("2.0.40608.0")) < 0 then 1, 1 elif compareILVersions v (parseILVersion ("2.0.0.0")) >= 0 then 2, 0 else 1, 0 @@ -628,7 +628,7 @@ let headerVersionSupportedByCLRVersion v = // The COM20HEADER version number // Whidbey version numbers are 2.5 // Earlier are 2.0 - // From an email from jeffschw: "Be built with a compiler that marks the COM20HEADER with Major >=2 and Minor >= 5. The V2.0 compilers produce images with 2.5, V1.x produces images with 2.0." + // From an email from jeffschw: "Be built with a compiler that marks the COM20HEADER with Major >=2 and Minor >= 5. The V2.0 compilers produce images with 2.5, V1.x produces images with 2.0." if compareILVersions v (parseILVersion ("2.0.0.0")) >= 0 then 2, 5 else 2, 0 @@ -650,7 +650,7 @@ type ILTokenMappings = EventTokenMap: ILTypeDef list * ILTypeDef -> ILEventDef -> int32 } let recordRequiredDataFixup requiredDataFixups (buf: ByteBuffer) pos lab = - requiredDataFixups := (pos, lab) :: !requiredDataFixups + requiredDataFixups := (pos, lab) :: !requiredDataFixups // Write a special value in that we check later when applying the fixup buf.EmitInt32 0xdeaddddd @@ -695,12 +695,12 @@ and GenTypeDefsPass1 enc cenv tds = List.iter (GenTypeDefPass1 enc cenv) tds // Pass 2 - allocate indexes for methods and fields and write rows for types //===================================================================== -let rec GetIdxForTypeDef cenv key = +let rec GetIdxForTypeDef cenv key = try cenv.typeDefs.GetTableEntry key with :? KeyNotFoundException -> let (TdKey (enc, n) ) = key - errorR(InternalError("One of your modules expects the type '"+String.concat "." (enc@[n])+"' to be defined within the module being emitted. You may be missing an input file", range0)) + errorR(InternalError("One of your modules expects the type '"+String.concat "." (enc@[n])+"' to be defined within the module being emitted. You may be missing an input file", range0)) 0 // -------------------------------------------------------------------- @@ -716,7 +716,7 @@ let rec GetAssemblyRefAsRow cenv (aref: ILAssemblyRef) = ((match aref.PublicKey with Some (PublicKey _) -> 0x0001 | _ -> 0x0000) ||| (if aref.Retargetable then 0x0100 else 0x0000)), BlobIndex (match aref.PublicKey with - | None -> 0 + | None -> 0 | Some (PublicKey b | PublicKeyToken b) -> GetBytesAsBlobIdx cenv b), StringIndex (GetStringHeapIdx cenv aref.Name), StringIndex (match aref.Locale with None -> 0 | Some s -> GetStringHeapIdx cenv s), @@ -731,9 +731,9 @@ and GetModuleRefAsRow cenv (mref: ILModuleRef) = and GetModuleRefAsFileRow cenv (mref: ILModuleRef) = SharedRow - [| ULong (if mref.HasMetadata then 0x0000 else 0x0001) - StringE (GetStringHeapIdx cenv mref.Name) - (match mref.Hash with None -> Blob 0 | Some s -> Blob (GetBytesAsBlobIdx cenv s)) |] + [| ULong (if mref.HasMetadata then 0x0000 else 0x0001) + StringE (GetStringHeapIdx cenv mref.Name) + (match mref.Hash with None -> Blob 0 | Some s -> Blob (GetBytesAsBlobIdx cenv s)) |] and GetModuleRefAsIdx cenv mref = FindOrAddSharedRow cenv TableNames.ModuleRef (GetModuleRefAsRow cenv mref) @@ -755,7 +755,7 @@ let isTypeLocal (ty: ILType) = ty.IsNominal && isNil ty.GenericArgs && isTypeRef let GetScopeRefAsImplementationElem cenv scoref = match scoref with - | ILScopeRef.Local -> (i_AssemblyRef, 0) + | ILScopeRef.Local -> (i_AssemblyRef, 0) | ILScopeRef.Assembly aref -> (i_AssemblyRef, GetAssemblyRefAsIdx cenv aref) | ILScopeRef.Module mref -> (i_File, GetModuleRefAsFileIdx cenv mref) @@ -857,7 +857,7 @@ and GetTypeAsTypeDefOrRef cenv env (ty: ILType) = and GetTypeAsBytes cenv env ty = emitBytesViaBuffer (fun bb -> EmitType cenv env bb ty) and GetTypeOfLocalAsBytes cenv env (l: ILLocal) = - emitBytesViaBuffer (fun bb -> EmitLocalInfo cenv env bb l) + emitBytesViaBuffer (fun bb -> EmitLocalInfo cenv env bb l) and GetTypeAsBlobIdx cenv env (ty: ILType) = GetBytesAsBlobIdx cenv (GetTypeAsBytes cenv env ty) @@ -871,39 +871,39 @@ and GetTypeAsTypeSpecIdx cenv env ty = and EmitType cenv env bb ty = match ty with // REVIEW: what are these doing here? - | ILType.Value tspec when tspec.Name = "System.String" -> bb.EmitByte et_STRING - | ILType.Value tspec when tspec.Name = "System.Object" -> bb.EmitByte et_OBJECT - | ty when isILSByteTy ty -> bb.EmitByte et_I1 - | ty when isILInt16Ty ty -> bb.EmitByte et_I2 - | ty when isILInt32Ty ty -> bb.EmitByte et_I4 - | ty when isILInt64Ty ty -> bb.EmitByte et_I8 - | ty when isILByteTy ty -> bb.EmitByte et_U1 - | ty when isILUInt16Ty ty -> bb.EmitByte et_U2 - | ty when isILUInt32Ty ty -> bb.EmitByte et_U4 - | ty when isILUInt64Ty ty -> bb.EmitByte et_U8 - | ty when isILDoubleTy ty -> bb.EmitByte et_R8 - | ty when isILSingleTy ty -> bb.EmitByte et_R4 - | ty when isILBoolTy ty -> bb.EmitByte et_BOOLEAN - | ty when isILCharTy ty -> bb.EmitByte et_CHAR - | ty when isILStringTy ty -> bb.EmitByte et_STRING - | ty when isILObjectTy ty -> bb.EmitByte et_OBJECT - | ty when isILIntPtrTy ty -> bb.EmitByte et_I - | ty when isILUIntPtrTy ty -> bb.EmitByte et_U - | ty when isILTypedReferenceTy ty -> bb.EmitByte et_TYPEDBYREF - - | ILType.Boxed tspec -> EmitTypeSpec cenv env bb (et_CLASS, tspec) - | ILType.Value tspec -> EmitTypeSpec cenv env bb (et_VALUETYPE, tspec) + | ILType.Value tspec when tspec.Name = "System.String" -> bb.EmitByte et_STRING + | ILType.Value tspec when tspec.Name = "System.Object" -> bb.EmitByte et_OBJECT + | ty when isILSByteTy ty -> bb.EmitByte et_I1 + | ty when isILInt16Ty ty -> bb.EmitByte et_I2 + | ty when isILInt32Ty ty -> bb.EmitByte et_I4 + | ty when isILInt64Ty ty -> bb.EmitByte et_I8 + | ty when isILByteTy ty -> bb.EmitByte et_U1 + | ty when isILUInt16Ty ty -> bb.EmitByte et_U2 + | ty when isILUInt32Ty ty -> bb.EmitByte et_U4 + | ty when isILUInt64Ty ty -> bb.EmitByte et_U8 + | ty when isILDoubleTy ty -> bb.EmitByte et_R8 + | ty when isILSingleTy ty -> bb.EmitByte et_R4 + | ty when isILBoolTy ty -> bb.EmitByte et_BOOLEAN + | ty when isILCharTy ty -> bb.EmitByte et_CHAR + | ty when isILStringTy ty -> bb.EmitByte et_STRING + | ty when isILObjectTy ty -> bb.EmitByte et_OBJECT + | ty when isILIntPtrTy ty -> bb.EmitByte et_I + | ty when isILUIntPtrTy ty -> bb.EmitByte et_U + | ty when isILTypedReferenceTy ty -> bb.EmitByte et_TYPEDBYREF + + | ILType.Boxed tspec -> EmitTypeSpec cenv env bb (et_CLASS, tspec) + | ILType.Value tspec -> EmitTypeSpec cenv env bb (et_VALUETYPE, tspec) | ILType.Array (shape, ty) -> if shape = ILArrayShape.SingleDimensional then (bb.EmitByte et_SZARRAY ; EmitType cenv env bb ty) else (bb.EmitByte et_ARRAY; EmitType cenv env bb ty; EmitArrayShape bb shape) | ILType.TypeVar tv -> let cgparams = env.EnclosingTyparCount - if int32 tv < cgparams then + if int32 tv < cgparams then bb.EmitByte et_VAR bb.EmitZ32 (int32 tv) else bb.EmitByte et_MVAR - bb.EmitZ32 (int32 tv - cgparams) + bb.EmitZ32 (int32 tv - cgparams) | ILType.Byref ty -> bb.EmitByte et_BYREF @@ -964,9 +964,9 @@ let rec GetVariantTypeAsInt32 ty = (List.assoc ty (Lazy.force ILVariantTypeMap )) else match ty with - | ILNativeVariant.Array vt -> vt_ARRAY ||| GetVariantTypeAsInt32 vt - | ILNativeVariant.Vector vt -> vt_VECTOR ||| GetVariantTypeAsInt32 vt - | ILNativeVariant.Byref vt -> vt_BYREF ||| GetVariantTypeAsInt32 vt + | ILNativeVariant.Array vt -> vt_ARRAY ||| GetVariantTypeAsInt32 vt + | ILNativeVariant.Vector vt -> vt_VECTOR ||| GetVariantTypeAsInt32 vt + | ILNativeVariant.Byref vt -> vt_BYREF ||| GetVariantTypeAsInt32 vt | _ -> failwith "Unexpected variant type" // based on information in ECMA and asmparse.y in the CLR codebase @@ -1006,8 +1006,8 @@ and EmitNativeType bb ty = | None -> () | Some n -> let u1 = Bytes.stringAsUtf8NullTerminated n - bb.EmitZ32 (Array.length u1) ; bb.EmitBytes u1 - | ILNativeType.Array (nt, sizeinfo) -> (* REVIEW: check if this corresponds to the ECMA spec *) + bb.EmitZ32 (Array.length u1) ; bb.EmitBytes u1 + | ILNativeType.Array (nt, sizeinfo) -> (* REVIEW: check if this corresponds to the ECMA spec *) bb.EmitByte nt_ARRAY match nt with | None -> bb.EmitZ32 (int nt_MAX) @@ -1023,8 +1023,8 @@ and EmitNativeType bb ty = bb.EmitZ32 pnum (* ElemMul *) (* z_u32 0x1l *) match additive with - | None -> () - | Some n -> (* NumElem *) bb.EmitZ32 n + | None -> () + | Some n -> (* NumElem *) bb.EmitZ32 n | _ -> failwith "Unexpected native type" // -------------------------------------------------------------------- @@ -1038,9 +1038,9 @@ let rec GetFieldInitAsBlobIdx cenv (x: ILFieldInit) = and GetFieldInit (bb: ByteBuffer) x = match x with | ILFieldInit.String b -> bb.EmitBytes (System.Text.Encoding.Unicode.GetBytes b) - | ILFieldInit.Bool b -> bb.EmitByte (if b then 0x01uy else 0x00uy) + | ILFieldInit.Bool b -> bb.EmitByte (if b then 0x01uy else 0x00uy) | ILFieldInit.Char x -> bb.EmitUInt16 x - | ILFieldInit.Int8 x -> bb.EmitByte (byte x) + | ILFieldInit.Int8 x -> bb.EmitByte (byte x) | ILFieldInit.Int16 x -> bb.EmitUInt16 (uint16 x) | ILFieldInit.Int32 x -> bb.EmitInt32 x | ILFieldInit.Int64 x -> bb.EmitInt64 x @@ -1050,7 +1050,7 @@ and GetFieldInit (bb: ByteBuffer) x = | ILFieldInit.UInt64 x -> bb.EmitInt64 (int64 x) | ILFieldInit.Single x -> bb.EmitInt32 (bitsOfSingle x) | ILFieldInit.Double x -> bb.EmitInt64 (bitsOfDouble x) - | ILFieldInit.Null -> bb.EmitInt32 0 + | ILFieldInit.Null -> bb.EmitInt32 0 and GetFieldInitFlags i = UShort @@ -1078,20 +1078,20 @@ and GetFieldInitFlags i = let GetMemberAccessFlags access = match access with | ILMemberAccess.Public -> 0x00000006 - | ILMemberAccess.Private -> 0x00000001 - | ILMemberAccess.Family -> 0x00000004 + | ILMemberAccess.Private -> 0x00000001 + | ILMemberAccess.Family -> 0x00000004 | ILMemberAccess.CompilerControlled -> 0x00000000 | ILMemberAccess.FamilyAndAssembly -> 0x00000002 | ILMemberAccess.FamilyOrAssembly -> 0x00000005 | ILMemberAccess.Assembly -> 0x00000003 -let GetTypeAccessFlags access = +let GetTypeAccessFlags access = match access with | ILTypeDefAccess.Public -> 0x00000001 - | ILTypeDefAccess.Private -> 0x00000000 + | ILTypeDefAccess.Private -> 0x00000000 | ILTypeDefAccess.Nested ILMemberAccess.Public -> 0x00000002 - | ILTypeDefAccess.Nested ILMemberAccess.Private -> 0x00000003 - | ILTypeDefAccess.Nested ILMemberAccess.Family -> 0x00000004 + | ILTypeDefAccess.Nested ILMemberAccess.Private -> 0x00000003 + | ILTypeDefAccess.Nested ILMemberAccess.Family -> 0x00000004 | ILTypeDefAccess.Nested ILMemberAccess.CompilerControlled -> failwith "bad type acccess" | ILTypeDefAccess.Nested ILMemberAccess.FamilyAndAssembly -> 0x00000006 | ILTypeDefAccess.Nested ILMemberAccess.FamilyOrAssembly -> 0x00000007 @@ -1120,12 +1120,12 @@ and GetTypeOptionAsTypeDefOrRef cenv env tyOpt = and GetTypeDefAsPropertyMapRow cenv tidx = UnsharedRow - [| SimpleIndex (TableNames.TypeDef, tidx) + [| SimpleIndex (TableNames.TypeDef, tidx) SimpleIndex (TableNames.Property, cenv.propertyDefs.Count + 1) |] and GetTypeDefAsEventMapRow cenv tidx = UnsharedRow - [| SimpleIndex (TableNames.TypeDef, tidx) + [| SimpleIndex (TableNames.TypeDef, tidx) SimpleIndex (TableNames.Event, cenv.eventDefs.Count + 1) |] and GetKeyForFieldDef tidx (fd: ILFieldDef) = @@ -1143,16 +1143,16 @@ and GenMethodDefPass2 cenv tidx md = "method" (fun (key: MethodDefKey) -> dprintn "Duplicate in method table is:" - dprintn (" Type index: "+string key.TypeIdx) - dprintn (" Method name: "+key.Name) - dprintn (" Method arity (num generic params): "+string key.GenericArity) + dprintn (" Type index: "+string key.TypeIdx) + dprintn (" Method name: "+key.Name) + dprintn (" Method arity (num generic params): "+string key.GenericArity) key.Name ) (GetKeyForMethodDef tidx md) cenv.methodDefIdxs.[md] <- idx -and GetKeyForPropertyDef tidx (x: ILPropertyDef) = +and GetKeyForPropertyDef tidx (x: ILPropertyDef) = PropKey (tidx, x.Name, x.PropertyType, x.Args) and GenPropertyDefPass2 cenv tidx x = @@ -1220,14 +1220,14 @@ let FindMethodDefIdx cenv mdkey = let typeNameOfIdx i = match (cenv.typeDefs.dict - |> Seq.fold (fun sofar kvp -> + |> Seq.fold (fun sofar kvp -> let tkey2 = kvp.Key let tidx2 = kvp.Value if i = tidx2 then if sofar = None then Some tkey2 else failwith "multiple type names map to index" - else sofar) None) with + else sofar) None) with | Some x -> x | None -> raise MethodDefNotFound let (TdKey (tenc, tname)) = typeNameOfIdx mdkey.TypeIdx @@ -1270,7 +1270,7 @@ let GetMethodRefAsMethodDefIdx cenv (mref: ILMethodRef) = let mdkey = MethodDefKey (tidx, mref.GenericArity, mref.Name, mref.ReturnType, mref.ArgTypes, mref.CallingConv.IsStatic) FindMethodDefIdx cenv mdkey with e -> - failwithf "Error in GetMethodRefAsMethodDefIdx for mref = %A, error: %s" (mref.Name, tref.Name) e.Message + failwithf "Error in GetMethodRefAsMethodDefIdx for mref = %A, error: %s" (mref.Name, tref.Name) e.Message let rec MethodRefInfoAsMemberRefRow cenv env fenv (nm, ty, callconv, args, ret, varargs, genarity) = MemberRefRow(GetTypeAsMemberRefParent cenv env ty, @@ -1280,9 +1280,9 @@ let rec MethodRefInfoAsMemberRefRow cenv env fenv (nm, ty, callconv, args, ret, and GetMethodRefInfoAsBlobIdx cenv env info = GetBytesAsBlobIdx cenv (GetCallsigAsBytes cenv env info) -let GetMethodRefInfoAsMemberRefIdx cenv env ((_, ty, _, _, _, _, _) as minfo) = +let GetMethodRefInfoAsMemberRefIdx cenv env ((_, ty, _, _, _, _, _) as minfo) = let fenv = envForMethodRef env ty - FindOrAddSharedRow cenv TableNames.MemberRef (MethodRefInfoAsMemberRefRow cenv env fenv minfo) + FindOrAddSharedRow cenv TableNames.MemberRef (MethodRefInfoAsMemberRefRow cenv env fenv minfo) let GetMethodRefInfoAsMethodRefOrDef isAlwaysMethodDef cenv env ((nm, ty: ILType, cc, args, ret, varargs, genarity) as minfo) = if Option.isNone varargs && (isAlwaysMethodDef || isTypeLocal ty) then @@ -1350,15 +1350,15 @@ and InfoOfMethodSpec (mspec: ILMethodSpec, varargs) = let rec GetOverridesSpecAsMemberRefIdx cenv env ospec = let fenv = envForOverrideSpec 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 + 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) = let ty = ospec.DeclaringType if isTypeLocal ty then if not ty.IsNominal then failwith "GetOverridesSpecAsMethodDefOrRef: unexpected local tref-ty" try (mdor_MethodDef, GetMethodRefAsMethodDefIdx cenv ospec.MethodRef) - with MethodDefNotFound -> (mdor_MemberRef, GetOverridesSpecAsMemberRefIdx cenv env ospec) + with MethodDefNotFound -> (mdor_MemberRef, GetOverridesSpecAsMemberRefIdx cenv env ospec) else (mdor_MemberRef, GetOverridesSpecAsMemberRefIdx cenv env ospec) @@ -1394,7 +1394,7 @@ and GetCustomAttrRow cenv hca (attr: ILAttribute) = for element in attr.Elements do match element with | ILAttribElem.Type (Some ty) when ty.IsNominal -> GetTypeRefAsTypeRefIdx cenv ty.TypeRef |> ignore - | ILAttribElem.TypeRef (Some tref) -> GetTypeRefAsTypeRefIdx cenv tref |> ignore + | ILAttribElem.TypeRef (Some tref) -> GetTypeRefAsTypeRefIdx cenv tref |> ignore | _ -> () UnsharedRow @@ -1426,7 +1426,7 @@ and GenSecurityDeclsPass3 cenv hds attrs = List.iter (GenSecurityDeclPass3 cenv hds) attrs // -------------------------------------------------------------------- -// ILFieldSpec --> FieldRef or ILFieldDef row +// ILFieldSpec --> FieldRef or ILFieldDef row // -------------------------------------------------------------------- let rec GetFieldSpecAsMemberRefRow cenv env fenv (fspec: ILFieldSpec) = @@ -1508,7 +1508,7 @@ type ExceptionClauseSpec = (int * int * int * int * ExceptionClauseKind) type CodeBuffer = // -------------------------------------------------------------------- - // Buffer to write results of emitting code into. Also record: + // Buffer to write results of emitting code into. Also record: // - branch sources (where fixups will occur) // - possible branch destinations // - locations of embedded handles into the string table @@ -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 @@ -1574,8 +1574,8 @@ type CodeBuffer = module Codebuf = // -------------------------------------------------------------------- - // Applying branch fixups. Use short versions of instructions - // wherever possible. Sadly we can only determine if we can use a short + // Applying branch fixups. Use short versions of instructions + // wherever possible. Sadly we can only determine if we can use a short // version after we've layed out the code for all other instructions. // This in turn means that using a short version may change // the various offsets into the code. @@ -1596,7 +1596,7 @@ module Codebuf = let newCode = ByteBuffer.Create origCode.Length // Copy over all the code, working out whether the branches will be short - // or long and adjusting the branch destinations. Record an adjust function to adjust all the other + // or long and adjusting the branch destinations. Record an adjust function to adjust all the other // gumpf that refers to fixed offsets in the code stream. let newCode, newReqdBrFixups, adjuster = let remainingReqdFixups = ref orderedOrigReqdBrFixups @@ -1630,7 +1630,7 @@ module Codebuf = origWhere := origEndOfNoBranchBlock newWhere := !newWhere + nobranch_len - // Now do the branch instruction. Decide whether the fixup will be short or long in the new code + // Now do the branch instruction. Decide whether the fixup will be short or long in the new code if doingLast then doneLast := true else @@ -1648,7 +1648,7 @@ module Codebuf = match i, tgs with | (_, Some i_short), [tg] when - // Use the original offsets to compute if the branch is small or large. This is + // Use the original offsets to compute if the branch is small or large. This is // a safe approximation because code only gets smaller. (let origDest = match origAvailBrFixups.TryGetValue tg with @@ -1687,7 +1687,7 @@ module Codebuf = if !origWhere <> origEndOfInstr then dprintn "mismatch between origWhere and origEndOfInstr" - let adjuster = + let adjuster = let arr = Array.ofList (List.rev !adjustments) fun addr -> let i = @@ -1706,7 +1706,7 @@ module Codebuf = let newAvailBrFixups = let tab = Dictionary<_, _>(10, HashIdentity.Structural) for (KeyValue(tglab, origBrDest)) in origAvailBrFixups do - tab.[tglab] <- adjuster origBrDest + 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 @@ -1773,7 +1773,7 @@ module Codebuf = let emitInstrCode (codebuf: CodeBuffer) i = if i > 0xFF then assert (i >>> 8 = 0xFE) - codebuf.EmitByte ((i >>> 8) &&& 0xFF) + codebuf.EmitByte ((i >>> 8) &&& 0xFF) codebuf.EmitByte (i &&& 0xFF) else codebuf.EmitByte i @@ -1835,49 +1835,49 @@ module Codebuf = match instr with | si when isNoArgInstr si -> emitInstrCode codebuf (encodingsOfNoArgInstr si) - | I_brcmp (cmp, tg1) -> + | I_brcmp (cmp, tg1) -> codebuf.RecordReqdBrFixup ((Lazy.force ILCmpInstrMap).[cmp], Some (Lazy.force ILCmpInstrRevMap).[cmp]) tg1 | I_br tg -> codebuf.RecordReqdBrFixup (i_br, Some i_br_s) tg - | I_seqpoint s -> codebuf.EmitSeqPoint cenv s + | I_seqpoint s -> codebuf.EmitSeqPoint cenv s | I_leave tg -> codebuf.RecordReqdBrFixup (i_leave, Some i_leave_s) tg - | I_call (tl, mspec, varargs) -> + | I_call (tl, mspec, varargs) -> emitTailness cenv codebuf tl emitMethodSpecInstr cenv codebuf env i_call (mspec, varargs) //emitAfterTailcall codebuf tl - | I_callvirt (tl, mspec, varargs) -> + | I_callvirt (tl, mspec, varargs) -> emitTailness cenv codebuf tl emitMethodSpecInstr cenv codebuf env i_callvirt (mspec, varargs) //emitAfterTailcall codebuf tl - | I_callconstraint (tl, ty, mspec, varargs) -> + | I_callconstraint (tl, ty, mspec, varargs) -> emitTailness cenv codebuf tl emitConstrained cenv codebuf env ty emitMethodSpecInstr cenv codebuf env i_callvirt (mspec, varargs) //emitAfterTailcall codebuf tl - | I_newobj (mspec, varargs) -> + | I_newobj (mspec, varargs) -> emitMethodSpecInstr cenv codebuf env i_newobj (mspec, varargs) - | I_ldftn mspec -> + | I_ldftn mspec -> emitMethodSpecInstr cenv codebuf env i_ldftn (mspec, None) - | I_ldvirtftn mspec -> + | I_ldvirtftn mspec -> emitMethodSpecInstr cenv codebuf env i_ldvirtftn (mspec, None) - | I_calli (tl, callsig, varargs) -> + | I_calli (tl, callsig, varargs) -> emitTailness cenv codebuf tl emitInstrCode codebuf i_calli codebuf.EmitUncodedToken (getUncodedToken TableNames.StandAloneSig (GetCallsigAsStandAloneSigIdx cenv env (callsig, varargs))) //emitAfterTailcall codebuf tl - | I_ldarg u16 -> emitShortUInt16Instr codebuf (i_ldarg_s, i_ldarg) u16 - | I_starg u16 -> emitShortUInt16Instr codebuf (i_starg_s, i_starg) u16 - | I_ldarga u16 -> emitShortUInt16Instr codebuf (i_ldarga_s, i_ldarga) u16 - | I_ldloc u16 -> emitShortUInt16Instr codebuf (i_ldloc_s, i_ldloc) u16 - | I_stloc u16 -> emitShortUInt16Instr codebuf (i_stloc_s, i_stloc) u16 - | I_ldloca u16 -> emitShortUInt16Instr codebuf (i_ldloca_s, i_ldloca) u16 + | I_ldarg u16 -> emitShortUInt16Instr codebuf (i_ldarg_s, i_ldarg) u16 + | I_starg u16 -> emitShortUInt16Instr codebuf (i_starg_s, i_starg) u16 + | I_ldarga u16 -> emitShortUInt16Instr codebuf (i_ldarga_s, i_ldarga) u16 + | I_ldloc u16 -> emitShortUInt16Instr codebuf (i_ldloc_s, i_ldloc) u16 + | I_stloc u16 -> emitShortUInt16Instr codebuf (i_stloc_s, i_stloc) u16 + | I_ldloca u16 -> emitShortUInt16Instr codebuf (i_ldloca_s, i_ldloca) u16 - | I_cpblk (al, vol) -> + | I_cpblk (al, vol) -> emitAlignment codebuf al emitVolatility codebuf vol emitInstrCode codebuf i_cpblk - | I_initblk (al, vol) -> + | I_initblk (al, vol) -> emitAlignment codebuf al emitVolatility codebuf vol emitInstrCode codebuf i_initblk @@ -1894,90 +1894,90 @@ module Codebuf = emitInstrCode codebuf i_ldc_r8 codebuf.EmitInt64 (bitsOfDouble x) - | I_ldind (al, vol, dt) -> + | I_ldind (al, vol, dt) -> emitAlignment codebuf al emitVolatility codebuf vol emitInstrCode codebuf (match dt with | DT_I -> i_ldind_i - | DT_I1 -> i_ldind_i1 - | DT_I2 -> i_ldind_i2 - | DT_I4 -> i_ldind_i4 - | DT_U1 -> i_ldind_u1 - | DT_U2 -> i_ldind_u2 - | DT_U4 -> i_ldind_u4 - | DT_I8 -> i_ldind_i8 - | DT_R4 -> i_ldind_r4 - | DT_R8 -> i_ldind_r8 - | DT_REF -> i_ldind_ref + | DT_I1 -> i_ldind_i1 + | DT_I2 -> i_ldind_i2 + | DT_I4 -> i_ldind_i4 + | DT_U1 -> i_ldind_u1 + | DT_U2 -> i_ldind_u2 + | DT_U4 -> i_ldind_u4 + | DT_I8 -> i_ldind_i8 + | DT_R4 -> i_ldind_r4 + | DT_R8 -> i_ldind_r8 + | DT_REF -> i_ldind_ref | _ -> failwith "ldind") - | I_stelem dt -> + | I_stelem dt -> emitInstrCode codebuf (match dt with | DT_I | DT_U -> i_stelem_i - | DT_U1 | DT_I1 -> i_stelem_i1 - | DT_I2 | DT_U2 -> i_stelem_i2 - | DT_I4 | DT_U4 -> i_stelem_i4 - | DT_I8 | DT_U8 -> i_stelem_i8 - | DT_R4 -> i_stelem_r4 - | DT_R8 -> i_stelem_r8 - | DT_REF -> i_stelem_ref + | DT_U1 | DT_I1 -> i_stelem_i1 + | DT_I2 | DT_U2 -> i_stelem_i2 + | DT_I4 | DT_U4 -> i_stelem_i4 + | DT_I8 | DT_U8 -> i_stelem_i8 + | DT_R4 -> i_stelem_r4 + | DT_R8 -> i_stelem_r8 + | DT_REF -> i_stelem_ref | _ -> failwith "stelem") - | I_ldelem dt -> + | I_ldelem dt -> emitInstrCode codebuf (match dt with | DT_I -> i_ldelem_i - | DT_I1 -> i_ldelem_i1 - | DT_I2 -> i_ldelem_i2 - | DT_I4 -> i_ldelem_i4 - | DT_I8 -> i_ldelem_i8 - | DT_U1 -> i_ldelem_u1 - | DT_U2 -> i_ldelem_u2 - | DT_U4 -> i_ldelem_u4 - | DT_R4 -> i_ldelem_r4 - | DT_R8 -> i_ldelem_r8 - | DT_REF -> i_ldelem_ref + | DT_I1 -> i_ldelem_i1 + | DT_I2 -> i_ldelem_i2 + | DT_I4 -> i_ldelem_i4 + | DT_I8 -> i_ldelem_i8 + | DT_U1 -> i_ldelem_u1 + | DT_U2 -> i_ldelem_u2 + | DT_U4 -> i_ldelem_u4 + | DT_R4 -> i_ldelem_r4 + | DT_R8 -> i_ldelem_r8 + | DT_REF -> i_ldelem_ref | _ -> failwith "ldelem") - | I_stind (al, vol, dt) -> + | I_stind (al, vol, dt) -> emitAlignment codebuf al emitVolatility codebuf vol emitInstrCode codebuf (match dt with | DT_U | DT_I -> i_stind_i - | DT_U1 | DT_I1 -> i_stind_i1 - | DT_U2 | DT_I2 -> i_stind_i2 - | DT_U4 | DT_I4 -> i_stind_i4 - | DT_U8 | DT_I8 -> i_stind_i8 - | DT_R4 -> i_stind_r4 - | DT_R8 -> i_stind_r8 - | DT_REF -> i_stind_ref + | DT_U1 | DT_I1 -> i_stind_i1 + | DT_U2 | DT_I2 -> i_stind_i2 + | DT_U4 | DT_I4 -> i_stind_i4 + | DT_U8 | DT_I8 -> i_stind_i8 + | DT_R4 -> i_stind_r4 + | DT_R8 -> i_stind_r8 + | DT_REF -> i_stind_ref | _ -> failwith "stelem") - | I_switch labs -> codebuf.RecordReqdBrFixups (i_switch, None) labs + | I_switch labs -> codebuf.RecordReqdBrFixups (i_switch, None) labs - | I_ldfld (al, vol, fspec) -> + | I_ldfld (al, vol, fspec) -> emitAlignment codebuf al emitVolatility codebuf vol emitFieldSpecInstr cenv codebuf env i_ldfld fspec - | I_ldflda fspec -> + | I_ldflda fspec -> emitFieldSpecInstr cenv codebuf env i_ldflda fspec - | I_ldsfld (vol, fspec) -> + | I_ldsfld (vol, fspec) -> emitVolatility codebuf vol emitFieldSpecInstr cenv codebuf env i_ldsfld fspec - | I_ldsflda fspec -> + | I_ldsflda fspec -> emitFieldSpecInstr cenv codebuf env i_ldsflda fspec - | I_stfld (al, vol, fspec) -> + | I_stfld (al, vol, fspec) -> emitAlignment codebuf al emitVolatility codebuf vol emitFieldSpecInstr cenv codebuf env i_stfld fspec - | I_stsfld (vol, fspec) -> + | I_stsfld (vol, fspec) -> emitVolatility codebuf vol emitFieldSpecInstr cenv codebuf env i_stsfld fspec - | I_ldtoken tok -> + | I_ldtoken tok -> emitInstrCode codebuf i_ldtoken codebuf.EmitUncodedToken (match tok with @@ -1996,14 +1996,14 @@ module Codebuf = | ILToken.ILField fspec -> match GetFieldSpecAsFieldDefOrRef cenv env fspec with | (true, idx) -> getUncodedToken TableNames.Field idx - | (false, idx) -> getUncodedToken TableNames.MemberRef idx) - | I_ldstr s -> + | (false, idx) -> getUncodedToken TableNames.MemberRef idx) + | I_ldstr s -> emitInstrCode codebuf i_ldstr codebuf.RecordReqdStringFixup (GetUserStringHeapIdx cenv s) - | I_box ty -> emitTypeInstr cenv codebuf env i_box ty - | I_unbox ty -> emitTypeInstr cenv codebuf env i_unbox ty - | I_unbox_any ty -> emitTypeInstr cenv codebuf env i_unbox_any ty + | I_box ty -> emitTypeInstr cenv codebuf env i_box ty + | I_unbox ty -> emitTypeInstr cenv codebuf env i_unbox ty + | I_unbox_any ty -> emitTypeInstr cenv codebuf env i_unbox_any ty | I_newarr (shape, ty) -> if (shape = ILArrayShape.SingleDimensional) then @@ -2016,7 +2016,7 @@ module Codebuf = if (shape = ILArrayShape.SingleDimensional) then emitTypeInstr cenv codebuf env i_stelem_any ty else - let args = List.init (shape.Rank+1) (fun i -> if i < shape.Rank then cenv.ilg.typ_Int32 else ty) + let args = List.init (shape.Rank+1) (fun i -> if i < shape.Rank then cenv.ilg.typ_Int32 else ty) emitMethodSpecInfoInstr cenv codebuf env i_call ("Set", mkILArrTy(ty, shape), ILCallingConv.Instance, args, ILType.Void, None, []) | I_ldelem_any (shape, ty) -> @@ -2026,7 +2026,7 @@ module Codebuf = let args = List.init shape.Rank (fun _ -> cenv.ilg.typ_Int32) emitMethodSpecInfoInstr cenv codebuf env i_call ("Get", mkILArrTy(ty, shape), ILCallingConv.Instance, args, ty, None, []) - | I_ldelema (ro, _isNativePtr, shape, ty) -> + | I_ldelema (ro, _isNativePtr, shape, ty) -> if (ro = ReadonlyAddress) then emitInstrCode codebuf i_readonly if (shape = ILArrayShape.SingleDimensional) then @@ -2035,26 +2035,26 @@ module Codebuf = let args = List.init shape.Rank (fun _ -> cenv.ilg.typ_Int32) emitMethodSpecInfoInstr cenv codebuf env i_call ("Address", mkILArrTy(ty, shape), ILCallingConv.Instance, args, ILType.Byref ty, None, []) - | I_castclass ty -> emitTypeInstr cenv codebuf env i_castclass ty - | I_isinst ty -> emitTypeInstr cenv codebuf env i_isinst ty - | I_refanyval ty -> emitTypeInstr cenv codebuf env i_refanyval ty - | I_mkrefany ty -> emitTypeInstr cenv codebuf env i_mkrefany ty - | I_initobj ty -> emitTypeInstr cenv codebuf env i_initobj ty - | I_ldobj (al, vol, ty) -> + | I_castclass ty -> emitTypeInstr cenv codebuf env i_castclass ty + | I_isinst ty -> emitTypeInstr cenv codebuf env i_isinst ty + | I_refanyval ty -> emitTypeInstr cenv codebuf env i_refanyval ty + | I_mkrefany ty -> emitTypeInstr cenv codebuf env i_mkrefany ty + | I_initobj ty -> emitTypeInstr cenv codebuf env i_initobj ty + | I_ldobj (al, vol, ty) -> emitAlignment codebuf al emitVolatility codebuf vol emitTypeInstr cenv codebuf env i_ldobj ty - | I_stobj (al, vol, ty) -> + | I_stobj (al, vol, ty) -> emitAlignment codebuf al emitVolatility codebuf vol emitTypeInstr cenv codebuf env i_stobj ty - | I_cpobj ty -> emitTypeInstr cenv codebuf env i_cpobj ty - | I_sizeof ty -> emitTypeInstr cenv codebuf env i_sizeof ty - | EI_ldlen_multi (_, m) -> + | I_cpobj ty -> emitTypeInstr cenv codebuf env i_cpobj ty + | I_sizeof ty -> emitTypeInstr cenv codebuf env i_sizeof ty + | EI_ldlen_multi (_, m) -> emitShortInt32Instr codebuf (i_ldc_i4_s, i_ldc_i4) m emitInstr cenv codebuf env (mkNormalCall(mkILNonGenericMethSpecInTy(cenv.ilg.typ_Array, ILCallingConv.Instance, "GetLength", [(cenv.ilg.typ_Int32)], (cenv.ilg.typ_Int32)))) - | _ -> failwith "an IL instruction cannot be emitted" + | _ -> failwith "an IL instruction cannot be emitted" let mkScopeNode cenv (localSigs: _[]) (startOffset, endOffset, ls: ILLocalDebugMapping list, childScopes) = @@ -2073,7 +2073,7 @@ 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) = + 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 @@ -2198,7 +2198,7 @@ module Codebuf = let EmitTopCode cenv localSigs env nm code = let codebuf = CodeBuffer.Create nm - let origScopes = emitCode cenv localSigs codebuf env code + let origScopes = emitCode cenv localSigs codebuf env code let origCode = codebuf.code.Close() let origExnClauses = List.rev codebuf.seh let origReqdStringFixups = codebuf.reqdStringFixupsInMethod @@ -2243,7 +2243,7 @@ let GenILMethodBody mname cenv env (il: ILMethodBody) = if isNil il.Locals && il.MaxStack <= 8 && isNil seh && codeSize < 64 then // Use Tiny format let alignedCodeSize = align 4 (codeSize + 1) - let codePadding = (alignedCodeSize - (codeSize + 1)) + let codePadding = (alignedCodeSize - (codeSize + 1)) let requiredStringFixups' = (1, requiredStringFixups) methbuf.EmitByte (byte codeSize <<< 2 ||| e_CorILMethod_TinyFormat) methbuf.EmitBytes code @@ -2262,7 +2262,7 @@ let GenILMethodBody mname cenv env (il: ILMethodBody) = (FindOrAddSharedRow cenv TableNames.StandAloneSig (GetLocalSigAsStandAloneSigIdx cenv env il.Locals)) let alignedCodeSize = align 0x4 codeSize - let codePadding = (alignedCodeSize - codeSize) + let codePadding = (alignedCodeSize - codeSize) methbuf.EmitByte flags methbuf.EmitByte 0x30uy // last four bits record size of fat header in 4 byte chunks - this is always 12 bytes = 3 four word chunks @@ -2378,7 +2378,7 @@ and GenFieldDefPass3 cenv env fd = let rec GetGenericParamAsGenericParamRow cenv _env idx owner gp = let flags = - (match gp.Variance with + (match gp.Variance with | NonVariant -> 0x0000 | CoVariant -> 0x0001 | ContraVariant -> 0x0002) ||| @@ -2426,7 +2426,7 @@ and GenGenericParamPass4 cenv env idx owner gp = // param and return --> Param Row // -------------------------------------------------------------------- -let rec GetParamAsParamRow cenv _env seq (param: ILParameter) = +let rec GetParamAsParamRow cenv _env seq (param: ILParameter) = let flags = (if param.IsIn then 0x0001 else 0x0000) ||| (if param.IsOut then 0x0002 else 0x0000) ||| @@ -2519,7 +2519,7 @@ let GenMethodDefAsRow cenv env midx (md: ILMethodDef) = RootScope = Some rootScope Range= match ilmbody.SourceMarker with - | Some m when cenv.generatePdb -> + | Some m when cenv.generatePdb -> // table indexes are 1-based, document array indexes are 0-based let doc = (cenv.documents.FindOrAddSharedEntry m.Document) - 1 @@ -2548,10 +2548,10 @@ let GenMethodDefAsRow cenv env midx (md: ILMethodDef) = 0x0000 | MethodBody.Native -> failwith "cannot write body of native method - Abstract IL cannot roundtrip mixed native/managed binaries" - | _ -> 0x0000) + | _ -> 0x0000) UnsharedRow - [| ULong codeAddr + [| ULong codeAddr UShort (uint16 implflags) UShort (uint16 flags) StringE (GetStringHeapIdx cenv md.Name) @@ -2580,27 +2580,27 @@ let GenMethodDefPass3 cenv env (md: ILMethodDef) = | MethodBody.PInvoke attr -> let flags = begin match attr.CallingConv with - | PInvokeCallingConvention.None -> 0x0000 - | PInvokeCallingConvention.Cdecl -> 0x0200 - | PInvokeCallingConvention.Stdcall -> 0x0300 + | PInvokeCallingConvention.None -> 0x0000 + | PInvokeCallingConvention.Cdecl -> 0x0200 + | PInvokeCallingConvention.Stdcall -> 0x0300 | PInvokeCallingConvention.Thiscall -> 0x0400 | PInvokeCallingConvention.Fastcall -> 0x0500 - | PInvokeCallingConvention.WinApi -> 0x0100 + | PInvokeCallingConvention.WinApi -> 0x0100 end ||| begin match attr.CharEncoding with - | PInvokeCharEncoding.None -> 0x0000 - | PInvokeCharEncoding.Ansi -> 0x0002 + | PInvokeCharEncoding.None -> 0x0000 + | PInvokeCharEncoding.Ansi -> 0x0002 | PInvokeCharEncoding.Unicode -> 0x0004 - | PInvokeCharEncoding.Auto -> 0x0006 + | PInvokeCharEncoding.Auto -> 0x0006 end ||| begin match attr.CharBestFit with | PInvokeCharBestFit.UseAssembly -> 0x0000 - | PInvokeCharBestFit.Enabled -> 0x0010 + | PInvokeCharBestFit.Enabled -> 0x0010 | PInvokeCharBestFit.Disabled -> 0x0020 end ||| begin match attr.ThrowOnUnmappableChar with | PInvokeThrowOnUnmappableChar.UseAssembly -> 0x0000 - | PInvokeThrowOnUnmappableChar.Enabled -> 0x1000 + | PInvokeThrowOnUnmappableChar.Enabled -> 0x1000 | PInvokeThrowOnUnmappableChar.Disabled -> 0x2000 end ||| (if attr.NoMangle then 0x0001 else 0x0000) ||| @@ -2613,7 +2613,7 @@ let GenMethodDefPass3 cenv env (md: ILMethodDef) = SimpleIndex (TableNames.ModuleRef, GetModuleRefAsIdx cenv attr.Where) |]) |> ignore | _ -> () -let GenMethodDefPass4 cenv env md = +let GenMethodDefPass4 cenv env md = let midx = GetMethodDefIdx cenv md List.iteri (fun n gp -> GenGenericParamPass4 cenv env n (tomd_MethodDef, midx) gp) md.GenericParams @@ -2631,7 +2631,7 @@ let rec GetPropertySigAsBlobIdx cenv env prop = and GetPropertySigAsBytes cenv env (prop: ILPropertyDef) = emitBytesViaBuffer (fun bb -> - let b = ((hasthisToByte prop.CallingConv) ||| e_IMAGE_CEE_CS_CALLCONV_PROPERTY) + let b = ((hasthisToByte prop.CallingConv) ||| e_IMAGE_CEE_CS_CALLCONV_PROPERTY) bb.EmitByte b bb.EmitZ32 prop.Args.Length EmitType cenv env bb prop.PropertyType @@ -2693,16 +2693,16 @@ and GenEventPass3 cenv env (md: ILEventDef) = let rec GetResourceAsManifestResourceRow cenv r = let data, impl = 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.. + // 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 - let alignedOffset = (align 0x8 offset) + let alignedOffset = (align 0x8 offset) let pad = alignedOffset - offset let resourceSize = bytes.Length cenv.resources.EmitPadding pad cenv.resources.EmitInt32 resourceSize cenv.resources.EmitBytes bytes - Data (alignedOffset, true), (i_File, 0) + Data (alignedOffset, true), (i_File, 0) match r.Location with | ILResourceLocation.LocalIn _ -> embedManagedResources (r.GetBytes()) @@ -2732,7 +2732,7 @@ let rec GenTypeDefPass3 enc cenv (td: ILTypeDef) = td.Events.AsList |> List.iter (GenEventPass3 cenv env) td.Fields.AsList |> List.iter (GenFieldDefPass3 cenv env) td.Methods |> Seq.iter (GenMethodDefPass3 cenv env) - td.MethodImpls.AsList |> List.iter (GenMethodImplPass3 cenv env td.GenericParams.Length tidx) + td.MethodImpls.AsList |> List.iter (GenMethodImplPass3 cenv env td.GenericParams.Length tidx) // ClassLayout entry if needed match td.Layout with | ILTypeDefLayout.Auto -> () @@ -2749,7 +2749,7 @@ let rec GenTypeDefPass3 enc cenv (td: ILTypeDef) = td.GenericParams |> List.iteri (fun n gp -> GenGenericParamPass3 cenv env n (tomd_TypeDef, tidx) gp) td.NestedTypes.AsList |> GenTypeDefsPass3 (enc@[td.Name]) cenv with e -> - failwith ("Error in pass3 for type "+td.Name+", error: "+e.Message) + failwith ("Error in pass3 for type "+td.Name+", error: "+e.Message) reraise() raise e @@ -2782,7 +2782,7 @@ let timestamp = absilWriteGetTimeStamp () // -------------------------------------------------------------------- let rec GenNestedExportedTypePass3 cenv cidx (ce: ILNestedExportedType) = - let flags = GetMemberAccessFlags ce.Access + let flags = GetMemberAccessFlags ce.Access let nidx = AddUnsharedRow cenv TableNames.ExportedType (UnsharedRow @@ -2828,16 +2828,16 @@ and GetManifsetAsAssemblyRow cenv m = UShort (match m.Version with None -> 0us | Some (_, _, _, w) -> w) ULong ( (match m.AssemblyLongevity with - | ILAssemblyLongevity.Unspecified -> 0x0000 - | ILAssemblyLongevity.Library -> 0x0002 + | ILAssemblyLongevity.Unspecified -> 0x0000 + | ILAssemblyLongevity.Library -> 0x0002 | ILAssemblyLongevity.PlatformAppDomain -> 0x0004 - | ILAssemblyLongevity.PlatformProcess -> 0x0006 - | ILAssemblyLongevity.PlatformSystem -> 0x0008) ||| + | ILAssemblyLongevity.PlatformProcess -> 0x0006 + | ILAssemblyLongevity.PlatformSystem -> 0x0008) ||| (if m.Retargetable then 0x100 else 0x0) ||| // Setting these causes peverify errors. Hence both ilread and ilwrite ignore them and refuse to set them. // Any debugging customattributes will automatically propagate // REVIEW: No longer appears to be the case - (if m.JitTracking then 0x8000 else 0x0) ||| + (if m.JitTracking then 0x8000 else 0x0) ||| (match m.PublicKey with None -> 0x0000 | Some _ -> 0x0001) ||| 0x0000) (match m.PublicKey with None -> Blob 0 | Some x -> Blob (GetBytesAsBlobIdx cenv x)) StringE (GetStringHeapIdx cenv m.Name) @@ -2863,7 +2863,7 @@ and newGuid (modul: ILModuleDef) = and deterministicGuid (modul: ILModuleDef) = let n = 16909060 - let m2 = Seq.sum (Seq.mapi (fun i x -> i + int x) modul.Name) // use a stable hash + 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) = @@ -2911,13 +2911,13 @@ let GenModule (cenv : cenv) (modul: ILModuleDef) = GenCustomAttrsPass3Or4 cenv (hca_Module, midx) modul.CustomAttrs // GenericParam is the only sorted table indexed by Columns in other tables (GenericParamConstraint\CustomAttributes). // Hence we need to sort it before we emit any entries in GenericParamConstraint\CustomAttributes that are attached to generic params. - // Note this mutates the rows in a table. 'SetRowsOfTable' clears + // Note this mutates the rows in a table. 'SetRowsOfTable' clears // the key --> index map since it is no longer valid cenv.GetTable(TableNames.GenericParam).SetRowsOfSharedTable (SortTableRows TableNames.GenericParam (cenv.GetTable(TableNames.GenericParam).GenericRowsOfTable)) GenTypeDefsPass4 [] cenv tds reportTime cenv.showTimes "Module Generation Pass 4" -let generateIL requiredDataFixups (desiredMetadataVersion, generatePdb, ilg : ILGlobals, emitTailcalls, deterministic, showTimes) (m : ILModuleDef) cilStartAddress normalizeAssemblyRefs = +let generateIL requiredDataFixups (desiredMetadataVersion, generatePdb, ilg : ILGlobals, emitTailcalls, deterministic, showTimes) (m : ILModuleDef) cilStartAddress normalizeAssemblyRefs = let isDll = m.IsDLL let cenv = @@ -2969,9 +2969,9 @@ let generateIL requiredDataFixups (desiredMetadataVersion, generatePdb, ilg : IL normalizeAssemblyRefs = normalizeAssemblyRefs } // Now the main compilation step - GenModule cenv m + GenModule cenv m - // .exe files have a .entrypoint instruction. Do not write it to the entrypoint when writing dll. + // .exe files have a .entrypoint instruction. Do not write it to the entrypoint when writing dll. let entryPointToken = match cenv.entrypoint with | Some (epHere, tok) -> @@ -2993,12 +2993,12 @@ let generateIL requiredDataFixups (desiredMetadataVersion, generatePdb, ilg : IL let enc = tds |> List.map (fun td -> td.Name) GetIdxForTypeDef cenv (TdKey(enc, td.Name)) - let strings = Array.map Bytes.stringAsUtf8NullTerminated cenv.strings.EntriesAsArray + let strings = Array.map Bytes.stringAsUtf8NullTerminated cenv.strings.EntriesAsArray let userStrings = cenv.userStrings.EntriesAsArray |> Array.map System.Text.Encoding.Unicode.GetBytes - let blobs = cenv.blobs.EntriesAsArray - let guids = cenv.guids.EntriesAsArray - let tables = cenv.tables - let code = cenv.GetCode() + let blobs = cenv.blobs.EntriesAsArray + let guids = cenv.guids.EntriesAsArray + let tables = cenv.tables + let code = cenv.GetCode() // turn idx tbls into token maps let mappings = { TypeDefTokenMap = (fun t -> @@ -3026,7 +3026,7 @@ let generateIL requiredDataFixups (desiredMetadataVersion, generatePdb, ilg : IL // TABLES+BLOBS --> PHYSICAL METADATA+BLOBS //===================================================================== let chunk sz next = ({addr=next; size=sz}, next + sz) -let nochunk next = ({addr= 0x0;size= 0x0; } , next) +let nochunk next = ({addr= 0x0;size= 0x0; }, next) let count f arr = Array.fold (fun x y -> x + f y) 0x0 arr @@ -3101,13 +3101,13 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca // Most addresses after this point are measured from the MD root // Switch to md-rooted addresses let next = metadataHeaderStartChunk.size - let _metadataHeaderVersionChunk, next = chunk paddedVersionLength next - let _metadataHeaderEndChunk, next = chunk 0x04 next - let _tablesStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#~".Length + 0x01))) next - let _stringsStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#Strings".Length + 0x01))) next + let _metadataHeaderVersionChunk, next = chunk paddedVersionLength next + let _metadataHeaderEndChunk, next = chunk 0x04 next + let _tablesStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#~".Length + 0x01))) next + let _stringsStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#Strings".Length + 0x01))) next let _userStringsStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#US".Length + 0x01))) next - let _guidsStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#GUID".Length + 0x01))) next - let _blobsStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#Blob".Length + 0x01))) next + let _guidsStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#GUID".Length + 0x01))) next + let _blobsStreamHeaderChunk, next = chunk (0x08 + (align 4 ("#Blob".Length + 0x01))) next let tablesStreamStart = next @@ -3131,8 +3131,8 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let (valid1, valid2), _ = (((0, 0), 0), tables) ||> Array.fold (fun ((valid1, valid2) as valid, n) rows -> let valid = - if rows.Count = 0 then valid else - ( (if n < 32 then valid1 ||| (1 <<< n ) else valid1), + if rows.Count = 0 then valid else + ( (if n < 32 then valid1 ||| (1 <<< n ) else valid1), (if n >= 32 then valid2 ||| (1 <<< (n-32)) else valid2) ) (valid, n+1)) @@ -3141,7 +3141,7 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let sorted1 = 0x3301fa00 let sorted2 = // If there are any generic parameters in the binary we're emitting then mark that - // table as sorted, otherwise don't. This maximizes the number of assemblies we emit + // table as sorted, otherwise don't. This maximizes the number of assemblies we emit // which have an ECMA-v.1. compliant set of sorted tables. (if tableSize (TableNames.GenericParam) > 0 then 0x00000400 else 0x00000000) ||| (if tableSize (TableNames.GenericParamConstraint) > 0 then 0x00001000 else 0x00000000) ||| @@ -3149,7 +3149,7 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca reportTime showTimes "Layout Header of Tables" - let guidAddress n = (if n = 0 then 0 else (n - 1) * 0x10 + 0x01) + let guidAddress n = (if n = 0 then 0 else (n - 1) * 0x10 + 0x01) let stringAddressTable = let tab = Array.create (strings.Length + 1) 0 @@ -3229,7 +3229,7 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let hcaBigness = codedBigness 5 TableNames.Method || codedBigness 5 TableNames.Field || - codedBigness 5 TableNames.TypeRef || + codedBigness 5 TableNames.TypeRef || codedBigness 5 TableNames.TypeDef || codedBigness 5 TableNames.Param || codedBigness 5 TableNames.InterfaceImpl || @@ -3245,7 +3245,7 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca codedBigness 5 TableNames.AssemblyRef || codedBigness 5 TableNames.File || codedBigness 5 TableNames.ExportedType || - codedBigness 5 TableNames.ManifestResource || + codedBigness 5 TableNames.ManifestResource || codedBigness 5 TableNames.GenericParam || codedBigness 5 TableNames.GenericParamConstraint || codedBigness 5 TableNames.MethodSpec @@ -3290,19 +3290,19 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let rsBigness = codedBigness 2 TableNames.Module || codedBigness 2 TableNames.ModuleRef || - codedBigness 2 TableNames.AssemblyRef || + codedBigness 2 TableNames.AssemblyRef || codedBigness 2 TableNames.TypeRef - let tablesBuf = ByteBuffer.Create 20000 + let tablesBuf = ByteBuffer.Create 20000 - // Now the coded tables themselves - first the schemata header + // Now the coded tables themselves - first the schemata header tablesBuf.EmitIntsAsBytes [| 0x00; 0x00; 0x00; 0x00 mdtableVersionMajor // major version of table schemata mdtableVersionMinor // minor version of table schemata ((if stringsBig then 0x01 else 0x00) ||| // bit vector for heap size - (if guidsBig then 0x02 else 0x00) ||| + (if guidsBig then 0x02 else 0x00) ||| (if blobsBig then 0x04 else 0x00)) 0x01 (* reserved, always 1 *) |] @@ -3327,29 +3327,29 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let t = x.Tag let n = x.Val match t with - | _ when t = RowElementTags.UShort -> tablesBuf.EmitUInt16 (uint16 n) - | _ when t = RowElementTags.ULong -> tablesBuf.EmitInt32 n - | _ when t = RowElementTags.Data -> recordRequiredDataFixup requiredDataFixups tablesBuf (tablesStreamStart + tablesBuf.Position) (n, false) + | _ when t = RowElementTags.UShort -> tablesBuf.EmitUInt16 (uint16 n) + | _ when t = RowElementTags.ULong -> tablesBuf.EmitInt32 n + | _ when t = RowElementTags.Data -> recordRequiredDataFixup requiredDataFixups tablesBuf (tablesStreamStart + tablesBuf.Position) (n, false) | _ when t = RowElementTags.DataResources -> recordRequiredDataFixup requiredDataFixups tablesBuf (tablesStreamStart + tablesBuf.Position) (n, true) - | _ when t = RowElementTags.Guid -> tablesBuf.EmitZUntaggedIndex -3 guidsStreamPaddedSize guidsBig (guidAddress n) - | _ when t = RowElementTags.Blob -> tablesBuf.EmitZUntaggedIndex -2 blobsStreamPaddedSize blobsBig (blobAddress n) - | _ when t = RowElementTags.String -> tablesBuf.EmitZUntaggedIndex -1 stringsStreamPaddedSize stringsBig (stringAddress n) - | _ when t <= RowElementTags.SimpleIndexMax -> + | _ when t = RowElementTags.Guid -> tablesBuf.EmitZUntaggedIndex -3 guidsStreamPaddedSize guidsBig (guidAddress n) + | _ when t = RowElementTags.Blob -> tablesBuf.EmitZUntaggedIndex -2 blobsStreamPaddedSize blobsBig (blobAddress n) + | _ when t = RowElementTags.String -> tablesBuf.EmitZUntaggedIndex -1 stringsStreamPaddedSize stringsBig (stringAddress n) + | _ when t <= RowElementTags.SimpleIndexMax -> let tnum = t - RowElementTags.SimpleIndexMin tablesBuf.EmitZUntaggedIndex tnum (size tnum) (bigness tnum) n - | _ when t <= RowElementTags.TypeDefOrRefOrSpecMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.TypeDefOrRefOrSpecMin) 2 tdorBigness n - | _ when t <= RowElementTags.TypeOrMethodDefMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.TypeOrMethodDefMin) 1 tomdBigness n - | _ when t <= RowElementTags.HasConstantMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasConstantMin) 2 hcBigness n - | _ when t <= RowElementTags.HasCustomAttributeMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasCustomAttributeMin) 5 hcaBigness n - | _ when t <= RowElementTags.HasFieldMarshalMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasFieldMarshalMin) 1 hfmBigness n - | _ when t <= RowElementTags.HasDeclSecurityMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasDeclSecurityMin) 2 hdsBigness n - | _ when t <= RowElementTags.MemberRefParentMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.MemberRefParentMin) 3 mrpBigness n - | _ when t <= RowElementTags.HasSemanticsMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasSemanticsMin) 1 hsBigness n - | _ when t <= RowElementTags.MethodDefOrRefMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.MethodDefOrRefMin) 1 mdorBigness n - | _ when t <= RowElementTags.MemberForwardedMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.MemberForwardedMin) 1 mfBigness n - | _ when t <= RowElementTags.ImplementationMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.ImplementationMin) 2 iBigness n - | _ when t <= RowElementTags.CustomAttributeTypeMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.CustomAttributeTypeMin) 3 catBigness n - | _ when t <= RowElementTags.ResolutionScopeMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.ResolutionScopeMin) 2 rsBigness n + | _ when t <= RowElementTags.TypeDefOrRefOrSpecMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.TypeDefOrRefOrSpecMin) 2 tdorBigness n + | _ when t <= RowElementTags.TypeOrMethodDefMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.TypeOrMethodDefMin) 1 tomdBigness n + | _ when t <= RowElementTags.HasConstantMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasConstantMin) 2 hcBigness n + | _ when t <= RowElementTags.HasCustomAttributeMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasCustomAttributeMin) 5 hcaBigness n + | _ when t <= RowElementTags.HasFieldMarshalMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasFieldMarshalMin) 1 hfmBigness n + | _ when t <= RowElementTags.HasDeclSecurityMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasDeclSecurityMin) 2 hdsBigness n + | _ when t <= RowElementTags.MemberRefParentMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.MemberRefParentMin) 3 mrpBigness n + | _ when t <= RowElementTags.HasSemanticsMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.HasSemanticsMin) 1 hsBigness n + | _ when t <= RowElementTags.MethodDefOrRefMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.MethodDefOrRefMin) 1 mdorBigness n + | _ when t <= RowElementTags.MemberForwardedMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.MemberForwardedMin) 1 mfBigness n + | _ when t <= RowElementTags.ImplementationMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.ImplementationMin) 2 iBigness n + | _ when t <= RowElementTags.CustomAttributeTypeMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.CustomAttributeTypeMin) 3 catBigness n + | _ when t <= RowElementTags.ResolutionScopeMax -> tablesBuf.EmitZTaggedIndex (t - RowElementTags.ResolutionScopeMin) 2 rsBigness n | _ -> failwith "invalid tag in row element" tablesBuf.Close() @@ -3374,7 +3374,7 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca reportTime showTimes "Layout Metadata" let metadata, guidStart = - let mdbuf = ByteBuffer.Create 500000 + let mdbuf = ByteBuffer.Create 500000 mdbuf.EmitIntsAsBytes [| 0x42; 0x53; 0x4a; 0x42 // Magic signature 0x01; 0x00 // Major version @@ -3395,7 +3395,7 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca mdbuf.EmitIntsAsBytes [| 0x23; 0x7e; 0x00; 0x00; (* #~00 *)|] mdbuf.EmitInt32 stringsChunk.addr mdbuf.EmitInt32 stringsChunk.size - mdbuf.EmitIntsAsBytes [| 0x23; 0x53; 0x74; 0x72; 0x69; 0x6e; 0x67; 0x73; 0x00; 0x00; 0x00; 0x00 (* "#Strings0000" *)|] + mdbuf.EmitIntsAsBytes [| 0x23; 0x53; 0x74; 0x72; 0x69; 0x6e; 0x67; 0x73; 0x00; 0x00; 0x00; 0x00 (* "#Strings0000" *)|] mdbuf.EmitInt32 userStringsChunk.addr mdbuf.EmitInt32 userStringsChunk.size mdbuf.EmitIntsAsBytes [| 0x23; 0x55; 0x53; 0x00; (* #US0*) |] @@ -3421,7 +3421,7 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca mdbuf.EmitIntAsByte 0x00 reportTime showTimes "Write Metadata Strings" // The user string stream - mdbuf.EmitByte 0x00uy + mdbuf.EmitByte 0x00uy for s in userStrings do mdbuf.EmitZ32 (s.Length + 1) mdbuf.EmitBytes s @@ -3450,9 +3450,9 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca // uses of strings in the code for (codeStartAddr, l) in requiredStringFixups do for (codeOffset, userStringIndex) in l do - if codeStartAddr < codep.addr || codeStartAddr >= codep.addr + codep.size then + if codeStartAddr < codep.addr || codeStartAddr >= codep.addr + codep.size then failwith "strings-in-code fixup: a group of fixups is located outside the code array" - let locInCode = ((codeStartAddr + codeOffset) - codep.addr) + let locInCode = ((codeStartAddr + codeOffset) - codep.addr) checkFixup32 code locInCode 0xdeadbeef let token = getUncodedToken TableNames.UserStrings (userStringAddress userStringIndex) if (Bytes.get code (locInCode-1) <> i_ldstr) then failwith "strings-in-code fixup: not at ldstr instruction!" @@ -3504,14 +3504,14 @@ let writeInt64 (os: BinaryWriter) x = os.Write (dw7 x) let writeInt32 (os: BinaryWriter) x = - os.Write (byte (b0 x)) - os.Write (byte (b1 x)) - os.Write (byte (b2 x)) - os.Write (byte (b3 x)) + os.Write (byte (b0 x)) + os.Write (byte (b1 x)) + os.Write (byte (b2 x)) + os.Write (byte (b3 x)) let writeInt32AsUInt16 (os: BinaryWriter) x = - os.Write (byte (b0 x)) - os.Write (byte (b1 x)) + os.Write (byte (b0 x)) + os.Write (byte (b1 x)) let writeDirectory os dict = writeInt32 os (if dict.size = 0x0 then 0x0 else dict.addr) @@ -3523,7 +3523,7 @@ let writeBinaryAndReportMappings (outfile, ilg: ILGlobals, pdbfile: string option, signer: ILStrongNameSigner option, portablePDB, embeddedPDB, embedAllSource, embedSourceList, sourceLink, emitTailcalls, deterministic, showTimes, dumpDebugInfo ) modul normalizeAssemblyRefs = - // Store the public key from the signer into the manifest. This means it will be written + // Store the public key from the signer into the manifest. This means it will be written // to the binary and also acts as an indicator to leave space for delay sign reportTime showTimes "Write Started" @@ -3614,7 +3614,7 @@ let writeBinaryAndReportMappings (outfile, let headerSectionPhysSize = nextPhys - headerSectionPhysLoc let next = align alignVirt (headerAddr + headerSize) - // TEXT SECTION: 8 bytes IAT table 72 bytes CLI header + // TEXT SECTION: 8 bytes IAT table 72 bytes CLI header let textSectionPhysLoc = nextPhys let textSectionAddr = next @@ -3674,7 +3674,7 @@ let writeBinaryAndReportMappings (outfile, let pdbOpt = match portablePDB with - | true -> + | true -> let (uncompressedLength, contentId, stream) as pdbStream = generatePortablePdb embedAllSource embedSourceList sourceLink showTimes pdbData deterministic @@ -3692,7 +3692,7 @@ let writeBinaryAndReportMappings (outfile, sizeof_IMAGE_DEBUG_DIRECTORY ) next // The debug data is given to us by the PDB writer and appears to - // typically be the type of the data plus the PDB file name. We fill + // typically be the type of the data plus the PDB file name. We fill // this in after we've written the binary. We approximate the size according // to what PDB writers seem to require and leave extra space just in case... let debugDataJustInCase = 40 @@ -3718,7 +3718,7 @@ let writeBinaryAndReportMappings (outfile, let next = align alignVirt (textSectionAddr + textSectionSize) // .RSRC SECTION (DATA) - let dataSectionPhysLoc = nextPhys + let dataSectionPhysLoc = nextPhys let dataSectionAddr = next let dataSectionVirtToPhys v = v - dataSectionAddr + dataSectionPhysLoc @@ -3761,8 +3761,8 @@ let writeBinaryAndReportMappings (outfile, let dataSectionPhysSize = nextPhys - dataSectionPhysLoc let next = align alignVirt (dataSectionAddr + dataSectionSize) - // .RELOC SECTION base reloc table: 0x0c size - let relocSectionPhysLoc = nextPhys + // .RELOC SECTION base reloc table: 0x0c size + let relocSectionPhysLoc = nextPhys let relocSectionAddr = next let baseRelocTableChunk, next = chunk 0x0c next @@ -3776,8 +3776,8 @@ let writeBinaryAndReportMappings (outfile, begin requiredDataFixups |> List.iter (fun (metadataOffset32, (dataOffset, kind)) -> - let metadataOffset = metadataOffset32 - if metadataOffset < 0 || metadataOffset >= metadata.Length - 4 then failwith "data RVA fixup: fixup located outside metadata" + let metadataOffset = metadataOffset32 + if metadataOffset < 0 || metadataOffset >= metadata.Length - 4 then failwith "data RVA fixup: fixup located outside metadata" checkFixup32 metadata metadataOffset 0xdeaddddd let dataRva = if kind then @@ -3795,7 +3795,7 @@ let writeBinaryAndReportMappings (outfile, end // IMAGE TOTAL SIZE - let imageEndSectionPhysLoc = nextPhys + let imageEndSectionPhysLoc = nextPhys let imageEndAddr = next reportTime showTimes "Layout image" @@ -3805,7 +3805,7 @@ let writeBinaryAndReportMappings (outfile, | None -> () | Some pExpected -> os.Flush() - let pCurrent = int32 os.BaseStream.Position + let pCurrent = int32 os.BaseStream.Position if pCurrent <> pExpected then failwith ("warning: "+chunkName+" not where expected, pCurrent = "+string pCurrent+", p.addr = "+string pExpected) writeBytes os chunk @@ -3844,7 +3844,7 @@ let writeBinaryAndReportMappings (outfile, let final = [| hCode; hData; hMeta |] |> Array.collect id |> sha.ComputeHash // Confirm we have found the correct data and aren't corrupting the metadata - if metadata.[ guidStart..guidStart+3] <> [| 4uy; 3uy; 2uy; 1uy |] then failwith "Failed to find MVID" + if metadata.[ guidStart..guidStart+3] <> [| 4uy; 3uy; 2uy; 1uy |] then failwith "Failed to find MVID" if metadata.[ guidStart+12..guidStart+15] <> [| 4uy; 3uy; 2uy; 1uy |] then failwith "Failed to find MVID" // Update MVID guid in metadata @@ -3853,7 +3853,7 @@ let writeBinaryAndReportMappings (outfile, // Use last 4 bytes for timestamp - High bit set, to stop tool chains becoming confused let timestamp = int final.[16] ||| (int final.[17] <<< 8) ||| (int final.[18] <<< 16) ||| (int (final.[19] ||| 128uy) <<< 24) writeInt32 os timestamp - // Update pdbData with new guid and timestamp. Portable and embedded PDBs don't need the ModuleID + // Update pdbData with new guid and timestamp. Portable and embedded PDBs don't need the ModuleID // Full and PdbOnly aren't supported under deterministic builds currently, they rely on non-determinsitic Windows native code { pdbData with ModuleID = final.[0..15] ; Timestamp = timestamp } else @@ -3886,7 +3886,7 @@ let writeBinaryAndReportMappings (outfile, // 000000a0 writeInt32 os dataSectionPhysSize // Size of the initialized data section writeInt32 os 0x00 // Size of the uninitialized data section - writeInt32 os entrypointCodeChunk.addr // RVA of entry point , needs to point to bytes 0xFF 0x25 followed by the RVA+!0x4000000 + writeInt32 os entrypointCodeChunk.addr // RVA of entry point, needs to point to bytes 0xFF 0x25 followed by the RVA+!0x4000000 writeInt32 os textSectionAddr // e.g. 0x0002000 // 000000b0 if modul.Is64Bit then @@ -3919,7 +3919,7 @@ let writeBinaryAndReportMappings (outfile, // x86 : IMAGE_DLLCHARACTERISTICS_ NO_SEH | IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE | IMAGE_DLLCHARACTERISTICS_NX_COMPAT // x64 : IMAGE_DLLCHARACTERISTICS_ NO_SEH | IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE | IMAGE_DLLCHARACTERISTICS_NX_COMPAT let dllCharacteristics = - let flags = + let flags = if modul.Is64Bit then (if isItanium then 0x8540 else 0x540) else 0x540 if modul.UseHighEntropyVA then flags ||| 0x20 // IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA @@ -3982,7 +3982,7 @@ let writeBinaryAndReportMappings (outfile, write (Some textSectionHeaderChunk.addr) os "text section header" [| |] // 00000178 - writeBytes os [| 0x2euy; 0x74uy; 0x65uy; 0x78uy; 0x74uy; 0x00uy; 0x00uy; 0x00uy; |] // ".text\000\000\000" + writeBytes os [| 0x2euy; 0x74uy; 0x65uy; 0x78uy; 0x74uy; 0x00uy; 0x00uy; 0x00uy; |] // ".text\000\000\000" // 00000180 writeInt32 os textSectionSize // VirtualSize: Total size of the section when loaded into memory in bytes rounded to Section Alignment. writeInt32 os textSectionAddr // VirtualAddress For executable images this is the address of the first byte of the section @@ -4012,7 +4012,7 @@ let writeBinaryAndReportMappings (outfile, // 000001c0 writeInt32AsUInt16 os 0x00 // NumberOfRelocations Number of relocations, set to 0 if unused. writeInt32AsUInt16 os 0x00 // NumberOfLinenumbers Always 0 (see Section 23.1). - writeBytes os [| 0x40uy; 0x00uy; 0x00uy; 0x40uy |] // Characteristics Flags: IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA + writeBytes os [| 0x40uy; 0x00uy; 0x00uy; 0x40uy |] // Characteristics Flags: IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA write (Some relocSectionHeaderChunk.addr) os "reloc section header" [| |] // 000001a0 @@ -4039,7 +4039,7 @@ let writeBinaryAndReportMappings (outfile, // e.g. 0x0200 write (Some (textV2P importAddrTableChunk.addr)) os "import addr table" [| |] writeInt32 os importNameHintTableChunk.addr - writeInt32 os 0x00 // QUERY 4 bytes of zeros not 2 like ECMA 24.3.1 says + writeInt32 os 0x00 // QUERY 4 bytes of zeros not 2 like ECMA 24.3.1 says // e.g. 0x0208 @@ -4052,7 +4052,7 @@ let writeBinaryAndReportMappings (outfile, let headerVersionMajor, headerVersionMinor = headerVersionSupportedByCLRVersion desiredMetadataVersion writePadding os "pad to cli header" cliHeaderPadding - write (Some (textV2P cliHeaderChunk.addr)) os "cli header" [| |] + write (Some (textV2P cliHeaderChunk.addr)) os "cli header" [| |] writeInt32 os 0x48 // size of header writeInt32AsUInt16 os headerVersionMajor // Major part of minimum version of CLR reqd. writeInt32AsUInt16 os headerVersionMinor // Minor part of minimum version of CLR reqd. ... @@ -4245,7 +4245,7 @@ let writeBinaryAndReportMappings (outfile, for i in idd do // write the debug raw data as given us by the PDB writer os2.BaseStream.Seek (int64 (textV2P i.iddChunk.addr), SeekOrigin.Begin) |> ignore - if i.iddChunk.size < i.iddData.Length then failwith "Debug data area is not big enough. Debug info may not be usable" + if i.iddChunk.size < i.iddData.Length then failwith "Debug data area is not big enough. Debug info may not be usable" writeBytes os2 i.iddData os2.Dispose() with e -> @@ -4260,7 +4260,7 @@ let writeBinaryAndReportMappings (outfile, ignore debugEmbeddedPdbChunk reportTime showTimes "Finalize PDB" - /// Sign the binary. No further changes to binary allowed past this point! + /// Sign the binary. No further changes to binary allowed past this point! match signer with | None -> () | Some s -> diff --git a/src/fsharp/AugmentWithHashCompare.fs b/src/fsharp/AugmentWithHashCompare.fs index 4aa0bed68c8..c859fb63889 100644 --- a/src/fsharp/AugmentWithHashCompare.fs +++ b/src/fsharp/AugmentWithHashCompare.fs @@ -712,38 +712,38 @@ let CheckAugmentationAttribs isImplementation g amap (tycon: Tycon) = // THESE ARE THE LEGITIMATE CASES // [< >] on anything - | _, _ , None , None, None , None, None , None , None + | _, _, None, None, None, None, None, None, None // [] on union/record/struct - | true, _, None, Some(true), None , None , None , Some(true), None + | true, _, None, Some(true), None, None, None, Some(true), None // [] on union/record/struct - | true, _, None, Some(true), None , None , Some(true), None , None -> + | true, _, None, Some(true), None, None, Some(true), None, None -> () // [] on union/record/struct - | true, _, None, None , Some(true), None , Some(true), None , None + | true, _, None, None, Some(true), None, Some(true), None, None // [] on union/record/struct - | true, _, None, None , Some(true), None , None , None , None -> + | true, _, None, None, Some(true), None, None, None, None -> if isTrueFSharpStructTycon g tycon then errorR(Error(FSComp.SR.augNoRefEqualsOnStruct(), m)) else () // [] on union/record/struct - | true, true, None, None , None , Some(true), None , None , Some(true) + | true, true, None, None, None, Some(true), None, None, Some(true) // [] - | true, _, None, None , None , Some(true), Some(true), None , None + | true, _, None, None, None, Some(true), Some(true), None, None // [] - | true, _, None, None , None , Some(true), None , Some(true), None + | true, _, None, None, None, Some(true), None, Some(true), None // [] on anything - | _ , _, None, None , None , None , Some(true), None , None + | _, _, None, None, None, None, Some(true), None, None // [] on anything - | _ , _, Some(true), None, None , None , Some(true), None , None -> + | _, _, Some(true), None, None, None, Some(true), None, None -> () @@ -754,18 +754,18 @@ let CheckAugmentationAttribs isImplementation g amap (tycon: Tycon) = errorR(Error(FSComp.SR.augNoEqualityNeedsNoComparison(), m)) // [] - | true, true, _, _, _ , None , _, _, Some(true) -> + | true, true, _, _, _, None, _, _, Some(true) -> errorR(Error(FSComp.SR.augStructCompNeedsStructEquality(), m)) // [] - | true, _, _, _, _ , Some(true), None, _, None -> + | true, _, _, _, _, Some(true), None, _, None -> errorR(Error(FSComp.SR.augStructEqNeedsNoCompOrStructComp(), m)) // [] - | true, _, _, Some(true), _ , _, None, None, _ -> + | true, _, _, Some(true), _, _, None, None, _ -> errorR(Error(FSComp.SR.augCustomEqNeedsNoCompOrCustomComp(), m)) // [] - | true, _, _, _, Some(true) , Some(true) , _, _, _ + | true, _, _, _, Some(true), Some(true), _, _, _ // [] | true, _, _, _, Some(true), _, _, _, Some(true) -> @@ -774,9 +774,9 @@ let CheckAugmentationAttribs isImplementation g amap (tycon: Tycon) = // non augmented type, [] // non augmented type, [] // non augmented type, [] - | false, _, _, _, Some(true), _ , _ , _, _ - | false, _, _, _, _ , Some(true), _ , _, _ - | false, _, _, _, _ , _ , _ , _, Some(true) -> + | false, _, _, _, Some(true), _, _, _, _ + | false, _, _, _, _, Some(true), _, _, _ + | false, _, _, _, _, _, _, _, Some(true) -> errorR(Error(FSComp.SR.augOnlyCertainTypesCanHaveAttrs(), m)) // All other cases | _ -> @@ -829,7 +829,7 @@ let TyconIsCandidateForAugmentationWithCompare (g: TcGlobals) (tycon: Tycon) = not (TyconRefHasAttribute g tycon.Range g.attrib_IsByRefLikeAttribute (mkLocalTyconRef tycon)) && match getAugmentationAttribs g tycon with // [< >] - | true, true, None, None, None, None , None, None, None + | true, true, None, None, None, None, None, None, None // [] | true, true, None, None, None, Some(true), None, None, Some(true) // [] @@ -845,7 +845,7 @@ let TyconIsCandidateForAugmentationWithEquals (g: TcGlobals) (tycon: Tycon) = match getAugmentationAttribs g tycon with // [< >] - | true, _, None, None, None, None , _, _, _ + | true, _, None, None, None, None, _, _, _ // [] // [] | true, _, None, None, None, Some(true), _, _, _ -> true diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index df5ffa8d8b7..33216b30e5e 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.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. /// Coordinating compiler operations - configuration, loading initial context, reporting errors etc. module internal FSharp.Compiler.CompileOps @@ -241,8 +241,8 @@ let GetDiagnosticNumber(err: PhasedDiagnostic) = | ErrorFromAddingTypeEquation _ -> 1 | FunctionExpected _ -> 2 | NotAFunctionButIndexer _ -> 3217 - | NotAFunction _ -> 3 - | FieldNotMutable _ -> 5 + | NotAFunction _ -> 3 + | FieldNotMutable _ -> 5 | Recursion _ -> 6 | InvalidRuntimeCoercion _ -> 7 | IndeterminateRuntimeCoercion _ -> 8 @@ -250,19 +250,19 @@ let GetDiagnosticNumber(err: PhasedDiagnostic) = | SyntaxError _ -> 10 // 11 cannot be reused // 12 cannot be reused - | IndeterminateStaticCoercion _ -> 13 - | StaticCoercionShouldUseBox _ -> 14 + | IndeterminateStaticCoercion _ -> 13 + | StaticCoercionShouldUseBox _ -> 14 // 15 cannot be reused | RuntimeCoercionSourceSealed _ -> 16 | OverrideDoesntOverride _ -> 17 - | UnionPatternsBindDifferentNames _ -> 18 - | UnionCaseWrongArguments _ -> 19 - | UnitTypeExpected _ -> 20 - | UnitTypeExpectedWithEquality _ -> 20 - | UnitTypeExpectedWithPossiblePropertySetter _ -> 20 - | UnitTypeExpectedWithPossibleAssignment _ -> 20 - | RecursiveUseCheckedAtRuntime _ -> 21 - | LetRecEvaluatedOutOfOrder _ -> 22 + | UnionPatternsBindDifferentNames _ -> 18 + | UnionCaseWrongArguments _ -> 19 + | UnitTypeExpected _ -> 20 + | UnitTypeExpectedWithEquality _ -> 20 + | UnitTypeExpectedWithPossiblePropertySetter _ -> 20 + | UnitTypeExpectedWithPossibleAssignment _ -> 20 + | RecursiveUseCheckedAtRuntime _ -> 21 + | LetRecEvaluatedOutOfOrder _ -> 22 | NameClash _ -> 23 // 24 cannot be reused | PatternMatchCompilation.MatchIncomplete _ -> 25 @@ -271,14 +271,14 @@ let GetDiagnosticNumber(err: PhasedDiagnostic) = | ValNotLocal _ -> 28 | MissingFields _ -> 29 | ValueRestriction _ -> 30 - | LetRecUnsound _ -> 31 - | FieldsFromDifferentTypes _ -> 32 + | LetRecUnsound _ -> 31 + | FieldsFromDifferentTypes _ -> 32 | TyconBadArgs _ -> 33 | ValueNotContained _ -> 34 - | Deprecated _ -> 35 + | Deprecated _ -> 35 | ConstrNotContained _ -> 36 | Duplicate _ -> 37 - | VarBoundTwice _ -> 38 + | VarBoundTwice _ -> 38 | UndefinedName _ -> 39 | LetRecCheckedAtRuntime _ -> 40 | UnresolvedOverloading _ -> 41 @@ -374,9 +374,9 @@ let GetWarningLevel err = match err.Exception with // Level 5 warnings | RecursiveUseCheckedAtRuntime _ - | LetRecEvaluatedOutOfOrder _ + | LetRecEvaluatedOutOfOrder _ | DefensiveCopyWarning _ - | FullAbstraction _ -> 5 + | FullAbstraction _ -> 5 | NumberedError((n, _), _) | ErrorWithSuggestions((n, _), _, _, _) | Error((n, _), _) -> @@ -386,7 +386,7 @@ let GetWarningLevel err = // 1178, tcNoEqualityNeeded2, "The struct, record or union type '%s' does not support structural equality because the type '%s' does not satisfy the 'equality' constraint...." if (n = 1178) then 5 else 2 // Level 2 - | _ -> 2 + | _ -> 2 let warningOn err level specificWarnOn = let n = GetDiagnosticNumber err @@ -610,7 +610,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | ConstraintSolverInfiniteTypes(contextInfo, denv, t1, t2, m, m2) -> // REVIEW: consider if we need to show _cxs (the type parameter constraints) let t1, t2, _cxs = NicePrint.minimalStringsOfTwoTypes denv t1 t2 - os.Append(ConstraintSolverInfiniteTypesE().Format t1 t2) |> ignore + os.Append(ConstraintSolverInfiniteTypesE().Format t1 t2) |> ignore match contextInfo with | ContextInfo.ReturnInComputationExpression -> @@ -631,7 +631,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = // REVIEW: consider if we need to show _cxs (the type parameter constraints) let t1, t2, _cxs = NicePrint.minimalStringsOfTwoTypes denv t1 t2 - os.Append(ConstraintSolverTypesNotInEqualityRelation1E().Format t1 t2 ) |> ignore + os.Append(ConstraintSolverTypesNotInEqualityRelation1E().Format t1 t2 ) |> ignore if m.StartLine <> m2.StartLine then os.Append(SeeAlsoE().Format (stringOfRange m)) |> ignore @@ -673,9 +673,9 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | _ -> () fopt |> Option.iter (Printf.bprintf os " %s") - | ErrorFromAddingTypeEquation(g, denv, t1, t2, ConstraintSolverTypesNotInEqualityRelation(_, t1', t2', m , _ , contextInfo), _) + | ErrorFromAddingTypeEquation(g, denv, t1, t2, ConstraintSolverTypesNotInEqualityRelation(_, t1', t2', m, _, contextInfo), _) when typeEquiv g t1 t1' - && typeEquiv g t2 t2' -> + && typeEquiv g t2 t2' -> let t1, t2, tpcs = NicePrint.minimalStringsOfTwoTypes denv t1 t2 match contextInfo with | ContextInfo.IfExpression range when range = m -> os.Append(FSComp.SR.ifExpression(t1, t2)) |> ignore @@ -814,7 +814,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = else os.Append(NameClash2E().Format k1 nm1 nm k2 nm2) |> ignore - | Duplicate(k, s, _) -> + | Duplicate(k, s, _) -> if k = "member" then os.Append(Duplicate1E().Format (DecompileOpName s)) |> ignore else @@ -831,7 +831,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = let _, errs = f(smr, ccuName, s) os.Append(errs) |> ignore - | FieldNotMutable _ -> + | FieldNotMutable _ -> os.Append(FieldNotMutableE().Format) |> ignore | FieldsFromDifferentTypes (_, fref1, fref2, _) -> @@ -874,9 +874,9 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | Some tpnm -> match ty1 with | TType_measure _ -> - os.Append(NonRigidTypar2E().Format tpnm (NicePrint.stringOfTy denv ty)) |> ignore + os.Append(NonRigidTypar2E().Format tpnm (NicePrint.stringOfTy denv ty)) |> ignore | _ -> - os.Append(NonRigidTypar3E().Format tpnm (NicePrint.stringOfTy denv ty)) |> ignore + os.Append(NonRigidTypar3E().Format tpnm (NicePrint.stringOfTy denv ty)) |> ignore | SyntaxError (ctxt, _) -> let ctxt = unbox>(ctxt) @@ -915,57 +915,57 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | Parser.TOKEN_INFIX_STAR_STAR_OP -> getErrorString("Parser.TOKEN.INFIX.STAR.STAR.OP") | Parser.TOKEN_INFIX_COMPARE_OP -> getErrorString("Parser.TOKEN.INFIX.COMPARE.OP") | Parser.TOKEN_COLON_GREATER -> getErrorString("Parser.TOKEN.COLON.GREATER") - | Parser.TOKEN_COLON_COLON ->getErrorString("Parser.TOKEN.COLON.COLON") + | Parser.TOKEN_COLON_COLON ->getErrorString("Parser.TOKEN.COLON.COLON") | Parser.TOKEN_PERCENT_OP -> getErrorString("Parser.TOKEN.PERCENT.OP") | Parser.TOKEN_INFIX_AT_HAT_OP -> getErrorString("Parser.TOKEN.INFIX.AT.HAT.OP") | Parser.TOKEN_INFIX_BAR_OP -> getErrorString("Parser.TOKEN.INFIX.BAR.OP") | Parser.TOKEN_PLUS_MINUS_OP -> getErrorString("Parser.TOKEN.PLUS.MINUS.OP") | Parser.TOKEN_PREFIX_OP -> getErrorString("Parser.TOKEN.PREFIX.OP") - | Parser.TOKEN_COLON_QMARK_GREATER -> getErrorString("Parser.TOKEN.COLON.QMARK.GREATER") + | Parser.TOKEN_COLON_QMARK_GREATER -> getErrorString("Parser.TOKEN.COLON.QMARK.GREATER") | Parser.TOKEN_INFIX_STAR_DIV_MOD_OP -> getErrorString("Parser.TOKEN.INFIX.STAR.DIV.MOD.OP") | Parser.TOKEN_INFIX_AMP_OP -> getErrorString("Parser.TOKEN.INFIX.AMP.OP") - | Parser.TOKEN_AMP -> getErrorString("Parser.TOKEN.AMP") - | Parser.TOKEN_AMP_AMP -> getErrorString("Parser.TOKEN.AMP.AMP") - | Parser.TOKEN_BAR_BAR -> getErrorString("Parser.TOKEN.BAR.BAR") - | Parser.TOKEN_LESS -> getErrorString("Parser.TOKEN.LESS") - | Parser.TOKEN_GREATER -> getErrorString("Parser.TOKEN.GREATER") - | Parser.TOKEN_QMARK -> getErrorString("Parser.TOKEN.QMARK") + | Parser.TOKEN_AMP -> getErrorString("Parser.TOKEN.AMP") + | Parser.TOKEN_AMP_AMP -> getErrorString("Parser.TOKEN.AMP.AMP") + | Parser.TOKEN_BAR_BAR -> getErrorString("Parser.TOKEN.BAR.BAR") + | Parser.TOKEN_LESS -> getErrorString("Parser.TOKEN.LESS") + | Parser.TOKEN_GREATER -> getErrorString("Parser.TOKEN.GREATER") + | Parser.TOKEN_QMARK -> getErrorString("Parser.TOKEN.QMARK") | Parser.TOKEN_QMARK_QMARK -> getErrorString("Parser.TOKEN.QMARK.QMARK") | Parser.TOKEN_COLON_QMARK-> getErrorString("Parser.TOKEN.COLON.QMARK") | Parser.TOKEN_INT32_DOT_DOT -> getErrorString("Parser.TOKEN.INT32.DOT.DOT") - | Parser.TOKEN_DOT_DOT -> getErrorString("Parser.TOKEN.DOT.DOT") - | Parser.TOKEN_QUOTE -> getErrorString("Parser.TOKEN.QUOTE") - | Parser.TOKEN_STAR -> getErrorString("Parser.TOKEN.STAR") - | Parser.TOKEN_HIGH_PRECEDENCE_TYAPP -> getErrorString("Parser.TOKEN.HIGH.PRECEDENCE.TYAPP") - | Parser.TOKEN_COLON -> getErrorString("Parser.TOKEN.COLON") - | Parser.TOKEN_COLON_EQUALS -> getErrorString("Parser.TOKEN.COLON.EQUALS") - | Parser.TOKEN_LARROW -> getErrorString("Parser.TOKEN.LARROW") + | Parser.TOKEN_DOT_DOT -> getErrorString("Parser.TOKEN.DOT.DOT") + | Parser.TOKEN_QUOTE -> getErrorString("Parser.TOKEN.QUOTE") + | Parser.TOKEN_STAR -> getErrorString("Parser.TOKEN.STAR") + | Parser.TOKEN_HIGH_PRECEDENCE_TYAPP -> getErrorString("Parser.TOKEN.HIGH.PRECEDENCE.TYAPP") + | Parser.TOKEN_COLON -> getErrorString("Parser.TOKEN.COLON") + | Parser.TOKEN_COLON_EQUALS -> getErrorString("Parser.TOKEN.COLON.EQUALS") + | Parser.TOKEN_LARROW -> getErrorString("Parser.TOKEN.LARROW") | Parser.TOKEN_EQUALS -> getErrorString("Parser.TOKEN.EQUALS") | Parser.TOKEN_GREATER_BAR_RBRACK -> getErrorString("Parser.TOKEN.GREATER.BAR.RBRACK") | Parser.TOKEN_MINUS -> getErrorString("Parser.TOKEN.MINUS") - | Parser.TOKEN_ADJACENT_PREFIX_OP -> getErrorString("Parser.TOKEN.ADJACENT.PREFIX.OP") + | Parser.TOKEN_ADJACENT_PREFIX_OP -> getErrorString("Parser.TOKEN.ADJACENT.PREFIX.OP") | Parser.TOKEN_FUNKY_OPERATOR_NAME -> getErrorString("Parser.TOKEN.FUNKY.OPERATOR.NAME") | Parser.TOKEN_COMMA-> getErrorString("Parser.TOKEN.COMMA") | Parser.TOKEN_DOT -> getErrorString("Parser.TOKEN.DOT") | Parser.TOKEN_BAR-> getErrorString("Parser.TOKEN.BAR") | Parser.TOKEN_HASH -> getErrorString("Parser.TOKEN.HASH") - | Parser.TOKEN_UNDERSCORE -> getErrorString("Parser.TOKEN.UNDERSCORE") - | Parser.TOKEN_SEMICOLON -> getErrorString("Parser.TOKEN.SEMICOLON") + | Parser.TOKEN_UNDERSCORE -> getErrorString("Parser.TOKEN.UNDERSCORE") + | Parser.TOKEN_SEMICOLON -> getErrorString("Parser.TOKEN.SEMICOLON") | Parser.TOKEN_SEMICOLON_SEMICOLON-> getErrorString("Parser.TOKEN.SEMICOLON.SEMICOLON") | Parser.TOKEN_LPAREN-> getErrorString("Parser.TOKEN.LPAREN") | Parser.TOKEN_RPAREN | Parser.TOKEN_RPAREN_COMING_SOON | Parser.TOKEN_RPAREN_IS_HERE -> getErrorString("Parser.TOKEN.RPAREN") - | Parser.TOKEN_LQUOTE -> getErrorString("Parser.TOKEN.LQUOTE") - | Parser.TOKEN_LBRACK -> getErrorString("Parser.TOKEN.LBRACK") - | Parser.TOKEN_LBRACE_BAR -> getErrorString("Parser.TOKEN.LBRACE.BAR") - | Parser.TOKEN_LBRACK_BAR -> getErrorString("Parser.TOKEN.LBRACK.BAR") - | Parser.TOKEN_LBRACK_LESS -> getErrorString("Parser.TOKEN.LBRACK.LESS") - | Parser.TOKEN_LBRACE -> getErrorString("Parser.TOKEN.LBRACE") - | Parser.TOKEN_BAR_RBRACK -> getErrorString("Parser.TOKEN.BAR.RBRACK") - | Parser.TOKEN_BAR_RBRACE -> getErrorString("Parser.TOKEN.BAR.RBRACE") - | Parser.TOKEN_GREATER_RBRACK -> getErrorString("Parser.TOKEN.GREATER.RBRACK") + | Parser.TOKEN_LQUOTE -> getErrorString("Parser.TOKEN.LQUOTE") + | Parser.TOKEN_LBRACK -> getErrorString("Parser.TOKEN.LBRACK") + | Parser.TOKEN_LBRACE_BAR -> getErrorString("Parser.TOKEN.LBRACE.BAR") + | Parser.TOKEN_LBRACK_BAR -> getErrorString("Parser.TOKEN.LBRACK.BAR") + | Parser.TOKEN_LBRACK_LESS -> getErrorString("Parser.TOKEN.LBRACK.LESS") + | Parser.TOKEN_LBRACE -> getErrorString("Parser.TOKEN.LBRACE") + | Parser.TOKEN_BAR_RBRACK -> getErrorString("Parser.TOKEN.BAR.RBRACK") + | Parser.TOKEN_BAR_RBRACE -> getErrorString("Parser.TOKEN.BAR.RBRACE") + | Parser.TOKEN_GREATER_RBRACK -> getErrorString("Parser.TOKEN.GREATER.RBRACK") | Parser.TOKEN_RQUOTE_DOT _ - | Parser.TOKEN_RQUOTE -> getErrorString("Parser.TOKEN.RQUOTE") - | Parser.TOKEN_RBRACK -> getErrorString("Parser.TOKEN.RBRACK") + | Parser.TOKEN_RQUOTE -> getErrorString("Parser.TOKEN.RQUOTE") + | Parser.TOKEN_RBRACK -> getErrorString("Parser.TOKEN.RBRACK") | Parser.TOKEN_RBRACE | Parser.TOKEN_RBRACE_COMING_SOON | Parser.TOKEN_RBRACE_IS_HERE -> getErrorString("Parser.TOKEN.RBRACE") | Parser.TOKEN_PUBLIC -> getErrorString("Parser.TOKEN.PUBLIC") | Parser.TOKEN_PRIVATE -> getErrorString("Parser.TOKEN.PRIVATE") @@ -982,14 +982,14 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | Parser.TOKEN_MEMBER -> getErrorString("Parser.TOKEN.MEMBER") | Parser.TOKEN_STATIC -> getErrorString("Parser.TOKEN.STATIC") | Parser.TOKEN_NAMESPACE-> getErrorString("Parser.TOKEN.NAMESPACE") - | Parser.TOKEN_OBLOCKBEGIN -> getErrorString("Parser.TOKEN.OBLOCKBEGIN") + | Parser.TOKEN_OBLOCKBEGIN -> getErrorString("Parser.TOKEN.OBLOCKBEGIN") | EndOfStructuredConstructToken -> getErrorString("Parser.TOKEN.OBLOCKEND") | Parser.TOKEN_THEN | Parser.TOKEN_OTHEN -> getErrorString("Parser.TOKEN.OTHEN") | Parser.TOKEN_ELSE | Parser.TOKEN_OELSE -> getErrorString("Parser.TOKEN.OELSE") | Parser.TOKEN_LET(_) - | Parser.TOKEN_OLET(_) -> getErrorString("Parser.TOKEN.OLET") + | Parser.TOKEN_OLET(_) -> getErrorString("Parser.TOKEN.OLET") | Parser.TOKEN_OBINDER | Parser.TOKEN_BINDER -> getErrorString("Parser.TOKEN.BINDER") | Parser.TOKEN_ODO -> getErrorString("Parser.TOKEN.ODO") @@ -1001,50 +1001,50 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | Parser.TOKEN_DO_BANG | Parser.TOKEN_ODO_BANG -> getErrorString("Parser.TOKEN.ODO.BANG") | Parser.TOKEN_YIELD -> getErrorString("Parser.TOKEN.YIELD") - | Parser.TOKEN_YIELD_BANG -> getErrorString("Parser.TOKEN.YIELD.BANG") + | Parser.TOKEN_YIELD_BANG -> getErrorString("Parser.TOKEN.YIELD.BANG") | Parser.TOKEN_OINTERFACE_MEMBER-> getErrorString("Parser.TOKEN.OINTERFACE.MEMBER") | Parser.TOKEN_ELIF -> getErrorString("Parser.TOKEN.ELIF") | Parser.TOKEN_RARROW -> getErrorString("Parser.TOKEN.RARROW") | Parser.TOKEN_SIG -> getErrorString("Parser.TOKEN.SIG") - | Parser.TOKEN_STRUCT -> getErrorString("Parser.TOKEN.STRUCT") - | Parser.TOKEN_UPCAST -> getErrorString("Parser.TOKEN.UPCAST") - | Parser.TOKEN_DOWNCAST -> getErrorString("Parser.TOKEN.DOWNCAST") - | Parser.TOKEN_NULL -> getErrorString("Parser.TOKEN.NULL") - | Parser.TOKEN_RESERVED -> getErrorString("Parser.TOKEN.RESERVED") - | Parser.TOKEN_MODULE | Parser.TOKEN_MODULE_COMING_SOON | Parser.TOKEN_MODULE_IS_HERE -> getErrorString("Parser.TOKEN.MODULE") - | Parser.TOKEN_AND -> getErrorString("Parser.TOKEN.AND") - | Parser.TOKEN_AS -> getErrorString("Parser.TOKEN.AS") - | Parser.TOKEN_ASSERT -> getErrorString("Parser.TOKEN.ASSERT") - | Parser.TOKEN_OASSERT -> getErrorString("Parser.TOKEN.ASSERT") + | Parser.TOKEN_STRUCT -> getErrorString("Parser.TOKEN.STRUCT") + | Parser.TOKEN_UPCAST -> getErrorString("Parser.TOKEN.UPCAST") + | Parser.TOKEN_DOWNCAST -> getErrorString("Parser.TOKEN.DOWNCAST") + | Parser.TOKEN_NULL -> getErrorString("Parser.TOKEN.NULL") + | Parser.TOKEN_RESERVED -> getErrorString("Parser.TOKEN.RESERVED") + | Parser.TOKEN_MODULE | Parser.TOKEN_MODULE_COMING_SOON | Parser.TOKEN_MODULE_IS_HERE -> getErrorString("Parser.TOKEN.MODULE") + | Parser.TOKEN_AND -> getErrorString("Parser.TOKEN.AND") + | Parser.TOKEN_AS -> getErrorString("Parser.TOKEN.AS") + | Parser.TOKEN_ASSERT -> getErrorString("Parser.TOKEN.ASSERT") + | Parser.TOKEN_OASSERT -> getErrorString("Parser.TOKEN.ASSERT") | Parser.TOKEN_ASR-> getErrorString("Parser.TOKEN.ASR") - | Parser.TOKEN_DOWNTO -> getErrorString("Parser.TOKEN.DOWNTO") - | Parser.TOKEN_EXCEPTION -> getErrorString("Parser.TOKEN.EXCEPTION") - | Parser.TOKEN_FALSE -> getErrorString("Parser.TOKEN.FALSE") - | Parser.TOKEN_FOR -> getErrorString("Parser.TOKEN.FOR") - | Parser.TOKEN_FUN -> getErrorString("Parser.TOKEN.FUN") + | Parser.TOKEN_DOWNTO -> getErrorString("Parser.TOKEN.DOWNTO") + | Parser.TOKEN_EXCEPTION -> getErrorString("Parser.TOKEN.EXCEPTION") + | Parser.TOKEN_FALSE -> getErrorString("Parser.TOKEN.FALSE") + | Parser.TOKEN_FOR -> getErrorString("Parser.TOKEN.FOR") + | Parser.TOKEN_FUN -> getErrorString("Parser.TOKEN.FUN") | Parser.TOKEN_FUNCTION-> getErrorString("Parser.TOKEN.FUNCTION") - | Parser.TOKEN_FINALLY -> getErrorString("Parser.TOKEN.FINALLY") - | Parser.TOKEN_LAZY -> getErrorString("Parser.TOKEN.LAZY") - | Parser.TOKEN_OLAZY -> getErrorString("Parser.TOKEN.LAZY") - | Parser.TOKEN_MATCH -> getErrorString("Parser.TOKEN.MATCH") + | Parser.TOKEN_FINALLY -> getErrorString("Parser.TOKEN.FINALLY") + | Parser.TOKEN_LAZY -> getErrorString("Parser.TOKEN.LAZY") + | Parser.TOKEN_OLAZY -> getErrorString("Parser.TOKEN.LAZY") + | Parser.TOKEN_MATCH -> getErrorString("Parser.TOKEN.MATCH") | Parser.TOKEN_MATCH_BANG -> getErrorString("Parser.TOKEN.MATCH.BANG") - | Parser.TOKEN_MUTABLE -> getErrorString("Parser.TOKEN.MUTABLE") - | Parser.TOKEN_NEW -> getErrorString("Parser.TOKEN.NEW") - | Parser.TOKEN_OF -> getErrorString("Parser.TOKEN.OF") - | Parser.TOKEN_OPEN -> getErrorString("Parser.TOKEN.OPEN") + | Parser.TOKEN_MUTABLE -> getErrorString("Parser.TOKEN.MUTABLE") + | Parser.TOKEN_NEW -> getErrorString("Parser.TOKEN.NEW") + | Parser.TOKEN_OF -> getErrorString("Parser.TOKEN.OF") + | Parser.TOKEN_OPEN -> getErrorString("Parser.TOKEN.OPEN") | Parser.TOKEN_OR -> getErrorString("Parser.TOKEN.OR") | Parser.TOKEN_VOID -> getErrorString("Parser.TOKEN.VOID") | Parser.TOKEN_EXTERN-> getErrorString("Parser.TOKEN.EXTERN") | Parser.TOKEN_INTERFACE -> getErrorString("Parser.TOKEN.INTERFACE") - | Parser.TOKEN_REC -> getErrorString("Parser.TOKEN.REC") - | Parser.TOKEN_TO -> getErrorString("Parser.TOKEN.TO") - | Parser.TOKEN_TRUE -> getErrorString("Parser.TOKEN.TRUE") - | Parser.TOKEN_TRY -> getErrorString("Parser.TOKEN.TRY") - | Parser.TOKEN_TYPE | Parser.TOKEN_TYPE_COMING_SOON | Parser.TOKEN_TYPE_IS_HERE -> getErrorString("Parser.TOKEN.TYPE") - | Parser.TOKEN_VAL -> getErrorString("Parser.TOKEN.VAL") - | Parser.TOKEN_INLINE -> getErrorString("Parser.TOKEN.INLINE") - | Parser.TOKEN_WHEN -> getErrorString("Parser.TOKEN.WHEN") - | Parser.TOKEN_WHILE -> getErrorString("Parser.TOKEN.WHILE") + | Parser.TOKEN_REC -> getErrorString("Parser.TOKEN.REC") + | Parser.TOKEN_TO -> getErrorString("Parser.TOKEN.TO") + | Parser.TOKEN_TRUE -> getErrorString("Parser.TOKEN.TRUE") + | Parser.TOKEN_TRY -> getErrorString("Parser.TOKEN.TRY") + | Parser.TOKEN_TYPE | Parser.TOKEN_TYPE_COMING_SOON | Parser.TOKEN_TYPE_IS_HERE -> getErrorString("Parser.TOKEN.TYPE") + | Parser.TOKEN_VAL -> getErrorString("Parser.TOKEN.VAL") + | Parser.TOKEN_INLINE -> getErrorString("Parser.TOKEN.INLINE") + | Parser.TOKEN_WHEN -> getErrorString("Parser.TOKEN.WHEN") + | Parser.TOKEN_WHILE -> getErrorString("Parser.TOKEN.WHILE") | Parser.TOKEN_WITH-> getErrorString("Parser.TOKEN.WITH") | Parser.TOKEN_IF -> getErrorString("Parser.TOKEN.IF") | Parser.TOKEN_DO -> getErrorString("Parser.TOKEN.DO") @@ -1053,13 +1053,13 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | Parser.TOKEN_IN | Parser.TOKEN_JOIN_IN -> getErrorString("Parser.TOKEN.IN") | Parser.TOKEN_HIGH_PRECEDENCE_PAREN_APP-> getErrorString("Parser.TOKEN.HIGH.PRECEDENCE.PAREN.APP") | Parser.TOKEN_HIGH_PRECEDENCE_BRACK_APP-> getErrorString("Parser.TOKEN.HIGH.PRECEDENCE.BRACK.APP") - | Parser.TOKEN_BEGIN -> getErrorString("Parser.TOKEN.BEGIN") + | Parser.TOKEN_BEGIN -> getErrorString("Parser.TOKEN.BEGIN") | Parser.TOKEN_END -> getErrorString("Parser.TOKEN.END") | Parser.TOKEN_HASH_LIGHT | Parser.TOKEN_HASH_LINE | Parser.TOKEN_HASH_IF | Parser.TOKEN_HASH_ELSE - | Parser.TOKEN_HASH_ENDIF -> getErrorString("Parser.TOKEN.HASH.ENDIF") + | Parser.TOKEN_HASH_ENDIF -> getErrorString("Parser.TOKEN.HASH.ENDIF") | Parser.TOKEN_INACTIVECODE -> getErrorString("Parser.TOKEN.INACTIVECODE") | Parser.TOKEN_LEX_FAILURE-> getErrorString("Parser.TOKEN.LEX.FAILURE") | Parser.TOKEN_WHITESPACE -> getErrorString("Parser.TOKEN.WHITESPACE") @@ -1175,8 +1175,8 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | [NONTERM_Category_Definition] -> os.Append(NONTERM_Category_DefinitionE().Format) |> ignore; true | [NONTERM_Category_SignatureFile] -> os.Append(NONTERM_Category_SignatureFileE().Format) |> ignore; true | [NONTERM_Category_Pattern] -> os.Append(NONTERM_Category_PatternE().Format) |> ignore; true - | [NONTERM_Category_Expr] -> os.Append(NONTERM_Category_ExprE().Format) |> ignore; true - | [NONTERM_Category_Type] -> os.Append(NONTERM_Category_TypeE().Format) |> ignore; true + | [NONTERM_Category_Expr] -> os.Append(NONTERM_Category_ExprE().Format) |> ignore; true + | [NONTERM_Category_Type] -> os.Append(NONTERM_Category_TypeE().Format) |> ignore; true | [Parser.NONTERM_typeArgsActual] -> os.Append(NONTERM_typeArgsActualE().Format) |> ignore; true | _ -> false) @@ -1194,7 +1194,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = |> List.map tokenIdToText |> Set.ofList |> Set.toList) with - | [tokenName1] -> os.Append(TokenName1E().Format (fix tokenName1)) |> ignore + | [tokenName1] -> os.Append(TokenName1E().Format (fix tokenName1)) |> ignore | [tokenName1;tokenName2] -> os.Append(TokenName1TokenName2E().Format (fix tokenName1) (fix tokenName2)) |> ignore | [tokenName1;tokenName2;tokenName3] -> os.Append(TokenName1TokenName2TokenName3E().Format (fix tokenName1) (fix tokenName2) (fix tokenName3)) |> ignore | _ -> () @@ -1255,7 +1255,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = os.Append(OverrideDoesntOverride2E().Format sig1) |> ignore let sig2 = DispatchSlotChecking.FormatMethInfoSig g amap m denv minfoVirt if sig1 <> sig2 then - os.Append(OverrideDoesntOverride3E().Format sig2) |> ignore + os.Append(OverrideDoesntOverride3E().Format sig2) |> ignore | UnionCaseWrongArguments (_, n1, n2, _) -> os.Append(UnionCaseWrongArgumentsE().Format n2 n1) |> ignore @@ -1315,10 +1315,10 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = if isAlreadyMutable then UnitTypeExpectedWithPossibleAssignmentToMutableE().Format (NicePrint.stringOfTy denv ty) bindingName else - UnitTypeExpectedWithPossibleAssignmentE().Format (NicePrint.stringOfTy denv ty) bindingName + UnitTypeExpectedWithPossibleAssignmentE().Format (NicePrint.stringOfTy denv ty) bindingName os.Append warningText |> ignore - | RecursiveUseCheckedAtRuntime _ -> + | RecursiveUseCheckedAtRuntime _ -> os.Append(RecursiveUseCheckedAtRuntimeE().Format) |> ignore | LetRecUnsound (_, [v], _) -> @@ -1372,7 +1372,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | InvalidArgument s - | Failure s as exn -> + | Failure s as exn -> ignore exn // use the argument, even in non DEBUG let f1 = SR.GetString("Failure1") let f2 = SR.GetString("Failure2") @@ -1394,8 +1394,8 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = os.Append(MatchIncomplete1E().Format) |> ignore match cexOpt with | None -> () - | Some (cex, false) -> os.Append(MatchIncomplete2E().Format cex) |> ignore - | Some (cex, true) -> os.Append(MatchIncomplete3E().Format cex) |> ignore + | Some (cex, false) -> os.Append(MatchIncomplete2E().Format cex) |> ignore + | Some (cex, true) -> os.Append(MatchIncomplete3E().Format cex) |> ignore if isComp then os.Append(MatchIncomplete4E().Format) |> ignore @@ -1403,8 +1403,8 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = os.Append(EnumMatchIncomplete1E().Format) |> ignore match cexOpt with | None -> () - | Some (cex, false) -> os.Append(MatchIncomplete2E().Format cex) |> ignore - | Some (cex, true) -> os.Append(MatchIncomplete3E().Format cex) |> ignore + | Some (cex, false) -> os.Append(MatchIncomplete2E().Format cex) |> ignore + | Some (cex, true) -> os.Append(MatchIncomplete3E().Format cex) |> ignore if isComp then os.Append(MatchIncomplete4E().Format) |> ignore @@ -1453,7 +1453,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | MemberKind.PropertyGet | MemberKind.PropertySet | MemberKind.Constructor -> true (* can't infer extra polymorphism *) - | _ -> false (* can infer extra polymorphism *) + | _ -> false (* can infer extra polymorphism *) end -> os.Append(ValueRestriction3E().Format (NicePrint.stringOfQualifiedValOrMember denv v)) |> ignore | _ -> @@ -1542,7 +1542,7 @@ let OutputPhasedErrorR (os: StringBuilder) (err: PhasedDiagnostic) = | InvalidInternalsVisibleToAssemblyName(badName, fileNameOption) -> match fileNameOption with | Some file -> os.Append(InvalidInternalsVisibleToAssemblyName1E().Format badName file) |> ignore - | None -> os.Append(InvalidInternalsVisibleToAssemblyName2E().Format badName) |> ignore + | None -> os.Append(InvalidInternalsVisibleToAssemblyName2E().Format badName) |> ignore | LoadedSourceNotFoundIgnoring(filename, _) -> os.Append(LoadedSourceNotFoundIgnoringE().Format filename) |> ignore @@ -1593,7 +1593,7 @@ let SanitizeFileName fileName implicitIncludeDir = // - fsi.exe sometimes passes "stdin" as a dummy filename // - if you have a #line directive, e.g. // # 1000 "Line01.fs" - // then it also asserts. But these are edge cases that can be fixed later, e.g. in bug 4651. + // then it also asserts. But these are edge cases that can be fixed later, e.g. in bug 4651. //System.Diagnostics.Debug.Assert(FileSystem.IsPathRootedShim(fileName), sprintf "filename should be absolute: '%s'" fileName) try let fullPath = FileSystem.GetFullPathShim(fileName) @@ -1645,7 +1645,7 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt SanitizeFileName file implicitIncludeDir let text, m, file = match errorStyle with - | ErrorStyle.EmacsErrors -> + | ErrorStyle.EmacsErrors -> let file = file.Replace("\\", "/") (sprintf "File \"%s\", line %d, characters %d-%d: " file m.StartLine m.StartColumn m.EndColumn), m, file @@ -1656,18 +1656,18 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt (sprintf "%s(%d,%d): " file m.StartLine m.StartColumn), m, file // We may also want to change TestErrors to be 1-based - | ErrorStyle.TestErrors -> + | ErrorStyle.TestErrors -> let file = file.Replace("/", "\\") let m = mkRange m.FileName (mkPos m.StartLine (m.StartColumn + 1)) (mkPos m.EndLine (m.EndColumn + 1) ) sprintf "%s(%d,%d-%d,%d): " file m.StartLine m.StartColumn m.EndLine m.EndColumn, m, file - | ErrorStyle.GccErrors -> + | ErrorStyle.GccErrors -> let file = file.Replace('/', System.IO.Path.DirectorySeparatorChar) let m = mkRange m.FileName (mkPos m.StartLine (m.StartColumn + 1)) (mkPos m.EndLine (m.EndColumn + 1) ) sprintf "%s:%d:%d: " file m.StartLine m.StartColumn, m, file // Here, we want the complete range information so Project Systems can generate proper squiggles - | ErrorStyle.VSErrors -> + | ErrorStyle.VSErrors -> // Show prefix only for real files. Otherwise, we just want a truncated error like: // parse error FS0031: blah blah if m<>range0 && m<>rangeStartup && m<>rangeCmdArgs then @@ -1699,7 +1699,7 @@ let CollectDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, errorSt // Show the subcategory for --vserrors so that we can fish it out in Visual Studio and use it to determine error stickiness. | ErrorStyle.VSErrors -> sprintf "%s %s FS%04d: " subcategory (if isError then "error" else "warning") errorNumber | _ -> sprintf "%s FS%04d: " (if isError then "error" else "warning") errorNumber - { ErrorNumber = errorNumber; Subcategory = subcategory; TextRepresentation = text} + { ErrorNumber = errorNumber; Subcategory = subcategory; TextRepresentation = text} let mainError, relatedErrors = SplitRelatedDiagnostics err let where = OutputWhere(mainError) @@ -1765,17 +1765,17 @@ let rec OutputDiagnostic (implicitIncludeDir, showFullPaths, flattenErrors, erro let OutputDiagnosticContext prefix fileLineFn os err = match GetRangeOfDiagnostic err with - | None -> () + | None -> () | Some m -> let filename = m.FileName let lineA = m.StartLine let lineB = m.EndLine - let line = fileLineFn filename lineA + let line = fileLineFn filename lineA if line<>"" then - let iA = m.StartColumn - let iB = m.EndColumn - let iLen = if lineA = lineB then max (iB - iA) 1 else 1 - Printf.bprintf os "%s%s\n" prefix line + let iA = m.StartColumn + let iB = m.EndColumn + let iLen = if lineA = lineB then max (iB - iA) 1 else 1 + Printf.bprintf os "%s%s\n" prefix line Printf.bprintf os "%s%s%s\n" prefix (String.make iA '-') (String.make iLen '^') //---------------------------------------------------------------------------- @@ -1788,7 +1788,7 @@ let GetDefaultFSharpCoreReference () = typeof>.Assembly.Location type private TypeInThisAssembly = class end // Use the ValueTuple that is executing with the compiler if it is from System.ValueTuple -// or the System.ValueTuple.dll that sits alongside the compiler. (Note we always ship one with the compiler) +// or the System.ValueTuple.dll that sits alongside the compiler. (Note we always ship one with the compiler) let GetDefaultSystemValueTupleReference () = try let asm = typeof>.Assembly @@ -1822,7 +1822,7 @@ let DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) = yield "System.Drawing" yield "System.Core" - // These are the Portable-profile and .NET Standard 1.6 dependencies of FSharp.Core.dll. These are needed + // These are the Portable-profile and .NET Standard 1.6 dependencies of FSharp.Core.dll. These are needed // when an F# sript references an F# profile 7, 78, 259 or .NET Standard 1.6 component which in turn refers // to FSharp.Core for profile 7, 78, 259 or .NET Standard. yield "System.Runtime" // lots of types @@ -1867,8 +1867,8 @@ let DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) = ] -// A set of assemblies to always consider to be system assemblies. A common set of these can be used a shared -// resources between projects in the compiler services. Also all assembles where well-known system types exist +// A set of assemblies to always consider to be system assemblies. A common set of these can be used a shared +// resources between projects in the compiler services. Also all assembles where well-known system types exist // referenced from TcGlobals must be listed here. let SystemAssemblies () = HashSet @@ -2002,14 +2002,14 @@ let (++) x s = x @ [s] /// Will return None if the filename is not found. let TryResolveFileUsingPaths(paths, m, name) = let () = - try FileSystem.IsPathRootedShim(name) |> ignore + try FileSystem.IsPathRootedShim(name) |> ignore with :? System.ArgumentException as e -> error(Error(FSComp.SR.buildProblemWithFilename(name, e.Message), m)) if FileSystem.IsPathRootedShim(name) && FileSystem.SafeExists name then Some name else let res = paths |> List.tryPick (fun path -> let n = Path.Combine (path, name) - if FileSystem.SafeExists n then Some n + if FileSystem.SafeExists n then Some n else None) res @@ -2092,7 +2092,7 @@ type IRawFSharpAssemblyData = /// The raw list AutoOpenAttribute attributes in the assembly 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 @@ -2143,7 +2143,7 @@ and IProjectReference = /// /// For project references this is maximum of the timestamps of all dependent files. /// The project is not actually built, nor are any assemblies read, but the timestamps for each dependent file - /// are read via the FileSystem. If the files don't exist, then a default timestamp is used. + /// are read via the FileSystem. If the files don't exist, then a default timestamp is used. /// /// 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. @@ -2299,7 +2299,7 @@ type TcConfigBuilder = 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 doTLR: bool (* run TLR pass? *) mutable doFinalSimplify: bool (* do final simplification pass *) mutable optsOn: bool (* optimizations are turned on *) mutable optSettings: Optimizer.OptimizationSettings @@ -2525,7 +2525,7 @@ type TcConfigBuilder = let outfile = match tcConfigB.outputFile, List.rev implFiles with | None, [] -> "out" + ext() - | None, h :: _ -> + | None, h :: _ -> let basic = fileNameOfPath h let modname = try Filename.chopExtension basic with _ -> basic modname+(ext()) @@ -2608,7 +2608,7 @@ type TcConfigBuilder = member tcConfigB.AddReferencedAssemblyByPath (m, path) = if FileSystem.IsInvalidPathShim(path) then warning(Error(FSComp.SR.buildInvalidAssemblyName(path), m)) - elif not (tcConfigB.referencedDLLs |> List.exists (fun ar2 -> m=ar2.Range && path=ar2.Text)) then // NOTE: We keep same paths if range is different. + elif not (tcConfigB.referencedDLLs |> List.exists (fun ar2 -> m=ar2.Range && path=ar2.Text)) then // NOTE: We keep same paths if range is different. let projectReference = tcConfigB.projectReferences |> List.tryPick (fun pr -> if pr.FileName = path then Some pr else None) tcConfigB.referencedDLLs <- tcConfigB.referencedDLLs ++ AssemblyReference(m, path, projectReference) @@ -2670,11 +2670,11 @@ type AssemblyResolution = member this.ProjectReference = this.originalReference.ProjectReference - /// Compute the ILAssemblyRef for a resolved assembly. This is done by reading the binary if necessary. The result + /// Compute the ILAssemblyRef for a resolved assembly. This is done by reading the binary if necessary. The result /// is cached. /// /// For project references in the language service, this would result in a build of the project. - /// This is because ``EvaluateRawContents(ctok)`` is used. However this path is only currently used + /// This is because ``EvaluateRawContents(ctok)`` is used. However this path is only currently used /// in fsi.fs, which does not use project references. // member this.GetILAssemblyRef(ctok, reduceMemoryUsage, tryGetMetadataSnapshot) = @@ -2692,7 +2692,7 @@ type AssemblyResolution = | Some contents -> match contents.ILScopeRef with | ILScopeRef.Assembly aref -> return Some aref - | _ -> return None + | _ -> return None | None -> return None } let assemblyRef = @@ -2794,7 +2794,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = // targetFrameworkVersion shouldn't matter since resolution has already happened. // In those cases where it does matter (e.g. --noframework is not being used or we are processing further // resolutions for a script) then it is correct to just use HighestInstalledNetFrameworkVersion(). - let clrRootValue, targetFrameworkVersionValue = + let clrRootValue, targetFrameworkVersionValue = match primaryAssemblyExplicitFilenameOpt with | Some primaryAssemblyFilename -> let filename = ComputeMakePathAbsolute data.implicitIncludeDir primaryAssemblyFilename @@ -2806,7 +2806,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = error(Error(FSComp.SR.buildErrorOpeningBinaryFile(filename, e.Message), rangeStartup)) | None -> #if !ENABLE_MONO_SUPPORT - // TODO: we have to get msbuild out of this + // TODO: we have to get msbuild out of this if data.useSimpleResolution then None, "" else @@ -2867,87 +2867,87 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = member x.subsystemVersion = data.subsystemVersion member x.useHighEntropyVA = data.useHighEntropyVA member x.inputCodePage = data.inputCodePage - member x.embedResources = data.embedResources + member x.embedResources = data.embedResources member x.errorSeverityOptions = data.errorSeverityOptions member x.mlCompatibility = data.mlCompatibility member x.checkOverflow = data.checkOverflow member x.showReferenceResolutions = data.showReferenceResolutions - member x.outputFile = data.outputFile - member x.platform = data.platform + member x.outputFile = data.outputFile + member x.platform = data.platform member x.prefer32Bit = data.prefer32Bit - member x.useSimpleResolution = data.useSimpleResolution - member x.target = data.target - member x.debuginfo = data.debuginfo + member x.useSimpleResolution = data.useSimpleResolution + member x.target = data.target + member x.debuginfo = data.debuginfo member x.testFlagEmitFeeFeeAs100001 = data.testFlagEmitFeeFeeAs100001 member x.dumpDebugInfo = data.dumpDebugInfo - member x.debugSymbolFile = data.debugSymbolFile - member x.typeCheckOnly = data.typeCheckOnly - member x.parseOnly = data.parseOnly + member x.debugSymbolFile = data.debugSymbolFile + member x.typeCheckOnly = data.typeCheckOnly + member x.parseOnly = data.parseOnly member x.importAllReferencesOnly = data.importAllReferencesOnly member x.simulateException = data.simulateException - member x.printAst = data.printAst + member x.printAst = data.printAst member x.targetFrameworkVersion = targetFrameworkVersionValue - member x.tokenizeOnly = data.tokenizeOnly - member x.testInteractionParser = data.testInteractionParser - member x.reportNumDecls = data.reportNumDecls - member x.printSignature = data.printSignature - member x.printSignatureFile = data.printSignatureFile - member x.xmlDocOutputFile = data.xmlDocOutputFile - member x.stats = data.stats - member x.generateFilterBlocks = data.generateFilterBlocks - member x.signer = data.signer + member x.tokenizeOnly = data.tokenizeOnly + member x.testInteractionParser = data.testInteractionParser + member x.reportNumDecls = data.reportNumDecls + member x.printSignature = data.printSignature + member x.printSignatureFile = data.printSignatureFile + member x.xmlDocOutputFile = data.xmlDocOutputFile + member x.stats = data.stats + member x.generateFilterBlocks = data.generateFilterBlocks + member x.signer = data.signer member x.container = data.container - member x.delaysign = data.delaysign - member x.publicsign = data.publicsign - member x.version = data.version + member x.delaysign = data.delaysign + member x.publicsign = data.publicsign + member x.version = data.version member x.metadataVersion = data.metadataVersion - member x.standalone = data.standalone - member x.extraStaticLinkRoots = data.extraStaticLinkRoots - member x.noSignatureData = data.noSignatureData - member x.onlyEssentialOptimizationData = data.onlyEssentialOptimizationData - member x.useOptimizationDataFile = data.useOptimizationDataFile - member x.jitTracking = data.jitTracking - member x.portablePDB = data.portablePDB - member x.embeddedPDB = data.embeddedPDB - member x.embedAllSource = data.embedAllSource - member x.embedSourceList = data.embedSourceList - member x.sourceLink = data.sourceLink - member x.ignoreSymbolStoreSequencePoints = data.ignoreSymbolStoreSequencePoints - member x.internConstantStrings = data.internConstantStrings - member x.extraOptimizationIterations = data.extraOptimizationIterations - member x.win32res = data.win32res + member x.standalone = data.standalone + member x.extraStaticLinkRoots = data.extraStaticLinkRoots + member x.noSignatureData = data.noSignatureData + member x.onlyEssentialOptimizationData = data.onlyEssentialOptimizationData + member x.useOptimizationDataFile = data.useOptimizationDataFile + member x.jitTracking = data.jitTracking + member x.portablePDB = data.portablePDB + member x.embeddedPDB = data.embeddedPDB + member x.embedAllSource = data.embedAllSource + member x.embedSourceList = data.embedSourceList + member x.sourceLink = data.sourceLink + member x.ignoreSymbolStoreSequencePoints = data.ignoreSymbolStoreSequencePoints + member x.internConstantStrings = data.internConstantStrings + member x.extraOptimizationIterations = data.extraOptimizationIterations + member x.win32res = data.win32res member x.win32manifest = data.win32manifest member x.includewin32manifest = data.includewin32manifest - member x.linkResources = data.linkResources - member x.showFullPaths = data.showFullPaths - member x.errorStyle = data.errorStyle - member x.utf8output = data.utf8output + member x.linkResources = data.linkResources + member x.showFullPaths = data.showFullPaths + member x.errorStyle = data.errorStyle + member x.utf8output = data.utf8output member x.flatErrors = data.flatErrors - member x.maxErrors = data.maxErrors - member x.baseAddress = data.baseAddress + member x.maxErrors = data.maxErrors + member x.baseAddress = data.baseAddress #if DEBUG - member x.showOptimizationData = data.showOptimizationData + member x.showOptimizationData = data.showOptimizationData #endif - member x.showTerms = data.showTerms - member x.writeTermsToFiles = data.writeTermsToFiles - member x.doDetuple = data.doDetuple - member x.doTLR = data.doTLR - member x.doFinalSimplify = data.doFinalSimplify - member x.optSettings = data.optSettings - member x.emitTailcalls = data.emitTailcalls - member x.deterministic = data.deterministic - member x.preferredUiLang = data.preferredUiLang - member x.lcid = data.lcid - member x.optsOn = data.optsOn - member x.productNameForBannerText = data.productNameForBannerText - member x.showBanner = data.showBanner - member x.showTimes = data.showTimes + member x.showTerms = data.showTerms + member x.writeTermsToFiles = data.writeTermsToFiles + member x.doDetuple = data.doDetuple + member x.doTLR = data.doTLR + member x.doFinalSimplify = data.doFinalSimplify + member x.optSettings = data.optSettings + member x.emitTailcalls = data.emitTailcalls + member x.deterministic = data.deterministic + member x.preferredUiLang = data.preferredUiLang + member x.lcid = data.lcid + member x.optsOn = data.optsOn + member x.productNameForBannerText = data.productNameForBannerText + member x.showBanner = data.showBanner + member x.showTimes = data.showTimes member x.showLoadedAssemblies = data.showLoadedAssemblies member x.continueAfterParseFailure = data.continueAfterParseFailure #if !NO_EXTENSIONTYPING - member x.showExtensionTypeMessages = data.showExtensionTypeMessages + member x.showExtensionTypeMessages = data.showExtensionTypeMessages #endif - member x.pause = data.pause + member x.pause = data.pause member x.alwaysCallVirt = data.alwaysCallVirt member x.noDebugData = data.noDebugData member x.isInteractive = data.isInteractive @@ -3057,7 +3057,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = |> List.distinct /// A closed set of assemblies where, for any subset S: - /// - the TcImports object built for S (and thus the F# Compiler CCUs for the assemblies in S) + /// - the TcImports object built for S (and thus the F# Compiler CCUs for the assemblies in S) /// is a resource that can be shared between any two IncrementalBuild objects that reference /// precisely S /// @@ -3113,7 +3113,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = let searchPaths = // if this is a #r reference (not from dummy range), make sure the directory of the declaring // file is included in the search path. This should ideally already be one of the search paths, but - // during some global checks it won't be. We append to the end of the search list so that this is the last + // during some global checks it won't be. We append to the end of the search list so that this is the last // place that is checked. if m <> range0 && m <> rangeStartup && m <> rangeCmdArgs && FileSystem.IsPathRootedShim m.FileName then tcConfig.GetSearchPathsForLibraryFiles() @ [Path.GetDirectoryName(m.FileName)] @@ -3186,7 +3186,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = assemblyName, highestPosition, assemblyGroup) |> Array.ofSeq - let logMessage showMessages = + let logMessage showMessages = if showMessages && tcConfig.showReferenceResolutions then (fun (message: string)->dprintf "%s\n" message) else ignore @@ -3396,7 +3396,7 @@ let QualFileNameOfSpecs filename specs = let QualFileNameOfImpls filename specs = match specs with | [SynModuleOrNamespace(modname, _, kind, _, _, _, _, m)] when kind.IsModule -> QualFileNameOfModuleName m filename modname - | [SynModuleOrNamespace(_, _, kind, _, _, _, _, m)] when not kind.IsModule -> QualFileNameOfFilename m filename + | [SynModuleOrNamespace(_, _, kind, _, _, _, _, m)] when not kind.IsModule -> QualFileNameOfFilename m filename | _ -> QualFileNameOfFilename (mkRange filename pos0 pos0) filename let PrepandPathToQualFileName x (QualifiedNameOfFile(q)) = ComputeQualifiedNameOfFileFromUniquePath (q.idRange, pathOfLid x@[q.idText]) @@ -3418,7 +3418,7 @@ let ComputeAnonModuleName check defaultNamespace filename (m: range) = | None -> modname | Some ns -> textOfPath [ns;modname] - let anonymousModuleNameRange = + let anonymousModuleNameRange = let filename = m.FileName mkRange filename pos0 pos0 pathToSynLid anonymousModuleNameRange (splitNamespace combined) @@ -3507,7 +3507,7 @@ let PostParseModuleImpls (defaultNamespace, filename, isLastCompiland, ParsedImp let PostParseModuleSpecs (defaultNamespace, filename, isLastCompiland, ParsedSigFile(hashDirectives, specs)) = match specs |> List.rev |> List.tryPick (function ParsedSigFileFragment.NamedModule(SynModuleOrNamespaceSig(lid, _, _, _, _, _, _, _)) -> Some(lid) | _ -> None) with - | Some lid when specs.Length > 1 -> + | Some lid when specs.Length > 1 -> errorR(Error(FSComp.SR.buildMultipleToplevelModules(), rangeOfLid lid)) | _ -> () @@ -3562,7 +3562,7 @@ let ParseInput (lexer, errorLogger: ErrorLogger, lexbuf: UnicodeLexing.Lexbuf, d // - fsi.exe sometimes passes "stdin" as a dummy filename // - if you have a #line directive, e.g. // # 1000 "Line01.fs" - // then it also asserts. But these are edge cases that can be fixed later, e.g. in bug 4651. + // then it also asserts. But these are edge cases that can be fixed later, e.g. in bug 4651. //System.Diagnostics.Debug.Assert(System.IO.Path.IsPathRooted(filename), sprintf "should be absolute: '%s'" filename) let lower = String.lowercase filename // Delay sending errors and warnings until after the file is parsed. This gives us a chance to scrape the @@ -3570,16 +3570,16 @@ let ParseInput (lexer, errorLogger: ErrorLogger, lexbuf: UnicodeLexing.Lexbuf, d let delayLogger = CapturingErrorLogger("Parsing") use unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> delayLogger) use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.Parse - let mutable scopedPragmas = [] + let mutable scopedPragmas = [] try let input = - if mlCompatSuffixes |> List.exists (Filename.checkSuffix lower) then + if mlCompatSuffixes |> List.exists (Filename.checkSuffix lower) then mlCompatWarning (FSComp.SR.buildCompilingExtensionIsForML()) rangeStartup - if FSharpImplFileSuffixes |> List.exists (Filename.checkSuffix lower) then + if FSharpImplFileSuffixes |> List.exists (Filename.checkSuffix lower) then let impl = Parser.implementationFile lexer lexbuf PostParseModuleImpls (defaultNamespace, filename, isLastCompiland, impl) - elif FSharpSigFileSuffixes |> List.exists (Filename.checkSuffix lower) then + elif FSharpSigFileSuffixes |> List.exists (Filename.checkSuffix lower) then let intfs = Parser.signatureFile lexer lexbuf PostParseModuleSpecs (defaultNamespace, filename, isLastCompiland, intfs) else @@ -3613,7 +3613,7 @@ let ParseOneInputLexbuf (tcConfig: TcConfig, lexResourceManager, conditionalComp let t = tokenizer.Lexer lexbuf printf "tokenize - got %s @ %a\n" (Parser.token_to_string t) outputRange lexbuf.LexemeRange (match t with Parser.EOF _ -> exit 0 | _ -> ()) - if lexbuf.IsPastEndOfStream then printf "!!! at end of stream\n" + if lexbuf.IsPastEndOfStream then printf "!!! at end of stream\n" if tcConfig.testInteractionParser then while true do @@ -3647,7 +3647,7 @@ let ParseOneInputLexbuf (tcConfig: TcConfig, lexResourceManager, conditionalComp let ParseOneInputFile (tcConfig: TcConfig, lexResourceManager, conditionalCompilationDefines, filename, isLastCompiland, errorLogger, retryLocked) = try let lower = String.lowercase filename - if List.exists (Filename.checkSuffix lower) (FSharpSigFileSuffixes@FSharpImplFileSuffixes) then + if List.exists (Filename.checkSuffix lower) (FSharpSigFileSuffixes@FSharpImplFileSuffixes) then if not(FileSystem.SafeExists(filename)) then error(Error(FSComp.SR.buildCouldNotFindSourceFile(filename), rangeStartup)) // bug 3155: if the file name is indirect, use a full path @@ -3661,7 +3661,7 @@ let ParseOneInputFile (tcConfig: TcConfig, lexResourceManager, conditionalCompil 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 + let resolvedPathToResolution = results |> List.map (fun r -> r.resolvedPath, r) |> Map.ofList /// Add some resolutions to the map of resolution results. member tcResolutions.AddResolutionResults(newResults) = TcAssemblyResolutions(tcConfig, results @ newResults, unresolved) @@ -3770,15 +3770,15 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, // Typecheck and optimization environments on disk //-------------------------------------------------------------------------- -let IsSignatureDataResource (r: ILResource) = +let IsSignatureDataResource (r: ILResource) = r.Name.StartsWithOrdinal(FSharpSignatureDataResourceName) || r.Name.StartsWithOrdinal(FSharpSignatureDataResourceName2) -let IsOptimizationDataResource (r: ILResource) = +let IsOptimizationDataResource (r: ILResource) = r.Name.StartsWithOrdinal(FSharpOptimizationDataResourceName)|| r.Name.StartsWithOrdinal(FSharpOptimizationDataResourceName2) -let GetSignatureDataResourceName (r: ILResource) = +let GetSignatureDataResourceName (r: ILResource) = if r.Name.StartsWithOrdinal(FSharpSignatureDataResourceName) then String.dropPrefix r.Name FSharpSignatureDataResourceName elif r.Name.StartsWithOrdinal(FSharpSignatureDataResourceName2) then @@ -3867,7 +3867,7 @@ type RawFSharpAssemblyDataBackedByFileOnDisk (ilModule: ILModuleDef, ilAssemblyR let optDataReaders = if optDataReaders.IsEmpty && List.contains ilShortAssemName externalSigAndOptData then let optDataFile = Path.ChangeExtension(filename, "optdata") - if not (FileSystem.SafeExists optDataFile) then + if not (FileSystem.SafeExists optDataFile) then error(Error(FSComp.SR.buildExpectedFileAlongSideFSharpCore(optDataFile, FileSystem.GetFullPathShim optDataFile), m)) [ (ilShortAssemName, (fun () -> FileSystem.ReadAllBytesShim optDataFile))] else @@ -3949,7 +3949,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu | None -> false | None -> false - member private tcImports.Base = + member private tcImports.Base = CheckDisposed() importsBase @@ -4009,7 +4009,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu member tcImports.GetImportedAssemblies() = CheckDisposed() match importsBase with - | Some(importsBase)-> List.append (importsBase.GetImportedAssemblies()) ccuInfos + | Some(importsBase)-> List.append (importsBase.GetImportedAssemblies()) ccuInfos | None -> ccuInfos member tcImports.GetCcusExcludingBase() = @@ -4202,7 +4202,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu CheckDisposed() tcImports.GetDllInfos() |> List.exists (fun dll -> match dll.ILScopeRef with - | ILScopeRef.Assembly a -> a.Name = nm + | ILScopeRef.Assembly a -> a.Name = nm | _ -> false) member tcImports.GetImportMap() = @@ -4322,14 +4322,14 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu name.Version let typeProviderEnvironment = - { resolutionFolder = tcConfig.implicitIncludeDir - outputFile = tcConfig.outputFile + { resolutionFolder = tcConfig.implicitIncludeDir + outputFile = tcConfig.outputFile showResolutionMessages = tcConfig.showExtensionTypeMessages - referencedAssemblies = Array.distinct [| for r in tcImports.AllAssemblyResolutions() -> r.resolvedPath |] - temporaryFolder = FileSystem.GetTempPathShim() } + referencedAssemblies = Array.distinct [| for r in tcImports.AllAssemblyResolutions() -> r.resolvedPath |] + temporaryFolder = FileSystem.GetTempPathShim() } // The type provider should not hold strong references to disposed - // TcImport objects. So the callbacks provided in the type provider config + // TcImport objects. So the callbacks provided in the type provider config // dispatch via a thunk which gets set to a non-resource-capturing // failing function when the object is disposed. let systemRuntimeContainsType = @@ -4487,7 +4487,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu Stamp = newStamp() FileName = Some filename QualifiedName= Some(ilScopeRef.QualifiedName) - SourceCodeDirectory = codeDir (* note: in some cases we fix up this information later *) + SourceCodeDirectory = codeDir (* note: in some cases we fix up this information later *) IsFSharp=true Contents = mspec #if !NO_EXTENSIONTYPING @@ -4504,7 +4504,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let optdata = lazy - (match Map.tryFind ccuName optDatas with + (match Map.tryFind ccuName optDatas with | None -> if verbose then dprintf "*** no optimization data for CCU %s, was DLL compiled with --no-optimization-data??\n" ccuName None @@ -4548,7 +4548,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu phase2 - // NOTE: When used in the Language Service this can cause the transitive checking of projects. Hence it must be cancellable. + // 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)> = cancellable { CheckDisposed() @@ -4589,7 +4589,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu tcImports.RegisterDll(dllinfo) let ilg = defaultArg ilGlobalsOpt EcmaMscorlibILGlobals let phase2 = - if assemblyData.HasAnyFSharpSignatureDataAttribute then + if assemblyData.HasAnyFSharpSignatureDataAttribute then if not (assemblyData.HasMatchingFSharpSignatureDataAttribute(ilg)) then errorR(Error(FSComp.SR.buildDifferentVersionMustRecompile(filename), m)) tcImports.PrepareToImportReferencedILAssembly (ctok, m, filename, dllinfo) @@ -4602,7 +4602,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu return dllinfo, phase2 } - // NOTE: When used in the Language Service this can cause the transitive checking of projects. Hence it must be cancellable. + // 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) = cancellable { CheckDisposed() @@ -4624,7 +4624,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu } /// Note that implicit loading is not used for compilations from MSBuild, which passes ``--noframework`` - /// Implicit loading is done in non-cancellation mode. Implicit loading is never used in the language service, so + /// Implicit loading is done in non-cancellation mode. Implicit loading is never used in the language service, so /// no cancellation is needed. member tcImports.ImplicitLoadIfAllowed (ctok, m, assemblyName, lookupOnly) = CheckDisposed() @@ -4644,10 +4644,10 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu false if tryFile (assemblyName + ".dll") then () - else tryFile (assemblyName + ".exe") |> ignore + 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 -> @@ -4657,12 +4657,12 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu #endif /// This doesn't need to be cancellable, it is only used by F# Interactive - member tcImports.TryFindExistingFullyQualifiedPathBySimpleAssemblyName (ctok, simpleAssemName) : string option = + member tcImports.TryFindExistingFullyQualifiedPathBySimpleAssemblyName (ctok, simpleAssemName) : string option = 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 = - resolutions.TryFindByExactILAssemblyRef (ctok, assemblyRef) |> Option.map (fun r -> r.resolvedPath) + 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 = let tcConfig = tcConfigP.Get(ctok) @@ -4698,10 +4698,10 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu // But don't cache resolution failures because the assembly may appear on the disk later. let resolved, unresolved = TcConfig.TryResolveLibsUsingMSBuildRules(tcConfig, [ assemblyReference ], assemblyReference.Range, mode) match resolved, unresolved with - | (assemblyResolution::_, _) -> + | (assemblyResolution::_, _) -> resolutions <- resolutions.AddResolutionResults resolved ResultD [assemblyResolution] - | (_, _::_) -> + | (_, _::_) -> resolutions <- resolutions.AddUnresolvedReferences unresolved ErrorD(AssemblyNotResolved(assemblyReference.Text, assemblyReference.Range)) | [], [] -> @@ -4736,7 +4736,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let primaryScopeRef = match primaryAssem with | (_, [ResolvedImportedAssembly(ccu)]) -> ccu.FSharpViewOfMetadata.ILScopeRef - | _ -> failwith "unexpected" + | _ -> failwith "unexpected" let ilGlobals = mkILGlobals primaryScopeRef frameworkTcImports.SetILGlobals ilGlobals @@ -4784,7 +4784,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu IlxSettings.ilxFsharpCoreLibAssemRef := (let scoref = fslibCcuInfo.ILScopeRef match scoref with - | ILScopeRef.Assembly aref -> Some aref + | ILScopeRef.Assembly aref -> Some aref | ILScopeRef.Local | ILScopeRef.Module _ -> error(InternalError("not ILScopeRef.Assembly", rangeStartup))) fslibCcuInfo.FSharpViewOfMetadata @@ -4860,7 +4860,7 @@ let RequireDLL (ctok, tcImports: TcImports, tcEnv, thisAssemblyName, m, file) = let dllinfos, ccuinfos = tcImports.RegisterAndImportReferencedAssemblies(ctok, resolutions) |> Cancellable.runWithoutCancellation let asms = - ccuinfos |> List.map (function + ccuinfos |> List.map (function | ResolvedImportedAssembly(asm) -> asm | UnresolvedImportedAssembly(assemblyName) -> error(Error(FSComp.SR.buildCouldNotResolveAssemblyRequiredByFile(assemblyName, file), m))) @@ -4881,10 +4881,10 @@ let ProcessMetaCommandsFromInput let canHaveScriptMetaCommands = match inp with - | ParsedInput.SigFile(_) -> false + | ParsedInput.SigFile(_) -> false | ParsedInput.ImplFile(ParsedImplFileInput(isScript = isScript)) -> isScript - let ProcessMetaCommand state hash = + let ProcessMetaCommand state hash = let mutable matchedm = range0 try match hash with @@ -5015,7 +5015,7 @@ type LoadClosureInput = { FileName: string SyntaxTree: ParsedInput option ParseDiagnostics: (PhasedDiagnostic * bool) list - MetaCommandDiagnostics: (PhasedDiagnostic * bool) list } + MetaCommandDiagnostics: (PhasedDiagnostic * bool) list } [] type LoadClosure = @@ -5032,7 +5032,7 @@ 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 /// Diagnostics seen while processing the compiler options implied root of closure @@ -5053,7 +5053,7 @@ module private ScriptPreprocessClosure = type ClosureSource = ClosureSource of filename: string * referenceRange: range * sourceText: string * parseRequired: bool /// Represents an output of the closure finding process - type ClosureFile = ClosureFile of string * range * ParsedInput option * (PhasedDiagnostic * bool) list * (PhasedDiagnostic * bool) list * (string * range) list // filename, range, errors, warnings, nowarns + type ClosureFile = ClosureFile of string * range * ParsedInput option * (PhasedDiagnostic * bool) list * (PhasedDiagnostic * bool) list * (string * range) list // filename, range, errors, warnings, nowarns type Observed() = let seen = System.Collections.Generic.Dictionary<_, bool>() @@ -5127,8 +5127,8 @@ module private ScriptPreprocessClosure = use stream = FileSystem.FileStreamReadShim filename use reader = match inputCodePage with - | None -> new StreamReader(stream, true) - | Some (n: int) -> new StreamReader(stream, Encoding.GetEncoding(n)) + | None -> new StreamReader(stream, true) + | Some (n: int) -> new StreamReader(stream, Encoding.GetEncoding(n)) let source = reader.ReadToEnd() [ClosureSource(filename, m, source, parseRequired)] with e -> @@ -5152,7 +5152,7 @@ module private ScriptPreprocessClosure = try TcConfig.Create(tcConfigB, validate=false), nowarns with ReportedError _ -> - // Recover by using a default TcConfig. + // Recover by using a default TcConfig. let tcConfigB = tcConfig.CloneOfOriginalBuilder TcConfig.Create(tcConfigB, validate=false), nowarns @@ -5233,7 +5233,7 @@ module private ScriptPreprocessClosure = | _ -> closureFiles // Get all source files. - let sourceFiles = [ for (ClosureFile(filename, m, _, _, _, _)) in closureFiles -> (filename, m) ] + let sourceFiles = [ for (ClosureFile(filename, m, _, _, _, _)) in closureFiles -> (filename, m) ] let sourceInputs = [ for (ClosureFile(filename, _, input, parseDiagnostics, metaDiagnostics, _nowarns)) in closureFiles -> @@ -5250,7 +5250,7 @@ module private ScriptPreprocessClosure = use unwindEL = PushErrorLoggerPhaseUntilUnwind (fun _ -> errorLogger) let references, unresolvedReferences = GetAssemblyResolutionInformation(ctok, tcConfig) - let references = references |> List.map (fun ar -> ar.resolvedPath, ar) + let references = references |> List.map (fun ar -> ar.resolvedPath, ar) references, unresolvedReferences, errorLogger.Diagnostics // Root errors and warnings - look at the last item in the closureFiles list @@ -5275,10 +5275,10 @@ module private ScriptPreprocessClosure = 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)) + References = List.groupBy fst references |> List.map (map2Of2 (List.map snd)) UnresolvedReferences = unresolvedReferences Inputs = sourceInputs - NoWarns = List.groupBy fst globalNoWarns |> List.map (map2Of2 (List.map snd)) + NoWarns = List.groupBy fst globalNoWarns |> List.map (map2Of2 (List.map snd)) OriginalLoadReferences = tcConfig.loadedSources ResolutionDiagnostics = resolutionDiagnostics AllRootFileDiagnostics = allRootDiagnostics @@ -5307,7 +5307,7 @@ module private ScriptPreprocessClosure = tryGetMetadataSnapshot, reduceMemoryUsage) let resolutions0, _unresolvedReferences = GetAssemblyResolutionInformation(ctok, tcConfig) - let references0 = resolutions0 |> List.map (fun r->r.originalReference.Range, r.resolvedPath) |> Seq.distinct |> List.ofSeq + let references0 = resolutions0 |> List.map (fun r->r.originalReference.Range, r.resolvedPath) |> Seq.distinct |> List.ofSeq references0 let tcConfig = @@ -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 = @@ -5412,7 +5412,7 @@ let CheckSimulateException(tcConfig: TcConfig) = // Type-check sets of files //-------------------------------------------------------------------------- -type RootSigs = Zmap +type RootSigs = Zmap type RootImpls = Zset let qnameOrder = Order.orderBy (fun (q: QualifiedNameOfFile) -> q.Text) @@ -5426,7 +5426,7 @@ type TcState = tcsCreatesGeneratedProvidedTypes: bool tcsRootSigs: RootSigs tcsRootImpls: RootImpls - tcsCcuSig: ModuleOrNamespaceType } + tcsCcuSig: ModuleOrNamespaceType } member x.NiceNameGenerator = x.tcsNiceNameGen @@ -5522,9 +5522,9 @@ let TypeCheckOneInputEventually (checkForErrors, tcConfig: TcConfig, tcImports: let! (tcEnv, sigFileType, createsGeneratedProvidedTypes) = TypeCheckOneSigFile (tcGlobals, tcState.tcsNiceNameGen, amap, tcState.tcsCcu, checkForErrors, conditionalDefines, tcSink, tcConfig.internalTestSpanStackReferring) tcState.tcsTcSigEnv file - let rootSigs = Zmap.add qualNameOfFile sigFileType tcState.tcsRootSigs + let rootSigs = Zmap.add qualNameOfFile sigFileType tcState.tcsRootSigs - // Add the signature to the signature env (unless it had an explicit signature) + // Add the signature to the signature env (unless it had an explicit signature) let ccuSigForFile = CombineCcuContentFragments m [sigFileType; tcState.tcsCcuSig] // Open the prefixPath for fsi.exe @@ -5560,7 +5560,7 @@ let TypeCheckOneInputEventually (checkForErrors, tcConfig: TcConfig, tcImports: // Typecheck the implementation file let! topAttrs, implFile, _implFileHiddenType, tcEnvAtEnd, createsGeneratedProvidedTypes = - TypeCheckOneImplFile (tcGlobals, tcState.tcsNiceNameGen, amap, tcState.tcsCcu, checkForErrors, conditionalDefines, tcSink, tcConfig.internalTestSpanStackReferring) tcImplEnv rootSigOpt file + TypeCheckOneImplFile (tcGlobals, tcState.tcsNiceNameGen, amap, tcState.tcsCcu, checkForErrors, conditionalDefines, tcSink, tcConfig.internalTestSpanStackReferring) tcImplEnv rootSigOpt file let hadSig = rootSigOpt.IsSome let implFileSigType = SigTypeOfImplFile implFile @@ -5609,7 +5609,7 @@ let TypeCheckOneInputEventually (checkForErrors, tcConfig: TcConfig, tcImports: } /// Typecheck a single file (or interactive entry into F# Interactive) -let TypeCheckOneInput (ctok, checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt) tcState inp = +let TypeCheckOneInput (ctok, checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt) tcState inp = // 'use' ensures that the warning handler is restored at the end use unwindEL = PushErrorLoggerPhaseUntilUnwind(fun oldLogger -> GetErrorLoggerFilteringByScopedPragmas(false, GetScopedPragmasForInput(inp), oldLogger) ) use unwindBP = PushThreadBuildPhaseUntilUnwind BuildPhase.TypeCheck @@ -5628,7 +5628,7 @@ let TypeCheckMultipleInputsFinish(results, tcState: TcState) = let TypeCheckOneInputAndFinishEventually(checkForErrors, tcConfig: TcConfig, tcImports, tcGlobals, prefixPathOpt, tcSink, tcState, input) = eventually { Logger.LogBlockStart LogCompilerFunctionId.CompileOps_TypeCheckOneInputAndFinishEventually - let! results, tcState = TypeCheckOneInputEventually(checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt, tcSink, tcState, input) + let! results, tcState = TypeCheckOneInputEventually(checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt, tcSink, tcState, input) let result = TypeCheckMultipleInputsFinish([results], tcState) Logger.LogBlockStop LogCompilerFunctionId.CompileOps_TypeCheckOneInputAndFinishEventually return result @@ -5647,7 +5647,7 @@ let TypeCheckClosedInputSetFinish (declaredImpls: TypedImplFile list, tcState) = let TypeCheckClosedInputSet (ctok, checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt, tcState, inputs) = // tcEnvAtEndOfLastFile is the environment required by fsi.exe when incrementally adding definitions - let results, tcState = (tcState, inputs) ||> List.mapFold (TypeCheckOneInput (ctok, checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt)) + let results, tcState = (tcState, inputs) ||> List.mapFold (TypeCheckOneInput (ctok, checkForErrors, tcConfig, tcImports, tcGlobals, prefixPathOpt)) let (tcEnvAtEndOfLastFile, topAttrs, implFiles, _), tcState = TypeCheckMultipleInputsFinish(results, tcState) let tcState, declaredImpls = TypeCheckClosedInputSetFinish (implFiles, tcState) tcState, topAttrs, declaredImpls, tcEnvAtEndOfLastFile diff --git a/src/fsharp/CompileOptions.fs b/src/fsharp/CompileOptions.fs index eb3c6364acf..4aeefae3bfa 100644 --- a/src/fsharp/CompileOptions.fs +++ b/src/fsharp/CompileOptions.fs @@ -751,7 +751,7 @@ let codeGenerationFlags isFsi (tcConfigB: TcConfigBuilder) = let embed = [ CompilerOption ("embed", tagNone, - OptionSwitch (SetEmbedAllSourceSwitch tcConfigB) , None, + OptionSwitch (SetEmbedAllSourceSwitch tcConfigB), None, Some (FSComp.SR.optsEmbedAllSource())) CompilerOption @@ -768,7 +768,7 @@ let codeGenerationFlags isFsi (tcConfigB: TcConfigBuilder) = let codegen = [ CompilerOption ("optimize", tagNone, - OptionSwitch (SetOptimizeSwitch tcConfigB) , None, + OptionSwitch (SetOptimizeSwitch tcConfigB), None, Some (FSComp.SR.optsOptimize())) CompilerOption @@ -1013,12 +1013,12 @@ let internalFlags (tcConfigB:TcConfigBuilder) = Some(InternalCommandLineOption("--ranges", rangeCmdArgs)), None) CompilerOption - ("terms" , tagNone, + ("terms", tagNone, OptionUnit (fun () -> tcConfigB.showTerms <- true), Some(InternalCommandLineOption("--terms", rangeCmdArgs)), None) CompilerOption - ("termsfile" , tagNone, + ("termsfile", tagNone, OptionUnit (fun () -> tcConfigB.writeTermsToFiles <- true), Some(InternalCommandLineOption("--termsfile", rangeCmdArgs)), None) @@ -1174,14 +1174,14 @@ let internalFlags (tcConfigB:TcConfigBuilder) = // "Display timing profiles for compilation" CompilerOption - ("times" , tagNone, + ("times", tagNone, OptionUnit (fun () -> tcConfigB.showTimes <- true), Some(InternalCommandLineOption("times", rangeCmdArgs)), None) #if !NO_EXTENSIONTYPING // "Display information about extension type resolution") CompilerOption - ("showextensionresolution" , tagNone, + ("showextensionresolution", tagNone, OptionUnit (fun () -> tcConfigB.showExtensionTypeMessages <- true), Some(InternalCommandLineOption("showextensionresolution", rangeCmdArgs)), None) #endif @@ -1392,7 +1392,7 @@ let miscFlagsFsi tcConfigB = miscFlagsBoth tcConfigB let abbreviatedFlagsBoth tcConfigB = [ CompilerOption("d", tagString, OptionString (defineSymbol tcConfigB), None, Some(FSComp.SR.optsShortFormOf("--define"))) - CompilerOption("O", tagNone, OptionSwitch (SetOptimizeSwitch tcConfigB) , None, Some(FSComp.SR.optsShortFormOf("--optimize[+|-]"))) + CompilerOption("O", tagNone, OptionSwitch (SetOptimizeSwitch tcConfigB), None, Some(FSComp.SR.optsShortFormOf("--optimize[+|-]"))) CompilerOption("g", tagNone, OptionSwitch (SetDebugSwitch tcConfigB None), None, Some(FSComp.SR.optsShortFormOf("--debug"))) CompilerOption("i", tagString, OptionUnit (fun () -> tcConfigB.printSignature <- true), None, Some(FSComp.SR.optsShortFormOf("--sig"))) referenceFlagAbbrev tcConfigB (* -r *) @@ -1416,12 +1416,12 @@ let abbreviatedFlagsFsc tcConfigB = // FSC help abbreviations. FSI has it's own help options... CompilerOption - ("?" , tagNone, + ("?", tagNone, OptionHelp (fun blocks -> displayHelpFsc tcConfigB blocks), None, Some(FSComp.SR.optsShortFormOf("--help"))) CompilerOption - ("help" , tagNone, + ("help", tagNone, OptionHelp (fun blocks -> displayHelpFsc tcConfigB blocks), None, Some(FSComp.SR.optsShortFormOf("--help"))) @@ -1526,15 +1526,15 @@ let GetCoreServiceCompilerOptions (tcConfigB:TcConfigBuilder) = /// The core/common options used by fsi.exe. [note, some additional options are added in fsi.fs]. let GetCoreFsiCompilerOptions (tcConfigB: TcConfigBuilder) = - [ PublicOptions(FSComp.SR.optsHelpBannerOutputFiles() , outputFileFlagsFsi tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerInputFiles() , inputFileFlagsFsi tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerResources() , resourcesFlagsFsi tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerCodeGen() , codeGenerationFlags true tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerErrsAndWarns() , errorsAndWarningsFlags tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerLanguage() , languageFlags tcConfigB) + [ PublicOptions(FSComp.SR.optsHelpBannerOutputFiles(), outputFileFlagsFsi tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerInputFiles(), inputFileFlagsFsi tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerResources(), resourcesFlagsFsi tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerCodeGen(), codeGenerationFlags true tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerErrsAndWarns(), errorsAndWarningsFlags tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerLanguage(), languageFlags tcConfigB) // Note: no HTML block for fsi.exe - PublicOptions(FSComp.SR.optsHelpBannerMisc() , miscFlagsFsi tcConfigB) - PublicOptions(FSComp.SR.optsHelpBannerAdvanced() , advancedFlagsFsi tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerMisc(), miscFlagsFsi tcConfigB) + PublicOptions(FSComp.SR.optsHelpBannerAdvanced(), advancedFlagsFsi tcConfigB) PrivateOptions(List.concat [ internalFlags tcConfigB abbreviatedFlagsFsi tcConfigB deprecatedFlagsFsi tcConfigB diff --git a/src/fsharp/ConstraintSolver.fs b/src/fsharp/ConstraintSolver.fs index c6f418e9dbe..196edd054cf 100644 --- a/src/fsharp/ConstraintSolver.fs +++ b/src/fsharp/ConstraintSolver.fs @@ -355,8 +355,8 @@ type OptionalTrace = let res = f newTrace match predicate res, t with | false, _ -> newTrace.Undo() - | true , WithTrace t -> t.actions <- newTrace.actions @ t.actions - | true , NoTrace -> () + | true, WithTrace t -> t.actions <- newTrace.actions @ t.actions + | true, NoTrace -> () res let CollectThenUndo f = @@ -833,16 +833,16 @@ and SolveTypeEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTr | (TType_app (tc2, [ms]), _) when (tc2.IsMeasureableReprTycon && typeEquiv csenv.g sty2 (reduceTyconRefMeasureableOrProvided csenv.g tc2 [ms])) -> SolveTypeEqualsType csenv ndeep m2 trace None ms (TType_measure Measure.One) - | TType_app (tc1, l1) , TType_app (tc2, l2) when tyconRefEq g tc1 tc2 -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace None l1 l2 - | TType_app (_, _) , TType_app (_, _) -> localAbortD - | TType_tuple (tupInfo1, l1) , TType_tuple (tupInfo2, l2) -> + | TType_app (tc1, l1), TType_app (tc2, l2) when tyconRefEq g tc1 tc2 -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace None l1 l2 + | TType_app (_, _), TType_app (_, _) -> localAbortD + | TType_tuple (tupInfo1, l1), TType_tuple (tupInfo2, l2) -> if evalTupInfoIsStruct tupInfo1 <> evalTupInfoIsStruct tupInfo2 then ErrorD (ConstraintSolverError(FSComp.SR.tcTupleStructMismatch(), csenv.m, m2)) else SolveTypeEqualsTypeEqns csenv ndeep m2 trace None l1 l2 | TType_anon (anonInfo1, l1),TType_anon (anonInfo2, l2) -> SolveAnonInfoEqualsAnonInfo csenv m2 anonInfo1 anonInfo2 ++ (fun () -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace None l1 l2) - | TType_fun (d1, r1) , TType_fun (d2, r2) -> SolveFunTypeEqn csenv ndeep m2 trace None d1 d2 r1 r2 - | TType_measure ms1 , TType_measure ms2 -> UnifyMeasures csenv trace ms1 ms2 + | TType_fun (d1, r1), TType_fun (d2, r2) -> SolveFunTypeEqn csenv ndeep m2 trace None d1 d2 r1 r2 + | TType_measure ms1, TType_measure ms2 -> UnifyMeasures csenv trace ms1 ms2 | TType_forall(tps1, rty1), TType_forall(tps2, rty2) -> if tps1.Length <> tps2.Length then localAbortD else let aenv = aenv.BindEquivTypars tps1 tps2 @@ -850,7 +850,7 @@ and SolveTypeEqualsType (csenv: ConstraintSolverEnv) ndeep m2 (trace: OptionalTr if not (typarsAEquiv g aenv tps1 tps2) then localAbortD else SolveTypeEqualsTypeKeepAbbrevs csenv ndeep m2 trace rty1 rty2 - | TType_ucase (uc1, l1) , TType_ucase (uc2, l2) when g.unionCaseRefEq uc1 uc2 -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace None l1 l2 + | TType_ucase (uc1, l1), TType_ucase (uc2, l2) when g.unionCaseRefEq uc1 uc2 -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace None l1 l2 | _ -> localAbortD @@ -911,13 +911,13 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional | _, TType_var r when not csenv.MatchingOnly -> SolveTyparSubtypeOfType csenv ndeep m2 trace r ty1 - | TType_tuple (tupInfo1, l1) , TType_tuple (tupInfo2, l2) -> + | TType_tuple (tupInfo1, l1), TType_tuple (tupInfo2, l2) -> if evalTupInfoIsStruct tupInfo1 <> evalTupInfoIsStruct tupInfo2 then ErrorD (ConstraintSolverError(FSComp.SR.tcTupleStructMismatch(), csenv.m, m2)) else SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln l1 l2 (* nb. can unify since no variance *) | TType_anon (anonInfo1, l1), TType_anon (anonInfo2, l2) -> SolveAnonInfoEqualsAnonInfo csenv m2 anonInfo1 anonInfo2 ++ (fun () -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln l1 l2) (* nb. can unify since no variance *) - | TType_fun (d1, r1) , TType_fun (d2, r2) -> SolveFunTypeEqn csenv ndeep m2 trace cxsln d1 d2 r1 r2 (* nb. can unify since no variance *) + | TType_fun (d1, r1), TType_fun (d2, r2) -> SolveFunTypeEqn csenv ndeep m2 trace cxsln d1 d2 r1 r2 (* nb. can unify since no variance *) | TType_measure ms1, TType_measure ms2 -> UnifyMeasures csenv trace ms1 ms2 // Enforce the identities float=float<1>, float32=float32<1> and decimal=decimal<1> @@ -927,7 +927,7 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional -> SolveTypeEqualsTypeKeepAbbrevsWithCxsln csenv ndeep m2 trace cxsln ms (TType_measure Measure.One) // Special subsumption rule for byref tags - | TType_app (tc1, l1) , TType_app (tc2, l2) when tyconRefEq g tc1 tc2 && g.byref2_tcr.CanDeref && tyconRefEq g g.byref2_tcr tc1 -> + | TType_app (tc1, l1), TType_app (tc2, l2) when tyconRefEq g tc1 tc2 && g.byref2_tcr.CanDeref && tyconRefEq g g.byref2_tcr tc1 -> match l1, l2 with | [ h1; tag1 ], [ h2; tag2 ] -> trackErrors { do! SolveTypeEqualsType csenv ndeep m2 trace None h1 h2 @@ -939,10 +939,10 @@ and SolveTypeSubsumesType (csenv: ConstraintSolverEnv) ndeep m2 (trace: Optional } | _ -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln l1 l2 - | 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 -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln l1 l2 - | TType_ucase (uc1, l1) , TType_ucase (uc2, l2) when g.unionCaseRefEq uc1 uc2 -> + | TType_ucase (uc1, l1), TType_ucase (uc2, l2) when g.unionCaseRefEq uc1 uc2 -> SolveTypeEqualsTypeEqns csenv ndeep m2 trace cxsln l1 l2 | _ -> @@ -1680,7 +1680,7 @@ and AddConstraint (csenv: ConstraintSolverEnv) ndeep m2 trace tp newConstraint } | TyparConstraint.SupportsComparison _, TyparConstraint.IsDelegate _ - | TyparConstraint.IsDelegate _ , TyparConstraint.SupportsComparison _ + | TyparConstraint.IsDelegate _, TyparConstraint.SupportsComparison _ | TyparConstraint.IsNonNullableStruct _, TyparConstraint.IsReferenceType _ | TyparConstraint.IsReferenceType _, TyparConstraint.IsNonNullableStruct _ -> ErrorD (Error(FSComp.SR.csStructConstraintInconsistent(), m)) diff --git a/src/fsharp/DetupleArgs.fs b/src/fsharp/DetupleArgs.fs index 67f5f43d617..7272e33983f 100644 --- a/src/fsharp/DetupleArgs.fs +++ b/src/fsharp/DetupleArgs.fs @@ -113,9 +113,9 @@ open FSharp.Compiler.Lib // [[FORMAL: SameArg xi]] -> xi // [[FORMAL: NewArgs vs]] -> [ [v1] ... [vN] ] // list up individual args for Expr.Lambda // -// [[REBIND: xi , SameArg xi]] -> // no binding needed +// [[REBIND: xi, SameArg xi]] -> // no binding needed // [[REBIND: [u], NewArgs vs]] -> u = "rebuildTuple(cpi, vs)" -// [[REBIND: us , NewArgs vs]] -> "rebuildTuple(cpi, vs)" then bind us to buildProjections. // for Expr.Lambda +// [[REBIND: us, NewArgs vs]] -> "rebuildTuple(cpi, vs)" then bind us to buildProjections. // for Expr.Lambda // // rebuildTuple - create tuple based on vs fringe according to cpi tuple structure. // @@ -346,7 +346,7 @@ let rec ValReprInfoForTS ts = let rec andTS ts tsB = match ts, tsB with - | _ , UnknownTS -> UnknownTS + | _, UnknownTS -> UnknownTS | UnknownTS, _ -> UnknownTS | TupleTS ss, TupleTS ssB -> if ss.Length <> ssB.Length then UnknownTS (* different tuple instances *) @@ -378,9 +378,9 @@ let typeTS g tys = tys |> uncheckedTypeTS g |> checkTS let rebuildTS g m ts vs = let rec rebuild vs ts = match vs, ts with - | [] , UnknownTS -> internalError "rebuildTS: not enough fringe to build tuple" + | [], UnknownTS -> internalError "rebuildTS: not enough fringe to build tuple" | v::vs, UnknownTS -> (exprForVal m v, v.Type), vs - | vs , TupleTS tss -> + | vs, TupleTS tss -> let xtys, vs = List.mapFold rebuild vs tss let xs, tys = List.unzip xtys let x = mkRefTupled g m xs tys @@ -415,10 +415,10 @@ let rec minimalCallPattern callPattern = let commonCallPattern callPatterns = let rec andCPs cpA cpB = match cpA, cpB with - | [] , [] -> [] + | [], [] -> [] | tsA::tsAs, tsB::tsBs -> andTS tsA tsB :: andCPs tsAs tsBs | _tsA::_tsAs, [] -> [] (* now trim to shortest - UnknownTS :: andCPs tsAs [] *) - | [] , _tsB::_tsBs -> [] (* now trim to shortest - UnknownTS :: andCPs [] tsBs *) + | [], _tsB::_tsBs -> [] (* now trim to shortest - UnknownTS :: andCPs [] tsBs *) List.reduce andCPs callPatterns @@ -530,7 +530,7 @@ let decideFormalSuggestedCP g z tys vss = let rec trimTsByAccess accessors ts = match ts, accessors with - | UnknownTS , _ -> UnknownTS + | UnknownTS, _ -> UnknownTS | TupleTS _tss, [] -> UnknownTS (* trim it, require the val at this point *) | TupleTS tss, TupleGet (i, _ty)::accessors -> let tss = List.mapNth i (trimTsByAccess accessors) tss @@ -683,7 +683,7 @@ let rec collapseArg env bindings ts (x: Expr) = let m = x.Range let env = rangeE env m match ts, x with - | UnknownTS , x -> + | UnknownTS, x -> let bindings, vx = noEffectExpr env bindings x bindings, [vx] | TupleTS tss, Expr.Op(TOp.Tuple tupInfo, _xtys, xs, _) when not (evalTupInfoIsStruct tupInfo) -> @@ -700,7 +700,7 @@ let rec collapseArg env bindings ts (x: Expr) = and collapseArgs env bindings n (callPattern) args = match callPattern, args with - | [] , args -> bindings, args + | [], args -> bindings, args | ts::tss, arg::args -> let env1 = suffixE env (string n) let bindings, xty = collapseArg env1 bindings ts arg @@ -754,9 +754,9 @@ let transFormal ybi xi = let transRebind ybi xi = match xi, ybi with - | _ , SameArg -> [] (* no rebinding, reused original formal *) + | _, SameArg -> [] (* no rebinding, reused original formal *) | [u], NewArgs (_vs, x) -> [mkCompGenBind u x] - | us , NewArgs (_vs, x) -> List.map2 mkCompGenBind us (tryDestRefTupleExpr x) + | us, NewArgs (_vs, x) -> List.map2 mkCompGenBind us (tryDestRefTupleExpr x) //------------------------------------------------------------------------- diff --git a/src/fsharp/ExtensionTyping.fs b/src/fsharp/ExtensionTyping.fs index 16e83147d1b..9bf54e3be79 100755 --- a/src/fsharp/ExtensionTyping.fs +++ b/src/fsharp/ExtensionTyping.fs @@ -1111,7 +1111,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) = if staticArgs.Length = 0 then - Some (typeBeforeArguments , (fun () -> ())) + Some (typeBeforeArguments, (fun () -> ())) else let fullTypePathAfterArguments = diff --git a/src/fsharp/FSharp.Build/Fsc.fs b/src/fsharp/FSharp.Build/Fsc.fs index d56dab90f0f..d1f0ea78d94 100644 --- a/src/fsharp/FSharp.Build/Fsc.fs +++ b/src/fsharp/FSharp.Build/Fsc.fs @@ -140,8 +140,8 @@ type public Fsc () as this = | "ANYCPU", true, "EXE" | "ANYCPU", true, "WINEXE" -> "anycpu32bitpreferred" | "ANYCPU", _, _ -> "anycpu" - | "X86" , _, _ -> "x86" - | "X64" , _, _ -> "x64" + | "X86", _, _ -> "x86" + | "X64", _, _ -> "x64" | _ -> null) // Resources if resources <> null then diff --git a/src/fsharp/FSharp.Core/Query.fs b/src/fsharp/FSharp.Core/Query.fs index fbab2547ed3..0f889072c7c 100644 --- a/src/fsharp/FSharp.Core/Query.fs +++ b/src/fsharp/FSharp.Core/Query.fs @@ -1341,7 +1341,7 @@ module Query = let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeTakeWhile (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallGroupBy(_, [_; qTy; _] , immutSource, Lambda(immutVar, immutKeySelector)) -> + | CallGroupBy(_, [_; qTy; _], immutSource, Lambda(immutVar, immutKeySelector)) -> let mutSource, sourceConv = TransInnerAndCommit CanEliminate.Yes check immutSource let mutVar, mutKeySelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar, MacroExpand immutKeySelector) let conv = match sourceConv with NoConv -> NoConv | _ -> GroupingConv(immutKeySelector.Type,immutVar.Type,sourceConv) diff --git a/src/fsharp/FSharp.Core/array.fs b/src/fsharp/FSharp.Core/array.fs index 5531a690038..13c3353ca06 100644 --- a/src/fsharp/FSharp.Core/array.fs +++ b/src/fsharp/FSharp.Core/array.fs @@ -723,7 +723,7 @@ namespace Microsoft.FSharp.Collections res2.[i] <- res.[downCount] downCount <- downCount - 1 - res1 , res2 + res1, res2 [] let find predicate (array: _[]) = diff --git a/src/fsharp/FSharp.Core/array2.fs b/src/fsharp/FSharp.Core/array2.fs index 3ef0c9ff437..d24ccf795ac 100644 --- a/src/fsharp/FSharp.Core/array2.fs +++ b/src/fsharp/FSharp.Core/array2.fs @@ -139,9 +139,9 @@ namespace Microsoft.FSharp.Collections checkNonNull "source" source checkNonNull "target" target - let sourceX0, sourceY0 = source.GetLowerBound 0 , source.GetLowerBound 1 + let sourceX0, sourceY0 = source.GetLowerBound 0, source.GetLowerBound 1 let sourceXN, sourceYN = (length1 source) + sourceX0, (length2 source) + sourceY0 - let targetX0, targetY0 = target.GetLowerBound 0 , target.GetLowerBound 1 + let targetX0, targetY0 = target.GetLowerBound 0, target.GetLowerBound 1 let targetXN, targetYN = (length1 target) + targetX0, (length2 target) + targetY0 if sourceIndex1 < sourceX0 then invalidArgOutOfRange "sourceIndex1" sourceIndex1 "source axis-0 lower bound" sourceX0 diff --git a/src/fsharp/FSharp.Core/map.fs b/src/fsharp/FSharp.Core/map.fs index 7ef250a0ee9..9b2fbc9d832 100644 --- a/src/fsharp/FSharp.Core/map.fs +++ b/src/fsharp/FSharp.Core/map.fs @@ -478,8 +478,10 @@ namespace Microsoft.FSharp.Collections [] member internal m.Comparer = comparer + //[] member internal m.Tree = tree + member m.Add(key,value) : Map<'Key,'Value> = #if TRACE_SETS_AND_MAPS MapTree.report() @@ -494,6 +496,7 @@ namespace Microsoft.FSharp.Collections [] member m.IsEmpty = MapTree.isEmpty tree + member m.Item with get(key : 'Key) = #if TRACE_SETS_AND_MAPS @@ -502,19 +505,24 @@ namespace Microsoft.FSharp.Collections MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree) #endif MapTree.find comparer key tree + member m.TryPick(f) = MapTree.tryPick f tree + member m.Exists(f) = MapTree.exists f tree - member m.Filter(f) : Map<'Key,'Value> = new Map<'Key,'Value>(comparer ,MapTree.filter comparer f tree) + + member m.Filter(f) : Map<'Key,'Value> = new Map<'Key,'Value>(comparer,MapTree.filter comparer f tree) + member m.ForAll(f) = MapTree.forall f tree + member m.Fold f acc = MapTree.foldBack f tree acc member m.FoldSection (lo:'Key) (hi:'Key) f (acc:'z) = MapTree.foldSection comparer lo hi f tree acc member m.Iterate f = MapTree.iter f tree - member m.MapRange f = new Map<'Key,'b>(comparer,MapTree.map f tree) + member m.MapRange f = new Map<'Key,'b>(comparer,MapTree.map f tree) - member m.Map f = new Map<'Key,'b>(comparer,MapTree.mapi f tree) + member m.Map f = new Map<'Key,'b>(comparer,MapTree.mapi f tree) member m.Partition(f) : Map<'Key,'Value> * Map<'Key,'Value> = let r1,r2 = MapTree.partition comparer f tree in @@ -530,7 +538,7 @@ namespace Microsoft.FSharp.Collections #endif MapTree.mem comparer key tree - member m.Remove(key) : Map<'Key,'Value> = + member m.Remove(key) : Map<'Key,'Value> = new Map<'Key,'Value>(comparer,MapTree.remove comparer key tree) member m.TryGetValue(key, [] value:byref<'Value>) = diff --git a/src/fsharp/FSharp.Core/prim-types.fs b/src/fsharp/FSharp.Core/prim-types.fs index 7929ef77581..7bdf69c2924 100644 --- a/src/fsharp/FSharp.Core/prim-types.fs +++ b/src/fsharp/FSharp.Core/prim-types.fs @@ -822,25 +822,33 @@ namespace Microsoft.FSharp.Core /// Implements generic comparison between two objects. This corresponds to the pseudo-code in the F# /// specification. The treatment of NaNs is governed by "comp". let rec GenericCompare (comp:GenericComparer) (xobj:obj,yobj:obj) = - (*if objEq xobj yobj then 0 else *) match xobj,yobj with | null,null -> 0 | null,_ -> -1 | _,null -> 1 + // Use Ordinal comparison for strings - | (:? string as x),(:? string as y) -> System.String.CompareOrdinal(x, y) + | (:? string as x),(:? string as y) -> + System.String.CompareOrdinal(x, y) + // Permit structural comparison on arrays | (:? System.Array as arr1),_ -> match arr1,yobj with // Fast path - | (:? (obj[]) as arr1), (:? (obj[]) as arr2) -> GenericComparisonObjArrayWithComparer comp arr1 arr2 + | (:? (obj[]) as arr1), (:? (obj[]) as arr2) -> + GenericComparisonObjArrayWithComparer comp arr1 arr2 // Fast path - | (:? (byte[]) as arr1), (:? (byte[]) as arr2) -> GenericComparisonByteArray arr1 arr2 - | _ , (:? System.Array as arr2) -> GenericComparisonArbArrayWithComparer comp arr1 arr2 - | _ -> FailGenericComparison xobj + | (:? (byte[]) as arr1), (:? (byte[]) as arr2) -> + GenericComparisonByteArray arr1 arr2 + | _, (:? System.Array as arr2) -> + GenericComparisonArbArrayWithComparer comp arr1 arr2 + | _ -> + FailGenericComparison xobj + // Check for IStructuralComparable | (:? IStructuralComparable as x),_ -> x.CompareTo(yobj,comp) + // Check for IComparable | (:? System.IComparable as x),_ -> if comp.ThrowsOnPER then @@ -853,15 +861,22 @@ namespace Microsoft.FSharp.Core raise NaNException | _ -> () x.CompareTo(yobj) - | (:? nativeint as x),(:? nativeint as y) -> if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) - | (:? unativeint as x),(:? unativeint as y) -> if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) + + | (:? nativeint as x),(:? nativeint as y) -> + if (# "clt" x y : bool #) then (-1) else (# "cgt" x y : int #) + + | (:? unativeint as x),(:? unativeint as y) -> + if (# "clt.un" x y : bool #) then (-1) else (# "cgt.un" x y : int #) + | _,(:? IStructuralComparable as yc) -> let res = yc.CompareTo(xobj,comp) if res < 0 then 1 elif res > 0 then -1 else 0 + | _,(:? System.IComparable as yc) -> // Note -c doesn't work here: be careful of comparison function returning minint - let c = yc.CompareTo(xobj) in + let c = yc.CompareTo(xobj) if c < 0 then 1 elif c > 0 then -1 else 0 + | _ -> FailGenericComparison xobj /// specialcase: Core implementation of structural comparison on arbitrary arrays. @@ -1090,7 +1105,7 @@ namespace Microsoft.FSharp.Core when 'T : string = // NOTE: we don't have to null check here because System.String.CompareOrdinal // gives reliable results on null values. - System.String.CompareOrdinal((# "" x : string #) ,(# "" y : string #)) + System.String.CompareOrdinal((# "" x : string #),(# "" y : string #)) when 'T : decimal = System.Decimal.Compare((# "" x:decimal #), (# "" y:decimal #)) @@ -1168,7 +1183,7 @@ namespace Microsoft.FSharp.Core when 'T : string = // NOTE: we don't have to null check here because System.String.CompareOrdinal // gives reliable results on null values. - System.String.CompareOrdinal((# "" x : string #) ,(# "" y : string #)) + System.String.CompareOrdinal((# "" x : string #),(# "" y : string #)) when 'T : decimal = System.Decimal.Compare((# "" x:decimal #), (# "" y:decimal #)) /// Generic less-than with static optimizations for some well-known cases. @@ -1374,7 +1389,7 @@ namespace Microsoft.FSharp.Core | (:? (char[]) as arr1), (:? (char[]) as arr2) -> GenericEqualityCharArray arr1 arr2 | (:? (float32[]) as arr1), (:? (float32[]) as arr2) -> GenericEqualitySingleArray er arr1 arr2 | (:? (float[]) as arr1), (:? (float[]) as arr2) -> GenericEqualityDoubleArray er arr1 arr2 - | _ , (:? System.Array as arr2) -> GenericEqualityArbArray er iec arr1 arr2 + | _, (:? System.Array as arr2) -> GenericEqualityArbArray er iec arr1 arr2 | _ -> xobj.Equals(yobj) | (:? IStructuralEquatable as x1),_ -> x1.Equals(yobj,iec) // Ensure ER NaN semantics on recursive calls @@ -4066,7 +4081,7 @@ namespace Microsoft.FSharp.Core when ^T : float32= (# "clt" x y : bool #) when ^T : char = (# "clt" x y : bool #) when ^T : decimal = System.Decimal.op_LessThan ((# "" x:decimal #), (# "" y:decimal #)) - when ^T : string = (# "clt" (System.String.CompareOrdinal((# "" x : string #) ,(# "" y : string #))) 0 : bool #) + when ^T : string = (# "clt" (System.String.CompareOrdinal((# "" x : string #),(# "" y : string #))) 0 : bool #) /// Static greater-than with static optimizations for some well-known cases. let inline (>) (x:^T) (y:^U) = @@ -4086,7 +4101,7 @@ namespace Microsoft.FSharp.Core when 'T : float32 = (# "cgt" x y : bool #) when 'T : char = (# "cgt" x y : bool #) when 'T : decimal = System.Decimal.op_GreaterThan ((# "" x:decimal #), (# "" y:decimal #)) - when ^T : string = (# "cgt" (System.String.CompareOrdinal((# "" x : string #) ,(# "" y : string #))) 0 : bool #) + when ^T : string = (# "cgt" (System.String.CompareOrdinal((# "" x : string #),(# "" y : string #))) 0 : bool #) /// Static less-than-or-equal with static optimizations for some well-known cases. let inline (<=) (x:^T) (y:^U) = @@ -4106,7 +4121,7 @@ namespace Microsoft.FSharp.Core when 'T : float32 = not (# "cgt.un" x y : bool #) when 'T : char = not (# "cgt" x y : bool #) when 'T : decimal = System.Decimal.op_LessThanOrEqual ((# "" x:decimal #), (# "" y:decimal #)) - when ^T : string = not (# "cgt" (System.String.CompareOrdinal((# "" x : string #) ,(# "" y : string #))) 0 : bool #) + when ^T : string = not (# "cgt" (System.String.CompareOrdinal((# "" x : string #),(# "" y : string #))) 0 : bool #) /// Static greater-than-or-equal with static optimizations for some well-known cases. let inline (>=) (x:^T) (y:^U) = @@ -4126,7 +4141,7 @@ namespace Microsoft.FSharp.Core when 'T : float32 = not (# "clt.un" x y : bool #) when 'T : char = not (# "clt" x y : bool #) when 'T : decimal = System.Decimal.op_GreaterThanOrEqual ((# "" x:decimal #), (# "" y:decimal #)) - when ^T : string = not (# "clt" (System.String.CompareOrdinal((# "" x : string #) ,(# "" y : string #))) 0 : bool #) + when ^T : string = not (# "clt" (System.String.CompareOrdinal((# "" x : string #),(# "" y : string #))) 0 : bool #) /// Static greater-than-or-equal with static optimizations for some well-known cases. @@ -4198,7 +4213,7 @@ namespace Microsoft.FSharp.Core when ^T : string = // NOTE: we don't have to null check here because System.String.CompareOrdinal // gives reliable results on null values. - System.String.CompareOrdinal((# "" e1 : string #) ,(# "" e2 : string #)) + System.String.CompareOrdinal((# "" e1 : string #),(# "" e2 : string #)) when ^T : decimal = System.Decimal.Compare((# "" e1:decimal #), (# "" e2:decimal #)) [] @@ -5018,7 +5033,7 @@ namespace Microsoft.FSharp.Core let inline ComputeSlice bound start finish length = match start, finish with | None, None -> bound, bound + length - 1 - | None, Some n when n >= bound -> bound , n + | None, Some n when n >= bound -> bound, n | Some m, None when m <= bound + length -> m, bound + length - 1 | Some m, Some n -> m, n | _ -> raise (System.IndexOutOfRangeException()) diff --git a/src/fsharp/FSharp.Core/prim-types.fsi b/src/fsharp/FSharp.Core/prim-types.fsi index a62b9d18783..c977af45417 100644 --- a/src/fsharp/FSharp.Core/prim-types.fsi +++ b/src/fsharp/FSharp.Core/prim-types.fsi @@ -732,7 +732,7 @@ namespace Microsoft.FSharp.Core /// /// When applied to a module within an assembly, then the attribute must not be given any arguments. /// When the enclosing namespace is opened in user source code, the module is also implicitly opened. - [] + [] [] type AutoOpenAttribute = inherit Attribute diff --git a/src/fsharp/FSharp.Core/printf.fs b/src/fsharp/FSharp.Core/printf.fs index 535d87d491b..0c2d6b70316 100644 --- a/src/fsharp/FSharp.Core/printf.fs +++ b/src/fsharp/FSharp.Core/printf.fs @@ -195,7 +195,7 @@ module internal PrintfImpl = Utils.Write(env, g, h) static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i) = Utils.Write(env, a, b, c, d, e, f, g) - Utils.Write(env, h ,i) + Utils.Write(env, h, i) static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j) = Utils.Write(env, a, b, c, d, e, f, g, h) Utils.Write(env, i, j) @@ -1283,7 +1283,7 @@ module internal PrintfImpl = let args = [| box prefix; tail |] mi.Invoke(null, args) else - System.Diagnostics.Debug.Assert(spec.IsStarPrecision || spec.IsStarWidth , "spec.IsStarPrecision || spec.IsStarWidth ") + System.Diagnostics.Debug.Assert(spec.IsStarPrecision || spec.IsStarWidth, "spec.IsStarPrecision || spec.IsStarWidth ") let mi = let n = if spec.IsStarWidth = spec.IsStarPrecision then 2 else 1 @@ -1321,7 +1321,7 @@ module internal PrintfImpl = let args = [| box prefix; box suffix |] mi.Invoke(null, args) else - System.Diagnostics.Debug.Assert(spec.IsStarPrecision || spec.IsStarWidth , "spec.IsStarPrecision || spec.IsStarWidth ") + System.Diagnostics.Debug.Assert(spec.IsStarPrecision || spec.IsStarWidth, "spec.IsStarPrecision || spec.IsStarWidth ") let mi = let n = if spec.IsStarWidth = spec.IsStarPrecision then 2 else 1 diff --git a/src/fsharp/FSharp.Core/quotations.fs b/src/fsharp/FSharp.Core/quotations.fs index 6198357fa08..7af4a9f7956 100644 --- a/src/fsharp/FSharp.Core/quotations.fs +++ b/src/fsharp/FSharp.Core/quotations.fs @@ -622,8 +622,8 @@ module Patterns = | InstancePropGetOp prop,_ -> prop.PropertyType | StaticPropSetOp _,_ -> typeof | InstancePropSetOp _,_ -> typeof - | InstanceFieldGetOp fld ,_ -> fld.FieldType - | StaticFieldGetOp fld ,_ -> fld.FieldType + | InstanceFieldGetOp fld,_ -> fld.FieldType + | StaticFieldGetOp fld,_ -> fld.FieldType | InstanceFieldSetOp _,_ -> typeof | StaticFieldSetOp _,_ -> typeof | NewObjectOp ctor,_ -> ctor.DeclaringType @@ -1429,7 +1429,7 @@ module Patterns = (fun env -> let v = a env in E(LambdaTerm(v,b (addVar env v)))) | 3 -> let a = u_dtype st let idx = u_int st - (fun env -> E(HoleTerm(a env.typeInst , idx))) + (fun env -> E(HoleTerm(a env.typeInst, idx))) | 4 -> let a = u_Expr st (fun env -> mkQuote(a env, true)) | 5 -> let a = u_Expr st diff --git a/src/fsharp/FSharp.Core/reflect.fs b/src/fsharp/FSharp.Core/reflect.fs index ea8f1bfdf70..f0d9c2854c2 100644 --- a/src/fsharp/FSharp.Core/reflect.fs +++ b/src/fsharp/FSharp.Core/reflect.fs @@ -265,7 +265,7 @@ module internal Impl = if isOptionType typ then match tag with | 0 (* None *) -> getInstancePropertyInfos (typ,[| |],bindingFlags) - | 1 (* Some *) -> getInstancePropertyInfos (typ,[| "Value" |] ,bindingFlags) + | 1 (* Some *) -> getInstancePropertyInfos (typ,[| "Value" |],bindingFlags) | _ -> failwith "fieldsPropsOfUnionCase" elif isListType typ then match tag with @@ -737,12 +737,12 @@ type FSharpType = static member IsUnion(typ:Type,?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public Impl.checkNonNull "typ" typ - let typ = Impl.getTypeOfReprType (typ ,BindingFlags.Public ||| BindingFlags.NonPublic) + let typ = Impl.getTypeOfReprType (typ,BindingFlags.Public ||| BindingFlags.NonPublic) Impl.isUnionType (typ,bindingFlags) static member IsFunction(typ:Type) = Impl.checkNonNull "typ" typ - let typ = Impl.getTypeOfReprType (typ ,BindingFlags.Public ||| BindingFlags.NonPublic) + let typ = Impl.getTypeOfReprType (typ,BindingFlags.Public ||| BindingFlags.NonPublic) Impl.isFunctionType typ static member IsModule(typ:Type) = @@ -781,7 +781,7 @@ type FSharpType = static member GetFunctionElements(functionType:Type) = Impl.checkNonNull "functionType" functionType - let functionType = Impl.getTypeOfReprType (functionType ,BindingFlags.Public ||| BindingFlags.NonPublic) + let functionType = Impl.getTypeOfReprType (functionType,BindingFlags.Public ||| BindingFlags.NonPublic) Impl.getFunctionTypeInfo functionType static member GetRecordFields(recordType:Type,?bindingFlags) = @@ -792,7 +792,7 @@ type FSharpType = static member GetUnionCases (unionType:Type,?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public Impl.checkNonNull "unionType" unionType - let unionType = Impl.getTypeOfReprType (unionType ,bindingFlags) + let unionType = Impl.getTypeOfReprType (unionType,bindingFlags) Impl.checkUnionType(unionType,bindingFlags); Impl.getUnionTypeTagNameMap(unionType,bindingFlags) |> Array.mapi (fun i _ -> UnionCaseInfo(unionType,i)) @@ -927,7 +927,7 @@ type FSharpValue = let unionType = ensureType(unionType,value) Impl.checkNonNull "unionType" unionType - let unionType = Impl.getTypeOfReprType (unionType ,bindingFlags) + let unionType = Impl.getTypeOfReprType (unionType,bindingFlags) Impl.checkUnionType(unionType,bindingFlags) let tag = Impl.getUnionTagReader (unionType,bindingFlags) value @@ -937,16 +937,16 @@ type FSharpValue = static member PreComputeUnionTagReader(unionType: Type,?bindingFlags) : (obj -> int) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public Impl.checkNonNull "unionType" unionType - let unionType = Impl.getTypeOfReprType (unionType ,bindingFlags) + let unionType = Impl.getTypeOfReprType (unionType,bindingFlags) Impl.checkUnionType(unionType,bindingFlags) - Impl.getUnionTagReader (unionType ,bindingFlags) + Impl.getUnionTagReader (unionType,bindingFlags) static member PreComputeUnionTagMemberInfo(unionType: Type,?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public Impl.checkNonNull "unionType" unionType; - let unionType = Impl.getTypeOfReprType (unionType ,bindingFlags) + let unionType = Impl.getTypeOfReprType (unionType,bindingFlags) Impl.checkUnionType(unionType,bindingFlags) - Impl.getUnionTagMemberInfo(unionType ,bindingFlags) + Impl.getUnionTagMemberInfo(unionType,bindingFlags) static member PreComputeUnionReader(unionCase: UnionCaseInfo,?bindingFlags) : (obj -> obj[]) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public diff --git a/src/fsharp/FSharp.Core/set.fs b/src/fsharp/FSharp.Core/set.fs index 85c04a2c241..394bc4963de 100644 --- a/src/fsharp/FSharp.Core/set.fs +++ b/src/fsharp/FSharp.Core/set.fs @@ -173,7 +173,7 @@ namespace Microsoft.FSharp.Collections let rec split (comparer: IComparer<'T>) pivot t = // Given a pivot and a set t - // Return { x in t s.t. x < pivot }, pivot in t? , { x in t s.t. x > pivot } + // Return { x in t s.t. x < pivot }, pivot in t?, { x in t s.t. x > pivot } match t with | SetNode(k1,t11,t12,_) -> let c = comparer.Compare(pivot,k1) @@ -187,8 +187,8 @@ namespace Microsoft.FSharp.Collections balance comparer t11 k1 t12Lo,havePivot,t12Hi | SetOne k1 -> let c = comparer.Compare(k1,pivot) - if c < 0 then t ,false,SetEmpty // singleton under pivot - elif c = 0 then SetEmpty,true ,SetEmpty // singleton is pivot + if c < 0 then t,false,SetEmpty // singleton under pivot + elif c = 0 then SetEmpty,true,SetEmpty // singleton is pivot else SetEmpty,false,t // singleton over pivot | SetEmpty -> SetEmpty,false,SetEmpty @@ -446,7 +446,7 @@ namespace Microsoft.FSharp.Collections match l1,l2 with | [],[] -> 0 | [],_ -> -1 - | _ ,[] -> 1 + | _,[] -> 1 | (SetEmpty _ :: t1),(SetEmpty :: t2) -> compareStacks comparer t1 t2 | (SetOne(n1k) :: t1),(SetOne(n2k) :: t2) -> let c = comparer.Compare(n1k,n2k) diff --git a/src/fsharp/IlxGen.fs b/src/fsharp/IlxGen.fs index 011fd9e5932..b361a297500 100644 --- a/src/fsharp/IlxGen.fs +++ b/src/fsharp/IlxGen.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. //-------------------------------------------------------------------------- // The ILX generator. @@ -84,7 +84,7 @@ let ChooseParamNames fieldNamesAndTypes = /// Approximation for purposes of optimization and giving a warning when compiling definition-only files as EXEs let rec CheckCodeDoesSomething (code: ILCode) = - code.Instrs |> Array.exists (function AI_ldnull | AI_nop | AI_pop | I_ret | I_seqpoint _ -> false | _ -> true) + code.Instrs |> Array.exists (function AI_ldnull | AI_nop | AI_pop | I_ret | I_seqpoint _ -> false | _ -> true) /// Choose the field names for variables captured by closures let ChooseFreeVarNames takenNames ts = @@ -92,22 +92,22 @@ let ChooseFreeVarNames takenNames ts = let rec chooseName names (t, nOpt) = let tn = match nOpt with None -> t | Some n -> t + string n if Zset.contains tn names then - chooseName names (t, Some(match nOpt with None -> 0 | Some n -> (n+1))) + chooseName names (t, Some(match nOpt with None -> 0 | Some n -> (n+1))) else let names = Zset.add tn names tn, names - let names = Zset.empty String.order |> Zset.addList takenNames + let names = Zset.empty String.order |> Zset.addList takenNames let ts, _names = List.mapFold chooseName names tns ts /// +++GLOBAL STATE: a name generator used by IlxGen for static fields, some generated arguments and other things. -/// REVIEW: this will mean the hosted compiler service is not deterministic. We should at least create a new one +/// REVIEW: this will mean the hosted compiler service is not deterministic. We should at least create a new one /// of these for each compilation. let ilxgenGlobalNng = NiceNameGenerator () /// We can't tailcall to methods taking byrefs. This helper helps search for them -let IsILTypeByref = function ILType.Byref _ -> true | _ -> false +let IsILTypeByref = function ILType.Byref _ -> true | _ -> false let mainMethName = CompilerGeneratedName "main" @@ -118,15 +118,15 @@ type AttributeDecoder (namedArgs) = let findConst x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_, Expr.Const(c, _, _))) -> Some c | _ -> None let findAppTr x = match NameMap.tryFind x nameMap with | Some(AttribExpr(_, Expr.App(_, _, [TType_app(tr, _)], _, _))) -> Some tr | _ -> None - member __.FindInt16 x dflt = match findConst x with | Some(Const.Int16 x) -> x | _ -> dflt + member __.FindInt16 x dflt = match findConst x with | Some(Const.Int16 x) -> x | _ -> dflt - member __.FindInt32 x dflt = match findConst x with | Some(Const.Int32 x) -> x | _ -> dflt + member __.FindInt32 x dflt = match findConst x with | Some(Const.Int32 x) -> x | _ -> dflt - member __.FindBool x dflt = match findConst x with | Some(Const.Bool x) -> x | _ -> dflt + member __.FindBool x dflt = match findConst x with | Some(Const.Bool x) -> x | _ -> dflt member __.FindString x dflt = match findConst x with | Some(Const.String x) -> x | _ -> dflt - member __.FindTypeName x dflt = match findAppTr x with | Some(tr) -> tr.DisplayName | _ -> dflt + member __.FindTypeName x dflt = match findAppTr x with | Some(tr) -> tr.DisplayName | _ -> dflt //-------------------------------------------------------------------------- // Statistics @@ -229,7 +229,7 @@ type cenv = /// The ImportMap for reading IL amap: ImportMap - /// A callback for TcVal in the typechecker. Used to generalize values when finding witnesses. + /// 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 @@ -254,7 +254,7 @@ type cenv = let mkTypeOfExpr cenv m ilty = - mkAsmExpr ([ mkNormalCall (mspec_Type_GetTypeFromHandle cenv.g) ], [], + mkAsmExpr ([ mkNormalCall (mspec_Type_GetTypeFromHandle cenv.g) ], [], [mkAsmExpr ([ I_ldtoken (ILToken.ILType ilty) ], [], [], [cenv.g.system_RuntimeTypeHandle_ty], m)], [cenv.g.system_Type_ty], m) @@ -294,7 +294,7 @@ let CompLocForFragment fragName (ccu: CcuThunk) = 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 n = submod.CompiledName @@ -306,7 +306,7 @@ let CompLocForFixedPath fragName qname (CompPath(sref, cpath)) = let ns, t = List.takeUntil (fun (_, mkind) -> mkind <> Namespace) cpath let ns = List.map fst ns let ns = textOfPath ns - let encl = t |> List.map (fun (s , _)-> s) + let encl = t |> List.map (fun (s, _)-> s) let ns = if ns = "" then None else Some ns { QualifiedNameOfFile = fragName TopImplQualifiedName = qname @@ -352,7 +352,7 @@ let CompLocForPrivateImplementationDetails cloc = Enclosing=[TypeNameForPrivateImplementationDetails cloc]; Namespace=None} /// Compute an ILTypeRef for a CompilationLocation -let rec TypeRefForCompLoc cloc = +let rec TypeRefForCompLoc cloc = match cloc.Enclosing with | [] -> mkILTyRef(cloc.Scope, TypeNameForPrivateImplementationDetails cloc) @@ -392,7 +392,7 @@ type TypeReprEnv(reprs: Map, count: int) = // Random value for post-hoc diagnostic analysis on generated tree * uint16 666 - /// Add an additional type parameter to the environment. If the parameter is a units-of-measure parameter + /// Add an additional type parameter to the environment. If the parameter is a units-of-measure parameter /// then it is ignored, since it doesn't corespond to a .NET type parameter. member tyenv.AddOne (tp: Typar) = if IsNonErasedTypar tp then @@ -470,7 +470,7 @@ let GenReadOnlyModReqIfNecessary (g: TcGlobals) ty ilTy = let rec GenTypeArgAux amap m tyenv tyarg = GenTypeAux amap m tyenv VoidNotOK PtrTypesNotOK tyarg -and GenTypeArgsAux amap m tyenv tyargs = +and GenTypeArgsAux amap m tyenv tyargs = List.map (GenTypeArgAux amap m tyenv) (DropErasedTyargs tyargs) and GenTyAppAux amap m tyenv repr tinst = @@ -520,7 +520,7 @@ and GenTypeAux amap m (tyenv: TypeReprEnv) voidOK ptrsOK ty = | TType_tuple (tupInfo, args) -> GenTypeAux amap m tyenv VoidNotOK ptrsOK (mkCompiledTupleTy g (evalTupInfoIsStruct tupInfo) args) - | TType_fun (dty, returnTy) -> EraseClosures.mkILFuncTy g.ilxPubCloEnv (GenTypeArgAux amap m tyenv dty) (GenTypeArgAux amap m tyenv returnTy) + | TType_fun (dty, returnTy) -> EraseClosures.mkILFuncTy g.ilxPubCloEnv (GenTypeArgAux amap m tyenv dty) (GenTypeArgAux amap m tyenv returnTy) | TType_anon (anonInfo, tinst) -> let tref = anonInfo.ILTypeRef @@ -583,7 +583,7 @@ and ComputeUnionHasHelpers g (tcref: TyconRef) = match TryFindFSharpAttribute g g.attrib_DefaultAugmentationAttribute tcref.Attribs with | Some(Attrib(_, _, [ AttribBoolArg (b) ], _, _, _, _)) -> if b then AllHelpers else NoHelpers - | Some (Attrib(_, _, _, _, _, _, m)) -> + | Some (Attrib(_, _, _, _, _, _, m)) -> errorR(Error(FSComp.SR.ilDefaultAugmentationAttributeCouldNotBeDecoded(), m)) AllHelpers | _ -> @@ -735,14 +735,14 @@ type ValStorage = | Null /// Indicates the value is stored in a static field. - | StaticField of ILFieldSpec * ValRef * (*hasLiteralAttr:*)bool * ILType * string * ILType * ILMethodRef * ILMethodRef * OptionalShadowLocal + | StaticField of ILFieldSpec * ValRef * (*hasLiteralAttr:*)bool * ILType * string * ILType * ILMethodRef * ILMethodRef * OptionalShadowLocal /// Indicates the value is "stored" as a property that recomputes it each time it is referenced. Used for simple constants that do not cause initialization triggers - | StaticProperty of ILMethodSpec * OptionalShadowLocal + | StaticProperty of ILMethodSpec * OptionalShadowLocal /// Indicates the value is "stored" as a IL static method (in a "main" class for a F# /// compilation unit, or as a member) according to its inferred or specified arity. - | Method of ValReprInfo * ValRef * ILMethodSpec * Range.range * ArgReprInfo list * TType list * ArgReprInfo + | Method of ValReprInfo * ValRef * ILMethodSpec * Range.range * ArgReprInfo list * TType list * ArgReprInfo /// Indicates the value is stored at the given position in the closure environment accessed via "ldarg 0" | Env of ILType * int * ILFieldSpec * NamedLocalIlxClosureInfo ref option @@ -759,7 +759,7 @@ and OptionalShadowLocal = | NoShadowLocal | ShadowLocal of ValStorage -/// The representation of a NamedLocalClosure is based on a cloinfo. However we can't generate a cloinfo until we've +/// The representation of a NamedLocalClosure is based on a cloinfo. However we can't generate a cloinfo until we've /// decided the representations of other items in the recursive set. Hence we use two phases to decide representations in /// a recursive set. Yuck. and NamedLocalIlxClosureInfo = @@ -778,7 +778,7 @@ and ModuleStorage = and BranchCallItem = | BranchCallClosure of ArityInfo | BranchCallMethod of - // Argument counts for compiled form of F# method or value + // Argument counts for compiled form of F# method or value ArityInfo * // Arg infos for compiled form of F# method or value (TType * ArgReprInfo) list list * @@ -814,11 +814,11 @@ and IlxGenEnv = /// All values in scope valsInScope: ValMap> - /// For optimizing direct tail recursion to a loop - mark says where to branch to. Length is 0 or 1. + /// For optimizing direct tail recursion to a loop - mark says where to branch to. Length is 0 or 1. /// REVIEW: generalize to arbitrary nested local loops?? innerVals: (ValRef * (BranchCallItem * Mark)) list - /// Full list of enclosing bound values. First non-compiler-generated element is used to help give nice names for closures and other expressions. + /// Full list of enclosing bound values. First non-compiler-generated element is used to help give nice names for closures and other expressions. letBoundVars: ValRef list /// The set of IL local variable indexes currently in use by lexically scoped variables, to allow reuse on different branches. @@ -831,7 +831,7 @@ and IlxGenEnv = let ReplaceTyenv tyenv (eenv: IlxGenEnv) = {eenv with tyenv = tyenv } -let EnvForTypars tps eenv = {eenv with tyenv = TypeReprEnv.ForTypars tps } +let EnvForTypars tps eenv = {eenv with tyenv = TypeReprEnv.ForTypars tps } let AddTyparsToEnv typars (eenv: IlxGenEnv) = {eenv with tyenv = eenv.tyenv.Add typars} @@ -840,7 +840,7 @@ let AddSignatureRemapInfo _msg (rpi, mhi) eenv = let OutputStorage (pps: TextWriter) s = match s with - | StaticField _ -> pps.Write "(top)" + | StaticField _ -> pps.Write "(top)" | StaticProperty _ -> pps.Write "(top)" | Method _ -> pps.Write "(top)" | Local _ -> pps.Write "(local)" @@ -864,7 +864,7 @@ let AddStorageForVal (g: TcGlobals) (v, s) eenv = if g.compilingFslib then // Passing an empty remap is sufficient for FSharp.Core.dll because it turns out the remapped type signature can // still be resolved. - match tryRescopeVal g.fslibCcu Remap.Empty v with + match tryRescopeVal g.fslibCcu Remap.Empty v with | ValueNone -> eenv | ValueSome vref -> match vref.TryDeref with @@ -940,7 +940,7 @@ let GetMethodSpecForMemberVal amap g (memberInfo: ValMemberInfo) (vref: ValRef) (fun gtp ty2 -> if not (typeEquiv g (mkTyparTy gtp) ty2) then warning(InternalError("CodeGen check: type checking did not quantify the correct type variables for this method: generalization list contained " - + gtp.Name + "#" + string gtp.Stamp + " and list from 'this' pointer contained " + (showL(typeL ty2)), m))) + + gtp.Name + "#" + string gtp.Stamp + " and list from 'this' pointer contained " + (showL(typeL ty2)), m))) ctps thisArgTys let methodArgTys, paramInfos = List.unzip flatArgInfos @@ -1017,7 +1017,7 @@ let IsFSharpValCompiledAsMethod g (v: Val) = | None -> false | Some topValInfo -> not (isUnitTy g v.Type && not v.IsMemberOrModuleBinding && not v.IsMutable) && - not v.IsCompiledAsStaticPropertyWithoutField && + not v.IsCompiledAsStaticPropertyWithoutField && match GetTopValTypeInFSharpForm g topValInfo v.Type v.Range with | [], [], _, _ when not v.IsMember -> false | _ -> true @@ -1025,11 +1025,11 @@ let IsFSharpValCompiledAsMethod g (v: Val) = /// Determine how a top level value is represented, when it is being represented /// as a method. This depends on its type and other representation inforrmation. /// 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 +/// 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) = - if isUnitTy g vref.Type && not vref.IsMemberOrModuleBinding && not vref.IsMutable then + if isUnitTy g vref.Type && not vref.IsMemberOrModuleBinding && not vref.IsMutable then Null else let topValInfo = @@ -1065,7 +1065,7 @@ let ComputeStorageForTopVal (amap, g, optIntraAssemblyInfo: IlxGenIntraAssemblyI 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 @@ -1076,7 +1076,7 @@ let ComputeStorageForNonLocalTopVal amap g cloc modref (v: Val) = | 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) @@ -1094,7 +1094,7 @@ let AddStorageForExternalCcu amap g eenv (ccu: CcuThunk) = List.foldBack (fun smodul acc -> let cloc = CompLocForSubModuleOrNamespace cloc smodul - let modref = mkNonLocalCcuRootEntityRef ccu smodul + let modref = mkNonLocalCcuRootEntityRef ccu smodul AddStorageForNonLocalModuleOrNamespaceRef amap g cloc acc modref smodul) ccu.RootModulesAndNamespaces 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. @@ -1139,9 +1139,9 @@ and AddBindingsForModuleDef allocVal cloc eenv x = | TMDefDo _ -> eenv | TMAbstract(ModuleOrNamespaceExprWithSig(mtyp, _, _)) -> - AddBindingsForLocalModuleType allocVal cloc eenv mtyp + AddBindingsForLocalModuleType allocVal cloc eenv mtyp | TMDefs(mdefs) -> - AddBindingsForModuleDefs allocVal cloc eenv mdefs + AddBindingsForModuleDefs allocVal cloc eenv mdefs /// Record how constructs are represented, for a module or namespace. and AddBindingsForModule allocVal cloc x eenv = @@ -1162,8 +1162,8 @@ and AddBindingsForModuleTopVals _g allocVal _cloc eenv vs = /// Put the partial results for a generated fragment (i.e. a part of a CCU generated by FSI) /// into the stored results for the whole CCU. -/// isIncrementalFragment = true --> "typed input" -/// isIncrementalFragment = false --> "#load" +/// isIncrementalFragment = true --> "typed input" +/// isIncrementalFragment = false --> "#load" let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (amap: ImportMap, isIncrementalFragment, g, ccu, fragName, intraAssemblyInfo, eenv, typedImplFiles) = let cloc = CompLocForFragment fragName ccu let allocVal = ComputeAndAddStorageForLocalTopVal (amap, g, intraAssemblyInfo, true, NoShadowLocal) @@ -1183,7 +1183,7 @@ let AddIncrementalLocalAssemblyFragmentToIlxGenEnv (amap: ImportMap, isIncrement 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 + /// NOTE: .NET && VS measure first column as column 1 column= m.StartColumn+1, endLine= m.EndLine, endColumn=m.EndColumn+1) @@ -1247,17 +1247,17 @@ let MergePropertyDefs m ilPropertyDefs = /// Information collected imperatively for each type definition type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = - let gmethods = new ResizeArray(0) - let gfields = new ResizeArray(0) + let gmethods = new ResizeArray(0) + let gfields = new ResizeArray(0) let gproperties: Dictionary = new Dictionary<_, _>(3, HashIdentity.Structural) - let gevents = new ResizeArray(0) - let gnested = new TypeDefsBuilder() + let gevents = new ResizeArray(0) + let gnested = new TypeDefsBuilder() member b.Close() = tdef.With(methods = mkILMethods (tdef.Methods.AsList @ ResizeArray.toList gmethods), - fields = mkILFields (tdef.Fields.AsList @ ResizeArray.toList gfields), + fields = mkILFields (tdef.Fields.AsList @ ResizeArray.toList gfields), properties = mkILProperties (tdef.Properties.AsList @ HashRangeSorted gproperties ), - events = mkILEvents (tdef.Events.AsList @ ResizeArray.toList gevents), + events = mkILEvents (tdef.Events.AsList @ ResizeArray.toList gevents), nestedTypes = mkILTypeDefs (tdef.NestedTypes.AsList @ gnested.Close())) member b.AddEventDef(edef) = gevents.Add edef @@ -1288,7 +1288,7 @@ type TypeDefBuilder(tdef: ILTypeDef, tdefDiscards) = member b.PrependInstructionsToSpecificMethodDef(cond, instrs, tag) = match ResizeArray.tryFindIndex cond gmethods with - | Some idx -> gmethods.[idx] <- prependInstrsToMethod instrs gmethods.[idx] + | Some idx -> gmethods.[idx] <- prependInstrsToMethod instrs gmethods.[idx] | None -> gmethods.Add(mkILClassCtor (mkMethodBody (false, [], 1, nonBranchingInstrsToCode instrs, tag))) @@ -1310,10 +1310,10 @@ and TypeDefsBuilder() = || not tdef.Events.AsList.IsEmpty || not tdef.Properties.AsList.IsEmpty || not (Array.isEmpty tdef.Methods.AsArray) then - yield tdef ] + yield tdef ] member b.FindTypeDefBuilder(nm) = - try tdefs.[nm] |> snd |> fst + try tdefs.[nm] |> snd |> fst with :? KeyNotFoundException -> failwith ("FindTypeDefBuilder: " + nm + " not found") member b.FindNestedTypeDefsBuilder(path) = @@ -1340,10 +1340,10 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu // A memoization table for generating value types for big constant arrays let rawDataValueTypeGenerator = - new MemoizationTable<(CompileLocation * int) , ILTypeSpec> + new MemoizationTable<(CompileLocation * int), ILTypeSpec> ((fun (cloc, size) -> - let name = CompilerGeneratedName ("T" + string(newUnique()) + "_" + string size + "Bytes") // Type names ending ...$T_37Bytes - let vtdef = mkRawDataValueTypeDef cenv.g.iltyp_ValueType (name, size, 0us) + let name = CompilerGeneratedName ("T" + string(newUnique()) + "_" + string size + "Bytes") // Type names ending ...$T_37Bytes + let vtdef = mkRawDataValueTypeDef cenv.g.iltyp_ValueType (name, size, 0us) let vtref = NestedTypeRefForCompLoc cloc vtdef.Name let vtspec = mkILTySpec(vtref, []) let vtdef = vtdef.WithAccess(ComputeTypeAccess vtref true) @@ -1376,7 +1376,7 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu mkILFields [ for (_, fldName, fldTy) in flds -> let fdef = mkILInstanceField (fldName, fldTy, None, ILMemberAccess.Private) - fdef.With(customAttrs = mkILCustomAttrs [ cenv.g.DebuggerBrowsableNeverAttribute ]) ] + fdef.With(customAttrs = mkILCustomAttrs [ cenv.g.DebuggerBrowsableNeverAttribute ]) ] // Generate property definitions for the fields compiled as properties let ilProperties = @@ -1385,7 +1385,7 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu ILPropertyDef(name=propName, attributes=PropertyAttributes.None, setMethod=None, - getMethod=Some(mkILMethRef(ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], fldTy )), + getMethod=Some(mkILMethRef(ilTypeRef, ILCallingConv.Instance, "get_" + propName, 0, [], fldTy )), callingConv=ILCallingConv.Instance.ThisConv, propertyType=fldTy, init= None, @@ -1434,7 +1434,7 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu (cenv.g.mk_IComparable_ty, true, m) (mkAppTy cenv.g.system_GenericIComparable_tcref [typ], true, m) (cenv.g.mk_IStructuralEquatable_ty, true, m) - (mkAppTy cenv.g.system_GenericIEquatable_tcref [typ], true, m) ] + (mkAppTy cenv.g.system_GenericIEquatable_tcref [typ], true, m) ] let vspec1, vspec2 = AugmentWithHashCompare.MakeValsForEqualsAugmentation cenv.g tcref let evspec1, evspec2, evspec3 = AugmentWithHashCompare.MakeValsForEqualityWithComparerAugmentation cenv.g tcref @@ -1446,7 +1446,7 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu tcaug.SetEquals (mkLocalValRef vspec1, mkLocalValRef vspec2) tcaug.SetHashAndEqualsWith (mkLocalValRef evspec1, mkLocalValRef evspec2, mkLocalValRef evspec3) - // Build the ILTypeDef. We don't rely on the normal record generation process because we want very specific field names + // Build the ILTypeDef. We don't rely on the normal record generation process because we want very specific field names let ilTypeDefAttribs = mkILCustomAttrs [ cenv.g.CompilerGeneratedAttribute; mkCompilationMappingAttr cenv.g (int SourceConstructFlags.RecordType) ] @@ -1474,7 +1474,7 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu (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 = [] @@ -1545,7 +1545,7 @@ type AssemblyBuilder(cenv: cenv, anonTypeTable: AnonTypeGenerationTable) as mgbu // 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 let instrs = - [ yield! (if condition "NO_ADD_FEEFEE_TO_CCTORS" then [] elif condition "ADD_SEQPT_TO_CCTORS" then seqpt else feefee) // mark start of hidden code + [ yield! (if condition "NO_ADD_FEEFEE_TO_CCTORS" then [] elif condition "ADD_SEQPT_TO_CCTORS" then seqpt else feefee) // mark start of hidden code yield mkLdcInt32 0 yield mkNormalStsfld fspec yield mkNormalLdsfld fspec @@ -1618,7 +1618,7 @@ type CodeGenBuffer(m: range, let mutable lastSeqPoint = None // Add a nop to make way for the first sequence point. - do if mgbuf.cenv.opts.generateDebugSymbols then + do if mgbuf.cenv.opts.generateDebugSymbols then let doc = mgbuf.cenv.g.memoize_file m.FileIndex let i = FeeFeeInstr mgbuf.cenv doc codebuf.Add(i) // for the FeeFee or a better sequence point @@ -1780,7 +1780,7 @@ type CodeGenBuffer(m: range, let codeLabels = let dict = Dictionary.newWithSize (codeLabelToPC.Count + codeLabelToCodeLabel.Count) - for kvp in codeLabelToPC do dict.Add(kvp.Key, lab2pc 0 kvp.Key) + for kvp in codeLabelToPC do dict.Add(kvp.Key, lab2pc 0 kvp.Key) for kvp in codeLabelToCodeLabel do dict.Add(kvp.Key, lab2pc 0 kvp.Key) dict @@ -1792,7 +1792,7 @@ module CG = 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 SetMarkToHere (cgbuf: CodeGenBuffer) m1 = cgbuf.SetMarkToHere(m1) let SetStack (cgbuf: CodeGenBuffer) s = cgbuf.SetStack(s) let GenerateMark (cgbuf: CodeGenBuffer) s = cgbuf.Mark(s) @@ -1812,7 +1812,7 @@ let GenConstArray cenv (cgbuf: CodeGenBuffer) eenv ilElementType (data:'a[]) (wr let bytes = buf.Close() let ilArrayType = mkILArr1DTy ilElementType if data.Length = 0 then - CG.EmitInstrs cgbuf (pop 0) (Push [ilArrayType]) [ mkLdcInt32 (0); I_newarr (ILArrayShape.SingleDimensional, ilElementType); ] + CG.EmitInstrs cgbuf (pop 0) (Push [ilArrayType]) [ mkLdcInt32 (0); I_newarr (ILArrayShape.SingleDimensional, ilElementType); ] else let vtspec = cgbuf.mgbuf.GenerateRawDataValueType(eenv.cloc, bytes.Length) let ilFieldName = CompilerGeneratedName ("field" + string(newUnique())) @@ -1864,7 +1864,7 @@ let discardAndReturnVoid = DiscardThen ReturnVoid //------------------------------------------------------------------------- -// This is the main code generation routine. It is used to generate +// This is the main code generation routine. It is used to generate // the bodies of methods in a couple of places //------------------------------------------------------------------------- @@ -1917,7 +1917,7 @@ let CodeGenMethod cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, let locals, maxStack, lab2pc, instrs, exns, localDebugSpecs, hasSequencePoints = CodeGenThen cenv mgbuf (entryPointInfo, methodName, eenv, alreadyUsedArgs, codeGenFunction, m) - let code = IL.buildILCode methodName lab2pc instrs exns localDebugSpecs + let code = IL.buildILCode methodName lab2pc instrs exns localDebugSpecs // Attach a source range to the method. Only do this is it has some sequence points, because .NET 2.0/3.5 // ILDASM has issues if you emit symbols with a source range but without any sequence points @@ -1990,13 +1990,13 @@ let BindingEmitsSequencePoint g bind = | _, None, SPSuppress -> false | _ -> true -let BindingIsInvisible (TBind(_, _, spBind)) = +let BindingIsInvisible (TBind(_, _, spBind)) = match spBind with | NoSequencePointAtInvisibleBinding _ -> true | _ -> false /// Determines if the code generated for a binding is to be marked as hidden, e.g. the 'newobj' for a local function definition. -let BindingEmitsHiddenCode (TBind(_, e, spBind)) = +let BindingEmitsHiddenCode (TBind(_, e, spBind)) = match spBind, stripExpr e with | _, (Expr.Lambda _ | Expr.TyLambda _) -> true | _ -> false @@ -2020,11 +2020,11 @@ let rec FirstEmittedCodeWillBeSequencePoint g sp expr = | SequencePointsAtSeq -> true | SuppressSequencePointOnExprOfSequential -> true | SuppressSequencePointOnStmtOfSequential -> false - | Expr.Match (SequencePointAtBinding _, _, _, _, _, _) -> true - | Expr.Op(( TOp.TryCatch (SequencePointAtTry _, _) - | TOp.TryFinally (SequencePointAtTry _, _) - | TOp.For (SequencePointAtForLoop _, _) - | TOp.While (SequencePointAtWhileLoop _, _)), _, _, _) -> true + | Expr.Match (SequencePointAtBinding _, _, _, _, _, _) -> true + | Expr.Op((TOp.TryCatch (SequencePointAtTry _, _) + | TOp.TryFinally (SequencePointAtTry _, _) + | TOp.For (SequencePointAtForLoop _, _) + | TOp.While (SequencePointAtWhileLoop _, _)), _, _, _) -> true | _ -> false | SPSuppress -> @@ -2049,14 +2049,14 @@ let EmitSequencePointForWholeExpr g sp expr = // and by inlining 'f' the expression becomes // let someCode () = (let sticky = x in y) // then we place the sequence point for the whole TAST expression 'let sticky = x in y', i.e. textual range 'f x' in the source code, but - // _before_ the evaluation of 'x'. This will only happen for sticky 'let' introduced by inlining and other code generation - // steps. We do _not_ do this for 'invisible' let which can be skipped. + // _before_ the evaluation of 'x'. This will only happen for sticky 'let' introduced by inlining and other code generation + // steps. We do _not_ do this for 'invisible' let which can be skipped. | Expr.Let (bind, _, _, _) when BindingIsInvisible bind -> false | Expr.LetRec(binds, _, _, _) when binds |> List.forall BindingIsInvisible -> false // If the binding is a lambda then we don't emit a sequence point. | Expr.Let (bind, _, _, _) when BindingEmitsHiddenCode bind -> false - | Expr.LetRec(binds, _, _, _) when binds |> List.forall BindingEmitsHiddenCode -> false + | Expr.LetRec(binds, _, _, _) when binds |> List.forall BindingEmitsHiddenCode -> false // If the binding is represented by a top-level generated constant value then we don't emit a sequence point. | Expr.Let (bind, _, _, _) when BindingEmitsNoCode g bind -> false @@ -2079,7 +2079,7 @@ let EmitSequencePointForWholeExpr g sp expr = | Expr.Match _ -> false | Expr.Op(TOp.TryCatch _, _, _, _) -> false | Expr.Op(TOp.TryFinally _, _, _, _) -> false - | Expr.Op(TOp.For _, _, _, _) -> false + | Expr.Op(TOp.For _, _, _, _) -> false | Expr.Op(TOp.While _, _, _, _) -> false | _ -> true | SPSuppress -> @@ -2097,7 +2097,7 @@ let EmitHiddenCodeMarkerForWholeExpr g sp expr = | SPAlways -> match stripExpr expr with | Expr.Let (bind, _, _, _) when BindingEmitsHiddenCode bind -> true - | Expr.LetRec(binds, _, _, _) when binds |> List.exists BindingEmitsHiddenCode -> true + | Expr.LetRec(binds, _, _, _) when binds |> List.exists BindingEmitsHiddenCode -> true | _ -> false | SPSuppress -> false @@ -2112,12 +2112,12 @@ let rec RangeOfSequencePointForWholeExpr g expr = | _, None, SPSuppress -> RangeOfSequencePointForWholeExpr g body | _, Some m, _ -> m | _, None, SPAlways -> RangeOfSequencePointForWholeExpr g bind.Expr - | Expr.LetRec(_, body, _, _) -> RangeOfSequencePointForWholeExpr g body + | Expr.LetRec(_, body, _, _) -> RangeOfSequencePointForWholeExpr g body | Expr.Sequential (expr1, _, NormalSeq, _, _) -> RangeOfSequencePointForWholeExpr g expr1 | _ -> expr.Range /// Used to avoid emitting multiple sequence points in decision tree generation -let DoesGenExprStartWithSequencePoint g sp expr = +let DoesGenExprStartWithSequencePoint g sp expr = FirstEmittedCodeWillBeSequencePoint g sp expr || EmitSequencePointForWholeExpr g sp expr @@ -2127,7 +2127,7 @@ let DoesGenExprStartWithSequencePoint g sp expr = let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = - let expr = stripExpr expr + let expr = stripExpr expr if not (FirstEmittedCodeWillBeSequencePoint cenv.g sp expr) then if EmitSequencePointForWholeExpr cenv.g sp expr then @@ -2147,9 +2147,9 @@ let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = GenMatch cenv cgbuf eenv (spBind, exprm, tree, targets, m, ty) sequel | Expr.Sequential(e1, e2, dir, spSeq, m) -> GenSequential cenv cgbuf eenv sp (e1, e2, dir, spSeq, m) sequel - | Expr.LetRec (binds, body, m, _) -> + | Expr.LetRec (binds, body, m, _) -> GenLetRec cenv cgbuf eenv (binds, body, m) sequel - | Expr.Let (bind, body, _, _) -> + | Expr.Let (bind, body, _, _) -> // This case implemented here to get a guaranteed tailcall // Make sure we generate the sequence point outside the scope of the variable let startScope, endScope as scopeMarks = StartDelayedLocalScope "let" cgbuf @@ -2171,7 +2171,7 @@ let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = // Generate the body GenExpr cenv cgbuf eenv spBody body (EndLocalScope(sequel, endScope)) - | Expr.Lambda _ | Expr.TyLambda _ -> + | Expr.Lambda _ | Expr.TyLambda _ -> GenLambda cenv cgbuf eenv false None expr sequel | Expr.App(Expr.Val(vref, _, m) as v, _, tyargs, [], _) when List.forall (isMeasureTy cenv.g) tyargs && @@ -2180,10 +2180,10 @@ let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = match StorageForValRef m vref eenv with | ValStorage.Local _ -> true | _ -> false - ) -> + ) -> // 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) -> + | 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 @@ -2196,9 +2196,9 @@ let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = | Expr.Op(op, tyargs, args, m) -> match op, args, tyargs with - | TOp.ExnConstr(c), _, _ -> + | TOp.ExnConstr(c), _, _ -> GenAllocExn cenv cgbuf eenv (c, args, m) sequel - | TOp.UnionCase(c), _, _ -> + | 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 @@ -2238,9 +2238,9 @@ let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = 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, _, _)], [] -> + | 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, _, _)], [] -> + | 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 @@ -2248,15 +2248,15 @@ let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = 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.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(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.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) @@ -2290,7 +2290,7 @@ let rec GenExpr (cenv: cenv) (cgbuf: CodeGenBuffer) eenv sp expr sequel = | Expr.Obj(_, ty, _, _, [meth], [], m) when isDelegateTy cenv.g ty -> GenDelegateExpr cenv cgbuf eenv expr (meth, m) sequel | Expr.Obj(_, ty, basev, basecall, overrides, interfaceImpls, m) -> - GenObjectExpr cenv cgbuf eenv expr (ty, basev, basecall, overrides, interfaceImpls, m) sequel + GenObjectExpr cenv cgbuf eenv expr (ty, basev, basecall, overrides, interfaceImpls, m) sequel | Expr.Quote(ast, conv, _, m, ty) -> GenQuotation cenv cgbuf eenv (ast, conv, m, ty) sequel | Expr.Link _ -> failwith "Unexpected reclink" @@ -2323,9 +2323,9 @@ and sequelIgnoringEndScopesAndDiscard sequel = let sequel = sequelIgnoreEndScopes sequel match sequelAfterDiscard sequel with | Some sq -> sq - | None -> sequel + | None -> sequel -and sequelIgnoreEndScopes sequel = +and sequelIgnoreEndScopes sequel = match sequel with | EndLocalScope(sq, _) -> sequelIgnoreEndScopes sq | sq -> sq @@ -2432,9 +2432,9 @@ and GenUnitTy cenv eenv m = let res = GenType cenv.amap m eenv.tyenv cenv.g.unit_ty cenv.ilUnitTy <- Some res res - | Some res -> res + | Some res -> res -and GenUnit cenv eenv m cgbuf = +and GenUnit cenv eenv m cgbuf = CG.EmitInstr cgbuf (pop 0) (Push [GenUnitTy cenv eenv m]) AI_ldnull and GenUnitThenSequel cenv eenv m cloc cgbuf sequel = @@ -2500,7 +2500,7 @@ and GenAllocUnionCaseCore cenv cgbuf eenv (c,tyargs,n,m) = let cuspec,idx = GenUnionCaseSpec cenv.amap m eenv.tyenv c tyargs CG.EmitInstrs cgbuf (pop n) (Push [cuspec.DeclaringType]) (EraseUnions.mkNewData cenv.g.ilg (cuspec, idx)) -and GenAllocUnionCase cenv cgbuf eenv (c,tyargs,args,m) sequel = +and GenAllocUnionCase cenv cgbuf eenv (c,tyargs,args,m) sequel = GenExprs cenv cgbuf eenv args GenAllocUnionCaseCore cenv cgbuf eenv (c,tyargs,args.Length,m) GenSequel cenv eenv.cloc cgbuf sequel @@ -2527,7 +2527,7 @@ and GenAllocRecd cenv cgbuf eenv ctorInfo (tcref,argtys,args,m) sequel = |> List.filter (fun f -> not f.IsCompilerGenerated) match ctorInfo with - | RecdExprIsObjInit -> + | RecdExprIsObjInit -> (args, relevantFields) ||> List.iter2 (fun e f -> CG.EmitInstr cgbuf (pop 0) (Push (if tcref.IsStructOrEnumTycon then [ILType.Byref ty] else [ty])) mkLdarg0 GenExpr cenv cgbuf eenv SPSuppress e Continue @@ -2569,15 +2569,15 @@ and GenNewArraySimple cenv cgbuf eenv (elems, elemTy, m) sequel = CG.EmitInstrs cgbuf (pop 0) (Push [ilArrTy]) [ (AI_ldc (DT_I4, ILConst.I4 (elems.Length))); I_newarr (ILArrayShape.SingleDimensional, ilElemTy) ] elems |> List.iteri (fun i e -> - CG.EmitInstrs cgbuf (pop 0) (Push [ilArrTy; cenv.g.ilg.typ_Int32]) [ AI_dup; (AI_ldc (DT_I4, ILConst.I4 i)) ] + CG.EmitInstrs cgbuf (pop 0) (Push [ilArrTy; cenv.g.ilg.typ_Int32]) [ AI_dup; (AI_ldc (DT_I4, ILConst.I4 i)) ] GenExpr cenv cgbuf eenv SPSuppress e Continue - CG.EmitInstr cgbuf (pop 3) Push0 (I_stelem_any (ILArrayShape.SingleDimensional, ilElemTy))) + CG.EmitInstr cgbuf (pop 3) Push0 (I_stelem_any (ILArrayShape.SingleDimensional, ilElemTy))) GenSequel cenv eenv.cloc cgbuf sequel and GenNewArray cenv cgbuf eenv (elems: Expr list, elemTy, m) sequel = // REVIEW: The restriction against enum types here has to do with Dev10/Dev11 bug 872799 - // GenConstArray generates a call to RuntimeHelpers.InitializeArray. On CLR 2.0/x64 and CLR 4.0/x64/x86, + // GenConstArray generates a call to RuntimeHelpers.InitializeArray. On CLR 2.0/x64 and CLR 4.0/x64/x86, // InitializeArray is a JIT intrinsic that will result in invalid runtime CodeGen when initializing an array // of enum types. Until bug 872799 is fixed, we'll need to generate arrays the "simple" way for enum types // Also note - C# never uses InitializeArray for enum types, so this change puts us on equal footing with them. @@ -2588,14 +2588,14 @@ and GenNewArray cenv cgbuf eenv (elems: Expr list, elemTy, m) sequel = let elems' = Array.ofList elems let test, write = match elems'.[0] with - | Expr.Const(Const.Bool _, _, _) -> - (function Const.Bool _ -> true | _ -> false), - (fun (buf: ByteBuffer) -> function Const.Bool b -> buf.EmitBoolAsByte b | _ -> failwith "unreachable") - | Expr.Const(Const.Char _, _, _) -> - (function Const.Char _ -> true | _ -> false), - (fun buf -> function Const.Char b -> buf.EmitInt32AsUInt16 (int b) | _ -> failwith "unreachable") - | Expr.Const(Const.Byte _, _, _) -> - (function Const.Byte _ -> true | _ -> false), + | Expr.Const(Const.Bool _, _, _) -> + (function Const.Bool _ -> true | _ -> false), + (fun (buf: ByteBuffer) -> function Const.Bool b -> buf.EmitBoolAsByte b | _ -> failwith "unreachable") + | Expr.Const(Const.Char _, _, _) -> + (function Const.Char _ -> true | _ -> false), + (fun buf -> function Const.Char b -> buf.EmitInt32AsUInt16 (int b) | _ -> failwith "unreachable") + | Expr.Const(Const.Byte _, _, _) -> + (function Const.Byte _ -> true | _ -> false), (fun buf -> function Const.Byte b -> buf.EmitByte b | _ -> failwith "unreachable") | Expr.Const(Const.UInt16 _, _, _) -> (function Const.UInt16 _ -> true | _ -> false), @@ -2606,17 +2606,17 @@ and GenNewArray cenv cgbuf eenv (elems: Expr list, elemTy, m) sequel = | Expr.Const(Const.UInt64 _, _, _) -> (function Const.UInt64 _ -> true | _ -> false), (fun buf -> function Const.UInt64 b -> buf.EmitInt64 (int64 b) | _ -> failwith "unreachable") - | Expr.Const(Const.SByte _, _, _) -> - (function Const.SByte _ -> true | _ -> false), + | Expr.Const(Const.SByte _, _, _) -> + (function Const.SByte _ -> true | _ -> false), (fun buf -> function Const.SByte b -> buf.EmitByte (byte b) | _ -> failwith "unreachable") - | Expr.Const(Const.Int16 _, _, _) -> - (function Const.Int16 _ -> true | _ -> false), + | Expr.Const(Const.Int16 _, _, _) -> + (function Const.Int16 _ -> true | _ -> false), (fun buf -> function Const.Int16 b -> buf.EmitUInt16 (uint16 b) | _ -> failwith "unreachable") - | Expr.Const(Const.Int32 _, _, _) -> - (function Const.Int32 _ -> true | _ -> false), + | Expr.Const(Const.Int32 _, _, _) -> + (function Const.Int32 _ -> true | _ -> false), (fun buf -> function Const.Int32 b -> buf.EmitInt32 b | _ -> failwith "unreachable") - | Expr.Const(Const.Int64 _, _, _) -> - (function Const.Int64 _ -> true | _ -> false), + | Expr.Const(Const.Int64 _, _, _) -> + (function Const.Int64 _ -> true | _ -> false), (fun buf -> function Const.Int64 b -> buf.EmitInt64 b | _ -> failwith "unreachable") | _ -> (function _ -> false), (fun _ _ -> failwith "unreachable") @@ -2649,10 +2649,10 @@ and GenCoerce cenv cgbuf eenv (e, tgty, m, srcty) sequel = GenExpr cenv cgbuf eenv SPSuppress e Continue if not (isObjTy cenv.g srcty) then let ilFromTy = GenType cenv.amap m eenv.tyenv srcty - CG.EmitInstrs cgbuf (pop 1) (Push [cenv.g.ilg.typ_Object]) [ I_box ilFromTy ] + CG.EmitInstrs cgbuf (pop 1) (Push [cenv.g.ilg.typ_Object]) [ I_box ilFromTy ] if not (isObjTy cenv.g tgty) then let ilToTy = GenType cenv.amap m eenv.tyenv tgty - CG.EmitInstrs cgbuf (pop 1) (Push [ilToTy]) [ I_unbox_any ilToTy ] + CG.EmitInstrs cgbuf (pop 1) (Push [ilToTy]) [ I_unbox_any ilToTy ] GenSequel cenv eenv.cloc cgbuf sequel and GenReraise cenv cgbuf eenv (rtnty, m) sequel = @@ -2661,7 +2661,7 @@ and GenReraise cenv cgbuf eenv (rtnty, m) sequel = // [See comment related to I_throw]. // Rethrow does not return. Required to push dummy value on the stack. // This follows prior behaviour by prim-types reraise<_>. - CG.EmitInstrs cgbuf (pop 0) (Push [ilReturnTy]) [AI_ldnull; I_unbox_any ilReturnTy ] + CG.EmitInstrs cgbuf (pop 0) (Push [ilReturnTy]) [AI_ldnull; I_unbox_any ilReturnTy ] GenSequel cenv eenv.cloc cgbuf sequel and GenGetExnField cenv cgbuf eenv (e, ecref, fieldNum, m) sequel = @@ -2734,7 +2734,7 @@ and GenGetUnionCaseTag cenv cgbuf eenv (e, tcref, tyargs, m) sequel = let cuspec = GenUnionSpec cenv.amap m eenv.tyenv tcref tyargs let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib tcref EraseUnions.emitLdDataTag cenv.g.ilg (UnionCodeGen cgbuf) (avoidHelpers, cuspec) - CG.EmitInstrs cgbuf (pop 1) (Push [cenv.g.ilg.typ_Int32]) [ ] // push/pop to match the line above + CG.EmitInstrs cgbuf (pop 1) (Push [cenv.g.ilg.typ_Int32]) [ ] // push/pop to match the line above GenSequel cenv eenv.cloc cgbuf sequel and GenSetUnionCaseField cenv cgbuf eenv (e, ucref, tyargs, n, e2, m) sequel = @@ -2809,11 +2809,11 @@ and GenFieldStore isStatic cenv cgbuf eenv (rfref: RecdFieldRef, tyargs, m) sequ /// Generate arguments to a call, unless the argument is the single lone "unit" value /// to a method or value compiled as a method taking no arguments -and GenUntupledArgsDiscardingLoneUnit cenv cgbuf eenv m numObjArgs curriedArgInfos args = - match curriedArgInfos , args with +and GenUntupledArgsDiscardingLoneUnit cenv cgbuf eenv m numObjArgs curriedArgInfos args = + match curriedArgInfos, args with // Type.M() // new C() - | [[]], [arg] when numObjArgs = 0 -> + | [[]], [arg] when numObjArgs = 0 -> assert isUnitTy cenv.g (tyOfExpr cenv.g arg) GenExpr cenv cgbuf eenv SPSuppress arg discard // obj.M() @@ -2865,13 +2865,13 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = (* when branch-calling methods we must have the right type parameters *) (match kind with | BranchCallClosure _ -> true - | BranchCallMethod (_, _, tps, _, _) -> + | BranchCallMethod (_, _, tps, _, _) -> (List.lengthsEqAndForall2 (fun ty tp -> typeEquiv cenv.g ty (mkTyparTy tp)) tyargs tps)) && (* must be exact #args, ignoring tupling - we untuple if needed below *) (let arityInfo = match kind with | BranchCallClosure arityInfo - | BranchCallMethod (arityInfo, _, _, _, _) -> arityInfo + | BranchCallMethod (arityInfo, _, _, _, _) -> arityInfo arityInfo.Length = args.Length ) && (* no tailcall out of exception handler, etc. *) @@ -2885,7 +2885,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = let ntmargs = List.foldBack (+) arityInfo 0 GenExprs cenv cgbuf eenv args ntmargs - | BranchCallMethod (arityInfo, curriedArgInfos, _, ntmargs, numObjArgs) -> + | BranchCallMethod (arityInfo, curriedArgInfos, _, ntmargs, numObjArgs) -> assert (curriedArgInfos.Length = arityInfo.Length ) assert (curriedArgInfos.Length = args.Length) //assert (curriedArgInfos.Length = ntmargs ) @@ -2976,7 +2976,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = // For instance method calls chop off some type arguments, which are already - // carried by the class. Also work out if it's a virtual call. + // carried by the class. Also work out if it's a virtual call. let _, virtualCall, newobj, isSuperInit, isSelfInit, _, _, _ = GetMemberCallInfo cenv.g (vref, valUseFlags) in // numEnclILTypeArgs will include unit-of-measure args, unfortunately. For now, just cut-and-paste code from GetMemberCallInfo @@ -2988,7 +2988,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = | _ -> 0 let (ilEnclArgTys, ilMethArgTys) = - if ilTyArgs.Length < numEnclILTypeArgs then error(InternalError("length mismatch", m)) + if ilTyArgs.Length < numEnclILTypeArgs then error(InternalError("length mismatch", m)) List.splitAt numEnclILTypeArgs ilTyArgs let boxity = mspec.DeclaringType.Boxity @@ -2999,7 +2999,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = let ccallInfo = match valUseFlags with - | PossibleConstrainedCall ty -> Some ty + | PossibleConstrainedCall ty -> Some ty | _ -> None let isBaseCall = match valUseFlags with VSlotDirectCall -> true | _ -> false @@ -3050,13 +3050,13 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = let pushes = if mustGenerateUnitAfterCall || isSuperInit || isSelfInit then Push0 else (Push [(GenType cenv.amap m eenv.tyenv actualRetTy)]) CG.EmitInstr cgbuf (pop (nargs + (if mspec.CallingConv.IsStatic || newobj then 0 else 1))) pushes callInstr - // For isSuperInit, load the 'this' pointer as the pretend 'result' of the operation. It will be popped again in most cases + // For isSuperInit, load the 'this' pointer as the pretend 'result' of the operation. It will be popped again in most cases if isSuperInit then CG.EmitInstrs cgbuf (pop 0) (Push [mspec.DeclaringType]) [ mkLdarg0 ] // When generating debug code, generate a 'nop' after a 'call' that returns 'void' // This is what C# does, as it allows the call location to be maintained correctly in the stack frame if cenv.opts.generateDebugSymbols && mustGenerateUnitAfterCall && (isTailCall = Normalcall) then - CG.EmitInstrs cgbuf (pop 0) Push0 [ AI_nop ] + CG.EmitInstrs cgbuf (pop 0) Push0 [ AI_nop ] if isNil laterArgs then assert isNil whereSaved @@ -3064,7 +3064,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = CommitCallSequel cenv eenv m eenv.cloc cgbuf mustGenerateUnitAfterCall sequel else //printfn "%d EXTRA ARGS IN TOP APP at %s" laterArgs.Length (stringOfRange m) - whereSaved |> List.iter (function + whereSaved |> List.iter (function | Choice1Of2 (ilTy, loc) -> EmitGetLocal cgbuf ilTy loc | Choice2Of2 expr -> GenExpr cenv cgbuf eenv SPSuppress expr Continue) GenIndirectCall cenv cgbuf eenv (actualRetTy, [], laterArgs, m) sequel) @@ -3075,7 +3075,7 @@ and GenApp cenv cgbuf eenv (f, fty, tyargs, args, m) sequel = // However, we know the type instantiation for the value. // In this case we can often generate a type-specific local expression for the value. // This reduces the number of dynamic type applications. - | (Expr.Val(vref, _, _), _, _) -> + | (Expr.Val(vref, _, _), _, _) -> GenGetValRefAndSequel cenv cgbuf eenv m vref (Some (tyargs, args, m, sequel)) | _ -> @@ -3093,9 +3093,9 @@ and CanTailcall (hasStructObjArg, ccallInfo, withinSEH, hasByrefArg, mustGenerat // We can tailcall even if we need to generate "unit", as long as we're about to throw the value away anyway as par of the return. // We can tailcall if we don't need to generate "unit", as long as we're about to return. (match sequelIgnoreEndScopes sequel with - | ReturnVoid | Return -> not mustGenerateUnitAfterCall - | DiscardThen ReturnVoid -> mustGenerateUnitAfterCall - | _ -> false) + | ReturnVoid | Return -> not mustGenerateUnitAfterCall + | DiscardThen ReturnVoid -> mustGenerateUnitAfterCall + | _ -> false) then Tailcall else Normalcall @@ -3117,7 +3117,7 @@ and GenNamedLocalTyFuncCall cenv (cgbuf: CodeGenBuffer) eenv ty cloinfo tyargs m // Local TyFunc are represented as a $contract type. they currently get stored in a value of type object // Recover result (value or reference types) via unbox_any. - CG.EmitInstrs cgbuf (pop 1) (Push [ilContractTy]) [I_unbox_any ilContractTy] + CG.EmitInstrs cgbuf (pop 1) (Push [ilContractTy]) [I_unbox_any ilContractTy] let actualRetTy = applyTys cenv.g ty (tyargs, []) let ilDirectInvokeMethSpec = mkILInstanceMethSpecInTy(ilContractTy, "DirectInvoke", [], ilContractFormalRetTy, ilTyArgs) @@ -3247,7 +3247,7 @@ and GenTryCatch cenv cgbuf eenv (e1, vf: Val, ef, vh: Val, eh, m, resty, spTry, // Why SPSuppress? Because we do not emit a sequence point at the start of the List.filter - we've already put one on // the 'with' keyword above - GenExpr cenv cgbuf eenvinner SPSuppress ef sequelOnBranches + GenExpr cenv cgbuf eenvinner SPSuppress ef sequelOnBranches CG.SetMarkToHere cgbuf afterJoin CG.SetStack cgbuf stackAfterJoin GenSequel cenv eenv.cloc cgbuf sequelAfterJoin @@ -3325,7 +3325,7 @@ and GenTryFinally cenv cgbuf eenv (bodyExpr, handlerExpr, m, resty, spTry, spFin let handlerMarks = (startOfHandler.CodeLabel, endOfHandler.CodeLabel) cgbuf.EmitExceptionClause { Clause = ILExceptionClause.Finally(handlerMarks) - Range = tryMarks } + Range = tryMarks } CG.SetMarkToHere cgbuf afterHandler CG.SetStack cgbuf [] @@ -3356,7 +3356,7 @@ and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = let stack, eenvinner = EmitSaveStack cenv cgbuf eenv m (start, finish) let isUp = (match dir with | FSharpForLoopUp | CSharpForLoopUp -> true | FSharpForLoopDown -> false) - let isFSharpStyle = (match dir with FSharpForLoopUp | FSharpForLoopDown -> true | CSharpForLoopUp -> false) + let isFSharpStyle = (match dir with FSharpForLoopUp | FSharpForLoopDown -> true | CSharpForLoopUp -> false) let finishIdx, eenvinner = if isFSharpStyle then @@ -3367,7 +3367,7 @@ and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = let _, eenvinner = AllocLocalVal cenv cgbuf v eenvinner None (start, finish) (* note: eenvStack noted stack spill vars are live *) match spFor with - | SequencePointAtForLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart + | SequencePointAtForLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart | NoSequencePointAtForLoop -> () GenExpr cenv cgbuf eenv SPSuppress e1 Continue @@ -3400,16 +3400,16 @@ and GenForLoop cenv cgbuf eenv (spFor, v, e1, dir, e2, loopBody, m) sequel = // FSharpForLoopDown: if v <> e2 - 1 then goto .inner // CSharpStyle: if v < e2 then goto .inner match spFor with - | SequencePointAtForLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart - | NoSequencePointAtForLoop -> () //CG.EmitSeqPoint cgbuf e2.Range + | SequencePointAtForLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart + | NoSequencePointAtForLoop -> () //CG.EmitSeqPoint cgbuf e2.Range GenGetLocalVal cenv cgbuf eenvinner e2.Range v None let cmp = match dir with FSharpForLoopUp | FSharpForLoopDown -> BI_bne_un | CSharpForLoopUp -> BI_blt - let e2Sequel = (CmpThenBrOrContinue (pop 2, [ I_brcmp(cmp, inner.CodeLabel) ])) + let e2Sequel = (CmpThenBrOrContinue (pop 2, [ I_brcmp(cmp, inner.CodeLabel) ])) if isFSharpStyle then - EmitGetLocal cgbuf cenv.g.ilg.typ_Int32 finishIdx + EmitGetLocal cgbuf cenv.g.ilg.typ_Int32 finishIdx CG.EmitInstr cgbuf (pop 0) (Push [cenv.g.ilg.typ_Int32]) (mkLdcInt32 1) CG.EmitInstr cgbuf (pop 1) Push0 (if isUp then AI_add else AI_sub) GenSequel cenv eenv.cloc cgbuf e2Sequel @@ -3432,7 +3432,7 @@ and GenWhileLoop cenv cgbuf eenv (spWhile, e1, e2, m) sequel = let startTest = CG.GenerateMark cgbuf "startTest" match spWhile with - | SequencePointAtWhileLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart + | SequencePointAtWhileLoop(spStart) -> CG.EmitSeqPoint cgbuf spStart | NoSequencePointAtWhileLoop -> () // SEQUENCE POINTS: Emit a sequence point to cover all of 'while e do' @@ -3475,11 +3475,11 @@ and GenSequential cenv cgbuf eenv spIn (e1, e2, specialSeqFlag, spSeq, _m) seque and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = let ilTyArgs = GenTypesPermitVoid cenv.amap m eenv.tyenv tyargs - let ilReturnTys = GenTypesPermitVoid cenv.amap m eenv.tyenv returnTys + let ilReturnTys = GenTypesPermitVoid cenv.amap m eenv.tyenv returnTys let ilAfterInst = il |> List.filter (function AI_nop -> false | _ -> true) |> List.map (fun i -> - let err s = + let err s = errorR(InternalError(sprintf "%s: bad instruction: %A" s i, m)) let modFieldSpec fspec = @@ -3491,28 +3491,28 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = let tspec = ty.TypeSpec mkILTy ty.Boxity (mkILTySpec(tspec.TypeRef, ilTyArgs)) } match i, ilTyArgs with - | I_unbox_any (ILType.TypeVar _) , [tyarg] -> I_unbox_any (tyarg) - | I_box (ILType.TypeVar _) , [tyarg] -> I_box (tyarg) - | I_isinst (ILType.TypeVar _) , [tyarg] -> I_isinst (tyarg) - | I_castclass (ILType.TypeVar _) , [tyarg] -> I_castclass (tyarg) - | I_newarr (shape, ILType.TypeVar _) , [tyarg] -> I_newarr (shape, tyarg) - | I_ldelem_any (shape, ILType.TypeVar _) , [tyarg] -> I_ldelem_any (shape, tyarg) - | I_ldelema (ro, _, shape, ILType.TypeVar _) , [tyarg] -> I_ldelema (ro, false, shape, tyarg) - | I_stelem_any (shape, ILType.TypeVar _) , [tyarg] -> I_stelem_any (shape, tyarg) - | I_ldobj (a, b, ILType.TypeVar _) , [tyarg] -> I_ldobj (a, b, tyarg) - | I_stobj (a, b, ILType.TypeVar _) , [tyarg] -> I_stobj (a, b, tyarg) + | I_unbox_any (ILType.TypeVar _), [tyarg] -> I_unbox_any (tyarg) + | I_box (ILType.TypeVar _), [tyarg] -> I_box (tyarg) + | I_isinst (ILType.TypeVar _), [tyarg] -> I_isinst (tyarg) + | I_castclass (ILType.TypeVar _), [tyarg] -> I_castclass (tyarg) + | I_newarr (shape, ILType.TypeVar _), [tyarg] -> I_newarr (shape, tyarg) + | I_ldelem_any (shape, ILType.TypeVar _), [tyarg] -> I_ldelem_any (shape, tyarg) + | I_ldelema (ro, _, shape, ILType.TypeVar _), [tyarg] -> I_ldelema (ro, false, shape, tyarg) + | I_stelem_any (shape, ILType.TypeVar _), [tyarg] -> I_stelem_any (shape, tyarg) + | I_ldobj (a, b, ILType.TypeVar _), [tyarg] -> I_ldobj (a, b, tyarg) + | I_stobj (a, b, ILType.TypeVar _), [tyarg] -> I_stobj (a, b, tyarg) | I_ldtoken (ILToken.ILType (ILType.TypeVar _)), [tyarg] -> I_ldtoken (ILToken.ILType (tyarg)) - | I_sizeof (ILType.TypeVar _) , [tyarg] -> I_sizeof (tyarg) + | I_sizeof (ILType.TypeVar _), [tyarg] -> I_sizeof (tyarg) // currently unused, added for forward compat, see https://visualfsharp.codeplex.com/SourceControl/network/forks/jackpappas/fsharpcontrib/contribution/7134 - | I_cpobj (ILType.TypeVar _) , [tyarg] -> I_cpobj (tyarg) - | I_initobj (ILType.TypeVar _) , [tyarg] -> I_initobj (tyarg) - | I_ldfld (al, vol, fspec) , _ -> I_ldfld (al, vol, modFieldSpec fspec) - | I_ldflda (fspec) , _ -> I_ldflda (modFieldSpec fspec) - | I_stfld (al, vol, fspec) , _ -> I_stfld (al, vol, modFieldSpec fspec) - | I_stsfld (vol, fspec) , _ -> I_stsfld (vol, modFieldSpec fspec) - | I_ldsfld (vol, fspec) , _ -> I_ldsfld (vol, modFieldSpec fspec) - | I_ldsflda (fspec) , _ -> I_ldsflda (modFieldSpec fspec) - | EI_ilzero(ILType.TypeVar _) , [tyarg] -> EI_ilzero(tyarg) + | I_cpobj (ILType.TypeVar _), [tyarg] -> I_cpobj (tyarg) + | I_initobj (ILType.TypeVar _), [tyarg] -> I_initobj (tyarg) + | I_ldfld (al, vol, fspec), _ -> I_ldfld (al, vol, modFieldSpec fspec) + | I_ldflda (fspec), _ -> I_ldflda (modFieldSpec fspec) + | I_stfld (al, vol, fspec), _ -> I_stfld (al, vol, modFieldSpec fspec) + | I_stsfld (vol, fspec), _ -> I_stsfld (vol, modFieldSpec fspec) + | I_ldsfld (vol, fspec), _ -> I_ldsfld (vol, modFieldSpec fspec) + | I_ldsflda (fspec), _ -> I_ldsflda (modFieldSpec fspec) + | EI_ilzero(ILType.TypeVar _), [tyarg] -> EI_ilzero(tyarg) | AI_nop, _ -> i // These are embedded in the IL for a an initonly ldfld, i.e. // here's the relevant comment from tc.fs @@ -3553,14 +3553,14 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = GenSequelEndScopes cgbuf sequel // 'throw' instructions are a bit of a problem - e.g. let x = (throw ...) in ... expects a value *) - // to be left on the stack. But dead-code checking by some versions of the .NET verifier *) + // to be left on the stack. But dead-code checking by some versions of the .NET verifier *) // mean that we can't just have fake code after the throw to generate the fake value *) // (nb. a fake value can always be generated by a "ldnull unbox.any ty" sequence *) // So in the worst case we generate a fake (never-taken) branch to a piece of code to generate *) // the fake value *) | [ I_throw ], [arg1], sequel, [ilRetTy] -> match sequelIgnoreEndScopes sequel with - | s when IsSequelImmediate s -> + | s when IsSequelImmediate s -> (* In most cases we can avoid doing this... *) GenExpr cenv cgbuf eenv SPSuppress arg1 Continue CG.EmitInstr cgbuf (pop 1) Push0 I_throw @@ -3572,7 +3572,7 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = CG.EmitInstrs cgbuf (pop 0) Push0 [mkLdcInt32 0; I_brcmp (BI_brfalse, after2.CodeLabel) ] CG.SetMarkToHere cgbuf after1 - CG.EmitInstrs cgbuf (pop 0) (Push [ilRetTy]) [AI_ldnull; I_unbox_any ilRetTy; I_br after3.CodeLabel ] + CG.EmitInstrs cgbuf (pop 0) (Push [ilRetTy]) [AI_ldnull; I_unbox_any ilRetTy; I_br after3.CodeLabel ] CG.SetMarkToHere cgbuf after2 GenExpr cenv cgbuf eenv SPSuppress arg1 Continue @@ -3582,13 +3582,13 @@ and GenAsmCode cenv cgbuf eenv (il, tyargs, args, returnTys, m) sequel = | _ -> // float or float32 or float<_> or float32<_> let g = cenv.g in - let anyfpType ty = typeEquivAux EraseMeasures g g.float_ty ty || typeEquivAux EraseMeasures g g.float32_ty ty + let anyfpType ty = typeEquivAux EraseMeasures g g.float_ty ty || typeEquivAux EraseMeasures g g.float32_ty ty // Otherwise generate the arguments, and see if we can use a I_brcmp rather than a comparison followed by an I_brfalse/I_brtrue GenExprs cenv cgbuf eenv args match ilAfterInst, sequel with - // NOTE: THESE ARE NOT VALID ON FLOATING POINT DUE TO NaN. Hence INLINE ASM ON FP. MUST BE CAREFULLY WRITTEN + // NOTE: THESE ARE NOT VALID ON FLOATING POINT DUE TO NaN. Hence INLINE ASM ON FP. MUST BE CAREFULLY WRITTEN | [ AI_clt ], CmpThenBrOrContinue(1, [ I_brcmp (BI_brfalse, label1) ]) when not (anyfpType (tyOfExpr g args.Head)) -> CG.EmitInstr cgbuf (pop 2) Push0 (I_brcmp(BI_bge, label1)) @@ -3643,7 +3643,7 @@ and GenQuotation cenv cgbuf eenv (ast, conv, m, ety) sequel = let astSerializedBytes = QuotationPickler.pickle astSpec - let someTypeInModuleExpr = mkTypeOfExpr cenv m eenv.someTypeInThisAssembly + let someTypeInModuleExpr = mkTypeOfExpr cenv m eenv.someTypeInThisAssembly let rawTy = mkRawQuotedExprTy cenv.g let spliceTypeExprs = List.map (GenType cenv.amap m eenv.tyenv >> (mkTypeOfExpr cenv m)) spliceTypes @@ -3652,7 +3652,7 @@ and GenQuotation cenv cgbuf eenv (ast, conv, m, ety) sequel = let deserializeExpr = match QuotationTranslator.QuotationGenerationScope.ComputeQuotationFormat cenv.g with | QuotationTranslator.QuotationSerializationFormat.FSharp_40_Plus -> - let referencedTypeDefExprs = List.map (mkILNonGenericBoxedTy >> mkTypeOfExpr cenv m) referencedTypeDefs + let referencedTypeDefExprs = List.map (mkILNonGenericBoxedTy >> mkTypeOfExpr cenv m) referencedTypeDefs let referencedTypeDefsExpr = mkArray (cenv.g.system_Type_ty, referencedTypeDefExprs, m) let spliceTypesExpr = mkArray (cenv.g.system_Type_ty, spliceTypeExprs, m) let spliceArgsExpr = mkArray (rawTy, spliceArgExprs, m) @@ -3678,7 +3678,7 @@ and GenQuotation cenv cgbuf eenv (ast, conv, m, ety) 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 hasByrefArg = ilMethRef.ArgTypes |> List.exists IsILTypeByref let isSuperInit = match valUseFlags with CtorValUsedAsSuperInit -> true | _ -> false let isBaseCall = match valUseFlags with VSlotDirectCall -> true | _ -> false let ccallInfo = match valUseFlags with PossibleConstrainedCall ty -> Some ty | _ -> None @@ -3706,7 +3706,7 @@ and GenILCall cenv cgbuf eenv (virt, valu, newobj, valUseFlags, isDllImport, ilM [ I_callconstraint(tail, ilObjArgTy, ilMethSpec, None) ] | None -> if useICallVirt then [ I_callvirt(tail, ilMethSpec, None) ] - else [ I_call(tail, ilMethSpec, None) ] + else [ I_call(tail, ilMethSpec, None) ] CG.EmitInstrs cgbuf (pop (argExprs.Length + (if isSuperInit then 1 else 0))) (if isSuperInit then Push0 else Push ilReturnTys) il @@ -3769,7 +3769,7 @@ and GenGetValAddr cenv cgbuf eenv (v: ValRef, m) sequel = | Env (_, _, ilField, _) -> CG.EmitInstrs cgbuf (pop 0) (Push [ILType.Byref ilTy]) [ mkLdarg0; mkNormalLdflda ilField ] - | Local (_, _, Some _) | StaticProperty _ | Method _ | Env _ | Null -> + | Local (_, _, Some _) | StaticProperty _ | Method _ | Env _ | Null -> errorR(Error(FSComp.SR.ilAddressOfValueHereIsInvalid(v.DisplayName), m)) CG.EmitInstrs cgbuf (pop 1) (Push [ILType.Byref ilTy]) [ I_ldarga (uint16 669 (* random value for post-hoc diagnostic analysis on generated tree *) ) ] @@ -3819,7 +3819,7 @@ and GenDefaultValue cenv cgbuf eenv (ty, m) = // we can just rely on zeroinit of all IL locals. if realloc then match ilTy with - | ILType.Byref _ -> () + | ILType.Byref _ -> () | _ -> EmitInitLocal cgbuf ilTy locIdx EmitGetLocal cgbuf ilTy locIdx ) @@ -3859,7 +3859,7 @@ and GenGenericParam cenv eenv (tp: Typar) = | "U2" -> "TResult2" | _ -> if nm.TrimEnd([| '0' .. '9' |]).Length = 1 then nm - elif nm.Length >= 1 && nm.[0] = 'T' && (nm.Length = 1 || not (System.Char.IsLower nm.[1])) then nm + elif nm.Length >= 1 && nm.[0] = 'T' && (nm.Length = 1 || not (System.Char.IsLower nm.[1])) then nm else "T" + (String.capitalize nm) else nm @@ -3907,7 +3907,7 @@ and GenFormalSlotsig m cenv eenv (TSlotSig(_, ty, ctps, mtps, paraml, returnTy)) let eenvForSlotSig = EnvForTypars (ctps @ mtps) eenv let ilParams = paraml |> List.map (GenSlotParam m cenv eenvForSlotSig) let ilRetTy = GenReturnType cenv.amap m eenvForSlotSig.tyenv returnTy - let ilRet = mkILReturn ilRetTy + let ilRet = mkILReturn ilRetTy let ilRet = match returnTy with | None -> ilRet @@ -3956,7 +3956,7 @@ and GenMethodImpl cenv eenv (useMethodImpl, (TSlotSig(nameOfOverridenMethod, _, and bindBaseOrThisVarOpt cenv eenv baseValOpt = match baseValOpt with | None -> eenv - | Some basev -> AddStorageForVal cenv.g (basev, notlazy (Arg 0)) eenv + | Some basev -> AddStorageForVal cenv.g (basev, notlazy (Arg 0)) eenv and fixupVirtualSlotFlags (mdef: ILMethodDef) = mdef.WithHideBySig() @@ -3972,7 +3972,7 @@ 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 let (TSlotSig(nameOfOverridenMethod, _, _, _, _, _)) = slotsig - if CompileAsEvent cenv.g attribs then + if CompileAsEvent cenv.g attribs then [] else let eenvUnderTypars = AddTyparsToEnv methTyparsOfOverridingMethod eenvinner @@ -3984,7 +3984,7 @@ and GenObjectMethod cenv eenvinner (cgbuf: CodeGenBuffer) useMethodImpl tmethod let ilAttribs = GenAttrs cenv eenvinner attribs // Args are stored starting at #1 - let eenvForMeth = AddStorageForLocalVals cenv.g (methodParams |> List.mapi (fun i v -> (v, Arg i))) eenvUnderTypars + let eenvForMeth = AddStorageForLocalVals cenv.g (methodParams |> List.mapi (fun i v -> (v, Arg i))) eenvUnderTypars let sequel = (if slotSigHasVoidReturnTy slotsig then discardAndReturnVoid else Return) let ilMethodBody = CodeGenMethodForExpr cenv cgbuf.mgbuf (SPAlways, [], nameOfOverridenMethod, eenvForMeth, 0, methodBodyExpr, sequel) @@ -4004,8 +4004,8 @@ and GenObjectMethod cenv eenvinner (cgbuf: CodeGenBuffer) useMethodImpl tmethod let mdef = mdef.With(customAttrs = mkILCustomAttrs ilAttribs) [(useMethodImpl, methodImplGenerator, methTyparsOfOverridingMethod), mdef] -and GenObjectExpr cenv cgbuf eenvouter expr (baseType, baseValOpt, basecall, overrides, interfaceImpls, m) sequel = - let cloinfo, _, eenvinner = GetIlxClosureInfo cenv m false None eenvouter expr +and GenObjectExpr cenv cgbuf eenvouter expr (baseType, baseValOpt, basecall, overrides, interfaceImpls, m) sequel = + let cloinfo, _, eenvinner = GetIlxClosureInfo cenv m false None eenvouter expr let cloAttribs = cloinfo.cloAttribs let cloFreeVars = cloinfo.cloFreeVars @@ -4199,7 +4199,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr | Expr.Lambda (_, _, _, _, _, m, _) | Expr.TyLambda(_, _, _, m, _) -> - let cloinfo, body, eenvinner = GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenv expr + let cloinfo, body, eenvinner = GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenv expr let entryPointInfo = match selfv with @@ -4215,7 +4215,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr 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 + let ilContractCtor = mkILNonGenericEmptyCtor None cenv.g.ilg.typ_Object let ilContractMeths = [ilContractCtor; mkILGenericVirtualMethod("DirectInvoke", ILMemberAccess.Assembly, ilContractMethTyargs, [], mkILReturn ilContractFormalRetTy, MethodBody.Abstract) ] let ilContractTypeDef = @@ -4247,7 +4247,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr cgbuf.mgbuf.AddTypeDef(ilContractTypeRef, ilContractTypeDef, false, false, None) - let ilCtorBody = mkILMethodBody (true, [], 8, nonBranchingInstrsToCode (mkCallBaseConstructor(ilContractTy, [])), None ) + let ilCtorBody = mkILMethodBody (true, [], 8, nonBranchingInstrsToCode (mkCallBaseConstructor(ilContractTy, [])), None ) let cloMethods = [ mkILGenericVirtualMethod("DirectInvoke", ILMemberAccess.Assembly, cloinfo.localTypeFuncDirectILGenericParams, [], mkILReturn (cloinfo.cloILFormalRetTy), MethodBody.IL ilCloBody) ] let cloTypeDefs = GenClosureTypeDefs cenv (ilCloTypeRef, cloinfo.cloILGenericParams, [], cloinfo.cloILFreeVars, cloinfo.ilCloLambdas, ilCtorBody, cloMethods, [], ilContractTy, []) cloTypeDefs @@ -4259,7 +4259,7 @@ and GenLambdaClosure cenv (cgbuf: CodeGenBuffer) eenv isLocalTypeFunc selfv expr cgbuf.mgbuf.AddTypeDef(ilCloTypeRef, cloTypeDef, false, false, None) cloinfo, m - | _ -> failwith "GenLambda: not a lambda" + | _ -> failwith "GenLambda: not a lambda" and GenLambdaVal cenv (cgbuf: CodeGenBuffer) eenv (cloinfo, m) = GenGetLocalVals cenv cgbuf eenv m cloinfo.cloFreeVars @@ -4312,7 +4312,7 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = NestedTypeRefForCompLoc eenvouter.cloc cloName // Collect the free variables of the closure - let cloFreeVarResults = freeInExpr CollectTyparsAndLocals expr + let cloFreeVarResults = freeInExpr CollectTyparsAndLocals expr // Partition the free variables when some can be accessed from places besides the immediate environment // Also filter out the current value being bound, if any, as it is available from the "this" @@ -4340,7 +4340,7 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = // -- "internal" ones, which get used internally in the implementation let cloContractFreeTyvarSet = (freeInType CollectTypars (tyOfExpr cenv.g expr)).FreeTypars - let cloInternalFreeTyvars = Zset.diff cloFreeVarResults.FreeTyvars.FreeTypars cloContractFreeTyvarSet |> Zset.elements + let cloInternalFreeTyvars = Zset.diff cloFreeVarResults.FreeTyvars.FreeTypars cloContractFreeTyvarSet |> Zset.elements let cloContractFreeTyvars = cloContractFreeTyvarSet |> Zset.elements let cloFreeTyvars = cloContractFreeTyvars @ cloInternalFreeTyvars @@ -4356,7 +4356,7 @@ and GetIlxClosureFreeVars cenv m selfv eenvouter takenNames expr = // If generating a named closure, add the closure itself as a var, available via "arg0" . // The latter doesn't apply for the delegate implementation of closures. // Build the environment that is active inside the closure itself - let eenvinner = eenvinner |> AddStorageForLocalVals cenv.g (match selfv with | Some v -> [(v.Deref, Arg 0)] | _ -> []) + let eenvinner = eenvinner |> AddStorageForLocalVals cenv.g (match selfv with | Some v -> [(v.Deref, Arg 0)] | _ -> []) let ilCloFreeVars = let ilCloFreeVarNames = ChooseFreeVarNames takenNames (List.map nameOfVal cloFreeVars) @@ -4396,8 +4396,8 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = getCallStructure ((DropErasedTypars tvs) :: tvacc) vacc (body, bty) | Expr.Lambda (_, _, _, vs, body, _, bty) when not isLocalTypeFunc -> // Transform a lambda taking untupled arguments into one - // taking only a single tupled argument if necessary. REVIEW: do this earlier - let tupledv, body = MultiLambdaToTupledLambda cenv.g vs body + // taking only a single tupled argument if necessary. REVIEW: do this earlier + let tupledv, body = MultiLambdaToTupledLambda cenv.g vs body getCallStructure tvacc (tupledv :: vacc) (body, bty) | _ -> (List.rev tvacc, List.rev vacc, e, ety) @@ -4446,19 +4446,19 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = // abstract DirectInvoke : overall-type // } // - // class ContractImplementation : Contract { + // class ContractImplementation : Contract { // override DirectInvoke : overall-type { expr } // } // // For a non-local type function closure, this becomes // - // class FunctionImplementation : FSharpTypeFunc { + // class FunctionImplementation : FSharpTypeFunc { // override Specialize : overall-type { expr } // } // // For a normal function closure, is empty, and this becomes // - // class FunctionImplementation : overall-type { + // class FunctionImplementation : overall-type { // override Invoke(..) { expr } // } @@ -4473,9 +4473,9 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = // function values. /// Compute the contract if it is a local type function - let ilContractGenericParams = GenGenericParams cenv eenvinner cloContractFreeTyvars + let ilContractGenericParams = GenGenericParams cenv eenvinner cloContractFreeTyvars let ilContractGenericActuals = GenGenericArgs m eenvouter.tyenv cloContractFreeTyvars - let ilInternalGenericParams = GenGenericParams cenv eenvinner cloInternalFreeTyvars + let ilInternalGenericParams = GenGenericParams cenv eenvinner cloInternalFreeTyvars let ilInternalGenericActuals = GenGenericArgs m eenvouter.tyenv cloInternalFreeTyvars let ilCloGenericFormals = ilContractGenericParams @ ilInternalGenericParams @@ -4485,7 +4485,7 @@ and GetIlxClosureInfo cenv m isLocalTypeFunc selfv eenvouter expr = if isLocalTypeFunc then let rec strip lambdas acc = match lambdas with - | Lambdas_forall(gp, r) -> strip r (gp::acc) + | Lambdas_forall(gp, r) -> strip r (gp::acc) | Lambdas_return returnTy -> List.rev acc, returnTy, lambdas | _ -> failwith "AdjustNamedLocalTypeFuncIlxClosureInfo: local functions can currently only be type functions" strip ilCloLambdas [] @@ -4524,9 +4524,9 @@ and IsNamedLocalTypeFuncVal g (v: Val) expr = and GenNamedLocalTypeFuncContractInfo cenv eenv m cloinfo = let ilCloTypeRef = cloinfo.cloSpec.TypeRef let ilContractTypeRef = ILTypeRef.Create(scope=ilCloTypeRef.Scope, enclosing=ilCloTypeRef.Enclosing, name=ilCloTypeRef.Name + "$contract") - let eenvForContract = EnvForTypars cloinfo.localTypeFuncContractFreeTypars eenv + let eenvForContract = EnvForTypars cloinfo.localTypeFuncContractFreeTypars eenv let ilContractGenericParams = GenGenericParams cenv eenv cloinfo.localTypeFuncContractFreeTypars - let tvs, contractRetTy = + let tvs, contractRetTy = match cloinfo.cloExpr with | Expr.TyLambda(_, tvs, _, _, bty) -> tvs, bty | e -> [], tyOfExpr cenv.g e @@ -4574,11 +4574,11 @@ and GenDelegateExpr cenv cgbuf eenvouter expr (TObjExprMethod((TSlotSig(_, deleg let numthis = 1 let tmvs, body = BindUnitVars cenv.g (tmvs, List.replicate (List.concat slotsig.FormalParams).Length ValReprInfo.unnamedTopArg1, body) - // The slot sig contains a formal instantiation. When creating delegates we're only + // The slot sig contains a formal instantiation. When creating delegates we're only // interested in the actual instantiation since we don't have to emit a method impl. let ilDelegeeParams, ilDelegeeRet = GenActualSlotsig m cenv envForDelegeeUnderTypars slotsig methTyparsOfOverridingMethod tmvs - let envForDelegeeMeth = AddStorageForLocalVals cenv.g (List.mapi (fun i v -> (v, Arg (i+numthis))) tmvs) envForDelegeeUnderTypars + let envForDelegeeMeth = AddStorageForLocalVals cenv.g (List.mapi (fun i v -> (v, Arg (i+numthis))) tmvs) envForDelegeeUnderTypars let ilMethodBody = CodeGenMethodForExpr cenv cgbuf.mgbuf (SPAlways, [], delegeeMethName, envForDelegeeMeth, 1, body, (if slotSigHasVoidReturnTy slotsig then discardAndReturnVoid else Return)) let delegeeInvokeMeth = mkILNonGenericInstanceMethod @@ -4619,11 +4619,11 @@ and GenStaticOptimization cenv cgbuf eenv (constraints, e2, e3, _m) sequel = // Generate discrimination trees //------------------------------------------------------------------------- -and IsSequelImmediate sequel = +and IsSequelImmediate sequel = match sequel with (* All of these can be done at the end of each branch - we don't need a real join point *) - | Return | ReturnVoid | Br _ | LeaveHandler _ -> true - | DiscardThen sequel -> IsSequelImmediate sequel + | Return | ReturnVoid | Br _ | LeaveHandler _ -> true + | DiscardThen sequel -> IsSequelImmediate sequel | _ -> false /// Generate a point where several branches of control flow can merge back together, e.g. after a conditional @@ -4646,7 +4646,7 @@ and GenJoinPoint cenv cgbuf pos eenv ty m sequel = // If something non-trivial happens after a discard then generate a join point, but first discard the value (often this means we won't generate it at all) | DiscardThen sequel -> - let stackAfterJoin = cgbuf.GetCurrentStack() + let stackAfterJoin = cgbuf.GetCurrentStack() let afterJoin = CG.GenerateDelayMark cgbuf (pos + "_join") DiscardThen (Br afterJoin), afterJoin, stackAfterJoin, sequel @@ -4722,7 +4722,7 @@ and GenDecisionTreeAndTargets cenv cgbuf stackAtTargets eenv tree targets repeat GenPostponedDecisionTreeTargets cenv cgbuf stackAtTargets targetInfos sequel and TryFindTargetInfo targetInfos n = - match IntMap.tryFind n targetInfos with + match IntMap.tryFind n targetInfos with | Some (targetInfo, _) -> Some targetInfo | None -> None @@ -4739,7 +4739,7 @@ and GenDecisionTreeAndTargetsInner cenv cgbuf inplabOpt stackAtTargets eenv tree let eenv = AllocStorageForBind cenv cgbuf scopeMarks eenv bind let sp = GenSequencePointForBind cenv cgbuf bind GenBindingAfterSequencePoint cenv cgbuf eenv sp bind (Some startScope) - // We don't get the scope marks quite right for dtree-bound variables. This is because + // We don't get the scope marks quite right for dtree-bound variables. This is because // we effectively lose an EndLocalScope for all dtrees that go to the same target // So we just pretend that the variable goes out of scope here. CG.SetMarkToHere cgbuf endScope @@ -4748,7 +4748,7 @@ and GenDecisionTreeAndTargetsInner cenv cgbuf inplabOpt stackAtTargets eenv tree | TDSuccess (es, targetIdx) -> GenDecisionTreeSuccess cenv cgbuf inplabOpt stackAtTargets eenv es targetIdx targets repeatSP targetInfos sequel - | TDSwitch(e, cases, dflt, m) -> + | TDSwitch(e, cases, dflt, m) -> GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases dflt m targets repeatSP targetInfos sequel and GetTarget (targets:_[]) n = @@ -4838,18 +4838,18 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau repeatSP() match cases with // optimize a test against a boolean value, i.e. the all-important if-then-else - | TCase(DecisionTreeTest.Const(Const.Bool b), successTree) :: _ -> + | TCase(DecisionTreeTest.Const(Const.Bool b), successTree) :: _ -> let failureTree = (match defaultTargetOpt with None -> cases.Tail.Head.CaseTree | Some d -> d) - GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e None eenv (if b then successTree else failureTree) (if b then failureTree else successTree) targets repeatSP targetInfos sequel + GenDecisionTreeTest cenv eenv.cloc cgbuf stackAtTargets e None eenv (if b then successTree else failureTree) (if b then failureTree else successTree) targets repeatSP targetInfos sequel // // Remove a single test for a union case . Union case tests are always exa - //| [ TCase(DecisionTreeTest.UnionCase _, successTree) ] when (defaultTargetOpt.IsNone) -> + //| [ TCase(DecisionTreeTest.UnionCase _, successTree) ] when (defaultTargetOpt.IsNone) -> // GenDecisionTreeAndTargetsInner cenv cgbuf inplabOpt stackAtTargets eenv successTree targets repeatSP targetInfos sequel // //GenDecisionTree cenv eenv.cloc cgbuf stackAtTargets e (Some (pop 1, Push [cenv.g.ilg.typ_Bool], Choice1Of2 (avoidHelpers, cuspec, idx))) eenv successTree failureTree targets repeatSP targetInfos sequel // Optimize a single test for a union case to an "isdata" test - much // more efficient code, and this case occurs in the generated equality testers where perf is important - | TCase(DecisionTreeTest.UnionCase(c, tyargs), successTree) :: rest when rest.Length = (match defaultTargetOpt with None -> 1 | Some _ -> 0) -> + | TCase(DecisionTreeTest.UnionCase(c, tyargs), successTree) :: rest when rest.Length = (match defaultTargetOpt with None -> 1 | Some _ -> 0) -> let failureTree = match defaultTargetOpt with | None -> rest.Head.CaseTree @@ -4861,7 +4861,7 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau | _ -> let caseLabels = List.map (fun _ -> CG.GenerateDelayMark cgbuf "switch_case") cases - let firstDiscrim = cases.Head.Discriminator + let firstDiscrim = cases.Head.Discriminator match firstDiscrim with // Iterated tests, e.g. exception constructors, nulltests, typetests and active patterns. // These should always have one positive and one negative branch @@ -4896,7 +4896,7 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau let cuspec = GenUnionSpec cenv.amap m eenv.tyenv hdc.TyconRef tyargs let dests = if cases.Length <> caseLabels.Length then failwith "internal error: DecisionTreeTest.UnionCase" - (cases , caseLabels) ||> List.map2 (fun case label -> + (cases, caseLabels) ||> List.map2 (fun case label -> match case with | TCase(DecisionTreeTest.UnionCase (c, _), _) -> (c.Index, label.CodeLabel) | _ -> failwith "error: mixed constructor/const test?") @@ -4904,7 +4904,7 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau let avoidHelpers = entityRefInThisAssembly cenv.g.compilingFslib hdc.TyconRef EraseUnions.emitDataSwitch cenv.g.ilg (UnionCodeGen cgbuf) (avoidHelpers, cuspec, dests) CG.EmitInstrs cgbuf (pop 1) Push0 [ ] // push/pop to match the line above - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel + GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel | DecisionTreeTest.Const c -> GenExpr cenv cgbuf eenv SPSuppress e Continue @@ -4919,7 +4919,7 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau | Const.Char _ -> if List.length cases <> List.length caseLabels then failwith "internal error: " let dests = - (cases, caseLabels) ||> List.map2 (fun case label -> + (cases, caseLabels) ||> List.map2 (fun case label -> let i = match case.Discriminator with DecisionTreeTest.Const c' -> @@ -4947,7 +4947,7 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau CG.EmitInstr cgbuf (pop 1) Push0 (I_switch destinationLabels) else error(InternalError("non-dense integer matches not implemented in codegen - these should have been removed by the pattern match compiler", switchm)) - GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel + GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel | _ -> error(InternalError("these matches should never be needed", switchm)) and GenDecisionTreeCases cenv cgbuf stackAtTargets eenv targets repeatSP targetInfos defaultTargetOpt caseLabels cases sequel = @@ -4971,7 +4971,7 @@ and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester eenv successTree match successTree, failureTree with // Peephole: if generating a boolean value or its negation then just leave it on the stack - // This comes up in the generated equality functions. REVIEW: do this as a peephole optimization elsewhere + // This comes up in the generated equality functions. REVIEW: do this as a peephole optimization elsewhere | TDSuccess(es1, n1), TDSuccess(es2, n2) when isNil es1 && isNil es2 && @@ -5013,7 +5013,7 @@ and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester eenv successTree match i with | Choice1Of2 (avoidHelpers, cuspec, idx) -> CG.EmitInstrs cgbuf pops pushes (EraseUnions.mkIsData cenv.g.ilg (avoidHelpers, cuspec, idx)) | Choice2Of2 i -> CG.EmitInstr cgbuf pops pushes i - CG.EmitInstr cgbuf (pop 1) Push0 (I_brcmp (BI_brfalse, failure.CodeLabel)) + CG.EmitInstr cgbuf (pop 1) Push0 (I_brcmp (BI_brfalse, failure.CodeLabel)) let targetInfos = GenDecisionTreeAndTargetsInner cenv cgbuf None stackAtTargets eenv successTree targets repeatSP targetInfos sequel @@ -5021,9 +5021,9 @@ and GenDecisionTreeTest cenv cloc cgbuf stackAtTargets e tester eenv successTree /// Generate fixups for letrec bindings and GenLetRecFixup cenv cgbuf eenv (ilxCloSpec: IlxClosureSpec, e, ilField: ILFieldSpec, e2, _m) = - GenExpr cenv cgbuf eenv SPSuppress e Continue + GenExpr cenv cgbuf eenv SPSuppress e Continue CG.EmitInstrs cgbuf (pop 0) Push0 [ I_castclass ilxCloSpec.ILType ] - GenExpr cenv cgbuf eenv SPSuppress e2 Continue + GenExpr cenv cgbuf eenv SPSuppress e2 Continue CG.EmitInstrs cgbuf (pop 2) Push0 [ mkNormalStfld (mkILFieldSpec(ilField.FieldRef, ilxCloSpec.ILType)) ] /// Generate letrec bindings @@ -5044,17 +5044,17 @@ and GenLetRecBindings cenv (cgbuf: CodeGenBuffer) eenv (allBinds: Bindings, m) = | Expr.Lambda _ | Expr.TyLambda _ | Expr.Obj _ -> let isLocalTypeFunc = Option.isSome selfv && (IsNamedLocalTypeFuncVal cenv.g (Option.get selfv) e) let selfv = (match e with Expr.Obj _ -> None | _ when isLocalTypeFunc -> None | _ -> Option.map mkLocalValRef selfv) - let clo, _, eenvclo = GetIlxClosureInfo cenv m isLocalTypeFunc selfv {eenv with letBoundVars=(mkLocalValRef boundv)::eenv.letBoundVars} e + let clo, _, eenvclo = GetIlxClosureInfo cenv m isLocalTypeFunc selfv {eenv with letBoundVars=(mkLocalValRef boundv)::eenv.letBoundVars} e clo.cloFreeVars |> List.iter (fun fv -> if Zset.contains fv forwardReferenceSet then match StorageForVal m fv eenvclo with | Env (_, _, ilField, _) -> fixups := (boundv, fv, (fun () -> GenLetRecFixup cenv cgbuf eenv (clo.cloSpec, access, ilField, exprForVal m fv, m))) :: !fixups | _ -> error (InternalError("GenLetRec: " + fv.LogicalName + " was not in the environment", m)) ) - | Expr.Val (vref, _, _) -> + | Expr.Val (vref, _, _) -> let fv = vref.Deref let needsFixup = Zset.contains fv forwardReferenceSet - if needsFixup then fixups := (boundv, fv, (fun () -> GenExpr cenv cgbuf eenv SPSuppress (set e) discard)) :: !fixups + if needsFixup then fixups := (boundv, fv, (fun () -> GenExpr cenv cgbuf eenv SPSuppress (set e) discard)) :: !fixups | _ -> failwith "compute real fixup vars" @@ -5078,7 +5078,7 @@ and GenLetRecBindings cenv (cgbuf: CodeGenBuffer) eenv (allBinds: Bindings, m) = // Record the variable as defined let forwardReferenceSet = Zset.remove bind.Var forwardReferenceSet // Execute and discard any fixups that can now be committed - fixups := !fixups |> List.filter (fun (boundv, fv, action) -> if (Zset.contains boundv forwardReferenceSet || Zset.contains fv forwardReferenceSet) then true else (action(); false)) + fixups := !fixups |> List.filter (fun (boundv, fv, action) -> if (Zset.contains boundv forwardReferenceSet || Zset.contains fv forwardReferenceSet) then true else (action(); false)) forwardReferenceSet) () @@ -5121,7 +5121,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s // There is no real reason we're doing this so late in the day match vspec.PublicPath, vspec.ReflectedDefinition with | Some _, Some e -> cgbuf.mgbuf.AddReflectedDefinition(vspec, e) - | _ -> () + | _ -> () let eenv = {eenv with letBoundVars= (mkLocalValRef vspec) :: eenv.letBoundVars} @@ -5150,7 +5150,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s CommitStartScope cgbuf startScopeMarkOpt GenExpr cenv cgbuf eenv SPSuppress cctorBody discard - | Method (topValInfo, _, mspec, _, paramInfos, methodArgTys, retInfo) -> + | Method (topValInfo, _, mspec, _, paramInfos, methodArgTys, retInfo) -> let tps, ctorThisValOpt, baseValOpt, vsl, body', bodyty = IteratedAdjustArityOfLambda cenv.g cenv.amap topValInfo rhsExpr let methodVars = List.concat vsl CommitStartScope cgbuf startScopeMarkOpt @@ -5184,7 +5184,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s match optShadowLocal with | NoShadowLocal -> () | ShadowLocal storage -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call (Normalcall, ilGetterMethSpec, None)) + CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call (Normalcall, ilGetterMethSpec, None)) GenSetStorage m cgbuf storage | StaticField (fspec, vref, hasLiteralAttr, ilTyForProperty, ilPropName, fty, ilGetterMethRef, ilSetterMethRef, optShadowLocal) -> @@ -5202,7 +5202,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s let ilFieldDef = match vref.LiteralValue with | Some konst -> ilFieldDef.WithLiteralDefaultValue( Some (GenFieldInit m konst) ) - | None -> ilFieldDef + | None -> ilFieldDef let ilFieldDef = let isClassInitializer = (cgbuf.MethodName = ".cctor") @@ -5261,7 +5261,7 @@ and GenBindingAfterSequencePoint cenv cgbuf eenv sp (TBind(vspec, rhsExpr, _)) s EmitSetStaticField cgbuf fspec | ShadowLocal storage-> CommitStartScope cgbuf startScopeMarkOpt - CG.EmitInstr cgbuf (pop 0) (Push [fty]) AI_dup + CG.EmitInstr cgbuf (pop 0) (Push [fty]) AI_dup EmitSetStaticField cgbuf fspec GenSetStorage m cgbuf storage @@ -5292,11 +5292,11 @@ and GenMarshal cenv attribs = attribs |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_MarshalAsAttribute >> not) match TryFindFSharpAttributeOpt cenv.g cenv.g.attrib_MarshalAsAttribute attribs with - | Some (Attrib(_, _, [ AttribInt32Arg unmanagedType ], namedArgs, _, _, m)) -> + | Some (Attrib(_, _, [ AttribInt32Arg unmanagedType ], namedArgs, _, _, m)) -> let decoder = AttributeDecoder namedArgs let rec decodeUnmanagedType unmanagedType = // enumeration values for System.Runtime.InteropServices.UnmanagedType taken from mscorlib.il - match unmanagedType with + match unmanagedType with | 0x0 -> ILNativeType.Empty | 0x01 -> ILNativeType.Void | 0x02 -> ILNativeType.Bool @@ -5372,7 +5372,7 @@ and GenMarshal cenv attribs = | "" -> None | res -> if (safeArraySubType = ILNativeVariant.IDispatch) || (safeArraySubType = ILNativeVariant.IUnknown) then Some(res) else None ILNativeType.SafeArray(safeArraySubType, safeArrayUserDefinedSubType) - | 0x1E -> ILNativeType.FixedArray (decoder.FindInt32 "SizeConst" 0x0) + | 0x1E -> ILNativeType.FixedArray (decoder.FindInt32 "SizeConst" 0x0) | 0x1F -> ILNativeType.Int | 0x20 -> ILNativeType.UInt | 0x22 -> ILNativeType.ByValStr @@ -5400,7 +5400,7 @@ and GenMarshal cenv attribs = | 0x30 -> ILNativeType.LPUTF8STR | _ -> ILNativeType.Empty Some(decodeUnmanagedType unmanagedType), otherAttribs - | Some (Attrib(_, _, _, _, _, _, m)) -> + | Some (Attrib(_, _, _, _, _, _, m)) -> errorR(Error(FSComp.SR.ilMarshalAsAttributeCannotBeDecoded(), m)) None, attribs | _ -> @@ -5424,7 +5424,7 @@ and GenParamAttribs cenv paramTy attribs = |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_OptionalAttribute >> not) |> List.filter (IsMatchingFSharpAttributeOpt cenv.g cenv.g.attrib_DefaultParameterValueAttribute >> not) - let Marshal, attribs = GenMarshal cenv attribs + let Marshal, attribs = GenMarshal cenv attribs inFlag, outFlag, optionalFlag, defaultValue, Marshal, attribs /// Generate IL parameters @@ -5491,7 +5491,7 @@ and GenReturnInfo cenv eenv ilRetTy (retInfo: ArgReprInfo) : ILReturn = /// Generate an IL property for a member and GenPropertyForMethodDef compileAsInstance tref mdef (v: Val) (memberInfo: ValMemberInfo) ilArgTys ilPropTy ilAttrs compiledName = - let name = match compiledName with | Some n -> n | _ -> v.PropertyName in (* chop "get_" *) + let name = match compiledName with | Some n -> n | _ -> v.PropertyName in (* chop "get_" *) ILPropertyDef(name = name, attributes = PropertyAttributes.None, @@ -5509,7 +5509,7 @@ and GenEventForProperty cenv eenvForMeth (mspec: ILMethodSpec) (v: Val) ilAttrsT let delegateTy = Infos.FindDelegateTypeOfPropertyEvent cenv.g cenv.amap evname m returnTy let ilDelegateTy = GenType cenv.amap m eenvForMeth.tyenv delegateTy let ilThisTy = mspec.DeclaringType - let addMethRef = mkILMethRef (ilThisTy.TypeRef, mspec.CallingConv, "add_" + evname, 0, [ilDelegateTy], ILType.Void) + let addMethRef = mkILMethRef (ilThisTy.TypeRef, mspec.CallingConv, "add_" + evname, 0, [ilDelegateTy], ILType.Void) let removeMethRef = mkILMethRef (ilThisTy.TypeRef, mspec.CallingConv, "remove_" + evname, 0, [ilDelegateTy], ILType.Void) ILEventDef(eventType = Some ilDelegateTy, name= evname, @@ -5559,7 +5559,7 @@ and ComputeFlagFixupsForMemberBinding cenv (v: Val, memberInfo: ValMemberInfo) = and ComputeMethodImplAttribs cenv (_v: Val) attrs = let implflags = match TryFindFSharpAttribute cenv.g cenv.g.attrib_MethodImplAttribute attrs with - | Some (Attrib(_, _, [ AttribInt32Arg flags ], _, _, _, _)) -> flags + | Some (Attrib(_, _, [ AttribInt32Arg flags ], _, _, _, _)) -> flags | _ -> 0x0 let hasPreserveSigAttr = @@ -5595,7 +5595,7 @@ and GenMethodForBinding match methodVars with | [] -> error(InternalError("Internal error: empty argument list for instance method", v.Range)) | h::t -> [h], t, true - | _ -> [], methodVars, false + | _ -> [], methodVars, false let nonUnitNonSelfMethodVars, body = BindUnitVars cenv.g (nonSelfMethodVars, paramInfos, body) let nonUnitMethodVars = selfMethodVars@nonUnitNonSelfMethodVars @@ -5609,7 +5609,7 @@ and GenMethodForBinding let eenvUnderMethLambdaTypars = EnvForTypars tps eenv let eenvUnderMethTypeTypars = EnvForTypars cmtps eenv - // Add the arguments to the environment. We add an implicit 'this' argument to constructors + // Add the arguments to the environment. We add an implicit 'this' argument to constructors let isCtor = v.IsConstructor let eenvForMeth = let eenvForMeth = eenvUnderMethLambdaTypars @@ -5628,12 +5628,12 @@ and GenMethodForBinding // Now generate the code. let hasPreserveSigNamedArg, ilMethodBody, hasDllImport = match TryFindFSharpAttributeOpt cenv.g cenv.g.attrib_DllImportAttribute v.Attribs with - | Some (Attrib(_, _, [ AttribStringArg(dll) ], namedArgs, _, _, m)) -> + | Some (Attrib(_, _, [ AttribStringArg(dll) ], namedArgs, _, _, m)) -> if not (isNil tps) then error(Error(FSComp.SR.ilSignatureForExternalFunctionContainsTypeParameters(), m)) let hasPreserveSigNamedArg, mbody = GenPInvokeMethod (v.CompiledName, dll, namedArgs) hasPreserveSigNamedArg, mbody, true - | Some (Attrib(_, _, _, _, _, _, m)) -> + | Some (Attrib(_, _, _, _, _, _, m)) -> error(Error(FSComp.SR.ilDllImportAttributeCouldNotBeDecoded(), m)) | _ -> @@ -5663,7 +5663,7 @@ and GenMethodForBinding let sourceNameAttribs, compiledName = match v.Attribs |> List.tryFind (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_CompiledNameAttribute) with - | Some (Attrib(_, _, [ AttribStringArg(b) ], _, _, _, _)) -> [ mkCompilationSourceNameAttr cenv.g v.LogicalName ], Some b + | Some (Attrib(_, _, [ AttribStringArg(b) ], _, _, _, _)) -> [ mkCompilationSourceNameAttr cenv.g v.LogicalName ], Some b | _ -> [], None // check if the hasPreserveSigNamedArg and hasSynchronizedImplFlag implementation flags have been specified @@ -5676,7 +5676,7 @@ and GenMethodForBinding let secDecls = if List.isEmpty securityAttributes then emptyILSecurityDecls else mkILSecurityDecls permissionSets // Do not push the attributes to the method for events and properties - let ilAttrsCompilerGenerated = if v.IsCompilerGenerated then [ cenv.g.CompilerGeneratedAttribute ] else [] + let ilAttrsCompilerGenerated = if v.IsCompilerGenerated then [ cenv.g.CompilerGeneratedAttribute ] else [] let ilAttrsThatGoOnPrimaryItem = [ yield! GenAttrs cenv eenv attrs @@ -5757,7 +5757,7 @@ and GenMethodForBinding let isAbstract = memberInfo.MemberFlags.IsDispatchSlot && - let tcref = v.MemberApparentEntity + let tcref = v.MemberApparentEntity not tcref.Deref.IsFSharpDelegateTycon let mdef = @@ -5767,12 +5767,12 @@ and GenMethodForBinding match memberInfo.MemberFlags.MemberKind with - | (MemberKind.PropertySet | MemberKind.PropertyGet) -> + | (MemberKind.PropertySet | MemberKind.PropertyGet) -> if not (isNil ilMethTypars) then error(InternalError("A property may not be more generic than the enclosing type - constrain the polymorphism in the expression", v.Range)) // Check if we're compiling the property as a .NET event - if CompileAsEvent cenv.g v.Attribs then + if CompileAsEvent cenv.g v.Attribs then // Emit the pseudo-property as an event, but not if its a private method impl if mdef.Access <> ILMemberAccess.Private then @@ -5804,7 +5804,7 @@ and GenMethodForBinding match v.MemberInfo with | Some memberInfo when v.IsExtensionMember -> match memberInfo.MemberFlags.MemberKind with - | (MemberKind.PropertySet | MemberKind.PropertyGet) -> ilAttrsThatGoOnPrimaryItem @ GenAttrs cenv eenv attrsAppliedToGetterOrSetter + | (MemberKind.PropertySet | MemberKind.PropertyGet) -> ilAttrsThatGoOnPrimaryItem @ GenAttrs cenv eenv attrsAppliedToGetterOrSetter | _ -> ilAttrsThatGoOnPrimaryItem | _ -> ilAttrsThatGoOnPrimaryItem @@ -5834,7 +5834,7 @@ and GenPInvokeMethod (nm, dll, namedArgs) = | 2 -> PInvokeCharEncoding.Ansi | 3 -> PInvokeCharEncoding.Unicode | 4 -> PInvokeCharEncoding.Auto - | _ -> PInvokeCharEncoding.None + | _ -> PInvokeCharEncoding.None NoMangle= decoder.FindBool "ExactSpelling" false LastError= decoder.FindBool "SetLastError" false ThrowOnUnmappableChar= if (decoder.FindBool "ThrowOnUnmappableChar" false) then PInvokeThrowOnUnmappableChar.Enabled else PInvokeThrowOnUnmappableChar.UseAssembly @@ -5859,7 +5859,7 @@ and GenSetVal cenv cgbuf eenv (vref, e, m) sequel = 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 + 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 = GenGetValRefAndSequel cenv cgbuf eenv m v None @@ -5893,7 +5893,7 @@ and CommitStartScope cgbuf startScopeMarkOpt = | None -> () | Some ss -> cgbuf.SetMarkToHere(ss) -and EmitInitLocal cgbuf ty idx = CG.EmitInstrs cgbuf (pop 0) Push0 [I_ldloca (uint16 idx); (I_initobj ty) ] +and EmitInitLocal cgbuf ty idx = CG.EmitInstrs cgbuf (pop 0) Push0 [I_ldloca (uint16 idx); (I_initobj ty) ] and EmitSetLocal cgbuf idx = CG.EmitInstr cgbuf (pop 1) Push0 (mkStloc (uint16 idx)) @@ -5912,7 +5912,7 @@ and GenSetStorage m cgbuf storage = | StaticField (_, _, hasLiteralAttr, ilContainerTy, _, _, _, ilSetterMethRef, _) -> if hasLiteralAttr then errorR(Error(FSComp.SR.ilLiteralFieldsCannotBeSet(), m)) - CG.EmitInstr cgbuf (pop 1) Push0 (I_call(Normalcall, mkILMethSpecForMethRefInTy(ilSetterMethRef, ilContainerTy, []), None)) + CG.EmitInstr cgbuf (pop 1) Push0 (I_call(Normalcall, mkILMethSpecForMethRefInTy(ilSetterMethRef, ilContainerTy, []), None)) | StaticProperty (ilGetterMethSpec, _) -> error(Error(FSComp.SR.ilStaticMethodIsNotLambda(ilGetterMethSpec.Name), m)) @@ -5928,7 +5928,7 @@ and GenSetStorage m cgbuf storage = | Env (_, _, ilField, _) -> // Note: ldarg0 has already been emitted in GenSetVal - CG.EmitInstr cgbuf (pop 2) Push0 (mkNormalStfld ilField) + CG.EmitInstr cgbuf (pop 2) Push0 (mkNormalStfld ilField) and CommitGetStorageSequel cenv cgbuf eenv m ty localCloInfo storeSequel = match localCloInfo, storeSequel with @@ -5953,11 +5953,11 @@ and GenGetStorageAndSequel cenv cgbuf eenv m (ty, ilTy) storage storeSequel = if hasLiteralAttr then EmitGetStaticField cgbuf ilTy fspec else - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call(Normalcall, mkILMethSpecForMethRefInTy (ilGetterMethRef, ilContainerTy, []), None)) + CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call(Normalcall, mkILMethSpecForMethRefInTy (ilGetterMethRef, ilContainerTy, []), None)) CommitGetStorageSequel cenv cgbuf eenv m ty None storeSequel | StaticProperty (ilGetterMethSpec, _) -> - CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call (Normalcall, ilGetterMethSpec, None)) + CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (I_call (Normalcall, ilGetterMethSpec, None)) CommitGetStorageSequel cenv cgbuf eenv m ty None storeSequel | Method (topValInfo, vref, mspec, _, _, _, _) -> @@ -5980,7 +5980,7 @@ and GenGetStorageAndSequel cenv cgbuf eenv m (ty, ilTy) storage storeSequel = MakeApplicationAndBetaReduce cenv.g (expr, exprty, [tyargs'], args, m) GenExpr cenv cgbuf eenv SPSuppress specializedExpr sequel - | Null -> + | Null -> CG.EmitInstr cgbuf (pop 0) (Push [ilTy]) (AI_ldnull) CommitGetStorageSequel cenv cgbuf eenv m ty None storeSequel @@ -6015,7 +6015,7 @@ and AllocLocal cenv cgbuf eenv compgen (v, ty, isFixed) (scopeMarks: Mark * Mark cgbuf.ReallocLocal((fun i (_, ty', isFixed') -> not isFixed' && not isFixed && not (IntMap.mem i eenv.liveLocals) && (ty = ty')), ranges, ty, isFixed) else cgbuf.AllocLocal(ranges, ty, isFixed), false - j, realloc, { eenv with liveLocals = IntMap.add j () eenv.liveLocals } + j, realloc, { eenv with liveLocals = IntMap.add j () eenv.liveLocals } /// Decide storage for local value and if necessary allocate an ILLocal for it and AllocLocalVal cenv cgbuf v eenv repr scopeMarks = @@ -6103,7 +6103,7 @@ and AllocTopValWithinExpr cenv cgbuf cloc scopeMarks v eenv = /// Save the stack /// - [gross] because IL flushes the stack at the exn. handler -/// - and because IL requires empty stack following a forward br (jump). +/// - and because IL requires empty stack following a forward br (jump). and EmitSaveStack cenv cgbuf eenv m scopeMarks = let savedStack = (cgbuf.GetCurrentStack()) let savedStackLocals, eenvinner = @@ -6128,7 +6128,7 @@ and GenAttribArg amap g eenv x (ilArgTy: ILType) = match x, ilArgTy with // Detect 'null' used for an array argument - | Expr.Const(Const.Zero, _, _), ILType.Array _ -> + | Expr.Const(Const.Zero, _, _), ILType.Array _ -> ILAttribElem.Null // Detect standard constants @@ -6138,28 +6138,28 @@ and GenAttribArg amap g eenv x (ilArgTy: ILType) = match c with | Const.Bool b -> ILAttribElem.Bool b - | Const.Int32 i when isobj || tynm = "System.Int32" -> ILAttribElem.Int32 ( i) - | Const.Int32 i when tynm = "System.SByte" -> ILAttribElem.SByte (sbyte i) - | Const.Int32 i when tynm = "System.Int16" -> ILAttribElem.Int16 (int16 i) - | Const.Int32 i when tynm = "System.Byte" -> ILAttribElem.Byte (byte i) + | Const.Int32 i when isobj || tynm = "System.Int32" -> ILAttribElem.Int32 ( i) + | Const.Int32 i when tynm = "System.SByte" -> ILAttribElem.SByte (sbyte i) + | Const.Int32 i when tynm = "System.Int16" -> ILAttribElem.Int16 (int16 i) + | Const.Int32 i when tynm = "System.Byte" -> ILAttribElem.Byte (byte i) | Const.Int32 i when tynm = "System.UInt16" ->ILAttribElem.UInt16 (uint16 i) | Const.Int32 i when tynm = "System.UInt32" ->ILAttribElem.UInt32 (uint32 i) | Const.Int32 i when tynm = "System.UInt64" ->ILAttribElem.UInt64 (uint64 (int64 i)) - | Const.SByte i -> ILAttribElem.SByte i - | Const.Int16 i -> ILAttribElem.Int16 i - | Const.Int32 i -> ILAttribElem.Int32 i - | Const.Int64 i -> ILAttribElem.Int64 i - | Const.Byte i -> ILAttribElem.Byte i - | Const.UInt16 i -> ILAttribElem.UInt16 i - | Const.UInt32 i -> ILAttribElem.UInt32 i - | Const.UInt64 i -> ILAttribElem.UInt64 i - | Const.Double i -> ILAttribElem.Double i + | Const.SByte i -> ILAttribElem.SByte i + | Const.Int16 i -> ILAttribElem.Int16 i + | Const.Int32 i -> ILAttribElem.Int32 i + | Const.Int64 i -> ILAttribElem.Int64 i + | Const.Byte i -> ILAttribElem.Byte i + | Const.UInt16 i -> ILAttribElem.UInt16 i + | Const.UInt32 i -> ILAttribElem.UInt32 i + | Const.UInt64 i -> ILAttribElem.UInt64 i + | Const.Double i -> ILAttribElem.Double i | Const.Single i -> ILAttribElem.Single i - | Const.Char i -> ILAttribElem.Char i - | Const.Zero when isobj -> ILAttribElem.Null - | Const.Zero when tynm = "System.String" -> ILAttribElem.String None - | Const.Zero when tynm = "System.Type" -> ILAttribElem.Type None - | Const.String i when isobj || tynm = "System.String" -> ILAttribElem.String (Some i) + | Const.Char i -> ILAttribElem.Char i + | Const.Zero when isobj -> ILAttribElem.Null + | Const.Zero when tynm = "System.String" -> ILAttribElem.String None + | Const.Zero when tynm = "System.Type" -> ILAttribElem.Type None + | Const.String i when isobj || tynm = "System.String" -> ILAttribElem.String (Some i) | _ -> error (InternalError ( "The type '" + tynm + "' may not be used as a custom attribute value", m)) // Detect '[| ... |]' nodes @@ -6168,11 +6168,11 @@ and GenAttribArg amap g eenv x (ilArgTy: ILType) = ILAttribElem.Array (ilElemTy, List.map (fun arg -> GenAttribArg amap g eenv arg ilElemTy) args) // Detect 'typeof' calls - | TypeOfExpr g ty, _ -> + | TypeOfExpr g ty, _ -> ILAttribElem.Type (Some (GenType amap x.Range eenv.tyenv ty)) // Detect 'typedefof' calls - | TypeDefOfExpr g ty, _ -> + | TypeDefOfExpr g ty, _ -> ILAttribElem.TypeRef (Some (GenType amap x.Range eenv.tyenv ty).TypeRef) // Ignore upcasts @@ -6198,7 +6198,7 @@ and GenAttribArg amap g eenv x (ilArgTy: ILType) = | ILAttribElem.UInt16 i1, ILAttribElem.UInt16 i2-> ILAttribElem.UInt16 (i1 ||| i2) | ILAttribElem.UInt32 i1, ILAttribElem.UInt32 i2-> ILAttribElem.UInt32 (i1 ||| i2) | ILAttribElem.UInt64 i1, ILAttribElem.UInt64 i2-> ILAttribElem.UInt64 (i1 ||| i2) - | _ -> error (InternalError ("invalid custom attribute value (not a valid constant): " + showL (exprL x), x.Range)) + | _ -> error (InternalError ("invalid custom attribute value (not a valid constant): " + showL (exprL x), x.Range)) // Other expressions are not valid custom attribute values | _ -> @@ -6230,7 +6230,7 @@ and GenCompilationArgumentCountsAttr cenv (v: Val) = let arities = if ValSpecIsCompiledAsInstance cenv.g v then List.tail tvi.AritiesOfArgs else tvi.AritiesOfArgs if arities.Length > 1 then yield mkCompilationArgumentCountsAttr cenv.g arities - | _ -> + | _ -> () ] // Create a permission set for a list of security attributes @@ -6252,7 +6252,7 @@ and CreatePermissionSets cenv eenv (securityAttributes: Attrib list) = //-------------------------------------------------------------------------- /// Generate a static class at the given cloc -and GenTypeDefForCompLoc (cenv, eenv, mgbuf: AssemblyBuilder, cloc, hidden, attribs, initTrigger, eliminateIfEmpty, addAtEnd) = +and GenTypeDefForCompLoc (cenv, eenv, mgbuf: AssemblyBuilder, cloc, hidden, attribs, initTrigger, eliminateIfEmpty, addAtEnd) = let tref = TypeRefForCompLoc cloc let tdef = mkILSimpleClass cenv.g.ilg @@ -6273,11 +6273,11 @@ and GenTypeDefForCompLoc (cenv, eenv, mgbuf: AssemblyBuilder, cloc, hidden, attr mgbuf.AddTypeDef(tref, tdef, eliminateIfEmpty, addAtEnd, None) -and GenModuleExpr cenv cgbuf qname lazyInitInfo eenv x = +and GenModuleExpr cenv cgbuf qname lazyInitInfo eenv x = let (ModuleOrNamespaceExprWithSig(mty, def, _)) = x // REVIEW: the scopeMarks are used for any shadow locals we create for the module bindings // We use one scope for all the bindings in the module, which makes them all appear with their "default" values - // rather than incrementally as we step through the initializations in the module. This is a little unfortunate + // rather than incrementally as we step through the initializations in the module. This is a little unfortunate // but stems from the way we add module values all at once before we generate the module itself. LocalScope "module" cgbuf (fun scopeMarks -> let sigToImplRemapInfo = ComputeRemappingFromImplementationToSignature cenv.g def mty @@ -6288,10 +6288,10 @@ and GenModuleExpr cenv cgbuf qname lazyInitInfo eenv x = AddBindingsForModuleDef allocVal eenv.cloc eenv def GenModuleDef cenv cgbuf qname lazyInitInfo eenv def) -and GenModuleDefs cenv cgbuf qname lazyInitInfo eenv mdefs = +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 -> @@ -6310,7 +6310,7 @@ and GenModuleDef cenv (cgbuf: CodeGenBuffer) qname lazyInitInfo eenv x = GenModuleExpr cenv cgbuf qname lazyInitInfo eenv mexpr | TMDefs(mdefs) -> - GenModuleDefs cenv cgbuf qname lazyInitInfo eenv mdefs + GenModuleDefs cenv cgbuf qname lazyInitInfo eenv mdefs // Generate a module binding @@ -6326,7 +6326,7 @@ and GenModuleBinding cenv (cgbuf: CodeGenBuffer) (qname: QualifiedNameOfFile) la if mspec.IsNamespace then eenv else {eenv with cloc = CompLocForFixedModule cenv.opts.fragName qname.Text mspec } - // Create the class to hold the contents of this module. No class needed if + // Create the class to hold the contents of this module. No class needed if // we're compiling it as a namespace. // // Most module static fields go into the "InitClass" static class. @@ -6351,7 +6351,7 @@ and GenModuleBinding cenv (cgbuf: CodeGenBuffer) (qname: QualifiedNameOfFile) la /// Generate the namespace fragments in a single file -and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, _, mexpr, hasExplicitEntryPoint, isScript, anonRecdTypes), optimizeDuringCodeGen) = +and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, _, mexpr, hasExplicitEntryPoint, isScript, anonRecdTypes), optimizeDuringCodeGen) = let m = qname.Range @@ -6409,7 +6409,7 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, CG.EmitInstr cgbuf (pop 0) Push0 I_ret), m) // The code generation for the initialization is now complete and the IL code is in topCode. - // Make a .cctor and/or main method to contain the code. This initializes all modules. + // Make a .cctor and/or main method to contain the code. This initializes all modules. // Library file (mainInfoOpt = None) : optional .cctor if topCode has initialization effect // Final file, explicit entry point (mainInfoOpt = Some _, GetExplicitEntryPointInfo() = Some) : main + optional .cctor if topCode has initialization effect // Final file, implicit entry point (mainInfoOpt = Some _, GetExplicitEntryPointInfo() = None) : main + initialize + optional .cctor calling initialize @@ -6470,7 +6470,7 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, if doesSomething then // Add the cctor - let cctorMethDef = mkILClassCtor (MethodBody.IL topCode) + let cctorMethDef = mkILClassCtor (MethodBody.IL topCode) mgbuf.AddMethodDef(initClassTy.TypeRef, cctorMethDef) @@ -6503,7 +6503,7 @@ and GenTopImpl cenv (mgbuf: AssemblyBuilder) mainInfoOpt eenv (TImplFile(qname, // We add the module type all over again. Note no shadow locals for static fields needed here since they are only relevant to the main/.cctor let eenvafter = let allocVal = ComputeAndAddStorageForLocalTopVal (cenv.amap, cenv.g, cenv.intraAssemblyInfo, cenv.opts.isInteractive, NoShadowLocal) - AddBindingsForLocalModuleType allocVal clocCcu eenv mexpr.Type + AddBindingsForLocalModuleType allocVal clocCcu eenv mexpr.Type eenvafter @@ -6624,7 +6624,7 @@ and GenToStringMethod cenv eenv ilThisTy m = // call the function returned by sprintf yield mkLdarg0 if ilThisTy.Boxity = ILBoxity.AsValue then - yield mkNormalLdobj ilThisTy ] @ + yield mkNormalLdobj ilThisTy ] @ callInstrs), None)) let mdef = mdef.With(customAttrs = mkILCustomAttrs [ cenv.g.CompilerGeneratedAttribute ]) @@ -6645,15 +6645,15 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let eenvinner = ReplaceTyenv (TypeReprEnv.ForTycon tycon) eenv let thisTy = generalizedTyconRef tcref - let ilThisTy = GenType cenv.amap m eenvinner.tyenv thisTy + let ilThisTy = GenType cenv.amap m eenvinner.tyenv thisTy let tref = ilThisTy.TypeRef - let ilGenParams = GenGenericParams cenv eenvinner tycon.TyparsNoRange - let ilIntfTys = tycon.ImmediateInterfaceTypesOfFSharpTycon |> List.map (GenType cenv.amap m eenvinner.tyenv) - let ilTypeName = tref.Name + let ilGenParams = GenGenericParams cenv eenvinner tycon.TyparsNoRange + let ilIntfTys = tycon.ImmediateInterfaceTypesOfFSharpTycon |> List.map (GenType cenv.amap m eenvinner.tyenv) + let ilTypeName = tref.Name - let hidden = IsHiddenTycon eenv.sigToImplRemapInfo tycon + let hidden = IsHiddenTycon eenv.sigToImplRemapInfo tycon let hiddenRepr = hidden || IsHiddenTyconRepr eenv.sigToImplRemapInfo tycon - let access = ComputeTypeAccess tref hidden + let access = ComputeTypeAccess tref hidden // The implicit augmentation doesn't actually create CompareTo(object) or Object.Equals // So we do it here. @@ -6689,12 +6689,12 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let abstractPropDefs = abstractPropDefs |> MergePropertyDefs m - let isAbstract = isAbstractTycon tycon + let isAbstract = isAbstractTycon tycon // Generate all the method impls showing how various abstract slots and interface slots get implemented // REVIEW: no method impl generated for IStructuralHash or ICompare let methodImpls = - [ for vref in tycon.MembersOfFSharpTyconByName |> NameMultiMap.range do + [ for vref in tycon.MembersOfFSharpTyconByName |> NameMultiMap.range do assert(vref.IsMember) let memberInfo = vref.MemberInfo.Value if memberInfo.MemberFlags.IsOverrideOrExplicitImpl && not (CompileAsEvent cenv.g vref.Attribs) then @@ -6729,7 +6729,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = | None -> None | Some memberInfo -> match name, memberInfo.MemberFlags.MemberKind with - | ("Item" | "op_IndexedLookup"), (MemberKind.PropertyGet | MemberKind.PropertySet) when not (isNil (ArgInfosOfPropertyVal cenv.g vref.Deref)) -> + | ("Item" | "op_IndexedLookup"), (MemberKind.PropertyGet | MemberKind.PropertySet) when not (isNil (ArgInfosOfPropertyVal cenv.g vref.Deref)) -> Some( mkILCustomAttribute cenv.g.ilg (cenv.g.FindSysILTypeRef "System.Reflection.DefaultMemberAttribute", [cenv.g.ilg.typ_String], [ILAttribElem.String(Some(name))], []) ) | _ -> None) |> Option.toList @@ -6749,7 +6749,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let ilDebugDisplayAttributes = [ yield! GenAttrs cenv eenv debugDisplayAttrs if generateDebugDisplayAttribute then - yield cenv.g.mkDebuggerDisplayAttribute ("{" + debugDisplayMethodName + "(),nq}") ] + yield cenv.g.mkDebuggerDisplayAttribute ("{" + debugDisplayMethodName + "(),nq}") ] let ilCustomAttrs = @@ -6757,19 +6757,19 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = yield! normalAttrs |> List.filter (IsMatchingFSharpAttribute cenv.g cenv.g.attrib_StructLayoutAttribute >> not) |> GenAttrs cenv eenv - yield! ilDebugDisplayAttributes ] + yield! ilDebugDisplayAttributes ] let reprAccess = ComputeMemberAccess hiddenRepr let ilTypeDefKind = - match tyconRepr with + match tyconRepr with | TFSharpObjectRepr o -> match o.fsobjmodel_kind with - | TTyconClass -> ILTypeDefKind.Class - | TTyconStruct -> ILTypeDefKind.ValueType - | TTyconInterface -> ILTypeDefKind.Interface - | TTyconEnum -> ILTypeDefKind.Enum + | TTyconClass -> ILTypeDefKind.Class + | TTyconStruct -> ILTypeDefKind.ValueType + | TTyconInterface -> ILTypeDefKind.Interface + | TTyconEnum -> ILTypeDefKind.Enum | TTyconDelegate _ -> ILTypeDefKind.Delegate | TRecdRepr _ | TUnionRepr _ when tycon.IsStructOrEnumTycon -> ILTypeDefKind.ValueType | _ -> ILTypeDefKind.Class @@ -6784,7 +6784,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = isEmptyStruct && cenv.opts.workAroundReflectionEmitBugs && not tycon.TyparsNoRange.IsEmpty // Compute a bunch of useful things for each field - let isCLIMutable = (TryFindFSharpBoolAttribute cenv.g cenv.g.attrib_CLIMutableAttribute tycon.Attribs = Some true) + let isCLIMutable = (TryFindFSharpBoolAttribute cenv.g cenv.g.attrib_CLIMutableAttribute tycon.Attribs = Some true) let fieldSummaries = [ for fspec in tycon.AllFieldsArray do @@ -6812,9 +6812,9 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let ilFieldOffset = match TryFindFSharpAttribute cenv.g cenv.g.attrib_FieldOffsetAttribute fspec.FieldAttribs with - | Some (Attrib(_, _, [ AttribInt32Arg(fieldOffset) ], _, _, _, _)) -> + | Some (Attrib(_, _, [ AttribInt32Arg(fieldOffset) ], _, _, _, _)) -> Some fieldOffset - | Some (Attrib(_, _, _, _, _, _, m)) -> + | Some (Attrib(_, _, _, _, _, _, m)) -> errorR(Error(FSComp.SR.ilFieldOffsetAttributeCouldNotBeDecoded(), m)) None | _ -> @@ -6852,14 +6852,14 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let literalValue = Option.map (GenFieldInit m) fspec.LiteralValue let fdef = - ILFieldDef(name = ilFieldName, - fieldType = ilPropType, - attributes = enum 0, - data = None, - literalValue = None, - offset = ilFieldOffset, - marshal = None, - customAttrs = mkILCustomAttrs (GenAttrs cenv eenv fattribs @ extraAttribs)) + ILFieldDef(name = ilFieldName, + fieldType = ilPropType, + attributes = enum 0, + data = None, + literalValue = None, + offset = ilFieldOffset, + marshal = None, + customAttrs = mkILCustomAttrs (GenAttrs cenv eenv fattribs @ extraAttribs)) .WithAccess(access) .WithStatic(isStatic) .WithSpecialName(ilFieldName="value__" && tycon.IsEnumTycon) @@ -6888,7 +6888,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = propertyType= ilPropType, init= None, args= [], - customAttrs = mkILCustomAttrs ilFieldAttrs) ] + customAttrs = mkILCustomAttrs ilFieldAttrs) ] let methodDefs = [ // Generate property getter methods for those fields that have properties @@ -6954,7 +6954,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = // call the function returned by sprintf yield mkLdarg0 if ilThisTy.Boxity = ILBoxity.AsValue then - yield mkNormalLdobj ilThisTy ] @ + yield mkNormalLdobj ilThisTy ] @ callInstrs), None)) yield ilMethodDef.WithSpecialName |> AddNonUserCompilerGeneratedAttribs cenv.g @@ -6989,7 +6989,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let ilMethodDef = mkILSimpleStorageCtorWithParamNames(None, spec, ilThisTy, [], ChooseParamNames fieldNamesAndTypes, reprAccess) yield ilMethodDef - // FSharp 1.0 bug 1988: Explicitly setting the ComVisible(true) attribute on an F# type causes an F# record to be emitted in a way that enables mutation for COM interop scenarios + // FSharp 1.0 bug 1988: Explicitly setting the ComVisible(true) attribute on an F# type causes an F# record to be emitted in a way that enables mutation for COM interop scenarios // FSharp 3.0 feature: adding CLIMutable to a record type causes emit of default constructor, and all fields get property setters // Records that are value types do not create a default constructor with CLIMutable or ComVisible if not isStructRecord && (isCLIMutable || (TryFindFSharpBoolAttribute cenv.g cenv.g.attrib_ComVisibleAttribute tycon.Attribs = Some true)) then @@ -7032,7 +7032,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let tdef = tdef.With(customAttrs = mkILCustomAttrs ilCustomAttrs, genericParams = ilGenParams) tdef, None - | TRecdRepr _ | TFSharpObjectRepr _ as tyconRepr -> + | TRecdRepr _ | TFSharpObjectRepr _ as tyconRepr -> let super = superOfTycon cenv.g tycon let ilBaseTy = GenType cenv.amap m eenvinner.tyenv super @@ -7075,7 +7075,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = let tdLayout, tdEncoding = match TryFindFSharpAttribute cenv.g cenv.g.attrib_StructLayoutAttribute tycon.Attribs with - | Some (Attrib(_, _, [ AttribInt32Arg(layoutKind) ], namedArgs, _, _, _)) -> + | Some (Attrib(_, _, [ AttribInt32Arg(layoutKind) ], namedArgs, _, _, _)) -> let decoder = AttributeDecoder namedArgs let ilPack = decoder.FindInt32 "Pack" 0x0 let ilSize = decoder.FindInt32 "Size" 0x0 @@ -7096,7 +7096,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = | 0x2 -> ILTypeDefLayout.Explicit layoutInfo | _ -> ILTypeDefLayout.Auto tdLayout, tdEncoding - | Some (Attrib(_, _, _, _, _, _, m)) -> + | Some (Attrib(_, _, _, _, _, _, m)) -> errorR(Error(FSComp.SR.ilStructLayoutAttributeCouldNotBeDecoded(), m)) ILTypeDefLayout.Auto, ILDefaultPInvokeEncoding.Ansi @@ -7171,7 +7171,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = else SourceConstructFlags.SumType)) ]) let tdef = ILTypeDef(name = ilTypeName, - layout = layout, + layout = layout, attributes = enum 0, genericParams = ilGenParams, customAttrs = cattrs, @@ -7204,7 +7204,7 @@ and GenTypeDef cenv mgbuf lazyInitInfo eenv m (tycon: Tycon) = (cuinfo.cudHasHelpers = SpecialFSharpOptionHelpers && (md.Name = "get_Value" || md.Name = "get_None" || md.Name = "Some"))), (fun (pd: ILPropertyDef) -> - (cuinfo.cudHasHelpers = SpecialFSharpListHelpers && (pd.Name = "Empty" || pd.Name = "IsEmpty" )) || + (cuinfo.cudHasHelpers = SpecialFSharpListHelpers && (pd.Name = "Empty" || pd.Name = "IsEmpty" )) || (cuinfo.cudHasHelpers = SpecialFSharpOptionHelpers && (pd.Name = "Value" || pd.Name = "None")))) tdef2, tdefDiscards @@ -7228,7 +7228,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) = - let exncref = mkLocalEntityRef exnc + let exncref = mkLocalEntityRef exnc match exnc.ExceptionInfo with | TExnAbbrevRepr _ | TExnAsmRepr _ | TExnNone -> () | TExnFresh _ -> @@ -7284,8 +7284,8 @@ and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = [ mkLdarg0 mkLdarg 1us mkLdarg 2us - mkNormalCall (mkILCtorMethSpecForTy (cenv.g.iltyp_Exception, [serializationInfoType; streamingContextType])) ] - , None)) + mkNormalCall (mkILCtorMethSpecForTy (cenv.g.iltyp_Exception, [serializationInfoType; streamingContextType])) ], + None)) //#if BE_SECURITY_TRANSPARENT [ilCtorDefForSerialziation] @@ -7321,7 +7321,7 @@ and GenExnDef cenv mgbuf eenv m (exnc: Tycon) = let ilTypeName = tref.Name - let interfaces = exnc.ImmediateInterfaceTypesOfFSharpTycon |> List.map (GenType cenv.amap m eenv.tyenv) + let interfaces = exnc.ImmediateInterfaceTypesOfFSharpTycon |> List.map (GenType cenv.amap m eenv.tyenv) let tdef = mkILGenericClass (ilTypeName, access, [], cenv.g.iltyp_Exception, @@ -7343,7 +7343,7 @@ let CodegenAssembly cenv eenv mgbuf fileImpls = let eenv = List.fold (GenTopImpl cenv mgbuf None) eenv a let eenv = GenTopImpl cenv mgbuf cenv.opts.mainMethodInfo eenv b - // Some constructs generate residue types and bindings. Generate these now. They don't result in any + // Some constructs generate residue types and bindings. Generate these now. They don't result in any // top-level initialization code. begin let extraBindings = mgbuf.GrabExtraBindingsToGenerate() @@ -7570,7 +7570,7 @@ type IlxAssemblyGenerator(amap: ImportMap, tcGlobals: TcGlobals, tcVal: Constrai /// Register a fragment of the current assembly with the ILX code generator. If 'isIncrementalFragment' is true then the input /// is assumed to be a fragment 'typed' into FSI.EXE, otherwise the input is assumed to be the result of a '#load' - member __.AddIncrementalLocalAssemblyFragment (isIncrementalFragment, fragName, typedImplFiles) = + member __.AddIncrementalLocalAssemblyFragment (isIncrementalFragment, fragName, typedImplFiles) = ilxGenEnv <- AddIncrementalLocalAssemblyFragmentToIlxGenEnv (amap, isIncrementalFragment, tcGlobals, ccu, fragName, intraAssemblyInfo, ilxGenEnv, typedImplFiles) /// Generate ILX code for an assembly fragment diff --git a/src/fsharp/InfoReader.fs b/src/fsharp/InfoReader.fs index 1c5525722e0..2a2bfd7ea67 100644 --- a/src/fsharp/InfoReader.fs +++ b/src/fsharp/InfoReader.fs @@ -108,7 +108,7 @@ type PropertyCollector(g, amap, m, ty, optFilter, ad) = let add pinfo = match props.TryGetValue(pinfo), pinfo with - | (true, FSProp (_, ty, Some vref1 , _)), FSProp (_, _, _, Some vref2) + | (true, FSProp (_, ty, Some vref1, _)), FSProp (_, _, _, Some vref2) | (true, FSProp (_, ty, _, Some vref2)), FSProp (_, _, Some vref1, _) -> let pinfo = FSProp (g, ty, Some vref1, Some vref2) props.[pinfo] <- pinfo @@ -217,7 +217,7 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = let st = info.ProvidedType match optFilter with | None -> - [ for fi in st.PApplyArray((fun st -> st.GetFields()), "GetFields" , m) -> ProvidedField(amap, fi, m) ] + [ for fi in st.PApplyArray((fun st -> st.GetFields()), "GetFields", m) -> ProvidedField(amap, fi, m) ] | Some name -> match st.PApply ((fun st -> st.GetField name), m) with | Tainted.Null -> [] @@ -242,7 +242,7 @@ type InfoReader(g: TcGlobals, amap: Import.ImportMap) = let st = info.ProvidedType match optFilter with | None -> - [ for ei in st.PApplyArray((fun st -> st.GetEvents()), "GetEvents" , m) -> ProvidedEvent(amap, ei, m) ] + [ for ei in st.PApplyArray((fun st -> st.GetEvents()), "GetEvents", m) -> ProvidedEvent(amap, ei, m) ] | Some name -> match st.PApply ((fun st -> st.GetEvent name), m) with | Tainted.Null -> [] diff --git a/src/fsharp/InnerLambdasToTopLevelFuncs.fs b/src/fsharp/InnerLambdasToTopLevelFuncs.fs index d66610c3c10..53fa7baa3a7 100644 --- a/src/fsharp/InnerLambdasToTopLevelFuncs.fs +++ b/src/fsharp/InnerLambdasToTopLevelFuncs.fs @@ -63,9 +63,9 @@ let emptyTR = TreeNode[] // and combined form, so this function should not be needed let destApp (f, fty, tys, args, m) = match stripExpr f with - | Expr.App (f2, fty2, tys2, [] , _) -> (f2, fty2, tys2 @ tys, args, m) - | Expr.App _ -> (f, fty, tys, args, m) (* has args, so not combine ty args *) - | f -> (f, fty, tys, args, m) + | Expr.App (f2, fty2, tys2, [], _) -> (f2, fty2, tys2 @ tys, args, m) + | Expr.App _ -> (f, fty, tys, args, m) (* has args, so not combine ty args *) + | f -> (f, fty, tys, args, m) #if DEBUG let showTyparSet tps = showL (commaListL (List.map typarL (Zset.elements tps))) @@ -320,7 +320,7 @@ type ReqdItem = let reqdItemOrder = let rep = function - | ReqdSubEnv v -> true , v + | ReqdSubEnv v -> true, v | ReqdVal v -> false, v Order.orderOn rep (Pair.order (Bool.order, valOrder)) diff --git a/src/fsharp/LexFilter.fs b/src/fsharp/LexFilter.fs index 279376b3d62..9e8206ca7f0 100755 --- a/src/fsharp/LexFilter.fs +++ b/src/fsharp/LexFilter.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. /// LexFilter - process the token stream prior to parsing. /// Implements the offside rule and a copule of other lexical transformations. @@ -46,15 +46,15 @@ type Context = | CtxtInterfaceHead of Position | CtxtTypeDefns of Position // 'type =', not removed when we find the "=" - | CtxtNamespaceHead of Position * token - | CtxtModuleHead of Position * token + | CtxtNamespaceHead of Position * token + | CtxtModuleHead of Position * token | CtxtMemberHead of Position | CtxtMemberBody of Position // If bool is true then this is "whole file" // module A.B // If bool is false, this is a "module declaration" // module A = ... - | CtxtModuleBody of Position * bool + | CtxtModuleBody of Position * bool | CtxtNamespaceBody of Position | CtxtException of Position | CtxtParen of Parser.token * Position @@ -152,12 +152,12 @@ let isNonAssocInfixToken token = let infixTokenLength token = match token with - | COMMA -> 1 + | COMMA -> 1 | AMP -> 1 | OR -> 1 | DOLLAR -> 1 | MINUS -> 1 - | STAR -> 1 + | STAR -> 1 | BAR -> 1 | LESS false -> 1 | GREATER false -> 1 @@ -184,13 +184,13 @@ let infixTokenLength token = let rec isIfBlockContinuator token = match token with // The following tokens may align with the "if" without closing the "if", e.g. - // if ... - // then ... + // if ... + // then ... // elif ... // else ... | THEN | ELSE | ELIF -> true // Likewise - // if ... then ( + // if ... then ( // ) elif begin // end else ... | END | RPAREN -> true @@ -259,7 +259,7 @@ let rec isTypeContinuator token = // type X = // | A // | B - // and Y = c <--- 'and' HERE + // and Y = c <--- 'and' HERE // // type X = { // x: int @@ -367,7 +367,7 @@ let isAtomicExprEndToken token = | IDENT _ | INT8 _ | INT16 _ | INT32 _ | INT64 _ | NATIVEINT _ | UINT8 _ | UINT16 _ | UINT32 _ | UINT64 _ | UNATIVEINT _ - | DECIMAL _ | BIGNUM _ | STRING _ | BYTEARRAY _ | CHAR _ + | DECIMAL _ | BIGNUM _ | STRING _ | BYTEARRAY _ | CHAR _ | IEEE32 _ | IEEE64 _ | RPAREN | RBRACK | RBRACE | BAR_RBRACE | BAR_RBRACK | END | NULL | FALSE | TRUE | UNDERSCORE -> true @@ -395,7 +395,7 @@ let parenTokensBalance t1 t2 = /// Used to save some aspects of the lexbuffer state [] type LexbufState(startPos: Position, - endPos : Position, + endPos : Position, pastEOF : bool) = member x.StartPos = startPos member x.EndPos = endPos @@ -452,14 +452,14 @@ let (|TyparsCloseOp|_|) (txt: string) = | "]" -> Some RBRACK | "-" -> Some MINUS | ".." -> Some DOT_DOT - | "?" -> Some QMARK + | "?" -> Some QMARK | "??" -> Some QMARK_QMARK | ":=" -> Some COLON_EQUALS | "::" -> Some COLON_COLON | "*" -> Some STAR | "&" -> Some AMP | "->" -> Some RARROW - | "<-" -> Some LARROW + | "<-" -> Some LARROW | "=" -> Some EQUALS | "<" -> Some (LESS false) | "$" -> Some DOLLAR @@ -467,7 +467,7 @@ let (|TyparsCloseOp|_|) (txt: string) = | "%%" -> Some (PERCENT_OP("%%")) | "" -> None | s -> - match List.ofSeq afterAngles with + match List.ofSeq afterAngles with | ('=' :: _) | ('!' :: '=' :: _) | ('<' :: _) @@ -498,23 +498,23 @@ 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 // // A lexbuf is a stateful object that can be enticed to emit tokens by calling - // 'lexer' functions designed to work with the lexbuf. Here we fake a new stream - // coming out of an existing lexbuf. Ideally lexbufs would be abstract interfaces + // 'lexer' functions designed to work with the lexbuf. Here we fake a new stream + // coming out of an existing lexbuf. Ideally lexbufs would be abstract interfaces // and we could just build a new abstract interface that wraps an existing one. // However that is not how F# lexbufs currently work. // // Part of the fakery we perform involves buffering a lookahead token which - // we eventually pass on to the client. However, this client also looks at + // we eventually pass on to the client. However, this client also looks at // other aspects of the 'state' of lexbuf directly, e.g. F# lexbufs have a triple // (start-pos, end-pos, eof-reached) // - // You may ask why the F# parser reads this lexbuf state directly. Well, the + // You may ask why the F# parser reads this lexbuf state directly. Well, the // pars.fsy code itself it doesn't, but the parser engines (prim-parsing.fs) // certainly do for F#. e.g. when these parsers read a token // from the lexstream they also read the position information and keep this @@ -541,13 +541,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // EOF token is processed as if on column -1 // This forces the closure of all contexts. | Parser.EOF _ -> tokenTup.LexbufState.StartPos.ColumnMinusOne - | _ -> tokenTup.LexbufState.StartPos + | _ -> tokenTup.LexbufState.StartPos //---------------------------------------------------------------------------- // Part II. The state of the new lex stream object. //-------------------------------------------------------------------------- - // Ok, we're going to the wrapped lexbuf. Set the lexstate back so that the lexbuf + // Ok, we're going to the wrapped lexbuf. Set the lexstate back so that the lexbuf // appears consistent and correct for the wrapped lexer function. let mutable savedLexbufState = Unchecked.defaultof let mutable haveLexbufState = false @@ -587,7 +587,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, //---------------------------------------------------------------------------- // Part III. Initial configuration of state. // - // We read a token. In F# Interactive the parser thread will be correctly blocking + // We read a token. In F# Interactive the parser thread will be correctly blocking // here. //-------------------------------------------------------------------------- @@ -596,7 +596,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let mutable prevWasAtomicEnd = false let peekInitial() = - let initialLookaheadTokenTup = popNextTokenTup() + let initialLookaheadTokenTup = popNextTokenTup() if debug then dprintf "first token: initialLookaheadTokenLexbufState = %a\n" outputPos (startPosOfTokenTup initialLookaheadTokenTup) delayToken initialLookaheadTokenTup @@ -653,18 +653,18 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // let f x = function // | Case1 -> ... // | Case2 -> ... - | (CtxtMatchClauses _), (CtxtFunction _ :: CtxtSeqBlock _ :: (CtxtLetDecl _ as limitCtxt) :: _rest) + | (CtxtMatchClauses _), (CtxtFunction _ :: CtxtSeqBlock _ :: (CtxtLetDecl _ as limitCtxt) :: _rest) -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) - // Otherwise 'function ...' places no limit until we hit a CtxtLetDecl etc... (Recursive) + // Otherwise 'function ...' places no limit until we hit a CtxtLetDecl etc... (Recursive) | (CtxtMatchClauses _), (CtxtFunction _ :: rest) -> unindentationLimit false rest - // 'try ... with' limited by 'try' + // 'try ... with' limited by 'try' | _, (CtxtMatchClauses _ :: (CtxtTry _ as limitCtxt) :: _rest) -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) - // 'fun ->' places no limit until we hit a CtxtLetDecl etc... (Recursive) + // 'fun ->' places no limit until we hit a CtxtLetDecl etc... (Recursive) | _, (CtxtFun _ :: rest) -> unindentationLimit false rest @@ -682,7 +682,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // x + x // This is a serious thing to allow, but is required since there is no "return" in this language. // Without it there is no way of escaping special cases in large bits of code without indenting the main case. - | CtxtSeqBlock _, (CtxtElse _ :: (CtxtIf _ as limitCtxt) :: _rest) + | CtxtSeqBlock _, (CtxtElse _ :: (CtxtIf _ as limitCtxt) :: _rest) -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) // Permitted inner-construct precise block alignment: @@ -693,7 +693,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // type ... // with ... // end - | CtxtWithAsAugment _, ((CtxtInterfaceHead _ | CtxtMemberHead _ | CtxtException _ | CtxtTypeDefns _) as limitCtxt :: _rest) + | CtxtWithAsAugment _, ((CtxtInterfaceHead _ | CtxtMemberHead _ | CtxtException _ | CtxtTypeDefns _) as limitCtxt :: _rest) -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) // Permit unindentation via parentheses (or begin/end) following a 'then', 'else' or 'do': @@ -718,7 +718,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // ... <-- this is before the "with" // end - | _, ((CtxtWithAsAugment _ | CtxtThen _ | CtxtElse _ | CtxtDo _ ) :: rest) + | _, ((CtxtWithAsAugment _ | CtxtThen _ | CtxtElse _ | CtxtDo _ ) :: rest) -> unindentationLimit false rest @@ -750,26 +750,26 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // 'if ... else {' limited by 'if' // 'if ... else [' limited by 'if' // 'if ... else [|' limited by 'if' - | _, (CtxtParen ((SIG | STRUCT | BEGIN), _) :: CtxtSeqBlock _ :: (CtxtModuleBody (_, false) as limitCtxt) :: _) - | _, (CtxtParen ((BEGIN | LPAREN | LBRACK | LBRACE | LBRACE_BAR | LBRACK_BAR) , _) :: CtxtSeqBlock _ :: CtxtThen _ :: (CtxtIf _ as limitCtxt) :: _) - | _, (CtxtParen ((BEGIN | LPAREN | LBRACK | LBRACE | LBRACE_BAR | LBRACK_BAR | LBRACK_LESS) , _) :: CtxtSeqBlock _ :: CtxtElse _ :: (CtxtIf _ as limitCtxt) :: _) + | _, (CtxtParen ((SIG | STRUCT | BEGIN), _) :: CtxtSeqBlock _ :: (CtxtModuleBody (_, false) as limitCtxt) :: _) + | _, (CtxtParen ((BEGIN | LPAREN | LBRACK | LBRACE | LBRACE_BAR | LBRACK_BAR), _) :: CtxtSeqBlock _ :: CtxtThen _ :: (CtxtIf _ as limitCtxt) :: _) + | _, (CtxtParen ((BEGIN | LPAREN | LBRACK | LBRACE | LBRACE_BAR | LBRACK_BAR | LBRACK_LESS), _) :: CtxtSeqBlock _ :: CtxtElse _ :: (CtxtIf _ as limitCtxt) :: _) // 'f ... (' in seqblock limited by 'f' // 'f ... {' in seqblock limited by 'f' NOTE: this is covered by the more generous case above // 'f ... [' in seqblock limited by 'f' // 'f ... [|' in seqblock limited by 'f' // 'f ... Foo<' in seqblock limited by 'f' - | _, (CtxtParen ((BEGIN | LPAREN | LESS true | LBRACK | LBRACK_BAR) , _) :: CtxtVanilla _ :: (CtxtSeqBlock _ as limitCtxt) :: _) + | _, (CtxtParen ((BEGIN | LPAREN | LESS true | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: (CtxtSeqBlock _ as limitCtxt) :: _) // 'type C = class ... ' limited by 'type' // 'type C = interface ... ' limited by 'type' // 'type C = struct ... ' limited by 'type' - | _, (CtxtParen ((CLASS | STRUCT | INTERFACE), _) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ as limitCtxt) :: _) + | _, (CtxtParen ((CLASS | STRUCT | INTERFACE), _) :: CtxtSeqBlock _ :: (CtxtTypeDefns _ as limitCtxt) :: _) -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) // REVIEW: document these | _, (CtxtSeqBlock _ :: CtxtParen((BEGIN | LPAREN | LBRACK | LBRACK_BAR), _) :: CtxtVanilla _ :: (CtxtSeqBlock _ as limitCtxt) :: _) - | (CtxtSeqBlock _), (CtxtParen ((BEGIN | LPAREN | LBRACE | LBRACE_BAR | LBRACK | LBRACK_BAR) , _) :: CtxtSeqBlock _ :: ((CtxtTypeDefns _ | CtxtLetDecl _ | CtxtMemberBody _ | CtxtWithAsLet _) as limitCtxt) :: _) + | (CtxtSeqBlock _), (CtxtParen ((BEGIN | LPAREN | LBRACE | LBRACE_BAR | LBRACK | LBRACK_BAR), _) :: CtxtSeqBlock _ :: ((CtxtTypeDefns _ | CtxtLetDecl _ | CtxtMemberBody _ | CtxtWithAsLet _) as limitCtxt) :: _) -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) // Permitted inner-construct (e.g. "then" block and "else" block in overall @@ -778,13 +778,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // then expr // elif expr // else expr - | (CtxtIf _ | CtxtElse _ | CtxtThen _), (CtxtIf _ as limitCtxt) :: _rest + | (CtxtIf _ | CtxtElse _ | CtxtThen _), (CtxtIf _ as limitCtxt) :: _rest -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) // Permitted inner-construct precise block alignment: // while ... // do expr // done - | (CtxtDo _), ((CtxtFor _ | CtxtWhile _) as limitCtxt) :: _rest + | (CtxtDo _), ((CtxtFor _ | CtxtWhile _) as limitCtxt) :: _rest -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) @@ -793,7 +793,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol + 1) // These contexts can have their contents exactly aligning - | _, ((CtxtParen _ | CtxtFor _ | CtxtWhen _ | CtxtWhile _ | CtxtTypeDefns _ | CtxtMatch _ | CtxtModuleBody (_, true) | CtxtNamespaceBody _ | CtxtTry _ | CtxtMatchClauses _ | CtxtSeqBlock _) as limitCtxt :: _) + | _, ((CtxtParen _ | CtxtFor _ | CtxtWhen _ | CtxtWhile _ | CtxtTypeDefns _ | CtxtMatch _ | CtxtModuleBody (_, true) | CtxtNamespaceBody _ | CtxtTry _ | CtxtMatchClauses _ | CtxtSeqBlock _) as limitCtxt :: _) -> PositionWithColumn(limitCtxt.StartPos, limitCtxt.StartCol) match newCtxt with @@ -816,7 +816,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let popCtxt() = match offsideStack with - | [] -> () + | [] -> () | h :: rest -> if debug then dprintf "<-- popping Context(%A), stack = %A\n" h rest offsideStack <- rest @@ -879,7 +879,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, false | GREATER _ | GREATER_RBRACK | GREATER_BAR_RBRACK -> let nParen = nParen - 1 - let hasAfterOp = (match lookaheadToken with GREATER _ -> false | _ -> true) + let hasAfterOp = (match lookaheadToken with GREATER _ -> false | _ -> true) if nParen > 0 then // Don't smash the token if there is an after op and we're in a nested paren stack := (lookaheadTokenTup, not hasAfterOp) :: (!stack).Tail @@ -902,7 +902,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // On successful parse of a set of type parameters, look for an adjacent (, e.g. // M>(args) // and insert a HIGH_PRECEDENCE_PAREN_APP - if afterOp.IsNone && (match nextTokenIsAdjacentLParenOrLBrack lookaheadTokenTup with Some LPAREN -> true | _ -> false) then + if afterOp.IsNone && (match nextTokenIsAdjacentLParenOrLBrack lookaheadTokenTup with Some LPAREN -> true | _ -> false) then let dotTokenTup = peekNextTokenTup() stack := (dotTokenTup.UseLocation(HIGH_PRECEDENCE_PAREN_APP), false) :: !stack true @@ -938,7 +938,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | NULL | INT8 _ | INT16 _ | INT32 _ | INT64 _ | NATIVEINT _ | UINT8 _ | UINT16 _ | UINT32 _ | UINT64 _ | UNATIVEINT _ - | DECIMAL _ | BIGNUM _ | STRING _ | BYTEARRAY _ | CHAR _ | TRUE | FALSE + | DECIMAL _ | BIGNUM _ | STRING _ | BYTEARRAY _ | CHAR _ | TRUE | FALSE | IEEE32 _ | IEEE64 _ | DOT | UNDERSCORE | EQUALS | IDENT _ | COMMA | RARROW | HASH @@ -996,26 +996,26 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let tokenBalancesHeadContext token stack = match token, stack with - | END, (CtxtWithAsAugment(_) :: _) + | END, (CtxtWithAsAugment(_) :: _) | (ELSE | ELIF), (CtxtIf _ :: _) - | DONE , (CtxtDo _ :: _) + | DONE, (CtxtDo _ :: _) // WITH balances except in the following contexts.... Phew - an overused keyword! - | WITH , ( ((CtxtMatch _ | CtxtException _ | CtxtMemberHead _ | CtxtInterfaceHead _ | CtxtTry _ | CtxtTypeDefns _ | CtxtMemberBody _) :: _) + | WITH, ( ((CtxtMatch _ | CtxtException _ | CtxtMemberHead _ | CtxtInterfaceHead _ | CtxtTry _ | CtxtTypeDefns _ | CtxtMemberBody _) :: _) // This is the nasty record/object-expression case - | (CtxtSeqBlock _ :: CtxtParen((LBRACE | LBRACE_BAR), _) :: _) ) - | FINALLY , (CtxtTry _ :: _) -> + | (CtxtSeqBlock _ :: CtxtParen((LBRACE | LBRACE_BAR), _) :: _) ) + | FINALLY, (CtxtTry _ :: _) -> true // for x in ienum ... // let x = ... in - | IN , ((CtxtFor _ | CtxtLetDecl _) :: _) -> + | IN, ((CtxtFor _ | CtxtLetDecl _) :: _) -> true // 'query { join x in ys ... }' // 'query { ... // join x in ys ... }' // 'query { for ... do // join x in ys ... }' - | IN , stack when detectJoinInCtxt stack -> + | IN, stack when detectJoinInCtxt stack -> true // NOTE: ;; does not terminate a 'namespace' body. @@ -1025,8 +1025,8 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | SEMICOLON_SEMICOLON, (CtxtSeqBlock _ :: CtxtModuleBody (_, true) :: _) -> true - | t2 , (CtxtParen(t1, _) :: _) -> - parenTokensBalance t1 t2 + | t2, (CtxtParen(t1, _) :: _) -> + parenTokensBalance t1 t2 | _ -> false @@ -1113,11 +1113,11 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, let isSemiSemi = match token with SEMICOLON_SEMICOLON -> true | _ -> false // If you see a 'member' keyword while you are inside the body of another member, then it usually means there is a syntax error inside this method - // and the upcoming 'member' is the start of the next member in the class. For better parser recovery and diagnostics, it is best to pop out of the + // and the upcoming 'member' is the start of the next member in the class. For better parser recovery and diagnostics, it is best to pop out of the // existing member context so the parser can recover. // - // However there are two places where 'member' keywords can appear inside expressions inside the body of a member. The first is object expressions, and - // the second is static inline constraints. We must not pop the context stack in those cases, or else legal code will not parse. + // However there are two places where 'member' keywords can appear inside expressions inside the body of a member. The first is object expressions, and + // the second is static inline constraints. We must not pop the context stack in those cases, or else legal code will not parse. // // It is impossible to decide for sure if we're in one of those two cases, so we must err conservatively if we might be. let thereIsACtxtMemberBodyOnTheStackAndWeShouldPopStackForUpcomingMember ctxtStack = @@ -1137,10 +1137,10 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, match ctxt with | CtxtFun _ | CtxtMatchClauses _ - | CtxtWithAsLet _ -> + | CtxtWithAsLet _ -> Some OEND - | CtxtWithAsAugment _ -> + | CtxtWithAsAugment _ -> Some ODECLEND | CtxtDo _ @@ -1164,7 +1164,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, not (isNil stack) && match token with | Parser.EOF _ -> true - | SEMICOLON_SEMICOLON -> not (tokenBalancesHeadContext token stack) + | SEMICOLON_SEMICOLON -> not (tokenBalancesHeadContext token stack) | END | ELSE | ELIF @@ -1178,7 +1178,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | BAR_RBRACK | WITH | FINALLY - | RQUOTE _ -> + | RQUOTE _ -> not (tokenBalancesHeadContext token stack) && // Only close the context if some context is going to match at some point in the stack. // If none match, the token will go through, and error recovery will kick in in the parser and report the extra token, @@ -1188,7 +1188,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | _ -> false // The TYPE and MODULE keywords cannot be used in expressions, but the parser has a hard time recovering on incomplete-expression-code followed by - // a TYPE or MODULE. So the lexfilter helps out by looking ahead for these tokens and (1) closing expression contexts and (2) inserting extra 'coming soon' tokens + // a TYPE or MODULE. So the lexfilter helps out by looking ahead for these tokens and (1) closing expression contexts and (2) inserting extra 'coming soon' tokens // that the expression rules in the FsYacc parser can 'shift' to make progress parsing the incomplete expressions, without using the 'recover' action. let insertComingSoonTokens(keywordName, comingSoon, isHere) = // compiling the source for FSharp.Core.dll uses crazy syntax like @@ -1220,7 +1220,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // preserve all other contexts | _ -> false) do match offsideStack.Head with - | CtxtParen _ -> + | CtxtParen _ -> if debug then dprintf "%s at %a terminates CtxtParen()\n" keywordName outputPos tokenStartPos popCtxt() | CtxtSeqBlock(_, _, AddBlockEnd) -> @@ -1242,7 +1242,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | _ -> failwith "impossible, the while loop guard just above prevents this" // See bugs 91609/92107/245850; we turn ...TYPE... into ...TYPE_COMING_SOON(x6), TYPE_IS_HERE... to help the parser recover when it sees "type" in a parenthesized expression. // And we do the same thing for MODULE. - // Why _six_ TYPE_COMING_SOON? It's rather arbitrary, this means we can recover from up to six unmatched parens before failing. The unit tests (with 91609 in the name) demonstrate this. + // Why _six_ TYPE_COMING_SOON? It's rather arbitrary, this means we can recover from up to six unmatched parens before failing. The unit tests (with 91609 in the name) demonstrate this. // Don't "delayToken tokenTup", we are replacing it, so consume it. if debug then dprintf "inserting 6 copies of %+A before %+A\n" comingSoon isHere delayTokenNoProcessing (tokenTup.UseLocation(isHere)) @@ -1257,7 +1257,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, tokensThatNeedNoProcessingCount <- tokensThatNeedNoProcessingCount - 1 returnToken tokenLexbufState token - | _ when tokenForcesHeadContextClosure token offsideStack -> + | _ when tokenForcesHeadContextClosure token offsideStack -> let ctxt = offsideStack.Head if debug then dprintf "IN/ELSE/ELIF/DONE/RPAREN/RBRACE/END at %a terminates context at position %a\n" outputPos tokenStartPos outputPos ctxt.StartPos popCtxt() @@ -1269,12 +1269,12 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, reprocess() // reset on ';;' rule. A ';;' terminates ALL entries - | SEMICOLON_SEMICOLON, [] -> + | SEMICOLON_SEMICOLON, [] -> if debug then dprintf ";; scheduling a reset\n" delayToken(tokenTup.UseLocation(ORESET)) returnToken tokenLexbufState SEMICOLON_SEMICOLON - | ORESET, [] -> + | ORESET, [] -> if debug then dprintf "performing a reset after a ;; has been swallowed\n" // NOTE: The parser thread of F# Interactive will often be blocked on this call, e.g. after an entry has been // processed and we're waiting for the first token of the next entry. @@ -1282,12 +1282,12 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, hwTokenFetch(true) - | IN, stack when detectJoinInCtxt stack -> + | IN, stack when detectJoinInCtxt stack -> returnToken tokenLexbufState JOIN_IN // Balancing rule. Encountering an 'in' balances with a 'let'. i.e. even a non-offside 'in' closes a 'let' // The 'IN' token is thrown away and becomes an ODECLEND - | IN, (CtxtLetDecl (blockLet, offsidePos) :: _) -> + | IN, (CtxtLetDecl (blockLet, offsidePos) :: _) -> if debug then dprintf "IN at %a (becomes %s)\n" outputPos tokenStartPos (if blockLet then "ODECLEND" else "IN") if tokenStartCol < offsidePos.Column then warn tokenTup (FSComp.SR.lexfltIncorrentIndentationOfIn()) popCtxt() @@ -1297,7 +1297,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // Balancing rule. Encountering a 'done' balances with a 'do'. i.e. even a non-offside 'done' closes a 'do' // The 'DONE' token is thrown away and becomes an ODECLEND - | DONE, (CtxtDo offsidePos :: _) -> + | DONE, (CtxtDo offsidePos :: _) -> if debug then dprintf "DONE at %a terminates CtxtDo(offsidePos=%a)\n" outputPos tokenStartPos outputPos offsidePos popCtxt() // reprocess as the DONE may close a DO context @@ -1305,8 +1305,8 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, hwTokenFetch(useBlockRule) // Balancing rule. Encountering a ')' or '}' balances with a '(' or '{', even if not offside - | ((END | RPAREN | RBRACE | BAR_RBRACE | RBRACK | BAR_RBRACK | RQUOTE _ | GREATER true) as t2), (CtxtParen (t1, _) :: _) - when parenTokensBalance t1 t2 -> + | ((END | RPAREN | RBRACE | BAR_RBRACE | RBRACK | BAR_RBRACK | RQUOTE _ | GREATER true) as t2), (CtxtParen (t1, _) :: _) + when parenTokensBalance t1 t2 -> if debug then dprintf "RPAREN/RBRACE/BAR_RBRACE/RBRACK/BAR_RBRACK/RQUOTE/END at %a terminates CtxtParen()\n" outputPos tokenStartPos popCtxt() // Queue a dummy token at this position to check if any closing rules apply @@ -1314,7 +1314,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, returnToken tokenLexbufState token // Balancing rule. Encountering a 'end' can balance with a 'with' but only when not offside - | END, (CtxtWithAsAugment(offsidePos) :: _) + | END, (CtxtWithAsAugment(offsidePos) :: _) when not (tokenStartCol + 1 <= offsidePos.Column) -> if debug then dprintf "END at %a terminates CtxtWithAsAugment()\n" outputPos tokenStartPos popCtxt() @@ -1347,7 +1347,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // Transition rule. CtxtModuleHead ~~~> push CtxtModuleBody; push CtxtSeqBlock // Applied when a ':' or '=' token is seen // Otherwise it's a 'head' module declaration, so ignore it - | _, (CtxtModuleHead (moduleTokenPos, prevToken) :: _) -> + | _, (CtxtModuleHead (moduleTokenPos, prevToken) :: _) -> match prevToken, token with | MODULE, GLOBAL when moduleTokenPos.Column < tokenStartPos.Column -> replaceCtxt tokenTup (CtxtModuleHead (moduleTokenPos, token)) @@ -1468,7 +1468,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // This is the first token in a block, or a token immediately // following an infix operator (see above). // Return the token, but only after processing any additional rules - // applicable for this token. Don't apply the CtxtSeqBlock rule for + // applicable for this token. Don't apply the CtxtSeqBlock rule for // this token, but do apply it on subsequent tokens. if debug then dprintf "repull for CtxtSeqBlockStart\n" replaceCtxt tokenTup (CtxtSeqBlock (NotFirstInSeqBlock, offsidePos, addBlockEnd)) @@ -1493,13 +1493,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // ... // ~~> insert OBLOCKSEP | _, (CtxtSeqBlock (NotFirstInSeqBlock, offsidePos, addBlockEnd) :: rest) - when useBlockRule + when useBlockRule && not (let isTypeCtxt = (match rest with | (CtxtTypeDefns _ :: _) -> true | _ -> false) // Don't insert 'OBLOCKSEP' between namespace declarations let isNamespaceCtxt = (match rest with | (CtxtNamespaceBody _ :: _) -> true | _ -> false) if isNamespaceCtxt then (match token with NAMESPACE -> true | _ -> false) elif isTypeCtxt then isTypeSeqBlockElementContinuator token - else isSeqBlockElementContinuator token) + else isSeqBlockElementContinuator token) && (tokenStartCol = offsidePos.Column) && (tokenStartPos.OriginalLine <> offsidePos.OriginalLine) -> if debug then dprintf "offside at column %d matches start of block(%a)! delaying token, returning OBLOCKSEP\n" tokenStartCol outputPos offsidePos @@ -1555,7 +1555,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // module M = ... // ... // NOTE: ;; does not terminate a whole file module body. - | _, ((CtxtModuleBody (offsidePos, wholeFile)) :: _) when (isSemiSemi && not wholeFile) || tokenStartCol <= offsidePos.Column -> + | _, ((CtxtModuleBody (offsidePos, wholeFile)) :: _) when (isSemiSemi && not wholeFile) || tokenStartCol <= offsidePos.Column -> if debug then dprintf "token at column %d is offside from MODULE with offsidePos %a! delaying token\n" tokenStartCol outputPos offsidePos popCtxt() reprocess() @@ -1571,7 +1571,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, popCtxt() reprocess() - // Pop CtxtMemberBody when offside. Insert an ODECLEND to indicate the end of the member + // Pop CtxtMemberBody when offside. Insert an ODECLEND to indicate the end of the member | _, ((CtxtMemberBody(offsidePos)) :: _) when isSemiSemi || tokenStartCol <= offsidePos.Column -> if debug then dprintf "token at column %d is offside from MEMBER/OVERRIDE head with offsidePos %a!\n" tokenStartCol outputPos offsidePos popCtxt() @@ -1584,19 +1584,19 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, reprocess() | _, (CtxtIf offsidePos :: _) - when isSemiSemi || (if isIfBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> + when isSemiSemi || (if isIfBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "offside from CtxtIf\n" popCtxt() reprocess() | _, (CtxtWithAsLet offsidePos :: _) - when isSemiSemi || (if isLetContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> + when isSemiSemi || (if isLetContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "offside from CtxtWithAsLet\n" popCtxt() insertToken OEND | _, (CtxtWithAsAugment(offsidePos) :: _) - when isSemiSemi || (if isWithAugmentBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> + when isSemiSemi || (if isWithAugmentBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "offside from CtxtWithAsAugment, isWithAugmentBlockContinuator = %b\n" (isWithAugmentBlockContinuator token) popCtxt() insertToken ODECLEND @@ -1608,13 +1608,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, reprocess() | _, (CtxtFor offsidePos :: _) - when isSemiSemi || (if isForLoopContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> + when isSemiSemi || (if isForLoopContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "offside from CtxtFor\n" popCtxt() reprocess() | _, (CtxtWhile offsidePos :: _) - when isSemiSemi || (if isWhileBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> + when isSemiSemi || (if isWhileBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "offside from CtxtWhile\n" popCtxt() reprocess() @@ -1637,7 +1637,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, reprocess() | _, (CtxtTry offsidePos :: _) - when isSemiSemi || (if isTryBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> + when isSemiSemi || (if isTryBlockContinuator token then tokenStartCol + 1 else tokenStartCol) <= offsidePos.Column -> if debug then dprintf "offside from CtxtTry\n" popCtxt() reprocess() @@ -1648,7 +1648,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // // then // ... - | _, (CtxtThen offsidePos :: _) when isSemiSemi || (if isThenBlockContinuator token then tokenStartCol + 1 else tokenStartCol)<= offsidePos.Column -> + | _, (CtxtThen offsidePos :: _) when isSemiSemi || (if isThenBlockContinuator token then tokenStartCol + 1 else tokenStartCol)<= offsidePos.Column -> if debug then dprintf "offside from CtxtThen, popping\n" popCtxt() reprocess() @@ -1667,33 +1667,33 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, (match token with // BAR occurs in pattern matching 'with' blocks | BAR -> - let cond1 = tokenStartCol + (if leadingBar then 0 else 2) < offsidePos.Column - let cond2 = tokenStartCol + (if leadingBar then 1 else 2) < offsidePos.Column + let cond1 = tokenStartCol + (if leadingBar then 0 else 2) < offsidePos.Column + let cond2 = tokenStartCol + (if leadingBar then 1 else 2) < offsidePos.Column if (cond1 <> cond2) then errorR(Lexhelp.IndentationProblem(FSComp.SR.lexfltSeparatorTokensOfPatternMatchMisaligned(), mkSynRange (startPosOfTokenTup tokenTup) tokenTup.LexbufState.EndPos)) cond1 | END -> tokenStartCol + (if leadingBar then -1 else 1) < offsidePos.Column - | _ -> tokenStartCol + (if leadingBar then -1 else 1) < offsidePos.Column)) -> + | _ -> tokenStartCol + (if leadingBar then -1 else 1) < offsidePos.Column)) -> if debug then dprintf "offside from WITH, tokenStartCol = %d, offsidePos = %a, delaying token, returning OEND\n" tokenStartCol outputPos offsidePos popCtxt() insertToken OEND // namespace ... ~~~> CtxtNamespaceHead - | NAMESPACE, (_ :: _) -> + | NAMESPACE, (_ :: _) -> if debug then dprintf "NAMESPACE: entering CtxtNamespaceHead, awaiting end of long identifier to push CtxtSeqBlock\n" pushCtxt tokenTup (CtxtNamespaceHead (tokenStartPos, token)) returnToken tokenLexbufState token // module ... ~~~> CtxtModuleHead - | MODULE, (_ :: _) -> + | MODULE, (_ :: _) -> insertComingSoonTokens("MODULE", MODULE_COMING_SOON, MODULE_IS_HERE) if debug then dprintf "MODULE: entering CtxtModuleHead, awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtModuleHead (tokenStartPos, token)) hwTokenFetch(useBlockRule) // exception ... ~~~> CtxtException - | EXCEPTION, (_ :: _) -> + | EXCEPTION, (_ :: _) -> if debug then dprintf "EXCEPTION: entering CtxtException(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtException tokenStartPos) returnToken tokenLexbufState token @@ -1727,7 +1727,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, pushCtxt tokenTup (CtxtLetDecl(blockLet, tokenStartPos)) returnToken tokenLexbufState (if blockLet then OBINDER b else token) - | (VAL | STATIC | ABSTRACT | MEMBER | OVERRIDE | DEFAULT), ctxtStack when thereIsACtxtMemberBodyOnTheStackAndWeShouldPopStackForUpcomingMember ctxtStack -> + | (VAL | STATIC | ABSTRACT | MEMBER | OVERRIDE | DEFAULT), ctxtStack when thereIsACtxtMemberBodyOnTheStackAndWeShouldPopStackForUpcomingMember ctxtStack -> if debug then dprintf "STATIC/MEMBER/OVERRIDE/DEFAULT: already inside CtxtMemberBody, popping all that context before starting next member...\n" // save this token, we'll consume it again later... delayTokenNoProcessing tokenTup @@ -1751,19 +1751,19 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // override ... ~~~> CtxtMemberHead // default ... ~~~> CtxtMemberHead // val ... ~~~> CtxtMemberHead - | (VAL | STATIC | ABSTRACT | MEMBER | OVERRIDE | DEFAULT), (ctxt :: _) when (match ctxt with CtxtMemberHead _ -> false | _ -> true) -> + | (VAL | STATIC | ABSTRACT | MEMBER | OVERRIDE | DEFAULT), (ctxt :: _) when (match ctxt with CtxtMemberHead _ -> false | _ -> true) -> if debug then dprintf "STATIC/MEMBER/OVERRIDE/DEFAULT: entering CtxtMemberHead, awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtMemberHead(tokenStartPos)) returnToken tokenLexbufState token // public new... ~~~> CtxtMemberHead - | (PUBLIC | PRIVATE | INTERNAL), (_ctxt :: _) when (match peekNextToken() with NEW -> true | _ -> false) -> + | (PUBLIC | PRIVATE | INTERNAL), (_ctxt :: _) when (match peekNextToken() with NEW -> true | _ -> false) -> if debug then dprintf "PUBLIC/PRIVATE/INTERNAL NEW: entering CtxtMemberHead, awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtMemberHead(tokenStartPos)) returnToken tokenLexbufState token // new( ~~~> CtxtMemberHead, if not already there because of 'public' - | NEW, ctxt :: _ when (match peekNextToken() with LPAREN -> true | _ -> false) && (match ctxt with CtxtMemberHead _ -> false | _ -> true) -> + | NEW, ctxt :: _ when (match peekNextToken() with LPAREN -> true | _ -> false) && (match ctxt with CtxtMemberHead _ -> false | _ -> true) -> if debug then dprintf "NEW: entering CtxtMemberHead, awaiting EQUALS to go to CtxtSeqBlock (%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtMemberHead(tokenStartPos)) returnToken tokenLexbufState token @@ -1783,7 +1783,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, if isControlFlowOrNotSameLine() then if debug then dprintf "LAZY/ASSERT, pushing CtxtSeqBlock\n" pushCtxtSeqBlock(true, AddBlockEnd) - returnToken tokenLexbufState (match token with LAZY -> OLAZY | _ -> OASSERT) + returnToken tokenLexbufState (match token with LAZY -> OLAZY | _ -> OASSERT) else returnToken tokenLexbufState token @@ -1852,13 +1852,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // comprehension | (CtxtSeqBlock _ :: CtxtParen ((LBRACK | LBRACE | LBRACE_BAR | LBRACK_BAR), _) :: _) -> true // comprehension - | (CtxtSeqBlock _ :: (CtxtDo _ | CtxtWhile _ | CtxtFor _ | CtxtWhen _ | CtxtMatchClauses _ | CtxtTry _ | CtxtThen _ | CtxtElse _) :: _) -> true + | (CtxtSeqBlock _ :: (CtxtDo _ | CtxtWhile _ | CtxtFor _ | CtxtWhen _ | CtxtMatchClauses _ | CtxtTry _ | CtxtThen _ | CtxtElse _) :: _) -> true | _ -> false) -> if debug then dprintf "RARROW, pushing CtxtSeqBlock, tokenStartPos = %a\n" outputPos tokenStartPos pushCtxtSeqBlock(false, AddOneSidedBlockEnd) returnToken tokenLexbufState token - | LARROW, _ when isControlFlowOrNotSameLine() -> + | LARROW, _ when isControlFlowOrNotSameLine() -> if debug then dprintf "LARROW, pushing CtxtSeqBlock, tokenStartPos = %a\n" outputPos tokenStartPos pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState token @@ -1887,7 +1887,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, pushCtxtSeqBlock(false, NoAddBlockEnd) returnToken tokenLexbufState token - | WITH, ((CtxtTry _ | CtxtMatch _) :: _) -> + | WITH, ((CtxtTry _ | CtxtMatch _) :: _) -> let lookaheadTokenTup = peekNextTokenTup() let lookaheadTokenStartPos = startPosOfTokenTup lookaheadTokenTup let leadingBar = match (peekNextToken()) with BAR -> true | _ -> false @@ -1895,13 +1895,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, pushCtxt lookaheadTokenTup (CtxtMatchClauses(leadingBar, lookaheadTokenStartPos)) returnToken tokenLexbufState OWITH - | FINALLY, (CtxtTry _ :: _) -> + | FINALLY, (CtxtTry _ :: _) -> if debug then dprintf "FINALLY, pushing pushCtxtSeqBlock, tokenStartPos = %a\n" outputPos tokenStartPos pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState token | WITH, (((CtxtException _ | CtxtTypeDefns _ | CtxtMemberHead _ | CtxtInterfaceHead _ | CtxtMemberBody _) as limCtxt) :: _) - | WITH, ((CtxtSeqBlock _) as limCtxt :: CtxtParen((LBRACE | LBRACE_BAR), _) :: _) -> + | WITH, ((CtxtSeqBlock _) as limCtxt :: CtxtParen((LBRACE | LBRACE_BAR), _) :: _) -> let lookaheadTokenTup = peekNextTokenTup() let lookaheadTokenStartPos = startPosOfTokenTup lookaheadTokenTup match lookaheadTokenTup.Token with @@ -1920,7 +1920,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, | PUBLIC | PRIVATE | INTERNAL | INLINE -> let offsidePos = - if lookaheadTokenStartPos.Column > tokenTup.LexbufState.EndPos.Column then + if lookaheadTokenStartPos.Column > tokenTup.LexbufState.EndPos.Column then // This detects: // { new Foo // with M() = 1 @@ -1968,7 +1968,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, // For attributes on properties: // member x.PublicGetSetProperty // with [] get() = "Ralf" - if (match lookaheadTokenTup.Token with LBRACK_LESS -> true | _ -> false) && (lookaheadTokenStartPos.OriginalLine = tokenTup.StartPos.OriginalLine) then + if (match lookaheadTokenTup.Token with LBRACK_LESS -> true | _ -> false) && (lookaheadTokenStartPos.OriginalLine = tokenTup.StartPos.OriginalLine) then let offsidePos = tokenStartPos pushCtxt tokenTup (CtxtWithAsLet(offsidePos)) returnToken tokenLexbufState OWITH @@ -1995,14 +1995,14 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState token - | WITH, stack -> + | WITH, stack -> if debug then dprintf "WITH\n" if debug then dprintf "WITH --> NO MATCH, pushing CtxtWithAsAugment (type augmentation), stack = %A" stack pushCtxt tokenTup (CtxtWithAsAugment(tokenStartPos)) pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState token - | FUNCTION, _ -> + | FUNCTION, _ -> let lookaheadTokenTup = peekNextTokenTup() let lookaheadTokenStartPos = startPosOfTokenTup lookaheadTokenTup let leadingBar = match (peekNextToken()) with BAR -> true | _ -> false @@ -2010,13 +2010,13 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, pushCtxt lookaheadTokenTup (CtxtMatchClauses(leadingBar, lookaheadTokenStartPos)) returnToken tokenLexbufState OFUNCTION - | THEN, _ -> + | THEN, _ -> if debug then dprintf "THEN, replacing THEN with OTHEN, pushing CtxtSeqBlock;CtxtThen(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtThen(tokenStartPos)) pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState OTHEN - | ELSE, _ -> + | ELSE, _ -> let lookaheadTokenTup = peekNextTokenTup() let lookaheadTokenStartPos = startPosOfTokenTup lookaheadTokenTup match peekNextToken() with @@ -2037,42 +2037,42 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState OELSE - | (ELIF | IF), _ -> + | (ELIF | IF), _ -> if debug then dprintf "IF, pushing CtxtIf(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtIf (tokenStartPos)) returnToken tokenLexbufState token - | (MATCH | MATCH_BANG), _ -> + | (MATCH | MATCH_BANG), _ -> if debug then dprintf "MATCH, pushing CtxtMatch(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtMatch (tokenStartPos)) returnToken tokenLexbufState token - | FOR, _ -> + | FOR, _ -> if debug then dprintf "FOR, pushing CtxtFor(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtFor (tokenStartPos)) returnToken tokenLexbufState token - | WHILE, _ -> + | WHILE, _ -> if debug then dprintf "WHILE, pushing CtxtWhile(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtWhile (tokenStartPos)) returnToken tokenLexbufState token - | WHEN, ((CtxtSeqBlock _) :: _) -> + | WHEN, ((CtxtSeqBlock _) :: _) -> if debug then dprintf "WHEN, pushing CtxtWhen(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtWhen (tokenStartPos)) returnToken tokenLexbufState token - | FUN, _ -> + | FUN, _ -> if debug then dprintf "FUN, pushing CtxtFun(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtFun (tokenStartPos)) returnToken tokenLexbufState OFUN - | INTERFACE, _ -> + | INTERFACE, _ -> let lookaheadTokenTup = peekNextTokenTup() let lookaheadTokenStartPos = startPosOfTokenTup lookaheadTokenTup match lookaheadTokenTup.Token with // type I = interface .... end - | DEFAULT | OVERRIDE | INTERFACE | NEW | TYPE | STATIC | END | MEMBER | ABSTRACT | INHERIT | LBRACK_LESS -> + | DEFAULT | OVERRIDE | INTERFACE | NEW | TYPE | STATIC | END | MEMBER | ABSTRACT | INHERIT | LBRACK_LESS -> if debug then dprintf "INTERFACE, pushing CtxtParen, tokenStartPos = %a, lookaheadTokenStartPos = %a\n" outputPos tokenStartPos outputPos lookaheadTokenStartPos pushCtxt tokenTup (CtxtParen (token, tokenStartPos)) pushCtxtSeqBlock(true, AddBlockEnd) @@ -2084,49 +2084,49 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, pushCtxt tokenTup (CtxtInterfaceHead(tokenStartPos)) returnToken tokenLexbufState OINTERFACE_MEMBER - | CLASS, _ -> + | CLASS, _ -> if debug then dprintf "CLASS, pushing CtxtParen(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtParen (token, tokenStartPos)) pushCtxtSeqBlock(true, AddBlockEnd) returnToken tokenLexbufState token - | TYPE, _ -> + | TYPE, _ -> insertComingSoonTokens("TYPE", TYPE_COMING_SOON, TYPE_IS_HERE) if debug then dprintf "TYPE, pushing CtxtTypeDefns(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtTypeDefns(tokenStartPos)) hwTokenFetch(useBlockRule) - | TRY, _ -> + | TRY, _ -> if debug then dprintf "Try, pushing CtxtTry(%a)\n" outputPos tokenStartPos pushCtxt tokenTup (CtxtTry (tokenStartPos)) // The ideal spec would be to push a begin/end block pair here, but we can only do that - // if we are able to balance the WITH with the TRY. We can't do that because of the numerous ways + // if we are able to balance the WITH with the TRY. We can't do that because of the numerous ways // WITH is used in the grammar (see what happens when we hit a WITH below. // This hits in the single line case: "try make ef1 t with _ -> make ef2 t". pushCtxtSeqBlock(false, AddOneSidedBlockEnd) returnToken tokenLexbufState token - | OBLOCKBEGIN, _ -> + | OBLOCKBEGIN, _ -> returnToken tokenLexbufState token - | ODUMMY(_), _ -> + | ODUMMY(_), _ -> if debug then dprintf "skipping dummy token as no offside rules apply\n" hwTokenFetch (useBlockRule) // Ordinary tokens start a vanilla block - | _, CtxtSeqBlock _ :: _ -> + | _, CtxtSeqBlock _ :: _ -> pushCtxt tokenTup (CtxtVanilla(tokenStartPos, isLongIdentEquals token)) if debug then dprintf "pushing CtxtVanilla at tokenStartPos = %a\n" outputPos tokenStartPos returnToken tokenLexbufState token - | _ -> + | _ -> returnToken tokenLexbufState token and rulesForBothSoftWhiteAndHardWhite(tokenTup: TokenTup) = match tokenTup.Token with // Insert HIGH_PRECEDENCE_PAREN_APP if needed - | IDENT _ when (nextTokenIsAdjacentLParenOrLBrack tokenTup).IsSome -> + | IDENT _ when (nextTokenIsAdjacentLParenOrLBrack tokenTup).IsSome -> let dotTokenTup = peekNextTokenTup() if debug then dprintf "inserting HIGH_PRECEDENCE_PAREN_APP at dotTokenPos = %a\n" outputPos (startPosOfTokenTup dotTokenTup) let hpa = @@ -2139,7 +2139,7 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, true // Insert HIGH_PRECEDENCE_TYAPP if needed - | (DELEGATE | IDENT _ | IEEE64 _ | IEEE32 _ | DECIMAL _ | INT8 _ | INT16 _ | INT32 _ | INT64 _ | NATIVEINT _ | UINT8 _ | UINT16 _ | UINT32 _ | UINT64 _ | BIGNUM _) when peekAdjacentTypars false tokenTup -> + | (DELEGATE | IDENT _ | IEEE64 _ | IEEE32 _ | DECIMAL _ | INT8 _ | INT16 _ | INT32 _ | INT64 _ | NATIVEINT _ | UINT8 _ | UINT16 _ | UINT32 _ | UINT64 _ | BIGNUM _) when peekAdjacentTypars false tokenTup -> let lessTokenTup = popNextTokenTup() delayToken (lessTokenTup.UseLocation(match lessTokenTup.Token with LESS _ -> LESS true | _ -> failwith "unreachable")) @@ -2150,21 +2150,21 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, true // Split this token to allow "1..2" for range specification - | INT32_DOT_DOT (i, v) -> + | INT32_DOT_DOT (i, v) -> let dotdotPos = new LexbufState(tokenTup.EndPos.ShiftColumnBy(-2), tokenTup.EndPos, false) delayToken(new TokenTup(DOT_DOT, dotdotPos, tokenTup.LastTokenPos)) delayToken(tokenTup.UseShiftedLocation(INT32(i, v), 0, -2)) true // Split @>. and @@>. into two - | RQUOTE_DOT (s, raw) -> + | RQUOTE_DOT (s, raw) -> let dotPos = new LexbufState(tokenTup.EndPos.ShiftColumnBy(-1), tokenTup.EndPos, false) delayToken(new TokenTup(DOT, dotPos, tokenTup.LastTokenPos)) delayToken(tokenTup.UseShiftedLocation(RQUOTE(s, raw), 0, -1)) true - | MINUS | PLUS_MINUS_OP _ | PERCENT_OP _ | AMP | AMP_AMP + | MINUS | PLUS_MINUS_OP _ | PERCENT_OP _ | AMP | AMP_AMP when ((match tokenTup.Token with - | PLUS_MINUS_OP s -> (s = "+") || (s = "+.") || (s = "-.") + | PLUS_MINUS_OP s -> (s = "+") || (s = "+.") || (s = "-.") | PERCENT_OP s -> (s = "%") || (s = "%%") | _ -> true) && nextTokenIsAdjacent tokenTup && @@ -2197,16 +2197,16 @@ type LexFilterImpl (lightSyntaxStatus: LightSyntaxStatus, compilingFsLib, lexer, if plusOrMinus then match nextTokenTup.Token with - | INT8(v, bad) -> delayMergedToken(INT8((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not - | INT16(v, bad) -> delayMergedToken(INT16((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not - | INT32(v, bad) -> delayMergedToken(INT32((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not + | INT8(v, bad) -> delayMergedToken(INT8((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not + | INT16(v, bad) -> delayMergedToken(INT16((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not + | INT32(v, bad) -> delayMergedToken(INT32((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not | INT32_DOT_DOT(v, bad) -> delayMergedToken(INT32_DOT_DOT((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not - | INT64(v, bad) -> delayMergedToken(INT64((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not - | NATIVEINT(v) -> delayMergedToken(NATIVEINT(if plus then v else -v)) - | IEEE32(v) -> delayMergedToken(IEEE32(if plus then v else -v)) - | IEEE64(v) -> delayMergedToken(IEEE64(if plus then v else -v)) - | DECIMAL(v) -> delayMergedToken(DECIMAL(if plus then v else System.Decimal.op_UnaryNegation v)) - | BIGNUM(v, s) -> delayMergedToken(BIGNUM((if plus then v else "-" + v), s)) + | INT64(v, bad) -> delayMergedToken(INT64((if plus then v else -v), (plus && bad))) // note: '-' makes a 'bad' max int 'good'. '+' does not + | NATIVEINT(v) -> delayMergedToken(NATIVEINT(if plus then v else -v)) + | IEEE32(v) -> delayMergedToken(IEEE32(if plus then v else -v)) + | IEEE64(v) -> delayMergedToken(IEEE64(if plus then v else -v)) + | DECIMAL(v) -> delayMergedToken(DECIMAL(if plus then v else System.Decimal.op_UnaryNegation v)) + | BIGNUM(v, s) -> delayMergedToken(BIGNUM((if plus then v else "-" + v), s)) | _ -> noMerge() else noMerge() @@ -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 0744fd720b9..bafcc706db6 100644 --- a/src/fsharp/MethodCalls.fs +++ b/src/fsharp/MethodCalls.fs @@ -84,7 +84,7 @@ type AssignedCalledArg<'T> = CallerArg: CallerArg<'T> } member x.Position = x.CalledArg.Position -/// Represents the possibilities for a named-setter argument (a property, field , or a record field setter) +/// Represents the possibilities for a named-setter argument (a property, field, or a record field setter) type AssignedItemSetterTarget = | AssignedPropSetter of PropInfo * MethInfo * TypeInst (* the MethInfo is a non-indexer setter property *) | AssignedILFieldSetter of ILFieldInfo @@ -1253,8 +1253,8 @@ module ProvidedMethodCalls = | [objArg] -> let erasedThisTy = eraseSystemType (amap, m, mi.PApply((fun mi -> mi.DeclaringType), m)) let thisVar = erasedThisTy.PApply((fun ty -> ProvidedVar.Fresh("this", ty)), m) - Some objArg , Array.append [| thisVar |] paramVars - | [] -> None , paramVars + Some objArg, Array.append [| thisVar |] paramVars + | [] -> None, paramVars | _ -> failwith "multiple objArgs?" let ea = mi.PApplyWithProvider((fun (methodInfo, provider) -> ExtensionTyping.GetInvokerExpression(provider, methodInfo, [| for p in paramVars -> p.PUntaintNoFailure id |])), m) diff --git a/src/fsharp/NameResolution.fs b/src/fsharp/NameResolution.fs index bca1d50d60c..ff9dbbe52e2 100644 --- a/src/fsharp/NameResolution.fs +++ b/src/fsharp/NameResolution.fs @@ -3387,7 +3387,7 @@ let ResolveExprDotLongIdentAndComputeRange (sink: TcResultsSink) (ncenv: NameRes AfterResolution.RecordResolution (None, (fun tpinst -> callSink(item, tpinst)), callSinkWithSpecificOverload, (fun () -> callSink (unrefinedItem, emptyTyparInst))) | true, true -> AfterResolution.RecordResolution (Some unrefinedItem, (fun tpinst -> callSink(item, tpinst)), callSinkWithSpecificOverload, (fun () -> callSink (unrefinedItem, emptyTyparInst))) - | _ , false -> + | _, false -> callSink (unrefinedItem, emptyTyparInst) AfterResolution.DoNothing diff --git a/src/fsharp/NicePrint.fs b/src/fsharp/NicePrint.fs index fdd35321e45..c718bf91050 100755 --- a/src/fsharp/NicePrint.fs +++ b/src/fsharp/NicePrint.fs @@ -1542,7 +1542,7 @@ module private TastDefinitionPrinting = (not v.IsConstructor, not v.IsInstance, // instance first v.DisplayName, // sort by name - List.sum v.NumArgs , // sort by #curried + List.sum v.NumArgs, // sort by #curried v.NumArgs.Length) // sort by arity let shouldShow (valRef: ValRef option) = diff --git a/src/fsharp/Optimizer.fs b/src/fsharp/Optimizer.fs index ae818cb9e84..250fda33d06 100644 --- a/src/fsharp/Optimizer.fs +++ b/src/fsharp/Optimizer.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. //------------------------------------------------------------------------- // The F# expression simplifier. The main aim is to inline simple, known functions @@ -35,7 +35,7 @@ open System.Collections.Generic #if DEBUG let verboseOptimizationInfo = - try not (System.String.IsNullOrEmpty (System.Environment.GetEnvironmentVariable "FSHARP_verboseOptimizationInfo")) with _ -> false + try not (System.String.IsNullOrEmpty (System.Environment.GetEnvironmentVariable "FSHARP_verboseOptimizationInfo")) with _ -> false let verboseOptimizations = try not (System.String.IsNullOrEmpty (System.Environment.GetEnvironmentVariable "FSHARP_verboseOptimizations")) with _ -> false #else @@ -43,7 +43,7 @@ let [] verboseOptimizationInfo = false let [] verboseOptimizations = false #endif -let i_ldlen = [ I_ldlen; (AI_conv DT_I4) ] +let i_ldlen = [ I_ldlen; (AI_conv DT_I4) ] /// size of a function call let [] callSize = 1 @@ -76,7 +76,7 @@ type ExprValueInfo = /// SizeValue(size, value) /// /// Records size info (maxDepth) for an ExprValueInfo - | SizeValue of int * ExprValueInfo + | SizeValue of int * ExprValueInfo /// ValValue(vref, value) /// @@ -101,7 +101,7 @@ type ExprValueInfo = /// the number of args in each bunch. NOTE: This include type arguments. /// expr: The value, a lambda term. /// ty: The type of lamba term - | CurriedLambdaValue of Unique * int * int * Expr * TType + | CurriedLambdaValue of Unique * int * int * Expr * TType /// ConstExprValue(size, value) | ConstExprValue of int * Expr @@ -169,20 +169,20 @@ type CcuOptimizationInfo = LazyModuleInfo #if DEBUG let braceL x = leftL (tagText "{") ^^ x ^^ rightL (tagText "}") -let seqL xL xs = Seq.fold (fun z x -> z @@ xL x) emptyL xs -let namemapL xL xmap = NameMap.foldBack (fun nm x z -> xL nm x @@ z) xmap emptyL +let seqL xL xs = Seq.fold (fun z x -> z @@ xL x) emptyL xs +let namemapL xL xmap = NameMap.foldBack (fun nm x z -> xL nm x @@ z) xmap emptyL let rec exprValueInfoL g exprVal = match exprVal with - | ConstValue (x, ty) -> NicePrint.layoutConst g ty x - | UnknownValue -> wordL (tagText "?") - | SizeValue (_, vinfo) -> exprValueInfoL g vinfo - | ValValue (vr, vinfo) -> bracketL ((valRefL vr ^^ wordL (tagText "alias")) --- exprValueInfoL g vinfo) - | TupleValue vinfos -> bracketL (exprValueInfosL g vinfos) - | RecdValue (_, vinfos) -> braceL (exprValueInfosL g vinfos) + | ConstValue (x, ty) -> NicePrint.layoutConst g ty x + | UnknownValue -> wordL (tagText "?") + | SizeValue (_, vinfo) -> exprValueInfoL g vinfo + | ValValue (vr, vinfo) -> bracketL ((valRefL vr ^^ wordL (tagText "alias")) --- exprValueInfoL g vinfo) + | TupleValue vinfos -> bracketL (exprValueInfosL g vinfos) + | RecdValue (_, vinfos) -> braceL (exprValueInfosL g vinfos) | UnionCaseValue (ucr, vinfos) -> unionCaseRefL ucr ^^ bracketL (exprValueInfosL g vinfos) | CurriedLambdaValue(_lambdaId, _arities, _bsize, expr, _ety) -> wordL (tagText "lam") ++ exprL expr (* (sprintf "lam(size=%d)" bsize) *) - | ConstExprValue (_size, x) -> exprL x + | ConstExprValue (_size, x) -> exprL x and exprValueInfosL g vinfos = commaListL (List.map (exprValueInfoL g) (Array.toList vinfos)) @@ -224,10 +224,10 @@ let rec SizeOfValueInfos (arr:_[]) = and SizeOfValueInfo x = match x with - | SizeValue (vdepth, _v) -> vdepth // terminate recursion at CACHED size nodes - | ConstValue (_x, _) -> 1 - | UnknownValue -> 1 - | ValValue (_vr, vinfo) -> SizeOfValueInfo vinfo + 1 + | SizeValue (vdepth, _v) -> vdepth // terminate recursion at CACHED size nodes + | ConstValue (_x, _) -> 1 + | UnknownValue -> 1 + | ValValue (_vr, vinfo) -> SizeOfValueInfo vinfo + 1 | TupleValue vinfos | RecdValue (_, vinfos) | UnionCaseValue (_, vinfos) -> 1 + SizeOfValueInfos vinfos @@ -254,13 +254,13 @@ let BoundValueInfoBySize vinfo = | SizeValue (vdepth, vinfo) -> if vdepth < depth then x else MakeSizedValueInfo (bound depth vinfo) | ValValue (vr, vinfo) -> ValValue (vr, bound (depth-1) vinfo) | TupleValue vinfos -> TupleValue (Array.map (bound (depth-1)) vinfos) - | RecdValue (tcref, vinfos) -> RecdValue (tcref, Array.map (bound (depth-1)) vinfos) + | RecdValue (tcref, vinfos) -> RecdValue (tcref, Array.map (bound (depth-1)) vinfos) | UnionCaseValue (ucr, vinfos) -> UnionCaseValue (ucr, Array.map (bound (depth-1)) vinfos) | ConstValue _ -> x | UnknownValue -> x | CurriedLambdaValue(_lambdaId, _arities, _bsize, _expr, _ety) -> x | ConstExprValue (_size, _) -> x - let maxDepth = 6 (* beware huge constants! *) + let maxDepth = 6 (* beware huge constants! *) let trimDepth = 3 let vdepth = SizeOfValueInfo vinfo if vdepth > maxDepth @@ -431,7 +431,7 @@ let CheckInlineValueIsComplete (v: Val) res = 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) @@ -450,7 +450,7 @@ let rec UnionOptimizationInfos (minfos : seq) = ModuleOrNamespaceInfos = minfos |> Seq.map (fun m -> m.Force().ModuleOrNamespaceInfos) - |> NameMap.union UnionOptimizationInfos } + |> NameMap.union UnionOptimizationInfos } let FindOrCreateModuleInfo n (ss: Map<_, _>) = match ss.TryFind n with @@ -463,18 +463,18 @@ let FindOrCreateGlobalModuleInfo n (ss: LayeredMap<_, _>) = | None -> EmptyModuleInfo let rec BindValueInSubModuleFSharpCore (mp: string[]) i (v: Val) vval ss = - if i < mp.Length then + if i < mp.Length then {ss with ModuleOrNamespaceInfos = BindValueInModuleForFslib mp.[i] mp (i+1) v vval ss.ModuleOrNamespaceInfos } else // REVIEW: this line looks quadratic for performance when compiling FSharp.Core {ss with ValInfos = ValInfos(Seq.append ss.ValInfos.Entries (Seq.singleton (mkLocalValRef v, vval))) } and BindValueInModuleForFslib n mp i v vval (ss: NameMap<_>) = - let old = FindOrCreateModuleInfo n ss + let old = FindOrCreateModuleInfo n ss Map.add n (notlazy (BindValueInSubModuleFSharpCore mp i v vval (old.Force()))) ss and BindValueInGlobalModuleForFslib n mp i v vval (ss: LayeredMap<_, _>) = - let old = FindOrCreateGlobalModuleInfo n ss + let old = FindOrCreateGlobalModuleInfo n ss ss.Add(n, notlazy (BindValueInSubModuleFSharpCore mp i v vval (old.Force()))) let BindValueForFslib (nlvref : NonLocalValOrMemberRef) v vval env = @@ -482,7 +482,7 @@ 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 = @@ -509,7 +509,7 @@ let BindExternalLocalVal cenv (v: Val) vval env = | UnknownValue -> env | _ -> #endif - { env with localExternalVals=env.localExternalVals.Add (v.Stamp, vval) } + { env with localExternalVals=env.localExternalVals.Add (v.Stamp, vval) } // If we're compiling fslib then also bind the value as a non-local path to // allow us to resolve the compiler-non-local-references that arise from env.fs // @@ -530,7 +530,7 @@ let BindExternalLocalVal cenv (v: Val) vval 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 = (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) env @@ -560,12 +560,12 @@ let BindTypeVarsToUnknown (tps: Typar list) env = // The names chosen are 'a', 'b' etc. These are also the compiled names in the IL code let nms = PrettyTypes.PrettyTyparNames (fun _ -> true) (env.typarInfos |> List.map (fun (tp, _) -> tp.Name) ) tps (tps, nms) ||> List.iter2 (fun tp nm -> - if PrettyTypes.NeedsPrettyTyparName tp then + if PrettyTypes.NeedsPrettyTyparName tp then 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) = - { env with globalModuleInfos=env.globalModuleInfos.Add(ccu.AssemblyName, mval) } + { env with globalModuleInfos=env.globalModuleInfos.Add(ccu.AssemblyName, mval) } /// Lookup information about values let GetInfoForLocalValue cenv env (v: Val) m = @@ -606,7 +606,7 @@ let TryGetInfoForNonLocalEntityRef env (nleref: NonLocalEntityRef) = let GetInfoForNonLocalVal cenv env (vref: ValRef) = if vref.IsDispatchSlot then UnknownValInfo - // REVIEW: optionally turn x-module on/off on per-module basis or + // REVIEW: optionally turn x-module on/off on per-module basis or elif cenv.settings.crossModuleOpt () || vref.MustInline then match TryGetInfoForNonLocalEntityRef env vref.nlr.EnclosingEntity.nlr with | Some(structInfo) -> @@ -645,7 +645,7 @@ let GetInfoForVal cenv env m (vref: ValRef) = let rec stripValue = function | ValValue(_, details) -> stripValue details (* step through ValValue "aliases" *) | SizeValue(_, details) -> stripValue details (* step through SizeValue "aliases" *) - | vinfo -> vinfo + | vinfo -> vinfo let (|StripConstValue|_|) ev = match stripValue ev with @@ -692,18 +692,18 @@ let mkUInt64Val (g: TcGlobals) n = ConstValue(Const.UInt64 n, g.uint64_ty) let (|StripInt32Value|_|) = function StripConstValue(Const.Int32 n) -> Some n | _ -> None -let MakeValueInfoForValue g m vref vinfo = +let MakeValueInfoForValue g m vref vinfo = #if DEBUG let rec check x = match x with - | ValValue (vref2, detail) -> if valRefEq g vref vref2 then error(Error(FSComp.SR.optRecursiveValValue(showL(exprValueInfoL g vinfo)), m)) else check detail + | ValValue (vref2, detail) -> if valRefEq g vref vref2 then error(Error(FSComp.SR.optRecursiveValValue(showL(exprValueInfoL g vinfo)), m)) else check detail | SizeValue (_n, detail) -> check detail | _ -> () check vinfo #else ignore g; ignore m #endif - ValValue (vref, vinfo) |> BoundValueInfoBySize + ValValue (vref, vinfo) |> BoundValueInfoBySize let MakeValueInfoForRecord tcref argvals = RecdValue (tcref, argvals) |> BoundValueInfoBySize @@ -721,12 +721,12 @@ let inline IntegerUnaryOp g f8 f16 f32 f64 fu8 fu16 fu32 fu64 a = match a with | StripConstValue(c) -> match c with - | Const.Bool a -> Some(mkBoolVal g (f32 (if a then 1 else 0) <> 0)) - | Const.Int32 a -> Some(mkInt32Val g (f32 a)) - | Const.Int64 a -> Some(mkInt64Val g (f64 a)) - | Const.Int16 a -> Some(mkInt16Val g (f16 a)) - | Const.SByte a -> Some(mkInt8Val g (f8 a)) - | Const.Byte a -> Some(mkUInt8Val g (fu8 a)) + | Const.Bool a -> Some(mkBoolVal g (f32 (if a then 1 else 0) <> 0)) + | Const.Int32 a -> Some(mkInt32Val g (f32 a)) + | Const.Int64 a -> Some(mkInt64Val g (f64 a)) + | Const.Int16 a -> Some(mkInt16Val g (f16 a)) + | Const.SByte a -> Some(mkInt8Val g (f8 a)) + | Const.Byte a -> Some(mkUInt8Val g (fu8 a)) | Const.UInt32 a -> Some(mkUInt32Val g (fu32 a)) | Const.UInt64 a -> Some(mkUInt64Val g (fu64 a)) | Const.UInt16 a -> Some(mkUInt16Val g (fu16 a)) @@ -741,7 +741,7 @@ let inline SignedIntegerUnaryOp g f8 f16 f32 f64 a = | Const.Int32 a -> Some(mkInt32Val g (f32 a)) | Const.Int64 a -> Some(mkInt64Val g (f64 a)) | Const.Int16 a -> Some(mkInt16Val g (f16 a)) - | Const.SByte a -> Some(mkInt8Val g (f8 a)) + | Const.SByte a -> Some(mkInt8Val g (f8 a)) | _ -> None | _ -> None @@ -750,12 +750,12 @@ let inline IntegerBinaryOp g f8 f16 f32 f64 fu8 fu16 fu32 fu64 a b = match a, b with | StripConstValue(c1), StripConstValue(c2) -> match c1, c2 with - | (Const.Bool a), (Const.Bool b) -> Some(mkBoolVal g (f32 (if a then 1 else 0) (if b then 1 else 0) <> 0)) - | (Const.Int32 a), (Const.Int32 b) -> Some(mkInt32Val g (f32 a b)) - | (Const.Int64 a), (Const.Int64 b) -> Some(mkInt64Val g (f64 a b)) - | (Const.Int16 a), (Const.Int16 b) -> Some(mkInt16Val g (f16 a b)) - | (Const.SByte a), (Const.SByte b) -> Some(mkInt8Val g (f8 a b)) - | (Const.Byte a), (Const.Byte b) -> Some(mkUInt8Val g (fu8 a b)) + | (Const.Bool a), (Const.Bool b) -> Some(mkBoolVal g (f32 (if a then 1 else 0) (if b then 1 else 0) <> 0)) + | (Const.Int32 a), (Const.Int32 b) -> Some(mkInt32Val g (f32 a b)) + | (Const.Int64 a), (Const.Int64 b) -> Some(mkInt64Val g (f64 a b)) + | (Const.Int16 a), (Const.Int16 b) -> Some(mkInt16Val g (f16 a b)) + | (Const.SByte a), (Const.SByte b) -> Some(mkInt8Val g (f8 a b)) + | (Const.Byte a), (Const.Byte b) -> Some(mkUInt8Val g (fu8 a b)) | (Const.UInt16 a), (Const.UInt16 b) -> Some(mkUInt16Val g (fu16 a b)) | (Const.UInt32 a), (Const.UInt32 b) -> Some(mkUInt32Val g (fu32 a b)) | (Const.UInt64 a), (Const.UInt64 b) -> Some(mkUInt64Val g (fu64 a b)) @@ -781,29 +781,29 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = match IntegerBinaryOp g Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) Unchecked.(-) t1 t2 with | Some res -> res | _ -> UnknownValue - | [ AI_mul ], [a;b], _ -> (match IntegerBinaryOp g Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) a b with Some res -> res | None -> UnknownValue) - | [ AI_and ], [a;b], _ -> (match IntegerBinaryOp g (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) a b with Some res -> res | None -> UnknownValue) - | [ AI_or ], [a;b], _ -> (match IntegerBinaryOp g (|||) (|||) (|||) (|||) (|||) (|||) (|||) (|||) a b with Some res -> res | None -> UnknownValue) - | [ AI_xor ], [a;b], _ -> (match IntegerBinaryOp g (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) a b with Some res -> res | None -> UnknownValue) + | [ AI_mul ], [a;b], _ -> (match IntegerBinaryOp g Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) Unchecked.( * ) a b with Some res -> res | None -> UnknownValue) + | [ AI_and ], [a;b], _ -> (match IntegerBinaryOp g (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) (&&&) a b with Some res -> res | None -> UnknownValue) + | [ AI_or ], [a;b], _ -> (match IntegerBinaryOp g (|||) (|||) (|||) (|||) (|||) (|||) (|||) (|||) a b with Some res -> res | None -> UnknownValue) + | [ AI_xor ], [a;b], _ -> (match IntegerBinaryOp g (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) (^^^) a b with Some res -> res | None -> UnknownValue) | [ AI_not ], [a], _ -> (match IntegerUnaryOp g (~~~) (~~~) (~~~) (~~~) (~~~) (~~~) (~~~) (~~~) a with Some res -> res | None -> UnknownValue) | [ AI_neg ], [a], _ -> (match SignedIntegerUnaryOp g (~-) (~-) (~-) (~-) a with Some res -> res | None -> UnknownValue) | [ AI_ceq ], [a;b], _ -> match stripValue a, stripValue b with - | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkBoolVal g (a1 = a2) - | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkBoolVal g (a1 = a2) + | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkBoolVal g (a1 = a2) | _ -> UnknownValue | [ AI_clt ], [a;b], _ -> match stripValue a, stripValue b with - | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkBoolVal g (a1 < a2) + | ConstValue(Const.Bool a1, _), ConstValue(Const.Bool a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkBoolVal g (a1 < a2) @@ -811,137 +811,137 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = | _ -> UnknownValue | [ (AI_conv(DT_U1))], [a], [ty] when typeEquiv g ty g.byte_ty -> match stripValue a with - | ConstValue(Const.SByte a, _) -> mkUInt8Val g (Unchecked.byte a) - | ConstValue(Const.Int16 a, _) -> mkUInt8Val g (Unchecked.byte a) - | ConstValue(Const.Int32 a, _) -> mkUInt8Val g (Unchecked.byte a) - | ConstValue(Const.Int64 a, _) -> mkUInt8Val g (Unchecked.byte a) - | ConstValue(Const.Byte a, _) -> mkUInt8Val g (Unchecked.byte a) + | ConstValue(Const.SByte a, _) -> mkUInt8Val g (Unchecked.byte a) + | ConstValue(Const.Int16 a, _) -> mkUInt8Val g (Unchecked.byte a) + | ConstValue(Const.Int32 a, _) -> mkUInt8Val g (Unchecked.byte a) + | ConstValue(Const.Int64 a, _) -> mkUInt8Val g (Unchecked.byte a) + | ConstValue(Const.Byte a, _) -> mkUInt8Val g (Unchecked.byte a) | ConstValue(Const.UInt16 a, _) -> mkUInt8Val g (Unchecked.byte a) | ConstValue(Const.UInt32 a, _) -> mkUInt8Val g (Unchecked.byte a) | ConstValue(Const.UInt64 a, _) -> mkUInt8Val g (Unchecked.byte a) | _ -> UnknownValue | [ (AI_conv(DT_U2))], [a], [ty] when typeEquiv g ty g.uint16_ty -> match stripValue a with - | ConstValue(Const.SByte a, _) -> mkUInt16Val g (Unchecked.uint16 a) - | ConstValue(Const.Int16 a, _) -> mkUInt16Val g (Unchecked.uint16 a) - | ConstValue(Const.Int32 a, _) -> mkUInt16Val g (Unchecked.uint16 a) - | ConstValue(Const.Int64 a, _) -> mkUInt16Val g (Unchecked.uint16 a) - | ConstValue(Const.Byte a, _) -> mkUInt16Val g (Unchecked.uint16 a) + | ConstValue(Const.SByte a, _) -> mkUInt16Val g (Unchecked.uint16 a) + | ConstValue(Const.Int16 a, _) -> mkUInt16Val g (Unchecked.uint16 a) + | ConstValue(Const.Int32 a, _) -> mkUInt16Val g (Unchecked.uint16 a) + | ConstValue(Const.Int64 a, _) -> mkUInt16Val g (Unchecked.uint16 a) + | ConstValue(Const.Byte a, _) -> mkUInt16Val g (Unchecked.uint16 a) | ConstValue(Const.UInt16 a, _) -> mkUInt16Val g (Unchecked.uint16 a) | ConstValue(Const.UInt32 a, _) -> mkUInt16Val g (Unchecked.uint16 a) | ConstValue(Const.UInt64 a, _) -> mkUInt16Val g (Unchecked.uint16 a) | _ -> UnknownValue | [ (AI_conv(DT_U4))], [a], [ty] when typeEquiv g ty g.uint32_ty -> match stripValue a with - | ConstValue(Const.SByte a, _) -> mkUInt32Val g (Unchecked.uint32 a) - | ConstValue(Const.Int16 a, _) -> mkUInt32Val g (Unchecked.uint32 a) - | ConstValue(Const.Int32 a, _) -> mkUInt32Val g (Unchecked.uint32 a) - | ConstValue(Const.Int64 a, _) -> mkUInt32Val g (Unchecked.uint32 a) - | ConstValue(Const.Byte a, _) -> mkUInt32Val g (Unchecked.uint32 a) + | ConstValue(Const.SByte a, _) -> mkUInt32Val g (Unchecked.uint32 a) + | ConstValue(Const.Int16 a, _) -> mkUInt32Val g (Unchecked.uint32 a) + | ConstValue(Const.Int32 a, _) -> mkUInt32Val g (Unchecked.uint32 a) + | ConstValue(Const.Int64 a, _) -> mkUInt32Val g (Unchecked.uint32 a) + | ConstValue(Const.Byte a, _) -> mkUInt32Val g (Unchecked.uint32 a) | ConstValue(Const.UInt16 a, _) -> mkUInt32Val g (Unchecked.uint32 a) | ConstValue(Const.UInt32 a, _) -> mkUInt32Val g (Unchecked.uint32 a) | ConstValue(Const.UInt64 a, _) -> mkUInt32Val g (Unchecked.uint32 a) | _ -> UnknownValue - | [ (AI_conv(DT_U8))], [a], [ty] when typeEquiv g ty g.uint64_ty -> + | [ (AI_conv(DT_U8))], [a], [ty] when typeEquiv g ty g.uint64_ty -> match stripValue a with - | ConstValue(Const.SByte a, _) -> mkUInt64Val g (Unchecked.uint64 a) - | ConstValue(Const.Int16 a, _) -> mkUInt64Val g (Unchecked.uint64 a) - | ConstValue(Const.Int32 a, _) -> mkUInt64Val g (Unchecked.uint64 a) - | ConstValue(Const.Int64 a, _) -> mkUInt64Val g (Unchecked.uint64 a) - | ConstValue(Const.Byte a, _) -> mkUInt64Val g (Unchecked.uint64 a) + | ConstValue(Const.SByte a, _) -> mkUInt64Val g (Unchecked.uint64 a) + | ConstValue(Const.Int16 a, _) -> mkUInt64Val g (Unchecked.uint64 a) + | ConstValue(Const.Int32 a, _) -> mkUInt64Val g (Unchecked.uint64 a) + | ConstValue(Const.Int64 a, _) -> mkUInt64Val g (Unchecked.uint64 a) + | ConstValue(Const.Byte a, _) -> mkUInt64Val g (Unchecked.uint64 a) | ConstValue(Const.UInt16 a, _) -> mkUInt64Val g (Unchecked.uint64 a) | ConstValue(Const.UInt32 a, _) -> mkUInt64Val g (Unchecked.uint64 a) | ConstValue(Const.UInt64 a, _) -> mkUInt64Val g (Unchecked.uint64 a) | _ -> UnknownValue - | [ (AI_conv(DT_I1))], [a], [ty] when typeEquiv g ty g.sbyte_ty -> + | [ (AI_conv(DT_I1))], [a], [ty] when typeEquiv g ty g.sbyte_ty -> match stripValue a with - | ConstValue(Const.SByte a, _) -> mkInt8Val g (Unchecked.sbyte a) - | ConstValue(Const.Int16 a, _) -> mkInt8Val g (Unchecked.sbyte a) - | ConstValue(Const.Int32 a, _) -> mkInt8Val g (Unchecked.sbyte a) - | ConstValue(Const.Int64 a, _) -> mkInt8Val g (Unchecked.sbyte a) - | ConstValue(Const.Byte a, _) -> mkInt8Val g (Unchecked.sbyte a) + | ConstValue(Const.SByte a, _) -> mkInt8Val g (Unchecked.sbyte a) + | ConstValue(Const.Int16 a, _) -> mkInt8Val g (Unchecked.sbyte a) + | ConstValue(Const.Int32 a, _) -> mkInt8Val g (Unchecked.sbyte a) + | ConstValue(Const.Int64 a, _) -> mkInt8Val g (Unchecked.sbyte a) + | ConstValue(Const.Byte a, _) -> mkInt8Val g (Unchecked.sbyte a) | ConstValue(Const.UInt16 a, _) -> mkInt8Val g (Unchecked.sbyte a) | ConstValue(Const.UInt32 a, _) -> mkInt8Val g (Unchecked.sbyte a) | ConstValue(Const.UInt64 a, _) -> mkInt8Val g (Unchecked.sbyte a) | _ -> UnknownValue - | [ (AI_conv(DT_I2))], [a], [ty] when typeEquiv g ty g.int16_ty -> + | [ (AI_conv(DT_I2))], [a], [ty] when typeEquiv g ty g.int16_ty -> match stripValue a with - | ConstValue(Const.Int32 a, _) -> mkInt16Val g (Unchecked.int16 a) - | ConstValue(Const.Int16 a, _) -> mkInt16Val g (Unchecked.int16 a) - | ConstValue(Const.SByte a, _) -> mkInt16Val g (Unchecked.int16 a) - | ConstValue(Const.Int64 a, _) -> mkInt16Val g (Unchecked.int16 a) + | ConstValue(Const.Int32 a, _) -> mkInt16Val g (Unchecked.int16 a) + | ConstValue(Const.Int16 a, _) -> mkInt16Val g (Unchecked.int16 a) + | ConstValue(Const.SByte a, _) -> mkInt16Val g (Unchecked.int16 a) + | ConstValue(Const.Int64 a, _) -> mkInt16Val g (Unchecked.int16 a) | ConstValue(Const.UInt32 a, _) -> mkInt16Val g (Unchecked.int16 a) | ConstValue(Const.UInt16 a, _) -> mkInt16Val g (Unchecked.int16 a) - | ConstValue(Const.Byte a, _) -> mkInt16Val g (Unchecked.int16 a) + | ConstValue(Const.Byte a, _) -> mkInt16Val g (Unchecked.int16 a) | ConstValue(Const.UInt64 a, _) -> mkInt16Val g (Unchecked.int16 a) | _ -> UnknownValue | [ (AI_conv(DT_I4))], [a], [ty] when typeEquiv g ty g.int32_ty -> match stripValue a with - | ConstValue(Const.Int32 a, _) -> mkInt32Val g (Unchecked.int32 a) - | ConstValue(Const.Int16 a, _) -> mkInt32Val g (Unchecked.int32 a) - | ConstValue(Const.SByte a, _) -> mkInt32Val g (Unchecked.int32 a) - | ConstValue(Const.Int64 a, _) -> mkInt32Val g (Unchecked.int32 a) + | ConstValue(Const.Int32 a, _) -> mkInt32Val g (Unchecked.int32 a) + | ConstValue(Const.Int16 a, _) -> mkInt32Val g (Unchecked.int32 a) + | ConstValue(Const.SByte a, _) -> mkInt32Val g (Unchecked.int32 a) + | ConstValue(Const.Int64 a, _) -> mkInt32Val g (Unchecked.int32 a) | ConstValue(Const.UInt32 a, _) -> mkInt32Val g (Unchecked.int32 a) | ConstValue(Const.UInt16 a, _) -> mkInt32Val g (Unchecked.int32 a) - | ConstValue(Const.Byte a, _) -> mkInt32Val g (Unchecked.int32 a) + | ConstValue(Const.Byte a, _) -> mkInt32Val g (Unchecked.int32 a) | ConstValue(Const.UInt64 a, _) -> mkInt32Val g (Unchecked.int32 a) | _ -> UnknownValue - | [ (AI_conv(DT_I8))], [a], [ty] when typeEquiv g ty g.int64_ty -> + | [ (AI_conv(DT_I8))], [a], [ty] when typeEquiv g ty g.int64_ty -> match stripValue a with - | ConstValue(Const.Int32 a, _) -> mkInt64Val g (Unchecked.int64 a) - | ConstValue(Const.Int16 a, _) -> mkInt64Val g (Unchecked.int64 a) - | ConstValue(Const.SByte a, _) -> mkInt64Val g (Unchecked.int64 a) - | ConstValue(Const.Int64 a, _) -> mkInt64Val g (Unchecked.int64 a) + | ConstValue(Const.Int32 a, _) -> mkInt64Val g (Unchecked.int64 a) + | ConstValue(Const.Int16 a, _) -> mkInt64Val g (Unchecked.int64 a) + | ConstValue(Const.SByte a, _) -> mkInt64Val g (Unchecked.int64 a) + | ConstValue(Const.Int64 a, _) -> mkInt64Val g (Unchecked.int64 a) | ConstValue(Const.UInt32 a, _) -> mkInt64Val g (Unchecked.int64 a) | ConstValue(Const.UInt16 a, _) -> mkInt64Val g (Unchecked.int64 a) - | ConstValue(Const.Byte a, _) -> mkInt64Val g (Unchecked.int64 a) + | ConstValue(Const.Byte a, _) -> mkInt64Val g (Unchecked.int64 a) | ConstValue(Const.UInt64 a, _) -> mkInt64Val g (Unchecked.int64 a) | _ -> UnknownValue - | [ AI_clt_un ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> + | [ AI_clt_un ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> match stripValue a, stripValue b with - | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkBoolVal g (a1 < a2) - | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkBoolVal g (a1 < a2) + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkBoolVal g (a1 < a2) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkBoolVal g (a1 < a2) | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkBoolVal g (a1 < a2) | _ -> UnknownValue - | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> + | [ AI_cgt ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> match stripValue a, stripValue b with - | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkBoolVal g (a1 > a2) - | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkBoolVal g (a1 > a2) - | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 > a2) - | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkBoolVal g (a1 > a2) + | ConstValue(Const.SByte a1, _), ConstValue(Const.SByte a2, _) -> mkBoolVal g (a1 > a2) + | ConstValue(Const.Int16 a1, _), ConstValue(Const.Int16 a2, _) -> mkBoolVal g (a1 > a2) + | ConstValue(Const.Int32 a1, _), ConstValue(Const.Int32 a2, _) -> mkBoolVal g (a1 > a2) + | ConstValue(Const.Int64 a1, _), ConstValue(Const.Int64 a2, _) -> mkBoolVal g (a1 > a2) | _ -> UnknownValue - | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> + | [ AI_cgt_un ], [a;b], [ty] when typeEquiv g ty g.bool_ty -> match stripValue a, stripValue b with - | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkBoolVal g (a1 > a2) - | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkBoolVal g (a1 > a2) + | ConstValue(Const.Char a1, _), ConstValue(Const.Char a2, _) -> mkBoolVal g (a1 > a2) + | ConstValue(Const.Byte a1, _), ConstValue(Const.Byte a2, _) -> mkBoolVal g (a1 > a2) | ConstValue(Const.UInt16 a1, _), ConstValue(Const.UInt16 a2, _) -> mkBoolVal g (a1 > a2) | ConstValue(Const.UInt32 a1, _), ConstValue(Const.UInt32 a2, _) -> mkBoolVal g (a1 > a2) | ConstValue(Const.UInt64 a1, _), ConstValue(Const.UInt64 a2, _) -> mkBoolVal g (a1 > a2) | _ -> UnknownValue | [ AI_shl ], [a;n], _ -> match stripValue a, stripValue n with - | ConstValue(Const.Int64 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 63 -> (mkInt64Val g (a <<< n)) - | ConstValue(Const.Int32 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 31 -> (mkInt32Val g (a <<< n)) - | ConstValue(Const.Int16 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 15 -> (mkInt16Val g (a <<< n)) - | ConstValue(Const.SByte a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 7 -> (mkInt8Val g (a <<< n)) + | ConstValue(Const.Int64 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 63 -> (mkInt64Val g (a <<< n)) + | ConstValue(Const.Int32 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 31 -> (mkInt32Val g (a <<< n)) + | ConstValue(Const.Int16 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 15 -> (mkInt16Val g (a <<< n)) + | ConstValue(Const.SByte a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 7 -> (mkInt8Val g (a <<< n)) | ConstValue(Const.UInt64 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 63 -> (mkUInt64Val g (a <<< n)) | ConstValue(Const.UInt32 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 31 -> (mkUInt32Val g (a <<< n)) | ConstValue(Const.UInt16 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 15 -> (mkUInt16Val g (a <<< n)) - | ConstValue(Const.Byte a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 7 -> (mkUInt8Val g (a <<< n)) + | ConstValue(Const.Byte a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 7 -> (mkUInt8Val g (a <<< n)) | _ -> UnknownValue | [ AI_shr ], [a;n], _ -> match stripValue a, stripValue n with - | ConstValue(Const.SByte a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 7 -> (mkInt8Val g (a >>> n)) + | ConstValue(Const.SByte a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 7 -> (mkInt8Val g (a >>> n)) | ConstValue(Const.Int16 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 15 -> (mkInt16Val g (a >>> n)) | ConstValue(Const.Int32 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 31 -> (mkInt32Val g (a >>> n)) | ConstValue(Const.Int64 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 63 -> (mkInt64Val g (a >>> n)) | _ -> UnknownValue | [ AI_shr_un ], [a;n], _ -> match stripValue a, stripValue n with - | ConstValue(Const.Byte a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 7 -> (mkUInt8Val g (a >>> n)) + | ConstValue(Const.Byte a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 7 -> (mkUInt8Val g (a >>> n)) | ConstValue(Const.UInt16 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 15 -> (mkUInt16Val g (a >>> n)) | ConstValue(Const.UInt32 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 31 -> (mkUInt32Val g (a >>> n)) | ConstValue(Const.UInt64 a, _), ConstValue(Const.Int32 n, _) when n >= 0 && n <= 63 -> (mkUInt64Val g (a >>> n)) @@ -953,7 +953,7 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = // We're conservative not to apply any actual data-changing conversions here. | [ ], [v], [ty] -> match stripValue v with - | ConstValue(Const.Bool a, _) -> + | ConstValue(Const.Bool a, _) -> if typeEquiv g ty g.bool_ty then v elif typeEquiv g ty g.sbyte_ty then mkInt8Val g (if a then 1y else 0y) elif typeEquiv g ty g.int16_ty then mkInt16Val g (if a then 1s else 0s) @@ -962,37 +962,37 @@ let mkAssemblyCodeValueInfo g instrs argvals tys = elif typeEquiv g ty g.uint16_ty then mkUInt16Val g (if a then 1us else 0us) elif typeEquiv g ty g.uint32_ty then mkUInt32Val g (if a then 1u else 0u) else UnknownValue - | ConstValue(Const.SByte a, _) -> + | ConstValue(Const.SByte a, _) -> if typeEquiv g ty g.sbyte_ty then v elif typeEquiv g ty g.int16_ty then mkInt16Val g (Unchecked.int16 a) elif typeEquiv g ty g.int32_ty then mkInt32Val g (Unchecked.int32 a) else UnknownValue - | ConstValue(Const.Byte a, _) -> + | ConstValue(Const.Byte a, _) -> if typeEquiv g ty g.byte_ty then v elif typeEquiv g ty g.uint16_ty then mkUInt16Val g (Unchecked.uint16 a) elif typeEquiv g ty g.uint32_ty then mkUInt32Val g (Unchecked.uint32 a) else UnknownValue - | ConstValue(Const.Int16 a, _) -> + | ConstValue(Const.Int16 a, _) -> if typeEquiv g ty g.int16_ty then v elif typeEquiv g ty g.int32_ty then mkInt32Val g (Unchecked.int32 a) else UnknownValue - | ConstValue(Const.UInt16 a, _) -> + | ConstValue(Const.UInt16 a, _) -> if typeEquiv g ty g.uint16_ty then v elif typeEquiv g ty g.uint32_ty then mkUInt32Val g (Unchecked.uint32 a) else UnknownValue - | ConstValue(Const.Int32 a, _) -> + | ConstValue(Const.Int32 a, _) -> if typeEquiv g ty g.int32_ty then v elif typeEquiv g ty g.uint32_ty then mkUInt32Val g (Unchecked.uint32 a) else UnknownValue - | ConstValue(Const.UInt32 a, _) -> + | ConstValue(Const.UInt32 a, _) -> if typeEquiv g ty g.uint32_ty then v elif typeEquiv g ty g.int32_ty then mkInt32Val g (Unchecked.int32 a) else UnknownValue - | ConstValue(Const.Int64 a, _) -> + | ConstValue(Const.Int64 a, _) -> if typeEquiv g ty g.int64_ty then v elif typeEquiv g ty g.uint64_ty then mkUInt64Val g (Unchecked.uint64 a) else UnknownValue - | ConstValue(Const.UInt64 a, _) -> + | ConstValue(Const.UInt64 a, _) -> if typeEquiv g ty g.uint64_ty then v elif typeEquiv g ty g.int64_ty then mkInt64Val g (Unchecked.int64 a) else UnknownValue @@ -1021,8 +1021,8 @@ let NoExprs : (Expr list * list>) = [], [] /// Common ways of building new value infos let CombineValueInfos einfos res = - { TotalSize = AddTotalSizes einfos - FunctionSize = AddFunctionSizes einfos + { TotalSize = AddTotalSizes einfos + FunctionSize = AddFunctionSizes einfos HasEffect = OrEffects einfos MightMakeCriticalTailcall = OrTailcalls einfos Info = res } @@ -1060,10 +1060,10 @@ let AbstractLazyModulInfoByHiding isAssemblyBoundary mhi = | CurriedLambdaValue (_, _, _, expr, _) | ConstExprValue(_, expr) when (let fvs = freeInExpr CollectAll expr (isAssemblyBoundary && not (freeVarsAllPublic fvs)) || - Zset.exists hiddenVal fvs.FreeLocals || - Zset.exists hiddenTycon fvs.FreeTyvars.FreeTycons || - Zset.exists hiddenTyconRepr fvs.FreeLocalTyconReprs || - Zset.exists hiddenRecdField fvs.FreeRecdFields || + Zset.exists hiddenVal fvs.FreeLocals || + Zset.exists hiddenTycon fvs.FreeTyvars.FreeTycons || + Zset.exists hiddenTyconRepr fvs.FreeLocalTyconReprs || + Zset.exists hiddenRecdField fvs.FreeRecdFields || Zset.exists hiddenUnionCase fvs.FreeUnionCases ) -> UnknownValue @@ -1074,10 +1074,10 @@ let AbstractLazyModulInfoByHiding isAssemblyBoundary mhi = Zset.exists hiddenTycon ftyvs.FreeTycons) -> UnknownValue - | TupleValue vinfos -> + | TupleValue vinfos -> TupleValue (Array.map abstractExprInfo vinfos) - | RecdValue (tcref, vinfos) -> + | RecdValue (tcref, vinfos) -> if hiddenTyconRepr tcref.Deref || Array.exists (tcref.MakeNestedRecdFieldRef >> hiddenRecdField) tcref.AllFieldsArray then UnknownValue else RecdValue (tcref, Array.map abstractExprInfo vinfos) @@ -1088,13 +1088,13 @@ let AbstractLazyModulInfoByHiding isAssemblyBoundary mhi = then UnknownValue else UnionCaseValue (ucref, Array.map abstractExprInfo vinfos) - | SizeValue(_vdepth, vinfo) -> + | SizeValue(_vdepth, vinfo) -> MakeSizedValueInfo (abstractExprInfo vinfo) | UnknownValue | ConstExprValue _ | CurriedLambdaValue _ - | ConstValue _ -> ivalue + | ConstValue _ -> ivalue and abstractValInfo v = { ValExprInfo=abstractExprInfo v.ValExprInfo @@ -1105,7 +1105,7 @@ let AbstractLazyModulInfoByHiding isAssemblyBoundary mhi = ValInfos = ValInfos(ss.ValInfos.Entries |> 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) )) } + |> Seq.map (fun (vref, e) -> check (* "its implementation uses a binding hidden by a signature" m *) vref (abstractValInfo e) )) } and abstractLazyModulInfo (ss: LazyModuleInfo) = ss.Force() |> abstractModulInfo |> notlazy @@ -1117,13 +1117,13 @@ let AbstractOptimizationInfoToEssentials = let rec abstractModulInfo (ss: ModuleInfo) = { ModuleOrNamespaceInfos = NameMap.map (Lazy.force >> abstractModulInfo >> notlazy) ss.ModuleOrNamespaceInfos - ValInfos = ss.ValInfos.Filter (fun (v, _) -> v.MustInline) } + ValInfos = ss.ValInfos.Filter (fun (v, _) -> v.MustInline) } and abstractLazyModulInfo ss = ss |> Lazy.force |> abstractModulInfo |> notlazy abstractLazyModulInfo -/// Hide information because of a "let ... in ..." or "let rec ... in ... " +/// Hide information because of a "let ... in ..." or "let rec ... in ... " 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 @@ -1151,7 +1151,7 @@ let AbstractExprInfoByVars (boundVars: Val list, boundTyVars) ivalue = ValValue (v2, detailR) // Check for escape in lambda - | CurriedLambdaValue (_, _, _, expr, _) | ConstExprValue(_, expr) when + | CurriedLambdaValue (_, _, _, expr, _) | ConstExprValue(_, expr) when (let fvs = freeInExpr (if isNil boundTyVars then CollectLocals else CollectTyparsAndLocals) expr (not (isNil boundVars) && List.exists (Zset.memberOf fvs.FreeLocals) boundVars) || (not (isNil boundTyVars) && List.exists (Zset.memberOf fvs.FreeTyvars.FreeTypars) boundTyVars) || @@ -1182,7 +1182,7 @@ let AbstractExprInfoByVars (boundVars: Val list, boundTyVars) ivalue = ValMakesNoCriticalTailcalls=v.ValMakesNoCriticalTailcalls } and abstractModulInfo ss = - { ModuleOrNamespaceInfos = ss.ModuleOrNamespaceInfos |> NameMap.map (Lazy.force >> abstractModulInfo >> notlazy) + { ModuleOrNamespaceInfos = ss.ModuleOrNamespaceInfos |> NameMap.map (Lazy.force >> abstractModulInfo >> notlazy) ValInfos = ss.ValInfos.Map (fun (vref, e) -> check vref (abstractValInfo e) ) } @@ -1194,15 +1194,15 @@ let RemapOptimizationInfo g tmenv = let rec remapExprInfo ivalue = match ivalue with - | ValValue (v, detail) -> ValValue (remapValRef tmenv v, remapExprInfo detail) - | TupleValue vinfos -> TupleValue (Array.map remapExprInfo vinfos) - | RecdValue (tcref, vinfos) -> RecdValue (remapTyconRef tmenv.tyconRefRemap tcref, Array.map remapExprInfo vinfos) + | ValValue (v, detail) -> ValValue (remapValRef tmenv v, remapExprInfo detail) + | TupleValue vinfos -> TupleValue (Array.map remapExprInfo vinfos) + | RecdValue (tcref, vinfos) -> RecdValue (remapTyconRef tmenv.tyconRefRemap tcref, Array.map remapExprInfo vinfos) | UnionCaseValue(cspec, vinfos) -> UnionCaseValue (remapUnionCaseRef tmenv.tyconRefRemap cspec, Array.map remapExprInfo vinfos) | SizeValue(_vdepth, vinfo) -> MakeSizedValueInfo (remapExprInfo vinfo) - | UnknownValue -> UnknownValue - | CurriedLambdaValue (uniq, arity, sz, expr, ty) -> CurriedLambdaValue (uniq, arity, sz, remapExpr g CloneAll tmenv expr, remapPossibleForallTy g tmenv ty) - | ConstValue (c, ty) -> ConstValue (c, remapPossibleForallTy g tmenv ty) - | ConstExprValue (sz, expr) -> ConstExprValue (sz, remapExpr g CloneAll tmenv expr) + | UnknownValue -> UnknownValue + | CurriedLambdaValue (uniq, arity, sz, expr, ty) -> CurriedLambdaValue (uniq, arity, sz, remapExpr g CloneAll tmenv expr, remapPossibleForallTy g tmenv ty) + | ConstValue (c, ty) -> ConstValue (c, remapPossibleForallTy g tmenv ty) + | ConstExprValue (sz, expr) -> ConstExprValue (sz, remapExpr g CloneAll tmenv expr) let remapValInfo v = { ValExprInfo=remapExprInfo v.ValExprInfo @@ -1313,10 +1313,10 @@ let rec SplitValuesByIsUsedOrHasEffect cenv fvs x = let IlAssemblyCodeInstrHasEffect i = match i with - | ( AI_nop | AI_ldc _ | AI_add | AI_sub | AI_mul | AI_xor | AI_and | AI_or + | ( AI_nop | AI_ldc _ | AI_add | AI_sub | AI_mul | AI_xor | AI_and | AI_or | AI_ceq | AI_cgt | AI_cgt_un | AI_clt | AI_clt_un | AI_conv _ | AI_shl | AI_shr | AI_shr_un | AI_neg | AI_not | AI_ldnull ) - | I_ldstr _ | I_ldtoken _ -> false + | I_ldstr _ | I_ldtoken _ -> false | _ -> true let IlAssemblyCodeHasEffect instrs = List.exists IlAssemblyCodeInstrHasEffect instrs @@ -1361,8 +1361,8 @@ and OpHasEffect g m op = | TOp.ExnFieldGet(ecref, n) -> isExnFieldMutable ecref n | TOp.RefAddrGet _ -> false | TOp.AnonRecdGet _ -> true // conservative - | TOp.ValFieldGet rfref -> rfref.RecdField.IsMutable || (TryFindTyconRefBoolAttribute g Range.range0 g.attrib_AllowNullLiteralAttribute rfref.TyconRef = Some(true)) - | TOp.ValFieldGetAddr (rfref, _readonly) -> rfref.RecdField.IsMutable + | TOp.ValFieldGet rfref -> rfref.RecdField.IsMutable || (TryFindTyconRefBoolAttribute g Range.range0 g.attrib_AllowNullLiteralAttribute rfref.TyconRef = Some(true)) + | TOp.ValFieldGetAddr (rfref, _readonly) -> rfref.RecdField.IsMutable | TOp.UnionCaseFieldGetAddr _ -> false // union case fields are immutable | TOp.LValueOp (LAddrOf _, _) -> false // addresses of values are always constants | TOp.UnionCaseFieldSet _ @@ -1370,19 +1370,19 @@ and OpHasEffect g m op = | TOp.Coerce | TOp.Reraise | TOp.For _ - | TOp.While _ - | TOp.TryCatch _ (* conservative *) + | TOp.While _ + | TOp.TryCatch _ (* conservative *) | TOp.TryFinally _ (* conservative *) | TOp.TraitCall _ | TOp.Goto _ | TOp.Label _ | TOp.Return | TOp.ILCall _ (* conservative *) - | TOp.LValueOp _ (* conservative *) + | TOp.LValueOp _ (* conservative *) | TOp.ValFieldSet _ -> true -let TryEliminateBinding cenv _env (TBind(vspec1, e1, spBind)) e2 _m = +let TryEliminateBinding cenv _env (TBind(vspec1, e1, spBind)) e2 _m = // don't eliminate bindings if we're not optimizing AND the binding is not a compiler generated variable if not (cenv.optimizing && cenv.settings.EliminateImmediatelyConsumedLocals()) && not vspec1.IsCompilerGenerated then @@ -1430,7 +1430,7 @@ let TryEliminateBinding cenv _env (TBind(vspec1, e1, spBind)) e2 _m = | Expr.App(f, f0ty, tyargs, args, m) when not (vspec1.LogicalName.Contains(suffixForVariablesThatMayNotBeEliminated)) -> match GetImmediateUseContext [] (f::args) with - | Some([], rargs) -> Some (MakeApplicationAndBetaReduce cenv.g (e1, f0ty, [tyargs], rargs , m)) + | Some([], rargs) -> Some (MakeApplicationAndBetaReduce cenv.g (e1, f0ty, [tyargs], rargs, m)) | Some(f::largs, rargs) -> Some (MakeApplicationAndBetaReduce cenv.g (f, f0ty, [tyargs], largs @ (e1::rargs), m)) | None -> None @@ -1441,7 +1441,7 @@ let TryEliminateBinding cenv _env (TBind(vspec1, e1, spBind)) e2 _m = | Expr.Op (c1, tyargs1, [Expr.Op (c2, tyargs2, [arg1;arg2], m2);arg3], m1) -> match GetImmediateUseContext [] [arg1;arg2;arg3] with | Some([], [arg2;arg3]) -> Some (Expr.Op (c1, tyargs1, [Expr.Op (c2, tyargs2, [e1;arg2], m2);arg3], m1)) - | Some([arg1], [arg3]) -> Some (Expr.Op (c1, tyargs1, [Expr.Op (c2, tyargs2, [arg1;e1], m2);arg3], m1)) + | Some([arg1], [arg3]) -> Some (Expr.Op (c1, tyargs1, [Expr.Op (c2, tyargs2, [arg1;e1], m2);arg3], m1)) | Some([arg1;arg2], []) -> Some (Expr.Op (c1, tyargs1, [Expr.Op (c2, tyargs2, [arg1;arg2], m2);e1], m1)) | Some _ -> error(InternalError("unexpected return pattern from GetImmediateUseContext", m1)) | None -> None @@ -1458,8 +1458,8 @@ let TryEliminateBinding cenv _env (TBind(vspec1, e1, spBind)) e2 _m = let TryEliminateLet cenv env bind e2 m = match TryEliminateBinding cenv env bind e2 m with - | Some e2R -> e2R, -localVarSize (* eliminated a let, hence reduce size estimate *) - | None -> mkLetBind m bind e2 , 0 + | Some e2R -> e2R, -localVarSize (* eliminated a let, hence reduce size estimate *) + | None -> mkLetBind m bind e2, 0 /// Detect the application of a value to an arbitrary number of arguments let rec (|KnownValApp|_|) expr = @@ -1478,7 +1478,7 @@ let (|TDBoolSwitch|_|) dtree = None /// Check target that have a constant bool value -let (|ConstantBoolTarget|_|) target = +let (|ConstantBoolTarget|_|) target = match target with | TTarget([], Expr.Const (Const.Bool b,_,_),_) -> Some b | _ -> None @@ -1486,33 +1486,33 @@ let (|ConstantBoolTarget|_|) target = /// Is this a tree, where each decision is a two-way switch (to prevent later duplication of trees), and each branch returns or true/false, /// apart from one branch which defers to another expression let rec CountBoolLogicTree ((targets: DecisionTreeTarget[], costOuterCaseTree, costOuterDefaultTree, testBool) as data) tree = - match tree with + match tree with | TDSwitch (_expr, [case], Some defaultTree, _range) -> let tc1,ec1 = CountBoolLogicTree data case.CaseTree let tc2, ec2 = CountBoolLogicTree data defaultTree tc1 + tc2, ec1 + ec2 - | TDSuccess([], idx) -> + | TDSuccess([], idx) -> match targets.[idx] with | ConstantBoolTarget result -> (if result = testBool then costOuterCaseTree else costOuterDefaultTree), 0 | TTarget([], _exp, _) -> costOuterCaseTree + costOuterDefaultTree, 10 | _ -> 100, 100 | _ -> 100, 100 -/// Rewrite a decision tree for which CountBoolLogicTree returned a low number (see below). Produce a new decision +/// Rewrite a decision tree for which CountBoolLogicTree returned a low number (see below). Produce a new decision /// tree where at each ConstantBoolSuccessTree tip we replace with either outerCaseTree or outerDefaultTree /// depending on whether the target result was true/false let rec RewriteBoolLogicTree ((targets: DecisionTreeTarget[], outerCaseTree, outerDefaultTree, testBool) as data) tree = - match tree with + match tree with | TDSwitch (expr, cases, defaultTree, range) -> let cases2 = cases |> List.map (RewriteBoolLogicCase data) let defaultTree2 = defaultTree |> Option.map (RewriteBoolLogicTree data) - TDSwitch (expr, cases2, defaultTree2, range) - | TDSuccess([], idx) -> + TDSwitch (expr, cases2, defaultTree2, range) + | TDSuccess([], idx) -> match targets.[idx] with | ConstantBoolTarget result -> if result = testBool then outerCaseTree else outerDefaultTree | TTarget([], exp, _) -> mkBoolSwitch exp.Range exp (if testBool then outerCaseTree else outerDefaultTree) (if testBool then outerDefaultTree else outerCaseTree) | _ -> failwith "CountBoolLogicTree should exclude this case" - | _ -> failwith "CountBoolLogicTree should exclude this case" + | _ -> failwith "CountBoolLogicTree should exclude this case" and RewriteBoolLogicCase data (TCase(test, tree)) = TCase(test, RewriteBoolLogicTree data tree) @@ -1527,9 +1527,9 @@ let rec CombineBoolLogic expr = | Expr.Match(outerSP, outerMatchRange, TDBoolSwitch(Expr.Match(_innerSP, _innerMatchRange, innerTree, innerTargets, _innerDefaultRange, _innerMatchTy), outerTestBool, outerCaseTree, outerDefaultTree, _outerSwitchRange ), - outerTargets, outerDefaultRange, outerMatchTy) -> + outerTargets, outerDefaultRange, outerMatchTy) -> - let costOuterCaseTree = match outerCaseTree with TDSuccess _ -> 0 | _ -> 1 + let costOuterCaseTree = match outerCaseTree with TDSuccess _ -> 0 | _ -> 1 let costOuterDefaultTree = match outerDefaultTree with TDSuccess _ -> 0 | _ -> 1 let tc, ec = CountBoolLogicTree (innerTargets, costOuterCaseTree, costOuterDefaultTree, outerTestBool) innerTree // At most one expression, no overall duplication of TSwitch nodes @@ -1567,7 +1567,7 @@ let ExpandStructuralBindingRaw cenv expr = | Expr.Let (TBind(v, rhs, tgtSeqPtOpt), body, m, _) when (isRefTupleExpr rhs && CanExpandStructuralBinding v) -> - let args = tryDestRefTupleExpr rhs + let args = tryDestRefTupleExpr rhs if List.forall ExprIsValue args then expr (* avoid re-expanding when recursion hits original binding *) else @@ -1615,7 +1615,7 @@ let (|QueryRun|_|) g expr = match expr with | Expr.App(Expr.Val (vref, _, _), _, _, [_builder; arg], _) when valRefEq g vref g.query_run_value_vref -> Some (arg, None) - | Expr.App(Expr.Val (vref, _, _), _, [ elemTy ] , [_builder; arg], _) when valRefEq g vref g.query_run_enumerable_vref -> + | Expr.App(Expr.Val (vref, _, _), _, [ elemTy ], [_builder; arg], _) when valRefEq g vref g.query_run_enumerable_vref -> Some (arg, Some elemTy) | _ -> None @@ -1630,31 +1630,31 @@ let (|AnyInstanceMethodApp|_|) 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 + | _ -> None let (|QuerySourceEnumerable|_|) g = function - | InstanceMethodApp g g.query_source_vref ([resTy], _builder, [res]) -> Some (resTy, res) - | _ -> None + | InstanceMethodApp g g.query_source_vref ([resTy], _builder, [res]) -> Some (resTy, res) + | _ -> None let (|QueryFor|_|) g = function - | InstanceMethodApp g g.query_for_vref ([srcTy;qTy;resTy;_qInnerTy], _builder, [src;selector]) -> Some (qTy, srcTy, resTy, src, selector) - | _ -> None + | InstanceMethodApp g g.query_for_vref ([srcTy;qTy;resTy;_qInnerTy], _builder, [src;selector]) -> Some (qTy, srcTy, resTy, src, selector) + | _ -> None let (|QueryYield|_|) g = function - | InstanceMethodApp g g.query_yield_vref ([resTy;qTy], _builder, [res]) -> Some (qTy, resTy, res) - | _ -> None + | InstanceMethodApp g g.query_yield_vref ([resTy;qTy], _builder, [res]) -> Some (qTy, resTy, res) + | _ -> None let (|QueryYieldFrom|_|) g = function - | InstanceMethodApp g g.query_yield_from_vref ([resTy;qTy], _builder, [res]) -> Some (qTy, resTy, res) - | _ -> None + | InstanceMethodApp g g.query_yield_from_vref ([resTy;qTy], _builder, [res]) -> Some (qTy, resTy, res) + | _ -> None let (|QuerySelect|_|) g = function - | InstanceMethodApp g g.query_select_vref ([srcTy;qTy;resTy], _builder, [src;selector]) -> Some (qTy, srcTy, resTy, src, selector) - | _ -> None + | InstanceMethodApp g g.query_select_vref ([srcTy;qTy;resTy], _builder, [src;selector]) -> Some (qTy, srcTy, resTy, src, selector) + | _ -> None let (|QueryZero|_|) g = function - | InstanceMethodApp g g.query_zero_vref ([resTy;qTy], _builder, _) -> Some (qTy, resTy) - | _ -> None + | InstanceMethodApp g g.query_zero_vref ([resTy;qTy], _builder, _) -> Some (qTy, resTy) + | _ -> None /// Look for a possible tuple and transform let (|AnyRefTupleTrans|) e = @@ -1667,7 +1667,7 @@ let (|AnyQueryBuilderOpTrans|_|) g = function | Expr.App((Expr.Val (vref, _, _) as v), vty, tyargs, [builder; AnyRefTupleTrans( (src::rest), replaceArgs) ], m) when (match vref.ApparentEnclosingEntity with Parent tcref -> tyconRefEq g tcref g.query_builder_tcref | ParentNone -> false) -> Some (src, (fun newSource -> Expr.App(v, vty, tyargs, [builder; replaceArgs(newSource::rest)], m))) - | _ -> None + | _ -> None let mkUnitDelayLambda (g: TcGlobals) m e = let uv, _ = mkCompGenLocal m "unitVar" g.unit_ty @@ -1676,23 +1676,23 @@ let mkUnitDelayLambda (g: TcGlobals) m e = /// If this returns "Some" then the source is not IQueryable. // := // | query.Select(, ) --> Seq.map(qexprInner', ...) -// | query.For(, ) --> IQueryable if qexprInner is IQueryable, otherwise Seq.collect(qexprInner', ...) -// | query.Yield --> not IQueryable -// | query.YieldFrom --> not IQueryable -// | query.Op(, ) --> IQueryable if qexprInner is IQueryable, otherwise query.Op(qexprInner', ) -// | :> seq<_> --> IQueryable if qexprInner is IQueryable +// | query.For(, ) --> IQueryable if qexprInner is IQueryable, otherwise Seq.collect(qexprInner', ...) +// | query.Yield --> not IQueryable +// | query.YieldFrom --> not IQueryable +// | query.Op(, ) --> IQueryable if qexprInner is IQueryable, otherwise query.Op(qexprInner', ) +// | :> seq<_> --> IQueryable if qexprInner is IQueryable // // := // | query.Select(, ) --> IQueryable if qexprInner is IQueryable, otherwise seq { qexprInner' } -// | query.For(, ) --> IQueryable if qexprInner is IQueryable, otherwise seq { qexprInner' } -// | query.Yield --> not IQueryable, seq { } -// | query.YieldFrom --> not IQueryable, seq { yield! } -// | query.Op(, ) --> IQueryable if qexprOuter is IQueryable, otherwise query.Op(qexpOuter', ) +// | query.For(, ) --> IQueryable if qexprInner is IQueryable, otherwise seq { qexprInner' } +// | query.Yield --> not IQueryable, seq { } +// | query.YieldFrom --> not IQueryable, seq { yield! } +// | query.Op(, ) --> IQueryable if qexprOuter is IQueryable, otherwise query.Op(qexpOuter', ) let rec tryRewriteToSeqCombinators g (e: Expr) = let m = e.Range match e with - // query.Yield --> Seq.singleton - | QueryYield g (_, resultElemTy, vExpr) -> Some (mkCallSeqSingleton g m resultElemTy vExpr) + // query.Yield --> Seq.singleton + | QueryYield g (_, resultElemTy, vExpr) -> Some (mkCallSeqSingleton g m resultElemTy vExpr) // query.YieldFrom (query.Source s) --> s | QueryYieldFrom g (_, _, QuerySourceEnumerable g (_, resExpr)) -> Some resExpr @@ -1796,7 +1796,7 @@ let TryDetectQueryQuoteAndRun cenv (expr: Expr) = match reqdResultInfo, exprIsEnumerableInfo with | Some _, Some _ | None, None -> resultExpr // the expression is a QuerySource, the result is a QuerySource, nothing to do | Some resultElemTy, None -> mkCallGetQuerySourceAsEnumerable cenv.g expr.Range resultElemTy (TType_app(cenv.g.tcref_System_Collections_IEnumerable, [])) resultExpr - | None, Some (resultElemTy, qTy) -> mkCallNewQuerySource cenv.g expr.Range resultElemTy qTy resultExpr + | None, Some (resultElemTy, qTy) -> mkCallNewQuerySource cenv.g expr.Range resultElemTy qTy resultExpr Some resultExprAfterConvertToResultTy | None -> None @@ -1868,12 +1868,12 @@ let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = let ty = mkMultiLambdaTy m argvs rty OptimizeLambdas None cenv env topValInfo expr ty - | Expr.TyLambda(_lambdaId, tps, _body, _m, rty) -> + | Expr.TyLambda(_lambdaId, tps, _body, _m, rty) -> let topValInfo = ValReprInfo (ValReprInfo.InferTyparInfo tps, [], ValReprInfo.unnamedRetVal) let ty = mkForallTyIfNeeded tps rty OptimizeLambdas None cenv env topValInfo expr ty - | Expr.TyChoose _ -> + | Expr.TyChoose _ -> OptimizeExpr cenv env (TypeRelations.ChooseTyparSolutionsForFreeChoiceTypars cenv.g cenv.amap expr) | Expr.Match(spMatch, exprm, dtree, targets, m, ty) -> @@ -2015,10 +2015,10 @@ and OptimizeExprOp cenv env (op, tyargs, args, m) = Info = ValueOfExpr newExpr } // Handle these as special cases since mutables are allowed inside their bodies - | TOp.While (spWhile, marker), _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _)] -> + | TOp.While (spWhile, marker), _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _)] -> OptimizeWhileLoop cenv { env with inLoop=true } (spWhile, marker, e1, e2, m) - | TOp.For(spStart, dir), _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _);Expr.Lambda(_, _, _, [v], e3, _, _)] -> + | TOp.For(spStart, dir), _, [Expr.Lambda(_, _, _, [_], e1, _, _);Expr.Lambda(_, _, _, [_], e2, _, _);Expr.Lambda(_, _, _, [v], e3, _, _)] -> OptimizeFastIntegerForLoop cenv { env with inLoop=true } (spStart, v, e1, dir, e2, e3, m) | TOp.TryFinally(spTry, spFinally), [resty], [Expr.Lambda(_, _, _, [_], e1, _, _); Expr.Lambda(_, _, _, [_], e2, _, _)] -> @@ -2068,8 +2068,8 @@ and OptimizeExprOpReductionsAfter cenv env (op, tyargs, argsR, arginfos, m) = | _ -> None match knownValue with | Some valu -> - match TryOptimizeVal cenv env (false, valu, m) with - | Some res -> OptimizeExpr cenv env res (* discard e1 since guard ensures it has no effects *) + match TryOptimizeVal cenv env (false, valu, m) with + | Some res -> OptimizeExpr cenv env res (* discard e1 since guard ensures it has no effects *) | None -> OptimizeExprOpFallback cenv env (op, tyargs, argsR, m) arginfos valu | None -> OptimizeExprOpFallback cenv env (op, tyargs, argsR, m) arginfos UnknownValue @@ -2084,11 +2084,11 @@ and OptimizeExprOpFallback cenv env (op, tyargs, argsR, m) arginfos valu = match op with | TOp.UnionCase c -> 2, MakeValueInfoForUnionCase c (Array.ofList argValues) | TOp.ExnConstr _ -> 2, valu (* REVIEW: information collection possible here *) - | TOp.Tuple tupInfo -> + | TOp.Tuple tupInfo -> let isStruct = evalTupInfoIsStruct tupInfo if isStruct then 0, valu else 1,MakeValueInfoForTuple (Array.ofList argValues) - | TOp.AnonRecd anonInfo -> + | TOp.AnonRecd anonInfo -> let isStruct = evalAnonInfoIsStruct anonInfo if isStruct then 0, valu else 1, valu @@ -2097,22 +2097,22 @@ and OptimizeExprOpFallback cenv env (op, tyargs, argsR, m) arginfos valu = | TOp.TupleFieldGet _ | TOp.UnionCaseFieldGet _ | TOp.ExnFieldGet _ - | TOp.UnionCaseTagGet _ -> + | TOp.UnionCaseTagGet _ -> // REVIEW: reduction possible here, and may be very effective 1, valu - | TOp.UnionCaseProof _ -> + | TOp.UnionCaseProof _ -> // We count the proof as size 0 // We maintain the value of the source of the proof-cast if it is known to be a UnionCaseValue let valu = match argValues.[0] with | StripUnionCaseValue (uc, info) -> UnionCaseValue(uc, info) - | _ -> valu + | _ -> valu 0, valu - | TOp.ILAsm(instrs, tys) -> + | TOp.ILAsm(instrs, tys) -> min instrs.Length 1, mkAssemblyCodeValueInfo cenv.g instrs argValues tys - | TOp.Bytes bytes -> bytes.Length/10 , valu - | TOp.UInt16s bytes -> bytes.Length/10 , valu + | TOp.Bytes bytes -> bytes.Length/10, valu + | TOp.UInt16s bytes -> bytes.Length/10, valu | TOp.ValFieldGetAddr _ | TOp.Array | TOp.For _ | TOp.While _ | TOp.TryCatch _ | TOp.TryFinally _ | TOp.ILCall _ | TOp.TraitCall _ | TOp.LValueOp _ | TOp.ValFieldSet _ @@ -2204,8 +2204,8 @@ and OptimizeFastIntegerForLoop cenv env (spStart, v, e1, dir, e2, e3, m) = let env = BindInternalValToUnknown cenv v env let e3R, e3info = OptimizeExpr cenv env e3 // Try to replace F#-style loops with C# style loops that recompute their bounds but which are compiled more efficiently by the JITs, e.g. - // F# "for x = 0 to arr.Length - 1 do ..." --> C# "for (int x = 0; x < arr.Length; x++) { ... }" - // F# "for x = 0 to 10 do ..." --> C# "for (int x = 0; x < 11; x++) { ... }" + // F# "for x = 0 to arr.Length - 1 do ..." --> C# "for (int x = 0; x < arr.Length; x++) { ... }" + // F# "for x = 0 to 10 do ..." --> C# "for (int x = 0; x < 11; x++) { ... }" let e2R, dir = match dir, e2R with // detect upwards for loops with bounds of the form "arr.Length - 1" and convert them to a C#-style for loop @@ -2226,7 +2226,7 @@ and OptimizeFastIntegerForLoop cenv env (spStart, v, e1, dir, e2, e3, m) = let eff = OrEffects einfos (* neither bounds nor body has an effect, and loops always terminate, hence eliminate the loop *) if not eff then - mkUnit cenv.g m , { TotalSize=0; FunctionSize=0; HasEffect=false; MightMakeCriticalTailcall=false; Info=UnknownValue } + mkUnit cenv.g m, { TotalSize=0; FunctionSize=0; HasEffect=false; MightMakeCriticalTailcall=false; Info=UnknownValue } else let exprR = mkFor cenv.g (spStart, v, e1R, dir, e2R, e3R, m) exprR, { TotalSize=AddTotalSizes einfos + forAndWhileLoopSize @@ -2280,7 +2280,7 @@ and OptimizeLinearExpr cenv env expr contf = HasEffect = flag <> NormalSeq || e1info.HasEffect || e2info.HasEffect MightMakeCriticalTailcall = (if flag = NormalSeq then e2info.MightMakeCriticalTailcall - else e1info.MightMakeCriticalTailcall || e2info.MightMakeCriticalTailcall) + else e1info.MightMakeCriticalTailcall || e2info.MightMakeCriticalTailcall) // can't propagate value: must access result of computation for its effects Info = UnknownValue })) @@ -2291,7 +2291,7 @@ and OptimizeLinearExpr cenv env expr contf = // Is it quadratic or quasi-quadtratic? if ValueIsUsedOrHasEffect cenv (fun () -> (freeInExpr CollectLocals bodyR).FreeLocals) (bindR, bindingInfo) then // Eliminate let bindings on the way back up - let exprR, adjust = TryEliminateLet cenv env bindR bodyR m + let exprR, adjust = TryEliminateLet cenv env bindR bodyR m exprR, { TotalSize = bindingInfo.TotalSize + bodyInfo.TotalSize + adjust FunctionSize = bindingInfo.FunctionSize + bodyInfo.FunctionSize + adjust @@ -2360,8 +2360,8 @@ and OptimizeTryCatch cenv env (e1, vf, ef, vh, eh, m, ty, spTry, spWith) = let efR, efinfo = OptimizeExpr cenv envinner ef let ehR, ehinfo = OptimizeExpr cenv envinner eh let info = - { TotalSize = e1info.TotalSize + efinfo.TotalSize+ ehinfo.TotalSize + tryCatchSize - FunctionSize = e1info.FunctionSize + efinfo.FunctionSize+ ehinfo.FunctionSize + tryCatchSize + { TotalSize = e1info.TotalSize + efinfo.TotalSize+ ehinfo.TotalSize + tryCatchSize + FunctionSize = e1info.FunctionSize + efinfo.FunctionSize+ ehinfo.FunctionSize + tryCatchSize HasEffect = e1info.HasEffect || efinfo.HasEffect || ehinfo.HasEffect MightMakeCriticalTailcall = false Info = UnknownValue } @@ -2369,7 +2369,7 @@ and OptimizeTryCatch cenv env (e1, vf, ef, vh, eh, m, ty, spTry, spWith) = info /// Optimize/analyze a while loop -and OptimizeWhileLoop cenv env (spWhile, marker, e1, e2, m) = +and OptimizeWhileLoop cenv env (spWhile, marker, e1, e2, m) = let e1R, e1info = OptimizeExpr cenv env e1 let e2R, e2info = OptimizeExpr cenv env e2 mkWhile cenv.g (spWhile, marker, e1R, e2R, m), @@ -2383,7 +2383,7 @@ and OptimizeWhileLoop cenv env (spWhile, marker, e1, e2, m) = /// a witness (should always be possible due to compulsory inlining of any /// code that contains calls to member constraints, except when analyzing /// not-yet-inlined generic code) -and OptimizeTraitCall cenv env (traitInfo, args, m) = +and OptimizeTraitCall cenv env (traitInfo, args, m) = // Resolve the static overloading early (during the compulsory rewrite phase) so we can inline. match ConstraintSolver.CodegenWitnessThatTypeSupportsTraitConstraint cenv.TcVal cenv.g cenv.amap m traitInfo args with @@ -2391,7 +2391,7 @@ and OptimizeTraitCall cenv env (traitInfo, args, m) = | OkResult (_, Some expr) -> OptimizeExpr cenv env expr // Resolution fails when optimizing generic code, ignore the failure - | _ -> + | _ -> let argsR, arginfos = OptimizeExprsThenConsiderSplits cenv env args OptimizeExprOpFallback cenv env (TOp.TraitCall(traitInfo), [], argsR, m) arginfos UnknownValue @@ -2413,7 +2413,7 @@ and TryOptimizeVal cenv env (mustInline, valInfoForVal, m) = // If the more specific info didn't reveal an inline then use the value match TryOptimizeVal cenv env (mustInline, detail, m) with | Some e -> Some e - | None -> Some(exprForValRef m vR) + | None -> Some(exprForValRef m vR) | ConstExprValue(_size, expr) -> Some (remarkExpr m (copyExpr cenv.g CloneAllAndMarkExprValsAsCompilerGenerated expr)) @@ -2432,7 +2432,7 @@ and TryOptimizeVal cenv env (mustInline, valInfoForVal, m) = | _ -> None and TryOptimizeValInfo cenv env m vinfo = - if vinfo.HasEffect then None else TryOptimizeVal cenv env (false, vinfo.Info , m) + 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 = @@ -2466,7 +2466,7 @@ and OptimizeVal cenv env expr (v: ValRef, m) = e, AddValEqualityInfo cenv.g m v einfo | None -> - if v.MustInline then error(Error(FSComp.SR.optFailedToInlineValue(v.DisplayName), m)) + if v.MustInline then error(Error(FSComp.SR.optFailedToInlineValue(v.DisplayName), m)) expr, (AddValEqualityInfo cenv.g m v { Info=valInfoForVal.ValExprInfo HasEffect=false @@ -2484,7 +2484,7 @@ and StripToNominalTyconRef cenv ty = mkCompiledTupleTyconRef cenv.g false (List.length tyargs), tyargs else failwith "StripToNominalTyconRef: unreachable" -and CanDevirtualizeApplication cenv v vref ty args = +and CanDevirtualizeApplication cenv v vref ty args = valRefEq cenv.g v vref && not (isUnitTy cenv.g ty) && isAppTy cenv.g ty @@ -2533,14 +2533,14 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedCompareToValues with - | Some (_, vref) -> Some (DevirtualizeApplication cenv env vref ty tyargs args m) + | Some (_, vref) -> Some (DevirtualizeApplication cenv env vref ty tyargs args m) | _ -> None | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_comparison_withc_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedCompareToWithComparerValues, args with - | Some vref, [comp; x; y] -> + | Some vref, [comp; x; y] -> // the target takes a tupled argument, so we need to reorder the arg expressions in the // arg list, and create a tuple of y & comp // push the comparer to the end and box the argument @@ -2556,21 +2556,21 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsValues with - | Some (_, vref) -> Some (DevirtualizeApplication cenv env vref ty tyargs args m) + | Some (_, vref) -> Some (DevirtualizeApplication cenv env vref ty tyargs args m) | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericEqualityWithComparerFast | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_withc_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsWithComparerValues, args with - | Some (_, _, withcEqualsVal), [comp; x; y] -> + | Some (_, _, withcEqualsVal), [comp; x; y] -> // push the comparer to the end and box the argument let args2 = [x; mkRefTupledNoTypes cenv.g m [mkCoerceExpr(y, cenv.g.obj_ty, m, ty) ; comp]] Some (DevirtualizeApplication cenv env withcEqualsVal ty tyargs args2 m) | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericEqualityWithComparer - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_per_inner_vref ty args && not(isRefTupleTy cenv.g ty) -> + | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_equality_per_inner_vref ty args && not(isRefTupleTy cenv.g ty) -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsWithComparerValues, args with | Some (_, _, withcEqualsVal), [x; y] -> @@ -2588,16 +2588,16 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericHashWithComparerIntrinsic - | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_hash_withc_inner_vref ty args -> + | Expr.Val(v, _, _), [ty], _ when CanDevirtualizeApplication cenv v cenv.g.generic_hash_withc_inner_vref ty args -> let tcref, tyargs = StripToNominalTyconRef cenv ty match tcref.GeneratedHashAndEqualsWithComparerValues, args with - | Some (_, withcGetHashCodeVal, _), [comp; x] -> + | Some (_, withcGetHashCodeVal, _), [comp; x] -> let args2 = [x; comp] Some (DevirtualizeApplication cenv env withcGetHashCodeVal ty tyargs args2 m) | _ -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericComparisonWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_comparison_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_comparison_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2611,7 +2611,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | None -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericHashWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_hash_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_hash_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2627,7 +2627,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericEqualityIntrinsic for tuple types // REVIEW (5537): GenericEqualityIntrinsic implements PER semantics, and we are replacing it to something also // implementing PER semantics. However GenericEqualityIntrinsic should implement ER semantics. - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_equality_per_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_equality_per_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2641,7 +2641,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | None -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericComparisonWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_comparison_withc_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_comparison_withc_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2655,7 +2655,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | None -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericHashWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_hash_withc_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_hash_withc_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2669,7 +2669,7 @@ and TryDevirtualizeApplication cenv env (f, tyargs, args, m) = | None -> None // Optimize/analyze calls to LanguagePrimitives.HashCompare.GenericEqualityWithComparerIntrinsic for tuple types - | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_equality_withc_inner_vref && isRefTupleTy cenv.g ty -> + | Expr.Val(v, _, _), [ty], _ when valRefEq cenv.g v cenv.g.generic_equality_withc_inner_vref && isRefTupleTy cenv.g ty -> let tyargs = destRefTupleTy cenv.g ty let vref = match tyargs.Length with @@ -2756,7 +2756,7 @@ and TryInlineApplication cenv env finfo (tyargs: TType list, args: Expr list, m) let isSecureMethod = match finfo.Info with - | ValValue(vref, _) -> + | ValValue(vref, _) -> vref.Attribs |> List.exists (fun a -> (IsSecurityAttribute cenv.g cenv.amap cenv.casApplied a m) || (IsSecurityCriticalAttribute cenv.g a)) | _ -> false @@ -2770,7 +2770,7 @@ and TryInlineApplication cenv env finfo (tyargs: TType list, args: Expr list, m) if isGetHashCode then None else // Inlining lambda - (* ---------- printf "Inlining lambda near %a = %s\n" outputRange m (showL (exprL f2)) (* JAMES: *) ----------*) + (* ---------- printf "Inlining lambda near %a = %s\n" outputRange m (showL (exprL f2)) (* JAMES: *) ----------*) let f2R = remarkExpr m (copyExpr cenv.g CloneAllAndMarkExprValsAsCompilerGenerated f2) // Optimizing arguments after inlining @@ -2778,7 +2778,7 @@ and TryInlineApplication cenv env finfo (tyargs: TType list, args: Expr list, m) // inlining kicking into effect let argsR = args |> List.map (fun e -> let eR, _einfo = OptimizeExpr cenv env e in eR) // Beta reduce. MakeApplicationAndBetaReduce cenv.g does all the hard work. - // Inlining: beta reducing + // Inlining: beta reducing let exprR = MakeApplicationAndBetaReduce cenv.g (f2R, f2ty, [tyargs], argsR, m) // Inlining: reoptimizing Some(OptimizeExpr cenv {env with dontInline= Zset.add lambdaId env.dontInline} exprR) @@ -2832,14 +2832,14 @@ and OptimizeApplication cenv env (f0, f0ty, tyargs, args, m) = // Determine if this application is a critical tailcall let mayBeCriticalTailcall = match newf0 with - | KnownValApp(vref, _typeArgs, otherArgs) -> + | KnownValApp(vref, _typeArgs, otherArgs) -> // Check if this is a call to a function of known arity that has been inferred to not be a critical tailcall when used as a direct call // This includes recursive calls to the function being defined (in which case we get a non-critical, closed-world tailcall). // Note we also have to check the argument count to ensure this is a direct call (or a partial application). let doesNotMakeCriticalTailcall = vref.MakesNoCriticalTailcalls || - (let valInfoForVal = GetInfoForVal cenv env m vref in valInfoForVal.ValMakesNoCriticalTailcalls) || + (let valInfoForVal = GetInfoForVal cenv env m vref in valInfoForVal.ValMakesNoCriticalTailcalls) || (match env.functionVal with | None -> false | Some (v, _) -> valEq vref.Deref v) if doesNotMakeCriticalTailcall then let numArgs = otherArgs.Length + newArgs.Length @@ -2847,7 +2847,7 @@ and OptimizeApplication cenv env (f0, f0ty, tyargs, args, m) = | Some i -> numArgs > i.NumCurriedArgs | None -> match env.functionVal with - | Some (_v, i) -> numArgs > i.NumCurriedArgs + | Some (_v, i) -> numArgs > i.NumCurriedArgs | None -> true // over-application of a known function, which presumably returns a function. This counts as an indirect call else true // application of a function that may make a critical tailcall @@ -2896,9 +2896,9 @@ and OptimizeLambdas (vspec: Val option) cenv env topValInfo e ety = else printfn "value %s at line %d does not make a critical tailcall" v.DisplayName v.Range.StartLine if cenv.settings.reportTotalSizes then - printfn "value %s at line %d has total size %d" v.DisplayName v.Range.StartLine bodyinfo.TotalSize + printfn "value %s at line %d has total size %d" v.DisplayName v.Range.StartLine bodyinfo.TotalSize if cenv.settings.reportFunctionSizes then - printfn "value %s at line %d has method size %d" v.DisplayName v.Range.StartLine bodyinfo.FunctionSize + printfn "value %s at line %d has method size %d" v.DisplayName v.Range.StartLine bodyinfo.FunctionSize if cenv.settings.reportHasEffect then if bodyinfo.HasEffect then printfn "function %s at line %d causes side effects or may not terminate" v.DisplayName v.Range.StartLine @@ -2978,7 +2978,7 @@ and ComputeSplitToMethodCondition flag threshold cenv env (e: Expr, einfo) = // It can't use any protected or base calls, rethrow(), byrefs etc. let m = e.Range (let fvs = freeInExpr CollectLocals e - not fvs.UsesUnboundRethrow && + not fvs.UsesUnboundRethrow && not fvs.UsesMethodLocalConstructs && fvs.FreeLocals |> Zset.forall (fun v -> // no direct-self-recursive references @@ -3084,7 +3084,7 @@ and OptimizeDecisionTree cenv env m x = and TryOptimizeDecisionTreeTest cenv test vinfo = match test, vinfo with - | DecisionTreeTest.UnionCase (c1, _), StripUnionCaseValue(c2, _) -> Some(cenv.g.unionCaseRefEq c1 c2) + | DecisionTreeTest.UnionCase (c1, _), StripUnionCaseValue(c2, _) -> Some(cenv.g.unionCaseRefEq c1 c2) | DecisionTreeTest.ArrayLength (_, _), _ -> None | DecisionTreeTest.Const c1, StripConstValue(c2) -> if c1 = Const.Zero || c2 = Const.Zero then None else Some(c1=c2) | DecisionTreeTest.IsNull, StripConstValue(c2) -> Some(c2=Const.Zero) @@ -3100,7 +3100,7 @@ and OptimizeSwitch cenv env (e, cases, dflt, m) = let cases, dflt = if cenv.settings.EliminateSwitch() && not einfo.HasEffect then // Attempt to find a definite success, i.e. the first case where there is definite success - match (List.tryFind (function (TCase(d2, _)) when TryOptimizeDecisionTreeTest cenv d2 einfo.Info = Some(true) -> true | _ -> false) cases) with + match (List.tryFind (function (TCase(d2, _)) when TryOptimizeDecisionTreeTest cenv d2 einfo.Info = Some(true) -> true | _ -> false) cases) with | Some(TCase(_, case)) -> [], Some(case) | _ -> // Filter definite failures @@ -3124,7 +3124,7 @@ and OptimizeSwitchFallback cenv env (eR, einfo, cases, dflt, m) = | Some df -> let dfR, einfo = OptimizeDecisionTree cenv env m df in Some dfR, [einfo] let size = (dinfos.Length + cinfos.Length) * 2 let info = CombineValueInfosUnknown (einfo :: cinfos @ dinfos) - let info = { info with TotalSize = info.TotalSize + size; FunctionSize = info.FunctionSize + size; } + let info = { info with TotalSize = info.TotalSize + size; FunctionSize = info.FunctionSize + size; } TDSwitch (eR, casesR, dfltR, m), info and OptimizeBinding cenv isRec env (TBind(vref, expr, spBind)) = @@ -3135,14 +3135,14 @@ and OptimizeBinding cenv isRec env (TBind(vref, expr, spBind)) = // any expression that contains a reference to any value in RVS. // This doesn't prevent splitting for mutually recursive references. See FSharp 1.0 bug 2892. let env = - if isRec then { env with dontSplitVars = env.dontSplitVars.Add vref () } + if isRec then { env with dontSplitVars = env.dontSplitVars.Add vref () } else env let exprOptimized, einfo = let env = if vref.IsCompilerGenerated && Option.isSome env.latestBoundId then env else {env with latestBoundId=Some vref.Id} let cenv = if vref.InlineInfo = ValInline.PseudoVal then { cenv with optimizing=false} else cenv let arityInfo = InferArityOfExprBinding cenv.g AllowTypeDirectedDetupling.No vref expr - let exprOptimized, einfo = OptimizeLambdas (Some vref) cenv env arityInfo expr vref.Type + let exprOptimized, einfo = OptimizeLambdas (Some vref) cenv env arityInfo expr vref.Type let size = localVarSize exprOptimized, {einfo with FunctionSize=einfo.FunctionSize+size; TotalSize = einfo.TotalSize+size} @@ -3166,10 +3166,10 @@ and OptimizeBinding cenv isRec env (TBind(vref, expr, spBind)) = | TupleValue a -> TupleValue(Array.map cut a) | RecdValue (tcref, a) -> RecdValue(tcref, Array.map cut a) | UnionCaseValue (a, b) -> UnionCaseValue (a, Array.map cut b) - | UnknownValue | ConstValue _ | ConstExprValue _ -> ivalue + | UnknownValue | ConstValue _ | ConstExprValue _ -> ivalue | SizeValue(_, a) -> MakeSizedValueInfo (cut a) - let einfo = if vref.MustInline then einfo else {einfo with Info = cut einfo.Info } + let einfo = if vref.MustInline then einfo else {einfo with Info = cut einfo.Info } let einfo = if (not vref.MustInline && not (cenv.settings.KeepOptimizationValues())) || @@ -3219,7 +3219,7 @@ and OptimizeBinding cenv isRec env (TBind(vref, expr, spBind)) = valRefEq cenv.g nvref cenv.g.generic_hash_inner_vref)) then {einfo with Info=UnknownValue} else einfo - if vref.MustInline && IsPartialExprVal einfo.Info then + if vref.MustInline && IsPartialExprVal einfo.Info then errorR(InternalError("the mustinline value '"+vref.LogicalName+"' was not inferred to have a known value", vref.Range)) let env = BindInternalLocalVal cenv vref (mkValInfo einfo vref) env @@ -3287,11 +3287,11 @@ and OptimizeModuleExpr cenv env x = | TMDefRec(isRec, tycons, mbinds, m) -> let mbinds = mbinds |> List.choose elimModuleBinding TMDefRec(isRec, tycons, mbinds, m) - | TMDefLet(bind, m) -> + | TMDefLet(bind, m) -> if Zset.contains bind.Var deadSet then TMDefRec(false, [], [], m) else x - | TMDefDo _ -> x + | TMDefDo _ -> x | TMDefs(defs) -> TMDefs(List.map elimModDef defs) - | TMAbstract _ -> x + | TMAbstract _ -> x and elimModuleBinding x = match x with @@ -3332,17 +3332,17 @@ and OptimizeModuleDef cenv (env, bindInfosColl) x = let env = BindValsInModuleOrNamespace cenv info env (TMAbstract(mexpr), info), (env, bindInfosColl) - | TMDefLet(bind, m) -> + | TMDefLet(bind, m) -> let ((bindR, binfo) as bindInfo), env = OptimizeBinding cenv false env bind (TMDefLet(bindR, m), notlazy { ValInfos=ValInfos [mkValBind bind (mkValInfo binfo bind.Var)] ModuleOrNamespaceInfos = NameMap.empty }), - (env , ([bindInfo]::bindInfosColl)) + (env, ([bindInfo]::bindInfosColl)) - | TMDefDo(e, m) -> + | TMDefDo(e, m) -> let (e, _einfo) = OptimizeExpr cenv env e (TMDefDo(e, m), EmptyModuleInfo), - (env , bindInfosColl) + (env, bindInfosColl) | TMDefs(defs) -> let (defs, info), (env, bindInfosColl) = OptimizeModuleDefs cenv (env, bindInfosColl) defs @@ -3354,7 +3354,7 @@ and OptimizeModuleBinding cenv (env, bindInfosColl) x = match x with | ModuleOrNamespaceBinding.Binding bind -> let ((bindR, binfo) as bindInfo), env = OptimizeBinding cenv true env bind - (ModuleOrNamespaceBinding.Binding bindR, Choice1Of2 (bindR, binfo)), (env, [ bindInfo ] :: bindInfosColl) + (ModuleOrNamespaceBinding.Binding bindR, Choice1Of2 (bindR, binfo)), (env, [ bindInfo ] :: bindInfosColl) | ModuleOrNamespaceBinding.Module(mspec, def) -> let id = mspec.Id let (def, info), (_, bindInfosColl) = OptimizeModuleDef cenv (env, bindInfosColl) def @@ -3368,7 +3368,7 @@ and OptimizeModuleDefs cenv (env, bindInfosColl) defs = (defs, UnionOptimizationInfos minfos), (env, bindInfosColl) and OptimizeImplFileInternal cenv env isIncrementalFragment hidden (TImplFile(qname, pragmas, mexpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = - let env, mexprR, minfo = + let env, mexprR, minfo = match mexpr with // FSI: FSI compiles everything as if you're typing incrementally into one module // This means the fragment is not truly a constrained module as later fragments will be typechecked @@ -3377,7 +3377,7 @@ and OptimizeImplFileInternal cenv env isIncrementalFragment hidden (TImplFile(qn | ModuleOrNamespaceExprWithSig(mty, def, m) when isIncrementalFragment -> let (def, minfo), (env, _bindInfosColl) = OptimizeModuleDef cenv (env, []) def env, ModuleOrNamespaceExprWithSig(mty, def, m), minfo - | _ -> + | _ -> let mexprR, minfo = OptimizeModuleExpr cenv env mexpr let env = BindValsInModuleOrNamespace cenv minfo env let env = { env with localExternalVals=env.localExternalVals.MarkAsCollapsible() } // take the chance to flatten to a dictionary @@ -3452,14 +3452,14 @@ let rec u_ExprInfo st = let rec loop st = let tag = u_byte st match tag with - | 0 -> u_tup2 u_const u_ty st |> (fun (c, ty) -> ConstValue(c, ty)) + | 0 -> u_tup2 u_const u_ty st |> (fun (c, ty) -> ConstValue(c, ty)) | 1 -> UnknownValue - | 2 -> u_tup2 u_vref loop st |> (fun (a, b) -> ValValue (a, b)) - | 3 -> u_array loop st |> (fun a -> TupleValue a) - | 4 -> u_tup2 u_ucref (u_array loop) st |> (fun (a, b) -> UnionCaseValue (a, b)) - | 5 -> u_tup4 u_int u_int u_expr u_ty st |> (fun (b, c, d, e) -> CurriedLambdaValue (newUnique(), b, c, d, e)) - | 6 -> u_tup2 u_int u_expr st |> (fun (a, b) -> ConstExprValue (a, b)) - | 7 -> u_tup2 u_tcref (u_array loop) st |> (fun (a, b) -> RecdValue (a, b)) + | 2 -> u_tup2 u_vref loop st |> (fun (a, b) -> ValValue (a, b)) + | 3 -> u_array loop st |> (fun a -> TupleValue a) + | 4 -> u_tup2 u_ucref (u_array loop) st |> (fun (a, b) -> UnionCaseValue (a, b)) + | 5 -> u_tup4 u_int u_int u_expr u_ty st |> (fun (b, c, d, e) -> CurriedLambdaValue (newUnique(), b, c, d, e)) + | 6 -> u_tup2 u_int u_expr st |> (fun (a, b) -> ConstExprValue (a, b)) + | 7 -> u_tup2 u_tcref (u_array loop) st |> (fun (a, b) -> RecdValue (a, b)) | _ -> failwith "loop" MakeSizedValueInfo (loop st) (* calc size of unpicked ExprValueInfo *) diff --git a/src/fsharp/PatternMatchCompilation.fs b/src/fsharp/PatternMatchCompilation.fs index ee310acddfb..0f4bf494cae 100644 --- a/src/fsharp/PatternMatchCompilation.fs +++ b/src/fsharp/PatternMatchCompilation.fs @@ -80,7 +80,7 @@ let debug = false // let x, y = [], [] // // BindSubExprOfInput actually produces the binding -// e.g. let v2 = \Gamma ['a, 'b]. ([] : 'a , [] : 'b) +// e.g. let v2 = \Gamma ['a, 'b]. ([] : 'a, [] : 'b) // let (x, y) = p. // When v = x, gtvs = 'a, 'b. We must bind: // x --> \Gamma A. fst (v2[A, ]) @@ -210,7 +210,7 @@ let RefuteDiscrimSet g m path discrims = | PathArray (p, ty, len, n) -> let flds, eCoversVals = mkOneKnown tm n (List.replicate len ty) - go p (fun _ -> Expr.Op(TOp.Array, [ty], flds , m), eCoversVals) + go p (fun _ -> Expr.Op(TOp.Array, [ty], flds, m), eCoversVals) | PathExnConstr (p, ecref, n) -> let flds, eCoversVals = ecref |> recdFieldTysOfExnDefRef |> mkOneKnown tm n @@ -298,7 +298,7 @@ let RefuteDiscrimSet g m path discrims = Expr.Op(TOp.UnionCase(ucref2), tinst, flds, m), false | [DecisionTreeTest.ArrayLength (n, ty)] -> - Expr.Op(TOp.Array, [ty], mkUnknowns (List.replicate (n+1) ty) , m), false + Expr.Op(TOp.Array, [ty], mkUnknowns (List.replicate (n+1) ty), m), false | _ -> raise CannotRefute @@ -435,7 +435,7 @@ let discrimsEq (g: TcGlobals) d1 d2 = | DecisionTreeTest.UnionCase (c1, _), DecisionTreeTest.UnionCase(c2, _) -> g.unionCaseRefEq c1 c2 | DecisionTreeTest.ArrayLength (n1, _), DecisionTreeTest.ArrayLength(n2, _) -> (n1=n2) | DecisionTreeTest.Const c1, DecisionTreeTest.Const c2 -> (c1=c2) - | DecisionTreeTest.IsNull , DecisionTreeTest.IsNull -> true + | DecisionTreeTest.IsNull, DecisionTreeTest.IsNull -> true | DecisionTreeTest.IsInst (srcty1, tgty1), DecisionTreeTest.IsInst (srcty2, tgty2) -> typeEquiv g srcty1 srcty2 && typeEquiv g tgty1 tgty2 | DecisionTreeTest.ActivePatternCase (_, _, vrefOpt1, n1, _), DecisionTreeTest.ActivePatternCase (_, _, vrefOpt2, n2, _) -> match vrefOpt1, vrefOpt2 with @@ -478,7 +478,7 @@ let canCompactConstantClass c = let discrimsHaveSameSimultaneousClass g d1 d2 = match d1, d2 with | DecisionTreeTest.Const _, DecisionTreeTest.Const _ - | DecisionTreeTest.IsNull , DecisionTreeTest.IsNull + | DecisionTreeTest.IsNull, DecisionTreeTest.IsNull | DecisionTreeTest.ArrayLength _, DecisionTreeTest.ArrayLength _ | DecisionTreeTest.UnionCase _, DecisionTreeTest.UnionCase _ -> true diff --git a/src/fsharp/PostInferenceChecks.fs b/src/fsharp/PostInferenceChecks.fs index a91473b6880..cf4d4e4ad94 100644 --- a/src/fsharp/PostInferenceChecks.fs +++ b/src/fsharp/PostInferenceChecks.fs @@ -2055,9 +2055,9 @@ let CheckEntityDefn cenv env (tycon: Entity) = if others |> List.exists (checkForDup EraseAll) then if others |> List.exists (checkForDup EraseNone) then - errorR(Error(FSComp.SR.chkDuplicateProperty(nm, NicePrint.minimalStringOfType cenv.denv ty) , m)) + errorR(Error(FSComp.SR.chkDuplicateProperty(nm, NicePrint.minimalStringOfType cenv.denv ty), m)) else - errorR(Error(FSComp.SR.chkDuplicatePropertyWithSuffix(nm, NicePrint.minimalStringOfType cenv.denv ty) , m)) + errorR(Error(FSComp.SR.chkDuplicatePropertyWithSuffix(nm, NicePrint.minimalStringOfType cenv.denv ty), m)) // Check to see if one is an indexer and one is not if ( (pinfo.HasGetter && @@ -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/QuotationPickler.fs b/src/fsharp/QuotationPickler.fs index c0e0360f6e8..df718278097 100644 --- a/src/fsharp/QuotationPickler.fs +++ b/src/fsharp/QuotationPickler.fs @@ -114,7 +114,7 @@ type ExprData = let mkVar v = VarExpr v -let mkHole (v, idx) = HoleExpr (v , idx) +let mkHole (v, idx) = HoleExpr (v, idx) let mkApp (a, b) = CombExpr(AppOp, [], [a; b]) diff --git a/src/fsharp/QuotationTranslator.fs b/src/fsharp/QuotationTranslator.fs index bd157c6ecc2..6166906244f 100644 --- a/src/fsharp/QuotationTranslator.fs +++ b/src/fsharp/QuotationTranslator.fs @@ -300,7 +300,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. else tryDestRefTupleExpr arg)) if verboseCReflect then - dprintfn "vref.DisplayName = %A , after unit adjust, #untupledCurriedArgs = %A, #curriedArgInfos = %d" vref.DisplayName (List.map List.length untupledCurriedArgs) curriedArgInfos.Length + dprintfn "vref.DisplayName = %A, after unit adjust, #untupledCurriedArgs = %A, #curriedArgInfos = %d" vref.DisplayName (List.map List.length untupledCurriedArgs) curriedArgInfos.Length let subCall = if isMember then // This is an application of a member method diff --git a/src/fsharp/SignatureConformance.fs b/src/fsharp/SignatureConformance.fs index b22de20da1b..6ba6dad410c 100644 --- a/src/fsharp/SignatureConformance.fs +++ b/src/fsharp/SignatureConformance.fs @@ -37,8 +37,8 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = // Used when checking attributes. let sigToImplRemap = let remap = Remap.Empty - let remap = (remapInfo.RepackagedEntities, remap) ||> List.foldBack (fun (implTcref , signTcref) acc -> addTyconRefRemap signTcref implTcref acc) - let remap = (remapInfo.RepackagedVals , remap) ||> List.foldBack (fun (implValRef, signValRef) acc -> addValRemap signValRef.Deref implValRef.Deref acc) + let remap = (remapInfo.RepackagedEntities, remap) ||> List.foldBack (fun (implTcref, signTcref) acc -> addTyconRefRemap signTcref implTcref acc) + let remap = (remapInfo.RepackagedVals, remap) ||> List.foldBack (fun (implValRef, signValRef) acc -> addValRemap signValRef.Deref implValRef.Deref acc) remap // For all attributable elements (types, modules, exceptions, record fields, unions, parameters, generic type parameters) @@ -536,7 +536,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = if typeAEquiv g aenv ty1 ty2 then true else (errorR (Error(FSComp.SR.DefinitionsInSigAndImplNotCompatibleRepresentationsDiffer(implTycon.TypeOrMeasureKind.ToString(), implTycon.DisplayName), m)); false) | TNoRepr, TNoRepr -> true #if !NO_EXTENSIONTYPING - | TProvidedTypeExtensionPoint info1 , TProvidedTypeExtensionPoint info2 -> + | TProvidedTypeExtensionPoint info1, TProvidedTypeExtensionPoint info2 -> Tainted.EqTainted info1.ProvidedType.TypeProvider info2.ProvidedType.TypeProvider && ProvidedType.TaintedEquals(info1.ProvidedType, info2.ProvidedType) | TProvidedNamespaceExtensionPoint _, TProvidedNamespaceExtensionPoint _ -> System.Diagnostics.Debug.Assert(false, "unreachable: TProvidedNamespaceExtensionPoint only on namespaces, not types" ) @@ -567,7 +567,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = (if implModType.ModuleOrNamespaceKind <> signModType.ModuleOrNamespaceKind then errorR(Error(FSComp.SR.typrelModuleNamespaceAttributesDifferInSigAndImpl(), m))) - (implModType.TypesByMangledName , signModType.TypesByMangledName) + (implModType.TypesByMangledName, signModType.TypesByMangledName) ||> NameMap.suball2 (fun s _fx -> errorR(RequiredButNotSpecified(denv, implModRef, "type", (fun os -> Printf.bprintf os "%s" s), m)); false) (checkTypeDef aenv) && @@ -659,7 +659,7 @@ let rec CheckNamesOfModuleOrNamespaceContents denv (implModRef: ModuleOrNamespac (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) && - (implModType.AllValsAndMembersByLogicalNameUncached , signModType.AllValsAndMembersByLogicalNameUncached) + (implModType.AllValsAndMembersByLogicalNameUncached, signModType.AllValsAndMembersByLogicalNameUncached) ||> NameMap.suball2 (fun _s (fxs: Val list) -> let fx = fxs.Head diff --git a/src/fsharp/TastOps.fs b/src/fsharp/TastOps.fs index dbf8371c537..cb5050592d3 100644 --- a/src/fsharp/TastOps.fs +++ b/src/fsharp/TastOps.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. /// Defines derived expression manipulation and construction functions. module internal FSharp.Compiler.Tastops @@ -57,7 +57,7 @@ type TyparMap<'T> = type TyconRefMap<'T>(imap: StampMap<'T>) = member m.Item with get (v: TyconRef) = imap.[v.Stamp] member m.TryFind (v: TyconRef) = imap.TryFind v.Stamp - member m.ContainsKey (v: TyconRef) = imap.ContainsKey v.Stamp + member m.ContainsKey (v: TyconRef) = imap.ContainsKey v.Stamp member m.Add (v: TyconRef) x = TyconRefMap (imap.Add (v.Stamp, x)) member m.Remove (v: TyconRef) = TyconRefMap (imap.Remove v.Stamp) member m.IsEmpty = imap.IsEmpty @@ -99,9 +99,9 @@ type Remap = removeTraitSolutions: bool } let emptyRemap = - { tpinst = emptyTyparInst + { tpinst = emptyTyparInst tyconRefRemap = emptyTyconRefRemap - valRemap = ValMap.Empty + valRemap = ValMap.Empty removeTraitSolutions = false } type Remap with @@ -119,14 +119,14 @@ let isRemapEmpty remap = remap.tyconRefRemap.IsEmpty && remap.valRemap.IsEmpty -let rec instTyparRef tpinst ty tp = +let rec instTyparRef tpinst ty tp = match tpinst with | [] -> ty | (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 = @@ -142,9 +142,9 @@ let instMeasureTyparRef tpinst unt (tp: Typar) = loop tpinst | _ -> failwith "instMeasureTyparRef: kind=Type" -let remapTyconRef (tcmap: TyconRefMap<_>) tcref = +let remapTyconRef (tcmap: TyconRefMap<_>) tcref = match tcmap.TryFind tcref with - | Some tcref -> tcref + | Some tcref -> tcref | None -> tcref let remapUnionCaseRef tcmap (UCRef(tcref, nm)) = UCRef(remapTyconRef tcmap tcref, nm) @@ -163,10 +163,10 @@ let generalizeTypars tps = List.map generalizeTypar tps let rec remapTypeAux (tyenv: Remap) (ty: TType) = let ty = stripTyparEqns ty match ty with - | TType_var tp as ty -> instTyparRef tyenv.tpinst ty tp + | TType_var tp as ty -> instTyparRef tyenv.tpinst ty tp | TType_app (tcref, tinst) as ty -> match tyenv.tyconRefRemap.TryFind tcref with - | Some tcref' -> TType_app (tcref', remapTypesAux tyenv tinst) + | Some tcref' -> TType_app (tcref', remapTypesAux tyenv tinst) | None -> match tinst with | [] -> ty // optimization to avoid re-allocation of TType_app node in the common case @@ -178,22 +178,22 @@ let rec remapTypeAux (tyenv: Remap) (ty: TType) = | TType_ucase (UCRef(tcref, n), tinst) -> match tyenv.tyconRefRemap.TryFind tcref with - | Some tcref' -> TType_ucase (UCRef(tcref', n), remapTypesAux tyenv tinst) + | Some tcref' -> TType_ucase (UCRef(tcref', n), remapTypesAux tyenv tinst) | None -> TType_ucase (UCRef(tcref, n), remapTypesAux tyenv tinst) - | TType_anon (anonInfo, l) as ty -> + | TType_anon (anonInfo, l) as ty -> let tupInfo' = remapTupInfoAux tyenv anonInfo.TupInfo let l' = remapTypesAux tyenv l if anonInfo.TupInfo === tupInfo' && l === l' then ty else TType_anon (AnonRecdTypeInfo.Create(anonInfo.Assembly, tupInfo', anonInfo.SortedIds), l') - | TType_tuple (tupInfo, l) as ty -> + | TType_tuple (tupInfo, l) as ty -> let tupInfo' = remapTupInfoAux tyenv tupInfo let l' = remapTypesAux tyenv l if tupInfo === tupInfo' && l === l' then ty else TType_tuple (tupInfo', l') - | TType_fun (d, r) as ty -> + | TType_fun (d, r) as ty -> let d' = remapTypeAux tyenv d let r' = remapTypeAux tyenv r if d === d' && r === r' then ty else @@ -212,7 +212,7 @@ and remapMeasureAux tyenv unt = | Measure.One -> unt | Measure.Con tcref -> match tyenv.tyconRefRemap.TryFind tcref with - | Some tcref -> Measure.Con tcref + | Some tcref -> Measure.Con tcref | None -> unt | Measure.Prod(u1, u2) -> Measure.Prod(remapMeasureAux tyenv u1, remapMeasureAux tyenv u2) | Measure.RationalPower(u, q) -> Measure.RationalPower(remapMeasureAux tyenv u, q) @@ -247,8 +247,8 @@ and remapTyparConstraintsAux tyenv cs = | TyparConstraint.IsDelegate(uty1, uty2, m) -> Some(TyparConstraint.IsDelegate(remapTypeAux tyenv uty1, remapTypeAux tyenv uty2, m)) | TyparConstraint.SimpleChoice(tys, m) -> Some(TyparConstraint.SimpleChoice(remapTypesAux tyenv tys, m)) - | TyparConstraint.SupportsComparison _ - | TyparConstraint.SupportsEquality _ + | TyparConstraint.SupportsComparison _ + | TyparConstraint.SupportsEquality _ | TyparConstraint.SupportsNull _ | TyparConstraint.IsUnmanaged _ | TyparConstraint.IsNonNullableStruct _ @@ -300,7 +300,7 @@ and copyAndRemapAndBindTyparsFull remapAttrib tyenv tps = let tps' = copyTypars tps let tyenv = { tyenv with tpinst = bindTypars tps (generalizeTypars tps') tyenv.tpinst } (tps, tps') ||> List.iter2 (fun tporig tp -> - tp.SetConstraints (remapTyparConstraintsAux tyenv tporig.Constraints) + tp.SetConstraints (remapTyparConstraintsAux tyenv tporig.Constraints) tp.SetAttribs (tporig.Attribs |> remapAttrib)) tps', tyenv @@ -327,10 +327,10 @@ and remapNonLocalValRef tyenv (nlvref: NonLocalValOrMemberRef) = let vlink' = remapValLinkage tyenv vlink if eref === eref' && vlink === vlink' then nlvref else { EnclosingEntity = eref' - ItemKey = vlink' } + ItemKey = vlink' } and remapValRef tmenv (vref: ValRef) = - match tmenv.valRemap.TryFind vref.Deref with + match tmenv.valRemap.TryFind vref.Deref with | None -> if vref.IsLocalRef then vref else let nlvref = vref.nlr @@ -375,14 +375,14 @@ let remapSlotSig remapAttrib tyenv (TSlotSig(nm, ty, ctps, methTypars, paraml, r let mkInstRemap tpinst = { tyconRefRemap = emptyTyconRefRemap - tpinst = tpinst - valRemap = ValMap.Empty + tpinst = tpinst + valRemap = ValMap.Empty removeTraitSolutions = false } // entry points for "typar -> TType" instantiation -let instType tpinst x = if isNil tpinst then x else remapTypeAux (mkInstRemap tpinst) x -let instTypes tpinst x = if isNil tpinst then x else remapTypesAux (mkInstRemap tpinst) x -let instTrait tpinst x = if isNil tpinst then x else remapTraitAux (mkInstRemap tpinst) x +let instType tpinst x = if isNil tpinst then x else remapTypeAux (mkInstRemap tpinst) x +let instTypes tpinst x = if isNil tpinst then x else remapTypesAux (mkInstRemap tpinst) x +let instTrait tpinst x = if isNil tpinst then x else remapTraitAux (mkInstRemap tpinst) x let instTyparConstraints tpinst x = if isNil tpinst then x else remapTyparConstraintsAux (mkInstRemap tpinst) x let instSlotSig tpinst ss = remapSlotSig (fun _ -> []) (mkInstRemap tpinst) ss let copySlotSig ss = remapSlotSig (fun _ -> []) Remap.Empty ss @@ -414,7 +414,7 @@ let reduceTyconRefAbbrevMeasureable (tcref: TyconRef) = let rec stripUnitEqnsFromMeasureAux canShortcut unt = match stripUnitEqnsAux canShortcut unt with - | Measure.Con tcref when tcref.IsTypeAbbrev -> + | Measure.Con tcref when tcref.IsTypeAbbrev -> stripUnitEqnsFromMeasureAux canShortcut (reduceTyconRefAbbrevMeasureable tcref) | m -> m @@ -599,7 +599,7 @@ let mkByref2Ty (g: TcGlobals) ty1 ty2 = TType_app (g.byref2_tcr, [ty1; ty2]) let mkVoidPtrTy (g: TcGlobals) = - assert g.voidptr_tcr.CanDeref // check we are using sufficient FSharp.Core , caller should check this + 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 = @@ -641,7 +641,7 @@ let isCompiledTupleTyconRef g tcref = tyconRefEq g g.struct_tuple8_tcr tcref let mkCompiledTupleTyconRef (g: TcGlobals) isStruct n = - if n = 1 then (if isStruct then g.struct_tuple1_tcr else g.ref_tuple1_tcr) + 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) elif n = 4 then (if isStruct then g.struct_tuple4_tcr else g.ref_tuple4_tcr) @@ -725,8 +725,8 @@ let rec stripTyEqnsA g canShortcut ty = // // Add the equation byref<'T> = byref<'T, ByRefKinds.InOut> for when using sufficient FSharp.Core // See RFC FS-1053.md - if tyconRefEq g tcref g.byref_tcr && g.byref2_tcr.CanDeref && g.byrefkind_InOut_tcr.CanDeref then - mkByref2Ty g tinst.[0] (TType_app(g.byrefkind_InOut_tcr, [])) + if tyconRefEq g tcref g.byref_tcr && g.byref2_tcr.CanDeref && g.byrefkind_InOut_tcr.CanDeref then + mkByref2Ty g tinst.[0] (TType_app(g.byrefkind_InOut_tcr, [])) // Add the equation double<1> = double for units of measure. elif tycon.IsMeasureableReprTycon && List.forall (isDimensionless g) tinst then @@ -753,7 +753,7 @@ let rec stripTyEqnsAndErase eraseFuncAndTuple (g: TcGlobals) ty = match ty with | TType_app (tcref, args) -> let tycon = tcref.Deref - if tycon.IsErased then + if tycon.IsErased then stripTyEqnsAndErase eraseFuncAndTuple g (reduceTyconMeasureableOrProvided g tycon args) elif tyconRefEq g tcref g.nativeptr_tcr && eraseFuncAndTuple then stripTyEqnsAndErase eraseFuncAndTuple g g.nativeint_ty @@ -781,59 +781,59 @@ let rec stripExnEqns (eref: TyconRef) = | _ -> exnc let primDestForallTy g ty = ty |> stripTyEqns g |> (function TType_forall (tyvs, tau) -> (tyvs, tau) | _ -> failwith "primDestForallTy: not a forall type") -let destFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (tyv, tau) -> (tyv, tau) | _ -> failwith "destFunTy: not a function type") -let destAnyTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, l) -> tupInfo, l | _ -> failwith "destAnyTupleTy: not a tuple type") -let destRefTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, l) when not (evalTupInfoIsStruct tupInfo) -> l | _ -> failwith "destRefTupleTy: not a reference tuple type") -let destStructTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, l) when evalTupInfoIsStruct tupInfo -> l | _ -> failwith "destStructTupleTy: not a struct tuple type") -let destTyparTy g ty = ty |> stripTyEqns g |> (function TType_var v -> v | _ -> failwith "destTyparTy: not a typar type") -let destAnyParTy g ty = ty |> stripTyEqns g |> (function TType_var v -> v | TType_measure unt -> destUnitParMeasure g unt | _ -> failwith "destAnyParTy: not a typar or unpar type") -let destMeasureTy g ty = ty |> stripTyEqns g |> (function TType_measure m -> m | _ -> failwith "destMeasureTy: not a unit-of-measure type") -let isFunTy g ty = ty |> stripTyEqns g |> (function TType_fun _ -> true | _ -> false) -let isForallTy g ty = ty |> stripTyEqns g |> (function TType_forall _ -> true | _ -> false) -let isAnyTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple _ -> true | _ -> false) -let isRefTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, _) -> not (evalTupInfoIsStruct tupInfo) | _ -> false) -let isStructTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, _) -> evalTupInfoIsStruct tupInfo | _ -> false) -let isAnonRecdTy g ty = ty |> stripTyEqns g |> (function TType_anon _ -> true | _ -> false) -let isStructAnonRecdTy g ty = ty |> stripTyEqns g |> (function TType_anon (anonInfo, _) -> evalAnonInfoIsStruct anonInfo | _ -> false) -let isUnionTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsUnionTycon | _ -> false) -let isReprHiddenTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsHiddenReprTycon | _ -> false) +let destFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (tyv, tau) -> (tyv, tau) | _ -> failwith "destFunTy: not a function type") +let destAnyTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, l) -> tupInfo, l | _ -> failwith "destAnyTupleTy: not a tuple type") +let destRefTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, l) when not (evalTupInfoIsStruct tupInfo) -> l | _ -> failwith "destRefTupleTy: not a reference tuple type") +let destStructTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, l) when evalTupInfoIsStruct tupInfo -> l | _ -> failwith "destStructTupleTy: not a struct tuple type") +let destTyparTy g ty = ty |> stripTyEqns g |> (function TType_var v -> v | _ -> failwith "destTyparTy: not a typar type") +let destAnyParTy g ty = ty |> stripTyEqns g |> (function TType_var v -> v | TType_measure unt -> destUnitParMeasure g unt | _ -> failwith "destAnyParTy: not a typar or unpar type") +let destMeasureTy g ty = ty |> stripTyEqns g |> (function TType_measure m -> m | _ -> failwith "destMeasureTy: not a unit-of-measure type") +let isFunTy g ty = ty |> stripTyEqns g |> (function TType_fun _ -> true | _ -> false) +let isForallTy g ty = ty |> stripTyEqns g |> (function TType_forall _ -> true | _ -> false) +let isAnyTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple _ -> true | _ -> false) +let isRefTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, _) -> not (evalTupInfoIsStruct tupInfo) | _ -> false) +let isStructTupleTy g ty = ty |> stripTyEqns g |> (function TType_tuple (tupInfo, _) -> evalTupInfoIsStruct tupInfo | _ -> false) +let isAnonRecdTy g ty = ty |> stripTyEqns g |> (function TType_anon _ -> true | _ -> false) +let isStructAnonRecdTy g ty = ty |> stripTyEqns g |> (function TType_anon (anonInfo, _) -> evalAnonInfoIsStruct anonInfo | _ -> false) +let isUnionTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsUnionTycon | _ -> false) +let isReprHiddenTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsHiddenReprTycon | _ -> false) let isFSharpObjModelTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsFSharpObjectModelTycon | _ -> false) -let isRecdTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsRecordTycon | _ -> false) -let isFSharpStructOrEnumTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsFSharpStructOrEnumTycon | _ -> false) -let isFSharpEnumTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsFSharpEnumTycon | _ -> false) -let isTyparTy g ty = ty |> stripTyEqns g |> (function TType_var _ -> true | _ -> false) -let isAnyParTy g ty = ty |> stripTyEqns g |> (function TType_var _ -> true | TType_measure unt -> isUnitParMeasure g unt | _ -> false) -let isMeasureTy g ty = ty |> stripTyEqns g |> (function TType_measure _ -> true | _ -> false) +let isRecdTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsRecordTycon | _ -> false) +let isFSharpStructOrEnumTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsFSharpStructOrEnumTycon | _ -> false) +let isFSharpEnumTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsFSharpEnumTycon | _ -> false) +let isTyparTy g ty = ty |> stripTyEqns g |> (function TType_var _ -> true | _ -> false) +let isAnyParTy g ty = ty |> stripTyEqns g |> (function TType_var _ -> true | TType_measure unt -> isUnitParMeasure g unt | _ -> false) +let isMeasureTy g ty = ty |> stripTyEqns g |> (function TType_measure _ -> true | _ -> false) let isProvenUnionCaseTy ty = match ty with TType_ucase _ -> true | _ -> false let mkAppTy tcref tyargs = TType_app(tcref, tyargs) let mkProvenUnionCaseTy ucref tyargs = TType_ucase(ucref, tyargs) -let isAppTy g ty = ty |> stripTyEqns g |> (function TType_app _ -> true | _ -> false) +let isAppTy g ty = ty |> stripTyEqns g |> (function TType_app _ -> true | _ -> false) let tryAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, tinst) -> ValueSome (tcref, tinst) | _ -> ValueNone) let destAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, tinst) -> tcref, tinst | _ -> failwith "destAppTy") -let tcrefOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref | _ -> failwith "tcrefOfAppTy") -let argsOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(_, tinst) -> tinst | _ -> []) +let tcrefOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref | _ -> failwith "tcrefOfAppTy") +let argsOfAppTy g ty = ty |> stripTyEqns g |> (function TType_app(_, tinst) -> tinst | _ -> []) let tryDestTyparTy g ty = ty |> stripTyEqns g |> (function TType_var v -> ValueSome v | _ -> ValueNone) -let tryDestFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (tyv, tau) -> ValueSome(tyv, tau) | _ -> ValueNone) -let tryDestAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> ValueSome tcref | _ -> ValueNone) +let tryDestFunTy g ty = ty |> stripTyEqns g |> (function TType_fun (tyv, tau) -> ValueSome(tyv, tau) | _ -> ValueNone) +let tryDestAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> ValueSome tcref | _ -> ValueNone) let tryDestAnonRecdTy g ty = ty |> stripTyEqns g |> (function TType_anon (anonInfo, tys) -> ValueSome (anonInfo, tys) | _ -> ValueNone) -let tryAnyParTy g ty = ty |> stripTyEqns g |> (function TType_var v -> ValueSome v | TType_measure unt when isUnitParMeasure g unt -> ValueSome(destUnitParMeasure g unt) | _ -> ValueNone) -let tryAnyParTyOption g ty = ty |> stripTyEqns g |> (function TType_var v -> Some v | TType_measure unt when isUnitParMeasure g unt -> Some(destUnitParMeasure g unt) | _ -> None) +let tryAnyParTy g ty = ty |> stripTyEqns g |> (function TType_var v -> ValueSome v | TType_measure unt when isUnitParMeasure g unt -> ValueSome(destUnitParMeasure g unt) | _ -> ValueNone) +let tryAnyParTyOption g ty = ty |> stripTyEqns g |> (function TType_var v -> Some v | TType_measure unt when isUnitParMeasure g unt -> Some(destUnitParMeasure g unt) | _ -> None) let (|AppTy|_|) g ty = ty |> stripTyEqns g |> (function TType_app(tcref, tinst) -> Some (tcref, tinst) | _ -> None) let (|RefTupleTy|_|) g ty = ty |> stripTyEqns g |> (function TType_tuple(tupInfo, tys) when not (evalTupInfoIsStruct tupInfo) -> Some tys | _ -> None) let (|FunTy|_|) g ty = ty |> stripTyEqns g |> (function TType_fun(dty, rty) -> Some (dty, rty) | _ -> None) -let tryNiceEntityRefOfTy ty = +let tryNiceEntityRefOfTy ty = let ty = stripTyparEqnsAux false ty match ty with | TType_app (tcref, _) -> ValueSome tcref | TType_measure (Measure.Con tcref) -> ValueSome tcref | _ -> ValueNone -let tryNiceEntityRefOfTyOption ty = +let tryNiceEntityRefOfTyOption ty = let ty = stripTyparEqnsAux false ty match ty with | TType_app (tcref, _) -> Some tcref @@ -856,7 +856,7 @@ let mkInstForAppTy g ty = | _ -> [] let domainOfFunTy g ty = fst (destFunTy g ty) -let rangeOfFunTy g ty = snd (destFunTy g ty) +let rangeOfFunTy g ty = snd (destFunTy g ty) let convertToTypeWithMetadataIfPossible g ty = if isAnyTupleTy g ty then @@ -936,12 +936,12 @@ and typarConstraintsAEquivAux erasureFlag g aenv tpc1 tpc2 = | TyparConstraint.SimpleChoice (tys1, _), TyparConstraint.SimpleChoice(tys2, _) -> ListSet.equals (typeAEquivAux erasureFlag g aenv) tys1 tys2 - | TyparConstraint.SupportsComparison _ , TyparConstraint.SupportsComparison _ - | TyparConstraint.SupportsEquality _ , TyparConstraint.SupportsEquality _ - | TyparConstraint.SupportsNull _ , TyparConstraint.SupportsNull _ - | TyparConstraint.IsNonNullableStruct _ , TyparConstraint.IsNonNullableStruct _ - | TyparConstraint.IsReferenceType _ , TyparConstraint.IsReferenceType _ - | TyparConstraint.IsUnmanaged _ , TyparConstraint.IsUnmanaged _ + | TyparConstraint.SupportsComparison _, TyparConstraint.SupportsComparison _ + | TyparConstraint.SupportsEquality _, TyparConstraint.SupportsEquality _ + | TyparConstraint.SupportsNull _, TyparConstraint.SupportsNull _ + | TyparConstraint.IsNonNullableStruct _, TyparConstraint.IsNonNullableStruct _ + | TyparConstraint.IsReferenceType _, TyparConstraint.IsReferenceType _ + | TyparConstraint.IsUnmanaged _, TyparConstraint.IsUnmanaged _ | TyparConstraint.RequiresDefaultConstructor _, TyparConstraint.RequiresDefaultConstructor _ -> true | _ -> false @@ -970,10 +970,10 @@ and typeAEquivAux erasureFlag g aenv ty1 ty2 = match aenv.EquivTypars.TryFind tp1 with | Some v -> typeEquivAux erasureFlag g v ty2 | None -> false - | TType_app (tc1, b1) , TType_app (tc2, b2) -> + | TType_app (tc1, b1), TType_app (tc2, b2) -> tcrefAEquiv g aenv tc1 tc2 && typesAEquivAux erasureFlag g aenv b1 b2 - | TType_ucase (UCRef(tc1, n1), b1) , TType_ucase (UCRef(tc2, n2), b2) -> + | TType_ucase (UCRef(tc1, n1), b1), TType_ucase (UCRef(tc2, n2), b2) -> n1=n2 && tcrefAEquiv g aenv tc1 tc2 && typesAEquivAux erasureFlag g aenv b1 b2 @@ -1056,7 +1056,7 @@ let rec getErasedTypes g ty = let valOrder = { new IComparer with member __.Compare(v1, v2) = compare v1.Stamp v2.Stamp } let tyconOrder = { new IComparer with member __.Compare(tc1, tc2) = compare tc1.Stamp tc2.Stamp } -let recdFieldRefOrder = +let recdFieldRefOrder = { new IComparer with member __.Compare(RFRef(tcref1, nm1), RFRef(tcref2, nm2)) = let c = tyconOrder.Compare (tcref1.Deref, tcref2.Deref) @@ -1105,7 +1105,7 @@ let ensureCcuHasModuleOrNamespaceAtPath (ccu: CcuThunk) path (CompPath(_, cpath) 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)) @@ -1139,7 +1139,7 @@ let tryDestRefTupleExpr e = match e with Expr.Op (TOp.Tuple tupInfo, _, es, _) w let rec rangeOfExpr x = match x with - | Expr.Val (_, _, m) | Expr.Op (_, _, _, m) | Expr.Const (_, m, _) | Expr.Quote (_, _, _, m, _) + | Expr.Val (_, _, m) | Expr.Op (_, _, _, m) | Expr.Const (_, m, _) | Expr.Quote (_, _, _, m, _) | Expr.Obj (_, _, _, _, _, _, m) | Expr.App(_, _, _, _, m) | Expr.Sequential (_, _, _, _, m) | Expr.StaticOptimization (_, _, _, m) | Expr.Lambda (_, _, _, _, _, m, _) | Expr.TyLambda (_, _, _, m, _)| Expr.TyChoose (_, _, m) | Expr.LetRec (_, _, m, _) | Expr.Let (_, _, m, _) | Expr.Match (_, _, _, _, m, _) -> m @@ -1167,7 +1167,7 @@ type MatchBuilder(spBind, inpRange: Range.range) = member x.CloseTargets() = targets |> ResizeArray.toList - member x.Close(dtree, m, ty) = primMkMatch (spBind, inpRange, dtree, targets.ToArray(), m, ty) + member x.Close(dtree, m, ty) = primMkMatch (spBind, inpRange, dtree, targets.ToArray(), m, ty) let mkBoolSwitch m g t e = TDSwitch(g, [TCase(DecisionTreeTest.Const(Const.Bool(true)), t)], Some e, m) @@ -1176,25 +1176,25 @@ let primMkCond spBind spTarget1 spTarget2 m ty e1 e2 e3 = let dtree = mkBoolSwitch m e1 (mbuilder.AddResultTarget(e2, spTarget1)) (mbuilder.AddResultTarget(e3, spTarget2)) mbuilder.Close(dtree, m, ty) -let mkCond spBind spTarget m ty e1 e2 e3 = primMkCond spBind spTarget spTarget m ty e1 e2 e3 +let mkCond spBind spTarget m ty e1 e2 e3 = primMkCond spBind spTarget spTarget m ty e1 e2 e3 //--------------------------------------------------------------------------- // Primitive constructors //--------------------------------------------------------------------------- -let exprForValRef m vref = Expr.Val(vref, NormalValUse, m) -let exprForVal m v = exprForValRef m (mkLocalValRef v) +let exprForValRef m vref = Expr.Val(vref, NormalValUse, m) +let exprForVal m v = exprForValRef m (mkLocalValRef v) let mkLocalAux m s ty mut compgen = let thisv = NewVal(s, m, None, ty, mut, compgen, None, taccessPublic, ValNotInRecScope, None, NormalVal, [], ValInline.Optional, XmlDoc.Empty, false, false, false, false, false, false, None, ParentNone) thisv, exprForVal m thisv -let mkLocal m s ty = mkLocalAux m s ty Immutable false +let mkLocal m s ty = mkLocalAux m s ty Immutable false let mkCompGenLocal m s ty = mkLocalAux m s ty Immutable true let mkMutableCompGenLocal m s ty = mkLocalAux m s ty Mutable true -// Type gives return type. For type-lambdas this is the formal return type. +// Type gives return type. For type-lambdas this is the formal return type. let mkMultiLambda m vs (b, rty) = Expr.Lambda (newUnique(), None, None, vs, b, m, rty) let rebuildLambda m ctorThisValOpt baseValOpt vs (b, rty) = Expr.Lambda (newUnique(), ctorThisValOpt, baseValOpt, vs, b, m, rty) let mkLambda m v (b, rty) = mkMultiLambda m [v] (b, rty) @@ -1225,7 +1225,7 @@ let mkMemberLambdas m tps ctorThisValOpt baseValOpt vsl (b, rty) = (rebuildLambda m ctorThisValOpt baseValOpt h (b, rty), (typeOfLambdaArg m h --> rty)) mkTypeLambda m tps expr -let mkMultiLambdaBind v letSeqPtOpt m tps vsl (b, rty) = +let mkMultiLambdaBind v letSeqPtOpt m tps vsl (b, rty) = TBind(v, mkMultiLambdas m tps vsl (b, rty), letSeqPtOpt) let mkBind seqPtOpt v e = TBind(v, e, seqPtOpt) @@ -1300,65 +1300,65 @@ let isBeingGeneralized tp typeScheme = 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) +let mkCoerceExpr(e, to_ty, m, from_ty) = Expr.Op (TOp.Coerce, [to_ty;from_ty], [e], m) -let mkAsmExpr(code, tinst, args, rettys, m) = Expr.Op (TOp.ILAsm(code, rettys), tinst, args, m) -let mkUnionCaseExpr(uc, tinst, args, m) = Expr.Op (TOp.UnionCase uc, tinst, args, m) -let mkExnExpr(uc, args, m) = Expr.Op (TOp.ExnConstr uc, [], args, m) -let mkTupleFieldGetViaExprAddr(tupInfo, e, tinst, i, m) = Expr.Op (TOp.TupleFieldGet(tupInfo, i), tinst, [e], m) -let mkAnonRecdFieldGetViaExprAddr(anonInfo, e, tinst, i, m) = Expr.Op (TOp.AnonRecdGet(anonInfo, i), tinst, [e], m) +let mkAsmExpr(code, tinst, args, rettys, m) = Expr.Op (TOp.ILAsm(code, rettys), tinst, args, m) +let mkUnionCaseExpr(uc, tinst, args, m) = Expr.Op (TOp.UnionCase uc, tinst, args, m) +let mkExnExpr(uc, args, m) = Expr.Op (TOp.ExnConstr uc, [], args, m) +let mkTupleFieldGetViaExprAddr(tupInfo, e, tinst, i, m) = Expr.Op (TOp.TupleFieldGet(tupInfo, i), tinst, [e], m) +let mkAnonRecdFieldGetViaExprAddr(anonInfo, e, tinst, i, m) = Expr.Op (TOp.AnonRecdGet(anonInfo, i), tinst, [e], m) -let mkRecdFieldGetViaExprAddr(e, fref, tinst, m) = Expr.Op (TOp.ValFieldGet(fref), tinst, [e], m) +let mkRecdFieldGetViaExprAddr(e, fref, tinst, m) = Expr.Op (TOp.ValFieldGet(fref), tinst, [e], m) let mkRecdFieldGetAddrViaExprAddr(readonly, e, fref, tinst, m) = Expr.Op (TOp.ValFieldGetAddr(fref, readonly), tinst, [e], m) let mkStaticRecdFieldGetAddr(readonly, fref, tinst, m) = Expr.Op (TOp.ValFieldGetAddr(fref, readonly), tinst, [], m) -let mkStaticRecdFieldGet(fref, tinst, m) = Expr.Op (TOp.ValFieldGet(fref), tinst, [], m) -let mkStaticRecdFieldSet(fref, tinst, e, m) = Expr.Op (TOp.ValFieldSet(fref), tinst, [e], m) +let mkStaticRecdFieldGet(fref, tinst, m) = Expr.Op (TOp.ValFieldGet(fref), tinst, [], m) +let mkStaticRecdFieldSet(fref, tinst, e, m) = Expr.Op (TOp.ValFieldSet(fref), tinst, [e], m) let mkArrayElemAddress g (readonly, ilInstrReadOnlyAnnotation, isNativePtr, shape, elemTy, exprs, m) = Expr.Op (TOp.ILAsm ([IL.I_ldelema(ilInstrReadOnlyAnnotation, isNativePtr, shape, mkILTyvarTy 0us)], [mkByrefTyWithFlag g readonly elemTy]), [elemTy], exprs, m) -let mkRecdFieldSetViaExprAddr (e1, fref, tinst, e2, m) = Expr.Op (TOp.ValFieldSet(fref), tinst, [e1;e2], m) +let mkRecdFieldSetViaExprAddr (e1, fref, tinst, e2, m) = Expr.Op (TOp.ValFieldSet(fref), tinst, [e1;e2], m) -let mkUnionCaseTagGetViaExprAddr (e1, cref, tinst, m) = Expr.Op (TOp.UnionCaseTagGet(cref), tinst, [e1], m) +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, +/// the input expression has 'TType_ucase', which is an F# compiler internal "type" corresponding to the union case. For struct-unions, /// the input should be the address of the expression. -let mkUnionCaseFieldGetProvenViaExprAddr (e1, cref, tinst, j, m) = Expr.Op (TOp.UnionCaseFieldGet(cref, j), tinst, [e1], m) +let mkUnionCaseFieldGetProvenViaExprAddr (e1, cref, tinst, j, m) = Expr.Op (TOp.UnionCaseFieldGet(cref, j), tinst, [e1], m) /// Build a 'TOp.UnionCaseFieldGetAddr' expression for a field of a union when we've already determined the value 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, /// the input should be the address of the expression. -let mkUnionCaseFieldGetAddrProvenViaExprAddr (readonly, e1, cref, tinst, j, m) = Expr.Op (TOp.UnionCaseFieldGetAddr(cref, j, readonly), tinst, [e1], m) +let mkUnionCaseFieldGetAddrProvenViaExprAddr (readonly, e1, cref, tinst, j, m) = Expr.Op (TOp.UnionCaseFieldGetAddr(cref, j, readonly), tinst, [e1], m) /// Build a 'get' expression for something we've already determined to be a particular union case, but where /// the static type of the input is not yet proven to be that particular union case. This requires a type /// cast to 'prove' the condition. -let mkUnionCaseFieldGetUnprovenViaExprAddr (e1, cref, tinst, j, m) = mkUnionCaseFieldGetProvenViaExprAddr(mkUnionCaseProof(e1, cref, tinst, m), cref, tinst, j, m) +let mkUnionCaseFieldGetUnprovenViaExprAddr (e1, cref, tinst, j, m) = mkUnionCaseFieldGetProvenViaExprAddr(mkUnionCaseProof(e1, cref, tinst, m), cref, tinst, j, m) -let mkUnionCaseFieldSet (e1, cref, tinst, j, e2, m) = Expr.Op (TOp.UnionCaseFieldSet(cref, j), tinst, [e1;e2], m) +let mkUnionCaseFieldSet (e1, cref, tinst, j, e2, m) = Expr.Op (TOp.UnionCaseFieldSet(cref, j), tinst, [e1;e2], m) -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 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 m = e.Range mkLambda m (fst (mkCompGenLocal m "unitVar" g.unit_ty)) (e, ety) -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 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) = - 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 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) = 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) @@ -1456,11 +1456,11 @@ 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 @@ -1616,17 +1616,17 @@ let tyconRefEqOpt g tcOpt tc = | None -> false | Some tc2 -> tyconRefEq g tc2 tc -let isStringTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g tcref g.system_String_tcref | _ -> false) -let isListTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g tcref g.list_tcr_canon | _ -> false) -let isArrayTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> isArrayTyconRef g tcref | _ -> false) -let isArray1DTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g tcref g.il_arr_tcr_map.[0] | _ -> false) -let isUnitTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g g.unit_tcr_canon tcref | _ -> false) -let isObjTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g g.system_Object_tcref tcref | _ -> false) -let isVoidTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g g.system_Void_tcref tcref | _ -> false) -let isILAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsILTycon | _ -> false) -let isNativePtrTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g g.nativeptr_tcr tcref | _ -> false) - -let isByrefTy g ty = +let isStringTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g tcref g.system_String_tcref | _ -> false) +let isListTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g tcref g.list_tcr_canon | _ -> false) +let isArrayTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> isArrayTyconRef g tcref | _ -> false) +let isArray1DTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g tcref g.il_arr_tcr_map.[0] | _ -> false) +let isUnitTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g g.unit_tcr_canon tcref | _ -> false) +let isObjTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g g.system_Object_tcref tcref | _ -> false) +let isVoidTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g g.system_Void_tcref tcref | _ -> false) +let isILAppTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.IsILTycon | _ -> false) +let isNativePtrTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tyconRefEq g g.nativeptr_tcr tcref | _ -> false) + +let isByrefTy g ty = ty |> stripTyEqns g |> (function | TType_app(tcref, _) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref | TType_app(tcref, _) -> tyconRefEq g g.byref_tcr tcref @@ -1635,24 +1635,24 @@ let isByrefTy g ty = let isInByrefTag g ty = ty |> stripTyEqns g |> (function TType_app(tcref, []) -> tyconRefEq g g.byrefkind_In_tcr tcref | _ -> false) let isInByrefTy g ty = ty |> stripTyEqns g |> (function - | TType_app(tcref, [_; tag]) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref && isInByrefTag g tag + | TType_app(tcref, [_; tag]) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref && isInByrefTag g tag | _ -> false) let isOutByrefTag g ty = ty |> stripTyEqns g |> (function TType_app(tcref, []) -> tyconRefEq g g.byrefkind_Out_tcr tcref | _ -> false) let isOutByrefTy g ty = ty |> stripTyEqns g |> (function - | TType_app(tcref, [_; tag]) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref && isOutByrefTag g tag + | TType_app(tcref, [_; tag]) when g.byref2_tcr.CanDeref -> tyconRefEq g g.byref2_tcr tcref && isOutByrefTag g tag | _ -> false) #if !NO_EXTENSIONTYPING -let extensionInfoOfTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.TypeReprInfo | _ -> TNoRepr) +let extensionInfoOfTy g ty = ty |> stripTyEqns g |> (function TType_app(tcref, _) -> tcref.TypeReprInfo | _ -> TNoRepr) #endif type TypeDefMetadata = | ILTypeMetadata of TILObjectReprData | FSharpOrArrayOrByrefOrTupleOrExnTypeMetadata #if !NO_EXTENSIONTYPING - | ProvidedTypeMetadata of TProvidedTypeInfo + | ProvidedTypeMetadata of TProvidedTypeInfo #endif let metadataOfTycon (tycon: Tycon) = @@ -1702,7 +1702,7 @@ let isFSharpObjModelRefTy g ty = isFSharpObjModelTy g ty && let tcref = tcrefOfAppTy g ty match tcref.FSharpObjectModelTypeInfo.fsobjmodel_kind with - | TTyconClass | TTyconInterface | TTyconDelegate _ -> true + | TTyconClass | TTyconInterface | TTyconDelegate _ -> true | TTyconStruct | TTyconEnum -> false let isFSharpClassTy g ty = @@ -1791,8 +1791,8 @@ let rec isUnmanagedTy g ty = let ty = stripTyEqnsAndMeasureEqns g ty match tryDestAppTy g ty with | ValueSome tcref -> - let isEq tcref2 = tyconRefEq g tcref tcref2 - if isEq g.nativeptr_tcr || isEq g.nativeint_tcr || + let isEq tcref2 = tyconRefEq g tcref tcref2 + if isEq g.nativeptr_tcr || isEq g.nativeint_tcr || isEq g.sbyte_tcr || isEq g.byte_tcr || isEq g.int16_tcr || isEq g.uint16_tcr || isEq g.int32_tcr || isEq g.uint32_tcr || @@ -1915,9 +1915,9 @@ let isEmptyFreeTyvars ftyvs = let unionFreeTyvars fvs1 fvs2 = if fvs1 === emptyFreeTyvars then fvs2 else if fvs2 === emptyFreeTyvars then fvs1 else - { FreeTycons = unionFreeTycons fvs1.FreeTycons fvs2.FreeTycons - FreeTraitSolutions = unionFreeLocals fvs1.FreeTraitSolutions fvs2.FreeTraitSolutions - FreeTypars = unionFreeTypars fvs1.FreeTypars fvs2.FreeTypars } + { FreeTycons = unionFreeTycons fvs1.FreeTycons fvs2.FreeTycons + FreeTraitSolutions = unionFreeLocals fvs1.FreeTraitSolutions fvs2.FreeTraitSolutions + FreeTypars = unionFreeTypars fvs1.FreeTypars fvs2.FreeTypars } type FreeVarOptions = { canCache: bool @@ -2006,7 +2006,7 @@ let accFreeTycon opts (tcref: TyconRef) 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 List.foldBack (fun tp acc -> { acc with FreeTypars = Zset.remove tp acc.FreeTypars}) tps acc @@ -2070,7 +2070,7 @@ and accFreeTyparRef opts (tp: Typar) acc = accFreeInTyparConstraints opts tp.Constraints { acc with FreeTypars = Zset.add tp acc.FreeTypars} -and accFreeInType opts ty acc = +and accFreeInType opts ty acc = match stripTyparEqns ty with | TType_tuple (tupInfo, l) -> accFreeInTypes opts l (accFreeInTupInfo opts tupInfo acc) | TType_anon (anonInfo, l) -> accFreeInTypes opts l (accFreeInTupInfo opts anonInfo.TupInfo acc) @@ -2080,7 +2080,7 @@ and accFreeInType opts ty acc = | [] -> acc // optimization to avoid unneeded call | [h] -> accFreeInType opts h acc // optimization to avoid unneeded call | _ -> accFreeInTypes opts tinst acc - | TType_ucase (UCRef(tc, _), tinst) -> accFreeInTypes opts tinst (accFreeTycon opts tc acc) + | TType_ucase (UCRef(tc, _), tinst) -> accFreeInTypes opts tinst (accFreeTycon opts tc acc) | TType_fun (d, r) -> accFreeInType opts d (accFreeInType opts r acc) | TType_var r -> accFreeTyparRef opts r acc | TType_forall (tps, r) -> unionFreeTyvars (boundTypars opts tps (freeInType opts r)) acc @@ -2113,15 +2113,15 @@ let freeInModuleTy mtyp = addFreeInModuleTy mtyp emptyFreeTyvars //-------------------------------------------------------------------------- // Free in type, left-to-right order preserved. This is used to determine the // order of type variables for top-level definitions based on their signature, -// so be careful not to change the order. We accumulate in reverse +// so be careful not to change the order. We accumulate in reverse // order. //-------------------------------------------------------------------------- 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 +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 // 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 @@ -2150,7 +2150,7 @@ and accFreeInTyparConstraintLeftToRight g cxFlag thruFlag acc tpc = | TyparConstraint.IsReferenceType _ | TyparConstraint.RequiresDefaultConstructor _ -> acc -and accFreeInTraitLeftToRight g cxFlag thruFlag acc (TTrait(tys, _, _, argtys, rty, _)) = +and accFreeInTraitLeftToRight g cxFlag thruFlag acc (TTrait(tys, _, _, argtys, rty, _)) = let acc = accFreeInTypesLeftToRight g cxFlag thruFlag acc tys let acc = accFreeInTypesLeftToRight g cxFlag thruFlag acc argtys let acc = Option.fold (accFreeInTypeLeftToRight g cxFlag thruFlag) acc rty @@ -2166,9 +2166,9 @@ and accFreeTyparRefLeftToRight g cxFlag thruFlag acc (tp: Typar) = else acc -and accFreeInTypeLeftToRight g cxFlag thruFlag acc ty = +and accFreeInTypeLeftToRight g cxFlag thruFlag acc ty = match (if thruFlag then stripTyEqns g ty else stripTyparEqns ty) with - | TType_anon (anonInfo, anonTys) -> + | TType_anon (anonInfo, anonTys) -> let acc = accFreeInTupInfoLeftToRight g cxFlag thruFlag acc anonInfo.TupInfo accFreeInTypesLeftToRight g cxFlag thruFlag acc anonTys | TType_tuple (tupInfo, tupTys) -> @@ -2235,7 +2235,7 @@ let GetMemberTypeInFSharpForm g memberFlags arities ty m = // It will also always have an arity (inferred from syntax). let checkMemberVal membInfo arity m = match membInfo, arity with - | None, _ -> error(InternalError("checkMemberVal - no membInfo" , m)) + | None, _ -> error(InternalError("checkMemberVal - no membInfo", m)) | _, None -> error(InternalError("checkMemberVal - no arity", m)) | Some membInfo, Some arity -> (membInfo, arity) @@ -2248,11 +2248,11 @@ let GetTopValTypeInCompiledForm g topValInfo ty m = let paramArgInfos = match paramArgInfos, topValInfo.ArgInfos with // static member and module value unit argument elimination - | [[(_argType, _)]] , [[]] -> + | [[(_argType, _)]], [[]] -> //assert isUnitTy g argType [[]] // instance member unit argument elimination - | [objInfo;[(_argType, _)]] , [[_objArg];[]] -> + | [objInfo;[(_argType, _)]], [[_objArg];[]] -> //assert isUnitTy g argType [objInfo; []] | _ -> @@ -2274,11 +2274,11 @@ let GetMemberTypeInMemberForm g memberFlags topValInfo ty m = let paramArgInfos = match paramArgInfos, topValInfo.ArgInfos with // static member and module value unit argument elimination - | [[(argType, _)]] , [[]] -> + | [[(argType, _)]], [[]] -> assert isUnitTy g argType [[]] // instance member unit argument elimination - | [[(argType, _)]] , [[_objArg];[]] -> + | [[(argType, _)]], [[_objArg];[]] -> assert isUnitTy g argType [[]] | _ -> @@ -2295,7 +2295,7 @@ 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 -> @@ -2335,7 +2335,7 @@ let ArgInfosOfMember g (vref: ValRef) = let GetFSharpViewOfReturnType (g: TcGlobals) retTy = match retTy with | None -> g.unit_ty - | Some retTy -> retTy + | Some retTy -> retTy /// Get the property "type" (getter return type) for an F# value that represents a getter or setter @@ -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 @@ -2454,7 +2454,7 @@ module PrettyTypes = let nm = if i < letters then String.make 1 (char(int baseName + i)) else String.make 1 baseName + string (i-letters+1) - tryName (nm, typeIndex, measureIndex) (fun () -> + tryName (nm, typeIndex, measureIndex) (fun () -> tryAgain (typeIndex, measureIndex)) else @@ -2591,7 +2591,7 @@ module SimplifyTypes = let accTyparCounts z ty = // Walk type to determine typars and their counts (for pprinting decisions) - foldTypeButNotConstraints (fun z ty -> match ty with | TType_var tp when tp.Rigidity = TyparRigidity.Rigid -> incM tp z | _ -> z) z ty + foldTypeButNotConstraints (fun z ty -> match ty with | TType_var tp when tp.Rigidity = TyparRigidity.Rigid -> incM tp z | _ -> z) z ty let emptyTyparCounts = Zmap.empty typarOrder @@ -2897,7 +2897,7 @@ let TryFindFSharpAttribute g tref attrs = List.tryFind (IsMatchingFSharpAttribut let TryFindFSharpAttributeOpt g tref attrs = match tref with None -> None | Some tref -> List.tryFind (IsMatchingFSharpAttribute g tref) attrs let HasFSharpAttributeOpt g trefOpt attrs = match trefOpt with Some tref -> List.exists (IsMatchingFSharpAttribute g tref) attrs | _ -> false -let IsMatchingFSharpAttributeOpt g attrOpt (Attrib(tcref2, _, _, _, _, _, _)) = match attrOpt with Some ((AttribInfo(_, tcref))) -> tyconRefEq g tcref tcref2 | _ -> false +let IsMatchingFSharpAttributeOpt g attrOpt (Attrib(tcref2, _, _, _, _, _, _)) = match attrOpt with Some ((AttribInfo(_, tcref))) -> tyconRefEq g tcref tcref2 | _ -> false let (|ExtractAttribNamedArg|_|) nm args = args |> List.tryPick (function (AttribNamedArg(nm2, _, _, v)) when nm = nm2 -> Some v | _ -> None) @@ -3200,9 +3200,9 @@ module DebugPrint = let angleL x = sepL Literals.leftAngle ^^ x ^^ rightL Literals.rightAngle - let braceL x = leftL Literals.leftBrace ^^ x ^^ rightL Literals.rightBrace + let braceL x = leftL Literals.leftBrace ^^ x ^^ rightL Literals.rightBrace - let braceBarL x = leftL Literals.leftBraceBar ^^ x ^^ rightL Literals.rightBraceBar + let braceBarL x = leftL Literals.leftBraceBar ^^ x ^^ rightL Literals.rightBraceBar let boolL = function true -> WordL.keywordTrue | false -> WordL.keywordFalse @@ -3308,9 +3308,9 @@ module DebugPrint = 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 - is multiple occurrence. + // #Type - inplace coercion constraint and singleton + // ('a :> Type) - inplace coercion constraint not singleton // ('a.opM: S->T) - inplace operator constraint let tpL = wordL (tagText (prefixOfStaticReq typar.StaticReq @@ -3744,9 +3744,9 @@ module DebugPrint = wordL(tagText "try") ^^ exprL x1 ^^ wordL(tagText "with") ^^ exprL x2 ^^ rightL(tagText "}") | Expr.Op (TOp.TryFinally _, [_], [x1;x2], _) -> wordL(tagText "try") ^^ exprL x1 ^^ wordL(tagText "finally") ^^ exprL x2 ^^ rightL(tagText "}") - | Expr.Op (TOp.Bytes _, _ , _ , _) -> + | Expr.Op (TOp.Bytes _, _, _, _) -> wordL(tagText "bytes++") - | Expr.Op (TOp.UInt16s _, _ , _ , _) -> wordL(tagText "uint16++") + | Expr.Op (TOp.UInt16s _, _, _, _) -> wordL(tagText "uint16++") | Expr.Op (TOp.RefAddrGet _, _tyargs, _args, _) -> wordL(tagText "GetRefLVal...") | Expr.Op (TOp.TraitCall _, _tyargs, _args, _) -> wordL(tagText "traitcall...") | Expr.Op (TOp.ExnFieldGet _, _tyargs, _args, _) -> wordL(tagText "TOp.ExnFieldGet...") @@ -3792,7 +3792,7 @@ module DebugPrint = and mdefL x = match x with - | TMDefRec(_, tycons , mbinds, _) -> aboveListL ((tycons |> List.map tyconL) @ List.map mbindL mbinds) + | TMDefRec(_, tycons, mbinds, _) -> aboveListL ((tycons |> List.map tyconL) @ List.map mbindL mbinds) | TMDefLet(bind, _) -> letL bind emptyL | TMDefDo(e, _) -> exprL e | TMDefs defs -> mdefsL defs @@ -3868,7 +3868,7 @@ module DebugPrint = //-------------------------------------------------------------------------- let wrapModuleOrNamespaceType id cpath mtyp = - NewModuleOrNamespace (Some cpath) taccessPublic id XmlDoc.Empty [] (MaybeLazy.Strict mtyp) + NewModuleOrNamespace (Some cpath) taccessPublic id XmlDoc.Empty [] (MaybeLazy.Strict mtyp) let wrapModuleOrNamespaceTypeInNamespace id cpath mtyp = let mspec = wrapModuleOrNamespaceType id cpath mtyp @@ -3888,7 +3888,7 @@ let SigTypeOfImplFile (TImplFile(_, _, mexpr, _, _, _)) = mexpr.Type type SignatureRepackageInfo = { RepackagedVals: (ValRef * ValRef) list - RepackagedEntities: (TyconRef * TyconRef) list } + RepackagedEntities: (TyconRef * TyconRef) list } member remapInfo.ImplToSigMapping = { TypeEquivEnv.Empty with EquivTycons = TyconRefMap.OfList remapInfo.RepackagedEntities } static member Empty = { RepackagedVals = []; RepackagedEntities= [] } @@ -3901,14 +3901,14 @@ type SignatureHidingInfo = HiddenUnionCases: Zset } static member Empty = - { HiddenTycons = Zset.empty tyconOrder - HiddenTyconReprs = Zset.empty tyconOrder - HiddenVals = Zset.empty valOrder - HiddenRecdFields = Zset.empty recdFieldRefOrder - HiddenUnionCases = Zset.empty unionCaseRefOrder } + { HiddenTycons = Zset.empty tyconOrder + HiddenTyconReprs = Zset.empty tyconOrder + HiddenVals = Zset.empty valOrder + HiddenRecdFields = Zset.empty recdFieldRefOrder + HiddenUnionCases = Zset.empty unionCaseRefOrder } let addValRemap v vNew tmenv = - { tmenv with valRemap= tmenv.valRemap.Add v (mkLocalValRef vNew) } + { tmenv with valRemap= tmenv.valRemap.Add v (mkLocalValRef vNew) } let mkRepackageRemapping mrpi = { valRemap = ValMap.OfList (mrpi.RepackagedVals |> List.map (fun (vref, x) -> vref.Deref, x)) @@ -3927,7 +3927,7 @@ let accEntityRemap (msigty: ModuleOrNamespaceType) (entity: Entity) (mrpi, mhi) // The type constructor is not present in the signature. Hence it is hidden. let mhi = { mhi with HiddenTycons = Zset.add entity mhi.HiddenTycons } (mrpi, mhi) - | Some sigtycon -> + | Some sigtycon -> // The type constructor is in the signature. Hence record the repackage entry let sigtcref = mkLocalTyconRef sigtycon let tcref = mkLocalTyconRef entity @@ -3943,24 +3943,24 @@ let accEntityRemap (msigty: ModuleOrNamespaceType) (entity: Entity) (mrpi, mhi) let mhi = (entity.AllFieldsArray, mhi) ||> Array.foldBack (fun rfield mhi -> match sigtycon.GetFieldByName(rfield.Name) with - | Some _ -> + | Some _ -> // The field is in the signature. Hence it is not hidden. mhi | _ -> // The field is not in the signature. Hence it is regarded as hidden. let rfref = tcref.MakeNestedRecdFieldRef rfield - { mhi with HiddenRecdFields = Zset.add rfref mhi.HiddenRecdFields }) + { mhi with HiddenRecdFields = Zset.add rfref mhi.HiddenRecdFields }) let mhi = (entity.UnionCasesAsList, mhi) ||> List.foldBack (fun ucase mhi -> match sigtycon.GetUnionCaseByName ucase.DisplayName with - | Some _ -> + | Some _ -> // The constructor is in the signature. Hence it is not hidden. mhi | _ -> // The constructor is not in the signature. Hence it is regarded as hidden. let ucref = tcref.MakeNestedUnionCaseRef ucase - { mhi with HiddenUnionCases = Zset.add ucref mhi.HiddenUnionCases }) + { mhi with HiddenUnionCases = Zset.add ucref mhi.HiddenUnionCases }) mhi (mrpi, mhi) @@ -3971,7 +3971,7 @@ let accSubEntityRemap (msigty: ModuleOrNamespaceType) (entity: Entity) (mrpi, mh // The type constructor is not present in the signature. Hence it is hidden. let mhi = { mhi with HiddenTycons = Zset.add entity mhi.HiddenTycons } (mrpi, mhi) - | Some sigtycon -> + | Some sigtycon -> // The type constructor is in the signature. Hence record the repackage entry let sigtcref = mkLocalTyconRef sigtycon let tcref = mkLocalTyconRef entity @@ -3995,7 +3995,7 @@ 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) @@ -4041,8 +4041,8 @@ let rec accEntityRemapFromModuleOrNamespace msigty x acc = let acc = (tycons, acc) ||> List.foldBack (accEntityRemap msigty) let acc = (tycons, acc) ||> List.foldBack (fun e acc -> accEntityRemapFromModuleOrNamespaceType e.ModuleOrNamespaceType (getCorrespondingSigTy e.LogicalName msigty) acc) acc - | TMDefLet _ -> acc - | TMDefDo _ -> acc + | TMDefLet _ -> acc + | TMDefDo _ -> acc | TMDefs defs -> accEntityRemapFromModuleOrNamespaceDefs msigty defs acc | TMAbstract mexpr -> accEntityRemapFromModuleOrNamespaceType mexpr.Type msigty acc @@ -4063,8 +4063,8 @@ let rec accValRemapFromModuleOrNamespace g aenv msigty x acc = let vslotvs = abstractSlotValsOfTycons tycons let acc = (vslotvs, acc) ||> List.foldBack (accValRemap g aenv msigty) acc - | TMDefLet(bind, _) -> accValRemap g aenv msigty bind.Var acc - | TMDefDo _ -> acc + | TMDefLet(bind, _) -> accValRemap g aenv msigty bind.Var acc + | TMDefDo _ -> acc | TMDefs defs -> accValRemapFromModuleOrNamespaceDefs g aenv msigty defs acc | TMAbstract mexpr -> accValRemapFromModuleOrNamespaceType g aenv mexpr.Type msigty acc @@ -4157,10 +4157,10 @@ let IsHidden setF accessF remapF debugF = if verbose then dprintf "IsHidden, #mrmi = %d, %s = %b\n" mrmi.Length (showL (debugF x)) res res -let IsHiddenTycon mrmi x = IsHidden (fun mhi -> mhi.HiddenTycons) (fun tc -> tc.Accessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) DebugPrint.tyconL mrmi x -let IsHiddenTyconRepr mrmi x = IsHidden (fun mhi -> mhi.HiddenTyconReprs) (fun v -> v.TypeReprAccessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) DebugPrint.tyconL mrmi x -let IsHiddenVal mrmi x = IsHidden (fun mhi -> mhi.HiddenVals) (fun v -> v.Accessibility) (fun rpi x -> (remapValRef rpi (mkLocalValRef x)).Deref) DebugPrint.valL mrmi x -let IsHiddenRecdField mrmi x = IsHidden (fun mhi -> mhi.HiddenRecdFields) (fun rfref -> rfref.RecdField.Accessibility) (fun rpi x -> remapRecdFieldRef rpi.tyconRefRemap x) DebugPrint.recdFieldRefL mrmi x +let IsHiddenTycon mrmi x = IsHidden (fun mhi -> mhi.HiddenTycons) (fun tc -> tc.Accessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) DebugPrint.tyconL mrmi x +let IsHiddenTyconRepr mrmi x = IsHidden (fun mhi -> mhi.HiddenTyconReprs) (fun v -> v.TypeReprAccessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) DebugPrint.tyconL mrmi x +let IsHiddenVal mrmi x = IsHidden (fun mhi -> mhi.HiddenVals) (fun v -> v.Accessibility) (fun rpi x -> (remapValRef rpi (mkLocalValRef x)).Deref) DebugPrint.valL mrmi x +let IsHiddenRecdField mrmi x = IsHidden (fun mhi -> mhi.HiddenRecdFields) (fun rfref -> rfref.RecdField.Accessibility) (fun rpi x -> remapRecdFieldRef rpi.tyconRefRemap x) DebugPrint.recdFieldRefL mrmi x //-------------------------------------------------------------------------- // Generic operations on module types @@ -4178,7 +4178,7 @@ let allValsOfModuleOrNamespaceTy m = foldModuleOrNamespaceTy (fun _ acc -> acc) let allEntitiesOfModuleOrNamespaceTy m = foldModuleOrNamespaceTy (fun ft acc -> ft :: acc) (fun _ acc -> acc) m [] //--------------------------------------------------------------------------- -// Free variables in terms. Are all constructs public accessible? +// Free variables in terms. Are all constructs public accessible? //--------------------------------------------------------------------------- let isPublicVal (lv: Val) = (lv.Accessibility = taccessPublic) @@ -4189,18 +4189,18 @@ let isPublicTycon (tcref: Tycon) = (tcref.Accessibility = taccessPublic) let freeVarsAllPublic fvs = // Are any non-public items used in the expr (which corresponded to the fvs)? // Recall, taccess occurs in: - // EntityData has ReprAccessibility and Accessiblity - // UnionCase has Accessibility - // RecdField has Accessibility - // ValData has Accessibility + // EntityData has ReprAccessibility and Accessiblity + // UnionCase has Accessibility + // RecdField has Accessibility + // ValData has Accessibility // The freevars and FreeTyvars collect local constructs. // Here, we test that all those constructs are public. // // CODEREVIEW: // What about non-local vals. This fix assumes non-local vals must be public. OK? - Zset.forall isPublicVal fvs.FreeLocals && + Zset.forall isPublicVal fvs.FreeLocals && Zset.forall isPublicUnionCase fvs.FreeUnionCases && - Zset.forall isPublicRecdField fvs.FreeRecdFields && + Zset.forall isPublicRecdField fvs.FreeRecdFields && Zset.forall isPublicTycon fvs.FreeTyvars.FreeTycons let freeTyvarsAllPublic tyvars = @@ -4220,7 +4220,7 @@ let rebuildLinearMatchExpr (sp, m, dtree, tg1, e2, sp2, m2, ty) = primMkMatch (sp, m, dtree, [|tg1;(TTarget([], e2, sp2))|], m2, ty) /// Detect a subset of 'Expr.Op' expressions we process in a linear way (i.e. using tailcalls, rather than -/// unbounded stack). Only covers Cons(args,Cons(args,Cons(args,Cons(args,...._)))). +/// unbounded stack). Only covers Cons(args,Cons(args,Cons(args,Cons(args,...._)))). let (|LinearOpExpr|_|) expr = match expr with | Expr.Op ((TOp.UnionCase _ as op), tinst, args, m) when not args.IsEmpty -> @@ -4232,7 +4232,7 @@ let rebuildLinearOpExpr (op, tinst, argsFront, argLast, m) = Expr.Op (op, tinst, argsFront@[argLast], m) //--------------------------------------------------------------------------- -// Free variables in terms. All binders are distinct. +// Free variables in terms. All binders are distinct. //--------------------------------------------------------------------------- let emptyFreeVars = @@ -4247,13 +4247,13 @@ let emptyFreeVars = let unionFreeVars fvs1 fvs2 = if fvs1 === emptyFreeVars then fvs2 else if fvs2 === emptyFreeVars then fvs1 else - { FreeLocals = unionFreeLocals fvs1.FreeLocals fvs2.FreeLocals - FreeTyvars = unionFreeTyvars fvs1.FreeTyvars fvs2.FreeTyvars - UsesMethodLocalConstructs = fvs1.UsesMethodLocalConstructs || fvs2.UsesMethodLocalConstructs - UsesUnboundRethrow = fvs1.UsesUnboundRethrow || fvs2.UsesUnboundRethrow - FreeLocalTyconReprs = unionFreeTycons fvs1.FreeLocalTyconReprs fvs2.FreeLocalTyconReprs - FreeRecdFields = unionFreeRecdFields fvs1.FreeRecdFields fvs2.FreeRecdFields - FreeUnionCases = unionFreeUnionCases fvs1.FreeUnionCases fvs2.FreeUnionCases } + { FreeLocals = unionFreeLocals fvs1.FreeLocals fvs2.FreeLocals + FreeTyvars = unionFreeTyvars fvs1.FreeTyvars fvs2.FreeTyvars + UsesMethodLocalConstructs = fvs1.UsesMethodLocalConstructs || fvs2.UsesMethodLocalConstructs + UsesUnboundRethrow = fvs1.UsesUnboundRethrow || fvs2.UsesUnboundRethrow + FreeLocalTyconReprs = unionFreeTycons fvs1.FreeLocalTyconReprs fvs2.FreeLocalTyconReprs + FreeRecdFields = unionFreeRecdFields fvs1.FreeRecdFields fvs2.FreeRecdFields + FreeUnionCases = unionFreeUnionCases fvs1.FreeUnionCases fvs2.FreeUnionCases } let inline accFreeTyvars (opts: FreeVarOptions) f v acc = if not opts.collectInTypes then acc else @@ -4262,10 +4262,10 @@ let inline accFreeTyvars (opts: FreeVarOptions) f v acc = if ftyvs === ftyvs' then acc else { acc with FreeTyvars = ftyvs' } -let accFreeVarsInTy opts ty acc = accFreeTyvars opts accFreeInType ty acc -let accFreeVarsInTys opts tys acc = if isNil tys then acc else accFreeTyvars opts accFreeInTypes tys acc +let accFreeVarsInTy opts ty acc = accFreeTyvars opts accFreeInType ty acc +let accFreeVarsInTys opts tys acc = if isNil tys then acc else accFreeTyvars opts accFreeInTypes tys acc let accFreevarsInTycon opts tcref acc = accFreeTyvars opts accFreeTycon tcref acc -let accFreevarsInVal opts v acc = accFreeTyvars opts accFreeInVal v acc +let accFreevarsInVal opts v acc = accFreeTyvars opts accFreeInVal v acc let accFreeVarsInTraitSln opts tys acc = accFreeTyvars opts accFreeInTraitSln tys acc @@ -4327,7 +4327,7 @@ and accFreeInValFlags opts flag acc = | VSlotDirectCall | CtorValUsedAsSelfInit | CtorValUsedAsSuperInit -> true - | PossibleConstrainedCall _ + | PossibleConstrainedCall _ | NormalValUse -> false let acc = accUsesFunctionLocalConstructs isMethLocal acc match flag with @@ -4343,11 +4343,11 @@ and accFreeLocalVal opts v fvs = and accLocalTyconRepr opts b fvs = if not opts.includeLocalTyconReprs then fvs else - if Zset.contains b fvs.FreeLocalTyconReprs then fvs + if Zset.contains b fvs.FreeLocalTyconReprs then fvs else { fvs with FreeLocalTyconReprs = Zset.add b fvs.FreeLocalTyconReprs } and accUsedRecdOrUnionTyconRepr opts (tc: Tycon) fvs = - if match tc.TypeReprInfo with TFSharpObjectRepr _ | TRecdRepr _ | TUnionRepr _ -> true | _ -> false + if match tc.TypeReprInfo with TFSharpObjectRepr _ | TRecdRepr _ | TUnionRepr _ -> true | _ -> false then accLocalTyconRepr opts tc fvs else fvs @@ -4376,7 +4376,7 @@ and accFreeValRef opts (vref: ValRef) fvs = and accFreeInMethod opts (TObjExprMethod(slotsig, _attribs, tps, tmvs, e, _)) acc = accFreeInSlotSig opts slotsig - (unionFreeVars (accFreeTyvars opts boundTypars tps (List.foldBack (boundLocalVals opts) tmvs (freeInExpr opts e))) acc) + (unionFreeVars (accFreeTyvars opts boundTypars tps (List.foldBack (boundLocalVals opts) tmvs (freeInExpr opts e))) acc) and accFreeInMethods opts methods acc = List.foldBack (accFreeInMethod opts) methods acc @@ -4404,7 +4404,7 @@ and accFreeInExprNonLinear opts x acc = match x with // BINDING CONSTRUCTS - | Expr.Lambda (_, ctorThisValOpt, baseValOpt, vs, bodyExpr, _, rty) -> + | Expr.Lambda (_, ctorThisValOpt, baseValOpt, vs, bodyExpr, _, rty) -> unionFreeVars (Option.foldBack (boundLocalVal opts) ctorThisValOpt (Option.foldBack (boundLocalVal opts) baseValOpt @@ -4425,7 +4425,7 @@ and accFreeInExprNonLinear opts x acc = | Expr.Let _ -> failwith "unreachable - linear expr" - | Expr.Obj (_, ty, basev, basecall, overrides, iimpls, _) -> + | Expr.Obj (_, ty, basev, basecall, overrides, iimpls, _) -> unionFreeVars (boundProtect (Option.foldBack (boundLocalVal opts) basev @@ -4505,7 +4505,7 @@ and accFreeInOp opts op acc = | TOp.Goto _ | TOp.Label _ | TOp.Return | TOp.TupleFieldGet _ -> acc - | TOp.Tuple tupInfo -> + | TOp.Tuple tupInfo -> accFreeTyvars opts accFreeInTupInfo tupInfo acc | TOp.AnonRecd anonInfo @@ -4526,7 +4526,7 @@ and accFreeInOp opts op acc = // Things containing just an exception reference | TOp.ExnConstr ecref | TOp.ExnFieldGet (ecref, _) - | TOp.ExnFieldSet (ecref, _) -> + | TOp.ExnFieldSet (ecref, _) -> accFreeExnRef ecref acc | TOp.ValFieldGet fref @@ -4591,14 +4591,14 @@ and freeInExpr opts expr = let rec accFreeInModuleOrNamespace opts mexpr acc = match mexpr with | TMDefRec(_, _, mbinds, _) -> List.foldBack (accFreeInModuleOrNamespaceBind opts) mbinds acc - | TMDefLet(bind, _) -> accBindRhs opts bind acc - | TMDefDo(e, _) -> accFreeInExpr opts e acc + | TMDefLet(bind, _) -> accBindRhs opts bind acc + | TMDefDo(e, _) -> accFreeInExpr opts e acc | TMDefs defs -> accFreeInModuleOrNamespaces opts defs acc | TMAbstract(ModuleOrNamespaceExprWithSig(_, mdef, _)) -> accFreeInModuleOrNamespace opts mdef acc // not really right, but sufficient for how this is used in optimization and accFreeInModuleOrNamespaceBind opts mbind acc = match mbind with - | ModuleOrNamespaceBinding.Binding bind -> accBindRhs opts bind acc + | ModuleOrNamespaceBinding.Binding bind -> accBindRhs opts bind acc | ModuleOrNamespaceBinding.Module (_, def) -> accFreeInModuleOrNamespace opts def acc and accFreeInModuleOrNamespaces opts mexprs acc = @@ -4667,7 +4667,7 @@ let InferArityOfExpr g allowTypeDirectedDetupling ty partialArgAttribsL retAttri let tps, vsl, _ = stripTopLambdaNoTypes expr let fun_arity = vsl.Length - let dtys, _ = stripFunTyN g fun_arity (snd (tryDestForallTy g ty)) + let dtys, _ = stripFunTyN g fun_arity (snd (tryDestForallTy g ty)) let partialArgAttribsL = Array.ofList partialArgAttribsL assert (List.length vsl = List.length dtys) @@ -4681,10 +4681,10 @@ let InferArityOfExpr g allowTypeDirectedDetupling ty partialArgAttribsL retAttri if (i = 0 && isUnitTy g ty) then [] else tryDestRefTupleTy g ty let ids = - if vs.Length = tys.Length then vs |> List.map (fun v -> Some v.Id) + if vs.Length = tys.Length then vs |> List.map (fun v -> Some v.Id) else tys |> List.map (fun _ -> None) let attribs = - if partialAttribs.Length = tys.Length then partialAttribs + 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 } @@ -4728,7 +4728,7 @@ let underlyingTypeOfEnumTy (g: TcGlobals) ty = let tycon = (tcrefOfAppTy g ty).Deref match tycon.GetFieldByName "value__" with | Some rf -> rf.FormalType - | None -> error(InternalError("no 'value__' field found for enumeration type " + tycon.LogicalName, tycon.Range)) + | 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) = @@ -4757,13 +4757,13 @@ let decideStaticOptimizationConstraint g c = match b with | AppTy g (tcref2, _) -> if tyconRefEq g tcref1 tcref2 then StaticOptimizationAnswer.Yes else StaticOptimizationAnswer.No - | RefTupleTy g _ | FunTy g _ -> StaticOptimizationAnswer.No + | RefTupleTy g _ | FunTy g _ -> StaticOptimizationAnswer.No | _ -> StaticOptimizationAnswer.Unknown | FunTy g _ -> let b = normalizeEnumTy g (stripTyEqnsAndMeasureEqns g b) match b with - | FunTy g _ -> StaticOptimizationAnswer.Yes + | FunTy g _ -> StaticOptimizationAnswer.Yes | AppTy g _ | RefTupleTy g _ -> StaticOptimizationAnswer.No | _ -> StaticOptimizationAnswer.Unknown | RefTupleTy g ts1 -> @@ -4824,12 +4824,12 @@ 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 = - { tyenv with tyconRefRemap=tyenv.tyconRefRemap.Add (mkLocalTyconRef tc) (mkLocalTyconRef tc') } + { tyenv with tyconRefRemap=tyenv.tyconRefRemap.Add (mkLocalTyconRef tc) (mkLocalTyconRef tc') } let bindTycons tcs tcs' tyenv = { tyenv with tyconRefRemap= (tcs, tcs', tyenv.tyconRefRemap) |||> List.foldBack2 (fun tc tc' acc -> acc.Add (mkLocalTyconRef tc) (mkLocalTyconRef tc')) } -let remapAttribKind tmenv k = +let remapAttribKind tmenv k = match k with | ILAttrib _ as x -> x | FSAttrib vref -> FSAttrib(remapValRef tmenv vref) @@ -4851,7 +4851,7 @@ let rec remapAttrib g tmenv (Attrib (tcref, kind, args, props, isGetOrSetAttr, t and remapAttribExpr g tmenv (AttribExpr(e1, e2)) = AttribExpr(remapExpr g CloneAll tmenv e1, remapExpr g CloneAll tmenv e2) -and remapAttribs g tmenv xs = List.map (remapAttrib g tmenv) xs +and remapAttribs g tmenv xs = List.map (remapAttrib g tmenv) xs and remapPossibleForallTy g tmenv ty = remapTypeFull (remapAttribs g tmenv) tmenv ty @@ -4870,15 +4870,15 @@ and remapValData g tmenv (d: ValData) = let memberInfoR = d.MemberInfo |> Option.map (remapMemberInfo g d.val_range topValInfo ty tyR tmenv) let attribsR = d.Attribs |> remapAttribs g tmenv { d with - val_type = tyR + val_type = tyR val_opt_data = match d.val_opt_data with | Some dd -> Some { dd with val_declaring_entity = declaringEntityR - val_repr_info = reprInfoR - val_member_info = memberInfoR - val_attribs = attribsR } + val_repr_info = reprInfoR + val_member_info = memberInfoR + val_attribs = attribsR } | None -> None } and remapParentRef tyenv p = @@ -4894,7 +4894,7 @@ and mapImmediateValsAndTycons ft fv (x: ModuleOrNamespaceType) = and copyVal compgen (v: Val) = match compgen with | OnlyCloneExprVals when v.IsMemberOrModuleBinding -> v - | _ -> v |> NewModifiedVal id + | _ -> v |> NewModifiedVal id and fixupValData g compgen tmenv (v2: Val) = // only fixup if we copy the value @@ -4928,9 +4928,9 @@ and remapExpr (g: TcGlobals) (compgen: ValCopyFlag) (tmenv: Remap) expr = remapLinearExpr g compgen tmenv expr (fun x -> x) // Binding constructs - see also dtrees below - | Expr.Lambda (_, ctorThisValOpt, baseValOpt, vs, b, m, rty) -> - let ctorThisValOpt, tmenv = Option.mapFold (copyAndRemapAndBindVal g compgen) tmenv ctorThisValOpt - let baseValOpt, tmenv = Option.mapFold (copyAndRemapAndBindVal g compgen) tmenv baseValOpt + | Expr.Lambda (_, ctorThisValOpt, baseValOpt, vs, b, m, rty) -> + let ctorThisValOpt, tmenv = Option.mapFold (copyAndRemapAndBindVal g compgen) tmenv ctorThisValOpt + let baseValOpt, tmenv = Option.mapFold (copyAndRemapAndBindVal g compgen) tmenv baseValOpt let vs, tmenv = copyAndRemapAndBindVals g compgen tmenv vs let b = remapExpr g compgen tmenv b let rty = remapType tmenv rty @@ -4962,7 +4962,7 @@ and remapExpr (g: TcGlobals) (compgen: ValCopyFlag) (tmenv: Remap) expr = | Expr.Quote (a, {contents=Some(typeDefs, argTypes, argExprs, data)}, isFromQueryExpression, m, ty) -> // fix value of compgen for both original expression and pickled AST let compgen = fixValCopyFlagForQuotations compgen - Expr.Quote (remapExpr g compgen tmenv a, {contents=Some(typeDefs, remapTypesAux tmenv argTypes, remapExprs g compgen tmenv argExprs, data)}, isFromQueryExpression, m, remapType tmenv ty) + Expr.Quote (remapExpr g compgen tmenv a, {contents=Some(typeDefs, remapTypesAux tmenv argTypes, remapExprs g compgen tmenv argExprs, data)}, isFromQueryExpression, m, remapType tmenv ty) | Expr.Quote (a, {contents=None}, isFromQueryExpression, m, ty) -> Expr.Quote (remapExpr g (fixValCopyFlagForQuotations compgen) tmenv a, {contents=None}, isFromQueryExpression, m, remapType tmenv ty) @@ -5036,7 +5036,7 @@ and remapLinearExpr g compgen tmenv expr contf = // tailcall for the linear position remapLinearExpr g compgen tmenvinner bodyExpr (contf << mkLetBind m bind') - | Expr.Sequential (expr1, expr2, dir, spSeq, m) -> + | Expr.Sequential (expr1, expr2, dir, spSeq, m) -> let expr1' = remapExpr g compgen tmenv expr1 // tailcall for the linear position remapLinearExpr g compgen tmenv expr2 (contf << (fun expr2' -> @@ -5093,7 +5093,7 @@ and remapOp tmenv op = TOp.ILCall (isVirtCall, isProtectedCall, valu, isNewObjCall, remapValFlags tmenv valUseFlags, isProperty, noTailCall, ilMethRef, remapTypes tmenv enclTypeArgs, remapTypes tmenv methTypeArgs, remapTypes tmenv tys) - | _ -> op + | _ -> op and remapValFlags tmenv x = match x with @@ -5111,7 +5111,7 @@ and remapDecisionTree g compgen tmenv x = List.map (fun (TCase(test, y)) -> let test' = match test with - | DecisionTreeTest.UnionCase (uc, tinst) -> DecisionTreeTest.UnionCase(remapUnionCaseRef tmenv.tyconRefRemap uc, remapTypes tmenv tinst) + | DecisionTreeTest.UnionCase (uc, tinst) -> DecisionTreeTest.UnionCase(remapUnionCaseRef tmenv.tyconRefRemap uc, remapTypes tmenv tinst) | DecisionTreeTest.ArrayLength (n, ty) -> DecisionTreeTest.ArrayLength(n, remapType tmenv ty) | DecisionTreeTest.Const _ -> test | DecisionTreeTest.IsInst (srcty, tgty) -> DecisionTreeTest.IsInst (remapType tmenv srcty, remapType tmenv tgty) @@ -5129,7 +5129,7 @@ and remapDecisionTree g compgen tmenv x = 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 + remapAndRenameBind g compgen tmenv bind v', tmenv and copyAndRemapAndBindBindings g compgen tmenv binds = let vs', tmenvinner = copyAndRemapAndBindVals g compgen tmenv (valsOfBinds binds) @@ -5138,7 +5138,7 @@ and copyAndRemapAndBindBindings g compgen tmenv binds = and remapAndRenameBinds g compgen tmenvinner binds vs' = List.map2 (remapAndRenameBind g compgen tmenvinner) binds vs' and remapAndRenameBind g compgen tmenvinner (TBind(_, repr, letSeqPtOpt)) v' = TBind(v', remapExpr g compgen tmenvinner repr, letSeqPtOpt) -and remapMethod g compgen tmenv (TObjExprMethod(slotsig, attribs, tps, vs, e, m)) = +and remapMethod g compgen tmenv (TObjExprMethod(slotsig, attribs, tps, vs, e, m)) = let attribs2 = attribs |> remapAttribs g tmenv let slotsig2 = remapSlotSig (remapAttribs g tmenv) tmenv slotsig let tps2, tmenvinner = tmenvCopyRemapAndBindTypars (remapAttribs g tmenv) tmenv tps @@ -5146,12 +5146,12 @@ and remapMethod g compgen tmenv (TObjExprMethod(slotsig, attribs, tps, vs, e, m) let e2 = remapExpr g compgen tmenvinner2 e TObjExprMethod(slotsig2, attribs2, tps2, vs2, e2, m) -and remapInterfaceImpl g compgen tmenv (ty, overrides) = +and remapInterfaceImpl g compgen tmenv (ty, overrides) = (remapType tmenv ty, List.map (remapMethod g compgen tmenv) overrides) and remapRecdField g tmenv x = { x with - rfield_type = x.rfield_type |> remapPossibleForallTy g tmenv + rfield_type = x.rfield_type |> remapPossibleForallTy g tmenv rfield_pattribs = x.rfield_pattribs |> remapAttribs g tmenv rfield_fattribs = x.rfield_fattribs |> remapAttribs g tmenv } @@ -5161,7 +5161,7 @@ and remapRecdFields g tmenv (x: TyconRecdFields) = and remapUnionCase g tmenv (x: UnionCase) = { x with FieldTable = x.FieldTable |> remapRecdFields g tmenv - ReturnType = x.ReturnType |> remapType tmenv + ReturnType = x.ReturnType |> remapType tmenv Attribs = x.Attribs |> remapAttribs g tmenv } and remapUnionCases g tmenv (x: TyconUnionData) = @@ -5173,7 +5173,7 @@ and remapFsObjData g tmenv x = (match x.fsobjmodel_kind with | TTyconDelegate slotsig -> TTyconDelegate (remapSlotSig (remapAttribs g tmenv) tmenv slotsig) | TTyconClass | TTyconInterface | TTyconStruct | TTyconEnum -> x.fsobjmodel_kind) - fsobjmodel_vslots = x.fsobjmodel_vslots |> List.map (remapValRef tmenv) + fsobjmodel_vslots = x.fsobjmodel_vslots |> List.map (remapValRef tmenv) fsobjmodel_rfields = x.fsobjmodel_rfields |> remapRecdFields g tmenv } @@ -5188,7 +5188,7 @@ and remapTyconRepr g tmenv repr = | TProvidedTypeExtensionPoint info -> TProvidedTypeExtensionPoint { info with - LazyBaseType = info.LazyBaseType.Force (range0, g.obj_ty) |> remapType tmenv |> LazyWithContext.NotLazy + LazyBaseType = info.LazyBaseType.Force (range0, g.obj_ty) |> remapType tmenv |> LazyWithContext.NotLazy // The load context for the provided type contains TyconRef objects. We must remap these. // This is actually done on-demand (see the implementation of ProvidedTypeContext) ProvidedType = @@ -5202,20 +5202,20 @@ and remapTyconRepr g tmenv repr = and remapTyconAug tmenv (x: TyconAugmentation) = { x with - tcaug_equals = x.tcaug_equals |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) - tcaug_compare = x.tcaug_compare |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) - tcaug_compare_withc = x.tcaug_compare_withc |> Option.map(remapValRef tmenv) - tcaug_hash_and_equals_withc = x.tcaug_hash_and_equals_withc |> Option.map (mapTriple (remapValRef tmenv, remapValRef tmenv, remapValRef tmenv)) - tcaug_adhoc = x.tcaug_adhoc |> NameMap.map (List.map (remapValRef tmenv)) - tcaug_adhoc_list = x.tcaug_adhoc_list |> ResizeArray.map (fun (flag, vref) -> (flag, remapValRef tmenv vref)) - tcaug_super = x.tcaug_super |> Option.map (remapType tmenv) - tcaug_interfaces = x.tcaug_interfaces |> List.map (map1Of3 (remapType tmenv)) } + tcaug_equals = x.tcaug_equals |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) + tcaug_compare = x.tcaug_compare |> Option.map (mapPair (remapValRef tmenv, remapValRef tmenv)) + tcaug_compare_withc = x.tcaug_compare_withc |> Option.map(remapValRef tmenv) + tcaug_hash_and_equals_withc = x.tcaug_hash_and_equals_withc |> Option.map (mapTriple (remapValRef tmenv, remapValRef tmenv, remapValRef tmenv)) + tcaug_adhoc = x.tcaug_adhoc |> NameMap.map (List.map (remapValRef tmenv)) + tcaug_adhoc_list = x.tcaug_adhoc_list |> ResizeArray.map (fun (flag, vref) -> (flag, remapValRef tmenv vref)) + tcaug_super = x.tcaug_super |> Option.map (remapType tmenv) + tcaug_interfaces = x.tcaug_interfaces |> List.map (map1Of3 (remapType tmenv)) } and remapTyconExnInfo g tmenv inp = match inp with | TExnAbbrevRepr x -> TExnAbbrevRepr (remapTyconRef tmenv.tyconRefRemap x) - | TExnFresh x -> TExnFresh (remapRecdFields g tmenv x) - | TExnAsmRepr _ | TExnNone -> inp + | TExnFresh x -> TExnFresh (remapRecdFields g tmenv x) + | TExnAsmRepr _ | TExnNone -> inp and remapMemberInfo g m topValInfo ty ty' tmenv x = // The slotsig in the ImplementedSlotSigs is w.r.t. the type variables in the value's type. @@ -5226,7 +5226,7 @@ and remapMemberInfo g m topValInfo ty ty' tmenv x = let renaming, _ = mkTyparToTyparRenaming tpsOrig tps let tmenv = { tmenv with tpinst = tmenv.tpinst @ renaming } { x with - ApparentEnclosingEntity = x.ApparentEnclosingEntity |> remapTyconRef tmenv.tyconRefRemap + ApparentEnclosingEntity = x.ApparentEnclosingEntity |> remapTyconRef tmenv.tyconRefRemap ImplementedSlotSigs = x.ImplementedSlotSigs |> List.map (remapSlotSig (remapAttribs g tmenv) tmenv) } @@ -5257,7 +5257,7 @@ and renameVal tmenv x = and copyTycon compgen (tycon: Tycon) = match compgen with | OnlyCloneExprVals -> tycon - | _ -> NewClonedTycon tycon + | _ -> NewClonedTycon tycon /// This operates over a whole nested collection of tycons and vals simultaneously *) and copyAndRemapAndBindTyconsAndVals g compgen tmenv tycons vs = @@ -5293,14 +5293,14 @@ and copyAndRemapAndBindTyconsAndVals g compgen tmenv tycons vs = (tycons, tycons') ||> List.iter2 (fun tcd tcd' -> let tps', tmenvinner2 = tmenvCopyRemapAndBindTypars (remapAttribs g tmenvinner) tmenvinner (tcd.entity_typars.Force(tcd.entity_range)) - tcd'.entity_typars <- LazyWithContext.NotLazy tps' - tcd'.entity_attribs <- tcd.entity_attribs |> remapAttribs g tmenvinner2 - tcd'.entity_tycon_repr <- tcd.entity_tycon_repr |> remapTyconRepr g tmenvinner2 - let typeAbbrevR = tcd.TypeAbbrev |> Option.map (remapType tmenvinner2) - tcd'.entity_tycon_tcaug <- tcd.entity_tycon_tcaug |> remapTyconAug tmenvinner2 + tcd'.entity_typars <- LazyWithContext.NotLazy tps' + tcd'.entity_attribs <- tcd.entity_attribs |> remapAttribs g tmenvinner2 + tcd'.entity_tycon_repr <- tcd.entity_tycon_repr |> remapTyconRepr g tmenvinner2 + let typeAbbrevR = tcd.TypeAbbrev |> Option.map (remapType tmenvinner2) + tcd'.entity_tycon_tcaug <- tcd.entity_tycon_tcaug |> remapTyconAug tmenvinner2 tcd'.entity_modul_contents <- MaybeLazy.Strict (tcd.entity_modul_contents.Value |> mapImmediateValsAndTycons lookupTycon lookupVal) - let exnInfoR = tcd.ExceptionInfo |> remapTyconExnInfo g tmenvinner2 + let exnInfoR = tcd.ExceptionInfo |> remapTyconExnInfo g tmenvinner2 match tcd'.entity_opt_data with | Some optData -> tcd'.entity_opt_data <- Some { optData with entity_tycon_abbrev = typeAbbrevR; entity_exn_info = exnInfoR } | _ -> @@ -5325,9 +5325,9 @@ and allEntitiesOfModDef mdef = | ModuleOrNamespaceBinding.Module(mspec, def) -> yield mspec yield! allEntitiesOfModDef def - | TMDefLet _ -> () - | TMDefDo _ -> () - | TMDefs defs -> + | TMDefLet _ -> () + | TMDefDo _ -> () + | TMDefs defs -> for def in defs do yield! allEntitiesOfModDef def | TMAbstract(ModuleOrNamespaceExprWithSig(mty, _, _)) -> @@ -5341,10 +5341,10 @@ and allValsOfModDef mdef = match mbind with | ModuleOrNamespaceBinding.Binding bind -> yield bind.Var | ModuleOrNamespaceBinding.Module(_, def) -> yield! allValsOfModDef def - | TMDefLet(bind, _) -> + | TMDefLet(bind, _) -> yield bind.Var - | TMDefDo _ -> () - | TMDefs defs -> + | TMDefDo _ -> () + | TMDefs defs -> for def in defs do yield! allValsOfModDef def | TMAbstract(ModuleOrNamespaceExprWithSig(mty, _, _)) -> @@ -5395,7 +5395,7 @@ and remapAndRenameModBind g compgen tmenv x = | ModuleOrNamespaceBinding.Binding bind -> let v2 = bind |> valOfBind |> renameVal tmenv let bind2 = remapAndRenameBind g compgen tmenv bind v2 - ModuleOrNamespaceBinding.Binding bind2 + ModuleOrNamespaceBinding.Binding bind2 | ModuleOrNamespaceBinding.Module(mspec, def) -> let mspec = renameTycon tmenv mspec let def = remapAndRenameModDef g compgen tmenv def @@ -5419,7 +5419,7 @@ let instExpr g tpinst e = remapExpr g CloneAll (mkInstRemap tpinst) e let rec remarkExpr m x = match x with - | Expr.Lambda (uniq, ctorThisValOpt, baseValOpt, vs, b, _, rty) -> + | Expr.Lambda (uniq, ctorThisValOpt, baseValOpt, vs, b, _, rty) -> Expr.Lambda (uniq, ctorThisValOpt, baseValOpt, vs, remarkExpr m b, m, rty) | Expr.TyLambda (uniq, tps, b, _, rty) -> @@ -5465,7 +5465,7 @@ let rec remarkExpr m x = | Expr.App(e1, e1ty, tyargs, args, _) -> Expr.App(remarkExpr m e1, e1ty, tyargs, remarkExprs m args, m) - | Expr.Sequential (e1, e2, dir, _, _) -> + | Expr.Sequential (e1, e2, dir, _, _) -> Expr.Sequential (remarkExpr m e1, remarkExpr m e2, dir, SuppressSequencePointOnExprOfSequential, m) | Expr.StaticOptimization (eqns, e2, e3, _) -> @@ -5523,14 +5523,14 @@ 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 +// each raised object. Hence we treat exception objects as if they have identity 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 // code until the construction of the entire return list has been completed. // 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 +// 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 = (g.compilingFslib && tyconRefEq g ucref.TyconRef g.list_tcr_canon && n = 1) || @@ -5553,11 +5553,11 @@ let ComputeFieldName tycon f = let isQuotedExprTy g ty = match tryAppTy g ty with ValueSome (tcref, _) -> tyconRefEq g tcref g.expr_tcr | _ -> false -let destQuotedExprTy g ty = match tryAppTy g ty with ValueSome (_, [ty]) -> ty | _ -> failwith "destQuotedExprTy" +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 = match tys with @@ -5588,9 +5588,9 @@ let rec tyOfExpr g e = | Expr.Obj (_, ty, _, _, _, _, _) | Expr.Match (_, _, _, _, _, ty) | Expr.Quote(_, _, _, _, ty) - | Expr.Const(_, _, ty) -> (ty) - | Expr.Val(vref, _, _) -> vref.Type - | Expr.Sequential(a, b, k, _, _) -> tyOfExpr g (match k with NormalSeq -> b | ThenDoSeq -> a) + | Expr.Const(_, _, ty) -> (ty) + | Expr.Val(vref, _, _) -> vref.Type + | Expr.Sequential(a, b, k, _, _) -> tyOfExpr g (match k with NormalSeq -> b | ThenDoSeq -> a) | Expr.Lambda(_, _, _, vs, _, _, rty) -> (mkRefTupledVarsTy g vs --> rty) | Expr.TyLambda(_, tyvs, _, _, rty) -> (tyvs +-> rty) | Expr.Let(_, e, _, _) @@ -5614,7 +5614,7 @@ let rec tyOfExpr g e = | TOp.AnonRecd anonInfo -> mkAnyAnonRecdTy g anonInfo tinst | (TOp.For _ | TOp.While _) -> g.unit_ty | TOp.Array -> (match tinst with [ty] -> mkArrayType g ty | _ -> failwith "bad TOp.Array node") - | (TOp.TryCatch _ | TOp.TryFinally _) -> (match tinst with [ty] -> ty | _ -> failwith "bad TOp_try node") + | (TOp.TryCatch _ | TOp.TryFinally _) -> (match tinst with [ty] -> ty | _ -> failwith "bad TOp_try node") | TOp.ValFieldGetAddr(fref, readonly) -> mkByrefTyWithFlag g readonly (actualTyOfRecdFieldRef fref tinst) | TOp.ValFieldGet(fref) -> actualTyOfRecdFieldRef fref tinst | (TOp.ValFieldSet _ | TOp.UnionCaseFieldSet _ | TOp.ExnFieldSet _ | TOp.LValueOp ((LSet | LByrefSet), _)) ->g.unit_ty @@ -5761,7 +5761,7 @@ let foldLinearBindingTargetsOfMatch tree (targets: _[]) = else let branchesToTargets = Array.create targets.Length [] // Build a map showing how each target might be reached - let rec accumulateTipsOfDecisionTree accBinds tree = + let rec accumulateTipsOfDecisionTree accBinds tree = match tree with | TDSwitch (_, cases, dflt, _) -> assert (isNil accBinds) // No switches under bindings @@ -5802,9 +5802,9 @@ let foldLinearBindingTargetsOfMatch tree (targets: _[]) = and rebuildDecisionTreeEdge (TCase(x, t)) = TCase(x, rebuildDecisionTree t) - let tree' = rebuildDecisionTree tree + let tree' = rebuildDecisionTree tree - /// rebuild the targets , replacing linear targets by ones that include all the 'let' bindings from the source + /// rebuild the targets, replacing linear targets by ones that include all the 'let' bindings from the source let targets' = targets |> Array.mapi (fun i (TTarget(vs, exprTarget, spTarget) as tg) -> if isLinearTgtIdx i then @@ -5833,7 +5833,7 @@ let rec simplifyTrivialMatch spBind exprm matchm ty tree (targets : _[]) = primMkMatch (spBind, exprm, tree, targets, matchm, ty) // Simplify a little as we go, including dead target elimination -let mkAndSimplifyMatch spBind exprm matchm ty tree targets = +let mkAndSimplifyMatch spBind exprm matchm ty tree targets = let targets = Array.ofList targets match tree with | TDSuccess _ -> @@ -5881,7 +5881,7 @@ let CanTakeAddressOf g m ty mut = // We can take the address of values of struct type even if the value is immutable // under certain conditions -// - all instances of the type are known to be immutable; OR +// - all instances of the type are known to be immutable; OR // - the operation is known not to mutate // // Note this may be taking the address of a closure field, i.e. a copy @@ -5922,7 +5922,7 @@ let MustTakeAddressOfRecdField (rfref: RecdField) = not rfref.IsStatic && rfref.IsMutable -let MustTakeAddressOfRecdFieldRef (rfref: RecdFieldRef) = MustTakeAddressOfRecdField rfref.RecdField +let MustTakeAddressOfRecdFieldRef (rfref: RecdFieldRef) = MustTakeAddressOfRecdField rfref.RecdField 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 @@ -6002,7 +6002,7 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress let readonly = false // array address is never forced to be readonly let writeonly = false let shape = ILArrayShape.SingleDimensional - let ilInstrReadOnlyAnnotation = if isTyparTy g elemTy && useReadonlyForGenericArrayAddress then ReadonlyAddress else NormalAddress + let ilInstrReadOnlyAnnotation = if isTyparTy g elemTy && useReadonlyForGenericArrayAddress then ReadonlyAddress else NormalAddress let isNativePtr = match addrExprVal with | Some(vf) -> valRefEq g vf g.addrof2_vref @@ -6016,17 +6016,17 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress let readonly = false // array address is never forced to be readonly let writeonly = false let shape = ILArrayShape.FromRank args.Length - let ilInstrReadOnlyAnnotation = if isTyparTy g elemTy && useReadonlyForGenericArrayAddress then ReadonlyAddress else NormalAddress + let ilInstrReadOnlyAnnotation = if isTyparTy g elemTy && useReadonlyForGenericArrayAddress then ReadonlyAddress else NormalAddress let isNativePtr = match addrExprVal with | 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]". + // 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), _, _, _), _, _) - when (valRefEq g (mkLocalValRef vref) vref2) && + when (valRefEq g (mkLocalValRef vref) vref2) && (MustTakeAddressOfByrefGet g vref2 || CanTakeAddressOfByrefGet g vref2 mut) -> let ty = tyOfExpr g e let readonly = isInByrefTy g ty @@ -6111,7 +6111,7 @@ let mkArray (argty, args, m) = Expr.Op(TOp.Array, [argty], args, m) // Compute fixups for letrec's. // // Generate an assignment expression that will fixup the recursion -// amongst the vals on the r.h.s. of a letrec. The returned expressions +// amongst the vals on the r.h.s. of a letrec. The returned expressions // include disorderly constructs such as expressions/statements // to set closure environments and non-mutable fields. These are only ever // generated by the backend code-generator when processing a "letrec" @@ -6127,8 +6127,8 @@ 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 exprToFix = stripExpr exprToFix +let rec IterateRecursiveFixups g (selfv: Val option) rvs ((access: Expr), set) exprToFix = + let exprToFix = stripExpr exprToFix match exprToFix with | Expr.Const _ -> () | Expr.Op (TOp.Tuple tupInfo, argtys, args, m) when not (evalTupInfoIsStruct tupInfo) -> @@ -6183,24 +6183,24 @@ let JoinTyparStaticReq r1 r2 = //------------------------------------------------------------------------- type ExprFolder<'State> = - { exprIntercept : (* recurseF *) ('State -> Expr -> 'State) -> (* noInterceptF *) ('State -> Expr -> 'State) -> 'State -> Expr -> 'State + { exprIntercept : (* recurseF *) ('State -> Expr -> 'State) -> (* noInterceptF *) ('State -> Expr -> 'State) -> 'State -> Expr -> 'State // the bool is 'bound in dtree' - valBindingSiteIntercept : 'State -> bool * Val -> 'State + valBindingSiteIntercept : 'State -> bool * Val -> 'State // these values are always bound to these expressions. bool indicates 'recursively' - nonRecBindingsIntercept : 'State -> Binding -> 'State - recBindingsIntercept : 'State -> Bindings -> 'State - dtreeIntercept : 'State -> DecisionTree -> 'State - targetIntercept : (* recurseF *) ('State -> Expr -> 'State) -> 'State -> DecisionTreeTarget -> 'State option + nonRecBindingsIntercept : 'State -> Binding -> 'State + recBindingsIntercept : 'State -> Bindings -> 'State + dtreeIntercept : 'State -> DecisionTree -> 'State + targetIntercept : (* recurseF *) ('State -> Expr -> 'State) -> 'State -> DecisionTreeTarget -> 'State option tmethodIntercept : (* recurseF *) ('State -> Expr -> 'State) -> 'State -> ObjExprMethod -> 'State option } let ExprFolder0 = - { exprIntercept = (fun _recurseF noInterceptF z x -> noInterceptF z x) - valBindingSiteIntercept = (fun z _b -> z) - nonRecBindingsIntercept = (fun z _bs -> z) - recBindingsIntercept = (fun z _bs -> z) - dtreeIntercept = (fun z _dt -> z) - targetIntercept = (fun _exprF _z _x -> None) + { exprIntercept = (fun _recurseF noInterceptF z x -> noInterceptF z x) + valBindingSiteIntercept = (fun z _b -> z) + nonRecBindingsIntercept = (fun z _bs -> z) + recBindingsIntercept = (fun z _bs -> z) + dtreeIntercept = (fun z _dt -> z) + targetIntercept = (fun _exprF _z _x -> None) tmethodIntercept = (fun _exprF _z _x -> None) } //------------------------------------------------------------------------- @@ -6223,7 +6223,7 @@ type ExprFolders<'State> (folders: ExprFolder<'State>) = and exprNoInterceptF (z: 'State) (x: Expr) = match x with - | Expr.Const _ -> z + | Expr.Const _ -> z | Expr.Val _ -> z @@ -6235,11 +6235,11 @@ type ExprFolders<'State> (folders: ExprFolder<'State>) = | Expr.Op (_c, _tyargs, args, _) -> exprsF z args - | Expr.Sequential (x0, x1, _dir, _, _) -> + | Expr.Sequential (x0, x1, _dir, _, _) -> let z = exprF z x0 exprF z x1 - | Expr.Lambda(_lambdaId , _ctorThisValOpt, _baseValOpt, _argvs, body, _m, _rty) -> + | Expr.Lambda(_lambdaId, _ctorThisValOpt, _baseValOpt, _argvs, body, _m, _rty) -> exprF z body | Expr.TyLambda(_lambdaId, _argtyvs, body, _m, _rty) -> @@ -6256,26 +6256,26 @@ type ExprFolders<'State> (folders: ExprFolder<'State>) = let z = valBindsF false z binds exprF z body - | Expr.Let (bind, body, _, _) -> + | Expr.Let (bind, body, _, _) -> let z = valBindF false z bind exprF z body | Expr.Link rX -> exprF z (!rX) - | Expr.Match (_spBind, _exprm, dtree, targets, _m, _ty) -> + | Expr.Match (_spBind, _exprm, dtree, targets, _m, _ty) -> let z = dtreeF z dtree let z = Array.fold targetF z targets.[0..targets.Length - 2] // tailcall targetF z targets.[targets.Length - 1] - | Expr.Quote(e, {contents=Some(_typeDefs, _argTypes, argExprs, _)}, _, _, _) -> + | Expr.Quote(e, {contents=Some(_typeDefs, _argTypes, argExprs, _)}, _, _, _) -> let z = exprF z e exprsF z argExprs | Expr.Quote(e, {contents=None}, _, _m, _) -> exprF z e - | Expr.Obj (_n, _typ, _basev, basecall, overrides, iimpls, _m) -> + | Expr.Obj (_n, _typ, _basev, basecall, overrides, iimpls, _m) -> let z = exprF z basecall let z = List.fold tmethodF z overrides List.fold (foldOn snd (List.fold tmethodF)) z iimpls @@ -6298,10 +6298,10 @@ type ExprFolders<'State> (folders: ExprFolder<'State>) = and dtreeF z dtree = let z = folders.dtreeIntercept z dtree match dtree with - | TDBind (bind, rest) -> + | TDBind (bind, rest) -> let z = valBindF true z bind dtreeF z rest - | TDSuccess (args, _) -> exprsF z args + | TDSuccess (args, _) -> exprsF z args | TDSwitch (test, dcases, dflt, _) -> let z = exprF z test let z = List.fold dcaseF z dcases @@ -6309,7 +6309,7 @@ type ExprFolders<'State> (folders: ExprFolder<'State>) = z and dcaseF z = function - TCase (_, dtree) -> dtreeF z dtree (* not collecting from test *) + TCase (_, dtree) -> dtreeF z dtree (* not collecting from test *) and targetF z x = match folders.targetIntercept exprFClosure z x with @@ -6349,10 +6349,12 @@ type ExprFolders<'State> (folders: ExprFolder<'State>) = do exprFClosure <- exprF // allocate one instance of this closure do exprNoInterceptFClosure <- exprNoInterceptF // allocate one instance of this closure + member x.FoldExpr = exprF + member x.FoldImplFile = implF -let FoldExpr folders state expr = ExprFolders(folders).FoldExpr state expr +let FoldExpr folders state expr = ExprFolders(folders).FoldExpr state expr let FoldImplFile folders state implFile = ExprFolders(folders).FoldImplFile state implFile @@ -6369,7 +6371,7 @@ let ExprStats x = #endif //------------------------------------------------------------------------- -// +// Make expressions //------------------------------------------------------------------------- let mkString (g: TcGlobals) m n = Expr.Const(Const.String n, m, g.string_ty) @@ -6386,17 +6388,17 @@ let mkFalse g m = mkBool g m false 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) +let mkInt g m n = mkInt32 g m (n) -let mkZero g m = mkInt g m 0 +let mkZero g m = mkInt g m 0 -let mkOne g m = mkInt g m 1 +let mkOne g m = mkInt g m 1 -let mkTwo g m = mkInt g m 2 +let mkTwo g m = mkInt g m 2 -let mkMinusOne g m = mkInt g m (-1) +let mkMinusOne g m = mkInt g m (-1) let destInt32 = function Expr.Const(Const.Int32 n, _, _) -> Some n | _ -> None @@ -6405,7 +6407,7 @@ let isIDelegateEventType g ty = | ValueSome tcref -> tyconRefEq g g.fslib_IDelegateEvent_tcr tcref | _ -> false -let destIDelegateEventType g ty = +let destIDelegateEventType g ty = if isIDelegateEventType g ty then match argsOfAppTy g ty with | [ty1] -> ty1 @@ -6472,14 +6474,14 @@ let rec existsR a b pred = if a<=b then pred a || existsR (a+1) b pred else fals // Given a permutation for record fields, work out the highest entry that we must lift out // of a record initialization. Lift out xi if xi goes to position that will be preceded by an expr with an effect -// that originally followed xi. If one entry gets lifted then everything before it also gets lifted. +// that originally followed xi. If one entry gets lifted then everything before it also gets lifted. let liftAllBefore sigma = let invSigma = inversePerm sigma let lifted = [ for i in 0 .. sigma.Length - 1 do let i' = sigma.[i] - if existsR 0 (i' - 1) (fun j' -> invSigma.[j'] > i) then + if existsR 0 (i' - 1) (fun j' -> invSigma.[j'] > i) then yield i ] if lifted.IsEmpty then 0 else List.max lifted + 1 @@ -6502,12 +6504,12 @@ let permuteExprList (sigma: int[]) (exprs: Expr list) (ty: TType list) (names: s let newExprs, reversedBinds = List.mapFold rewrite [] (exprs |> List.indexed) let binds = List.rev reversedBinds - let reorderedExprs = permute sigma (Array.ofList newExprs) + let reorderedExprs = permute sigma (Array.ofList newExprs) binds, Array.toList reorderedExprs /// Evaluate the expressions in the original order, but build a record with the results in field order /// Note some fields may be static. If this were not the case we could just use -/// let sigma = Array.map #Index () +/// 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) = @@ -6519,19 +6521,18 @@ let mkRecordExpr g (lnk, tcref, tinst, rfrefs: RecdFieldRef list, args, m) = let sigma = Array.create rfrefsArray.Length -1 Array.iteri (fun j (i, _) -> if sigma.[i] <> -1 then error(InternalError("bad permutation", m)) - sigma.[i] <- j) rfrefsArray + sigma.[i] <- j) rfrefsArray - let argTys = List.map (fun rfref -> actualTyOfRecdFieldRef rfref tinst) rfrefs + let argTys = List.map (fun rfref -> actualTyOfRecdFieldRef rfref tinst) rfrefs let names = rfrefs |> List.map (fun rfref -> rfref.FieldName) - let binds, args = permuteExprList sigma args argTys names + let binds, args = permuteExprList sigma args argTys names mkLetsBind m binds (Expr.Op (TOp.Recd(lnk, tcref), tinst, args, m)) - //------------------------------------------------------------------------- // List builders //------------------------------------------------------------------------- -let mkRefCell g m ty e = mkRecordExpr g (RecdExpr, g.refcell_tcr_canon, [ty], [mkRefCellContentsRef g], [e], m) +let mkRefCell g m ty e = mkRecordExpr g (RecdExpr, g.refcell_tcr_canon, [ty], [mkRefCellContentsRef g], [e], m) let mkRefCellGet g m ty e = mkRecdFieldGetViaExprAddr (e, mkRefCellContentsRef g, [ty], m) @@ -6583,7 +6584,7 @@ let mkInitializeArrayMethSpec (g: TcGlobals) = let tref = g.FindSysILTypeRef "System.Runtime.CompilerServices.RuntimeHelpers" mkILNonGenericStaticMethSpecInTy(mkILNonGenericBoxedTy tref, "InitializeArray", [g.ilg.typ_Array;g.iltyp_RuntimeFieldHandle], ILType.Void) -let mkInvalidCastExnNewobj (g: TcGlobals) = +let mkInvalidCastExnNewobj (g: TcGlobals) = mkNormalNewobj (mkILCtorMethSpecForTy (mkILNonGenericBoxedTy (g.FindSysILTypeRef "System.InvalidCastException"), [])) @@ -6794,7 +6795,7 @@ let mkCallSeqFinally g m elemTy arg1 arg2 = mkApps g (typedExprForIntrinsic g m g.seq_finally_info, [[elemTy]], [ arg1; arg2 ], m) let mkCallSeqOfFunctions g m ty1 ty2 arg1 arg2 arg3 = - mkApps g (typedExprForIntrinsic g m g.seq_of_functions_info, [[ty1;ty2]], [ arg1; arg2; arg3 ], m) + mkApps g (typedExprForIntrinsic g m g.seq_of_functions_info, [[ty1;ty2]], [ arg1; arg2; arg3 ], m) let mkCallSeqToArray g m elemTy arg1 = mkApps g (typedExprForIntrinsic g m g.seq_to_array_info, [[elemTy]], [ arg1 ], m) @@ -6827,9 +6828,9 @@ let mkCallLiftValueWithName (g: TcGlobals) m ty nm e1 = // Use "Expr.ValueWithName" if it exists in FSharp.Core match vref.TryDeref with | ValueSome _ -> - mkApps g (typedExprForIntrinsic g m g.lift_value_with_name_info , [[ty]], [mkRefTupledNoTypes g m [e1; mkString g m nm]], m) + mkApps g (typedExprForIntrinsic g m g.lift_value_with_name_info, [[ty]], [mkRefTupledNoTypes g m [e1; mkString g m nm]], m) | ValueNone -> - mkApps g (typedExprForIntrinsic g m g.lift_value_info , [[ty]], [e1], m) + mkApps g (typedExprForIntrinsic g m g.lift_value_info, [[ty]], [e1], m) let mkCallLiftValueWithDefn g m qty e1 = assert isQuotedExprTy g qty @@ -6840,7 +6841,7 @@ let mkCallLiftValueWithDefn g m qty e1 = | ValueSome _ -> let copyOfExpr = copyExpr g ValCopyFlag.CloneAll e1 let quoteOfCopyOfExpr = Expr.Quote(copyOfExpr, ref None, false, m, qty) - mkApps g (typedExprForIntrinsic g m g.lift_value_with_defn_info , [[ty]], [mkRefTupledNoTypes g m [e1; quoteOfCopyOfExpr]], m) + mkApps g (typedExprForIntrinsic g m g.lift_value_with_defn_info, [[ty]], [mkRefTupledNoTypes g m [e1; quoteOfCopyOfExpr]], m) | ValueNone -> Expr.Quote(e1, ref None, false, m, qty) @@ -6848,13 +6849,13 @@ let mkCallCheckThis g m ty e1 = mkApps g (typedExprForIntrinsic g m g.check_this_info, [[ty]], [e1], m) let mkCallFailInit g m = - mkApps g (typedExprForIntrinsic g m g.fail_init_info , [], [mkUnit g m], m) + mkApps g (typedExprForIntrinsic g m g.fail_init_info, [], [mkUnit g m], m) let mkCallFailStaticInit g m = - mkApps g (typedExprForIntrinsic g m g.fail_static_init_info , [], [mkUnit g m], m) + mkApps g (typedExprForIntrinsic g m g.fail_static_init_info, [], [mkUnit g m], m) let mkCallQuoteToLinqLambdaExpression g m ty e1 = - mkApps g (typedExprForIntrinsic g m g.quote_to_linq_lambda_info , [[ty]], [e1], m) + mkApps g (typedExprForIntrinsic g m g.quote_to_linq_lambda_info, [[ty]], [e1], m) let mkLazyDelayed g m ty f = mkApps g (typedExprForIntrinsic g m g.lazy_create_info, [[ty]], [ f ], m) @@ -6891,9 +6892,9 @@ 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 @@ -6908,9 +6909,9 @@ let mkLdelem (_g: TcGlobals) m ty arre idxe = mkAsmExpr ([ IL.I_ldelem_any (ILAr // 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. @@ -6933,15 +6934,15 @@ let mkReraise m returnTy = Expr.Op (TOp.Reraise, [returnTy], [], m) (* could sup // CompilationMappingAttribute, SourceConstructFlags //---------------------------------------------------------------------------- -let tnameCompilationSourceNameAttr = FSharpLib.Core + ".CompilationSourceNameAttribute" +let tnameCompilationSourceNameAttr = FSharpLib.Core + ".CompilationSourceNameAttribute" let tnameCompilationArgumentCountsAttr = FSharpLib.Core + ".CompilationArgumentCountsAttribute" -let tnameCompilationMappingAttr = FSharpLib.Core + ".CompilationMappingAttribute" -let tnameSourceConstructFlags = FSharpLib.Core + ".SourceConstructFlags" +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_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 = mkILCustomAttribute g.ilg (tref_CompilationMappingAttr g, @@ -6961,7 +6962,7 @@ let mkCompilationArgumentCountsAttr (g: TcGlobals) nums = []) let mkCompilationSourceNameAttr (g: TcGlobals) n = - mkILCustomAttribute g.ilg (tref_CompilationSourceNameAttr g, [ g.ilg.typ_String ], + mkILCustomAttribute g.ilg (tref_CompilationSourceNameAttr g, [ g.ilg.typ_String ], [ILAttribElem.String(Some n)], []) @@ -7003,7 +7004,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], @@ -7018,8 +7019,8 @@ let IsSignatureDataVersionAttr cattr = isILAttribByName ([], tname_SignatureData let TryFindAutoOpenAttr (ilg: IL.ILGlobals) cattr = if isILAttribByName ([], tname_AutoOpenAttr) cattr then match decodeILAttribData ilg cattr with - | [ILAttribElem.String s], _ -> s - | [], _ -> None + | [ILAttribElem.String s], _ -> s + | [], _ -> None | _ -> warning(Failure(FSComp.SR.tastUnexpectedDecodeOfAutoOpenAttribute())) None @@ -7031,18 +7032,18 @@ let tname_InternalsVisibleToAttr = "System.Runtime.CompilerServices.InternalsVis let TryFindInternalsVisibleToAttr ilg cattr = if isILAttribByName ([], tname_InternalsVisibleToAttr) cattr then match decodeILAttribData ilg cattr with - | [ILAttribElem.String s], _ -> s - | [], _ -> None + | [ILAttribElem.String s], _ -> s + | [], _ -> None | _ -> warning(Failure(FSComp.SR.tastUnexpectedDecodeOfInternalsVisibleToAttribute())) None else None -let IsMatchingSignatureDataVersionAttr ilg ((v1, v2, v3, _) : ILVersionInfo) cattr = +let IsMatchingSignatureDataVersionAttr ilg ((v1, v2, v3, _) : ILVersionInfo) cattr = IsSignatureDataVersionAttr cattr && match decodeILAttribData ilg cattr with - | [ILAttribElem.Int32 u1; ILAttribElem.Int32 u2;ILAttribElem.Int32 u3 ], _ -> + | [ILAttribElem.Int32 u1; ILAttribElem.Int32 u2;ILAttribElem.Int32 u3 ], _ -> (v1 = uint16 u1) && (v2 = uint16 u2) && (v3 = uint16 u3) | _ -> warning(Failure(FSComp.SR.tastUnexpectedDecodeOfInterfaceDataVersionAttribute())) @@ -7054,7 +7055,7 @@ let mkCompilerGeneratedAttr (g: TcGlobals) n = //-------------------------------------------------------------------------- // tupled lambda --> method/function with a given topValInfo specification. // -// AdjustArityOfLambdaBody: "(vs, body)" represents a lambda "fun (vs) -> body". The +// AdjustArityOfLambdaBody: "(vs, body)" represents a lambda "fun (vs) -> body". The // aim is to produce a "static method" represented by a pair // "(mvs, body)" where mvs has the List.length "arity". //-------------------------------------------------------------------------- @@ -7063,7 +7064,7 @@ let untupledToRefTupled g vs = let untupledTys = typesOfVals vs let m = (List.head vs).Range let tupledv, tuplede = mkCompGenLocal m "tupledArg" (mkRefTupledTy g untupledTys) - let untupling_es = List.mapi (fun i _ -> mkTupleFieldGet g (tupInfoRef, tuplede, untupledTys, i, m)) untupledTys + let untupling_es = List.mapi (fun i _ -> mkTupleFieldGet g (tupInfoRef, tuplede, untupledTys, i, m)) untupledTys // These are non-sticky - at the caller,any sequence point for 'body' goes on 'body' _after_ the binding has been made tupledv, mkInvisibleLets m vs untupling_es @@ -7080,7 +7081,7 @@ let AdjustArityOfLambdaBody g arity (vs: Val list) body = elif nvs = 1 then let v = vs.Head let untupledTys = destRefTupleTy g v.Type - if (untupledTys.Length <> arity) then failwith "length untupledTys <> arity" + if (untupledTys.Length <> arity) then failwith "length untupledTys <> arity" let dummyvs, dummyes = untupledTys |> List.mapi (fun i ty -> mkCompGenLocal v.Range (v.LogicalName + "_" + string i) ty) @@ -7089,7 +7090,7 @@ let AdjustArityOfLambdaBody g arity (vs: Val list) body = let body = mkInvisibleLet v.Range v (mkRefTupled g v.Range dummyes untupledTys) body dummyvs, body else - let tupledv, untupler = untupledToRefTupled g vs + let tupledv, untupler = untupledToRefTupled g vs [tupledv], untupler body let MultiLambdaToTupledLambda g vs body = @@ -7097,7 +7098,7 @@ let MultiLambdaToTupledLambda g vs body = | [] -> failwith "MultiLambdaToTupledLambda: expected some argments" | [v] -> v, body | vs -> - let tupledv, untupler = untupledToRefTupled g vs + let tupledv, untupler = untupledToRefTupled g vs tupledv, untupler body let (|RefTuple|_|) expr = @@ -7110,14 +7111,14 @@ let MultiLambdaToTupledLambdaIfNeeded g (vs, arg) body = | [], _ -> failwith "MultiLambdaToTupledLambda: expected some argments" | [v], _ -> [(v, arg)], body | vs, RefTuple args when args.Length = vs.Length -> List.zip vs args, body - | vs, _ -> - let tupledv, untupler = untupledToRefTupled g vs + | vs, _ -> + let tupledv, untupler = untupledToRefTupled g vs [(tupledv, arg)], untupler body //-------------------------------------------------------------------------- // Beta reduction via let-bindings. Reduce immediate apps. of lambdas to let bindings. // Includes binding the immediate application of generic -// functions. Input type is the type of the function. Makes use of the invariant +// functions. Input type is the type of the function. Makes use of the invariant // that any two expressions have distinct local variables (because we explicitly copy // expressions). //------------------------------------------------------------------------ @@ -7159,7 +7160,7 @@ let rec MakeApplicationAndBetaReduceAux g (f, fty, tyargsl: TType list list, arg // VALID: // (fun a b -> E[a, b]) t1 t2 ---> let a = t1 in let b = t2 in E[t1, t2] // INVALID: - // (fun a -> E[a]) t1 t2 ---> let a = t1 in E[a] t2 UNLESS: E[a] has no effects OR t2 has no effects + // (fun a -> E[a]) t1 t2 ---> let a = t1 in E[a] t2 UNLESS: E[a] has no effects OR t2 has no effects match tryStripLambdaN argsl.Length f with | Some (argvsl, body) -> @@ -7222,7 +7223,7 @@ let stripTupledFunTy g ty = let (|ExprValWithPossibleTypeInst|_|) expr = match expr with - | Expr.App (Expr.Val (vref, flags, m), _fty, tyargs, [], _) -> + | Expr.App (Expr.Val (vref, flags, m), _fty, tyargs, [], _) -> Some (vref, flags, tyargs, m) | Expr.Val (vref, flags, m) -> Some (vref, flags, [], m) @@ -7265,7 +7266,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex match expr with | Expr.Op (TOp.Coerce, [inputTy;actualTy], [exprWithActualTy], m) when - isFunTy g actualTy && isFunTy g inputTy -> + isFunTy g actualTy && isFunTy g inputTy -> if typeEquiv g actualTy inputTy then Some(exprWithActualTy, suppliedArgs) @@ -7344,7 +7345,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex mkRefTupled g appm ((actualTys, argTys) ||> List.mapi2 (fun i actualTy dummyTy -> let argExprElement = mkTupleFieldGet g (tupInfoRef, tupleVar, argTys, i, appm) - mkCoerceIfNeeded g actualTy dummyTy argExprElement)) + mkCoerceIfNeeded g actualTy dummyTy argExprElement)) actualTys /// Given an argument that has a tuple type that satisfies the input argument types, @@ -7352,7 +7353,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex let CoerceTupled niceNames (argExpr: Expr) (actualTys: TType list) = let argExprTy = (tyOfExpr g argExpr) - let argTys = + let argTys = match actualTys with | [_] -> [tyOfExpr g argExpr] @@ -7374,7 +7375,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex let binderBuilder = (fun tm -> mkCompGenLet appm v argExpr tm) let expr = match actualTys, argTys with - | [actualTy], [argTy] -> mkCoerceIfNeeded g actualTy argTy ve + | [actualTy], [argTy] -> mkCoerceIfNeeded g actualTy argTy ve | _ -> CoerceBoundTuple ve argTys actualTys binderBuilder, expr @@ -7383,7 +7384,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex (fun tm -> tm), argExpr else - let detupledArgs, argTys = + let detupledArgs, argTys = match actualTys with | [_actualType] -> [argExpr], [tyOfExpr g argExpr] @@ -7397,7 +7398,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex // for // let f (x, y) = 1 // and we're not building lambdas, just coerce the arguments in place - if detupledArgs.Length = actualTys.Length then + if detupledArgs.Length = actualTys.Length then (fun tm -> tm), CoerceDetupled argTys detupledArgs actualTys else // In this case there is a tuple mismatch. @@ -7429,7 +7430,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex assert (inpArgTys.Length = actualArgTys.Length) - let inpsAsVars, inpsAsExprs = inpArgTys |> List.mapi (fun j ty -> mkCompGenLocal appm ("arg" + string i + string j) ty) |> List.unzip + let inpsAsVars, inpsAsExprs = inpArgTys |> List.mapi (fun j ty -> mkCompGenLocal appm ("arg" + string i + string j) ty) |> List.unzip let inpsAsActualArg = CoerceDetupled inpArgTys inpsAsExprs actualArgTys let inpCloVarType = (mkFunTy (mkRefTupledTy g actualArgTys) cloVar.Type) let newResTy = mkFunTy inpArgTy resTy @@ -7481,7 +7482,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex let lambdaBuilder = (fun tm -> tm) lambdaBuilder, binderBuilder, inpsAsActualArg | None -> - let inpsAsVars, inpsAsExprs = (niceNames, inpArgTys) ||> List.map2 (fun nm ty -> mkCompGenLocal appm nm ty) |> List.unzip + let inpsAsVars, inpsAsExprs = (niceNames, inpArgTys) ||> List.map2 (fun nm ty -> mkCompGenLocal appm nm ty) |> List.unzip let inpsAsActualArg = CoerceDetupled inpArgTys inpsAsExprs actualArgTys let lambdaBuilder = (fun tm -> mkMultiLambda appm inpsAsVars (tm, tyOfExpr g tm)) let binderBuilder = (fun tm -> tm) @@ -7518,7 +7519,7 @@ let NormalizeAndAdjustPossibleSubsumptionExprs g inputExpr = let expr, args = // AdjustPossibleSubsumptionExpr can take into account an application match stripExpr inputExpr with - | Expr.App(f, _fty, [], args, _) -> + | Expr.App(f, _fty, [], args, _) -> f, args | _ -> @@ -7535,7 +7536,7 @@ let NormalizeAndAdjustPossibleSubsumptionExprs g inputExpr = //--------------------------------------------------------------------------- -// LinearizeTopMatch - when only one non-failing target, make linear. The full +// LinearizeTopMatch - when only one non-failing target, make linear. The full // complexity of this is only used for spectacularly rare bindings such as // type ('a, 'b) either = This of 'a | That of 'b // let this_f1 = This (fun x -> x) @@ -7560,18 +7561,18 @@ let AdjustValToTopVal (tmp: Val) parent valData = /// tree, T0(v0, .., vN) => rhs ; T1() => fail ; ... /// Convert it to bind T0's variables, then continue with T0's rhs: /// let tmp = switch tree, TO(fv0, ..., fvN) => Tup (fv0, ..., fvN) ; T1() => fail; ... -/// let v1 = #1 tmp in ... -/// and vN = #N tmp +/// let v1 = #1 tmp in ... +/// and vN = #N tmp /// rhs /// Motivation: /// - For top-level let bindings with possibly failing matches, /// this makes clear that subsequent bindings (if reached) are top-level ones. -let LinearizeTopMatchAux g parent (spBind, m, tree, targets, m2, ty) = +let LinearizeTopMatchAux g parent (spBind, m, tree, targets, m2, ty) = let targetsL = Array.toList targets (* items* package up 0, 1, more items *) let itemsProj tys i x = match tys with - | [] -> failwith "itemsProj: no items?" + | [] -> failwith "itemsProj: no items?" | [_] -> x (* no projection needed *) | tys -> Expr.Op (TOp.TupleFieldGet(tupInfoRef, i), tys, [x], m) let isThrowingTarget = function TTarget(_, x, _) -> isThrow x @@ -7579,30 +7580,30 @@ let LinearizeTopMatchAux g parent (spBind, m, tree, targets, m2, ty) = (* Have failing targets and ONE successful one, so linearize *) let (TTarget (vs, rhs, spTarget)) = Option.get (List.tryFind (isThrowingTarget >> not) targetsL) (* note - old code here used copy value to generate locals - this was not right *) - let fvs = vs |> List.map (fun v -> fst(mkLocal v.Range v.LogicalName v.Type)) (* fresh *) - let vtys = vs |> List.map (fun v -> v.Type) - let tmpTy = mkRefTupledVarsTy g vs + let fvs = vs |> List.map (fun v -> fst(mkLocal v.Range v.LogicalName v.Type)) (* fresh *) + let vtys = vs |> List.map (fun v -> v.Type) + let tmpTy = mkRefTupledVarsTy g vs let tmp, tmpe = mkCompGenLocal m "matchResultHolder" tmpTy AdjustValToTopVal tmp parent ValReprInfo.emptyValData - let newTg = TTarget (fvs, mkRefTupledVars g m fvs, spTarget) + let newTg = TTarget (fvs, mkRefTupledVars g m fvs, spTarget) let fixup (TTarget (tvs, tx, spTarget)) = match destThrow tx with | Some (m, _, e) -> let tx = mkThrow m tmpTy e TTarget(tvs, tx, spTarget) (* Throwing targets, recast it's "return type" *) - | None -> newTg (* Non-throwing target, replaced [new/old] *) + | None -> newTg (* Non-throwing target, replaced [new/old] *) - let targets = Array.map fixup targets - let binds = + let targets = Array.map fixup targets + let binds = vs |> List.mapi (fun i v -> let ty = v.Type - let rhs = etaExpandTypeLambda g m v.Typars (itemsProj vtys i tmpe, ty) + let rhs = etaExpandTypeLambda g m v.Typars (itemsProj vtys i tmpe, ty) // update the arity of the value v.SetValReprInfo (Some (InferArityOfExpr g AllowTypeDirectedDetupling.Yes ty [] [] rhs)) // This binding is deliberately non-sticky - any sequence point for 'rhs' goes on 'rhs' _after_ the binding has been evaluated - mkInvisibleBind v rhs) in (* vi = proj tmp *) + mkInvisibleBind v rhs) in (* vi = proj tmp *) mkCompGenLet m tmp (primMkMatch (spBind, m, tree, targets, m2, tmpTy)) (* note, probably retyped match, but note, result still has same type *) (mkLetsFromBindings m binds rhs) @@ -7620,8 +7621,8 @@ let LinearizeTopMatch g parent = function //--------------------------------------------------------------------------- -let commaEncs strs = String.concat "," strs -let angleEnc str = "{" + str + "}" +let commaEncs strs = String.concat "," strs +let angleEnc str = "{" + str + "}" let ticksAndArgCountTextOfTyconRef (tcref: TyconRef) = // Generic type names are (name + "`" + digits) where name does not contain "`". let path = Array.toList (fullMangledPathToTyconRef tcref) @ [tcref.CompiledName] @@ -7629,12 +7630,14 @@ let ticksAndArgCountTextOfTyconRef (tcref: TyconRef) = let typarEnc _g (gtpsType, gtpsMethod) typar = match List.tryFindIndex (typarEq typar) gtpsType with - | Some idx -> "`" + string idx // single-tick-index for typar from type - | None -> + | Some idx -> "`" + string idx // single-tick-index for typar from type + | None -> match List.tryFindIndex (typarEq typar) gtpsMethod with - | Some idx -> "``" + string idx // double-tick-index for typar from method - | None -> warning(InternalError("Typar not found during XmlDoc generation", typar.Range)) - "``0" // REVIEW: this should be ERROR not WARNING? + | Some idx -> + "``" + string idx // double-tick-index for typar from method + | None -> + warning(InternalError("Typar not found during XmlDoc generation", typar.Range)) + "``0" let rec typeEnc g (gtpsType, gtpsMethod) ty = if verbose then dprintf "--> typeEnc" @@ -7643,16 +7646,11 @@ let rec typeEnc g (gtpsType, gtpsMethod) ty = | TType_forall _ -> "Microsoft.FSharp.Core.FSharpTypeFunc" - | _ when isArrayTy g ty -> + | _ when isArrayTy g ty -> let tcref, tinst = destAppTy g ty let arraySuffix = match rankOfArrayTyconRef g tcref with - // The easy case | 1 -> "[]" - // REVIEW - // In fact IL supports 3 kinds of multidimensional arrays, and each kind of array has its own xmldoc spec. - // We don't support all these, and instead always pull xmldocs for 0-based-arbitrary-length ("0:") multidimensional arrays. - // This is probably the 99% case anyway. | 2 -> "[0:, 0:]" | 3 -> "[0:, 0:, 0:]" | 4 -> "[0:, 0:, 0:, 0:]" @@ -7660,7 +7658,7 @@ let rec typeEnc g (gtpsType, gtpsMethod) ty = typeEnc g (gtpsType, gtpsMethod) (List.head tinst) + arraySuffix | TType_ucase (UCRef(tcref, _), tinst) - | TType_app (tcref, tinst) -> + | TType_app (tcref, tinst) -> if tyconRefEq g g.byref_tcr tcref then typeEnc g (gtpsType, gtpsMethod) (List.head tinst) + "@" elif tyconRefEq g tcref g.nativeptr_tcr then @@ -7669,12 +7667,14 @@ let rec typeEnc g (gtpsType, gtpsMethod) ty = let tyName = let ty = stripTyEqnsAndMeasureEqns g ty match ty with - | TType_app (tcref, _tinst) -> + | TType_app (tcref, _tinst) -> // Generic type names are (name + "`" + digits) where name does not contain "`". // In XML doc, when used in type instances, these do not use the ticks. let path = Array.toList (fullMangledPathToTyconRef tcref) @ [tcref.CompiledName] textOfPath (List.map DemangleGenericTypeName path) - | _ -> assert(false); failwith "impossible" + | _ -> + assert false + failwith "impossible" tyName + tyargsEnc g (gtpsType, gtpsMethod) tinst | TType_anon (anonInfo, tinst) -> @@ -7686,10 +7686,10 @@ let rec typeEnc g (gtpsType, gtpsMethod) ty = else sprintf "System.Tuple%s"(tyargsEnc g (gtpsType, gtpsMethod) tys) - | TType_fun (f, x) -> + | TType_fun (f, x) -> "Microsoft.FSharp.Core.FSharpFunc" + tyargsEnc g (gtpsType, gtpsMethod) [f;x] - | TType_var typar -> + | TType_var typar -> typarEnc g (gtpsType, gtpsMethod) typar | TType_measure _ -> "?" @@ -7743,7 +7743,7 @@ let XmlDocSigOfVal g path (v: Val) = let tps, argInfos, _, _ = GetTopValTypeInCompiledForm g w v.Type v.Range let name = v.CompiledName let prefix = - if w.NumCurriedArgs = 0 && isNil tps then "P:" + if w.NumCurriedArgs = 0 && isNil tps then "P:" else "M:" [], tps, argInfos, prefix, path, name let argTs = argInfos |> List.concat |> List.map fst @@ -7752,17 +7752,17 @@ let XmlDocSigOfVal g path (v: Val) = let genArity = if arity=0 then "" else sprintf "``%d" arity prefix + prependPath path name + genArity + args -let BuildXmlDocSig prefix paths = prefix + List.fold prependPath "" paths +let BuildXmlDocSig prefix paths = prefix + List.fold prependPath "" paths let XmlDocSigOfUnionCase = BuildXmlDocSig "T:" // Would like to use "U:", but ParseMemberSignature only accepts C# signatures -let XmlDocSigOfField = BuildXmlDocSig "F:" +let XmlDocSigOfField = BuildXmlDocSig "F:" -let XmlDocSigOfProperty = BuildXmlDocSig "P:" +let XmlDocSigOfProperty = BuildXmlDocSig "P:" -let XmlDocSigOfTycon = BuildXmlDocSig "T:" +let XmlDocSigOfTycon = BuildXmlDocSig "T:" -let XmlDocSigOfSubModul = BuildXmlDocSig "T:" +let XmlDocSigOfSubModul = BuildXmlDocSig "T:" let XmlDocSigOfEntity (eref: EntityRef) = XmlDocSigOfTycon [(buildAccessPath eref.CompilationPathOpt); eref.Deref.CompiledName] @@ -7772,14 +7772,14 @@ let XmlDocSigOfEntity (eref: EntityRef) = //-------------------------------------------------------------------------- -let enum_CompilationRepresentationAttribute_Static = 0b0000000000000001 -let enum_CompilationRepresentationAttribute_Instance = 0b0000000000000010 +let enum_CompilationRepresentationAttribute_Static = 0b0000000000000001 +let enum_CompilationRepresentationAttribute_Instance = 0b0000000000000010 let enum_CompilationRepresentationAttribute_StaticInstanceMask = 0b0000000000000011 -let enum_CompilationRepresentationAttribute_ModuleSuffix = 0b0000000000000100 -let enum_CompilationRepresentationAttribute_PermitNull = 0b0000000000001000 +let enum_CompilationRepresentationAttribute_ModuleSuffix = 0b0000000000000100 +let enum_CompilationRepresentationAttribute_PermitNull = 0b0000000000001000 let HasUseNullAsTrueValueAttribute g attribs = - match TryFindFSharpInt32Attribute g g.attrib_CompilationRepresentationAttribute attribs with + match TryFindFSharpInt32Attribute g g.attrib_CompilationRepresentationAttribute attribs with | Some(flags) -> ((flags &&& enum_CompilationRepresentationAttribute_PermitNull) <> 0) | _ -> false @@ -7917,7 +7917,7 @@ let mkIsInstConditional g m tgty vinpe v e2 e3 = let tg3 = mbuilder.AddResultTarget(e3, SuppressSequencePointAtTarget) let dtree = TDSwitch(exprForVal m v, [TCase(DecisionTreeTest.IsNull, tg3)], Some tg2, m) let expr = mbuilder.Close(dtree, m, tyOfExpr g e2) - mkCompGenLet m v (mkIsInst tgty vinpe m) expr + mkCompGenLet m v (mkIsInst tgty vinpe m) expr else let mbuilder = new MatchBuilder(NoSequencePointAtInvisibleBinding, m) @@ -7939,7 +7939,7 @@ 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) @@ -8004,7 +8004,7 @@ let ValSpecIsCompiledAsInstance g (v: Val) = // These only differ if the value is an extension member, and in that case MemberIsCompiledAsInstance always returns // false anyway MemberIsCompiledAsInstance g v.MemberApparentEntity v.IsExtensionMember membInfo v.Attribs - | _ -> false + | _ -> false let ValRefIsCompiledAsInstanceMember g (vref: ValRef) = ValSpecIsCompiledAsInstance g vref.Deref @@ -8022,14 +8022,14 @@ let GetMemberCallInfo g (vref: ValRef, vFlags) = membInfo.MemberFlags.IsDispatchSlot) && not membInfo.MemberFlags.IsFinal && (match vFlags with VSlotDirectCall -> false | _ -> true) - let isNewObj = (membInfo.MemberFlags.MemberKind = MemberKind.Constructor) && (match vFlags with NormalValUse -> true | _ -> false) + let isNewObj = (membInfo.MemberFlags.MemberKind = MemberKind.Constructor) && (match vFlags with NormalValUse -> true | _ -> false) let isSuperInit = (membInfo.MemberFlags.MemberKind = MemberKind.Constructor) && (match vFlags with CtorValUsedAsSuperInit -> true | _ -> false) - let isSelfInit = (membInfo.MemberFlags.MemberKind = MemberKind.Constructor) && (match vFlags with CtorValUsedAsSelfInit -> true | _ -> false) + let isSelfInit = (membInfo.MemberFlags.MemberKind = MemberKind.Constructor) && (match vFlags with CtorValUsedAsSelfInit -> true | _ -> false) let isCompiledAsInstance = ValRefIsCompiledAsInstanceMember g vref let takesInstanceArg = isCompiledAsInstance && not isNewObj let isPropGet = (membInfo.MemberFlags.MemberKind = MemberKind.PropertyGet) && (membInfo.MemberFlags.IsInstance = isCompiledAsInstance) let isPropSet = (membInfo.MemberFlags.MemberKind = MemberKind.PropertySet) && (membInfo.MemberFlags.IsInstance = isCompiledAsInstance) - numEnclTypeArgs, virtualCall, isNewObj, isSuperInit, isSelfInit , takesInstanceArg, isPropGet, isPropSet + numEnclTypeArgs, virtualCall, isNewObj, isSuperInit, isSelfInit, takesInstanceArg, isPropGet, isPropSet | _ -> 0, false, false, false, false, false, false, false @@ -8053,7 +8053,7 @@ type ActivePatternElemRef with | None -> error(InternalError("not an active pattern name", vref.Range)) | Some apinfo -> let nms = apinfo.ActiveTags - if n < 0 || n >= List.length nms then error(InternalError("name_of_apref: index out of range for active pattern reference", vref.Range)) + 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 = @@ -8093,11 +8093,11 @@ 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 vty = v.TauType + let vty = v.TauType let vtps = v.Typars |> Zset.ofList typarOrder if not (isFunTy g v.TauType) then errorR(Error(FSComp.SR.activePatternIdentIsNotFunctionTyped(v.LogicalName), v.Range)) - let argtys, resty = stripFunTy g vty + let argtys, resty = stripFunTy g vty let argtps, restps= (freeInTypes CollectTypars argtys).FreeTypars, (freeInType CollectTypars resty).FreeTypars // Error if an active pattern is generic in type variables that only occur in the result Choice<_, ...>. // Note: The test restricts to v.Typars since typars from the closure are considered fixed. @@ -8115,7 +8115,7 @@ type ExprRewritingEnv = IsUnderQuotations: bool } let rec rewriteBind env bind = - match env.PreInterceptBinding with + match env.PreInterceptBinding with | Some f -> match f (RewriteExpr env) bind with | Some res -> res @@ -8142,7 +8142,7 @@ and RewriteExpr env expr = postRewriteExpr env expr and preRewriteExpr env expr = - match env.PreIntercept with + match env.PreIntercept with | Some f -> f (RewriteExpr env) expr | None -> None @@ -8157,7 +8157,7 @@ and rewriteExprStructure env expr = | Expr.Val _ -> expr | Expr.App(f0, f0ty, tyargs, args, m) -> - let f0' = RewriteExpr env f0 + let f0' = RewriteExpr env f0 let args' = rewriteExprs env args if f0 === f0' && args === args' then expr else Expr.App(f0', f0ty, tyargs, args', m) @@ -8222,7 +8222,7 @@ and rewriteLinearExpr env expr contf = rewriteLinearExpr env bodyExpr (contf << (fun bodyExpr' -> mkLetBind m bind bodyExpr')) - | Expr.Sequential (expr1, expr2, dir, spSeq, m) -> + | Expr.Sequential (expr1, expr2, dir, spSeq, m) -> let expr1' = RewriteExpr env expr1 // tailcall rewriteLinearExpr env expr2 (contf << (fun expr2' -> @@ -8280,17 +8280,17 @@ and rewriteObjExprInterfaceImpl env (ty, overrides) = and rewriteModuleOrNamespaceExpr env x = match x with - | ModuleOrNamespaceExprWithSig(mty, def, m) -> ModuleOrNamespaceExprWithSig(mty, rewriteModuleOrNamespaceDef env def, m) + | ModuleOrNamespaceExprWithSig(mty, def, m) -> ModuleOrNamespaceExprWithSig(mty, rewriteModuleOrNamespaceDef env def, m) and rewriteModuleOrNamespaceDefs env x = List.map (rewriteModuleOrNamespaceDef env) x and rewriteModuleOrNamespaceDef env x = match x with | TMDefRec(isRec, tycons, mbinds, m) -> TMDefRec(isRec, tycons, rewriteModuleOrNamespaceBindings env mbinds, m) - | TMDefLet(bind, m) -> TMDefLet(rewriteBind env bind, m) - | TMDefDo(e, m) -> TMDefDo(RewriteExpr env e, m) - | TMDefs defs -> TMDefs(rewriteModuleOrNamespaceDefs env defs) - | TMAbstract mexpr -> TMAbstract(rewriteModuleOrNamespaceExpr env mexpr) + | TMDefLet(bind, m) -> TMDefLet(rewriteBind env bind, m) + | TMDefDo(e, m) -> TMDefDo(RewriteExpr env e, m) + | TMDefs defs -> TMDefs(rewriteModuleOrNamespaceDefs env defs) + | TMAbstract mexpr -> TMAbstract(rewriteModuleOrNamespaceExpr env mexpr) and rewriteModuleOrNamespaceBinding env x = match x with @@ -8337,7 +8337,7 @@ let MakeExportRemapping viewedCcu (mspec: ModuleOrNamespace) = allRemap //-------------------------------------------------------------------------- -// Apply a "local to nonlocal" renaming to a module type. This can't use +// Apply a "local to nonlocal" renaming to a module type. This can't use // remap_mspec since the remapping we want isn't to newly created nodes // but rather to remap to the nonlocal references. This is deliberately // "breaking" the binding structure implicit in the module type, which is @@ -8348,31 +8348,31 @@ let MakeExportRemapping viewedCcu (mspec: ModuleOrNamespace) = let rec remapEntityDataToNonLocal g tmenv (d: Entity) = let tps', tmenvinner = tmenvCopyRemapAndBindTypars (remapAttribs g tmenv) tmenv (d.entity_typars.Force(d.entity_range)) - let typarsR = LazyWithContext.NotLazy tps' - let attribsR = d.entity_attribs |> remapAttribs g tmenvinner - let tyconReprR = d.entity_tycon_repr |> remapTyconRepr g tmenvinner - let tyconAbbrevR = d.TypeAbbrev |> Option.map (remapType tmenvinner) - let tyconTcaugR = d.entity_tycon_tcaug |> remapTyconAug tmenvinner - let modulContentsR = + let typarsR = LazyWithContext.NotLazy tps' + let attribsR = d.entity_attribs |> remapAttribs g tmenvinner + let tyconReprR = d.entity_tycon_repr |> remapTyconRepr g tmenvinner + let tyconAbbrevR = d.TypeAbbrev |> Option.map (remapType tmenvinner) + let tyconTcaugR = d.entity_tycon_tcaug |> remapTyconAug tmenvinner + let modulContentsR = MaybeLazy.Strict (d.entity_modul_contents.Value |> mapImmediateValsAndTycons (remapTyconToNonLocal g tmenv) (remapValToNonLocal g tmenv)) - let exnInfoR = d.ExceptionInfo |> remapTyconExnInfo g tmenvinner + let exnInfoR = d.ExceptionInfo |> remapTyconExnInfo g tmenvinner { d with - entity_typars = typarsR - entity_attribs = attribsR - entity_tycon_repr = tyconReprR - entity_tycon_tcaug = tyconTcaugR + entity_typars = typarsR + entity_attribs = attribsR + entity_tycon_repr = tyconReprR + entity_tycon_tcaug = tyconTcaugR entity_modul_contents = modulContentsR - entity_opt_data = + entity_opt_data = match d.entity_opt_data with | Some dd -> - Some { dd with entity_tycon_abbrev = tyconAbbrevR; entity_exn_info = exnInfoR } + Some { dd with entity_tycon_abbrev = tyconAbbrevR; entity_exn_info = exnInfoR } | _ -> None } and remapTyconToNonLocal g tmenv x = x |> NewModifiedTycon (remapEntityDataToNonLocal g tmenv) -and remapValToNonLocal g tmenv inp = +and remapValToNonLocal g tmenv inp = // creates a new stamp inp |> NewModifiedVal (remapValData g tmenv) @@ -8411,7 +8411,7 @@ type Entity with | Some membInfo -> let argInfos = ArgInfosOfMember g vref argInfos.Length = 1 && - List.lengthsEqAndForall2 (typeEquiv g) (List.map fst (List.head argInfos)) argtys && + List.lengthsEqAndForall2 (typeEquiv g) (List.map fst (List.head argInfos)) argtys && membInfo.MemberFlags.IsOverrideOrExplicitImpl) member tycon.HasMember g nm argtys = @@ -8451,24 +8451,24 @@ let IsSimpleSyntacticConstantExpr g inputExpr = -> checkExpr vrefs arg // compare, =, <>, +, -, <, >, <=, >=, <<<, >>>, &&& | BinopExpr g (vref, arg1, arg2) - when (valRefEq g vref g.equals_operator_vref || - valRefEq g vref g.compare_operator_vref || - valRefEq g vref g.unchecked_addition_vref || - valRefEq g vref g.less_than_operator_vref || - valRefEq g vref g.less_than_or_equals_operator_vref || - valRefEq g vref g.greater_than_operator_vref || - valRefEq g vref g.greater_than_or_equals_operator_vref || - valRefEq g vref g.not_equals_operator_vref || - valRefEq g vref g.unchecked_addition_vref || - valRefEq g vref g.unchecked_multiply_vref || - valRefEq g vref g.unchecked_subtraction_vref || + when (valRefEq g vref g.equals_operator_vref || + valRefEq g vref g.compare_operator_vref || + valRefEq g vref g.unchecked_addition_vref || + valRefEq g vref g.less_than_operator_vref || + valRefEq g vref g.less_than_or_equals_operator_vref || + valRefEq g vref g.greater_than_operator_vref || + valRefEq g vref g.greater_than_or_equals_operator_vref || + valRefEq g vref g.not_equals_operator_vref || + valRefEq g vref g.unchecked_addition_vref || + valRefEq g vref g.unchecked_multiply_vref || + valRefEq g vref g.unchecked_subtraction_vref || // Note: division and modulus can raise exceptions, so are not included - valRefEq g vref g.bitwise_shift_left_vref || - valRefEq g vref g.bitwise_shift_right_vref || - valRefEq g vref g.bitwise_xor_vref || - valRefEq g vref g.bitwise_and_vref || + valRefEq g vref g.bitwise_shift_left_vref || + valRefEq g vref g.bitwise_shift_right_vref || + valRefEq g vref g.bitwise_xor_vref || + valRefEq g vref g.bitwise_and_vref || valRefEq g vref g.bitwise_or_vref) && - (not (typeEquiv g (tyOfExpr g arg1) g.string_ty) && not (typeEquiv g (tyOfExpr g arg1) g.decimal_ty) ) + (not (typeEquiv g (tyOfExpr g arg1) g.string_ty) && not (typeEquiv g (tyOfExpr g arg1) g.decimal_ty) ) -> checkExpr vrefs arg1 && checkExpr vrefs arg2 | Expr.Val(vref, _, _) -> vref.Deref.IsCompiledAsStaticPropertyWithoutField || vrefs.Contains vref.Stamp | Expr.Match(_, _, dtree, targets, _, _) -> checkDecisionTree vrefs dtree && targets |> Array.forall (checkDecisionTreeTarget vrefs) @@ -8501,16 +8501,16 @@ let EvalArithBinOp (opInt8, opInt16, opInt32, opInt64, opUInt8, opUInt16, opUInt let m = unionRanges arg1.Range arg2.Range try match arg1, arg2 with - | Expr.Const(Const.Int32 x1, _, ty), Expr.Const(Const.Int32 x2, _, _) -> Expr.Const(Const.Int32 (opInt32 x1 x2), m, ty) - | Expr.Const(Const.SByte x1, _, ty), Expr.Const(Const.SByte x2, _, _) -> Expr.Const(Const.SByte (opInt8 x1 x2), m, ty) - | Expr.Const(Const.Int16 x1, _, ty), Expr.Const(Const.Int16 x2, _, _) -> Expr.Const(Const.Int16 (opInt16 x1 x2), m, ty) - | Expr.Const(Const.Int64 x1, _, ty), Expr.Const(Const.Int64 x2, _, _) -> Expr.Const(Const.Int64 (opInt64 x1 x2), m, ty) - | Expr.Const(Const.Byte x1, _, ty), Expr.Const(Const.Byte x2, _, _) -> Expr.Const(Const.Byte (opUInt8 x1 x2), m, ty) + | Expr.Const(Const.Int32 x1, _, ty), Expr.Const(Const.Int32 x2, _, _) -> Expr.Const(Const.Int32 (opInt32 x1 x2), m, ty) + | Expr.Const(Const.SByte x1, _, ty), Expr.Const(Const.SByte x2, _, _) -> Expr.Const(Const.SByte (opInt8 x1 x2), m, ty) + | Expr.Const(Const.Int16 x1, _, ty), Expr.Const(Const.Int16 x2, _, _) -> Expr.Const(Const.Int16 (opInt16 x1 x2), m, ty) + | Expr.Const(Const.Int64 x1, _, ty), Expr.Const(Const.Int64 x2, _, _) -> Expr.Const(Const.Int64 (opInt64 x1 x2), m, ty) + | Expr.Const(Const.Byte x1, _, ty), Expr.Const(Const.Byte x2, _, _) -> Expr.Const(Const.Byte (opUInt8 x1 x2), m, ty) | Expr.Const(Const.UInt16 x1, _, ty), Expr.Const(Const.UInt16 x2, _, _) -> Expr.Const(Const.UInt16 (opUInt16 x1 x2), m, ty) | Expr.Const(Const.UInt32 x1, _, ty), Expr.Const(Const.UInt32 x2, _, _) -> Expr.Const(Const.UInt32 (opUInt32 x1 x2), m, ty) | Expr.Const(Const.UInt64 x1, _, ty), Expr.Const(Const.UInt64 x2, _, _) -> Expr.Const(Const.UInt64 (opUInt64 x1 x2), m, ty) | _ -> error (Error ( FSComp.SR.tastNotAConstantExpression(), m)) - with :? System.OverflowException -> error (Error ( FSComp.SR.tastConstantExpressionOverflow(), m)) + with :? System.OverflowException -> error (Error ( FSComp.SR.tastConstantExpressionOverflow(), m)) // See also PostTypeCheckSemanticChecks.CheckAttribArgExpr, which must match this precisely let rec EvalAttribArgExpr g x = @@ -8521,19 +8521,19 @@ let rec EvalAttribArgExpr g x = match c with | Const.Bool _ | Const.Int32 _ - | Const.SByte _ - | Const.Int16 _ + | Const.SByte _ + | Const.Int16 _ | Const.Int32 _ | Const.Int64 _ - | Const.Byte _ - | Const.UInt16 _ - | Const.UInt32 _ - | Const.UInt64 _ + | Const.Byte _ + | Const.UInt16 _ + | Const.UInt32 _ + | Const.UInt64 _ | Const.Double _ | Const.Single _ | Const.Char _ | Const.Zero _ - | Const.String _ -> + | Const.String _ -> x | Const.Decimal _ | Const.IntPtr _ | Const.UIntPtr _ | Const.Unit _ -> errorR (Error ( FSComp.SR.tastNotAConstantExpression(), m)) @@ -8574,27 +8574,27 @@ let rec EvalAttribArgExpr g x = and EvaledAttribExprEquality g e1 e2 = match e1, e2 with | Expr.Const(c1, _, _), Expr.Const(c2, _, _) -> c1 = c2 - | TypeOfExpr g ty1, TypeOfExpr g ty2 -> typeEquiv g ty1 ty2 + | TypeOfExpr g ty1, TypeOfExpr g ty2 -> typeEquiv g ty1 ty2 | TypeDefOfExpr g ty1, TypeDefOfExpr g ty2 -> typeEquiv g ty1 ty2 | _ -> false let (|ConstToILFieldInit|_|) c = match c with - | Const.SByte n -> Some (ILFieldInit.Int8 n) - | Const.Int16 n -> Some (ILFieldInit.Int16 n) - | Const.Int32 n -> Some (ILFieldInit.Int32 n) - | Const.Int64 n -> Some (ILFieldInit.Int64 n) - | Const.Byte n -> Some (ILFieldInit.UInt8 n) - | Const.UInt16 n -> Some (ILFieldInit.UInt16 n) - | Const.UInt32 n -> Some (ILFieldInit.UInt32 n) - | Const.UInt64 n -> Some (ILFieldInit.UInt64 n) - | Const.Bool n -> Some (ILFieldInit.Bool n) - | Const.Char n -> Some (ILFieldInit.Char (uint16 n)) - | Const.Single n -> Some (ILFieldInit.Single n) - | Const.Double n -> Some (ILFieldInit.Double n) - | Const.String s -> Some (ILFieldInit.String s) - | Const.Zero -> Some (ILFieldInit.Null) - | _ -> None + | Const.SByte n -> Some (ILFieldInit.Int8 n) + | Const.Int16 n -> Some (ILFieldInit.Int16 n) + | Const.Int32 n -> Some (ILFieldInit.Int32 n) + | Const.Int64 n -> Some (ILFieldInit.Int64 n) + | Const.Byte n -> Some (ILFieldInit.UInt8 n) + | Const.UInt16 n -> Some (ILFieldInit.UInt16 n) + | Const.UInt32 n -> Some (ILFieldInit.UInt32 n) + | Const.UInt64 n -> Some (ILFieldInit.UInt64 n) + | Const.Bool n -> Some (ILFieldInit.Bool n) + | Const.Char n -> Some (ILFieldInit.Char (uint16 n)) + | Const.Single n -> Some (ILFieldInit.Single n) + | Const.Double n -> Some (ILFieldInit.Double n) + | Const.String s -> Some (ILFieldInit.String s) + | Const.Zero -> Some (ILFieldInit.Null) + | _ -> None let EvalLiteralExprOrAttribArg g x = match x with @@ -8648,7 +8648,7 @@ let rec mkCompiledTuple g isStruct (argtys, args, m) = | [ty8], [arg8] -> match ty8 with // if it's already been nested or ended, pass it through - | TType_app(tn, _) when (isCompiledTupleTyconRef g tn) -> + | TType_app(tn, _) when (isCompiledTupleTyconRef g tn) -> ty8, arg8 | _ -> let ty8enc = TType_app((if isStruct then g.struct_tuple1_tcr else g.ref_tuple1_tcr), [ty8]) @@ -8670,7 +8670,7 @@ let mkILFieldSpecForTupleItem (ty: ILType) n = let mkGetTupleItemN g m n (ty: ILType) isStruct te retty = if isStruct then - mkAsmExpr([mkNormalLdfld (mkILFieldSpecForTupleItem ty n) ], [], [te], [retty], m) + mkAsmExpr([mkNormalLdfld (mkILFieldSpecForTupleItem ty n) ], [], [te], [retty], m) else mkAsmExpr([IL.mkNormalCall(mkILMethodSpecForTupleItem g ty n)], [], [te], [retty], m) /// Match an Int32 constant expression @@ -8733,8 +8733,8 @@ let (|CompiledForEachExpr|_|) g expr = let mBody = bodyExpr.Range let mWholeExpr = expr.Range - let spForLoop, mForLoop = match enumeratorBind with SequencePointAtBinding(spStart) -> SequencePointAtForLoop(spStart), spStart | _ -> NoSequencePointAtForLoop, mEnumExpr - let spWhileLoop = match enumeratorBind with SequencePointAtBinding(spStart) -> SequencePointAtWhileLoop(spStart)| _ -> NoSequencePointAtWhileLoop + let spForLoop, mForLoop = match enumeratorBind with SequencePointAtBinding(spStart) -> SequencePointAtForLoop(spStart), spStart | _ -> NoSequencePointAtForLoop, mEnumExpr + let spWhileLoop = match enumeratorBind with SequencePointAtBinding(spStart) -> SequencePointAtWhileLoop(spStart)| _ -> NoSequencePointAtWhileLoop let enumerableTy = tyOfExpr g enumerableExpr Some (enumerableTy, enumerableExpr, elemVar, bodyExpr, (mEnumExpr, mBody, spForLoop, mForLoop, spWhileLoop, mWholeExpr)) @@ -8788,12 +8788,12 @@ let DetectAndOptimizeForExpression g option expr = elif isListTy g enumerableTy then // type is list, optimize for expression as: // let mutable $currentVar = listExpr - // let mutable $nextVar = $tailOrNull + // let mutable $nextVar = $tailOrNull // while $guardExpr do // let i = $headExpr // bodyExpr () - // $current <- $next - // $next <- $tailOrNull + // $current <- $next + // $next <- $tailOrNull let IndexHead = 0 let IndexTail = 1 @@ -8833,7 +8833,7 @@ let DetectAndOptimizeForExpression g option expr = let (|InnerExprPat|) expr = stripExpr expr /// One of the transformations performed by the compiler -/// is to eliminate variables of static type "unit". These is a +/// 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) = diff --git a/src/fsharp/TastPickle.fs b/src/fsharp/TastPickle.fs index 95f471c6fd4..8e210613e65 100755 --- a/src/fsharp/TastPickle.fs +++ b/src/fsharp/TastPickle.fs @@ -838,7 +838,7 @@ let unpickleObjWithDanglingCcus file ilscope (iILModule: ILModuleDef option) u ( iccus= new_itbl "iccus (fake)" [| |] ientities= NodeInTable<_, _>.Create (Tycon.NewUnlinked, (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "itycons", 0) itypars= NodeInTable<_, _>.Create (Typar.NewUnlinked, (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "itypars", 0) - ivals = NodeInTable<_, _>.Create (Val.NewUnlinked , (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "ivals", 0) + ivals = NodeInTable<_, _>.Create (Val.NewUnlinked, (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "ivals", 0) ianoninfos=NodeInTable<_, _>.Create(AnonRecdTypeInfo.NewUnlinked, (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "ianoninfos", 0) istrings = new_itbl "istrings (fake)" [| |] inlerefs = new_itbl "inlerefs (fake)" [| |] @@ -871,7 +871,7 @@ let unpickleObjWithDanglingCcus file ilscope (iILModule: ILModuleDef option) u ( iilscope= ilscope ientities= NodeInTable<_, _>.Create(Tycon.NewUnlinked, (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "itycons", ntycons) itypars= NodeInTable<_, _>.Create(Typar.NewUnlinked, (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "itypars", ntypars) - ivals= NodeInTable<_, _>.Create(Val.NewUnlinked , (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "ivals", nvals) + ivals= NodeInTable<_, _>.Create(Val.NewUnlinked, (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "ivals", nvals) ianoninfos=NodeInTable<_, _>.Create(AnonRecdTypeInfo.NewUnlinked, (fun osgn tg -> osgn.Link tg), (fun osgn -> osgn.IsLinked), "ianoninfos", nanoninfos) istrings = stringTab ipubpaths = pubpathTab @@ -1797,7 +1797,7 @@ and p_tycon_repr x st = p_byte 0 st; false else // Pickle generated type definitions as a TAsmRepr - p_byte 1 st; p_byte 2 st; p_ILType (mkILBoxedType(ILTypeSpec.Create(ExtensionTyping.GetILTypeRefOfProvidedType(info.ProvidedType , range0), []))) st; true + p_byte 1 st; p_byte 2 st; p_ILType (mkILBoxedType(ILTypeSpec.Create(ExtensionTyping.GetILTypeRefOfProvidedType(info.ProvidedType, range0), []))) st; true | TProvidedNamespaceExtensionPoint _ -> p_byte 0 st; false #endif | TILObjectRepr (TILObjectReprData (_, _, td)) -> error (Failure("Unexpected IL type definition"+td.Name)) diff --git a/src/fsharp/TypeChecker.fs b/src/fsharp/TypeChecker.fs index d85cf3e5e63..6c47f4e262c 100755 --- a/src/fsharp/TypeChecker.fs +++ b/src/fsharp/TypeChecker.fs @@ -1,6 +1,6 @@ -// 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. -/// The typechecker. Left-to-right constrained type checking +/// The typechecker. Left-to-right constrained type checking /// with generalization at appropriate points. module internal FSharp.Compiler.TypeChecker @@ -56,7 +56,7 @@ exception BakedInMemberConstraintName of string * range exception FunctionExpected of DisplayEnv * TType * range exception NotAFunction of DisplayEnv * TType * range * range exception NotAFunctionButIndexer of DisplayEnv * TType * string option * range * range -exception Recursion of DisplayEnv * Ident * TType * TType * range +exception Recursion of DisplayEnv * Ident * TType * TType * range exception RecursiveUseCheckedAtRuntime of DisplayEnv * ValRef * range exception LetRecEvaluatedOutOfOrder of DisplayEnv * ValRef * ValRef * range exception LetRecCheckedAtRuntime of range @@ -127,15 +127,15 @@ type CtorInfo = } /// Represents an item in the environment that may restrict the automatic generalization of later -/// declarations because it refers to type inference variables. As type inference progresses +/// declarations because it refers to type inference variables. As type inference progresses /// these type inference variables may get solved. [] type UngeneralizableItem(computeFreeTyvars: (unit -> FreeTyvars)) = // Flag is for: have we determined that this item definitely has // no free type inference variables? This implies that - // (a) it will _never_ have any free type inference variables as further constraints are added to the system. - // (b) its set of FreeTycons will not change as further constraints are added to the system + // (a) it will _never_ have any free type inference variables as further constraints are added to the system. + // (b) its set of FreeTycons will not change as further constraints are added to the system let mutable willNeverHaveFreeTypars = false // If WillNeverHaveFreeTypars then we can cache the computation of FreeTycons, since they are invariant. @@ -224,7 +224,7 @@ type TcEnv = let computeAccessRights eAccessPath eInternalsVisibleCompPaths eFamilyType = AccessibleFrom (eAccessPath :: eInternalsVisibleCompPaths, eFamilyType) // env.eAccessRights -let emptyTcEnv g = +let emptyTcEnv g = let cpath = compPathInternal // allow internal access initially { eNameResEnv = NameResolutionEnv.Empty g eUngeneralizableItems = [] @@ -265,19 +265,19 @@ let EnterFamilyRegion tcref env = let ExitFamilyRegion env = let eFamilyType = None match env.eFamilyType with - | None -> env // optimization to avoid reallocation + | None -> env // optimization to avoid reallocation | _ -> { env with - eAccessRights = computeAccessRights env.eAccessPath env.eInternalsVisibleCompPaths eFamilyType // update this computed field + eAccessRights = computeAccessRights env.eAccessPath env.eInternalsVisibleCompPaths eFamilyType // update this computed field eFamilyType = eFamilyType } -let AreWithinCtorShape env = match env.eCtorInfo with None -> false | Some ctorInfo -> ctorInfo.ctorShapeCounter > 0 -let AreWithinImplicitCtor env = match env.eCtorInfo with None -> false | Some ctorInfo -> ctorInfo.ctorIsImplicit -let GetCtorShapeCounter env = match env.eCtorInfo with None -> 0 | Some ctorInfo -> ctorInfo.ctorShapeCounter -let GetRecdInfo env = match env.eCtorInfo with None -> RecdExpr | Some ctorInfo -> if ctorInfo.ctorShapeCounter = 1 then RecdExprIsObjInit else RecdExpr +let AreWithinCtorShape env = match env.eCtorInfo with None -> false | Some ctorInfo -> ctorInfo.ctorShapeCounter > 0 +let AreWithinImplicitCtor env = match env.eCtorInfo with None -> false | Some ctorInfo -> ctorInfo.ctorIsImplicit +let GetCtorShapeCounter env = match env.eCtorInfo with None -> 0 | Some ctorInfo -> ctorInfo.ctorShapeCounter +let GetRecdInfo env = match env.eCtorInfo with None -> RecdExpr | Some ctorInfo -> if ctorInfo.ctorShapeCounter = 1 then RecdExprIsObjInit else RecdExpr -let AdjustCtorShapeCounter f env = {env with eCtorInfo = Option.map (fun ctorInfo -> { ctorInfo with ctorShapeCounter = f ctorInfo.ctorShapeCounter }) env.eCtorInfo } -let ExitCtorShapeRegion env = AdjustCtorShapeCounter (fun _ -> 0) env +let AdjustCtorShapeCounter f env = {env with eCtorInfo = Option.map (fun ctorInfo -> { ctorInfo with ctorShapeCounter = f ctorInfo.ctorShapeCounter }) env.eCtorInfo } +let ExitCtorShapeRegion env = AdjustCtorShapeCounter (fun _ -> 0) env /// Add a type to the TcEnv, i.e. register it as ungeneralizable. let addFreeItemOfTy ty eUngeneralizableItems = @@ -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 @@ -590,7 +590,7 @@ let MakeInnerEnvForMember env (v: Val) = let GetCurrAccumulatedModuleOrNamespaceType env = !(env.eModuleOrNamespaceTypeAccumulator) /// Set the current accumulator for the namespace/module we're in, updating the inferred contents -let SetCurrAccumulatedModuleOrNamespaceType env x = env.eModuleOrNamespaceTypeAccumulator := x +let SetCurrAccumulatedModuleOrNamespaceType env x = env.eModuleOrNamespaceTypeAccumulator := x /// Set up the initial environment accounting for the enclosing "namespace X.Y.Z" definition let LocateEnv ccu env enclosingNamespacePath = @@ -609,7 +609,7 @@ let LocateEnv ccu env enclosingNamespacePath = let BuildRootModuleType enclosingNamespacePath (cpath: CompilationPath) mtyp = (enclosingNamespacePath, (cpath, (mtyp, []))) ||> List.foldBack (fun id (cpath, (mtyp, mspecs)) -> - let a, b = wrapModuleOrNamespaceTypeInNamespace id cpath.ParentCompPath mtyp + let a, b = wrapModuleOrNamespaceTypeInNamespace id cpath.ParentCompPath mtyp cpath.ParentCompPath, (a, b :: mspecs)) |> fun (_, (mtyp, mspecs)) -> mtyp, List.rev mspecs @@ -775,7 +775,7 @@ let UnifyFunctionType extraInfo cenv denv mFunExpr ty = | ValueNone -> match extraInfo with | Some argm -> error (NotAFunction(denv, ty, mFunExpr, argm)) - | None -> error (FunctionExpected(denv, ty, mFunExpr)) + | None -> error (FunctionExpected(denv, ty, mFunExpr)) let ReportImplicitlyIgnoredBoolExpression denv m ty expr = let checkExpr m expr = @@ -848,9 +848,9 @@ let UnifyUnitType cenv (env: TcEnv) m ty expr = // Logically extends System.AttributeTargets module AttributeTargets = - let FieldDecl = AttributeTargets.Field ||| AttributeTargets.Property + let FieldDecl = AttributeTargets.Field ||| AttributeTargets.Property let FieldDeclRestricted = AttributeTargets.Field - let UnionCaseDecl = AttributeTargets.Method ||| AttributeTargets.Property + let UnionCaseDecl = AttributeTargets.Method ||| AttributeTargets.Property let TyconDecl = AttributeTargets.Class ||| AttributeTargets.Interface ||| AttributeTargets.Delegate ||| AttributeTargets.Struct ||| AttributeTargets.Enum let ExnDecl = AttributeTargets.Class let ModuleDecl = AttributeTargets.Class @@ -908,7 +908,7 @@ let TcConst cenv ty m env c = | SynConst.Measure(_, SynMeasure.Anon _) -> (mkAppTy tcr [TType_measure (Measure.Var (NewAnonTypar (TyparKind.Measure, m, TyparRigidity.Anon, (if iszero then NoStaticReq else HeadTypeStaticReq), TyparDynamicReq.No)))]) - | SynConst.Measure(_, ms) -> mkAppTy tcr [TType_measure (tcMeasure ms)] + | SynConst.Measure(_, ms) -> mkAppTy tcr [TType_measure (tcMeasure ms)] | _ -> mkAppTy tcr [TType_measure Measure.One] unif measureTy @@ -919,19 +919,19 @@ let TcConst cenv ty m env c = | SynConst.Int16 i -> unif cenv.g.int16_ty; Const.Int16 i | SynConst.Int32 i -> unif cenv.g.int_ty; Const.Int32 i | SynConst.Int64 i -> unif cenv.g.int64_ty; Const.Int64 i - | SynConst.IntPtr i -> unif cenv.g.nativeint_ty; Const.IntPtr i + | SynConst.IntPtr i -> unif cenv.g.nativeint_ty; Const.IntPtr i | SynConst.Byte i -> unif cenv.g.byte_ty; Const.Byte i | SynConst.UInt16 i -> unif cenv.g.uint16_ty; Const.UInt16 i | SynConst.UInt32 i -> unif cenv.g.uint32_ty; Const.UInt32 i | SynConst.UInt64 i -> unif cenv.g.uint64_ty; Const.UInt64 i | SynConst.UIntPtr i -> unif cenv.g.unativeint_ty; Const.UIntPtr i | SynConst.Measure(SynConst.Single f, _) | SynConst.Single f -> unifyMeasureArg (f=0.0f) cenv.g.pfloat32_tcr c; Const.Single f - | SynConst.Measure(SynConst.Double f, _) | SynConst.Double f -> unifyMeasureArg (f=0.0) cenv.g.pfloat_tcr c; Const.Double f - | SynConst.Measure(SynConst.Decimal s, _) | SynConst.Decimal s -> unifyMeasureArg false cenv.g.pdecimal_tcr c; Const.Decimal s - | SynConst.Measure(SynConst.SByte i, _) | SynConst.SByte i -> unifyMeasureArg (i=0y) cenv.g.pint8_tcr c; Const.SByte i - | SynConst.Measure(SynConst.Int16 i, _) | SynConst.Int16 i -> unifyMeasureArg (i=0s) cenv.g.pint16_tcr c; Const.Int16 i - | SynConst.Measure(SynConst.Int32 i, _) | SynConst.Int32 i -> unifyMeasureArg (i=0) cenv.g.pint_tcr c; Const.Int32 i - | SynConst.Measure(SynConst.Int64 i, _) | SynConst.Int64 i -> unifyMeasureArg (i=0L) cenv.g.pint64_tcr c; Const.Int64 i + | SynConst.Measure(SynConst.Double f, _) | SynConst.Double f -> unifyMeasureArg (f=0.0) cenv.g.pfloat_tcr c; Const.Double f + | SynConst.Measure(SynConst.Decimal s, _) | SynConst.Decimal s -> unifyMeasureArg false cenv.g.pdecimal_tcr c; Const.Decimal s + | SynConst.Measure(SynConst.SByte i, _) | SynConst.SByte i -> unifyMeasureArg (i=0y) cenv.g.pint8_tcr c; Const.SByte i + | SynConst.Measure(SynConst.Int16 i, _) | SynConst.Int16 i -> unifyMeasureArg (i=0s) cenv.g.pint16_tcr c; Const.Int16 i + | SynConst.Measure(SynConst.Int32 i, _) | SynConst.Int32 i -> unifyMeasureArg (i=0) cenv.g.pint_tcr c; Const.Int32 i + | SynConst.Measure(SynConst.Int64 i, _) | SynConst.Int64 i -> unifyMeasureArg (i=0L) cenv.g.pint64_tcr c; Const.Int64 i | SynConst.Char c -> unif cenv.g.char_ty; Const.Char c | SynConst.String (s, _) -> unif cenv.g.string_ty; Const.String s | SynConst.UserNum _ -> error (InternalError(FSComp.SR.tcUnexpectedBigRationalConstant(), m)) @@ -945,9 +945,9 @@ let TcFieldInit (_m: range) lit = PatternMatchCompilation.ilFieldToTastConst lit //------------------------------------------------------------------------- // Arities. These serve two roles in the system: -// 1. syntactic arities come from the syntactic forms found +// 1. syntactic arities come from the syntactic forms found // signature files and the syntactic forms of function and member definitions. -// 2. compiled arities representing representation choices w.r.t. internal representations of +// 2. compiled arities representing representation choices w.r.t. internal representations of // functions and members. //------------------------------------------------------------------------- @@ -1008,11 +1008,11 @@ let ComputeLogicalName (id: Ident) memberFlags = | MemberKind.Constructor -> ".ctor" | MemberKind.Member -> match id.idText with - | (".ctor" | ".cctor") as r -> errorR(Error(FSComp.SR.tcInvalidMemberNameCtor(), id.idRange)); r + | (".ctor" | ".cctor") as r -> errorR(Error(FSComp.SR.tcInvalidMemberNameCtor(), id.idRange)); r | r -> r - | MemberKind.PropertyGetSet -> error(InternalError(FSComp.SR.tcMemberKindPropertyGetSetNotExpected(), id.idRange)) - | MemberKind.PropertyGet -> "get_" + id.idText - | MemberKind.PropertySet -> "set_" + id.idText + | MemberKind.PropertyGetSet -> error(InternalError(FSComp.SR.tcMemberKindPropertyGetSetNotExpected(), id.idRange)) + | MemberKind.PropertyGet -> "get_" + id.idText + | MemberKind.PropertySet -> "set_" + id.idText /// ValMemberInfoTransient(memberInfo, logicalName, compiledName) type ValMemberInfoTransient = ValMemberInfoTransient of ValMemberInfo * string * string @@ -1020,7 +1020,7 @@ type ValMemberInfoTransient = ValMemberInfoTransient of ValMemberInfo * string * /// Make the unique "name" for a member. // // optImplSlotTy = None (for classes) or Some ty (when implementing interface type ty) -let MakeMemberDataAndMangledNameForMemberVal(g, tcref, isExtrinsic, attrs, optImplSlotTys, memberFlags, valSynData, id, isCompGen) = +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 = @@ -1109,26 +1109,26 @@ type DeclKind = static member IsModuleOrMemberOrExtensionBinding x = match x with | ModuleOrMemberBinding -> true - | IntrinsicExtensionBinding -> true + | IntrinsicExtensionBinding -> true | ExtrinsicExtensionBinding -> true | ClassLetBinding _ -> false | ObjectExpressionOverrideBinding -> false | ExpressionBinding -> false - static member MustHaveArity x = DeclKind.IsModuleOrMemberOrExtensionBinding x + static member MustHaveArity x = DeclKind.IsModuleOrMemberOrExtensionBinding x member x.CanBeDllImport = match x with | ModuleOrMemberBinding -> true - | IntrinsicExtensionBinding -> true + | IntrinsicExtensionBinding -> true | ExtrinsicExtensionBinding -> true | ClassLetBinding _ -> true | ObjectExpressionOverrideBinding -> false | ExpressionBinding -> false - static member IsAccessModifierPermitted x = DeclKind.IsModuleOrMemberOrExtensionBinding x + static member IsAccessModifierPermitted x = DeclKind.IsModuleOrMemberOrExtensionBinding x - static member ImplicitlyStatic x = DeclKind.IsModuleOrMemberOrExtensionBinding x + static member ImplicitlyStatic x = DeclKind.IsModuleOrMemberOrExtensionBinding x static member AllowedAttribTargets memberFlagsOpt x = match x with @@ -1140,25 +1140,25 @@ type DeclKind = | Some flags when flags.MemberKind = MemberKind.PropertySet -> AttributeTargets.Property | Some _ -> AttributeTargets.Method | None -> AttributeTargets.Field ||| AttributeTargets.Method ||| AttributeTargets.Property - | IntrinsicExtensionBinding -> AttributeTargets.Method ||| AttributeTargets.Property + | IntrinsicExtensionBinding -> AttributeTargets.Method ||| AttributeTargets.Property | ExtrinsicExtensionBinding -> AttributeTargets.Method ||| AttributeTargets.Property | ClassLetBinding _ -> AttributeTargets.Field ||| AttributeTargets.Method | ExpressionBinding -> enum 0 // indicates attributes not allowed on expression 'let' bindings // Note: now always true - static member CanGeneralizeConstrainedTypars x = + static member CanGeneralizeConstrainedTypars x = match x with | ModuleOrMemberBinding -> true - | IntrinsicExtensionBinding -> true + | IntrinsicExtensionBinding -> true | ExtrinsicExtensionBinding -> true | ClassLetBinding _ -> true | ObjectExpressionOverrideBinding -> true | ExpressionBinding -> true - static member ConvertToLinearBindings x = + static member ConvertToLinearBindings x = match x with | ModuleOrMemberBinding -> true - | IntrinsicExtensionBinding -> true + | IntrinsicExtensionBinding -> true | ExtrinsicExtensionBinding -> true | ClassLetBinding _ -> true | ObjectExpressionOverrideBinding -> true @@ -1205,7 +1205,7 @@ type PrelimValScheme2 = Ident * TypeScheme * PartialValReprInfo option * - ValMemberInfoTransient option * + ValMemberInfoTransient option * bool * ValInline * ValBaseOrThisInfo * @@ -1222,8 +1222,8 @@ type ValScheme = Ident * TypeScheme * ValReprInfo option * - ValMemberInfoTransient option * - bool * // isMutable + ValMemberInfoTransient option * + bool * // isMutable ValInline * ValBaseOrThisInfo * SynAccess option * @@ -1335,7 +1335,7 @@ let PublishValueDefn cenv env declKind (vspec: Val) = let vref = mkLocalValRef vspec tcaug.tcaug_adhoc <- NameMultiMap.add vspec.LogicalName vref tcaug.tcaug_adhoc tcaug.tcaug_adhoc_list.Add (ValRefIsExplicitImpl cenv.g vref, vref) - | _ -> () + | _ -> () let CombineVisibilityAttribs vis1 vis2 m = match vis1 with @@ -1449,7 +1449,7 @@ let MakeAndPublishVal cenv env (altActualParent, inSig, declKind, vrec, vscheme, else let implflags = match TryFindFSharpAttribute cenv.g cenv.g.attrib_MethodImplAttribute attrs with - | Some (Attrib(_, _, [ AttribInt32Arg flags ], _, _, _, _)) -> flags + | Some (Attrib(_, _, [ AttribInt32Arg flags ], _, _, _, _)) -> flags | _ -> 0x0 // MethodImplOptions.NoInlining = 0x8 let NO_INLINING = 0x8 @@ -1674,7 +1674,7 @@ let ChooseCanonicalValSchemeAfterInference g denv valscheme m = let valscheme = ValScheme(id, typeScheme, arityInfo, memberInfoOpt, isMutable, inlineFlag, baseOrThis, vis, compgen, isIncrClass, isTyFunc, hasDeclaredTypars) valscheme -let PlaceTyparsInDeclarationOrder declaredTypars generalizedTypars = +let PlaceTyparsInDeclarationOrder declaredTypars generalizedTypars = declaredTypars @ (generalizedTypars |> List.filter (fun tp -> not (ListSet.contains typarEq tp declaredTypars))) let SetTyparRigid _g denv m (tp: Typar) = @@ -1700,7 +1700,7 @@ let GeneralizeVal cenv denv enclosingDeclaredTypars generalizedTyparsForThisBind // Trim out anything not in type of the value (as opposed to the type of the r.h.s) // This is important when a single declaration binds // multiple generic items, where each item does not use all the polymorphism - // of the r.h.s. , e.g. let x, y = None, [] + // of the r.h.s., e.g. let x, y = None, [] let computeRelevantTypars thruFlag = let ftps = freeInTypeLeftToRight cenv.g thruFlag ty let generalizedTypars = generalizedTyparsForThisBinding |> List.filter (fun tp -> ListSet.contains typarEq tp ftps) @@ -1760,10 +1760,10 @@ let UseSyntacticArity declKind typeScheme partialValReprInfo = // 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 = (fun () -> 1) // [0] or [1]? Answer: [0] -// let f = (fun (a: unit) -> 1) // [0] or [1]? Answer: [1] +// let f () () = 1 // [0;1] or [0;0]? Answer: [0;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] // // The particular choice of [1] for // let f (a: unit) = 1 @@ -1781,12 +1781,12 @@ let UseSyntacticArity declKind typeScheme partialValReprInfo = let CombineSyntacticAndInferredArities g declKind rhsExpr prelimScheme = let (PrelimValScheme2(_, typeScheme, partialValReprInfoOpt, memberInfoOpt, isMutable, _, _, ArgAndRetAttribs(argAttribs, retAttribs), _, _, _)) = prelimScheme match partialValReprInfoOpt, DeclKind.MustHaveArity declKind with - | _ , false -> None - | None , true -> Some(PartialValReprInfo([], ValReprInfo.unnamedRetVal)) + | _, false -> None + | None, true -> Some(PartialValReprInfo([], ValReprInfo.unnamedRetVal)) // Don't use any expression information for members, where syntax dictates the arity completely | _ when memberInfoOpt.IsSome -> partialValReprInfoOpt - | Some(partialValReprInfoFromSyntax), true -> + | Some(partialValReprInfoFromSyntax), true -> let (PartialValReprInfo(curriedArgInfosFromSyntax, retInfoFromSyntax)) = partialValReprInfoFromSyntax let partialArityInfo = if isMutable then @@ -1835,10 +1835,10 @@ let UseNoArity prelimScheme = BuildValScheme ExpressionBinding None prelimScheme let MakeSimpleVals cenv env names = - let tyschemes = DontGeneralizeVals names + let tyschemes = DontGeneralizeVals names let valSchemes = NameMap.map UseNoArity tyschemes - let values = MakeAndPublishVals cenv env (ParentNone, false, ExpressionBinding, ValNotInRecScope, valSchemes, [], XmlDoc.Empty, None) - let vspecMap = NameMap.map fst values + let values = MakeAndPublishVals cenv env (ParentNone, false, ExpressionBinding, ValNotInRecScope, valSchemes, [], XmlDoc.Empty, None) + let vspecMap = NameMap.map fst values values, vspecMap let MakeAndPublishSimpleVals cenv env m names mergeNamesInOneNameresEnv = @@ -1894,7 +1894,7 @@ let MakeAndPublishSimpleVals cenv env m names mergeNamesInOneNameresEnv = values, vspecMap - let envinner = AddLocalValMap cenv.tcSink m vspecMap env + let envinner = AddLocalValMap cenv.tcSink m vspecMap env envinner, values, vspecMap @@ -2028,7 +2028,7 @@ let rec ApplyUnionCaseOrExn (makerForUnionCase, makerForExnTag) m cenv env overa let ad = env.eAccessRights match item with | Item.ExnCase ecref -> - CheckEntityAttributes cenv.g ecref m |> CommitOperationResult + CheckEntityAttributes cenv.g ecref m |> CommitOperationResult UnifyTypes cenv env m overallTy cenv.g.exn_ty CheckTyconAccessible cenv.amap m ad ecref |> ignore let mkf = makerForExnTag ecref @@ -2158,7 +2158,7 @@ module GeneralizationHelpers = canGeneralizeOp && List.forall (IsGeneralizableValue g) args - | Expr.LetRec(binds, body, _, _) -> + | Expr.LetRec(binds, body, _, _) -> binds |> List.forall (fun b -> not b.Var.IsMutable) && binds |> List.forall (fun b -> IsGeneralizableValue g b.Expr) && IsGeneralizableValue g body @@ -2363,7 +2363,7 @@ module GeneralizationHelpers = // can't infer extra polymorphism for properties | MemberKind.PropertyGet | MemberKind.PropertySet -> false // can't infer extra polymorphism for class constructors - | MemberKind.ClassConstructor -> false + | MemberKind.ClassConstructor -> false // can't infer extra polymorphism for constructors | MemberKind.Constructor -> false // feasible to infer extra polymorphism @@ -2410,17 +2410,17 @@ let ComputeInlineFlag memFlagsOption isInline isMutable m = // // This is because the first lambda in a function definition "let F x = e" // now looks like a constructor application, i.e. let (F x) = e ... -// also let A.F x = e ... -// also let f x = e ... +// also let A.F x = e ... +// also let f x = e ... // // The other parts turn property definitions into method definitions. //------------------------------------------------------------------------- // NormalizedBindingRhs records the r.h.s. of a binding after some munging just before type checking. -// NOTE: This is a bit of a mess. In the early implementation of F# we decided +// NOTE: This is a bit of a mess. In the early implementation of F# we decided // to have the parser convert "let f x = e" into -// "let f = fun x -> e". This is called "pushing" a pattern across to the right hand side. Complex +// "let f = fun x -> e". This is called "pushing" a pattern across to the right hand side. Complex // patterns (e.g. non-tuple patterns) result in a computation on the right. // However, this approach really isn't that great - especially since // the language is now considerably more complex, e.g. we use @@ -2448,8 +2448,8 @@ type NormalizedBinding = | NormalizedBinding of SynAccess option * SynBindingKind * - bool * (* pesudo/mustinline value? *) - bool * (* mutable *) + bool * (* pesudo/mustinline value? *) + bool * (* mutable *) SynAttributes * XmlDoc * SynValTyparDecls * @@ -2486,12 +2486,12 @@ module BindingNormalization = if memberFlags.IsInstance then // instance method without adhoc "this" argument error(Error(FSComp.SR.tcInstanceMemberRequiresTarget(), m)) - match args, memberFlags.MemberKind with - | _, MemberKind.PropertyGetSet -> error(Error(FSComp.SR.tcUnexpectedPropertyInSyntaxTree(), m)) + match args, memberFlags.MemberKind with + | _, MemberKind.PropertyGetSet -> error(Error(FSComp.SR.tcUnexpectedPropertyInSyntaxTree(), m)) | [], MemberKind.ClassConstructor -> error(Error(FSComp.SR.tcStaticInitializerRequiresArgument(), m)) - | [], MemberKind.Constructor -> error(Error(FSComp.SR.tcObjectConstructorRequiresArgument(), m)) + | [], MemberKind.Constructor -> error(Error(FSComp.SR.tcObjectConstructorRequiresArgument(), m)) | [_], MemberKind.ClassConstructor - | [_], MemberKind.Constructor -> MakeNormalizedStaticOrValBinding cenv ValOrMemberBinding id vis typars args rhsExpr valSynData + | [_], MemberKind.Constructor -> MakeNormalizedStaticOrValBinding cenv ValOrMemberBinding id vis typars args rhsExpr valSynData // Static property declared using 'static member P = expr': transformed to a method taking a "unit" argument // static property: these transformed into methods taking one "unit" argument | [], MemberKind.Member -> @@ -2508,10 +2508,10 @@ module BindingNormalization = if not memberFlags.IsInstance then // static method with adhoc "this" argument error(Error(FSComp.SR.tcStaticMemberShouldNotHaveThis(), m)) - match args, memberFlags.MemberKind with - | _, MemberKind.ClassConstructor -> error(Error(FSComp.SR.tcExplicitStaticInitializerSyntax(), m)) - | _, MemberKind.Constructor -> error(Error(FSComp.SR.tcExplicitObjectConstructorSyntax(), m)) - | _, MemberKind.PropertyGetSet -> error(Error(FSComp.SR.tcUnexpectedPropertySpec(), m)) + match args, memberFlags.MemberKind with + | _, MemberKind.ClassConstructor -> error(Error(FSComp.SR.tcExplicitStaticInitializerSyntax(), m)) + | _, MemberKind.Constructor -> error(Error(FSComp.SR.tcExplicitObjectConstructorSyntax(), m)) + | _, MemberKind.PropertyGetSet -> error(Error(FSComp.SR.tcUnexpectedPropertySpec(), m)) // Instance property declared using 'x.Member': transformed to methods taking a "this" and a "unit" argument // We push across the 'this' arg in mk_rec_binds | [], MemberKind.Member -> @@ -2539,7 +2539,7 @@ module BindingNormalization = | None -> match ResolvePatternLongIdent cenv.tcSink nameResolver AllIdsOK true m ad env.eNameResEnv TypeNameResolutionInfo.Default longId with | Item.NewDef id -> - if id.idText = opNameCons then + if id.idText = opNameCons then NormalizedBindingPat(pat, rhsExpr, valSynData, typars) else if isObjExprBinding = ObjExprBinding then @@ -2552,8 +2552,8 @@ module BindingNormalization = match longId with // x.Member in member binding patterns. | [thisId;memberId] -> NormalizeInstanceMemberBinding cenv memberFlags valSynData thisId memberId toolId vis typars args m rhsExpr - | [memberId] -> NormalizeStaticMemberBinding cenv memberFlags valSynData memberId vis typars args m rhsExpr - | _ -> NormalizedBindingPat(pat, rhsExpr, valSynData, typars) + | [memberId] -> NormalizeStaticMemberBinding cenv memberFlags valSynData memberId vis typars args m rhsExpr + | _ -> NormalizedBindingPat(pat, rhsExpr, valSynData, typars) // Object constructors are normalized in TcLetrec // Here we are normalizing member definitions with simple (not long) ids, @@ -2598,7 +2598,7 @@ module EventDeclarationNormalization = // reconstitute valSynInfo by adding the argument let argInfos = match argInfos with - | [[thisArgInfo];[]] -> [[thisArgInfo];SynInfo.unnamedTopArg] // instance property getter + | [[thisArgInfo];[]] -> [[thisArgInfo];SynInfo.unnamedTopArg] // instance property getter | [[]] -> [SynInfo.unnamedTopArg] // static property getter | _ -> error(BadEventTransformation(m)) @@ -2623,7 +2623,7 @@ module EventDeclarationNormalization = match declPattern with | SynPat.FromParseError(p, _) -> RenameBindingPattern f p | SynPat.Typed(pat', _, _) -> RenameBindingPattern f pat' - | SynPat.Named (SynPat.Wild m1, id, x2, vis2, m) -> SynPat.Named (SynPat.Wild m1, ident(f id.idText, id.idRange) , x2, vis2, m) + | SynPat.Named (SynPat.Wild m1, id, x2, vis2, m) -> SynPat.Named (SynPat.Wild m1, ident(f id.idText, id.idRange), x2, vis2, m) | SynPat.InstanceMember(thisId, id, toolId, vis2, m) -> SynPat.InstanceMember(thisId, ident(f id.idText, id.idRange), toolId, vis2, m) | _ -> error(Error(FSComp.SR.tcOnlySimplePatternsInLetRec(), declPattern.Range)) @@ -2719,7 +2719,7 @@ let TcValEarlyGeneralizationConsistencyCheck cenv (env: TcEnv) (v: Val, vrec, ti //printfn "running post-inference check for '%s'" v.DisplayName //printfn "tau = '%s'" (DebugPrint.showType tau) //printfn "vty = '%s'" (DebugPrint.showType vty) - let tpsorig, tau2 = tryDestForallTy cenv.g vty + let tpsorig, tau2 = tryDestForallTy cenv.g vty //printfn "tau2 = '%s'" (DebugPrint.showType tau2) if not (isNil tpsorig) then let tpsorig = NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g tpsorig @@ -2740,9 +2740,9 @@ let TcValEarlyGeneralizationConsistencyCheck cenv (env: TcEnv) (v: Val, vrec, ti /// F# object model member, in which case the optInst is the type instantiation /// inferred by member overload resolution, and vrefFlags indicate if the /// member is being used in a special way, i.e. may be one of: -/// | CtorValUsedAsSuperInit "inherit Panel()" -/// | CtorValUsedAsSelfInit "new() = new OwnType(3)" -/// | VSlotDirectCall "base.OnClick(eventArgs)" +/// | CtorValUsedAsSuperInit "inherit Panel()" +/// | CtorValUsedAsSelfInit "new() = new OwnType(3)" +/// | VSlotDirectCall "base.OnClick(eventArgs)" let TcVal checkAttributes cenv env tpenv (vref: ValRef) optInst optAfterResolution m = let (tpsorig, _, _, _, tinst, _) as res = let v = vref.Deref @@ -2750,7 +2750,7 @@ let TcVal checkAttributes cenv env tpenv (vref: ValRef) optInst optAfterResoluti v.SetHasBeenReferenced() CheckValAccessible m env.eAccessRights vref if checkAttributes then - CheckValAttributes cenv.g vref m |> CommitOperationResult + CheckValAttributes cenv.g vref m |> CommitOperationResult let vty = vref.Type // byref-typed values get dereferenced if isByrefTy cenv.g vty then @@ -2769,7 +2769,7 @@ let TcVal checkAttributes cenv env tpenv (vref: ValRef) optInst optAfterResoluti | None -> // References to 'this' in classes get dereferenced from their implicit reference cell and poked - if v.BaseOrThisInfo = CtorThisVal && isRefCellTy cenv.g vty then + if v.BaseOrThisInfo = CtorThisVal && isRefCellTy cenv.g vty then let exprForVal = exprForValRef m vref //if AreWithinCtorPreConstruct env then // warning(SelfRefObjCtor(AreWithinImplicitCtor env, m)) @@ -2789,7 +2789,7 @@ let TcVal checkAttributes cenv env tpenv (vref: ValRef) optInst optAfterResoluti match vrec with | ValInRecScope false -> - let tpsorig, tau = vref.TypeScheme + let tpsorig, tau = vref.TypeScheme let tinst = tpsorig |> List.map mkTyparTy tpsorig, NormalValUse, tinst, tau, tpenv | ValInRecScope true @@ -2804,7 +2804,7 @@ let TcVal checkAttributes cenv env tpenv (vref: ValRef) optInst optAfterResoluti warning(Error(FSComp.SR.tcDoesNotAllowExplicitTypeArguments(v.DisplayName), m)) match vrec with | ValInRecScope false -> - let tpsorig, tau = vref.TypeScheme + let tpsorig, tau = vref.TypeScheme 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)) @@ -2834,7 +2834,7 @@ let TcVal checkAttributes cenv env tpenv (vref: ValRef) optInst optAfterResoluti valRefEq cenv.g vref cenv.g.splice_expr_vref || valRefEq cenv.g vref cenv.g.splice_raw_expr_vref - let exprForVal = RecordUseOfRecValue cenv vrec vref exprForVal m + let exprForVal = RecordUseOfRecValue cenv vrec vref exprForVal m tpsorig, exprForVal, isSpecial, tau, tinst, tpenv @@ -2903,7 +2903,7 @@ type ApplicableExpr = member x.Expr = match x with - | ApplicableExpr(_, e, _) -> e + | ApplicableExpr(_, e, _) -> e let MakeApplicableExprNoFlex cenv expr = ApplicableExpr (cenv, expr, true) @@ -2914,7 +2914,7 @@ let MakeApplicableExprNoFlex cenv expr = /// De-condensation is determined BEFORE any arguments are checked. Thus /// let f (x:'a) (y:'a) = () /// -/// f (new obj()) "string" +/// f (new obj()) "string" /// /// does not type check (the argument instantiates 'a to "obj" but there is no flexibility on the /// second argument position. @@ -3049,7 +3049,7 @@ let BuildDisposableCleanup cenv env m (v: Val) = let ad = env.eAccessRights let disposeMethod = match TryFindIntrinsicOrExtensionMethInfo cenv env m ad "Dispose" cenv.g.system_IDisposable_ty with - | [x] -> x + | [x] -> x | _ -> error(InternalError(FSComp.SR.tcCouldNotFindIDisposable(), m)) @@ -3074,7 +3074,7 @@ let BuildOffsetToStringData cenv env m = let ad = env.eAccessRights let offsetToStringDataMethod = match TryFindIntrinsicOrExtensionMethInfo cenv env m ad "get_OffsetToStringData" cenv.g.system_RuntimeHelpers_ty with - | [x] -> x + | [x] -> x | _ -> error(Error(FSComp.SR.tcCouldNotFindOffsetToStringData(), m)) let offsetExpr, _ = BuildPossiblyConditionalMethodCall cenv env NeverMutates m false offsetToStringDataMethod NormalValUse [] [] [] @@ -3149,7 +3149,7 @@ let (|BinOpExpr|_|) e = let (|SimpleEqualsExpr|_|) e = match e with - | BinOpExpr(opId, a, b) when opId.idText = opNameEquals -> Some (a, b) + | BinOpExpr(opId, a, b) when opId.idText = opNameEquals -> Some (a, b) | _ -> None // For join clauses that join on nullable, we syntactically insert the creation of nullable values on the appropriate side of the condition, @@ -3272,7 +3272,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr let tryType (exprToSearchForGetEnumeratorAndItem, tyToSearchForGetEnumeratorAndItem) = match findMethInfo true m "GetEnumerator" tyToSearchForGetEnumeratorAndItem with | Exception e -> Exception e - | Result getEnumerator_minfo -> + | Result getEnumerator_minfo -> let getEnumerator_minst = FreshenMethInfo m getEnumerator_minfo let retTypeOfGetEnumerator = getEnumerator_minfo.GetFSharpReturnTy(cenv.amap, m, getEnumerator_minst) @@ -3280,11 +3280,11 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr match findMethInfo false m "MoveNext" retTypeOfGetEnumerator with | Exception e -> Exception e - | Result moveNext_minfo -> + | Result moveNext_minfo -> let moveNext_minst = FreshenMethInfo m moveNext_minfo let retTypeOfMoveNext = moveNext_minfo.GetFSharpReturnTy(cenv.amap, m, moveNext_minst) - if not (typeEquiv cenv.g cenv.g.bool_ty retTypeOfMoveNext) then err false retTypeOfGetEnumerator else + if not (typeEquiv cenv.g cenv.g.bool_ty retTypeOfMoveNext) then err false retTypeOfGetEnumerator else if hasArgs moveNext_minfo moveNext_minst then err false retTypeOfGetEnumerator else match findMethInfo false m "get_Current" retTypeOfGetEnumerator with @@ -3293,7 +3293,7 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr let get_Current_minst = FreshenMethInfo m get_Current_minfo if hasArgs get_Current_minfo get_Current_minst then err false retTypeOfGetEnumerator else - let enumElemTy = get_Current_minfo.GetFSharpReturnTy(cenv.amap, m, get_Current_minst) + let enumElemTy = get_Current_minfo.GetFSharpReturnTy(cenv.amap, m, get_Current_minst) // Compute the element type of the strongly typed enumerator // @@ -3352,8 +3352,8 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr else Tastops.mkCompGenLocal m "enumerator" retTypeOfGetEnumerator, retTypeOfGetEnumerator - let getEnumExpr, getEnumTy = - let (getEnumExpr, getEnumTy) as res = BuildPossiblyConditionalMethodCall cenv env PossiblyMutates m false getEnumerator_minfo NormalValUse getEnumerator_minst [exprToSearchForGetEnumeratorAndItem] [] + let getEnumExpr, getEnumTy = + let (getEnumExpr, getEnumTy) as res = BuildPossiblyConditionalMethodCall cenv env PossiblyMutates m false getEnumerator_minfo NormalValUse getEnumerator_minst [exprToSearchForGetEnumeratorAndItem] [] if not isEnumeratorTypeStruct || localAlloc then res else // wrap enumerators that are represented as mutable structs into ref cells @@ -3361,9 +3361,9 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr let getEnumTy = mkRefCellTy cenv.g getEnumTy getEnumExpr, getEnumTy - let guardExpr , guardTy = BuildPossiblyConditionalMethodCall cenv env DefinitelyMutates m false moveNext_minfo NormalValUse moveNext_minst [enumeratorExpr] [] - let currentExpr, currentTy = BuildPossiblyConditionalMethodCall cenv env DefinitelyMutates m true get_Current_minfo NormalValUse get_Current_minst [enumeratorExpr] [] - let currentExpr = mkCoerceExpr(currentExpr, enumElemTy, currentExpr.Range, currentTy) + let guardExpr, guardTy = BuildPossiblyConditionalMethodCall cenv env DefinitelyMutates m false moveNext_minfo NormalValUse moveNext_minst [enumeratorExpr] [] + let currentExpr, currentTy = BuildPossiblyConditionalMethodCall cenv env DefinitelyMutates m true get_Current_minfo NormalValUse get_Current_minst [enumeratorExpr] [] + let currentExpr = mkCoerceExpr(currentExpr, enumElemTy, currentExpr.Range, currentTy) let currentExpr, enumElemTy = // Implicitly dereference byref for expr 'for x in ...' if isByrefTy cenv.g enumElemTy then @@ -3377,13 +3377,13 @@ let AnalyzeArbitraryExprAsEnumerable cenv (env: TcEnv) localAlloc m exprty expr // First try the original known static type match (if isArray1DTy cenv.g exprty then Exception (Failure "") else tryType (expr, exprty)) with - | Result res -> res + | Result res -> res | Exception e -> let probe ty = if (AddCxTypeMustSubsumeTypeUndoIfFailed env.DisplayEnv cenv.css m ty exprty) then match tryType (mkCoerceExpr(expr, ty, expr.Range, exprty), ty) with - | Result res -> Some res + | Result res -> Some res | Exception e -> PreserveStackTrace(e) raise e @@ -3699,9 +3699,9 @@ type PreInitializationGraphEliminationBinding = /// Check for safety and determine if we need to insert lazy thunks let EliminateInitializationGraphs (getTyconBinds: 'TyconDataIn -> PreInitializationGraphEliminationBinding list) - (morphTyconBinds: (PreInitializationGraphEliminationBinding list -> Binding list) -> 'TyconDataIn -> 'TyconDataOut) + (morphTyconBinds: (PreInitializationGraphEliminationBinding list -> Binding list) -> 'TyconDataIn -> 'TyconDataOut) (getLetBinds: 'LetDataIn list -> PreInitializationGraphEliminationBinding list) - (morphLetBinds: (PreInitializationGraphEliminationBinding list -> Binding list) -> 'LetDataIn list -> Binding list) + (morphLetBinds: (PreInitializationGraphEliminationBinding list -> Binding list) -> 'LetDataIn list -> Binding list) g mustHaveArity denv (fixupsAndBindingsWithoutLaziness: MutRecShape<_, _, _, _, _> list) bindsm = @@ -3756,12 +3756,12 @@ let EliminateInitializationGraphs // NOTE: we can't fixup recursive references inside delegates since the closure delegee of a delegate is not accessible // from outside. Object expressions implementing interfaces can, on the other hand, be fixed up. See FSharp 1.0 bug 1469 if isInterfaceTy g ty then - List.iter (fun (TObjExprMethod(_, _, _, _, e, _)) -> checkDelayed st e) overrides - List.iter (snd >> List.iter (fun (TObjExprMethod(_, _, _, _, e, _)) -> checkDelayed st e)) extraImpls + List.iter (fun (TObjExprMethod(_, _, _, _, e, _)) -> checkDelayed st e) overrides + List.iter (snd >> List.iter (fun (TObjExprMethod(_, _, _, _, e, _)) -> checkDelayed st e)) extraImpls else CheckExpr (strict st) e - List.iter (fun (TObjExprMethod(_, _, _, _, e, _)) -> CheckExpr (lzy (strict st)) e) overrides - List.iter (snd >> List.iter (fun (TObjExprMethod(_, _, _, _, e, _)) -> CheckExpr (lzy (strict st)) e)) extraImpls + List.iter (fun (TObjExprMethod(_, _, _, _, e, _)) -> CheckExpr (lzy (strict st)) e) overrides + List.iter (snd >> List.iter (fun (TObjExprMethod(_, _, _, _, e, _)) -> CheckExpr (lzy (strict st)) e)) extraImpls // Expressions where fixups may be needed | Expr.Val (v, _, m) -> CheckValRef st v m @@ -3772,7 +3772,7 @@ let EliminateInitializationGraphs // Composite expressions | Expr.Const _ -> () - | Expr.LetRec (binds, e, _, _) -> + | Expr.LetRec (binds, e, _, _) -> binds |> List.iter (CheckBinding (strict st)) CheckExpr (strict st) e | Expr.Let (bind, e, _, _) -> @@ -3787,13 +3787,13 @@ let EliminateInitializationGraphs // Binary expressions | Expr.Sequential (e1, e2, _, _, _) | Expr.StaticOptimization (_, e1, e2, _) -> - CheckExpr (strict st) e1; CheckExpr (strict st) e2 + CheckExpr (strict st) e1; CheckExpr (strict st) e2 // n-ary expressions - | Expr.Op(op, _, args, m) -> CheckExprOp st op m; List.iter (CheckExpr (strict st)) args + | Expr.Op(op, _, args, m) -> CheckExprOp st op m; List.iter (CheckExpr (strict st)) args // misc | Expr.Link(eref) -> CheckExpr st !eref - | Expr.TyChoose (_, b, _) -> CheckExpr st b - | Expr.Quote _ -> () + | Expr.TyChoose (_, b, _) -> CheckExpr st b + | Expr.Quote _ -> () and CheckBinding st (TBind(_, e, _)) = CheckExpr st e and CheckDecisionTree st = function @@ -3868,11 +3868,11 @@ let EliminateInitializationGraphs let vty = (mkLazyTy g ty) let fty = (g.unit_ty --> ty) - let flazy, felazy = Tastops.mkCompGenLocal m v.LogicalName fty + let flazy, felazy = Tastops.mkCompGenLocal m v.LogicalName fty let frhs = mkUnitDelayLambda g m e if mustHaveArity then flazy.SetValReprInfo (Some(InferArityOfExpr g AllowTypeDirectedDetupling.Yes fty [] [] frhs)) - let vlazy, velazy = Tastops.mkCompGenLocal m v.LogicalName vty + let vlazy, velazy = Tastops.mkCompGenLocal m v.LogicalName vty let vrhs = (mkLazyDelayed g m ty felazy) if mustHaveArity then vlazy.SetValReprInfo (Some(InferArityOfExpr g AllowTypeDirectedDetupling.Yes vty [] [] vrhs)) @@ -3917,7 +3917,7 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = | Some safeInitVal -> let ty = tyOfExpr g recdExpr let thisExpr = mkGetArg0 m ty - let setExpr = mkRefCellSet g m ty (exprForValRef m (mkLocalValRef safeInitVal)) thisExpr + let setExpr = mkRefCellSet g m ty (exprForValRef m (mkLocalValRef safeInitVal)) thisExpr Expr.Sequential(recdExpr, setExpr, ThenDoSeq, SuppressSequencePointOnExprOfSequential, m) let recdExpr = match ctorInfo.safeInitInfo with @@ -3938,19 +3938,19 @@ let CheckAndRewriteObjectCtor g env (ctorLambaExpr: Expr) = | Expr.Op(TOp.Recd(RecdExprIsObjInit, _), _, _, _) -> rewriteConstruction expr // = "a; " - | Expr.Sequential(a, body, NormalSeq, spSeq, b) -> Expr.Sequential(a, checkAndRewrite body, NormalSeq, spSeq, b) + | Expr.Sequential(a, body, NormalSeq, spSeq, b) -> Expr.Sequential(a, checkAndRewrite body, NormalSeq, spSeq, b) // = " then " | Expr.Sequential(body, a, ThenDoSeq, spSeq, b) -> Expr.Sequential(checkAndRewrite body, a, ThenDoSeq, spSeq, b) // = "let pat = expr in " - | Expr.Let(bind, body, m, _) -> mkLetBind m bind (checkAndRewrite body) + | Expr.Let(bind, body, m, _) -> mkLetBind m bind (checkAndRewrite body) // The constructor is a sequence "let pat = expr in " - | Expr.Match(spBind, a, b, targets, c, d) -> Expr.Match(spBind, a, b, (targets |> Array.map (fun (TTarget(vs, body, spTarget)) -> TTarget(vs, checkAndRewrite body, spTarget))), c, d) + | Expr.Match(spBind, a, b, targets, c, d) -> Expr.Match(spBind, a, b, (targets |> Array.map (fun (TTarget(vs, body, spTarget)) -> TTarget(vs, checkAndRewrite body, spTarget))), c, d) // = "let rec binds in " - | Expr.LetRec(a, body, _, _) -> Expr.LetRec (a, checkAndRewrite body , m, NewFreeVarsCache()) + | Expr.LetRec(a, body, _, _) -> Expr.LetRec (a, checkAndRewrite body, m, NewFreeVarsCache()) // = "new C(...)" | Expr.App(f, b, c, d, m) -> @@ -4002,9 +4002,9 @@ let buildApp cenv expr resultTy arg m = match expr, arg with // Special rule for building applications of the 'x && y' operator - | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [x0], _), _) , _ + | ApplicableExpr(_, Expr.App(Expr.Val(vf, _, _), _, _, [x0], _), _), _ when valRefEq g vf g.and_vref - || valRefEq g vf g.and2_vref -> + || valRefEq g vf g.and2_vref -> MakeApplicableExprNoFlex cenv (mkLazyAnd g m x0 arg), resultTy // Special rule for building applications of the 'x || y' operator @@ -4065,7 +4065,7 @@ let buildApp cenv expr resultTy arg m = let wrap, e1a', _readonly, _writeonly = mkExprAddrOfExpr g true false AddressOfOp arg (Some(vf)) m MakeApplicableExprNoFlex cenv (wrap(e1a')), resultTy - | _ when isByrefTy g resultTy -> + | _ when isByrefTy g resultTy -> // Handle byref returns, byref-typed returns get implicitly dereferenced let v, _ = mkCompGenLocal m "byrefReturn" resultTy let expr = expr.SupplyArgument(arg, m) @@ -4189,7 +4189,7 @@ type RecursiveBindingInfo = Val * ExplicitTyparInfo * PartialValReprInfo * - ValMemberInfoTransient option * + ValMemberInfoTransient option * Val option * Val option * SafeInitData * @@ -4198,12 +4198,12 @@ type RecursiveBindingInfo = DeclKind member x.EnclosingDeclaredTypars = let (RBInfo(_, _, enclosingDeclaredTypars, _, _, _, _, _, _, _, _, _, _, _)) = x in enclosingDeclaredTypars - member x.Val = let (RBInfo(_, _, _, _, vspec, _, _, _, _, _, _, _, _, _)) = x in vspec - member x.ExplicitTyparInfo = let (RBInfo(_, _, _, _, _, flex, _, _, _, _, _, _, _, _)) = x in flex - member x.DeclaredTypars = let (ExplicitTyparInfo(_, declaredTypars, _)) = x.ExplicitTyparInfo in declaredTypars - member x.Index = let (RBInfo(i, _, _, _, _, _, _, _, _, _, _, _, _, _)) = x in i - member x.ContainerInfo = let (RBInfo(_, c, _, _, _, _, _, _, _, _, _, _, _, _)) = x in c - member x.DeclKind = let (RBInfo(_, _, _, _, _, _, _, _, _, _, _, _, _, declKind)) = x in declKind + member x.Val = let (RBInfo(_, _, _, _, vspec, _, _, _, _, _, _, _, _, _)) = x in vspec + member x.ExplicitTyparInfo = let (RBInfo(_, _, _, _, _, flex, _, _, _, _, _, _, _, _)) = x in flex + member x.DeclaredTypars = let (ExplicitTyparInfo(_, declaredTypars, _)) = x.ExplicitTyparInfo in declaredTypars + member x.Index = let (RBInfo(i, _, _, _, _, _, _, _, _, _, _, _, _, _)) = x in i + member x.ContainerInfo = let (RBInfo(_, c, _, _, _, _, _, _, _, _, _, _, _, _)) = x in c + member x.DeclKind = let (RBInfo(_, _, _, _, _, _, _, _, _, _, _, _, _, declKind)) = x in declKind type PreCheckingRecursiveBinding = { SyntacticBinding: NormalizedBinding @@ -4242,7 +4242,7 @@ let GetInstanceMemberThisVariable (v: Val, x) = match e with | Expr.TyLambda (_, _, b, _, _) -> firstArg b | Expr.TyChoose (_, b, _) -> firstArg b - | Expr.Lambda (_, _, _, [v], _, _, _) -> Some v + | Expr.Lambda (_, _, _, [v], _, _, _) -> Some v | _ -> failwith "GetInstanceMemberThisVariable: instance member did not have expected internal form" firstArg x @@ -4315,7 +4315,7 @@ let rec TcTyparConstraint ridx cenv newOk checkCxs occ (env: TcEnv) tpenv c = | WhereTyparSupportsMember(tps, memSpfn, m) -> let traitInfo, tpenv = TcPseudoMemberSpec cenv newOk env tps tpenv memSpfn m match traitInfo with - | TTrait(objtys, ".ctor", memberFlags, argTys, returnTy, _) when memberFlags.MemberKind = MemberKind.Constructor -> + | TTrait(objtys, ".ctor", memberFlags, argTys, returnTy, _) when memberFlags.MemberKind = MemberKind.Constructor -> match objtys, argTys with | [ty], [] when typeEquiv cenv.g ty (GetFSharpViewOfReturnType cenv.g returnTy) -> AddCxTypeMustSupportDefaultCtor env.DisplayEnv cenv.css m NoTrace ty @@ -4343,7 +4343,7 @@ and TcPseudoMemberSpec cenv newOk env synTypes tpenv memSpfn m = let memberConstraintTypars, _ = tryDestForallTy cenv.g memberConstraintTy let topValInfo = TranslatePartialArity memberConstraintTypars partialValReprInfo let _, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm cenv.g topValInfo memberConstraintTy m - //if curriedArgInfos.Length > 1 then error(Error(FSComp.SR.tcInvalidConstraint(), m)) + //if curriedArgInfos.Length > 1 then error(Error(FSComp.SR.tcInvalidConstraint(), m)) let argTys = List.concat curriedArgInfos let argTys = List.map fst argTys let logicalCompiledName = ComputeLogicalName id memberFlags @@ -4583,7 +4583,7 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscope | SynType.LongIdent(LongIdentWithDots(tc, _) as lidwd) -> let m = lidwd.Range let ad = env.eAccessRights - let tcref = ForceRaise(ResolveTypeLongIdent cenv.tcSink cenv.nameResolver occ OpenQualified env.eNameResEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No) + let tcref = ForceRaise(ResolveTypeLongIdent cenv.tcSink cenv.nameResolver occ OpenQualified env.eNameResEnv ad tc TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No) match optKind, tcref.TypeOrMeasureKind with | Some TyparKind.Type, TyparKind.Measure -> error(Error(FSComp.SR.tcExpectedTypeNotUnitOfMeasure(), m)) @@ -4660,7 +4660,7 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscope sortedArgTys |> List.iteri (fun i (x,_) -> let item = Item.AnonRecdField(anonInfo, sortedCheckedArgTys, i, x.idRange) CallNameResolutionSink cenv.tcSink (x.idRange,env.NameEnv,item,item,emptyTyparInst,ItemOccurence.UseInType,env.DisplayEnv,env.eAccessRights)) - TType_anon(anonInfo, sortedCheckedArgTys),tpenv + TType_anon(anonInfo, sortedCheckedArgTys),tpenv | SynType.Fun(domainTy, resultTy, _) -> let domainTy', tpenv = TcTypeAndRecover cenv newOk checkCxs occ env tpenv domainTy @@ -4693,7 +4693,7 @@ and TcTypeOrMeasure optKind cenv newOk checkCxs occ env (tpenv: SyntacticUnscope | SynType.HashConstraint(ty, m) -> let tp = TcAnonTypeOrMeasure (Some TyparKind.Type) cenv TyparRigidity.WarnIfNotRigid TyparDynamicReq.Yes newOk m let ty', tpenv = TcTypeAndRecover cenv newOk checkCxs occ env tpenv ty - AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css m NoTrace ty' (mkTyparTy tp) + AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css m NoTrace ty' (mkTyparTy tp) tp.AsType, tpenv | SynType.StaticConstant (c, m) -> @@ -4821,20 +4821,20 @@ and TcStaticConstantParameter cenv (env: TcEnv) tpenv kind (v: SynType) idOpt co | 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,22 +4849,22 @@ and TcStaticConstantParameter cenv (env: TcEnv) tpenv kind (v: SynType) idOpt co // 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.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) - | _ -> fail() + | 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) + | _ -> fail() | _ -> error(Error(FSComp.SR.tcInvalidConstantExpression(), v.Range)) v, tpenv' | SynType.LongIdent(lidwd) -> @@ -4916,7 +4916,7 @@ and CrackStaticConstantArgs cenv env tpenv (staticParameters: Tainted if sp.PUntaint((fun sp -> sp.IsOptional), m) then match sp.PUntaint((fun sp -> sp.RawDefaultValue), m) with - | null -> error (Error(FSComp.SR.etStaticParameterRequiresAValue (spName, containerName, containerName, spName) , m)) + | null -> error (Error(FSComp.SR.etStaticParameterRequiresAValue (spName, containerName, containerName, spName), m)) | v -> v else error (Error(FSComp.SR.etStaticParameterRequiresAValue (spName, containerName, containerName, spName), m)) @@ -5027,7 +5027,7 @@ and TcTypeApp cenv newOk checkCxs occ env tpenv m tcref pathTypeArgs (synArgTys: ty, tpenv -and TcTypeOrMeasureAndRecover optKind cenv newOk checkCxs occ env tpenv ty = +and TcTypeOrMeasureAndRecover optKind cenv newOk checkCxs occ env tpenv ty = try TcTypeOrMeasure optKind cenv newOk checkCxs occ env tpenv ty with e -> errorRecovery e ty.Range @@ -5040,7 +5040,7 @@ and TcTypeOrMeasureAndRecover optKind cenv newOk checkCxs occ env tpenv ty = rty, tpenv -and TcTypeAndRecover cenv newOk checkCxs occ env tpenv ty = +and TcTypeAndRecover cenv newOk checkCxs occ env tpenv ty = TcTypeOrMeasureAndRecover (Some TyparKind.Type) cenv newOk checkCxs occ env tpenv ty and TcNestedTypeApplication cenv newOk checkCxs occ env tpenv mWholeTypeApp ty tyargs = @@ -5058,7 +5058,7 @@ and TryAdjustHiddenVarNameToCompGenName cenv env (id: Ident) altNameRefCellOpt = | Some ({contents = Undecided altId } as altNameRefCell) -> match ResolvePatternLongIdent cenv.tcSink cenv.nameResolver AllIdsOK false id.idRange env.eAccessRights env.eNameResEnv TypeNameResolutionInfo.Default [id] with | Item.NewDef _ -> None // the name is not in scope as a pattern identifier (e.g. union case), so do not use the alternate ID - | _ -> altNameRefCell := Decided altId; Some altId // the name is in scope as a pattern identifier, so use the alternate ID + | _ -> altNameRefCell := Decided altId; Some altId // the name is in scope as a pattern identifier, so use the alternate ID | Some ({contents = Decided altId }) -> Some altId | None -> None @@ -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 @@ -5152,7 +5152,7 @@ and TcSimplePats cenv optArgsOK checkCxs ty env (tpenv, names, takenNames: Set< | SynSimplePats.SimplePats([SynSimplePat.Id(_, _, _, _, true, _)], _) -> UnifyTypes cenv env m ty (mkOptionTy cenv.g cty') | _ -> UnifyTypes cenv env m ty cty' - TcSimplePats cenv optArgsOK checkCxs ty env (tpenv, names, takenNames) p + TcSimplePats cenv optArgsOK checkCxs ty env (tpenv, names, takenNames) p and TcSimplePatsOfUnknownType cenv optArgsOK checkCxs env tpenv spats = let argty = NewInferenceType () @@ -5327,7 +5327,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p | SynPat.Named (SynPat.Wild _, id, _, None, _) -> SynExpr.Ident(id) | SynPat.Typed (p, cty, m) -> SynExpr.Typed (convSynPatToSynExpr p, cty, m) | SynPat.LongIdent (LongIdentWithDots(longId, dotms) as lidwd, _, _tyargs, args, None, m) -> - let args = match args with SynConstructorArgs.Pats args -> args | _ -> failwith "impossible: active patterns can be used only with SynConstructorArgs.Pats" + let args = match args with SynConstructorArgs.Pats args -> args | _ -> failwith "impossible: active patterns can be used only with SynConstructorArgs.Pats" let e = if dotms.Length = longId.Length then let e = SynExpr.LongIdent(false, LongIdentWithDots(longId, List.truncate (dotms.Length - 1) dotms), None, m) @@ -5378,7 +5378,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p // | Case(_, v) let result = Array.zeroCreate numArgTys for (id, pat) in pairs do - match argNames |> List.tryFindIndex (fun id2 -> id.idText = id2.idText) with + match argNames |> List.tryFindIndex (fun id2 -> id.idText = id2.idText) with | None -> match item with | Item.UnionCase(uci, _) -> @@ -5447,7 +5447,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p // LITERAL F# FIELDS CheckRecdFieldInfoAccessible cenv.amap m env.eAccessRights rfinfo if not rfinfo.IsStatic then errorR (Error (FSComp.SR.tcFieldIsNotStatic(rfinfo.Name), m)) - CheckRecdFieldInfoAttributes cenv.g rfinfo m |> CommitOperationResult + CheckRecdFieldInfoAttributes cenv.g rfinfo m |> CommitOperationResult match rfinfo.LiteralValue with | None -> error (Error(FSComp.SR.tcFieldNotLiteralCannotBeUsedInPattern(), m)) | Some lit -> @@ -5472,7 +5472,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p CallNameResolutionSink cenv.tcSink (m, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Pattern, env.DisplayEnv, env.AccessRights) (fun _ -> TPat_const (lit, m)), (tpenv, names, takenNames) - | _ -> error (Error(FSComp.SR.tcRequireVarConstRecogOrLiteral(), m)) + | _ -> error (Error(FSComp.SR.tcRequireVarConstRecogOrLiteral(), m)) | SynPat.QuoteExpr(_, m) -> error (Error(FSComp.SR.tcInvalidPattern(), m)) @@ -5494,7 +5494,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p else List.foldBack (mkConsListPat cenv.g argty) args' (mkNilListPat cenv.g m argty)), acc | SynPat.Record (flds, m) -> - let tcref, fldsmap, _fldsList = BuildFieldMap cenv env true ty flds m + let tcref, fldsmap, _fldsList = BuildFieldMap cenv env true ty flds m // REVIEW: use _fldsList to type check pattern in code order not field defn order let _, inst, tinst, gtyp = infoOfTyconRef m tcref UnifyTypes cenv env m ty gtyp @@ -5524,7 +5524,7 @@ and TcPat warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) ty p suppressErrorReporting (fun () -> TcPatAndRecover warnOnUpper cenv env topValInfo vFlags (tpenv, names, takenNames) (NewErrorType()) pat) and TcPatterns warnOnUpper cenv env vFlags s argTys args = - assert (List.length args = List.length argTys) + assert (List.length args = List.length argTys) List.mapFold (fun s (ty, pat) -> TcPat warnOnUpper cenv env None vFlags s ty pat) s (List.zip argTys args) @@ -5545,7 +5545,7 @@ and RecordNameAndTypeResolutions_IdeallyWithoutHavingOtherEffects cenv env tpenv // The tricky bit is to not also have any other effects from typechecking, namely producing error diagnostics (which may be spurious) or having // side-effects on the typecheck environment. // - // REVIEW: We are yet to deal with the tricky bit. As it stands, we turn off error logging, but still have typechecking environment effects. As a result, + // REVIEW: We are yet to deal with the tricky bit. As it stands, we turn off error logging, but still have typechecking environment effects. As a result, // at the very least, you cannot call this function unless you're already reported a typechecking error (the 'worst' possible outcome would be // to incorrectly solve typecheck constraints as a result of effects in this function, and then have the code compile successfully and behave // in some weird way; so ensure the code can't possibly compile before calling this function as an expedient way to get better IntelliSense). @@ -5582,7 +5582,7 @@ and TcExprFlex cenv flex compat ty (env: TcEnv) tpenv (e: SynExpr) = if compat then (destTyparTy cenv.g argty).SetIsCompatFlex(true) AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css e.Range NoTrace ty argty - let e', tpenv = TcExpr cenv argty env tpenv e + let e', tpenv = TcExpr cenv argty env tpenv e let e' = mkCoerceIfNeeded cenv.g ty argty e' e', tpenv else @@ -5615,7 +5615,7 @@ and TcExprNoRecover cenv ty (env: TcEnv) tpenv (expr: SynExpr) = // This recursive entry is only used from one callsite (DiscardAfterMissingQualificationAfterDot) -// and has been added relatively late in F# 4.0 to preserve the structure of previous code. It pushes a 'delayed' parameter +// and has been added relatively late in F# 4.0 to preserve the structure of previous code. It pushes a 'delayed' parameter // through TcExprOfUnknownType, TcExpr and TcExprNoRecover and TcExprOfUnknownTypeThen cenv env tpenv expr delayed = let exprty = NewInferenceType () @@ -5700,7 +5700,7 @@ and TcExprThen cenv overallTy env tpenv synExpr delayed = | SynExpr.DotIndexedSet (e1, e2, _, _, mDot, mWholeExpr) -> TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv synExpr e1 e2 delayed - | _ -> + | _ -> match delayed with | [] -> TcExprUndelayed cenv overallTy env tpenv synExpr | _ -> @@ -5775,7 +5775,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = let idv1, idve1 = mkCompGenLocal mArg (cenv.synArgNameGenerator.New()) domainTy let envinner = ExitFamilyRegion env let idv2, matchExpr, tpenv = TcAndPatternCompileMatchClauses m mArg (if isExnMatch then Throw else ThrowIncompleteMatchException) cenv None domainTy resultTy envinner tpenv clauses - let overallExpr = mkMultiLambda m [idv1] ((mkLet spMatch m idv2 idve1 matchExpr), resultTy) + let overallExpr = mkMultiLambda m [idv1] ((mkLet spMatch m idv2 idve1 matchExpr), resultTy) overallExpr, tpenv | SynExpr.Assert (x, m) -> @@ -5786,7 +5786,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = // e: ty | SynExpr.Typed (synBodyExpr, synType, m) -> - let tgtTy, tpenv = TcTypeAndRecover cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synType + let tgtTy, tpenv = TcTypeAndRecover cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synType UnifyTypes cenv env m overallTy tgtTy let expr, tpenv = TcExpr cenv overallTy env tpenv synBodyExpr expr, tpenv @@ -5795,7 +5795,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = | SynExpr.TypeTest (synInnerExpr, tgtTy, m) -> let innerExpr, srcTy, tpenv = TcExprOfUnknownType cenv env tpenv synInnerExpr UnifyTypes cenv env m overallTy cenv.g.bool_ty - let tgtTy, tpenv = TcType cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv tgtTy + let tgtTy, tpenv = TcType cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv tgtTy TcRuntimeTypeTest (*isCast*)false (*isOperator*)true cenv env.DisplayEnv m tgtTy srcTy let expr = mkCallTypeTest cenv.g m tgtTy innerExpr expr, tpenv @@ -5835,7 +5835,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = // TcRuntimeTypeTest ensures tgtTy is a nominal type. Hence we can insert a check here // based on the nullness semantics of the nominal type. - let expr = mkCallUnbox cenv.g m tgtTy innerExpr + let expr = mkCallUnbox cenv.g m tgtTy innerExpr expr, tpenv | SynExpr.Null m -> @@ -5904,9 +5904,9 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = | SynExpr.For (spBind, id, start, dir, finish, body, m) -> UnifyTypes cenv env m overallTy cenv.g.unit_ty - let startExpr , tpenv = TcExpr cenv cenv.g.int_ty env tpenv start + let startExpr, tpenv = TcExpr cenv cenv.g.int_ty env tpenv start let finishExpr, tpenv = TcExpr cenv cenv.g.int_ty env tpenv finish - let idv, _ = mkLocal id.idRange id.idText cenv.g.int_ty + let idv, _ = mkLocal id.idRange id.idText cenv.g.int_ty let envinner = AddLocalVal cenv.tcSink m idv env // notify name resolution sink about loop variable @@ -5914,7 +5914,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = CallNameResolutionSink cenv.tcSink (idv.Range, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Binding, env.DisplayEnv, env.eAccessRights) let bodyExpr, tpenv = TcStmt cenv envinner tpenv body - mkFastForLoop cenv.g (spBind, m, idv, startExpr, dir, finishExpr, bodyExpr), tpenv + mkFastForLoop cenv.g (spBind, m, idv, startExpr, dir, finishExpr, bodyExpr), tpenv | SynExpr.ForEach (spForLoop, SeqExprOnly seqExprOnly, isFromSource, pat, enumSynExpr, bodySynExpr, m) -> assert isFromSource @@ -5936,7 +5936,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = TcComputationOrSequenceExpression cenv env overallTy m None tpenv comp - | SynExpr.ArrayOrListOfSeqExpr (isArray, comp, m) -> + | SynExpr.ArrayOrListOfSeqExpr (isArray, comp, m) -> CallExprHasTypeSink cenv.tcSink (m, env.NameEnv, overallTy, env.DisplayEnv, env.eAccessRights) match comp with @@ -5966,11 +5966,11 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = let genCollElemTy = NewInferenceType () - let genCollTy = (if isArray then mkArrayType else mkListTy) cenv.g genCollElemTy + let genCollTy = (if isArray then mkArrayType else mkListTy) cenv.g genCollElemTy UnifyTypes cenv env m overallTy genCollTy - let exprty = mkSeqTy cenv.g genCollElemTy + let exprty = mkSeqTy cenv.g genCollElemTy // Check the comprehension let expr, tpenv = TcExpr cenv exprty env tpenv comp @@ -6100,7 +6100,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = TcLongIdentThen cenv overallTy env tpenv lidwd [ DelayedApp(ExprAtomicFlag.Atomic, e1, mStmt); MakeDelayedSet(e2, mStmt) ] | SynExpr.TraitCall(tps, memSpfn, arg, m) -> - let synTypes = tps |> List.map (fun tp -> SynType.Var(tp, m)) + let synTypes = tps |> List.map (fun tp -> SynType.Var(tp, m)) let (TTrait(_, logicalCompiledName, _, argTys, returnTy, _) as traitInfo), tpenv = TcPseudoMemberSpec cenv NewTyparsOK env synTypes tpenv memSpfn m if BakedInTraitConstraintNames.Contains logicalCompiledName then warning(BakedInMemberConstraintName(logicalCompiledName, m)) @@ -6126,7 +6126,7 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = | SynExpr.LibraryOnlyUnionCaseFieldSet (e1, c, n, e2, m) -> UnifyTypes cenv env m overallTy cenv.g.unit_ty let e1', ty1, tpenv = TcExprOfUnknownType cenv env tpenv e1 - let mkf, ty2 = TcUnionCaseOrExnField cenv env ty1 m c n + let mkf, ty2 = TcUnionCaseOrExnField cenv env ty1 m c n ((fun (a, b) n e2' -> if not (isUnionCaseFieldMutable cenv.g a n) then errorR(Error(FSComp.SR.tcFieldIsNotMutable(), m)) mkUnionCaseFieldSet(e1', a, b, n, e2', m)), @@ -6168,8 +6168,8 @@ and TcExprUndelayed cenv overallTy env tpenv (synExpr: SynExpr) = | SynExpr.ImplicitZero m -> error(Error(FSComp.SR.tcConstructRequiresSequenceOrComputations(), m)) - | SynExpr.DoBang (_, m) - | SynExpr.LetOrUseBang (_, _, _, _, _, _, m) -> + | SynExpr.DoBang (_, m) + | SynExpr.LetOrUseBang (_, _, _, _, _, _, m) -> error(Error(FSComp.SR.tcConstructRequiresComputationExpression(), m)) | SynExpr.MatchBang (_, _, _, m) -> @@ -6186,7 +6186,7 @@ and TcIteratedLambdas cenv isFirst (env: TcEnv) overallTy takenNames tpenv e = let envinner = if isMember then envinner else ExitFamilyRegion envinner let bodyExpr, tpenv = TcIteratedLambdas cenv false envinner resultTy takenNames tpenv bodyExpr // See bug 5758: Non-monotonicity in inference: need to ensure that parameters are never inferred to have byref type, instead it is always declared - byrefs |> Map.iter (fun _ (orig, v) -> + byrefs |> Map.iter (fun _ (orig, v) -> if not orig && isByrefTy cenv.g v.Type then errorR(Error(FSComp.SR.tcParameterInferredByref v.DisplayName, v.Range))) mkMultiLambda m (List.map (fun nm -> NameMap.find nm vspecMap) vs) (bodyExpr, resultTy), tpenv | e -> @@ -6199,7 +6199,7 @@ and TcIteratedLambdas cenv isFirst (env: TcEnv) overallTy takenNames tpenv e = // Check expr.[idx] // This is a little over complicated for my liking. Basically we want to interpret e1.[idx] as e1.Item(idx). // However it's not so simple as all that. First "Item" can have a different name according to an attribute in -// .NET metadata. This means we manually typecheck 'e1' and look to see if it has a nominal type. We then +// .NET metadata. This means we manually typecheck 'e1' and look to see if it has a nominal type. We then // do the right thing in each case. and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArgs delayed = let ad = env.eAccessRights @@ -6238,7 +6238,7 @@ and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArg let GetIndexArgs (es: SynIndexerArg list) = [ for e in es do yield! e.Exprs ] let MakeIndexParam vopt = match indexArgs with - | [] -> failwith "unexpected empty index list" + | [] -> failwith "unexpected empty index list" | [SynIndexerArg.One h] -> SynExpr.Paren(h, range0, None, idxRange) | _ -> SynExpr.Paren(SynExpr.Tuple(false, GetIndexArgs indexArgs @ Option.toList vopt, [], idxRange), range0, None, idxRange) @@ -6253,9 +6253,9 @@ and TcIndexerThen cenv env overallTy mWholeExpr mDot tpenv wholeExpr e1 indexArg | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_] as idxs), _, _))], _, _) -> Some (indexOpPath, "GetArray3D", idxs) | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_;_] as idxs), _, _))], _, _) -> Some (indexOpPath, "GetArray4D", idxs) | false, true, SynExpr.DotIndexedGet(_, [SynIndexerArg.One idx], _, _) -> Some (indexOpPath, "GetArray", [idx]) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_] as idxs), _, _))] , e3, _, _, _) -> Some (indexOpPath, "SetArray2D", (idxs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_] as idxs), _, _))] , e3, _, _, _) -> Some (indexOpPath, "SetArray3D", (idxs @ [e3])) - | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_;_] as idxs), _, _))] , e3, _, _, _) -> Some (indexOpPath, "SetArray4D", (idxs @ [e3])) + | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_] as idxs), _, _))], e3, _, _, _) -> Some (indexOpPath, "SetArray2D", (idxs @ [e3])) + | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_] as idxs), _, _))], e3, _, _, _) -> Some (indexOpPath, "SetArray3D", (idxs @ [e3])) + | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One(SynExpr.Tuple (false, ([_;_;_;_] as idxs), _, _))], e3, _, _, _) -> Some (indexOpPath, "SetArray4D", (idxs @ [e3])) | false, true, SynExpr.DotIndexedSet(_, [SynIndexerArg.One _], e3, _, _, _) -> Some (indexOpPath, "SetArray", (GetIndexArgs indexArgs @ [e3])) | true, false, SynExpr.DotIndexedGet(_, [SynIndexerArg.Two _], _, _) -> Some (sliceOpPath, "GetStringSlice", GetIndexArgs indexArgs) | true, false, SynExpr.DotIndexedGet(_, [SynIndexerArg.One _], _, _) -> Some (indexOpPath, "GetString", GetIndexArgs indexArgs) @@ -6326,7 +6326,7 @@ and TcNewExpr cenv env tpenv objTy mObjTyOpt superInit arg mWholeExprOrObjTy = | SynExpr.Const (SynConst.Unit, _) -> () | _ -> errorR(Error(FSComp.SR.tcObjectConstructorsOnTypeParametersCannotTakeArguments(), mWholeExprOrObjTy)) - mkCallCreateInstance cenv.g mWholeExprOrObjTy objTy , tpenv + mkCallCreateInstance cenv.g mWholeExprOrObjTy objTy, tpenv else if not (isAppTy cenv.g objTy) && not (isAnyTupleTy cenv.g objTy) then error(Error(FSComp.SR.tcNamedTypeRequired(if superInit then "inherit" else "new"), mWholeExprOrObjTy)) let item = ForceRaise (ResolveObjectConstructor cenv.nameResolver env.DisplayEnv mWholeExprOrObjTy ad objTy) @@ -6433,19 +6433,19 @@ and TcRecordConstruction cenv overallTy env tpenv optOrigExprInfo objTy fldsList if optOrigExprInfo.IsNone && not (Zset.subset ns2 ns1) then error (MissingFields(Zset.elements (Zset.diff ns2 ns1), m)) - if not (Zset.subset ns1 ns2) then + if not (Zset.subset ns1 ns2) then error (Error(FSComp.SR.tcExtraneousFieldsGivenValues(), m)) // Build record let rfrefs = List.map (fst >> mkRecdFieldRef tcref) fldsList // Check accessibility: this is also done in BuildFieldMap, but also need to check - // for fields in { new R with a=1 and b=2 } constructions and { r with a=1 } copy-and-update expressions + // for fields in { new R with a=1 and b=2 } constructions and { r with a=1 } copy-and-update expressions rfrefs |> List.iter (fun rfref -> CheckRecdFieldAccessible cenv.amap m env.eAccessRights rfref |> ignore CheckFSharpAttributes cenv.g rfref.PropertyAttribs m |> CommitOperationResult) - let args = List.map snd fldsList + let args = List.map snd fldsList let expr = mkRecordExpr cenv.g (GetRecdInfo env, tcref, tinst, rfrefs, args, m) @@ -6531,9 +6531,9 @@ and FreshenObjExprAbstractSlot cenv (env: TcEnv) (implty: TType) virtNameAndArit 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 @@ -6568,7 +6568,7 @@ and TcObjectExprBinding cenv (env: TcEnv) implty tpenv (absSlotInfo, bind) = bindingRhs, logicalMethId, memberFlags | SynPat.InstanceMember(thisId, memberId, _, _, _), Some memberFlags -> - CheckMemberFlags None NewSlotsOK OverridesOK memberFlags mBinding + CheckMemberFlags None NewSlotsOK OverridesOK memberFlags mBinding let bindingRhs = PushOnePatternToRhs cenv true (mkSynThisPatVar thisId) bindingRhs let logicalMethId = ident (ComputeLogicalName memberId memberFlags, memberId.idRange) bindingRhs, logicalMethId, memberFlags @@ -6607,7 +6607,7 @@ and TcObjectExprBinding cenv (env: TcEnv) implty tpenv (absSlotInfo, bind) = let freeInEnv = GeneralizationHelpers.ComputeUngeneralizableTypars env let generalizedTypars = GeneralizationHelpers.ComputeAndGeneralizeGenericTypars(cenv, denv, m, freeInEnv, false, CanGeneralizeConstrainedTypars, inlineFlag, Some(rhsExpr), declaredTypars, [], bindingTy, false) - let declaredTypars = ChooseCanonicalDeclaredTyparsAfterInference cenv.g env.DisplayEnv declaredTypars m + let declaredTypars = ChooseCanonicalDeclaredTyparsAfterInference cenv.g env.DisplayEnv declaredTypars m let generalizedTypars = PlaceTyparsInDeclarationOrder declaredTypars generalizedTypars @@ -6621,12 +6621,12 @@ and ComputeObjectExprOverrides cenv (env: TcEnv) tpenv impls = let slotImplSets = DispatchSlotChecking.GetSlotImplSets cenv.infoReader env.DisplayEnv true (impls |> List.map (fun (m, ty, _) -> ty, m)) let allImpls = - (impls, slotImplSets) ||> List.map2 (fun (m, ty, binds) implTySet -> + (impls, slotImplSets) ||> List.map2 (fun (m, ty, binds) implTySet -> let binds = binds |> List.map (BindingNormalization.NormalizeBinding ObjExprBinding cenv env) m, ty, binds, implTySet) let overridesAndVirts, tpenv = - (tpenv, allImpls) ||> List.mapFold (fun tpenv (m, implty, binds, SlotImplSet(reqdSlots, dispatchSlotsKeyed, availPriorOverrides, _) ) -> + (tpenv, allImpls) ||> List.mapFold (fun tpenv (m, implty, binds, SlotImplSet(reqdSlots, dispatchSlotsKeyed, availPriorOverrides, _) ) -> // Generate extra bindings fo object expressions with bindings using the CLIEvent attribute let binds, bindsAttributes = @@ -6657,7 +6657,7 @@ and ComputeObjectExprOverrides cenv (env: TcEnv) tpenv impls = // 3. infer must-have types by name/arity let preAssignedVirtsPerBinding = - bindKeys |> List.map (fun bkey -> List.filter (fst >> (=) bkey) virtNameAndArityPairs) + bindKeys |> List.map (fun bkey -> List.filter (fst >> (=) bkey) virtNameAndArityPairs) let absSlotInfo = (List.zip4 binds bindsAttributes bindNames preAssignedVirtsPerBinding) @@ -6692,7 +6692,7 @@ and CheckSuperType cenv ty m = and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, mNewExpr, mWholeExpr) = let mObjTy = synObjTy.Range - let objTy, tpenv = TcType cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synObjTy + let objTy, tpenv = TcType cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synObjTy match tryDestAppTy cenv.g objTy with | ValueNone -> error(Error(FSComp.SR.tcNewMustBeUsedWithNamedType(), mNewExpr)) | ValueSome tcref -> @@ -6702,7 +6702,7 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, CheckSuperType cenv objTy synObjTy.Range // Add the object type to the ungeneralizable items - let env = {env with eUngeneralizableItems = addFreeItemOfTy objTy env.eUngeneralizableItems } + let env = {env with eUngeneralizableItems = addFreeItemOfTy objTy env.eUngeneralizableItems } // Object expression members can access protected members of the implemented type let env = EnterFamilyRegion tcref env @@ -6732,7 +6732,7 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, // Work out the type of any interfaces to implement let extraImpls, tpenv = - (tpenv , extraImpls) ||> List.mapFold (fun tpenv (InterfaceImpl(synIntfTy, overrides, m)) -> + (tpenv, extraImpls) ||> List.mapFold (fun tpenv (InterfaceImpl(synIntfTy, overrides, m)) -> let intfTy, tpenv = TcType cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv synIntfTy if not (isInterfaceTy cenv.g intfTy) then error(Error(FSComp.SR.tcExpectedInterfaceType(), m)) @@ -6822,7 +6822,7 @@ and TcObjectExpr cenv overallTy env tpenv (synObjTy, argopt, binds, extraImpls, //------------------------------------------------------------------------- /// Check a constant string expression. It might be a 'printf' format string -and TcConstStringExpr cenv overallTy env m tpenv s = +and TcConstStringExpr cenv overallTy env m tpenv s = if (AddCxTypeEqualsTypeUndoIfFailed env.DisplayEnv cenv.css m overallTy cenv.g.string_ty) then mkString cenv.g m s, tpenv @@ -6842,7 +6842,7 @@ and TcConstStringExpr cenv overallTy env m tpenv s = match cenv.tcSink.CurrentSink with | None -> () - | Some sink -> + | Some sink -> for specifierLocation, numArgs in specifierLocations do sink.NotifyFormatSpecifierLocation(specifierLocation, numArgs) @@ -6858,7 +6858,7 @@ and TcConstStringExpr cenv overallTy env m tpenv s = //------------------------------------------------------------------------- /// Check a constant expression. -and TcConstExpr cenv overallTy env m tpenv c = +and TcConstExpr cenv overallTy env m tpenv c = match c with // NOTE: these aren't "really" constants @@ -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 @@ -7055,7 +7055,7 @@ and TcAnonRecdExpr cenv overallTy env tpenv (isStruct, optOrigExpr, unsortedArgs let wrap, oldveaddr, _readonly, _writeonly = mkExprAddrOfExpr cenv.g origExprIsStruct false NeverMutates oldve None mOrigExpr - // Put all the expressions in unsorted order. The new bindings come first. The origin of each is tracked using + // Put all the expressions in unsorted order. The new bindings come first. The origin of each is tracked using /// - Choice1Of2 for a new binding /// - Choice2Of2 for a binding coming from the original expression let unsortedIdAndExprsAll = @@ -7070,7 +7070,7 @@ and TcAnonRecdExpr cenv overallTy env tpenv (isStruct, optOrigExpr, unsortedArgs let tcref, tinst = destAppTy cenv.g origExprTy let fspecs = tcref.Deref.TrueInstanceFieldsAsList for fspec in fspecs do - yield fspec.Id, Choice2Of2 (mkRecdFieldGetViaExprAddr (oldveaddr , tcref.MakeNestedRecdFieldRef fspec, tinst, mOrigExpr)) + yield fspec.Id, Choice2Of2 (mkRecdFieldGetViaExprAddr (oldveaddr, tcref.MakeNestedRecdFieldRef fspec, tinst, mOrigExpr)) else error (Error (FSComp.SR.tcCopyAndUpdateNeedsRecordType(), mOrigExpr)) |] |> Array.distinctBy (fst >> textOfId) @@ -7105,7 +7105,7 @@ and TcAnonRecdExpr cenv overallTy env tpenv (isStruct, optOrigExpr, unsortedArgs expr, tpenv -and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWholeExpr, spForLoop) = +and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWholeExpr, spForLoop) = UnifyTypes cenv env mWholeExpr overallTy cenv.g.unit_ty let mPat = pat.Range @@ -7126,7 +7126,7 @@ and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWhol (cenv.g.int32_ty, (fun _ x -> x), id, Choice1Of3 (startExpr, finishExpr)) // optimize 'for i in arr do' - | _ when isArray1DTy cenv.g enumExprTy -> + | _ when isArray1DTy cenv.g enumExprTy -> let arrVar, arrExpr = mkCompGenLocal mEnumExpr "arr" enumExprTy let idxVar, idxExpr = mkCompGenLocal mPat "idx" cenv.g.int32_ty let elemTy = destArrayTy cenv.g enumExprTy @@ -7201,7 +7201,7 @@ and TcForEachExpr cenv overallTy env tpenv (pat, enumSynExpr, bodySynExpr, mWhol mForLoopStart), cleanupE, mForLoopStart, cenv.g.unit_ty, NoSequencePointAtTry, NoSequencePointAtFinally)))) - let overallExpr = overallExprFixup overallExpr + let overallExpr = overallExprFixup overallExpr overallExpr, tpenv //------------------------------------------------------------------------- @@ -7339,7 +7339,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv match customOperationMethodsIndexedByKeyword.TryGetValue nm.idText with | true, [opData] -> let (opName, maintainsVarSpaceUsingBind, maintainsVarSpace, _allowInto, isLikeZip, isLikeJoin, isLikeGroupJoin, _joinConditionWord, methInfo) = opData - if (maintainsVarSpaceUsingBind && maintainsVarSpace) || (isLikeZip && isLikeJoin) || (isLikeZip && isLikeGroupJoin) || (isLikeJoin && isLikeGroupJoin) then + if (maintainsVarSpaceUsingBind && maintainsVarSpace) || (isLikeZip && isLikeJoin) || (isLikeZip && isLikeGroupJoin) || (isLikeJoin && isLikeGroupJoin) then errorR(Error(FSComp.SR.tcCustomOperationInvalid opName, nm.idRange)) match customOperationMethodsIndexedByMethodName.TryGetValue methInfo.LogicalName with | true, [_] -> () @@ -7351,43 +7351,43 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv /// Decide if the identifier represents a use of a custom query operator let hasCustomOperations () = not (isNil customOperationMethods) - let isCustomOperation nm = tryGetDataForCustomOperation nm |> Option.isSome + let isCustomOperation nm = tryGetDataForCustomOperation nm |> Option.isSome // Check for the MaintainsVariableSpace on custom operation let customOperationMaintainsVarSpace (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false - | Some (_nm, _maintainsVarSpaceUsingBind, maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> maintainsVarSpace + | Some (_nm, _maintainsVarSpaceUsingBind, maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> maintainsVarSpace let customOperationMaintainsVarSpaceUsingBind (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false - | Some (_nm, maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> maintainsVarSpaceUsingBind + | Some (_nm, maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> maintainsVarSpaceUsingBind let customOperationIsLikeZip (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false - | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeZip + | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeZip let customOperationIsLikeJoin (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false - | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeJoin + | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeJoin let customOperationIsLikeGroupJoin (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false - | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeGroupJoin + | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, isLikeGroupJoin, _joinConditionWord, _methInfo) -> isLikeGroupJoin let customOperationJoinConditionWord (nm: Ident) = match tryGetDataForCustomOperation nm with - | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, Some joinConditionWord, _methInfo) -> joinConditionWord + | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, _allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, Some joinConditionWord, _methInfo) -> joinConditionWord | _ -> "on" let customOperationAllowsInto (nm: Ident) = match tryGetDataForCustomOperation nm with | None -> false - | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> allowInto + | Some (_nm, _maintainsVarSpaceUsingBind, _maintainsVarSpace, allowInto, _isLikeZip, _isLikeJoin, _isLikeGroupJoin, _joinConditionWord, _methInfo) -> allowInto let customOpUsageText nm = match tryGetDataForCustomOperation nm with @@ -7431,7 +7431,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let expectedArgCountForCustomOperator (nm: Ident) = match tryGetArgInfosForCustomOperator nm with | None -> 0 - | Some argInfos -> max (argInfos.Length - 1) 0 // drop the computation context argument + | 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) = @@ -7453,7 +7453,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | SingleIdent nm when isCustomOperation nm && predicate nm -> Some nm | _ -> None - // e1 in e2 ('in' is parsed as 'JOIN_IN') + // e1 in e2 ('in' is parsed as 'JOIN_IN') let (|InExpr|_|) (e: SynExpr) = match e with | SynExpr.JoinIn(e1, _, e2, mApp) -> Some (e1, e2, mApp) @@ -7526,7 +7526,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let (|JoinExpr|_|) (e: SynExpr) = match e with - | InExpr (JoinOp(nm, innerSourcePat, _, alreadyGivenError), onExpr, mJoinCore) -> + | InExpr (JoinOp(nm, innerSourcePat, _, alreadyGivenError), onExpr, mJoinCore) -> let (innerSource, keySelectors) = MatchOnExprOrRecover alreadyGivenError nm onExpr Some(nm, innerSourcePat, innerSource, keySelectors, mJoinCore) | JoinOp (nm, innerSourcePat, mJoinCore, alreadyGivenError) -> @@ -7565,7 +7565,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv Some(nm, secondSourcePat, secondSource, None, None, mZipCore) // zip (without secondSource or in - gives error) - | CustomOpId customOperationIsLikeZip nm -> + | CustomOpId customOperationIsLikeZip nm -> errorR(Error(FSComp.SR.tcOperatorIncorrectSyntax(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) Some(nm, arbPat e.Range, arbExpr("_secondSource", e.Range), None, None, e.Range) @@ -7600,7 +7600,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let rec strip e = match e with | SynExpr.FromParseError(SynExpr.App(_, _, f, arg, _), _) - | SynExpr.App(_, _, f, arg, _) -> + | SynExpr.App(_, _, f, arg, _) -> let g, acc = strip f g, (arg::acc) | _ -> e, [] @@ -7614,7 +7614,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let (|CustomOperationClause|_|) e = match e with - | OptionalIntoSuffix(StripApps(SingleIdent nm, _) as core, optInto) when isCustomOperation nm -> + | OptionalIntoSuffix(StripApps(SingleIdent nm, _) as core, optInto) when isCustomOperation nm -> // Now we know we have a custom operation, commit the name resolution let optIntoInfo = match optInto with @@ -7710,7 +7710,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // ... // --> // zip expr1 expr2 (fun pat1 pat3 -> ...) - | ForEachThenJoinOrGroupJoinOrZipClause (isFromSource, firstSourcePat, firstSource, nm, secondSourcePat, secondSource, keySelectorsOpt, secondResultPatOpt, mOpCore, innerComp) -> + | ForEachThenJoinOrGroupJoinOrZipClause (isFromSource, firstSourcePat, firstSource, nm, secondSourcePat, secondSource, keySelectorsOpt, secondResultPatOpt, mOpCore, innerComp) -> if not q then error(Error(FSComp.SR.tcCustomOperationMayNotBeUsedHere(), nm.idRange)) @@ -7764,14 +7764,14 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv secondSource (mkSynLambda firstSourceSimplePats keySelector1 mSynthetic) (mkSynLambda secondSourceSimplePats keySelector2 mSynthetic) - (mkSynLambda firstSourceSimplePats (mkSynLambda innerPat e mSynthetic) mSynthetic) ] + (mkSynLambda firstSourceSimplePats (mkSynLambda innerPat e mSynthetic) mSynthetic) ] let mkZipExpr e = let mSynthetic = mOpCore.MakeSynthetic() mkSynCall methInfo.DisplayName mOpCore [ firstSource secondSource - (mkSynLambda firstSourceSimplePats (mkSynLambda secondSourceSimplePats e mSynthetic) mSynthetic) ] + (mkSynLambda firstSourceSimplePats (mkSynLambda secondSourceSimplePats e mSynthetic) mSynthetic) ] // wraps given expression into sequence with result produced by arbExpr so result will look like: // l; SynExpr.ArbitraryAfterError(...) @@ -7851,7 +7851,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // Case from C# spec: A query expression with a join clause with an into followed by something other than a select clause // Case from C# spec: A query expression with a join clause without an into followed by something other than a select clause let valsInner, _env = varSpaceInner.Force mOpCore - let varSpaceExpr = mkExprForVarSpace mOpCore valsInner + let varSpaceExpr = mkExprForVarSpace mOpCore valsInner let varSpacePat = mkPatForVarSpace mOpCore valsInner let joinExpr = mkOverallExprGivenVarSpaceExpr varSpaceExpr Some (trans true q varSpaceInner (SynExpr.ForEach (NoSequencePointAtForLoop, SeqExprOnly false, false, varSpacePat, joinExpr, innerComp, mOpCore)) translatedCtxt) @@ -7908,7 +7908,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv // 'join' clauses preceded by 'let' and other constructs get processed by repackaging with a 'for' loop. let patvs, _env = varSpace.Force comp.Range - let varSpaceExpr = mkExprForVarSpace mClause patvs + let varSpaceExpr = mkExprForVarSpace mClause patvs let varSpacePat = mkPatForVarSpace mClause patvs let dataCompPrior = @@ -7927,7 +7927,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv if not q then error(Error(FSComp.SR.tcCustomOperationMayNotBeUsedHere(), opExpr.Range)) let patvs, _env = varSpace.Force comp.Range - let varSpaceExpr = mkExprForVarSpace mClause patvs + let varSpaceExpr = mkExprForVarSpace mClause patvs let dataCompPriorToOp = let isYield = not (customOperationMaintainsVarSpaceUsingBind nm) @@ -7957,7 +7957,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv errorR(Error(FSComp.SR.tcBinaryOperatorRequiresBody(nm.idText, Option.get (customOpUsageText nm)), nm.idRange)) match optionalCont with | None -> - // we are about to drop the 'opExpr' AST on the floor. we've already reported an error. attempt to get name resolutions before dropping it + // we are about to drop the 'opExpr' AST on the floor. we've already reported an error. attempt to get name resolutions before dropping it RecordNameAndTypeResolutions_IdeallyWithoutHavingOtherEffects cenv env tpenv opExpr dataCompPrior | Some contExpr -> consumeClauses varSpace dataCompPrior contExpr lastUsesBind @@ -7982,7 +7982,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv match optionalCont with | None -> - match optionalIntoPat with + match optionalIntoPat with | Some intoPat -> errorR(Error(FSComp.SR.tcIntoNeedsRestOfQuery(), intoPat.Range)) | None -> () dataCompAfterOp @@ -8042,7 +8042,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv if isQuery && not(innerComp1.IsArbExprAndThusAlreadyReportedError) then match innerComp1 with - | SynExpr.JoinIn _ -> () // an error will be reported later when we process innerComp1 as a sequential + | SynExpr.JoinIn _ -> () // an error will be reported later when we process innerComp1 as a sequential | _ -> errorR(Error(FSComp.SR.tcUnrecognizedQueryOperator(), innerComp1.RangeOfFirstPortion)) match tryTrans true false varSpace innerComp1 id with @@ -8055,7 +8055,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv | SynExpr.IfThenElse (_, _, _, _, _, mIfToThen, _m) -> mIfToThen | SynExpr.Match (SequencePointAtBinding mMatch, _, _, _) -> mMatch | SynExpr.TryWith (_, _, _, _, _, SequencePointAtTry mTry, _) -> mTry - | SynExpr.TryFinally (_, _, _, SequencePointAtTry mTry, _) -> mTry + | SynExpr.TryFinally (_, _, _, SequencePointAtTry mTry, _) -> mTry | SynExpr.For (SequencePointAtForLoop mBind, _, _, _, _, _, _) -> mBind | SynExpr.ForEach (SequencePointAtForLoop mBind, _, _, _, _, _, _) -> mBind | SynExpr.While (SequencePointAtWhileLoop mWhile, _, _, _) -> mWhile @@ -8128,7 +8128,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env bindRange ad "Using" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Using"), bindRange)) Some (translatedCtxt (mkSynCall "Using" bindRange [rhsExpr; consumeExpr ])) - // 'let! pat = expr in expr' --> build.Bind(e1, (function _argN -> match _argN with pat -> expr)) + // 'let! pat = expr in expr' --> build.Bind(e1, (function _argN -> match _argN with pat -> expr)) | SynExpr.LetOrUseBang(spBind, false, isFromSource, pat, rhsExpr, innerComp, _) -> let bindRange = match spBind with SequencePointAtBinding(m) -> m | _ -> rhsExpr.Range @@ -8146,10 +8146,10 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv let rhsExpr = if isFromSource then mkSourceExpr rhsExpr else rhsExpr Some (trans true q varSpace innerComp (fun holeFill -> let consumeExpr = SynExpr.MatchLambda(false, pat.Range, [Clause(pat, None, holeFill, innerRange, SequencePointAtTarget)], spBind, innerRange) - translatedCtxt (mkSynCall "Bind" bindRange [rhsExpr; consumeExpr]))) + translatedCtxt (mkSynCall "Bind" bindRange [rhsExpr; consumeExpr]))) - // 'use! pat = e1 in e2' --> build.Bind(e1, (function _argN -> match _argN with pat -> build.Using(x, (fun _argN -> match _argN with pat -> e2)))) - | SynExpr.LetOrUseBang(spBind, true, isFromSource, (SynPat.Named (SynPat.Wild _, id, false, _, _) as pat) , rhsExpr, innerComp, _) + // 'use! pat = e1 in e2' --> build.Bind(e1, (function _argN -> match _argN with pat -> build.Using(x, (fun _argN -> match _argN with pat -> e2)))) + | SynExpr.LetOrUseBang(spBind, true, isFromSource, (SynPat.Named (SynPat.Wild _, id, false, _, _) as pat), rhsExpr, innerComp, _) | SynExpr.LetOrUseBang(spBind, true, isFromSource, (SynPat.LongIdent (LongIdentWithDots([id], _), _, _, _, _, _) as pat), rhsExpr, innerComp, _) -> let bindRange = match spBind with SequencePointAtBinding(m) -> m | _ -> rhsExpr.Range @@ -8187,7 +8187,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv if isQuery then error(Error(FSComp.SR.tcTryWithMayNotBeUsedInQueries(), mTry)) let clauses = clauses |> List.map (fun (Clause(pat, cond, clauseComp, patm, sp)) -> Clause(pat, cond, transNoQueryOps clauseComp, patm, sp)) let consumeExpr = SynExpr.MatchLambda(true, mTryToLast, clauses, NoSequencePointAtStickyBinding, mTryToLast) - if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mTry ad "TryWith" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("TryWith"), mTry)) + if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mTry ad "TryWith" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("TryWith"), mTry)) if isNil (TryFindIntrinsicOrExtensionMethInfo cenv env mTry ad "Delay" builderTy) then error(Error(FSComp.SR.tcRequireBuilderMethod("Delay"), mTry)) Some(translatedCtxt (mkSynCall "TryWith" mTry [mkSynCall "Delay" mTry [mkSynDelay2 (transNoQueryOps innerComp)]; consumeExpr])) @@ -8241,7 +8241,7 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv else if isQuery && not comp.IsArbExprAndThusAlreadyReportedError then match comp with - | SynExpr.JoinIn _ -> () // an error will be reported later when we process innerComp1 as a sequential + | SynExpr.JoinIn _ -> () // an error will be reported later when we process innerComp1 as a sequential | _ -> errorR(Error(FSComp.SR.tcUnrecognizedQueryOperator(), comp.RangeOfFirstPortion)) trans true q varSpace (SynExpr.ImplicitZero comp.Range) (fun holeFill -> translatedCtxt (SynExpr.Sequential(SuppressSequencePointOnStmtOfSequential, true, comp, holeFill, comp.Range))) @@ -8272,9 +8272,9 @@ and TcComputationExpression cenv env overallTy mWhole interpExpr builderTy tpenv match comp with | SynExpr.YieldOrReturn ((true, _), _, _) -> { env with eContextInfo = ContextInfo.YieldInComputationExpression } | SynExpr.YieldOrReturn ((_, true), _, _) -> { env with eContextInfo = ContextInfo.ReturnInComputationExpression } - | _ -> env + | _ -> env - let lambdaExpr , tpenv= TcExpr cenv (builderTy --> overallTy) env tpenv lambdaExpr + let lambdaExpr, tpenv= TcExpr cenv (builderTy --> overallTy) env tpenv lambdaExpr // beta-var-reduce to bind the builder using a 'let' binding let coreExpr = mkApps cenv.g ((lambdaExpr, tyOfExpr cenv.g lambdaExpr), [], [interpExpr], mBuilderVal) @@ -8330,7 +8330,7 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = let matchv, matchExpr = compileSeqExprMatchClauses cenv env enumExprMark (pat', vspecs) innerExpr None enumElemTy genOuterTy let lam = mkLambda enumExprMark matchv (matchExpr, tyOfExpr cenv.g matchExpr) - Some(mkSeqCollect cenv env m enumElemTy genOuterTy lam enumExpr , tpenv) + Some(mkSeqCollect cenv env m enumElemTy genOuterTy lam enumExpr, tpenv) | SynExpr.For (spBind, id, start, dir, finish, innerComp, m) -> Some(tcSequenceExprBody env genOuterTy tpenv (elimFastIntegerForLoop (spBind, id, start, dir, finish, innerComp, m))) @@ -8393,7 +8393,7 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = tpenv true comp - (fun x -> x) |> Some + (fun x -> x) |> Some // 'use x = expr in expr' | SynExpr.LetOrUse (_isRec, true, [Binding (_vis, NormalBinding, _, _, _, _, _, pat, _, rhsExpr, _, _spBind)], innerComp, wholeExprMark) -> @@ -8436,7 +8436,7 @@ and TcSequenceExpression cenv env tpenv comp overallTy m = if not isYield then errorR(Error(FSComp.SR.tcUseYieldBangForMultipleResults(), m)) - AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css m NoTrace genOuterTy genExprTy + AddCxTypeMustSubsumeType ContextInfo.NoContext env.DisplayEnv cenv.css m NoTrace genOuterTy genExprTy Some(mkCoerceExpr(resultExpr, genOuterTy, m, genExprTy), tpenv) | SynExpr.YieldOrReturn((isYield, _), yieldExpr, m) -> @@ -8501,7 +8501,7 @@ and Propagate cenv overallTy env tpenv (expr: ApplicableExpr) exprty delayed = | DelayedDotLookup _ :: _ -> () | DelayedTypeApp (_, _mTypeArgs, mExprAndTypeArgs) :: delayedList' -> // Note this case should not occur: would eventually give an "Unexpected type application" error in TcDelayed - propagate isAddrOf delayedList' mExprAndTypeArgs exprty + propagate isAddrOf delayedList' mExprAndTypeArgs exprty | DelayedApp (_, arg, mExprAndArg) :: delayedList' -> let denv = env.DisplayEnv @@ -8517,7 +8517,7 @@ and Propagate cenv overallTy env tpenv (expr: ApplicableExpr) exprty delayed = valRefEq cenv.g vf cenv.g.nativeptr_tobyref_vref) -> true | _ -> false - propagate isAddrOf delayedList' mExprAndArg resultTy + propagate isAddrOf delayedList' mExprAndArg resultTy | _ -> let mArg = arg.Range @@ -8585,8 +8585,8 @@ and TcDelayed cenv overallTy env tpenv mExpr expr exprty (atomicFlag: ExprAtomic /// Convert the delayed identifiers to a dot-lookup. /// -/// TcItemThen: For StaticItem [.Lookup] , mPrior is the range of StaticItem -/// TcLookupThen: For expr.InstanceItem [.Lookup] , mPrior is the range of expr.InstanceItem +/// TcItemThen: For StaticItem [.Lookup], mPrior is the range of StaticItem +/// TcLookupThen: For expr.InstanceItem [.Lookup], mPrior is the range of expr.InstanceItem and delayRest rest mPrior delayed = match rest with | [] -> delayed @@ -8693,7 +8693,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let (|FittedArgs|_|) arg = match arg with | SynExprParen(SynExpr.Tuple(false, args, _, _), _, _, _) - | SynExpr.Tuple(false, args, _, _) when numArgTys > 1 -> Some args + | SynExpr.Tuple(false, args, _, _) when numArgTys > 1 -> Some args | SynExprParen(arg, _, _, _) | arg when numArgTys = 1 -> Some [arg] | _ -> None @@ -8870,7 +8870,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let tyargs, tpenv = TcTypesOrMeasures None cenv NewTyparsOK CheckCxs ItemOccurence.UseInType env tpenv tys mTypeArgs // FUTURE: can we do better than emptyTyparInst here, in order to display instantiations - // of type variables in the quick info provided in the IDE? But note we haven't yet even checked if the + // of type variables in the quick info provided in the IDE? But note we haven't yet even checked if the // number of type arguments is correct... CallNameResolutionSink cenv.tcSink (mExprAndTypeArgs, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, env.eAccessRights) @@ -8992,7 +8992,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | SynExpr.Record(_, copyOpt, fields, _) -> copyOpt |> Option.forall (fst >> isSimpleArgument) && fields |> List.forall (p23 >> Option.forall isSimpleArgument) | SynExpr.App (_, _, synExpr, synExpr2, _) -> isSimpleArgument synExpr && isSimpleArgument synExpr2 | SynExpr.IfThenElse(synExpr, synExpr2, synExprOpt, _, _, _, _) -> isSimpleArgument synExpr && isSimpleArgument synExpr2 && Option.forall isSimpleArgument synExprOpt - | SynExpr.DotIndexedGet(synExpr, _, _, _) -> isSimpleArgument synExpr + | SynExpr.DotIndexedGet(synExpr, _, _, _) -> isSimpleArgument synExpr | SynExpr.ObjExpr _ | SynExpr.AnonRecd _ | SynExpr.While _ @@ -9025,7 +9025,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del | SynExpr.ArbitraryAfterError(_, _) | SynExpr.FromParseError(_, _) | SynExpr.DiscardAfterMissingQualificationAfterDot(_, _) - | SynExpr.ImplicitZero _ + | SynExpr.ImplicitZero _ | SynExpr.YieldOrReturn _ | SynExpr.YieldOrReturnFrom _ | SynExpr.MatchBang _ @@ -9077,7 +9077,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del UnifyTypes cenv env mStmt overallTy cenv.g.unit_ty vref.Deref.SetHasBeenReferenced() CheckValAccessible mItem env.eAccessRights vref - CheckValAttributes cenv.g vref mItem |> CommitOperationResult + CheckValAttributes cenv.g vref mItem |> CommitOperationResult let vty = vref.Type let vty2 = if isByrefTy cenv.g vty then @@ -9109,7 +9109,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let vexpFlex = (if isSpecial then MakeApplicableExprNoFlex cenv vexp else MakeApplicableExprWithFlex cenv env vexp) // We need to eventually record the type resolution for an expression, but this is done // inside PropagateThenTcDelayed, so we don't have to explicitly call 'CallExprHasTypeSink' here - PropagateThenTcDelayed cenv overallTy env tpenv mExprAndTypeArgs vexpFlex vexpFlex.Type ExprAtomicFlag.Atomic otherDelayed + PropagateThenTcDelayed cenv overallTy env tpenv mExprAndTypeArgs vexpFlex vexpFlex.Type ExprAtomicFlag.Atomic otherDelayed // Value get | _ -> @@ -9137,7 +9137,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let meths = pinfos |> GettersOfPropInfos let isByrefMethReturnSetter = meths |> List.exists (function (_,Some pinfo) -> isByrefTy cenv.g (pinfo.GetPropertyType(cenv.amap,mItem)) | _ -> false) if isByrefMethReturnSetter then - // x.P <- ... byref setter + // x.P <- ... byref setter if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable(nm), mItem)) TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt [] mItem mItem nm ad NeverMutates true meths afterResolution NormalValUse args ExprAtomicFlag.Atomic delayed else @@ -9206,7 +9206,7 @@ and TcItemThen cenv overallTy env tpenv (item, mItem, rest, afterResolution) del let e2', tpenv = TcExprFlex cenv true false fieldTy env tpenv e2 let expr = mkStaticRecdFieldSet (rfinfo.RecdFieldRef, rfinfo.TypeInst, e2', mStmt) expr, tpenv - | _ -> + | _ -> let exprty = fieldTy let expr = match rfinfo.LiteralValue with @@ -9322,7 +9322,7 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela let meths = pinfos |> GettersOfPropInfos let isByrefMethReturnSetter = meths |> List.exists (function (_,Some pinfo) -> isByrefTy cenv.g (pinfo.GetPropertyType(cenv.amap,mItem)) | _ -> false) if isByrefMethReturnSetter then - // x.P <- ... byref setter + // x.P <- ... byref setter if isNil meths then error (Error (FSComp.SR.tcPropertyIsNotReadable(nm), mItem)) TcMethodApplicationThen cenv env overallTy None tpenv tyargsOpt objArgs mExprAndItem mItem nm ad PossiblyMutates true meths afterResolution NormalValUse args atomicFlag delayed else @@ -9375,7 +9375,7 @@ and TcLookupThen cenv overallTy env tpenv mObjExpr objExpr objExprTy longId dela | Item.ILField finfo -> // Get or set instance IL field - ILFieldInstanceChecks cenv.g cenv.amap ad mItem finfo + ILFieldInstanceChecks cenv.g cenv.amap ad mItem finfo let exprty = finfo.FieldType(cenv.amap, mItem) match delayed with @@ -9458,7 +9458,7 @@ and TcMethodApplicationThen objArgs // The 'obj' arguments in obj.M(...) and obj.M, if any m // The range of the object argument or whole application. We immediately union this with the range of the arguments mItem // The range of the item that resolved to the method name - methodName // string, name of the method + methodName // string, name of the method ad // accessibility rights of the caller mut // what do we know/assume about whether this method will mutate or not? isProp // is this a property call? Used for better error messages and passed to BuildMethodCall @@ -9466,7 +9466,7 @@ and TcMethodApplicationThen afterResolution // do we need to notify sink after overload resolution isSuperInit // is this a special invocation, e.g. a super-class constructor call. Passed through to BuildMethodCall args // the _syntactic_ method arguments, not yet type checked. - atomicFlag // is the expression atomic or not? + atomicFlag // is the expression atomic or not? delayed // further lookups and applications that follow this = @@ -9511,7 +9511,7 @@ and TcMethodApplication tpenv tyargsOpt objArgs - mMethExpr // range of the entire method expression + mMethExpr // range of the entire method expression mItem methodName (objTyOpt: TType option) @@ -9601,7 +9601,7 @@ and TcMethodApplication // member x.M(arg1, arg2) // being used with // x.M p - // We typecheck this as if it has been written "(fun (v1, v2) -> x.M(v1, v2)) p" + // We typecheck this as if it has been written "(fun (v1, v2) -> x.M(v1, v2)) p" // Without this rule this requires // x.M (fst p, snd p) | [calledMeth] @@ -9644,9 +9644,9 @@ and TcMethodApplication let UnifyMatchingSimpleArgumentTypes exprTy (calledMeth: MethInfo) = let curriedArgTys = GenerateMatchingSimpleArgumentTypes calledMeth let returnTy = - (exprTy, curriedArgTys) ||> List.fold (fun exprTy argTys -> + (exprTy, curriedArgTys) ||> List.fold (fun exprTy argTys -> let domainTy, resultTy = UnifyFunctionType None cenv denv mMethExpr exprTy - UnifyTypes cenv env mMethExpr domainTy (mkRefTupledTy cenv.g argTys) + UnifyTypes cenv env mMethExpr domainTy (mkRefTupledTy cenv.g argTys) resultTy) curriedArgTys, returnTy @@ -9685,7 +9685,7 @@ and TcMethodApplication | None, _ -> let domainTy, returnTy = UnifyFunctionType None cenv denv mMethExpr exprTy - let argTys = if isUnitTy cenv.g domainTy then [] else tryDestRefTupleTy cenv.g domainTy + let argTys = if isUnitTy cenv.g domainTy then [] else tryDestRefTupleTy cenv.g domainTy // Only apply this rule if a candidate method exists with this number of arguments let argTys = if candidates |> List.exists (CalledMethHasSingleArgumentGroupOfThisLength argTys.Length) then @@ -9747,7 +9747,7 @@ and TcMethodApplication UnifyMatchingSimpleArgumentTypes exprTy calledMeth | _ -> let domainTy, returnTy = UnifyFunctionType None cenv denv mMethExpr exprTy - let argTys = if isUnitTy cenv.g domainTy then [] else tryDestRefTupleTy cenv.g domainTy + let argTys = if isUnitTy cenv.g domainTy then [] else tryDestRefTupleTy cenv.g domainTy // Only apply this rule if a candidate method exists with this number of arguments let argTys = if candidates |> List.exists (CalledMethHasSingleArgumentGroupOfThisLength argTys.Length) then @@ -9775,15 +9775,15 @@ and TcMethodApplication match ExamineMethodForLambdaPropagation meth with | Some (unnamedInfo, namedInfo) -> let calledObjArgTys = meth.CalledObjArgTys(mMethExpr) - if (calledObjArgTys, callerObjArgTys) ||> Seq.forall2 (fun calledTy callerTy -> AddCxTypeMustSubsumeTypeMatchingOnlyUndoIfFailed denv cenv.css mMethExpr calledTy callerTy) then + if (calledObjArgTys, callerObjArgTys) ||> Seq.forall2 (fun calledTy callerTy -> AddCxTypeMustSubsumeTypeMatchingOnlyUndoIfFailed denv cenv.css mMethExpr calledTy callerTy) then yield (List.toArraySquared unnamedInfo, List.toArraySquared namedInfo) | None -> () |] else [| |] // Now typecheck the argument expressions - let unnamedCurriedCallerArgs, (lambdaPropagationInfo, tpenv) = TcUnnamedMethodArgs cenv env lambdaPropagationInfo tpenv unnamedCurriedCallerArgs - let namedCurriedCallerArgs, (_, tpenv) = TcMethodNamedArgs cenv env lambdaPropagationInfo tpenv namedCurriedCallerArgs + let unnamedCurriedCallerArgs, (lambdaPropagationInfo, tpenv) = TcUnnamedMethodArgs cenv env lambdaPropagationInfo tpenv unnamedCurriedCallerArgs + let namedCurriedCallerArgs, (_, tpenv) = TcMethodNamedArgs cenv env lambdaPropagationInfo tpenv namedCurriedCallerArgs unnamedCurriedCallerArgs, namedCurriedCallerArgs, None, exprTy, tpenv let preArgumentTypeCheckingCalledMethGroup = @@ -9821,7 +9821,7 @@ and TcMethodApplication if not uniquelyResolved then GeneralizationHelpers.CanonicalizePartialInferenceProblem (cenv, denv, mItem) (//freeInTypeLeftToRight cenv.g false returnTy @ - (unnamedCurriedCallerArgs |> List.collectSquared (fun callerArg -> freeInTypeLeftToRight cenv.g false callerArg.Type))) + (unnamedCurriedCallerArgs |> List.collectSquared (fun callerArg -> freeInTypeLeftToRight cenv.g false callerArg.Type))) let result, errors = ResolveOverloading csenv NoTrace methodName 0 None callerArgCounts ad postArgumentTypeCheckingCalledMethGroup true (Some returnTy) @@ -9868,7 +9868,7 @@ and TcMethodApplication RaiseOperationResult errors match result with | None -> error(InternalError("at least one error should be returned by failed method overloading", mItem)) - | Some res -> res + | Some res -> res let finalCalledMethInfo = finalCalledMeth.Method let finalCalledMethInst = finalCalledMeth.CalledTyArgs @@ -9898,13 +9898,13 @@ and TcMethodApplication if (isInstance && finalCalledMethInfo.IsInstance && typeEquiv cenv.g finalCalledMethInfo.ApparentEnclosingType cenv.g.obj_ty && - (finalCalledMethInfo.LogicalName = "GetHashCode" || finalCalledMethInfo.LogicalName = "Equals")) then + (finalCalledMethInfo.LogicalName = "GetHashCode" || finalCalledMethInfo.LogicalName = "Equals")) then objArgs |> List.iter (fun expr -> ConstraintSolver.AddCxTypeMustSupportEquality env.DisplayEnv cenv.css mMethExpr NoTrace (tyOfExpr cenv.g expr)) // Uses of a Dictionary() constructor without an IEqualityComparer argument imply an equality constraint // on the first type argument. - if HasHeadType cenv.g cenv.g.tcref_System_Collections_Generic_Dictionary finalCalledMethInfo.ApparentEnclosingType && + if HasHeadType cenv.g cenv.g.tcref_System_Collections_Generic_Dictionary finalCalledMethInfo.ApparentEnclosingType && finalCalledMethInfo.IsConstructor && not (finalCalledMethInfo.GetParamDatas(cenv.amap, mItem, finalCalledMeth.CalledTyArgs) |> List.existsSquared (fun (ParamData(_, _, _, _, _, _, _, ty)) -> @@ -9932,8 +9932,8 @@ and TcMethodApplication // For unapplied 'e.M' we first evaluate 'e' outside the lambda, i.e. 'let v = e in (fun arg -> v.M(arg))' let objArgPreBinder, objArgs = match objArgs, lambdaVars with - | [objArg], Some _ -> - if finalCalledMethInfo.IsExtensionMember && finalCalledMethInfo.ObjArgNeedsAddress(cenv.amap, mMethExpr) then + | [objArg], Some _ -> + if finalCalledMethInfo.IsExtensionMember && finalCalledMethInfo.ObjArgNeedsAddress(cenv.amap, mMethExpr) then error(Error(FSComp.SR.tcCannotPartiallyApplyExtensionMethodForByref(finalCalledMethInfo.DisplayName), mMethExpr)) let objArgTy = tyOfExpr cenv.g objArg let v, ve = mkCompGenLocal mMethExpr "objectArg" objArgTy @@ -9960,7 +9960,7 @@ and TcMethodApplication elif isLinqExpressionTy cenv.g calledArgTy && isDelegateTy cenv.g (destLinqExpressionTy cenv.g calledArgTy) && isFunTy cenv.g callerArgTy then let delegateTy = destLinqExpressionTy cenv.g calledArgTy let expr = CoerceFromFSharpFuncToDelegate cenv.g cenv.amap cenv.infoReader ad callerArgTy m callerArgExpr delegateTy - None, mkCallQuoteToLinqLambdaExpression cenv.g m delegateTy (Expr.Quote(expr, ref None, false, m, mkQuotedExprTy cenv.g delegateTy)) + None, mkCallQuoteToLinqLambdaExpression cenv.g m delegateTy (Expr.Quote(expr, ref None, false, m, mkQuotedExprTy cenv.g delegateTy)) // auto conversions to quotations (to match auto conversions to LINQ expressions) elif reflArgInfo.AutoQuote && isQuotedExprTy cenv.g calledArgTy && not (isQuotedExprTy cenv.g callerArgTy) then @@ -10002,7 +10002,7 @@ and TcMethodApplication let arg = [ { NamedArgIdOpt = None CalledArg=paramArrayCalledArg - CallerArg=CallerArg(paramArrayCalledArg.CalledArgumentType, mMethExpr, false, Expr.Op(TOp.Array, [paramArrayCalledArgElementType], es , mMethExpr)) } ] + CallerArg=CallerArg(paramArrayCalledArg.CalledArgumentType, mMethExpr, false, Expr.Op(TOp.Array, [paramArrayCalledArgElementType], es, mMethExpr)) } ] paramArrayPreBinders, arg // CLEANUP: Move all this code into some isolated file, e.g. "optional.fs" @@ -10012,14 +10012,14 @@ and TcMethodApplication // CallerSide optional arguments are largely for COM interop, e.g. to PIA assemblies for Word etc. // As a result we follow the VB and C# behavior here. // - // "1. If the parameter is statically typed as System.Object and does not have a value, then there are four cases: - // a. The parameter is marked with MarshalAs(IUnknown), MarshalAs(Interface), or MarshalAs(IDispatch). In this case we pass null. - // b. Else if the parameter is marked with IUnknownConstantAttribute. In this case we pass new System.Runtime.InteropServices.UnknownWrapper(null) - // c. Else if the parameter is marked with IDispatchConstantAttribute. In this case we pass new System.Runtime.InteropServices.DispatchWrapper(null) - // d. Else, we will pass Missing.Value. - // 2. Otherwise, if there is a value attribute, then emit the default value. - // 3. Otherwise, we emit default(T). - // 4. Finally, we apply conversions from the value to the parameter type. This is where the nullable conversions take place for VB. + // "1. If the parameter is statically typed as System.Object and does not have a value, then there are four cases: + // a. The parameter is marked with MarshalAs(IUnknown), MarshalAs(Interface), or MarshalAs(IDispatch). In this case we pass null. + // b. Else if the parameter is marked with IUnknownConstantAttribute. In this case we pass new System.Runtime.InteropServices.UnknownWrapper(null) + // c. Else if the parameter is marked with IDispatchConstantAttribute. In this case we pass new System.Runtime.InteropServices.DispatchWrapper(null) + // d. Else, we will pass Missing.Value. + // 2. Otherwise, if there is a value attribute, then emit the default value. + // 3. Otherwise, we emit default(T). + // 4. Finally, we apply conversions from the value to the parameter type. This is where the nullable conversions take place for VB. // - VB allows you to mark ref parameters as optional. The semantics of this is that we create a temporary // with type = type of parameter, load the optional value to it, and call the method. // - VB also allows you to mark arrays with Nothing as the optional value. @@ -10145,7 +10145,7 @@ and TcMethodApplication finalUnnamedCalledOutArgs |> List.map (fun calledArg -> let calledArgTy = calledArg.CalledArgumentType let outArgTy = destByrefTy cenv.g calledArgTy - let outv, outArgExpr = mkMutableCompGenLocal mMethExpr PrettyNaming.outArgCompilerGeneratedName outArgTy // mutable! + let outv, outArgExpr = mkMutableCompGenLocal mMethExpr PrettyNaming.outArgCompilerGeneratedName outArgTy // mutable! let expr = mkDefault(mMethExpr, outArgTy) let callerArg = CallerArg(calledArgTy, mMethExpr, false, mkValAddr mMethExpr false (mkLocalValRef outv)) let outArg = { NamedArgIdOpt=None;CalledArg=calledArg;CallerArg=callerArg } @@ -10182,7 +10182,7 @@ and TcMethodApplication let item = Item.ArgName (defaultArg assignedArg.CalledArg.NameOpt id, assignedArg.CalledArg.CalledArgumentType, Some(ArgumentContainer.Method(finalCalledMethInfo))) CallNameResolutionSink cenv.tcSink (id.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.Use, env.DisplayEnv, ad)) - let allArgsPreBinders, allArgsCoerced = List.map coerce allArgs |> List.unzip + let allArgsPreBinders, allArgsCoerced = List.map coerce allArgs |> List.unzip // Make the call expression let expr, exprty = @@ -10203,8 +10203,8 @@ and TcMethodApplication if isNil outArgTmpBinds then expr, exprty else let outArgTys = outArgExprs |> List.map (tyOfExpr cenv.g) - let expr = if isUnitTy cenv.g exprty then mkCompGenSequential mMethExpr expr (mkRefTupled cenv.g mMethExpr outArgExprs outArgTys) - else mkRefTupled cenv.g mMethExpr (expr :: outArgExprs) (exprty :: outArgTys) + let expr = if isUnitTy cenv.g exprty then mkCompGenSequential mMethExpr expr (mkRefTupled cenv.g mMethExpr outArgExprs outArgTys) + else mkRefTupled cenv.g mMethExpr (expr :: outArgExprs) (exprty :: outArgTys) let expr = mkLetsBind mMethExpr outArgTmpBinds expr expr, tyOfExpr cenv.g expr @@ -10217,7 +10217,7 @@ and TcMethodApplication else // This holds the result of the call let objv, objExpr = mkMutableCompGenLocal mMethExpr "returnVal" exprty // mutable in case it's a struct - // This expression mutates the properties on the result of the call + // This expression mutates the properties on the result of the call let setterExprPrebinders, propSetExpr = (mkUnit cenv.g mMethExpr, finalAssignedItemSetters) ||> List.mapFold (fun acc (AssignedItemSetter(id, setter, CallerArg(callerArgTy, m, isOptCallerArg, argExpr))) -> if isOptCallerArg then error(Error(FSComp.SR.tcInvalidOptionalAssignmentToPropertyOrField(), m)) @@ -10234,7 +10234,7 @@ and TcMethodApplication | AssignedILFieldSetter finfo -> // Get or set instance IL field - ILFieldInstanceChecks cenv.g cenv.amap ad m finfo + ILFieldInstanceChecks cenv.g cenv.amap ad m finfo let calledArgTy = finfo.FieldType (cenv.amap, m) let argExprPrebinder, argExpr = coerceExpr false calledArgTy ReflectedArgInfo.None callerArgTy m argExpr let action = BuildILFieldSet cenv.g m objExpr finfo argExpr @@ -10255,7 +10255,7 @@ and TcMethodApplication argExprPrebinder, mkCompGenSequential m acc action) // now put them together - let expr = mkCompGenLet mMethExpr objv expr (mkCompGenSequential mMethExpr propSetExpr objExpr) + let expr = mkCompGenLet mMethExpr objv expr (mkCompGenSequential mMethExpr propSetExpr objExpr) setterExprPrebinders, expr // Build the lambda expression if any @@ -10294,14 +10294,14 @@ and TcMethodApplication and TcUnnamedMethodArgs cenv env lambdaPropagationInfo tpenv args = List.mapiFoldSquared (TcUnnamedMethodArg cenv env) (lambdaPropagationInfo, tpenv) args -and TcUnnamedMethodArg cenv env (lambdaPropagationInfo, tpenv) (i, j, CallerArg(argTy, mArg, isOpt, argExpr)) = +and TcUnnamedMethodArg cenv env (lambdaPropagationInfo, tpenv) (i, j, CallerArg(argTy, mArg, isOpt, argExpr)) = // Try to find the lambda propagation info for the corresponding unnamed argument at this position let lambdaPropagationInfoForArg = [| for (unnamedInfo, _) in lambdaPropagationInfo -> if i < unnamedInfo.Length && j < unnamedInfo.[i].Length then unnamedInfo.[i].[j] else NoInfo |] TcMethodArg cenv env (lambdaPropagationInfo, tpenv) (lambdaPropagationInfoForArg, CallerArg(argTy, mArg, isOpt, argExpr)) -and TcMethodNamedArgs cenv env lambdaPropagationInfo tpenv args = +and TcMethodNamedArgs cenv env lambdaPropagationInfo tpenv args = List.mapFoldSquared (TcMethodNamedArg cenv env) (lambdaPropagationInfo, tpenv) args and TcMethodNamedArg cenv env (lambdaPropagationInfo, tpenv) (CallerNamedArg(id, arg)) = @@ -10316,7 +10316,7 @@ and TcMethodNamedArg cenv env (lambdaPropagationInfo, tpenv) (CallerNamedArg(id, let arg', (lambdaPropagationInfo, tpenv) = TcMethodArg cenv env (lambdaPropagationInfo, tpenv) (lambdaPropagationInfoForArg, arg) CallerNamedArg(id, arg'), (lambdaPropagationInfo, tpenv) -and TcMethodArg cenv env (lambdaPropagationInfo, tpenv) (lambdaPropagationInfoForArg, CallerArg(argTy, mArg, isOpt, argExpr)) = +and TcMethodArg cenv env (lambdaPropagationInfo, tpenv) (lambdaPropagationInfoForArg, CallerArg(argTy, mArg, isOpt, argExpr)) = // Apply the F# 3.1 rule for extracting information for lambdas // @@ -10362,8 +10362,8 @@ and TcMethodArg cenv env (lambdaPropagationInfo, tpenv) (lambdaPropagationInfo let lambdaPropagationInfo = [| for (info, argInfo) in Array.zip lambdaPropagationInfo lambdaPropagationInfoForArg do match argInfo with - | ArgDoesNotMatch _ -> () - | NoInfo | CallerLambdaHasArgTypes _ -> + | ArgDoesNotMatch _ -> () + | NoInfo | CallerLambdaHasArgTypes _ -> yield info | CalledArgMatchesType adjustedCalledTy -> if AddCxTypeMustSubsumeTypeMatchingOnlyUndoIfFailed env.DisplayEnv cenv.css mArg adjustedCalledTy argTy then @@ -10382,7 +10382,7 @@ and TcNewDelegateThen cenv overallTy env tpenv mDelTy mExprAndArg delegateTy arg match args with | [farg], [] -> let m = arg.Range - let callerArg, (_, tpenv) = TcMethodArg cenv env (Array.empty, tpenv) (Array.empty, CallerArg(fty, m, false, farg)) + let callerArg, (_, tpenv) = TcMethodArg cenv env (Array.empty, tpenv) (Array.empty, CallerArg(fty, m, false, farg)) let expr = BuildNewDelegateExpr (None, cenv.g, cenv.amap, delegateTy, invokeMethInfo, delArgTys, callerArg.Expr, fty, m) PropagateThenTcDelayed cenv overallTy env tpenv m (MakeApplicableExprNoFlex cenv expr) delegateTy atomicFlag delayed | _ -> @@ -10443,7 +10443,7 @@ and TcLinearExprs bodyChecker cenv env overallTy tpenv isCompExpr expr cont = let thenExpr, tpenv = let env = match env.eContextInfo with - | ContextInfo.ElseBranchResult _ -> { env with eContextInfo = ContextInfo.ElseBranchResult synThenExpr.Range } + | ContextInfo.ElseBranchResult _ -> { env with eContextInfo = ContextInfo.ElseBranchResult synThenExpr.Range } | _ -> match synElseExprOpt with | None -> { env with eContextInfo = ContextInfo.OmittedElseBranch synThenExpr.Range } @@ -10485,7 +10485,7 @@ and TcMatchPattern cenv inputTy env tpenv (pat: SynPat, optWhenExpr) = match optWhenExpr with | Some whenExpr -> let guardEnv = { envinner with eContextInfo = ContextInfo.PatternMatchGuard whenExpr.Range } - let whenExpr', tpenv = TcExpr cenv cenv.g.bool_ty guardEnv tpenv whenExpr + let whenExpr', tpenv = TcExpr cenv cenv.g.bool_ty guardEnv tpenv whenExpr Some whenExpr', tpenv | None -> None, tpenv patf' (TcPatPhase2Input (values, true)), optWhenExpr', NameMap.range vspecMap, envinner, tpenv @@ -10524,11 +10524,11 @@ and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBindi match overallExprTy with | ty when isByrefTy cenv.g ty -> let okByRef = - match stripExpr fixedExpr with + match stripExpr fixedExpr with | Expr.Op (op, tyargs, args, _) -> match op, tyargs, args with | TOp.ValFieldGetAddr (rfref, _), _, [_] -> not rfref.Tycon.IsStructOrEnumTycon - | TOp.ILAsm ([ I_ldflda (fspec)], _), _, _ -> fspec.DeclaringType.Boxity = ILBoxity.AsObject + | TOp.ILAsm ([ I_ldflda (fspec)], _), _, _ -> fspec.DeclaringType.Boxity = ILBoxity.AsObject | TOp.ILAsm ([ I_ldelema _], _), _, _ -> true | TOp.RefAddrGet _, _, _ -> true | _ -> false @@ -10538,7 +10538,7 @@ and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBindi let elemTy = destByrefTy cenv.g overallExprTy UnifyTypes cenv env mBinding (mkNativePtrTy cenv.g elemTy) overallPatTy - mkCompGenLetIn mBinding "pinnedByref" ty fixedExpr (fun (v, ve) -> + mkCompGenLetIn mBinding "pinnedByref" ty fixedExpr (fun (v, ve) -> v.SetIsFixed() mkConvToNativeInt cenv.g ve mBinding) @@ -10580,7 +10580,7 @@ and TcAndBuildFixedExpr cenv env (overallPatTy, fixedExpr, overallExprTy, mBindi // check for non-null and non-empty let zero = mkConvToNativeInt cenv.g (mkInt32 cenv.g mBinding 0) mBinding // This is arr.Length - let arrayLengthExpr = mkCallArrayLength cenv.g mBinding elemTy ve + let arrayLengthExpr = mkCallArrayLength cenv.g mBinding elemTy ve mkNullTest cenv.g mBinding ve (mkNullTest cenv.g mBinding arrayLengthExpr (mkCompGenLetIn mBinding "pinnedByref" (mkByrefTy cenv.g elemTy) elemZeroAddress (fun (v, ve) -> @@ -10708,8 +10708,8 @@ and TcNormalizedBinding declKind (cenv: cenv) env tpenv overallTy safeThisValOpt let apinfoOpt = match NameMap.range nameToPrelimValSchemeMap with | [PrelimValScheme1(id, _, ty, _, _, _, _, _, _, _, _) ] -> - match ActivePatternInfoOfValName id.idText id.idRange with - | Some apinfo -> Some (apinfo, ty, id.idRange) + match ActivePatternInfoOfValName id.idText id.idRange with + | Some apinfo -> Some (apinfo, ty, id.idRange) | None -> None | _ -> None @@ -10811,7 +10811,7 @@ and TcBindingTyparDecls alwaysRigid cenv env tpenv (SynValTyparDecls(synTypars, declaredTypars |> List.iter (fun tp -> tp.SetRigidity TyparRigidity.WillBeRigid) rigidCopyOfDeclaredTypars - ExplicitTyparInfo(rigidCopyOfDeclaredTypars, declaredTypars, infer) , tpenv + ExplicitTyparInfo(rigidCopyOfDeclaredTypars, declaredTypars, infer), tpenv and TcNonrecBindingTyparDecls cenv env tpenv bind = let (NormalizedBinding(_, _, _, _, _, _, synTyparDecls, _, _, _, _, _)) = bind @@ -10826,12 +10826,12 @@ and TcNonRecursiveBinding declKind cenv env tpenv ty b = // TcAttribute* //------------------------------------------------------------------------ -and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = +and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = let (LongIdentWithDots(tycon, _)) = synAttr.TypeName - let arg = synAttr.ArgExpr - let targetIndicator = synAttr.Target + let arg = synAttr.ArgExpr + let targetIndicator = synAttr.Target let isAppliedToGetterOrSetter = synAttr.AppliesToGetterAndSetter - let mAttr = synAttr.Range + let mAttr = synAttr.Range let (typath, tyid) = List.frontAndBack tycon let tpenv = emptyUnscopedTyparEnv @@ -10843,9 +10843,9 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = let tyid = mkSynId tyid.idRange n let tycon = (typath @ [tyid]) let ad = env.eAccessRights - match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInAttribute OpenQualified env.eNameResEnv ad tycon TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No with + match ResolveTypeLongIdent cenv.tcSink cenv.nameResolver ItemOccurence.UseInAttribute OpenQualified env.eNameResEnv ad tycon TypeNameResolutionStaticArgsInfo.DefiniteEmpty PermitDirectReferenceToGeneratedType.No with | Exception err -> raze(err) - | _ -> success(TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInAttribute env tpenv (SynType.App(SynType.LongIdent(LongIdentWithDots(tycon, [])), None, [], [], None, false, mAttr)) ) + | _ -> success(TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInAttribute env tpenv (SynType.App(SynType.LongIdent(LongIdentWithDots(tycon, [])), None, [], [], None, false, mAttr)) ) ForceRaise ((try1 (tyid.idText + "Attribute")) |> ResultOrException.otherwise (fun () -> (try1 tyid.idText))) let ad = env.eAccessRights @@ -10887,7 +10887,7 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = AttribBoolArg(_allowMultiple) AttribBoolArg(inherited)], _, _, _, _)) -> (validOn, inherited) - | Some _ -> + | Some _ -> warning(Error(FSComp.SR.tcUnexpectedConditionInImportedAssembly(), mAttr)) (validOnDefault, inheritedDefault) | _ -> @@ -10902,10 +10902,10 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = | Some id when id.idText = "property" -> AttributeTargets.Property | Some id when id.idText = "method" -> AttributeTargets.Method | Some id when id.idText = "param" -> AttributeTargets.Parameter - | Some id when id.idText = "type" -> AttributeTargets.TyconDecl - | Some id when id.idText = "constructor" -> AttributeTargets.Constructor - | Some id when id.idText = "event" -> AttributeTargets.Event - | Some id -> + | Some id when id.idText = "type" -> AttributeTargets.TyconDecl + | Some id when id.idText = "constructor" -> AttributeTargets.Constructor + | Some id when id.idText = "event" -> AttributeTargets.Event + | Some id -> errorR(Error(FSComp.SR.tcUnrecognizedAttributeTarget(), id.idRange)) possibleTgts | _ -> possibleTgts @@ -10927,7 +10927,7 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = let meths = minfos |> List.map (fun minfo -> minfo, None) let afterResolution = ForNewConstructors cenv.tcSink env tyid.idRange methodName minfos let (expr, attributeAssignedNamedItems, _), _ = - TcMethodApplication true cenv env tpenv None [] mAttr mAttr methodName None ad PossiblyMutates false meths afterResolution NormalValUse [arg] (NewInferenceType ()) [] + TcMethodApplication true cenv env tpenv None [] mAttr mAttr methodName None ad PossiblyMutates false meths afterResolution NormalValUse [arg] (NewInferenceType ()) [] UnifyTypes cenv env mAttr ty (tyOfExpr cenv.g expr) @@ -10950,12 +10950,12 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = CheckILFieldAttributes cenv.g finfo m id.idText, false, finfo.FieldType(cenv.amap, m) | Item.RecdField rfinfo when not rfinfo.IsStatic -> - CheckRecdFieldInfoAttributes cenv.g rfinfo m |> CommitOperationResult + CheckRecdFieldInfoAttributes cenv.g rfinfo m |> CommitOperationResult CheckRecdFieldInfoAccessible cenv.amap m ad rfinfo // This uses the F# backend name mangling of fields.... - let nm = ComputeFieldName rfinfo.Tycon rfinfo.RecdField + let nm = ComputeFieldName rfinfo.Tycon rfinfo.RecdField nm, false, rfinfo.FieldType - | _ -> + | _ -> errorR(Error(FSComp.SR.tcPropertyOrFieldNotFoundInAttribute(), m)) id.idText, false, cenv.g.unit_ty let propNameItem = Item.SetterArg(id, setterItem) @@ -10973,7 +10973,7 @@ and TcAttribute canFail cenv (env: TcEnv) attrTgt (synAttr: SynAttribute) = Attrib(tcref, ILAttrib(ilMethRef), args, namedAttribArgMap, isAppliedToGetterOrSetter, Some constrainedTgts, m) | Expr.App((InnerExprPat(ExprValWithPossibleTypeInst(vref, _, _, _))), _, _, args, _) -> - let args = args |> List.collect (function Expr.Const(Const.Unit, _, _) -> [] | expr -> tryDestRefTupleExpr expr) |> List.map mkAttribExpr + let args = args |> List.collect (function Expr.Const(Const.Unit, _, _) -> [] | expr -> tryDestRefTupleExpr expr) |> List.map mkAttribExpr Attrib(tcref, FSAttrib(vref), args, namedAttribArgMap, isAppliedToGetterOrSetter, Some constrainedTgts, mAttr) | _ -> @@ -11039,9 +11039,9 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds // Generalize the bindings... (((fun x -> x), env, tpenv), checkedBinds) ||> List.fold (fun (buildExpr, env, tpenv) tbinfo -> let (CheckedBindingInfo(inlineFlag, attrs, doc, tcPatPhase2, flex, nameToPrelimValSchemeMap, rhsExpr, _, tauTy, m, spBind, _, konst, isFixed)) = tbinfo - let enclosingDeclaredTypars = [] + let enclosingDeclaredTypars = [] let (ExplicitTyparInfo(_, declaredTypars, canInferTypars)) = flex - let allDeclaredTypars = enclosingDeclaredTypars @ declaredTypars + let allDeclaredTypars = enclosingDeclaredTypars @ declaredTypars let generalizedTypars, prelimValSchemes2 = let canInferTypars = GeneralizationHelpers. ComputeCanInferExtraGeneralizableTypars (containerInfo.ParentRef, canInferTypars, None) @@ -11056,7 +11056,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds GeneralizationHelpers.ComputeAndGeneralizeGenericTypars (cenv, denv, m, freeInEnv, canInferTypars, canConstrain, inlineFlag, Some rhsExpr, allDeclaredTypars, maxInferredTypars, tauTy, false) - let prelimValSchemes2 = GeneralizeVals cenv denv enclosingDeclaredTypars generalizedTypars nameToPrelimValSchemeMap + let prelimValSchemes2 = GeneralizeVals cenv denv enclosingDeclaredTypars generalizedTypars nameToPrelimValSchemeMap generalizedTypars, prelimValSchemes2 @@ -11076,7 +11076,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds | (TPat_wild _ | TPat_const (Const.Unit, _)) when not isUse && not isFixed && isNil generalizedTypars -> let mkSequentialBind (tm, tmty) = (mkSequential SequencePointsAtSeq m rhsExpr tm, tmty) - (buildExpr >> mkSequentialBind , env, tpenv) + (buildExpr >> mkSequentialBind, env, tpenv) | _ -> // nice: don't introduce awful temporary for r.h.s. in the 99% case where we know what we're binding it to @@ -11089,7 +11089,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds v, pat //Op (LValueOp (LByrefGet,x),[],[],C:\GitHub\dsyme\visualfsharp\a.fs (15,42--15,43) IsSynthetic=false) - | _ when inlineFlag.MustInline -> + | _ when inlineFlag.MustInline -> error(Error(FSComp.SR.tcInvalidInlineSpecification(), m)) | _ -> @@ -11106,7 +11106,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds tmp, checkedPat - // Add the bind "let patternInputTmp = rhsExpr" to the bodyExpr we get from mkPatBind + // Add the bind "let patternInputTmp = rhsExpr" to the bodyExpr we get from mkPatBind let mkRhsBind (bodyExpr, bodyExprTy) = let letExpr = mkLet spBind m patternInputTmp rhsExpr bodyExpr letExpr, bodyExprTy @@ -11133,7 +11133,7 @@ and TcLetBinding cenv isUse env containerInfo declKind tpenv (synBinds, synBinds let envInner = AddLocalValMap cenv.tcSink scopem prelimRecValues env - ((buildExpr >> mkCleanup >> mkPatBind >> mkRhsBind), envInner, tpenv)) + ((buildExpr >> mkCleanup >> mkPatBind >> mkRhsBind), envInner, tpenv)) /// Return binds corresponding to the linearised let-bindings. /// This reveals the bound items, e.g. when the lets occur in incremental object defns. @@ -11149,8 +11149,8 @@ and TcLetBindings cenv env containerInfo declKind tpenv (binds, bindsm, scopem) let unite = mkUnit cenv.g bindsm let expr, _ = mkf (unite, cenv.g.unit_ty) let rec stripLets acc = function - | Expr.Let (bind, body, m, _) -> stripLets (TMDefLet(bind, m) :: acc) body - | Expr.Sequential (e1, e2, NormalSeq, _, m) -> stripLets (TMDefDo(e1, m) :: acc) e2 + | Expr.Let (bind, body, m, _) -> stripLets (TMDefLet(bind, m) :: acc) body + | Expr.Sequential (e1, e2, NormalSeq, _, m) -> stripLets (TMDefDo(e1, m) :: acc) e2 | Expr.Const (Const.Unit, _, _) -> List.rev acc | _ -> failwith "TcLetBindings: let sequence is non linear. Maybe a LHS pattern was not linearised?" let binds = stripLets [] expr @@ -11404,7 +11404,7 @@ and AnalyzeRecursiveStaticMemberOrValDecl match memberFlags.MemberKind with // Explicit struct or class constructor - | MemberKind.Constructor -> + | MemberKind.Constructor -> // A fairly adhoc place to put this check if tcref.IsStructOrEnumTycon && (match valSynInfo with SynValInfo([[]], _) -> true | _ -> false) then errorR(Error(FSComp.SR.tcStructsCannotHaveConstructorWithNoArguments(), mBinding)) @@ -11600,7 +11600,7 @@ and AnalyzeAndMakeAndPublishRecursiveValue overridesOK isGeneratedEventVal cenv // Do the type annotations give the full and complete generic type? // If so, generic recursion can be used when using this type. - let isComplete = ComputeIsComplete enclosingDeclaredTypars declaredTypars ty + let isComplete = ComputeIsComplete enclosingDeclaredTypars declaredTypars ty // NOTE: The type scheme here is normally not 'complete'!!!! The type is more or less just a type variable at this point. // NOTE: toparity, type and typars get fixed-up after inference @@ -11626,7 +11626,7 @@ and AnalyzeAndMakeAndPublishRecursiveValue overridesOK isGeneratedEventVal cenv // Suppress hover tip for "get" and "set" at property definitions, where toolId <> bindingId match toolIdOpt with - | Some tid when not tid.idRange.IsSynthetic && tid.idRange <> bindingId.idRange -> + | Some tid when not tid.idRange.IsSynthetic && tid.idRange <> bindingId.idRange -> let item = Item.Value (mkLocalValRef vspec) CallNameResolutionSink cenv.tcSink (tid.idRange, env.NameEnv, item, item, emptyTyparInst, ItemOccurence.RelatedText, env.DisplayEnv, env.eAccessRights) | _ -> () @@ -11684,7 +11684,7 @@ and TcLetrecBinding let allDeclaredTypars = enclosingDeclaredTypars @ rbind.RecBindingInfo.DeclaredTypars // Notes on FSharp 1.0, 3187: - // - Progressively collect the "eligible for early generalization" set of bindings -- DONE + // - Progressively collect the "eligible for early generalization" set of bindings -- DONE // - After checking each binding, check this set to find generalizable bindings // - The only reason we can't generalize is if a binding refers to type variables to which // additional constraints may be applied as part of checking a later binding @@ -11769,7 +11769,7 @@ and TcIncrementalLetRecGeneralization cenv scopem // to type variables free in later bindings. Look for ones whose type doesn't involve any of the other types let newGeneralizedRecBinds, preGeneralizationRecBinds, tpenv = - //printfn "\n---------------------\nConsidering early generalization after type checking binding %s" vspec.DisplayName + //printfn "\n---------------------\nConsidering early generalization after type checking binding %s" vspec.DisplayName // Get the type variables free in bindings that have not yet been checked. // @@ -11829,14 +11829,14 @@ and TcIncrementalLetRecGeneralization cenv scopem //printfn "(failed generalization test 1 for binding for %s)" pgrbind.RecBindingInfo.Val.DisplayName // Any declared type parameters in an type are always generalizable - let freeInBinding = Zset.diff freeInBinding (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.ExtraGeneralizableTypars)) + let freeInBinding = Zset.diff freeInBinding (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.ExtraGeneralizableTypars)) if freeInBinding.IsEmpty then true else //printfn "(failed generalization test 2 for binding for %s)" pgrbind.RecBindingInfo.Val.DisplayName // Any declared method parameters can always be generalized - let freeInBinding = Zset.diff freeInBinding (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.RecBindingInfo.DeclaredTypars)) + let freeInBinding = Zset.diff freeInBinding (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.RecBindingInfo.DeclaredTypars)) if freeInBinding.IsEmpty then true else @@ -11844,7 +11844,7 @@ and TcIncrementalLetRecGeneralization cenv scopem // Type variables free in the non-recursive environment do not stop us generalizing the binding, // since they can't be generalized anyway - let freeInBinding = Zset.diff freeInBinding freeInEnv + let freeInBinding = Zset.diff freeInBinding freeInEnv if freeInBinding.IsEmpty then true else @@ -11892,8 +11892,8 @@ and TcIncrementalLetRecGeneralization cenv scopem freeInEnv else let freeInBinding = (freeInType CollectAllNoCaching pgrbind.RecBindingInfo.Val.TauType).FreeTypars - let freeInBinding = Zset.diff freeInBinding (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.ExtraGeneralizableTypars)) - let freeInBinding = Zset.diff freeInBinding (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.RecBindingInfo.DeclaredTypars)) + let freeInBinding = Zset.diff freeInBinding (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.ExtraGeneralizableTypars)) + let freeInBinding = Zset.diff freeInBinding (Zset.ofList typarOrder (NormalizeDeclaredTyparsForEquiRecursiveInference cenv.g pgrbind.RecBindingInfo.DeclaredTypars)) Zset.union freeInBinding freeInEnv) // Process the bindings marked for transition from PreGeneralization --> PostGeneralization @@ -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)) @@ -12083,7 +12083,7 @@ and FixupLetrecBind cenv denv generalizedTyparsForRecursiveBlock (bind: PostBind | Some _ -> #endif match PartitionValTyparsForApparentEnclosingType cenv.g vspec with - | Some(parentTypars, memberParentTypars, _, _, _) -> + | Some(parentTypars, memberParentTypars, _, _, _) -> ignore(SignatureConformance.Checker(cenv.g, cenv.amap, denv, SignatureRepackageInfo.Empty, false).CheckTypars vspec.Range TypeEquivEnv.Empty memberParentTypars parentTypars) | None -> errorR(Error(FSComp.SR.tcMemberIsNotSufficientlyGeneric(), vspec.Range)) @@ -12106,7 +12106,7 @@ and FixupLetrecBind cenv denv generalizedTyparsForRecursiveBlock (bind: PostBind and unionGeneralizedTypars typarSets = List.foldBack (ListSet.unionFavourRight typarEq) typarSets [] -and TcLetrec overridesOK cenv env tpenv (binds, bindsm, scopem) = +and TcLetrec overridesOK cenv env tpenv (binds, bindsm, scopem) = // Create prelimRecValues for the recursive items (includes type info from LHS of bindings) *) let binds = binds |> List.map (fun (RecDefnBindingInfo(a, b, c, bind)) -> NormalizedRecBindingDefn(a, b, c, BindingNormalization.NormalizeBinding ValOrMemberBinding cenv env bind)) @@ -12115,7 +12115,7 @@ and TcLetrec overridesOK cenv env tpenv (binds, bindsm, scopem) = let envRec = AddLocalVals cenv.tcSink scopem prelimRecValues env // Typecheck bindings - let uncheckedRecBindsTable = uncheckedRecBinds |> List.map (fun rbind -> rbind.RecBindingInfo.Val.Stamp, rbind) |> Map.ofList + let uncheckedRecBindsTable = uncheckedRecBinds |> List.map (fun rbind -> rbind.RecBindingInfo.Val.Stamp, rbind) |> Map.ofList let (_, generalizedRecBinds, preGeneralizationRecBinds, tpenv, _) = ((env, [], [], tpenv, uncheckedRecBindsTable), uncheckedRecBinds) ||> List.fold (TcLetrecBinding (cenv, envRec, scopem, [], None)) @@ -12276,7 +12276,7 @@ module TcRecdUnionAndEnumDeclarations = begin if isIncrClass && (not zeroInit || not isMutable) then errorR(Error(FSComp.SR.tcUninitializedValFieldsMustBeMutable(), m)) if isStatic && (not zeroInit || not isMutable || vis <> Some SynAccess.Private ) then errorR(Error(FSComp.SR.tcStaticValFieldsMustBeMutableAndPrivate(), m)) let konst = if zeroInit then Some Const.Zero else None - let rfspec = MakeRecdFieldSpec cenv env parent (isStatic, konst, ty', attrsForProperty, attrsForField, id, nameGenerated, isMutable, isVolatile, xmldoc, vis, m) + let rfspec = MakeRecdFieldSpec cenv env parent (isStatic, konst, ty', attrsForProperty, attrsForField, id, nameGenerated, isMutable, isVolatile, xmldoc, vis, m) match parent with | Parent tcref when useGenuineField tcref.Deref rfspec -> // Recheck the attributes for errors if the definition only generates a field @@ -12333,7 +12333,7 @@ module TcRecdUnionAndEnumDeclarations = begin else seen.Add(f.Name, sf) - let TcUnionCaseDecl cenv env parent thisTy tpenv (UnionCase (synAttrs, id, args, xmldoc, vis, m)) = + let TcUnionCaseDecl cenv env parent thisTy tpenv (UnionCase (synAttrs, id, args, xmldoc, vis, m)) = let attrs = TcAttributes cenv env AttributeTargets.UnionCaseDecl synAttrs // the attributes of a union case decl get attached to the generated "static factory" method let vis, _ = ComputeAccessAndCompPath env None m vis None parent let vis = CombineReprAccess parent vis @@ -12385,7 +12385,7 @@ module TcRecdUnionAndEnumDeclarations = begin let TcEnumDecls cenv env parent thisTy enumCases = let fieldTy = NewInferenceType () - let enumCases' = enumCases |> List.map (TcEnumDecl cenv env parent thisTy fieldTy) |> CheckDuplicates (fun f -> f.Id) "enum element" + let enumCases' = enumCases |> List.map (TcEnumDecl cenv env parent thisTy fieldTy) |> CheckDuplicates (fun f -> f.Id) "enum element" fieldTy, enumCases' end @@ -12397,7 +12397,7 @@ end 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 + if tcref.HasInterface cenv.g ty' then errorR(Error(FSComp.SR.tcDuplicateSpecOfInterface(), m)) tcaug.tcaug_interfaces <- (ty', compgen, m) :: tcaug.tcaug_interfaces @@ -12413,7 +12413,7 @@ let TcAndPublishMemberSpec cenv env containerInfo declKind tpenv memb = [], tpenv -let TcTyconMemberSpecs cenv env containerInfo declKind tpenv (augSpfn: SynMemberSigs) = +let TcTyconMemberSpecs cenv env containerInfo declKind tpenv (augSpfn: SynMemberSigs) = let members, tpenv = List.mapFold (TcAndPublishMemberSpec cenv env containerInfo declKind) tpenv augSpfn List.concat members, tpenv @@ -12432,7 +12432,7 @@ let TcModuleOrNamespaceLidAndPermitAutoResolve tcSink env amap (longId: Ident li | 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 @@ -12476,7 +12476,7 @@ let TcOpenDecl tcSink (g: TcGlobals) amap m scopem env (longId: Ident list) = // Bug FSharp 1.0 3133: 'open Lexing'. Skip this warning if we successfully resolved to at least a module name if not (modrefs |> List.exists (fun (_, modref, _) -> modref.IsModule && not (HasFSharpAttribute g g.attrib_RequireQualifiedAccessAttribute modref.Attribs))) then modrefs |> List.iter (fun (_, modref, _) -> - if IsPartiallyQualifiedNamespace modref then + if IsPartiallyQualifiedNamespace modref then errorR(Error(FSComp.SR.tcOpenUsedWithPartiallyQualifiedPath(fullDisplayTextOfModRef modref), m))) let modrefs = List.map p23 modrefs @@ -12578,14 +12578,14 @@ module IncrClassChecking = let ctorTy = mkFunTy argty objTy // REVIEW: no attributes can currently be specified for the implicit constructor let attribs = TcAttributes cenv env (AttributeTargets.Constructor ||| AttributeTargets.Method) attrs - let memberFlags = CtorMemberFlags + let memberFlags = CtorMemberFlags - let synArgInfos = List.map (SynInfo.InferSynArgInfoFromSimplePat []) spats + let synArgInfos = List.map (SynInfo.InferSynArgInfoFromSimplePat []) spats let valSynData = SynValInfo([synArgInfos], SynInfo.unnamedRetVal) - let id = ident ("new", m) + let id = ident ("new", m) CheckForNonAbstractInterface ModuleOrMemberBinding tcref memberFlags id.idRange - let memberInfo = MakeMemberDataAndMangledNameForMemberVal(cenv.g, tcref, false, attribs, [], memberFlags, valSynData, id, false) + let memberInfo = MakeMemberDataAndMangledNameForMemberVal(cenv.g, tcref, false, attribs, [], memberFlags, valSynData, id, false) let partialValReprInfo = TranslateTopValSynInfo m (TcAttributes cenv env) valSynData let prelimTyschemeG = TypeScheme(copyOfTyconTypars, ctorTy) let isComplete = ComputeIsComplete copyOfTyconTypars [] ctorTy @@ -12605,7 +12605,7 @@ module IncrClassChecking = let valSynData = SynValInfo([[]], SynInfo.unnamedRetVal) let id = ident ("cctor", m) CheckForNonAbstractInterface ModuleOrMemberBinding tcref ClassCtorMemberFlags id.idRange - let memberInfo = MakeMemberDataAndMangledNameForMemberVal(cenv.g, tcref, false, [(*no attributes*)], [], ClassCtorMemberFlags, valSynData, id, false) + let memberInfo = MakeMemberDataAndMangledNameForMemberVal(cenv.g, tcref, false, [(*no attributes*)], [], ClassCtorMemberFlags, valSynData, id, false) let partialValReprInfo = TranslateTopValSynInfo m (TcAttributes cenv env) valSynData let prelimTyschemeG = TypeScheme(copyOfTyconTypars, cctorTy) let topValInfo = InferGenericArityFromTyScheme prelimTyschemeG partialValReprInfo @@ -12616,23 +12616,23 @@ module IncrClassChecking = let thisVal = // --- Create this for use inside constructor - let thisId = ident ("this", m) - let thisValScheme = ValScheme(thisId, NonGenericTypeScheme(thisTy), None, None, false, ValInline.Never, CtorThisVal, None, true, false, false, false) - let thisVal = MakeAndPublishVal cenv env (ParentNone, false, ClassLetBinding(false), ValNotInRecScope, thisValScheme, [], XmlDoc.Empty, None, false) + let thisId = ident ("this", m) + let thisValScheme = ValScheme(thisId, NonGenericTypeScheme(thisTy), None, None, false, ValInline.Never, CtorThisVal, None, true, false, false, false) + let thisVal = MakeAndPublishVal cenv env (ParentNone, false, ClassLetBinding(false), ValNotInRecScope, thisValScheme, [], XmlDoc.Empty, None, false) thisVal - {TyconRef = tcref - InstanceCtorDeclaredTypars = copyOfTyconTypars - StaticCtorValInfo = cctorValInfo - InstanceCtorArgs = ctorArgs - InstanceCtorVal = ctorVal - InstanceCtorValScheme = ctorValScheme - InstanceCtorBaseValOpt = baseValOpt - InstanceCtorSafeThisValOpt = safeThisValOpt - InstanceCtorSafeInitInfo = safeInitInfo - InstanceCtorThisVal = thisVal + {TyconRef = tcref + InstanceCtorDeclaredTypars = copyOfTyconTypars + StaticCtorValInfo = cctorValInfo + InstanceCtorArgs = ctorArgs + InstanceCtorVal = ctorVal + InstanceCtorValScheme = ctorValScheme + InstanceCtorBaseValOpt = baseValOpt + InstanceCtorSafeThisValOpt = safeThisValOpt + InstanceCtorSafeInitInfo = safeInitInfo + InstanceCtorThisVal = thisVal // For generating names of local fields - NameGenerator = NiceNameGenerator() + NameGenerator = NiceNameGenerator() } @@ -12646,8 +12646,8 @@ module IncrClassChecking = /// 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 name = rfref.FieldName - let id = ident (name, v.Range) - let ty = v.Type |> instType formalTyparInst + let id = ident (name, v.Range) + let ty = v.Type |> instType formalTyparInst let taccess = TAccess [cpath] let isVolatile = HasFSharpAttribute g g.attrib_VolatileFieldAttribute v.Attribs @@ -12781,7 +12781,7 @@ module IncrClassChecking = ValReprInfo(tpNames@ValReprInfo.InferTyparInfo(copyOfTyconTypars), args, ret) let prelimTyschemeG = TypeScheme(copyOfTyconTypars@tps, memberTauTy) - let memberValScheme = ValScheme(id, prelimTyschemeG, Some(topValInfo), Some(memberInfo), false, ValInline.Never, NormalVal, None, true (* isCompilerGenerated *) , true (* isIncrClass *) , false, false) + let memberValScheme = ValScheme(id, prelimTyschemeG, Some(topValInfo), Some(memberInfo), false, ValInline.Never, NormalVal, None, true (* isCompilerGenerated *), true (* isIncrClass *), false, false) let methodVal = MakeAndPublishVal cenv env (Parent(tcref), false, ModuleOrMemberBinding, ValNotInRecScope, memberValScheme, v.Attribs, XmlDoc.Empty, None, false) reportIfUnused() InMethod(isStatic, methodVal, topValInfo) @@ -12803,7 +12803,7 @@ module IncrClassChecking = 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 @@ -12811,7 +12811,7 @@ module IncrClassChecking = member localRep.IsValRepresentedAsMethod (v: Val) = localRep.IsValWithRepresentation(v) && match localRep.LookupRepr(v) with - | InMethod _ -> true + | InMethod _ -> true | _ -> false /// Make the elaborated expression that represents a use of a @@ -12879,13 +12879,13 @@ module IncrClassChecking = /// Used as part of processing "let" bindings in a type definition. member localRep.PublishIncrClassFields (cenv, denv, cpath, ctorInfo: IncrClassCtorLhs, safeStaticInitInfo) = let tcref = ctorInfo.TyconRef - let rfspecs = + let rfspecs = [ for KeyValue(v, repr) in localRep.ValReprs do match repr with | InField(isStatic, _, rfref) -> // Instance fields for structs are published earlier because the full set of fields is determined syntactically from the implicit // constructor arguments. This is important for the "default value" and "does it have an implicit default constructor" - // semantic conditions for structs - see bug FSharp 1.0 5304. + // semantic conditions for structs - see bug FSharp 1.0 5304. if isStatic || not tcref.IsFSharpStructOrEnumTycon then let ctorDeclaredTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv denv ctorInfo.TyconRef.Range @@ -12938,13 +12938,13 @@ module IncrClassChecking = Some (localRep.MakeValueLookup thisValOpt thisTyInst safeStaticInitInfo v [] m) // Rewrite assignments to mutable values stored as fields - | Expr.Op(TOp.LValueOp (LSet, ValDeref v) , [], [arg], m) + | Expr.Op(TOp.LValueOp (LSet, ValDeref v), [], [arg], m) when localRep.IsValWithRepresentation(v) -> let arg = rw arg Some (localRep.MakeValueAssign thisValOpt thisTyInst safeStaticInitInfo v arg m) // Rewrite taking the address of mutable values stored as fields - | Expr.Op(TOp.LValueOp (LAddrOf readonly, ValDeref v), [], [] , m) + | Expr.Op(TOp.LValueOp (LAddrOf readonly, ValDeref v), [], [], m) when localRep.IsValWithRepresentation(v) -> Some (localRep.MakeValueGetAddress readonly thisValOpt thisTyInst safeStaticInitInfo v m) @@ -12980,7 +12980,7 @@ module IncrClassChecking = let denv = env.DisplayEnv - let thisVal = ctorInfo.InstanceCtorThisVal + let thisVal = ctorInfo.InstanceCtorThisVal let m = thisVal.Range let ctorDeclaredTypars = ctorInfo.GetNormalizedInstanceCtorDeclaredTypars cenv denv m @@ -13039,7 +13039,7 @@ module IncrClassChecking = else unionFreeVars staticForcedFieldVars (freeInExpr CollectLocalsNoCaching e) (staticForcedFieldVars, instanceForcedFieldVars))) - let staticForcedFieldVars = (staticForcedFieldVars, memberBinds) ||> accFreeInBindings + let staticForcedFieldVars = (staticForcedFieldVars, memberBinds) ||> accFreeInBindings let instanceForcedFieldVars = (instanceForcedFieldVars, memberBinds) ||> accFreeInBindings // Any references to static variables in the 'inherits' expression force those static variables to be represented as fields @@ -13096,7 +13096,7 @@ module IncrClassChecking = let m = match spBind, rhsExpr with // Don't generate big sequence points for functions in classes - | _, (Expr.Lambda _ | Expr.TyLambda _) -> v.Range + | _, (Expr.Lambda _ | Expr.TyLambda _) -> v.Range | SequencePointAtBinding m, _ -> m | _ -> v.Range let assignExpr = reps.MakeValueAssign (Some thisVal) thisTyInst NoSafeInitInfo v rhsExpr m @@ -13122,17 +13122,17 @@ module IncrClassChecking = match dec with | (IncrClassBindingGroup(binds, isStatic, isRec)) -> let actions, reps, methodBinds = - let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ChooseAndAddRepresentation(cenv, env, isStatic, isCtorArg, ctorInfo, staticForcedFieldVars, instanceForcedFieldVars, bind)) // extend + let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ChooseAndAddRepresentation(cenv, env, isStatic, isCtorArg, ctorInfo, staticForcedFieldVars, instanceForcedFieldVars, bind)) // extend if isRec then // Note: the recursive calls are made via members on the object // or via access to fields. This means the recursive loop is "broken", // and we can collapse to sequential bindings - let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // inscope before + let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // inscope before let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip // since can occur in RHS of own defns actions, reps, methodBinds else - let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip - let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // inscope after + let actions, methodBinds = binds |> List.map (TransBind reps) |> List.unzip + let reps = (reps, binds) ||> List.fold (fun rep bind -> rep.ValNowWithRepresentation bind.Var) // inscope after actions, reps, methodBinds let methodBinds = List.concat methodBinds if isStatic then @@ -13158,7 +13158,7 @@ module IncrClassChecking = | Phase2CCtorJustAfterSuperInit -> let binders = [ match ctorInfo.InstanceCtorSafeThisValOpt with - | None -> () + | None -> () | Some v -> let setExpr = mkRefCellSet cenv.g m ctorInfo.InstanceCtorThisVal.Type (exprForVal m v) (exprForVal m ctorInfo.InstanceCtorThisVal) let setExpr = reps.FixupIncrClassExprPhase2C cenv (Some(thisVal)) safeStaticInitInfo thisTyInst setExpr @@ -13242,7 +13242,7 @@ module IncrClassChecking = // This ref cell itself may be stored in a field of the object and accessed via arg0. // Likewise the incoming arguments will eventually be stored in fields and accessed via arg0. // - // As a result, the most natural way to implement this would be to simply capture arg0 if needed + // As a result, the most natural way to implement this would be to simply capture arg0 if needed // and access all variables via that. This would be done by rewriting the inheritsExpr as follows: // let inheritsExpr = reps.FixupIncrClassExprPhase2C (Some(thisVal)) thisTyInst inheritsExpr // However, the rules of IL mean we are not actually allowed to capture arg0 @@ -13306,20 +13306,20 @@ module MutRecBindingChecking = /// Represents one element in a type definition, after the first phase type TyconBindingPhase2A = /// An entry corresponding to the definition of the implicit constructor for a class - | Phase2AIncrClassCtor of IncrClassCtorLhs + | Phase2AIncrClassCtor of IncrClassCtorLhs /// An 'inherit' declaration in an incremental class /// /// Phase2AInherit (ty, arg, baseValOpt, m) - | Phase2AInherit of SynType * SynExpr * Val option * range + | Phase2AInherit of SynType * SynExpr * Val option * range /// A set of value or function definitions in an incremental class /// /// Phase2AIncrClassBindings (tcref, letBinds, isStatic, isRec, m) | Phase2AIncrClassBindings of TyconRef * Ast.SynBinding list * bool * bool * range /// A 'member' definition in a class - | Phase2AMember of PreCheckingRecursiveBinding + | Phase2AMember of PreCheckingRecursiveBinding #if OPEN_IN_TYPE_DECLARATIONS /// A dummy declaration, should we ever support 'open' in type definitions - | Phase2AOpen of LongIdent * range + | Phase2AOpen of LongIdent * range #endif /// Indicates the super init has just been called, 'this' may now be published | Phase2AIncrClassCtorJustAfterSuperInit @@ -13331,15 +13331,15 @@ module MutRecBindingChecking = | TyconBindingsPhase2A of Tycon option * DeclKind * Val list * TyconRef * Typar list * TType * TyconBindingPhase2A list /// The collected syntactic input definitions for a recursive group of type or type-extension definitions - type MutRecDefnsPhase2AData = MutRecShape list + type MutRecDefnsPhase2AData = MutRecShape list /// Represents one element in a type definition, after the second phase type TyconBindingPhase2B = - | Phase2BIncrClassCtor of IncrClassCtorLhs * Tast.Binding option - | Phase2BInherit of Expr * Val option + | Phase2BIncrClassCtor of IncrClassCtorLhs * Tast.Binding option + | Phase2BInherit of Expr * Val option /// A set of value of function definitions in a class definition with an implicit constructor. | Phase2BIncrClassBindings of IncrClassBindingGroup list - | Phase2BMember of int + | Phase2BMember of int /// An intermediate definition that represent the point in an implicit class definition where /// the super type has been initialized. | Phase2BIncrClassCtorJustAfterSuperInit @@ -13354,10 +13354,10 @@ module MutRecBindingChecking = /// Represents one element in a type definition, after the third phase type TyconBindingPhase2C = - | Phase2CIncrClassCtor of IncrClassCtorLhs * Tast.Binding option - | Phase2CInherit of Expr * Val option + | Phase2CIncrClassCtor of IncrClassCtorLhs * Tast.Binding option + | Phase2CInherit of Expr * Val option | Phase2CIncrClassBindings of IncrClassBindingGroup list - | Phase2CMember of PreInitializationGraphEliminationBinding + | Phase2CMember of PreInitializationGraphEliminationBinding // Indicates the last 'field' has been initialized, only 'do' comes after | Phase2CIncrClassCtorJustAfterSuperInit | Phase2CIncrClassCtorJustAfterLastLet @@ -13374,18 +13374,18 @@ module MutRecBindingChecking = // The basic iteration over the declarations in a single type definition // State: - // tpenv: floating type parameter environment - // recBindIdx: index of the recursive binding - // prelimRecValuesRev: accumulation of prelim value entries - // uncheckedBindsRev: accumulation of unchecked bindings + // tpenv: floating type parameter environment + // recBindIdx: index of the recursive binding + // prelimRecValuesRev: accumulation of prelim value entries + // uncheckedBindsRev: accumulation of unchecked bindings let (defnsAs: MutRecDefnsPhase2AData), (tpenv, _, uncheckedBindsRev) = let initialOuterState = (tpenv, 0, ([]: PreCheckingRecursiveBinding list)) (initialOuterState, envMutRec, mutRecDefns) |||> MutRecShapes.mapFoldWithEnv (fun outerState envForDecls defn -> let (tpenv, recBindIdx, uncheckedBindsRev) = outerState match defn with - | MutRecShape.Module _ -> failwith "unreachable" - | MutRecShape.Open x -> MutRecShape.Open x, outerState - | MutRecShape.ModuleAbbrev x -> MutRecShape.ModuleAbbrev x, outerState + | MutRecShape.Module _ -> failwith "unreachable" + | MutRecShape.Open x -> MutRecShape.Open x, outerState + | MutRecShape.ModuleAbbrev x -> MutRecShape.ModuleAbbrev x, outerState | MutRecShape.Lets recBinds -> let normRecDefns = [ for (RecDefnBindingInfo(a, b, c, bind)) in recBinds do @@ -13492,7 +13492,7 @@ module MutRecBindingChecking = | MemberKind.Constructor -> error(Error(FSComp.SR.tcMeasureDeclarationsRequireStaticMembersNotConstructors(), m)) | _ -> () let rbind = NormalizedRecBindingDefn(containerInfo, newslotsOK, declKind, bind) - let overridesOK = DeclKind.CanOverrideOrImplement(declKind) + let overridesOK = DeclKind.CanOverrideOrImplement(declKind) let (binds, _values), (tpenv, recBindIdx) = AnalyzeAndMakeAndPublishRecursiveValue overridesOK false cenv envForTycon (tpenv, recBindIdx) rbind let cbinds = [ for rbind in binds -> Phase2AMember rbind ] @@ -13532,7 +13532,7 @@ module MutRecBindingChecking = let afterRev = restRev |> List.takeWhile isAfter let beforeRev = restRev |> List.skipWhile isAfter - [ yield! List.rev beforeRev + [ yield! List.rev beforeRev yield Phase2AIncrClassCtorJustAfterLastLet yield! List.rev afterRev ] b1 :: rest @@ -13554,7 +13554,7 @@ module MutRecBindingChecking = let (defnsBs: MutRecDefnsPhase2BData), (tpenv, generalizedRecBinds, preGeneralizationRecBinds, _, _) = - let uncheckedRecBindsTable = uncheckedRecBinds |> List.map (fun rbind -> rbind.RecBindingInfo.Val.Stamp, rbind) |> Map.ofList + let uncheckedRecBindsTable = uncheckedRecBinds |> List.map (fun rbind -> rbind.RecBindingInfo.Val.Stamp, rbind) |> Map.ofList // Loop through the types being defined... // @@ -13581,14 +13581,14 @@ module MutRecBindingChecking = match defnsA with | MutRecShape.Module _ -> failwith "unreachable" - | MutRecShape.Open x -> MutRecShape.Open x, outerState - | MutRecShape.ModuleAbbrev x -> MutRecShape.ModuleAbbrev x, outerState + | MutRecShape.Open x -> MutRecShape.Open x, outerState + | MutRecShape.ModuleAbbrev x -> MutRecShape.ModuleAbbrev x, outerState | MutRecShape.Lets binds -> let defnBs, (tpenv, _, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) = let initialInnerState = (tpenv, envForDecls, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) - (initialInnerState, binds) ||> List.mapFold (fun innerState rbind -> + (initialInnerState, binds) ||> List.mapFold (fun innerState rbind -> let (tpenv, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) = innerState @@ -13608,7 +13608,7 @@ module MutRecBindingChecking = let envForTycon = if isExtrinsic then envForTycon else AddLocalTyconRefs true cenv.g cenv.amap tcref.Range [tcref] envForTycon // Set up the environment so use-before-definition warnings are given, at least // until we reach a Phase2AIncrClassCtorJustAfterSuperInit. - let envForTycon = { envForTycon with eCtorInfo = Some (InitialImplicitCtorInfo()) } + let envForTycon = { envForTycon with eCtorInfo = Some (InitialImplicitCtorInfo()) } let reqdThisValTyOpt = Some thisTy @@ -13623,7 +13623,7 @@ module MutRecBindingChecking = let defnBs, (tpenv, _, _, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) = let initialInnerState = (tpenv, envForTycon, envForTycon, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) - (initialInnerState, defnAs) ||> List.mapFold (fun innerState defnA -> + (initialInnerState, defnAs) ||> List.mapFold (fun innerState defnA -> let (tpenv, envInstance, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) = innerState @@ -13636,8 +13636,8 @@ module MutRecBindingChecking = let envStatic = AddDeclaredTypars CheckForDuplicateTypars incrClassCtorLhs.InstanceCtorDeclaredTypars envStatic let envInstance = match incrClassCtorLhs.InstanceCtorSafeThisValOpt with Some v -> AddLocalVal cenv.tcSink scopem v envInstance | None -> envInstance let envInstance = List.foldBack AddLocalValPrimitive incrClassCtorLhs.InstanceCtorArgs envInstance - let envNonRec = match incrClassCtorLhs.InstanceCtorSafeThisValOpt with Some v -> AddLocalVal cenv.tcSink scopem v envNonRec | None -> envNonRec - let envNonRec = List.foldBack AddLocalValPrimitive incrClassCtorLhs.InstanceCtorArgs envNonRec + let envNonRec = match incrClassCtorLhs.InstanceCtorSafeThisValOpt with Some v -> AddLocalVal cenv.tcSink scopem v envNonRec | None -> envNonRec + let envNonRec = List.foldBack AddLocalValPrimitive incrClassCtorLhs.InstanceCtorArgs envNonRec let safeThisValBindOpt = TcLetrecComputeCtorSafeThisValBind cenv incrClassCtorLhs.InstanceCtorSafeThisValOpt let innerState = (tpenv, envInstance, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) @@ -13649,7 +13649,7 @@ module MutRecBindingChecking = let baseTy = baseTy |> convertToTypeWithMetadataIfPossible cenv.g let inheritsExpr, tpenv = TcNewExpr cenv envInstance tpenv baseTy (Some synBaseTy.Range) true arg m let envInstance = match baseValOpt with Some baseVal -> AddLocalVal cenv.tcSink scopem baseVal envInstance | None -> envInstance - let envNonRec = match baseValOpt with Some baseVal -> AddLocalVal cenv.tcSink scopem baseVal envNonRec | None -> envNonRec + let envNonRec = match baseValOpt with Some baseVal -> AddLocalVal cenv.tcSink scopem baseVal envNonRec | None -> envNonRec let innerState = (tpenv, envInstance, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) Phase2BInherit (inheritsExpr, baseValOpt), innerState @@ -13693,7 +13693,7 @@ module MutRecBindingChecking = | _ -> errorR (Error(FSComp.SR.tcMemberAndLocalClassBindingHaveSameName(nm), bind.Var.Range)) // Also add static entries to the envInstance if necessary - let envInstance = (if isStatic then (binds, envInstance) ||> List.foldBack (fun b e -> AddLocalVal cenv.tcSink scopem b.Var e) else env) + let envInstance = (if isStatic then (binds, envInstance) ||> List.foldBack (fun b e -> AddLocalVal cenv.tcSink scopem b.Var e) else env) let envStatic = (if isStatic then env else envStatic) let innerState = (tpenv, envInstance, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) Phase2BIncrClassBindings bindRs, innerState @@ -13704,7 +13704,7 @@ module MutRecBindingChecking = | Phase2AIncrClassCtorJustAfterLastLet -> let innerState = (tpenv, envInstance, envStatic, envNonRec, generalizedRecBinds, preGeneralizationRecBinds, uncheckedRecBindsTable) - Phase2BIncrClassCtorJustAfterLastLet , innerState + Phase2BIncrClassCtorJustAfterLastLet, innerState #if OPEN_IN_TYPE_DECLARATIONS @@ -13730,7 +13730,7 @@ module MutRecBindingChecking = // Type variables derived from the type definition (or implicit constructor) are always generalizable (we check their generalizability later). // Note they may be solved to be equi-recursive. - let extraGeneralizableTypars = copyOfTyconTypars + let extraGeneralizableTypars = copyOfTyconTypars // Inside the incremental class syntax we assert the type of the 'this' variable to be precisely the same type as the // this variable for the implicit class constructor. For static members, we assert the type variables associated @@ -13783,7 +13783,7 @@ module MutRecBindingChecking = | Phase2BInherit (inheritsExpr, basevOpt) -> Phase2CInherit (inheritsExpr, basevOpt) - | Phase2BIncrClassBindings bindRs -> + | Phase2BIncrClassBindings bindRs -> Phase2CIncrClassBindings bindRs | Phase2BIncrClassCtorJustAfterSuperInit -> @@ -13792,11 +13792,11 @@ module MutRecBindingChecking = | Phase2BIncrClassCtorJustAfterLastLet -> Phase2CIncrClassCtorJustAfterLastLet - | Phase2BMember idx -> + | Phase2BMember idx -> // Phase2C: Fixup member bindings let generalizedBinding = generalizedBindingsMap.[idx] let vxbind = TcLetrecAdjustMemberForSpecialVals cenv generalizedBinding - let pgbrind = FixupLetrecBind cenv denv generalizedTyparsForRecursiveBlock vxbind + let pgbrind = FixupLetrecBind cenv denv generalizedTyparsForRecursiveBlock vxbind Phase2CMember pgbrind) TyconBindingsPhase2C(tyconOpt, tcref, defnCs)) @@ -13805,7 +13805,7 @@ module MutRecBindingChecking = [ for idx in bindIdxs do let generalizedBinding = generalizedBindingsMap.[idx] let vxbind = TcLetrecAdjustMemberForSpecialVals cenv generalizedBinding - yield FixupLetrecBind cenv denv generalizedTyparsForRecursiveBlock vxbind ]) + yield FixupLetrecBind cenv denv generalizedTyparsForRecursiveBlock vxbind ]) // --- Extract field bindings from let-bindings @@ -13850,7 +13850,7 @@ module MutRecBindingChecking = | _ -> false) if needsSafeStaticInit && hasStaticBindings then - let rfield = MakeSafeInitField cenv.g envForDecls tcref.Range true + let rfield = MakeSafeInitField cenv.g envForDecls tcref.Range true SafeInitField(mkRecdFieldRef tcref rfield.Name, rfield) else NoSafeInitInfo @@ -13877,7 +13877,7 @@ module MutRecBindingChecking = // Compute the cpath used when creating the hidden fields let cpath = envForTycon.eAccessPath - let localDecs = + let localDecs = defnCs |> List.filter (function | Phase2CIncrClassBindings _ | Phase2CIncrClassCtorJustAfterSuperInit @@ -13886,7 +13886,7 @@ module MutRecBindingChecking = let memberBindsWithFixups = defnCs |> List.choose (function Phase2CMember pgrbind -> Some pgrbind | _ -> None) // Extend localDecs with "let safeThisVal = ref null" if there is a safeThisVal - let localDecs = + let localDecs = match safeThisValBindOpt with | None -> localDecs | Some bind -> Phase2CIncrClassBindings [IncrClassBindingGroup([bind], false, false)] :: localDecs @@ -13898,7 +13898,7 @@ module MutRecBindingChecking = [ for localDec in localDecs do match localDec with | Phase2CIncrClassBindings(binds) -> yield Phase2CBindings binds - | Phase2CIncrClassCtorJustAfterSuperInit -> yield Phase2CCtorJustAfterSuperInit + | Phase2CIncrClassCtorJustAfterSuperInit -> yield Phase2CCtorJustAfterSuperInit | Phase2CIncrClassCtorJustAfterLastLet -> yield Phase2CCtorJustAfterLastLet | _ -> () ] let memberBinds = memberBindsWithFixups |> List.map (fun x -> x.Binding) @@ -13916,7 +13916,7 @@ module MutRecBindingChecking = | Some(cctorBodyLambdaExpr) -> [ (let _, cctorVal, cctorValScheme = incrClassCtorLhs.StaticCtorValInfo.Force() let cctorValueExprBinding = TBind(cctorVal, cctorBodyLambdaExpr, NoSequencePointAtStickyBinding) - let rbind = { ValScheme = cctorValScheme; Binding = cctorValueExprBinding } + let rbind = { ValScheme = cctorValScheme; Binding = cctorValueExprBinding } FixupLetrecBind cenv envForDecls.DisplayEnv generalizedTyparsForRecursiveBlock rbind) ] ) // Publish the fields of the representation to the type @@ -13981,11 +13981,11 @@ module MutRecBindingChecking = /// Compute the active environments within each nested module. let TcMutRecDefns_ComputeEnvs getTyconOpt getVals (cenv: cenv) report scopem m envInitial mutRecShape = (envInitial, mutRecShape) ||> MutRecShapes.computeEnvs - (fun envAbove (MutRecDefnsPhase2DataForModule (mtypeAcc, mspec)) -> MakeInnerEnvWithAcc envAbove mspec.Id mtypeAcc mspec.ModuleOrNamespaceType.ModuleOrNamespaceKind) + (fun envAbove (MutRecDefnsPhase2DataForModule (mtypeAcc, mspec)) -> MakeInnerEnvWithAcc envAbove mspec.Id mtypeAcc mspec.ModuleOrNamespaceType.ModuleOrNamespaceKind) (fun envAbove decls -> // Collect the type definitions, exception definitions, modules and "open" declarations - let tycons = decls |> List.choose (function MutRecShape.Tycon d -> getTyconOpt d | _ -> None) + let tycons = decls |> List.choose (function MutRecShape.Tycon d -> getTyconOpt d | _ -> None) let mspecs = decls |> List.choose (function MutRecShape.Module (MutRecDefnsPhase2DataForModule (_, mspec), _) -> Some mspec | _ -> None) 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) @@ -13993,18 +13993,18 @@ module MutRecBindingChecking = 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 - // where not everything has been added. The things added last will be preferred in name + // The order here is sensitive. The things added first will be resolved in an environment + // where not everything has been added. The things added last will be preferred in name // resolution. // // 'open' declarations ('open M') may refer to modules being defined ('M') and so must be - // processed in an environment where 'M' is present. However, in later processing the names of + // processed in an environment where 'M' is present. However, in later processing the names of // modules being defined ('M') take precedence over those coming from 'open' declarations. // So add the names of the modules being defined to the environment twice - once to allow // the processing of 'open M', and once to allow the correct name resolution of 'M'. // // Module abbreviations being defined ('module M = A.B.C') are not available for use in 'open' - // declarations. So + // declarations. So // namespace rec N = // open M // module M = FSharp.Core.Operators @@ -14034,7 +14034,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 (defnsAs, uncheckedRecBinds, tpenv) = TcMutRecBindings_Phase2A_CreateRecursiveValuesAndCheckArgumentPatterns cenv tpenv (envMutRecPrelimWithReprs, mutRecDefns) + let (defnsAs, uncheckedRecBinds, tpenv) = TcMutRecBindings_Phase2A_CreateRecursiveValuesAndCheckArgumentPatterns cenv tpenv (envMutRecPrelimWithReprs, mutRecDefns) // Now basic member values are created we can compute the final attributes (i.e. in the case where attributes refer to constructors being defined) mutRecDefns |> MutRecShapes.iterTycons (fun (MutRecDefnsPhase2InfoForTycon(_, _, _, _, _, fixupFinalAttrs)) -> @@ -14049,7 +14049,7 @@ module MutRecBindingChecking = (envInitial, MutRecShapes.dropEnvs defnsAs) ||> TcMutRecDefns_ComputeEnvs (fun (TyconBindingsPhase2A(tyconOpt, _, _, _, _, _, _)) -> tyconOpt) - (fun binds -> [ for bind in binds -> bind.RecBindingInfo.Val ]) + (fun binds -> [ for bind in binds -> bind.RecBindingInfo.Val ]) cenv false scopem scopem ||> MutRecShapes.extendEnvs (fun envForDecls decls -> @@ -14064,7 +14064,7 @@ module MutRecBindingChecking = [ for defnB in defnAs do match defnB with | Phase2AIncrClassCtor (incrClassCtorLhs) -> yield incrClassCtorLhs.InstanceCtorVal - | _ -> () ]) + | _ -> () ]) let envForDeclsUpdated = envForDecls @@ -14090,14 +14090,14 @@ module MutRecBindingChecking = for defnA in defnAs do match defnA with | Phase2AMember rbind -> yield! rbind.RecBindingInfo.EnclosingDeclaredTypars - | _ -> () ]) + | _ -> () ]) // Now check they don't escape the overall scope of the recursive set of types if not (isNil allExtraGeneralizableTypars) then let freeInInitialEnv = GeneralizationHelpers.ComputeUngeneralizableTypars envInitial for extraTypar in allExtraGeneralizableTypars do if Zset.memberOf freeInInitialEnv extraTypar then - let ty = mkTyparTy extraTypar + let ty = mkTyparTy extraTypar error(Error(FSComp.SR.tcNotSufficientlyGenericBecauseOfScope(NicePrint.prettyStringOfTy denv ty), extraTypar.Range)) // Solve any type variables in any part of the overall type signature of the class whose @@ -14164,7 +14164,7 @@ module MutRecBindingChecking = let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: TcEnv) (mutRecDefns: MutRecDefnsPhase2Data) = let interfacesFromTypeDefn envForTycon tyconMembersData = let (MutRecDefnsPhase2DataForTycon(_, _, declKind, tcref, _, _, declaredTyconTypars, members, _, _, _)) = tyconMembersData - let overridesOK = DeclKind.CanOverrideOrImplement(declKind) + let overridesOK = DeclKind.CanOverrideOrImplement(declKind) members |> List.collect (function | SynMemberDefn.Interface(ity, defnOpt, _) -> let _, ty = if tcref.Deref.IsExceptionDecl then [], cenv.g.exn_ty else generalizeTyconRef tcref @@ -14174,7 +14174,7 @@ let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: let ity' = let envinner = AddDeclaredTypars CheckForDuplicateTypars declaredTyconTypars envForTycon - TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInType envinner emptyUnscopedTyparEnv ity |> fst + TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInType envinner emptyUnscopedTyparEnv ity |> fst if not (isInterfaceTy cenv.g ity') then errorR(Error(FSComp.SR.tcTypeIsNotInterfaceType0(), ity.Range)) if not (tcref.HasInterface cenv.g ity') then @@ -14195,10 +14195,10 @@ let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: | _ -> []) - let interfaceMembersFromTypeDefn tyconMembersData (ity', defn, _) implTySet = + let interfaceMembersFromTypeDefn tyconMembersData (ity', defn, _) implTySet = let (MutRecDefnsPhase2DataForTycon(_, parent, declKind, tcref, baseValOpt, safeInitInfo, declaredTyconTypars, _, _, newslotsOK, _)) = tyconMembersData let containerInfo = ContainerInfo(parent, Some(MemberOrValContainerInfo(tcref, Some(ity', implTySet), baseValOpt, safeInitInfo, declaredTyconTypars))) - defn |> List.choose (fun mem -> + defn |> List.choose (fun mem -> match mem with | SynMemberDefn.Member(_, m) -> Some(TyconBindingDefn(containerInfo, newslotsOK, declKind, mem, m)) | SynMemberDefn.AutoProperty(_, _, _, _, _, _, _, _, _, _, m) -> Some(TyconBindingDefn(containerInfo, newslotsOK, declKind, mem, m)) @@ -14218,13 +14218,13 @@ let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: -> Some(TyconBindingDefn(containerInfo, newslotsOK, declKind, memb, memb.Range)) // Interfaces exist in the member list - handled above in interfaceMembersFromTypeDefn - | SynMemberDefn.Interface _ -> None + | SynMemberDefn.Interface _ -> None // The following should have been List.unzip out already in SplitTyconDefn | SynMemberDefn.AbstractSlot _ | SynMemberDefn.ValField _ - | SynMemberDefn.Inherit _ -> error(InternalError("Unexpected declaration element", memb.Range)) - | SynMemberDefn.NestedType _ -> error(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), memb.Range))) + | SynMemberDefn.Inherit _ -> error(InternalError("Unexpected declaration element", memb.Range)) + | SynMemberDefn.NestedType _ -> error(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), memb.Range))) let tpenv = emptyUnscopedTyparEnv @@ -14252,7 +14252,7 @@ let TcMutRecDefns_Phase2 cenv envInitial bindsm scopem mutRecNSInfo (envMutRec: (envMutRec, mutRecDefns) ||> MutRecShapes.mapTyconsWithEnv (fun envForDecls tyconData -> let (MutRecDefnsPhase2DataForTycon(tyconOpt, _, declKind, tcref, _, _, declaredTyconTypars, _, _, _, fixupFinalAttrs)) = tyconData let obinds = tyconBindingsOfTypeDefn tyconData - let ibinds = + let ibinds = let intfTypes = interfacesFromTypeDefn envForDecls tyconData let slotImplSets = DispatchSlotChecking.GetSlotImplSets cenv.infoReader envForDecls.DisplayEnv false (List.map (fun (ity, _, m) -> (ity, m)) intfTypes) (intfTypes, slotImplSets) ||> List.map2 (interfaceMembersFromTypeDefn tyconData) |> List.concat @@ -14380,7 +14380,7 @@ module AddAugmentationDeclarations = let vspec1, vspec2 = AugmentWithHashCompare.MakeValsForEqualsAugmentation cenv.g tcref tcaug.SetEquals (mkLocalValRef vspec1, mkLocalValRef vspec2) if not tycon.IsExceptionDecl then - PublishInterface cenv env.DisplayEnv tcref m true (mkAppTy cenv.g.system_GenericIEquatable_tcref [ty]) + PublishInterface cenv env.DisplayEnv tcref m true (mkAppTy cenv.g.system_GenericIEquatable_tcref [ty]) PublishValueDefn cenv env ModuleOrMemberBinding vspec1 PublishValueDefn cenv env ModuleOrMemberBinding vspec2 AugmentWithHashCompare.MakeBindingsForEqualsAugmentation cenv.g tycon @@ -14435,7 +14435,7 @@ module TyconConstraintInference = match ty with // Look for array, UIntPtr and IntPtr types | SpecialComparableHeadType g tinst -> - tinst |> List.forall (checkIfFieldTypeSupportsComparison tycon) + tinst |> List.forall (checkIfFieldTypeSupportsComparison tycon) // Otherwise it's a nominal type | _ -> @@ -14446,7 +14446,7 @@ module TyconConstraintInference = (if initialAssumedTycons.Contains tcref.Stamp then assumedTycons.Contains tcref.Stamp else - ExistsSameHeadTypeInHierarchy g cenv.amap range0 ty g.mk_IComparable_ty || + ExistsSameHeadTypeInHierarchy g cenv.amap range0 ty g.mk_IComparable_ty || ExistsSameHeadTypeInHierarchy g cenv.amap range0 ty g.mk_IStructuralComparable_ty) && // Check it isn't ruled out by the user @@ -14455,7 +14455,7 @@ module TyconConstraintInference = // Check the structural dependencies (tinst, tcref.TyparsNoRange) ||> List.lengthsEqAndForall2 (fun ty tp -> if tp.ComparisonConditionalOn || assumedTypars.Contains tp.Stamp then - checkIfFieldTypeSupportsComparison tycon ty + checkIfFieldTypeSupportsComparison tycon ty else true) | _ -> @@ -14524,7 +14524,7 @@ module TyconConstraintInference = uneliminatedTycons /// Infer 'equality' constraints from type definitions - let InferSetOfTyconsSupportingEquatable cenv (denv: DisplayEnv) (tyconsWithStructuralTypes:(Tycon * _) list) = + let InferSetOfTyconsSupportingEquatable cenv (denv: DisplayEnv) (tyconsWithStructuralTypes:(Tycon * _) list) = let g = cenv.g let tab = tyconsWithStructuralTypes |> List.map (fun (tycon, c) -> tycon.Stamp, (tycon, c)) |> Map.ofList @@ -14582,7 +14582,7 @@ module TyconConstraintInference = // Check the structural dependencies (tinst, tcref.TyparsNoRange) ||> List.lengthsEqAndForall2 (fun ty tp -> if tp.EqualityConditionalOn || assumedTypars.Contains tp.Stamp then - checkIfFieldTypeSupportsEquality tycon ty + checkIfFieldTypeSupportsEquality tycon ty else true) | _ -> @@ -14661,13 +14661,13 @@ let ComputeModuleName (longPath: Ident list) = if longPath.Length <> 1 then error(Error(FSComp.SR.tcInvalidModuleName(), (List.head longPath).idRange)) longPath.Head -let CheckForDuplicateConcreteType env nm m = +let CheckForDuplicateConcreteType env nm m = let curr = GetCurrAccumulatedModuleOrNamespaceType env if Map.containsKey nm curr.AllEntitiesByCompiledAndLogicalMangledNames then // Use 'error' instead of 'errorR' here to avoid cascading errors - see bug 1177 in FSharp 1.0 error (Duplicate(FSComp.SR.tcTypeExceptionOrModule(), nm, m)) -let CheckForDuplicateModule env nm m = +let CheckForDuplicateModule env nm m = let curr = GetCurrAccumulatedModuleOrNamespaceType env if curr.ModulesAndNamespacesByDemangledName.ContainsKey(nm) then errorR (Duplicate(FSComp.SR.tcTypeOrModule(), nm, m)) @@ -14705,7 +14705,7 @@ module TcExceptionDeclarations = if not (isNil args') then errorR (Error(FSComp.SR.tcExceptionAbbreviationsShouldNotHaveArgumentList(), m)) TExnAbbrevRepr exnc - | Item.CtorGroup(_, meths) , [] -> + | Item.CtorGroup(_, meths), [] -> // REVIEW: check this really is an exception type match args' with | [] -> () @@ -14759,7 +14759,7 @@ module TcExceptionDeclarations = let TcExnDefn cenv envInitial parent (SynExceptionDefn(core, aug, m), scopem) = let binds1, exnc = TcExnDefnCore cenv envInitial parent core - let envMutRec = AddLocalExnDefnAndReport cenv.tcSink scopem (AddLocalTycons cenv.g cenv.amap scopem [exnc] envInitial) exnc + let envMutRec = AddLocalExnDefnAndReport cenv.tcSink scopem (AddLocalTycons cenv.g cenv.amap scopem [exnc] envInitial) exnc let defns = [MutRecShape.Tycon(MutRecDefnsPhase2DataForTycon(Some exnc, parent, ModuleOrMemberBinding, mkLocalEntityRef exnc, None, NoSafeInitInfo, [], aug, m, NoNewSlots, (fun () -> ())))] let binds2, envFinal = TcMutRecDefns_Phase2 cenv envInitial m scopem None envMutRec defns @@ -14770,7 +14770,7 @@ module TcExceptionDeclarations = let TcExnSignature cenv envInitial parent tpenv (SynExceptionSig(core, aug, _), scopem) = let binds, exnc = TcExnDefnCore cenv envInitial parent core - let envMutRec = AddLocalExnDefnAndReport cenv.tcSink scopem (AddLocalTycons cenv.g cenv.amap scopem [exnc] envInitial) exnc + let envMutRec = AddLocalExnDefnAndReport cenv.tcSink scopem (AddLocalTycons cenv.g cenv.amap scopem [exnc] envInitial) exnc let ecref = mkLocalEntityRef exnc let vals, _ = TcTyconMemberSpecs cenv envMutRec (ContainerInfo(parent, Some(MemberOrValContainerInfo(ecref, None, None, NoSafeInitInfo, [])))) ModuleOrMemberBinding tpenv aug binds, vals, ecref, envMutRec @@ -14803,11 +14803,11 @@ module EstablishTypeDefinitionCores = mkSynId id.idRange (if erasedArity = 0 then id.idText else id.idText + "`" + string erasedArity) let private GetTyconAttribs g attrs = - let hasClassAttr = HasFSharpAttribute g g.attrib_ClassAttribute attrs + let hasClassAttr = HasFSharpAttribute g g.attrib_ClassAttribute attrs let hasAbstractClassAttr = HasFSharpAttribute g g.attrib_AbstractClassAttribute attrs - let hasInterfaceAttr = HasFSharpAttribute g g.attrib_InterfaceAttribute attrs - let hasStructAttr = HasFSharpAttribute g g.attrib_StructAttribute attrs - let hasMeasureAttr = HasFSharpAttribute g g.attrib_MeasureAttribute attrs + let hasInterfaceAttr = HasFSharpAttribute g g.attrib_InterfaceAttribute attrs + let hasStructAttr = HasFSharpAttribute g g.attrib_StructAttribute attrs + let hasMeasureAttr = HasFSharpAttribute g g.attrib_MeasureAttribute attrs (hasClassAttr, hasAbstractClassAttr, hasInterfaceAttr, hasStructAttr, hasMeasureAttr) //------------------------------------------------------------------------- @@ -14831,7 +14831,7 @@ module EstablishTypeDefinitionCores = else TyconInterface | k -> if hasClassAttr && not (match k with TyconClass -> true | _ -> false) || - hasMeasureAttr && not (match k with TyconClass | TyconAbbrev | TyconHiddenRepr -> true | _ -> false) || + hasMeasureAttr && not (match k with TyconClass | TyconAbbrev | TyconHiddenRepr -> true | _ -> false) || hasInterfaceAttr && not (match k with TyconInterface -> true | _ -> false) || hasStructAttr && not (match k with TyconStruct | TyconRecord | TyconUnion -> true | _ -> false) then error(Error(FSComp.SR.tcKindOfTypeSpecifiedDoesNotMatchDefinition(), m)) @@ -14874,11 +14874,11 @@ module EstablishTypeDefinitionCores = errorR(Error(FSComp.SR.tcIllegalFormForExplicitTypeDeclaration(), m)) for argTys in curriedArgTys do for (argty, _) in argTys do - yield (argty , m) + yield (argty, m) | SynTypeDefnSimpleRepr.General (_, _, _, fields, _, _, implicitCtorSynPats, _) when tycon.IsFSharpStructOrEnumTycon -> // for structs for (Field(_, isStatic, _, ty, _, _, _, m)) in fields do - if not isStatic then + if not isStatic then let ty', _ = TcTypeAndRecover cenv NoNewTypars NoCheckCxs ItemOccurence.UseInType env tpenv ty yield (ty', m) @@ -14913,7 +14913,7 @@ module EstablishTypeDefinitionCores = [ for d in compDecls do match d with | MutRecShape.Tycon (MutRecDefnsPhase1DataForTycon(ComponentInfo(_, typars, _, ids, _, _, _, _), _, _, _, _, isAtOriginalTyconDefn), _) -> - if isAtOriginalTyconDefn && (TcTyparDecls cenv env typars |> List.forall (fun p -> p.Kind = TyparKind.Measure)) then + if isAtOriginalTyconDefn && (TcTyparDecls cenv env typars |> List.forall (fun p -> p.Kind = TyparKind.Measure)) then yield (List.last ids).idText | _ -> () ] |> set @@ -14963,7 +14963,7 @@ module EstablishTypeDefinitionCores = let innerTypeNames = TypeNamesInMutRecDecls cenv envForDecls decls MutRecDefnsPhase2DataForModule (mtypeAcc, mspec), (innerParent, innerTypeNames, envForDecls) - /// Establish 'type C < T1... TN > = ...' including + /// Establish 'type C < T1... TN > = ...' including /// - computing the mangled name for C /// but /// - we don't yet 'properly' establish constraints on type parameters @@ -15044,10 +15044,10 @@ module EstablishTypeDefinitionCores = let repr = match synTyconRepr with - | SynTypeDefnSimpleRepr.Exception _ -> TNoRepr + | SynTypeDefnSimpleRepr.Exception _ -> TNoRepr | SynTypeDefnSimpleRepr.None m -> // Run InferTyconKind to raise errors on inconsistent attribute sets - InferTyconKind cenv.g (TyconHiddenRepr, attrs, [], [], inSig, true, m) |> ignore + InferTyconKind cenv.g (TyconHiddenRepr, attrs, [], [], inSig, true, m) |> ignore if not inSig && not hasMeasureAttr then errorR(Error(FSComp.SR.tcTypeRequiresDefinition(), m)) if hasMeasureAttr then @@ -15064,7 +15064,7 @@ module EstablishTypeDefinitionCores = // Note: the table of union cases is initially empty MakeUnionRepr [] - | SynTypeDefnSimpleRepr.TypeAbbrev _ -> + | SynTypeDefnSimpleRepr.TypeAbbrev _ -> // Run InferTyconKind to raise errors on inconsistent attribute sets InferTyconKind cenv.g (TyconAbbrev, attrs, [], [], inSig, true, m) |> ignore TNoRepr @@ -15078,7 +15078,7 @@ module EstablishTypeDefinitionCores = // Run InferTyconKind to raise errors on inconsistent attribute sets InferTyconKind cenv.g (TyconRecord, attrs, [], [], inSig, true, m) |> ignore // Note: the table of record fields is initially empty - TRecdRepr (MakeRecdFieldsTable []) + TRecdRepr (MakeRecdFieldsTable []) | SynTypeDefnSimpleRepr.General (kind, _, slotsigs, fields, isConcrete, _, _, _) -> let kind = InferTyconKind cenv.g (kind, attrs, slotsigs, fields, inSig, isConcrete, m) @@ -15088,10 +15088,10 @@ module EstablishTypeDefinitionCores = | _ -> let kind = match kind with - | TyconClass -> TTyconClass - | TyconInterface -> TTyconInterface - | TyconDelegate _ -> TTyconDelegate (MakeSlotSig("Invoke", cenv.g.unit_ty, [], [], [], None)) - | TyconStruct -> TTyconStruct + | TyconClass -> TTyconClass + | TyconInterface -> TTyconInterface + | TyconDelegate _ -> TTyconDelegate (MakeSlotSig("Invoke", cenv.g.unit_ty, [], [], [], None)) + | TyconStruct -> TTyconStruct | _ -> error(InternalError("should have inferred tycon kind", m)) let repr = { fsobjmodel_kind=kind @@ -15141,7 +15141,7 @@ module EstablishTypeDefinitionCores = let optGeneratedTypePath = Some (tcref.CompilationPath.MangledPath @ [ tcref.LogicalName ]) let _hasNoArgs, providedTypeAfterStaticArguments, checkTypeName = TcProvidedTypeAppToStaticConstantArgs cenv envinner optGeneratedTypePath tpenv tcrefBeforeStaticArguments args m let isGenerated = providedTypeAfterStaticArguments.PUntaint((fun st -> not st.IsErased), m) - if isGenerated then + if isGenerated then Some (tcrefBeforeStaticArguments, providedTypeAfterStaticArguments, checkTypeName, args, m) else None // The provided type (after ApplyStaticArguments) must also be marked 'IsErased=false' @@ -15289,8 +15289,8 @@ module EstablishTypeDefinitionCores = /// Establish any type abbreviations /// /// e.g. for - /// type B<'a when 'a: C> = DDD of C - /// and C = B + /// type B<'a when 'a: C> = DDD of C + /// and C = B /// /// we establish /// @@ -15376,7 +15376,7 @@ module EstablishTypeDefinitionCores = // Publish the immediately declared interfaces. let tyconWithImplementsL = - (envMutRec, mutRecDefns) ||> MutRecShapes.mapTyconsWithEnv (fun envinner (origInfo, tyconAndAttrsOpt) -> + (envMutRec, mutRecDefns) ||> MutRecShapes.mapTyconsWithEnv (fun envinner (origInfo, tyconAndAttrsOpt) -> match origInfo, tyconAndAttrsOpt with | (typeDefCore, _, _), Some (tycon, (attrs, _)) -> let (MutRecDefnsPhase1DataForTycon(_, synTyconRepr, explicitImplements, _, _, _)) = typeDefCore @@ -15453,7 +15453,7 @@ module EstablishTypeDefinitionCores = errorR (Error(FSComp.SR.tcStructsInterfacesEnumsDelegatesMayNotInheritFromOtherTypes(), m)) CheckSuperType cenv ty m if isTyparTy cenv.g ty then - if firstPass then + if firstPass then errorR(Error(FSComp.SR.tcCannotInheritFromVariableType(), m)) Some cenv.g.obj_ty // a "super" that is a variable type causes grief later else @@ -15627,14 +15627,14 @@ module EstablishTypeDefinitionCores = errorR (Error(FSComp.SR.tcAbbreviatedTypesCannotBeSealed(), m)) noAbstractClassAttributeCheck() noAllowNullLiteralAttributeCheck() - if hasMeasureableAttr then + if hasMeasureableAttr then let kind = if hasMeasureAttr then TyparKind.Measure else TyparKind.Type let theTypeAbbrev, _ = TcTypeOrMeasureAndRecover (Some kind) cenv NoNewTypars CheckCxs ItemOccurence.UseInType envinner tpenv rhsType TMeasureableRepr theTypeAbbrev, None, NoSafeInitInfo // If we already computed a representation, e.g. for a generative type definition, then don't change it here. - elif (match tycon.TypeReprInfo with TNoRepr -> false | _ -> true) then - tycon.TypeReprInfo , None, NoSafeInitInfo + elif (match tycon.TypeReprInfo with TNoRepr -> false | _ -> true) then + tycon.TypeReprInfo, None, NoSafeInitInfo else TNoRepr, None, NoSafeInitInfo @@ -15662,7 +15662,7 @@ module EstablishTypeDefinitionCores = noAllowNullLiteralAttributeCheck() structLayoutAttributeCheck(true) // these are allowed for records let recdFields = TcRecdUnionAndEnumDeclarations.TcNamedFieldDecls cenv envinner innerParent false tpenv fields - recdFields |> CheckDuplicates (fun f -> f.Id) "field" |> ignore + recdFields |> CheckDuplicates (fun f -> f.Id) "field" |> ignore writeFakeRecordFieldsToSink recdFields TRecdRepr (MakeRecdFieldsTable recdFields), None, NoSafeInitInfo @@ -15691,14 +15691,14 @@ module EstablishTypeDefinitionCores = let taccess = TAccess [envinner.eAccessPath] yield NewRecdField false None id false ty false false [(*no property attributes*)] [(*no field attributes *)] XmlDoc.Empty taccess (*compiler generated:*)true ] - (userFields @ implicitStructFields) |> CheckDuplicates (fun f -> f.Id) "field" |> ignore + (userFields @ implicitStructFields) |> CheckDuplicates (fun f -> f.Id) "field" |> ignore writeFakeRecordFieldsToSink userFields let superTy = tycon.TypeContents.tcaug_super let containerInfo = TyconContainerInfo(innerParent, thisTyconRef, thisTyconRef.Typars(m), NoSafeInitInfo) let kind = InferTyconKind cenv.g (kind, attrs, slotsigs, fields, inSig, isConcrete, m) match kind with - | TyconHiddenRepr -> + | TyconHiddenRepr -> hiddenReprChecks(true) noAllowNullLiteralAttributeCheck() TNoRepr, None, NoSafeInitInfo @@ -15746,7 +15746,7 @@ module EstablishTypeDefinitionCores = noAbstractClassAttributeCheck() noFieldsCheck(userFields) let ty', _ = TcTypeAndRecover cenv NoNewTypars CheckCxs ItemOccurence.UseInType envinner tpenv ty - let _, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm cenv.g (arity |> TranslateTopValSynInfo m (TcAttributes cenv envinner) |> TranslatePartialArity []) ty' m + let _, curriedArgInfos, returnTy, _ = GetTopValTypeInCompiledForm cenv.g (arity |> TranslateTopValSynInfo m (TcAttributes cenv envinner) |> TranslatePartialArity []) ty' m if curriedArgInfos.Length < 1 then error(Error(FSComp.SR.tcInvalidDelegateSpecification(), m)) if curriedArgInfos.Length > 1 then error(Error(FSComp.SR.tcDelegatesCannotBeCurried(), m)) let ttps = thisTyconRef.Typars(m) @@ -15794,7 +15794,7 @@ module EstablishTypeDefinitionCores = TFSharpObjectRepr { fsobjmodel_kind=kind fsobjmodel_vslots= abstractSlots - fsobjmodel_rfields=MakeRecdFieldsTable (userFields @ implicitStructFields @ safeInitFields) } + fsobjmodel_rfields=MakeRecdFieldsTable (userFields @ implicitStructFields @ safeInitFields) } repr, baseValOpt, safeInitInfo | SynTypeDefnSimpleRepr.Enum (decls, m) -> @@ -15840,7 +15840,7 @@ module EstablishTypeDefinitionCores = let edgesFrom (tycon: Tycon) = - let rec accInAbbrevType ty acc = + let rec accInAbbrevType ty acc = match stripTyparEqns ty with | TType_anon (_,l) | TType_tuple (_, l) -> accInAbbrevTypes l acc @@ -15849,7 +15849,7 @@ module EstablishTypeDefinitionCores = let tycon2 = tc.Deref let acc = accInAbbrevTypes tinst acc // Record immediate recursive references - if ListSet.contains (===) tycon2 tycons then + if ListSet.contains (===) tycon2 tycons then (tycon, tycon2) :: acc // Expand the representation of abbreviations elif tc.IsTypeAbbrev then @@ -15869,9 +15869,9 @@ module EstablishTypeDefinitionCores = and accInMeasure ms acc = match stripUnitEqns ms with - | Measure.Con tc when ListSet.contains (===) tc.Deref tycons -> + | Measure.Con tc when ListSet.contains (===) tc.Deref tycons -> (tycon, tc.Deref) :: acc - | Measure.Con tc when tc.IsTypeAbbrev -> + | Measure.Con tc when tc.IsTypeAbbrev -> accInMeasure (reduceTyconRefAbbrevMeasureable tc) acc | Measure.Prod (ms1, ms2) -> accInMeasure ms1 (accInMeasure ms2 acc) | Measure.Inv ms -> accInMeasure ms acc @@ -15947,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) @@ -15955,7 +15955,7 @@ module EstablishTypeDefinitionCores = and accStructFieldType structTycon structTyInst fspec fieldTy (doneTypes, acc) = let fieldTy = stripTyparEqns fieldTy match fieldTy with - | TType_app (tcref2 , tinst2) when tcref2.IsStructOrEnumTycon -> + | TType_app (tcref2, tinst2) when tcref2.IsStructOrEnumTycon -> // The field is a struct. // An edge (tycon, tycon2) should be recorded, unless it is the "static self-typed field" case. let tycon2 = tcref2.Deref @@ -15975,7 +15975,7 @@ module EstablishTypeDefinitionCores = else let acc = insertEdgeToTycon tycon2 acc // collect edge (tycon, tycon2), if tycon2 is initial. accStructInstanceFields fieldTy tycon2 tinst2 (doneTypes, acc) // recurse through struct field looking for more edges - | TType_app (tcref2 , tinst2) when tcref2.IsTypeAbbrev -> + | TType_app (tcref2, tinst2) when tcref2.IsTypeAbbrev -> // The field is a type abbreviation. Expand and repeat. accStructFieldType structTycon structTyInst fspec (reduceTyconRefAbbrev tcref2 tinst2) (doneTypes, acc) | _ -> @@ -15992,7 +15992,7 @@ module EstablishTypeDefinitionCores = let fspecs = if structTycon.IsUnionTycon then [ for uc in structTycon.UnionCasesArray do - for c in uc.FieldTable.FieldsByIndex do + for c in uc.FieldTable.FieldsByIndex do yield c] else structTycon.AllFieldsAsList @@ -16000,7 +16000,7 @@ module EstablishTypeDefinitionCores = let doneTypes, acc = List.foldBack (accStructField structTycon tinst) fspecs (doneTypes, acc) doneTypes, acc and accStructInstanceFields ty structTycon tinst (doneTypes, acc) = accStructFields false ty structTycon tinst (doneTypes, acc) - and accStructAllFields ty (structTycon: Tycon) tinst (doneTypes, acc) = accStructFields true ty structTycon tinst (doneTypes, acc) + and accStructAllFields ty (structTycon: Tycon) tinst (doneTypes, acc) = accStructFields true ty structTycon tinst (doneTypes, acc) let acc = [] let acc = @@ -16039,7 +16039,7 @@ module EstablishTypeDefinitionCores = let envForTycon = AddDeclaredTypars CheckForDuplicateTypars (tycon.Typars(m)) envForDecls let thisTyconRef = mkLocalTyconRef tycon let envForTycon = MakeInnerEnvForTyconRef envForTycon thisTyconRef false - try TcTyparConstraints cenv NoNewTypars checkCxs ItemOccurence.UseInType envForTycon tpenv synTyconConstraints |> ignore + try TcTyparConstraints cenv NoNewTypars checkCxs ItemOccurence.UseInType envForTycon tpenv synTyconConstraints |> ignore with e -> errorRecovery e m | _ -> ()) @@ -16047,7 +16047,7 @@ module EstablishTypeDefinitionCores = 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. + // Also for abbreviations of any of these. Augmentations are skipped in this phase. let withEntities = mutRecDefns |> MutRecShapes.mapWithParent @@ -16084,7 +16084,7 @@ module EstablishTypeDefinitionCores = // Publish tycons (envTmp, withEnvs) ||> MutRecShapes.iterTyconsWithEnv - (fun envAbove (_, tyconOpt) -> + (fun envAbove (_, tyconOpt) -> tyconOpt |> Option.iter (fun tycon -> // recheck these in case type is a duplicate in a mutually recursive set CheckForDuplicateConcreteType envAbove tycon.LogicalName tycon.Range @@ -16098,7 +16098,7 @@ module EstablishTypeDefinitionCores = // Add the types to the environment. This does not add the fields and union cases (because we haven't established them yet). // We re-add them to the original environment later on. We don't report them to the Language Service yet as we don't know if // they are well-formed (e.g. free of abbreviation cycles) - let envMutRecPrelim, withEnvs = (envInitial, withEntities) ||> MutRecBindingChecking.TcMutRecDefns_ComputeEnvs snd (fun _ -> []) cenv false scopem m + let envMutRecPrelim, withEnvs = (envInitial, withEntities) ||> MutRecBindingChecking.TcMutRecDefns_ComputeEnvs snd (fun _ -> []) cenv false scopem m // Phase 1B. Establish the kind of each type constructor // Here we run InferTyconKind and record partial information about the kind of the type constructor. @@ -16112,7 +16112,7 @@ module EstablishTypeDefinitionCores = origInfo, res) // Phase 1C. Establish the abbreviations (no constraint checking, because constraints not yet established) - (envMutRecPrelim, withAttrs) ||> MutRecShapes.iterTyconsWithEnv (fun envForDecls (origInfo, tyconAndAttrsOpt) -> + (envMutRecPrelim, withAttrs) ||> MutRecShapes.iterTyconsWithEnv (fun envForDecls (origInfo, tyconAndAttrsOpt) -> match origInfo, tyconAndAttrsOpt with | (typeDefCore, _, _), Some (tycon, (attrs, _)) -> TcTyconDefnCore_Phase1C_Phase1E_EstablishAbbreviations cenv envForDecls inSig tpenv FirstPass typeDefCore tycon attrs | _ -> ()) @@ -16122,7 +16122,7 @@ module EstablishTypeDefinitionCores = TcTyconDefnCore_CheckForCyclicAbbreviations tycons - // Phase 1D. Establish the super type and interfaces (no constraint checking, because constraints not yet established) + // Phase 1D. Establish the super type and interfaces (no constraint checking, because constraints not yet established) (envMutRecPrelim, withAttrs) |> TcTyconDefnCore_Phase1D_Phase1F_EstablishSuperTypesAndInterfaceTypes cenv tpenv inSig FirstPass // Interlude between Phase1D and Phase1E - Add the interface and member declarations for @@ -16153,7 +16153,7 @@ module EstablishTypeDefinitionCores = tyconOpt |> Option.iter (fun tycon -> tycon.Typars(m) |> List.iter (SetTyparRigid cenv.g envForDecls.DisplayEnv m))) // Phase1E. OK, now recheck the abbreviations, super/interface and explicit constraints types (this time checking constraints) - (envMutRecPrelim, withAttrs) ||> MutRecShapes.iterTyconsWithEnv (fun envForDecls (origInfo, tyconAndAttrsOpt) -> + (envMutRecPrelim, withAttrs) ||> MutRecShapes.iterTyconsWithEnv (fun envForDecls (origInfo, tyconAndAttrsOpt) -> match origInfo, tyconAndAttrsOpt with | (typeDefCore, _, _), Some (tycon, (attrs, _)) -> TcTyconDefnCore_Phase1C_Phase1E_EstablishAbbreviations cenv envForDecls inSig tpenv SecondPass typeDefCore tycon attrs | _ -> ()) @@ -16167,8 +16167,8 @@ module EstablishTypeDefinitionCores = let envMutRecPrelim, withAttrs = (envMutRecPrelim, withAttrs) ||> MutRecShapes.extendEnvs (fun envForDecls decls -> - let tycons = decls |> List.choose (function MutRecShape.Tycon (_, Some (tycon, _)) -> Some tycon | _ -> None) - let exns = tycons |> List.filter (fun tycon -> tycon.IsExceptionDecl) + let tycons = decls |> List.choose (function MutRecShape.Tycon (_, Some (tycon, _)) -> Some tycon | _ -> None) + let exns = tycons |> List.filter (fun tycon -> tycon.IsExceptionDecl) let envForDecls = (envForDecls, exns) ||> List.fold (AddLocalExnDefnAndReport cenv.tcSink scopem) envForDecls) @@ -16278,15 +16278,15 @@ module TcDeclarations = let private isAugmentationTyconDefnRepr = function (SynTypeDefnSimpleRepr.General(TyconAugmentation, _, _, _, _, _, _, _)) -> true | _ -> false - let private isAutoProperty = function SynMemberDefn.AutoProperty _ -> true | _ -> false - let private isMember = function SynMemberDefn.Member _ -> true | _ -> false - let private isImplicitCtor = function SynMemberDefn.ImplicitCtor _ -> true | _ -> false + let private isAutoProperty = function SynMemberDefn.AutoProperty _ -> true | _ -> false + let private isMember = function SynMemberDefn.Member _ -> true | _ -> false + let private isImplicitCtor = function SynMemberDefn.ImplicitCtor _ -> true | _ -> false let private isImplicitInherit = function SynMemberDefn.ImplicitInherit _ -> true | _ -> false - let private isAbstractSlot = function SynMemberDefn.AbstractSlot _ -> true | _ -> false - let private isInterface = function SynMemberDefn.Interface _ -> true | _ -> false - let private isInherit = function SynMemberDefn.Inherit _ -> true | _ -> false - let private isField = function SynMemberDefn.ValField (_, _) -> true | _ -> false - let private isTycon = function SynMemberDefn.NestedType _ -> true | _ -> false + let private isAbstractSlot = function SynMemberDefn.AbstractSlot _ -> true | _ -> false + let private isInterface = function SynMemberDefn.Interface _ -> true | _ -> false + let private isInherit = function SynMemberDefn.Inherit _ -> true | _ -> false + let private isField = function SynMemberDefn.ValField (_, _) -> true | _ -> false + let private isTycon = function SynMemberDefn.NestedType _ -> true | _ -> false let private allFalse ps x = List.forall (fun p -> not (p x)) ps @@ -16319,30 +16319,30 @@ module TcDeclarations = let _, ds = ds |> List.takeUntil (allFalse [isMember;isAbstractSlot;isInterface;isAutoProperty]) match ds with - | SynMemberDefn.Member (_, m) :: _ -> errorR(InternalError("List.takeUntil is wrong, have binding", m)) - | SynMemberDefn.AbstractSlot (_, _, m) :: _ -> errorR(InternalError("List.takeUntil is wrong, have slotsig", m)) - | SynMemberDefn.Interface (_, _, m) :: _ -> errorR(InternalError("List.takeUntil is wrong, have interface", m)) - | SynMemberDefn.ImplicitCtor (_, _, _, _, m) :: _ -> errorR(InternalError("implicit class construction with two implicit constructions", m)) + | SynMemberDefn.Member (_, m) :: _ -> errorR(InternalError("List.takeUntil is wrong, have binding", m)) + | SynMemberDefn.AbstractSlot (_, _, m) :: _ -> errorR(InternalError("List.takeUntil is wrong, have slotsig", m)) + | SynMemberDefn.Interface (_, _, m) :: _ -> errorR(InternalError("List.takeUntil is wrong, have interface", m)) + | SynMemberDefn.ImplicitCtor (_, _, _, _, m) :: _ -> errorR(InternalError("implicit class construction with two implicit constructions", m)) | SynMemberDefn.AutoProperty (_, _, _, _, _, _, _, _, _, _, m) :: _ -> errorR(InternalError("List.takeUntil is wrong, have auto property", m)) | SynMemberDefn.ImplicitInherit (_, _, _, m) :: _ -> errorR(Error(FSComp.SR.tcTypeDefinitionsWithImplicitConstructionMustHaveOneInherit(), m)) - | SynMemberDefn.LetBindings (_, _, _, m) :: _ -> errorR(Error(FSComp.SR.tcTypeDefinitionsWithImplicitConstructionMustHaveLocalBindingsBeforeMembers(), m)) - | SynMemberDefn.Inherit (_, _, m) :: _ -> errorR(Error(FSComp.SR.tcInheritDeclarationMissingArguments(), m)) - | SynMemberDefn.NestedType (_, _, m) :: _ -> errorR(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), m)) + | SynMemberDefn.LetBindings (_, _, _, m) :: _ -> errorR(Error(FSComp.SR.tcTypeDefinitionsWithImplicitConstructionMustHaveLocalBindingsBeforeMembers(), m)) + | SynMemberDefn.Inherit (_, _, m) :: _ -> errorR(Error(FSComp.SR.tcInheritDeclarationMissingArguments(), m)) + | SynMemberDefn.NestedType (_, _, m) :: _ -> errorR(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), m)) | _ -> () | ds -> // Classic class construction let _, ds = List.takeUntil (allFalse [isMember;isAbstractSlot;isInterface;isInherit;isField;isTycon]) ds match ds with - | SynMemberDefn.Member (_, m) :: _ -> errorR(InternalError("CheckMembersForm: List.takeUntil is wrong", m)) - | SynMemberDefn.ImplicitCtor (_, _, _, _, m) :: _ -> errorR(InternalError("CheckMembersForm: implicit ctor line should be first", m)) + | SynMemberDefn.Member (_, m) :: _ -> errorR(InternalError("CheckMembersForm: List.takeUntil is wrong", m)) + | SynMemberDefn.ImplicitCtor (_, _, _, _, m) :: _ -> errorR(InternalError("CheckMembersForm: implicit ctor line should be first", m)) | SynMemberDefn.ImplicitInherit (_, _, _, m) :: _ -> errorR(Error(FSComp.SR.tcInheritConstructionCallNotPartOfImplicitSequence(), m)) - | SynMemberDefn.AutoProperty(_, _, _, _, _, _, _, _, _, _, m) :: _ -> errorR(Error(FSComp.SR.tcAutoPropertyRequiresImplicitConstructionSequence(), m)) + | SynMemberDefn.AutoProperty(_, _, _, _, _, _, _, _, _, _, m) :: _ -> errorR(Error(FSComp.SR.tcAutoPropertyRequiresImplicitConstructionSequence(), m)) | SynMemberDefn.LetBindings (_, false, _, m) :: _ -> errorR(Error(FSComp.SR.tcLetAndDoRequiresImplicitConstructionSequence(), m)) - | SynMemberDefn.AbstractSlot (_, _, m) :: _ - | SynMemberDefn.Interface (_, _, m) :: _ - | SynMemberDefn.Inherit (_, _, m) :: _ - | SynMemberDefn.ValField (_, m) :: _ - | SynMemberDefn.NestedType (_, _, m) :: _ -> errorR(InternalError("CheckMembersForm: List.takeUntil is wrong", m)) + | SynMemberDefn.AbstractSlot (_, _, m) :: _ + | SynMemberDefn.Interface (_, _, m) :: _ + | SynMemberDefn.Inherit (_, _, m) :: _ + | SynMemberDefn.ValField (_, m) :: _ + | SynMemberDefn.NestedType (_, _, m) :: _ -> errorR(InternalError("CheckMembersForm: List.takeUntil is wrong", m)) | _ -> () @@ -16357,17 +16357,17 @@ module TcDeclarations = match trepr with | SynTypeDefnRepr.ObjectModel(kind, cspec, m) -> CheckMembersForm cspec - let fields = cspec |> List.choose (function SynMemberDefn.ValField (f, _) -> Some(f) | _ -> None) + let fields = cspec |> List.choose (function SynMemberDefn.ValField (f, _) -> Some(f) | _ -> None) let implements2 = cspec |> List.choose (function SynMemberDefn.Interface (ty, _, _) -> Some(ty, ty.Range) | _ -> None) - let inherits = cspec |> List.choose (function - | SynMemberDefn.Inherit (ty, idOpt, m) -> Some(ty, m, idOpt) + let inherits = cspec |> List.choose (function + | SynMemberDefn.Inherit (ty, idOpt, m) -> Some(ty, m, idOpt) | SynMemberDefn.ImplicitInherit (ty, _, idOpt, m) -> Some(ty, m, idOpt) | _ -> None) //let nestedTycons = cspec |> List.choose (function SynMemberDefn.NestedType (x, _, _) -> Some(x) | _ -> None) - let slotsigs = cspec |> List.choose (function SynMemberDefn.AbstractSlot (x, y, _) -> Some(x, y) | _ -> None) + let slotsigs = cspec |> List.choose (function SynMemberDefn.AbstractSlot (x, y, _) -> Some(x, y) | _ -> None) let members = - let membersIncludingAutoProps = + let membersIncludingAutoProps = cspec |> List.filter (fun memb -> match memb with | SynMemberDefn.Interface _ @@ -16377,7 +16377,7 @@ module TcDeclarations = | SynMemberDefn.AutoProperty _ | SynMemberDefn.Open _ | SynMemberDefn.ImplicitInherit _ -> true - | SynMemberDefn.NestedType (_, _, m) -> error(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), m)); false + | SynMemberDefn.NestedType (_, _, m) -> error(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), m)); false // covered above | SynMemberDefn.ValField _ | SynMemberDefn.Inherit _ @@ -16412,7 +16412,7 @@ module TcDeclarations = // Convert autoproperties to member bindings in the post-list let rec postAutoProps memb = match memb with - | SynMemberDefn.AutoProperty (attribs, isStatic, id, tyOpt, propKind, memberFlags, xmlDoc, access, _synExpr, mGetSetOpt, _mWholeAutoProp) -> + | SynMemberDefn.AutoProperty (attribs, isStatic, id, tyOpt, propKind, memberFlags, xmlDoc, access, _synExpr, mGetSetOpt, _mWholeAutoProp) -> let mMemberPortion = id.idRange // Only the keep the non-field-targeted attributes let attribs = attribs |> List.filter (fun a -> match a.Target with Some t when t.idText = "field" -> false | _ -> true) @@ -16485,7 +16485,7 @@ module TcDeclarations = let implicitCtorSynPats = members |> List.tryPick (function - | SynMemberDefn.ImplicitCtor (_, _, spats, _, _) -> Some spats + | SynMemberDefn.ImplicitCtor (_, _, spats, _, _) -> Some spats | _ -> None) // An ugly bit of code to pre-determine if a type has a nullary constructor, prior to establishing the @@ -16518,7 +16518,7 @@ module TcDeclarations = /// Bind a collection of mutually recursive definitions in an implementation file let TcMutRecDefinitions cenv envInitial parent typeNames tpenv m scopem mutRecNSInfo (mutRecDefns: MutRecDefnsInitialData) = - // Split the definitions into "core representations" and "members". The code to process core representations + // Split the definitions into "core representations" and "members". The code to process core representations // is shared between processing of signature files and implementation files. let mutRecDefnsAfterSplit = mutRecDefns |> MutRecShapes.mapTycons SplitTyconDefn @@ -16547,7 +16547,7 @@ module TcDeclarations = MutRecDefnsPhase2DataForTycon(tyconOpt, innerParent, declKind, tcref, baseValOpt, safeInitInfo, declaredTyconTypars, members, tyDeclRange, newslotsOK, fixupFinalAttrs)) // By now we've established the full contents of type definitions apart from their - // members and any fields determined by implicit construction. We know the kinds and + // members and any fields determined by implicit construction. We know the kinds and // representations of types and have established them as valid. // // We now reconstruct the active environments all over again - this will add the union cases and fields. @@ -16558,11 +16558,11 @@ module TcDeclarations = (envInitial, MutRecShapes.dropEnvs mutRecDefnsAfterPrep) ||> MutRecBindingChecking.TcMutRecDefns_ComputeEnvs (fun (MutRecDefnsPhase2DataForTycon(tyconOpt, _, _, _, _, _, _, _, _, _, _)) -> tyconOpt) - (fun _binds -> [ (* no values are available yet *) ]) + (fun _binds -> [ (* no values are available yet *) ]) cenv true scopem m // Check the members and decide on representations for types with implicit constructors. - let withBindings, envFinal = TcMutRecDefns_Phase2 cenv envInitial m scopem mutRecNSInfo envMutRecPrelimWithReprs withEnvs + let withBindings, envFinal = TcMutRecDefns_Phase2 cenv envInitial m scopem mutRecNSInfo envMutRecPrelimWithReprs withEnvs // Generate the hash/compare/equality bindings for all tycons. // @@ -16596,15 +16596,15 @@ module TcDeclarations = match trepr with | SynTypeDefnSigRepr.ObjectModel(kind, cspec, m) -> - let fields = cspec |> List.choose (function SynMemberSig.ValField (f, _) -> Some(f) | _ -> None) + let fields = cspec |> List.choose (function SynMemberSig.ValField (f, _) -> Some(f) | _ -> None) let implements2 = cspec |> List.choose (function SynMemberSig.Interface (ty, m) -> Some(ty, m) | _ -> None) - let inherits = cspec |> List.choose (function SynMemberSig.Inherit (ty, _) -> Some(ty, m, None) | _ -> None) + let inherits = cspec |> List.choose (function SynMemberSig.Inherit (ty, _) -> Some(ty, m, None) | _ -> None) //let nestedTycons = cspec |> List.choose (function SynMemberSig.NestedType (x, _) -> Some(x) | _ -> None) - let slotsigs = cspec |> List.choose (function SynMemberSig.Member (v, fl, _) when fl.IsDispatchSlot -> Some(v, fl) | _ -> None) - let members = cspec |> List.filter (function + let slotsigs = cspec |> List.choose (function SynMemberSig.Member (v, fl, _) when fl.IsDispatchSlot -> Some(v, fl) | _ -> None) + let members = cspec |> List.filter (function | SynMemberSig.Interface _ -> true | SynMemberSig.Member (_, memberFlags, _) when not memberFlags.IsDispatchSlot -> true - | SynMemberSig.NestedType (_, m) -> error(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), m)); false + | SynMemberSig.NestedType (_, m) -> error(Error(FSComp.SR.tcTypesCannotContainNestedTypes(), m)); false | _ -> false) let isConcrete = members |> List.exists (function @@ -16619,7 +16619,7 @@ module TcDeclarations = memberFlags.MemberKind=MemberKind.Constructor && // REVIEW: This is a syntactic approximation (match valSpfn.SynType, valSpfn.SynInfo.ArgInfos with - | SynType.Fun (SynType.LongIdent (LongIdentWithDots([id], _)), _, _), [[_]] when id.idText = "unit" -> true + | SynType.Fun (SynType.LongIdent (LongIdentWithDots([id], _)), _, _), [[_]] when id.idText = "unit" -> true | _ -> false) | _ -> false) @@ -16680,7 +16680,7 @@ module TcDeclarations = MutRecBindingChecking.TcMutRecDefns_UpdateModuleContents mutRecNSInfo mutRecDefnsAfterCore // By now we've established the full contents of type definitions apart from their - // members and any fields determined by implicit construction. We know the kinds and + // members and any fields determined by implicit construction. We know the kinds and // representations of types and have established them as valid. // // We now reconstruct the active environments all over again - this will add the union cases and fields. @@ -16691,7 +16691,7 @@ module TcDeclarations = (envInitial, MutRecShapes.dropEnvs mutRecDefnsAfterCore) ||> MutRecBindingChecking.TcMutRecDefns_ComputeEnvs (fun (_, tyconOpt, _, _) -> tyconOpt) - (fun _binds -> [ (* no values are available yet *) ]) + (fun _binds -> [ (* no values are available yet *) ]) cenv true scopem m let mutRecDefnsAfterVals = TcMutRecSignatureDecls_Phase2 cenv scopem envMutRecPrelimWithReprs withEnvs @@ -16754,7 +16754,7 @@ let rec TcSignatureElementNonMutRec cenv parent typeNames endm (env: TcEnv) synS // Now typecheck the signature, accumulating and then recording the submodule description. let id = ident (modName, id.idRange) - let mspec = NewModuleOrNamespace (Some env.eCompPath) vis id (xml.ToXmlDoc()) attribs (MaybeLazy.Strict (NewEmptyModuleOrNamespaceType modKind)) + let mspec = NewModuleOrNamespace (Some env.eCompPath) vis id (xml.ToXmlDoc()) attribs (MaybeLazy.Strict (NewEmptyModuleOrNamespaceType modKind)) let! (mtyp, _) = TcModuleOrNamespaceSignatureElementsNonMutRec cenv (Parent (mkLocalModRef mspec)) env (id, modKind, mdefs, m, xml) @@ -17033,7 +17033,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem if letrec then let scopem = unionRanges m scopem let binds = binds |> List.map (fun bind -> RecDefnBindingInfo(containerInfo, NoNewSlots, ModuleOrMemberBinding, bind)) - let binds, env, _ = TcLetrec WarnOnOverrides cenv env tpenv (binds, m, scopem) + let binds, env, _ = TcLetrec WarnOnOverrides cenv env tpenv (binds, m, scopem) return ((fun e -> TMDefRec(true, [], binds |> List.map ModuleOrNamespaceBinding.Binding, m) :: e), []), env, env else let binds, env, _ = TcLetBindings cenv env containerInfo ModuleOrMemberBinding tpenv (binds, m, scopem) @@ -17093,7 +17093,7 @@ let rec TcModuleOrNamespaceElementNonMutRec (cenv: cenv) parent typeNames scopem // // In this case the envAtEnd is the environment at the end of this module, which doesn't contain the module definition itself // but does contain the results of all the 'open' declarations and so on. - let envAtEnd = (if isContinuingModule then envAtEnd else env) + let envAtEnd = (if isContinuingModule then envAtEnd else env) return ((fun modDefs -> modDefn :: modDefs), topAttrsNew), env, envAtEnd @@ -17181,7 +17181,7 @@ and TcModuleOrNamespaceElementsNonMutRec cenv parent typeNames endm (defsSoFar, let! firstDef', env', envAtEnd' = TcModuleOrNamespaceElementNonMutRec cenv parent typeNames scopem env firstDef // tail recursive - return! TcModuleOrNamespaceElementsNonMutRec cenv parent typeNames endm ( (firstDef' :: defsSoFar), env', envAtEnd') otherDefs + return! TcModuleOrNamespaceElementsNonMutRec cenv parent typeNames endm ( (firstDef' :: defsSoFar), env', envAtEnd') otherDefs | [] -> return List.rev defsSoFar, envAtEnd } @@ -17241,7 +17241,7 @@ and TcModuleOrNamespaceElementsMutRec cenv parent typeNames endm envInitial mutR | SynModuleDecl.DoExpr _ -> failwith "unreachable: SynModuleDecl.DoExpr - ElimModuleDoBinding" - | (SynModuleDecl.NamespaceFragment _ as d) -> error(Error(FSComp.SR.tcUnsupportedMutRecDecl(), d.Range))) + | (SynModuleDecl.NamespaceFragment _ as d) -> error(Error(FSComp.SR.tcUnsupportedMutRecDecl(), d.Range))) loop (match parent with ParentNone -> true | Parent _ -> false) [] defs @@ -17311,16 +17311,16 @@ and TcModuleOrNamespaceElements cenv parent endm env xml mutRecNSInfo defs = //-------------------------------------------------------------------------- -let ApplyAssemblyLevelAutoOpenAttributeToTcEnv g amap (ccu: CcuThunk) scopem env (p, root) = +let ApplyAssemblyLevelAutoOpenAttributeToTcEnv g amap (ccu: CcuThunk) scopem env (p, root) = let warn() = warning(Error(FSComp.SR.tcAttributeAutoOpenWasIgnored(p, ccu.AssemblyName), scopem)) env let p = splitNamespace p if isNil p then warn() else let h, t = List.frontAndBack p - let modref = mkNonLocalTyconRef (mkNonLocalEntityRef ccu (Array.ofList h)) t + let modref = mkNonLocalTyconRef (mkNonLocalEntityRef ccu (Array.ofList h)) t match modref.TryDeref with - | ValueNone -> warn() + | ValueNone -> warn() | ValueSome _ -> let openDecl = OpenDeclaration.Create ([], [modref], scopem, false) OpenModulesOrNamespaces TcResultsSink.NoSink g amap scopem root env [modref] openDecl @@ -17332,7 +17332,7 @@ let AddCcuToTcEnv(g, amap, scopem, env, assemblyName, ccu, autoOpens, internalsV // See https://fslang.uservoice.com/forums/245727-f-language/suggestions/6107641-make-microsoft-prefix-optional-when-using-core-f // "Microsoft" is opened by default in FSharp.Core let autoOpens = - let autoOpens = autoOpens |> List.map (fun p -> (p, false)) + let autoOpens = autoOpens |> List.map (fun p -> (p, false)) if ccuEq ccu g.fslibCcu then // Auto open 'Microsoft' in FSharp.Core.dll. Even when using old versions of FSharp.Core.dll that do // not have this attribute. The 'true' means 'treat all namespaces so revealed as "roots" accessible via @@ -17360,17 +17360,17 @@ type ConditionalDefines = type TopAttribs = { mainMethodAttrs: Attribs netModuleAttrs: Attribs - assemblyAttrs: Attribs } + assemblyAttrs: Attribs } let EmptyTopAttrs = { mainMethodAttrs=[] netModuleAttrs=[] - assemblyAttrs =[] } + assemblyAttrs =[] } let CombineTopAttrs topAttrs1 topAttrs2 = { mainMethodAttrs = topAttrs1.mainMethodAttrs @ topAttrs2.mainMethodAttrs - netModuleAttrs = topAttrs1.netModuleAttrs @ topAttrs2.netModuleAttrs - assemblyAttrs = topAttrs1.assemblyAttrs @ topAttrs2.assemblyAttrs } + netModuleAttrs = topAttrs1.netModuleAttrs @ topAttrs2.netModuleAttrs + assemblyAttrs = topAttrs1.assemblyAttrs @ topAttrs2.assemblyAttrs } let rec IterTyconsOfModuleOrNamespaceType f (mty: ModuleOrNamespaceType) = mty.AllEntities |> QueueList.iter (fun tycon -> f tycon) @@ -17462,11 +17462,11 @@ let CheckModuleSignature g cenv m denvAtEnd rootSigOpt implFileTypePriorToSig im raise (ReportedError None) // Compute the remapping from implementation to signature - let remapInfo , _ = ComputeRemappingFromInferredSignatureToExplicitSignature cenv.g implFileTypePriorToSig sigFileType + let remapInfo, _ = ComputeRemappingFromInferredSignatureToExplicitSignature cenv.g implFileTypePriorToSig sigFileType let aenv = { TypeEquivEnv.Empty with EquivTycons = TyconRefMap.OfList remapInfo.RepackagedEntities } - if not (SignatureConformance.Checker(cenv.g, cenv.amap, denv, remapInfo, true).CheckSignature aenv (mkLocalModRef implFileSpecPriorToSig) sigFileType) then ( + if not (SignatureConformance.Checker(cenv.g, cenv.amap, denv, remapInfo, true).CheckSignature aenv (mkLocalModRef implFileSpecPriorToSig) sigFileType) then ( // We can just raise 'ReportedError' since CheckModuleOrNamespace raises its own error raise (ReportedError None) ) @@ -17501,8 +17501,8 @@ let TypeCheckOneImplFile // REVIEW: consider checking if '_others' is empty let netModuleAttrs, _others = others |> List.partition (fun (possTargets, _) -> possTargets &&& AttributeTargets.Module <> enum 0) { mainMethodAttrs = List.map snd mainMethodAttrs - netModuleAttrs = List.map snd netModuleAttrs - assemblyAttrs = List.map snd assemblyAttrs} + netModuleAttrs = List.map snd netModuleAttrs + assemblyAttrs = List.map snd assemblyAttrs} let denvAtEnd = envAtEnd.DisplayEnv let m = qualNameOfFile.Range @@ -17565,7 +17565,7 @@ let TypeCheckOneImplFile // Warn on version attributes. topAttrs.assemblyAttrs |> List.iter (function - | Attrib(tref, _, [ AttribExpr(Expr.Const (Const.String(version), range, _), _) ] , _, _, _, _) -> + | Attrib(tref, _, [ AttribExpr(Expr.Const (Const.String(version), range, _), _) ], _, _, _, _) -> let attrName = tref.CompiledRepresentationForNamedType.FullName let isValid() = try IL.parseILVersion version |> ignore; true @@ -17585,7 +17585,7 @@ let TypeCheckOneImplFile /// Check an entire signature file -let TypeCheckOneSigFile (g, niceNameGen, amap, topCcu, checkForErrors, conditionalDefines, tcSink, isInternalTestSpanStackReferring) tcEnv (ParsedSigFileInput(_, qualNameOfFile, _, _, sigFileFrags)) = +let TypeCheckOneSigFile (g, niceNameGen, amap, topCcu, checkForErrors, conditionalDefines, tcSink, isInternalTestSpanStackReferring) tcEnv (ParsedSigFileInput(_, qualNameOfFile, _, _, sigFileFrags)) = eventually { let cenv = cenv.Create (g, false, niceNameGen, amap, topCcu, true, false, conditionalDefines, tcSink, (LightweightTcValForUsingInBuildMethodCall g), isInternalTestSpanStackReferring) let envinner, mtypeAcc = MakeInitialEnv tcEnv diff --git a/src/fsharp/TypeRelations.fs b/src/fsharp/TypeRelations.fs index 2d07a2b4177..05c016d3cfa 100755 --- a/src/fsharp/TypeRelations.fs +++ b/src/fsharp/TypeRelations.fs @@ -31,14 +31,14 @@ let rec TypeDefinitelySubsumesTypeNoCoercion ndeep g amap m ty1 ty2 = 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 -> + | 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 @@ -67,14 +67,14 @@ let rec TypesFeasiblyEquiv ndeep g amap m ty1 ty2 = let ty2 = stripTyEqns g ty2 match ty1, ty2 with // QUERY: should these be false for non-equal rigid typars? warn-if-not-rigid typars? - | TType_var _ , _ + | 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 @@ -89,14 +89,14 @@ let rec TypeFeasiblySubsumesType ndeep g amap m ty1 canCoerce ty2 = let ty2 = stripTyEqns g ty2 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_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 diff --git a/src/fsharp/ast.fs b/src/fsharp/ast.fs index b4819ad5392..a5068dae2d6 100644 --- a/src/fsharp/ast.fs +++ b/src/fsharp/ast.fs @@ -526,7 +526,7 @@ and | MeasurePower of measureType: SynType * SynRationalConst * range: range /// F# syntax: 1, "abc" etc, used in parameters to type providers - /// For the dimensionless units i.e. 1 , and static parameters to provided types + /// For the dimensionless units i.e. 1, and static parameters to provided types | StaticConstant of constant: SynConst * range: range /// F# syntax: const expr, used in static parameters to type providers @@ -716,10 +716,10 @@ and /// F# syntax: expr.[expr, ..., expr] <- expr | 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' + /// 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 - /// F# syntax: expr.Items(e1) <- e2 , rarely used named-property-setter notation, e.g. (stringExpr).Chars(3) <- 'a' + /// 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 /// F# syntax: expr :? type @@ -1312,10 +1312,10 @@ and /// A type abbreviation, "type X = A.B.C" | TypeAbbrev of ParserDetail * SynType * range: range - /// An abstract definition , "type X" + /// An abstract definition, "type X" | None of range: range - /// An exception definition , "exception E = ..." + /// An exception definition, "exception E = ..." | Exception of SynExceptionDefnRepr member this.Range = diff --git a/src/fsharp/fsc.fs b/src/fsharp/fsc.fs index ecc94eef7fd..f88d7789ee5 100644 --- a/src/fsharp/fsc.fs +++ b/src/fsharp/fsc.fs @@ -1510,7 +1510,7 @@ module StaticLinker = let access = (if isNested then ILTypeDefAccess.Nested ILMemberAccess.Public else ILTypeDefAccess.Public) let tdefs = mkILTypeDefs (List.map buildRelocatedGeneratedType ch) - mkILSimpleClass ilGlobals (ilTgtTyRef.Name, access, emptyILMethods, emptyILFields, tdefs , emptyILProperties, emptyILEvents, emptyILCustomAttrs, ILTypeInit.OnAny) + mkILSimpleClass ilGlobals (ilTgtTyRef.Name, access, emptyILMethods, emptyILFields, tdefs, emptyILProperties, emptyILEvents, emptyILCustomAttrs, ILTypeInit.OnAny) [ for (ProviderGeneratedType(_, ilTgtTyRef, _) as node) in tcImports.ProviderGeneratedTypeRoots do yield (ilTgtTyRef, buildRelocatedGeneratedType node) ] @@ -2000,7 +2000,7 @@ let main1OfAst (ctok, legacyReferenceResolver, reduceMemoryUsage, assemblyName, // data structures involved here are so large we can't take the risk. Args(ctok, tcConfig, tcImports, frameworkTcImports, tcGlobals, errorLogger, generatedCcu, outfile, typedAssembly, topAttrs, pdbFile, assemblyName, - assemVerFromAttrib, signingInfo ,exiter) + assemVerFromAttrib, signingInfo,exiter) /// Phase 2a: encode signature data, optimize, encode optimization data diff --git a/src/fsharp/fsi/fsi.fs b/src/fsharp/fsi/fsi.fs index e3c60242137..b5341a5d64b 100644 --- a/src/fsharp/fsi/fsi.fs +++ b/src/fsharp/fsi/fsi.fs @@ -696,8 +696,8 @@ type internal FsiCommandLineOptions(fsi: FsiEvaluationSessionHostConfig, argv: s Some (FSIstrings.SR.fsiHelp())) ]); PrivateOptions( - [ CompilerOption("?" , tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help"); - CompilerOption("help" , tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help"); + [ CompilerOption("?", tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help"); + CompilerOption("help", tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help"); CompilerOption("full-help", tagNone, OptionHelp (fun blocks -> displayHelpFsi tcConfigB blocks), None, None); // "Short form of --help"); ]); PublicOptions(FSComp.SR.optsHelpBannerAdvanced(), @@ -1977,9 +1977,9 @@ type internal FsiInteractionProcessor let rec execParsedInteractions (ctok, tcConfig, istate, action, errorLogger: ErrorLogger, lastResult:option) = let action,nextAction,istate = match action with - | None -> None ,None,istate + | None -> None,None,istate | Some (IHash _) -> action,None,istate - | Some (IDefns ([],_)) -> None ,None,istate + | Some (IDefns ([],_)) -> None,None,istate | Some (IDefns (SynModuleDecl.HashDirective(hash,mh)::defs,m)) -> Some (IHash(hash,mh)),Some (IDefns(defs,m)),istate @@ -1989,7 +1989,7 @@ type internal FsiInteractionProcessor // only add automatic debugger breaks before 'let' or 'do' expressions with sequence points match def with | SynModuleDecl.DoExpr (SequencePointInfoForBinding.SequencePointAtBinding _, _, _) - | SynModuleDecl.Let (_, SynBinding.Binding(_, _, _, _, _, _, _, _ ,_ ,_ ,_ , SequencePointInfoForBinding.SequencePointAtBinding _) :: _, _) -> true + | SynModuleDecl.Let (_, SynBinding.Binding(_, _, _, _, _, _, _, _,_,_,_, SequencePointInfoForBinding.SequencePointAtBinding _) :: _, _) -> true | _ -> false let defsA = Seq.takeWhile (isDefHash >> not) defs |> Seq.toList let defsB = Seq.skipWhile (isDefHash >> not) defs |> Seq.toList diff --git a/src/fsharp/layout.fs b/src/fsharp/layout.fs index 02eaf804773..2fa02f41025 100644 --- a/src/fsharp/layout.fs +++ b/src/fsharp/layout.fs @@ -58,8 +58,8 @@ let mkNode l r joint = //-------------------------------------------------------------------------- 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 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 = @@ -361,13 +361,13 @@ let squashTo maxWidth layout = 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 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 + 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 let breaks = breaks0 () diff --git a/src/fsharp/pars.fsy b/src/fsharp/pars.fsy index aef3d2d8d05..1a7afd753f8 100644 --- a/src/fsharp/pars.fsy +++ b/src/fsharp/pars.fsy @@ -1218,7 +1218,7 @@ moduleDefn: /* 'type' definitions */ | opt_attributes opt_declVisibility typeKeyword tyconDefn tyconDefnList { if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2)) - let (TypeDefn(ComponentInfo(cas ,a,cs,b,c,d,d2,d3),e,f,g)) = $4 + let (TypeDefn(ComponentInfo(cas,a,cs,b,c,d,d2,d3),e,f,g)) = $4 let tc = (TypeDefn(ComponentInfo($1@cas,a,cs,b,c,d,d2,d3),e,f,g)) let types = tc :: $5 [ SynModuleDecl.Types(types, (rhs parseState 3, types) ||> unionRangeWithListBy (fun t -> t.Range) ) ] } @@ -1288,7 +1288,7 @@ namedModuleDefnBlock: // System.DateTime.Now // module M2 = // Microsoft.FSharp.Core.List - // The second is a module abbreviation , the first a module containing a single expression. + // The second is a module abbreviation, the first a module containing a single expression. // The resolution is in favour of the module abbreviation, i.e. anything of the form // module M2 = ID.ID.ID.ID // will be taken as a module abbreviation, regardles of the identifiers themselves. @@ -2493,7 +2493,7 @@ cPrototype: let bindingId = SynPat.LongIdent (LongIdentWithDots([nm],[]), None, Some noInferredTypars, SynConstructorArgs.Pats [SynPat.Tuple(false,args,argsm)], vis, nmm) let binding = mkSynBinding (xmlDoc, bindingId) - (vis, false, false, mBindLhs, NoSequencePointAtInvisibleBinding, Some rty ,rhsExpr, mRhs, [], attrs, None) + (vis, false, false, mBindLhs, NoSequencePointAtInvisibleBinding, Some rty, rhsExpr, mRhs, [], attrs, None) [], [binding]) } /* A list of arguments in an 'extern' DllImport function definition */ @@ -3038,7 +3038,7 @@ declExpr: | hardwhiteLetBindings OBLOCKSEP typedSeqExprBlock %prec expr_let { let hwlb,m = $1 - mkLocalBindings (unionRanges m $3.Range ,hwlb,$3) } + mkLocalBindings (unionRanges m $3.Range, hwlb, $3) } | hardwhiteLetBindings OBLOCKSEP error %prec expr_let { let hwlb,m = $1 @@ -4727,7 +4727,7 @@ measureTypeExpr: typar: | QUOTE ident { let id = mkSynId (lhs parseState) ($2).idText - Typar(id ,NoStaticReq,false) } + Typar(id, NoStaticReq,false) } | staticallyKnownHeadTypar { $1 } diff --git a/src/fsharp/range.fs b/src/fsharp/range.fs index 84419892a78..2bf3f17f613 100755 --- a/src/fsharp/range.fs +++ b/src/fsharp/range.fs @@ -325,7 +325,7 @@ let rangeCmdArgs = rangeN "commandLineArgs" 0 let trimRangeToLine (r:range) = let startL, startC = r.StartLine, r.StartColumn - let endL , _endC = r.EndLine, r.EndColumn + let endL, _endC = r.EndLine, r.EndColumn if endL <= startL then r else diff --git a/src/fsharp/service/IncrementalBuild.fs b/src/fsharp/service/IncrementalBuild.fs index 836a4f288bd..d061f3f75ee 100755 --- a/src/fsharp/service/IncrementalBuild.fs +++ b/src/fsharp/service/IncrementalBuild.fs @@ -529,7 +529,7 @@ module internal IncrementalBuild = match found with | VectorResult rv -> if rv.Size <> expectedWidth then - actionFunc (ResizeResultAction(ve.Id , expectedWidth)) acc + actionFunc (ResizeResultAction(ve.Id, expectedWidth)) acc else acc | _ -> acc | None -> acc @@ -1286,7 +1286,7 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput try IncrementalBuilderEventTesting.MRU.Add(IncrementalBuilderEventTesting.IBEParsed filename) - let input = ParseOneInputFile(tcConfig, lexResourceManager, [], filename , isLastCompiland, errorLogger, (*retryLocked*)true) + let input = ParseOneInputFile(tcConfig, lexResourceManager, [], filename, isLastCompiland, errorLogger, (*retryLocked*)true) fileParsed.Trigger (filename) input, sourceRange, filename, errorLogger.GetErrors () diff --git a/src/fsharp/service/ServiceInterfaceStubGenerator.fs b/src/fsharp/service/ServiceInterfaceStubGenerator.fs index d2ec593838a..e4a2bc7e029 100644 --- a/src/fsharp/service/ServiceInterfaceStubGenerator.fs +++ b/src/fsharp/service/ServiceInterfaceStubGenerator.fs @@ -124,7 +124,7 @@ type internal InterfaceData = sprintf "- %s" s let rec (|TypeIdent|_|) = function - | SynType.Var(SynTypar.Typar(s, req , _), _) -> + | SynType.Var(SynTypar.Typar(s, req, _), _) -> match req with | NoStaticReq -> Some ("'" + s.idText) @@ -240,16 +240,18 @@ module internal InterfaceStubGenerator = name :: acc, allNames) ([], namesWithIndices) List.rev argsSoFar' :: argsSoFar, namesWithIndices) ([], Map.ofList [ ctx.ObjectIdent, Set.empty ]) - args - |> List.rev - |> List.map (function - | [] -> unit - | [arg] when arg = unit -> unit - | [arg] when not v.IsMember || isItemIndexer -> arg - | args when isItemIndexer -> String.concat tupSep args - | args -> bracket (String.concat tupSep args)) - |> String.concat argSep - , namesWithIndices + let argText = + args + |> List.rev + |> List.map (function + | [] -> unit + | [arg] when arg = unit -> unit + | [arg] when not v.IsMember || isItemIndexer -> arg + | args when isItemIndexer -> String.concat tupSep args + | args -> bracket (String.concat tupSep args)) + |> String.concat argSep + + argText, namesWithIndices [] type internal MemberInfo = @@ -307,11 +309,12 @@ module internal InterfaceStubGenerator = "", Map.ofList [ctx.ObjectIdent, Set.empty] | _ -> formatArgsUsage ctx verboseMode v argInfos - if String.IsNullOrWhiteSpace(args) then "" - elif args.StartsWithOrdinal("(") then args - elif v.CurriedParameterGroups.Count > 1 && (not verboseMode) then " " + args - else sprintf "(%s)" args - , namesWithIndices + let argText = + if String.IsNullOrWhiteSpace(args) then "" + elif args.StartsWithOrdinal("(") then args + elif v.CurriedParameterGroups.Count > 1 && (not verboseMode) then " " + args + else sprintf "(%s)" args + argText, namesWithIndices let preprocess (ctx: Context) (v: FSharpMemberOrFunctionOrValue) = let buildUsage argInfos = diff --git a/src/fsharp/service/ServiceLexing.fs b/src/fsharp/service/ServiceLexing.fs index e751049ebfc..3932fbf4b60 100755 --- a/src/fsharp/service/ServiceLexing.fs +++ b/src/fsharp/service/ServiceLexing.fs @@ -227,7 +227,7 @@ module internal TokenClassifications = | 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 diff --git a/src/fsharp/service/ServiceUntypedParse.fs b/src/fsharp/service/ServiceUntypedParse.fs index 1e6b98ebdc4..0f465a28037 100755 --- a/src/fsharp/service/ServiceUntypedParse.fs +++ b/src/fsharp/service/ServiceUntypedParse.fs @@ -1134,7 +1134,7 @@ module UntypedParseImpl = Some (id.idRange.End, findSetters arg) | (SynExpr.App (_, false, SynExpr.TypeApp(SynExpr.Ident id, _, _, _, mGreaterThan, _, _), arg, _)) -> // A<_>() - Some (endOfClosingTokenOrIdent mGreaterThan id , findSetters arg) + Some (endOfClosingTokenOrIdent mGreaterThan id, findSetters arg) | (SynExpr.App (_, false, SynExpr.LongIdent(_, lid, _, _), arg, _)) -> // A.B() Some (endOfLastIdent lid, findSetters arg) diff --git a/src/fsharp/symbols/Symbols.fs b/src/fsharp/symbols/Symbols.fs index 3f89cebafd5..7adcdfbee4e 100644 --- a/src/fsharp/symbols/Symbols.fs +++ b/src/fsharp/symbols/Symbols.fs @@ -1051,7 +1051,7 @@ and FSharpField(cenv: SymbolEnv, d: FSharpFieldData) = match d, uc.V with | RecdOrClass r1, RecdOrClass r2 -> recdFieldRefOrder.Compare(r1, r2) = 0 | Union (u1, n1), Union (u2, n2) -> cenv.g.unionCaseRefEq u1 u2 && n1 = n2 - | AnonField (anonInfo1, _, _, _) , AnonField (anonInfo2, _, _, _) -> x.Name = uc.Name && anonInfoEquiv anonInfo1 anonInfo2 + | AnonField (anonInfo1, _, _, _), AnonField (anonInfo2, _, _, _) -> x.Name = uc.Name && anonInfoEquiv anonInfo1 anonInfo2 | _ -> false | _ -> false diff --git a/src/fsharp/tast.fs b/src/fsharp/tast.fs index 08851f56464..687c81ce145 100644 --- a/src/fsharp/tast.fs +++ b/src/fsharp/tast.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. //------------------------------------------------------------------------- // Defines the typed abstract syntax trees used throughout the F# compiler. @@ -45,7 +45,7 @@ type Stamp = int64 let newStamp = let i = ref 0L in fun () -> System.Threading.Interlocked.Increment(i) /// A global generator of compiler generated names -// ++GLOBAL MUTABLE STATE (concurrency safe by locking inside NiceNameGenerator) +// ++GLOBAL MUTABLE STATE (concurrency safe by locking inside NiceNameGenerator) let globalNng = NiceNameGenerator() /// A global generator of stable compiler generated names @@ -88,7 +88,7 @@ type ValRecursiveScopeInfo = /// The normal value for this flag when the value is not within its recursive scope | ValNotInRecScope -type ValMutability = +type ValMutability = | Immutable | Mutable @@ -343,7 +343,7 @@ type TyparFlags(flags: int32) = member x.IsCompilerGenerated = (flags &&& 0b00000000000000100) <> 0x0 /// Indicates if the type variable has a static "head type" requirement, i.e. ^a variables used in FSharp.Core and member constraints. - member x.StaticReq = + member x.StaticReq = match (flags &&& 0b00000000000001000) with | 0b00000000000000000 -> NoStaticReq | 0b00000000000001000 -> HeadTypeStaticReq @@ -361,7 +361,7 @@ type TyparFlags(flags: int32) = | _ -> failwith "unreachable" /// Indicates whether a type variable can be instantiated by types or units-of-measure. - member x.Kind = + member x.Kind = match (flags &&& 0b00001000100000000) with | 0b00000000000000000 -> TyparKind.Type | 0b00000000100000000 -> TyparKind.Measure @@ -373,7 +373,7 @@ type TyparFlags(flags: int32) = (flags &&& 0b00000001000000000) <> 0x0 /// Indicates if a type parameter is needed at runtime and may not be eliminated - member x.DynamicReq = + member x.DynamicReq = match (flags &&& 0b00000010000000000) with | 0b00000000000000000 -> TyparDynamicReq.No | 0b00000010000000000 -> TyparDynamicReq.Yes @@ -394,7 +394,7 @@ type TyparFlags(flags: int32) = TyparFlags(flags &&& ~~~0b00010000000000000) /// Get the flags as included in the F# binary metadata. We pickle this as int64 to allow for future expansion - member x.PickledBits = flags + member x.PickledBits = flags /// Encode entity flags into a bit field. We leave lots of space to allow for future expansion. [] @@ -513,13 +513,13 @@ let ComputeDefinitionLocationOfProvidedItem (p: Tainted<#IProvidedCustomAttribut // Coordinates from type provider are 1-based for lines and columns // Coordinates internally in the F# compiler are 1-based for lines and 0-based for columns let pos = Range.mkPos line (max 0 (column - 1)) - Range.mkRange filePath pos pos |> Some + Range.mkRange filePath pos pos |> Some #endif /// A public path records where a construct lives within the global namespace /// of a CCU. -type PublicPath = +type PublicPath = | PubPath of string[] member x.EnclosingPath = let (PubPath(pp)) = x @@ -597,7 +597,7 @@ type EntityOptionalData = } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "EntityOptionalData(...)" @@ -605,7 +605,7 @@ and /// Represents a type definition, exception definition, module definition or [] Entity = { /// The declared type parameters of the type - // MUTABILITY; used only during creation and remapping of tycons + // MUTABILITY; used only during creation and remapping of tycons mutable entity_typars: LazyWithContext mutable entity_flags: EntityFlags @@ -638,7 +638,7 @@ and /// Represents a type definition, exception definition, module definition or /// This field is used when the 'tycon' is really a module definition. It holds statically nested type definitions and nested modules // - // MUTABILITY: only used during creation and remapping of tycons and + // MUTABILITY: only used during creation and remapping of tycons and // when compiling fslib to fixup compiler forward references to internal items mutable entity_modul_contents: MaybeLazy @@ -737,8 +737,8 @@ and /// Represents a type definition, exception definition, module definition or match x.TypeReprInfo with | TProvidedTypeExtensionPoint info -> match ComputeDefinitionLocationOfProvidedItem info.ProvidedType with - | Some range -> range - | None -> x.entity_range + | Some range -> range + | None -> x.entity_range | _ -> #endif x.entity_range @@ -754,7 +754,7 @@ and /// Represents a type definition, exception definition, module definition or | Some { entity_other_range = Some (r, false) } -> r | _ -> x.Range - member x.SetOtherRange m = + member x.SetOtherRange m = match x.entity_opt_data with | Some optData -> optData.entity_other_range <- Some m | _ -> x.entity_opt_data <- Some { Entity.NewEmptyEntityOptData() with entity_other_range = Some m } @@ -935,7 +935,7 @@ and /// Represents a type definition, exception definition, module definition or member x.AllFieldTable = match x.TypeReprInfo with | TRecdRepr x | TFSharpObjectRepr {fsobjmodel_rfields=x} -> x - | _ -> + | _ -> match x.ExceptionInfo with | TExnFresh x -> x | _ -> @@ -970,13 +970,13 @@ and /// Represents a type definition, exception definition, module definition or member x.GetFieldByName n = x.AllFieldTable.FieldByName n /// Indicate if this is a type whose r.h.s. is known to be a union type definition. - member x.IsUnionTycon = match x.TypeReprInfo with | TUnionRepr _ -> true | _ -> false + member x.IsUnionTycon = match x.TypeReprInfo with | TUnionRepr _ -> true | _ -> false /// Get the union cases and other union-type information for a type, if any member x.UnionTypeInfo = match x.TypeReprInfo with | TUnionRepr x -> ValueSome x - | _ -> ValueNone + | _ -> ValueNone /// Get the union cases for a type, if any member x.UnionCasesArray = @@ -990,7 +990,7 @@ and /// Represents a type definition, exception definition, module definition or /// Get a union case of a type by name member x.GetUnionCaseByName n = match x.UnionTypeInfo with - | ValueSome x -> NameMap.tryFind n x.CasesTable.CasesByName + | ValueSome x -> NameMap.tryFind n x.CasesTable.CasesByName | ValueNone -> None @@ -1011,22 +1011,22 @@ and /// Represents a type definition, exception definition, module definition or entity_opt_data = Unchecked.defaultof<_>} /// Create a new entity with the given backing data. Only used during unpickling of F# metadata. - static member New _reason (data: Entity) : Entity = data + static member New _reason (data: Entity) : Entity = data /// Link an entity based on empty, unlinked data to the given data. Only used during unpickling of F# metadata. member x.Link (tg: EntityData) = - x.entity_typars <- tg.entity_typars - x.entity_flags <- tg.entity_flags - x.entity_stamp <- tg.entity_stamp - x.entity_logical_name <- tg.entity_logical_name - x.entity_range <- tg.entity_range - x.entity_attribs <- tg.entity_attribs - x.entity_tycon_repr <- tg.entity_tycon_repr - x.entity_tycon_tcaug <- tg.entity_tycon_tcaug - x.entity_modul_contents <- tg.entity_modul_contents - x.entity_pubpath <- tg.entity_pubpath - x.entity_cpath <- tg.entity_cpath - x.entity_il_repr_cache <- tg.entity_il_repr_cache + x.entity_typars <- tg.entity_typars + x.entity_flags <- tg.entity_flags + x.entity_stamp <- tg.entity_stamp + x.entity_logical_name <- tg.entity_logical_name + x.entity_range <- tg.entity_range + x.entity_attribs <- tg.entity_attribs + x.entity_tycon_repr <- tg.entity_tycon_repr + x.entity_tycon_tcaug <- tg.entity_tycon_tcaug + x.entity_modul_contents <- tg.entity_modul_contents + x.entity_pubpath <- tg.entity_pubpath + x.entity_cpath <- tg.entity_cpath + x.entity_il_repr_cache <- tg.entity_il_repr_cache match tg.entity_opt_data with | Some tg -> x.entity_opt_data <- @@ -1049,68 +1049,68 @@ and /// Represents a type definition, exception definition, module definition or member x.FSharpObjectModelTypeInfo = match x.TypeReprInfo with | TFSharpObjectRepr x -> x - | _ -> failwith "not an F# object model type definition" + | _ -> failwith "not an F# object model type definition" /// Indicate if this is a type definition backed by Abstract IL metadata. - member x.IsILTycon = match x.TypeReprInfo with | TILObjectRepr _ -> true | _ -> false + member x.IsILTycon = match x.TypeReprInfo with | TILObjectRepr _ -> true | _ -> false /// Get the Abstract IL scope, nesting and metadata for this /// type definition, assuming it is backed by Abstract IL metadata. - member x.ILTyconInfo = match x.TypeReprInfo with | TILObjectRepr data -> data | _ -> failwith "not a .NET type definition" + member x.ILTyconInfo = match x.TypeReprInfo with | TILObjectRepr data -> data | _ -> failwith "not a .NET type definition" /// Get the Abstract IL metadata for this type definition, assuming it is backed by Abstract IL metadata. member x.ILTyconRawMetadata = let (TILObjectReprData(_, _, td)) = x.ILTyconInfo in td /// Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition. - member x.IsRecordTycon = match x.TypeReprInfo with | TRecdRepr _ -> true | _ -> false + member x.IsRecordTycon = match x.TypeReprInfo with | TRecdRepr _ -> true | _ -> false /// Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition that is a value type. member x.IsStructRecordOrUnionTycon = match x.TypeReprInfo with TRecdRepr _ | TUnionRepr _ -> x.entity_flags.IsStructRecordOrUnionType | _ -> false /// The on-demand analysis about whether the entity has the IsByRefLike attribute - member x.TryIsByRefLike = x.entity_flags.TryIsByRefLike + member x.TryIsByRefLike = x.entity_flags.TryIsByRefLike /// Set the on-demand analysis about whether the entity has the IsByRefLike attribute - member x.SetIsByRefLike b = x.entity_flags <- x.entity_flags.WithIsByRefLike b + member x.SetIsByRefLike b = x.entity_flags <- x.entity_flags.WithIsByRefLike b /// These two bits represents the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct - member x.TryIsReadOnly = x.entity_flags.TryIsReadOnly + member x.TryIsReadOnly = x.entity_flags.TryIsReadOnly /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct - member x.SetIsReadOnly b = x.entity_flags <- x.entity_flags.WithIsReadOnly b + member x.SetIsReadOnly b = x.entity_flags <- x.entity_flags.WithIsReadOnly b /// Indicates if this is an F# type definition whose r.h.s. is known to be some kind of F# object model definition - member x.IsFSharpObjectModelTycon = match x.TypeReprInfo with | TFSharpObjectRepr _ -> true | _ -> false + member x.IsFSharpObjectModelTycon = match x.TypeReprInfo with | TFSharpObjectRepr _ -> true | _ -> false /// Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll which uses /// an assembly-code representation for the type, e.g. the primitive array type constructor. - member x.IsAsmReprTycon = match x.TypeReprInfo with | TAsmRepr _ -> true | _ -> false + member x.IsAsmReprTycon = match x.TypeReprInfo with | TAsmRepr _ -> true | _ -> false /// Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll like 'float<_>' which /// defines a measure type with a relation to an existing non-measure type as a representation. - member x.IsMeasureableReprTycon = match x.TypeReprInfo with | TMeasureableRepr _ -> true | _ -> false + member x.IsMeasureableReprTycon = match x.TypeReprInfo with | TMeasureableRepr _ -> true | _ -> false /// Indicates if this is an F# type definition whose r.h.s. definition is unknown (i.e. a traditional ML 'abstract' type in a signature, /// which in F# is called a 'unknown representation' type). - member x.IsHiddenReprTycon = match x.TypeAbbrev, x.TypeReprInfo with | None, TNoRepr -> true | _ -> false + member x.IsHiddenReprTycon = match x.TypeAbbrev, x.TypeReprInfo with | None, TNoRepr -> true | _ -> false /// Indicates if this is an F#-defined interface type definition member x.IsFSharpInterfaceTycon = x.IsFSharpObjectModelTycon && match x.FSharpObjectModelTypeInfo.fsobjmodel_kind with TTyconInterface -> true | _ -> false /// Indicates if this is an F#-defined delegate type definition - member x.IsFSharpDelegateTycon = x.IsFSharpObjectModelTycon && match x.FSharpObjectModelTypeInfo.fsobjmodel_kind with TTyconDelegate _ -> true | _ -> false + member x.IsFSharpDelegateTycon = x.IsFSharpObjectModelTycon && match x.FSharpObjectModelTypeInfo.fsobjmodel_kind with TTyconDelegate _ -> true | _ -> false /// Indicates if this is an F#-defined enum type definition - member x.IsFSharpEnumTycon = x.IsFSharpObjectModelTycon && match x.FSharpObjectModelTypeInfo.fsobjmodel_kind with TTyconEnum -> true | _ -> false + member x.IsFSharpEnumTycon = x.IsFSharpObjectModelTycon && match x.FSharpObjectModelTypeInfo.fsobjmodel_kind with TTyconEnum -> true | _ -> false /// Indicates if this is an F#-defined class type definition - member x.IsFSharpClassTycon = x.IsFSharpObjectModelTycon && match x.FSharpObjectModelTypeInfo.fsobjmodel_kind with TTyconClass -> true | _ -> false + member x.IsFSharpClassTycon = x.IsFSharpObjectModelTycon && match x.FSharpObjectModelTypeInfo.fsobjmodel_kind with TTyconClass -> true | _ -> false /// Indicates if this is a .NET-defined enum type definition - member x.IsILEnumTycon = x.IsILTycon && x.ILTyconRawMetadata.IsEnum + member x.IsILEnumTycon = x.IsILTycon && x.ILTyconRawMetadata.IsEnum /// Indicates if this is an enum type definition - member x.IsEnumTycon = + member x.IsEnumTycon = #if !NO_EXTENSIONTYPING match x.TypeReprInfo with | TProvidedTypeExtensionPoint info -> info.IsEnum @@ -1120,23 +1120,23 @@ and /// Represents a type definition, exception definition, module definition or x.IsILEnumTycon || x.IsFSharpEnumTycon - /// Indicates if this is an F#-defined struct or enum type definition , i.e. a value type definition + /// Indicates if this is an F#-defined struct or enum type definition, i.e. a value type definition member x.IsFSharpStructOrEnumTycon = match x.TypeReprInfo with | TRecdRepr _ -> x.IsStructRecordOrUnionTycon | TUnionRepr _ -> x.IsStructRecordOrUnionTycon | TFSharpObjectRepr info -> match info.fsobjmodel_kind with - | TTyconClass | TTyconInterface | TTyconDelegate _ -> false + | TTyconClass | TTyconInterface | TTyconDelegate _ -> false | TTyconStruct | TTyconEnum -> true | _ -> false - /// Indicates if this is a .NET-defined struct or enum type definition , i.e. a value type definition + /// Indicates if this is a .NET-defined struct or enum type definition, i.e. a value type definition member x.IsILStructOrEnumTycon = x.IsILTycon && x.ILTyconRawMetadata.IsStructOrEnum - /// Indicates if this is a struct or enum type definition , i.e. a value type definition + /// Indicates if this is a struct or enum type definition, i.e. a value type definition member x.IsStructOrEnumTycon = #if !NO_EXTENSIONTYPING match x.TypeReprInfo with @@ -1214,9 +1214,9 @@ and /// Represents a type definition, exception definition, module definition or | _ -> #endif let ilTypeRefForCompilationPath (CompPath(sref, p)) item = - let rec top racc p = + let rec top racc p = match p with - | [] -> ILTypeRef.Create(sref, [], textOfPath (List.rev (item::racc))) + | [] -> ILTypeRef.Create(sref, [], textOfPath (List.rev (item::racc))) | (h, istype)::t -> match istype with | FSharpModuleWithSuffix | ModuleOrType -> @@ -1244,7 +1244,7 @@ and /// Represents a type definition, exception definition, module definition or let ilTypeOpt = match x.TyparsNoRange with | [] -> Some (mkILTy boxity (mkILTySpec (ilTypeRef, []))) - | _ -> None + | _ -> None CompiledTypeRepr.ILAsmNamed (ilTypeRef, boxity, ilTypeOpt)) /// Gets the data indicating the compiled representation of a named type or module in terms of Abstract IL data structures. @@ -1264,10 +1264,10 @@ and /// Represents a type definition, exception definition, module definition or member x.SetAttribs attribs = x.entity_attribs <- attribs /// Sets the structness of a record or union type definition - member x.SetIsStructRecordOrUnion b = let flags = x.entity_flags in x.entity_flags <- EntityFlags(flags.IsPrefixDisplay, flags.IsModuleOrNamespace, flags.PreEstablishedHasDefaultConstructor, flags.HasSelfReferentialConstructor, b) + member x.SetIsStructRecordOrUnion b = let flags = x.entity_flags in x.entity_flags <- EntityFlags(flags.IsPrefixDisplay, flags.IsModuleOrNamespace, flags.PreEstablishedHasDefaultConstructor, flags.HasSelfReferentialConstructor, b) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = x.LogicalName @@ -1339,13 +1339,13 @@ and mutable tcaug_abstract: bool } - member tcaug.SetCompare x = tcaug.tcaug_compare <- Some x + member tcaug.SetCompare x = tcaug.tcaug_compare <- Some x - member tcaug.SetCompareWith x = tcaug.tcaug_compare_withc <- Some x + member tcaug.SetCompareWith x = tcaug.tcaug_compare_withc <- Some x - member tcaug.SetEquals x = tcaug.tcaug_equals <- Some x + member tcaug.SetEquals x = tcaug.tcaug_equals <- Some x - member tcaug.SetHashAndEqualsWith x = tcaug.tcaug_hash_and_equals_withc <- Some x + member tcaug.SetHashAndEqualsWith x = tcaug.tcaug_hash_and_equals_withc <- Some x member tcaug.SetHasObjectGetHashCode b = tcaug.tcaug_hasObjectGetHashCode <- b @@ -1363,7 +1363,7 @@ and tcaug_abstract=false } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TyconAugmentation(...)" @@ -1373,22 +1373,22 @@ and TyconRepresentation = /// Indicates the type is a class, struct, enum, delegate or interface - | TFSharpObjectRepr of TyconObjModelData + | TFSharpObjectRepr of TyconObjModelData /// Indicates the type is a record - | TRecdRepr of TyconRecdFields + | TRecdRepr of TyconRecdFields /// Indicates the type is a discriminated union - | TUnionRepr of TyconUnionData + | TUnionRepr of TyconUnionData /// Indicates the type is a type from a .NET assembly without F# metadata. - | TILObjectRepr of TILObjectReprData + | TILObjectRepr of TILObjectReprData /// Indicates the type is implemented as IL assembly code using the given closed Abstract IL type - | TAsmRepr of ILType + | TAsmRepr of ILType /// Indicates the type is parameterized on a measure (e.g. float<_>) but erases to some other type (e.g. float) - | TMeasureableRepr of TType + | TMeasureableRepr of TType #if !NO_EXTENSIONTYPING /// TProvidedTypeExtensionPoint @@ -1413,7 +1413,7 @@ and | TNoRepr //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -1424,7 +1424,7 @@ and | TILObjectReprData of ILScopeRef * ILTypeDef list * ILTypeDef [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TILObjectReprData(...)" @@ -1441,20 +1441,20 @@ and /// 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 /// error messages) - ProvidedType: Tainted + ProvidedType: Tainted /// The base type of the type. We use it to compute the compiled representation of the type for erased types. /// Reading is delayed, since it does an import on the underlying type LazyBaseType: LazyWithContext /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. - IsClass: bool + IsClass: bool /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. - IsSealed: bool + IsSealed: bool /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. - IsInterface: bool + IsInterface: bool /// A flag read eagerly from the provided type and used to compute basic properties of the type definition. IsStructOrEnum: bool @@ -1483,7 +1483,7 @@ and else failwith "expect erased type" [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TProvidedTypeInfo(...)" @@ -1508,7 +1508,7 @@ and member x.IsValueType = match x with - | TTyconClass | TTyconInterface | TTyconDelegate _ -> false + | TTyconClass | TTyconInterface | TTyconDelegate _ -> false | TTyconStruct | TTyconEnum -> true and @@ -1524,7 +1524,7 @@ and fsobjmodel_rfields: TyconRecdFields } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TyconObjModelData(...)" @@ -1550,7 +1550,7 @@ and member x.TrueInstanceFieldsAsList = x.AllFieldsAsList |> List.filter (fun f -> not f.IsStatic && not f.IsCompilerGenerated) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TyconRecdFields(...)" @@ -1569,7 +1569,7 @@ and member x.UnionCasesAsList = x.CasesByIndex |> Array.toList [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TyconUnionCases(...)" @@ -1585,7 +1585,7 @@ and member x.UnionCasesAsList = x.CasesTable.CasesByIndex |> Array.toList [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TyconUnionData(...)" @@ -1649,7 +1649,7 @@ and member uc.IsNullary = (uc.FieldTable.FieldsByIndex.Length = 0) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "UnionCase(" + x.DisplayName + ")" @@ -1756,20 +1756,20 @@ and /// The default initialization info, for static literals member v.LiteralValue = - match v.rfield_const with + match v.rfield_const with | None -> None | Some Const.Zero -> None | Some k -> Some k /// Indicates if the field is zero-initialized member v.IsZeroInit = - match v.rfield_const with + match v.rfield_const with | None -> false | Some Const.Zero -> true | _ -> false [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = x.Name @@ -1790,7 +1790,7 @@ and // %+A formatting is used, so this is not needed //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -1865,35 +1865,35 @@ and [] member mtyp.ActivePatternElemRefLookupTable = activePatternElemRefCache /// Get a list of types defined within this module, namespace or type. - member mtyp.TypeDefinitions = entities |> Seq.filter (fun x -> not x.IsExceptionDecl && not x.IsModuleOrNamespace) |> Seq.toList + member mtyp.TypeDefinitions = entities |> Seq.filter (fun x -> not x.IsExceptionDecl && not x.IsModuleOrNamespace) |> Seq.toList /// Get a list of F# exception definitions defined within this module, namespace or type. - member mtyp.ExceptionDefinitions = entities |> Seq.filter (fun x -> x.IsExceptionDecl) |> Seq.toList + member mtyp.ExceptionDefinitions = entities |> Seq.filter (fun x -> x.IsExceptionDecl) |> Seq.toList /// Get a list of module and namespace definitions defined within this module, namespace or type. member mtyp.ModuleAndNamespaceDefinitions = entities |> Seq.filter (fun x -> x.IsModuleOrNamespace) |> Seq.toList /// Get a list of type and exception definitions defined within this module, namespace or type. - member mtyp.TypeAndExceptionDefinitions = entities |> Seq.filter (fun x -> not x.IsModuleOrNamespace) |> Seq.toList + member mtyp.TypeAndExceptionDefinitions = entities |> Seq.filter (fun x -> not x.IsModuleOrNamespace) |> Seq.toList /// Get a table of types defined within this module, namespace or type. The /// table is indexed by both name and generic arity. This means that for generic /// 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 cacheOptRef tyconsByMangledNameCache (fun () -> - List.foldBack addTyconByMangledName mtyp.TypeAndExceptionDefinitions Map.empty) + List.foldBack addTyconByMangledName mtyp.TypeAndExceptionDefinitions Map.empty) /// Get a table of entities indexed by both logical and compiled names member mtyp.AllEntitiesByCompiledAndLogicalMangledNames: NameMap = @@ -1905,12 +1905,12 @@ and [] else NameMap.add name2 x tab cacheOptRef allEntitiesByMangledNameCache (fun () -> - QueueList.foldBack addEntityByMangledName entities Map.empty) + 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 - QueueList.foldBack addEntityByMangledName entities Map.empty + 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). @@ -1958,7 +1958,7 @@ and [] member mtyp.ExceptionDefinitionsByDemangledName = let add (tycon: Tycon) acc = NameMap.add tycon.LogicalName tycon acc cacheOptRef exconsByDemangledNameCache (fun () -> - List.foldBack add mtyp.ExceptionDefinitions Map.empty) + 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 = @@ -1967,10 +1967,10 @@ and [] NameMap.add entity.DemangledModuleOrNamespaceName entity acc else acc cacheOptRef modulesByDemangledNameCache (fun () -> - QueueList.foldBack add entities Map.empty) + QueueList.foldBack add entities Map.empty) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "ModuleOrNamespaceType(...)" @@ -2099,7 +2099,7 @@ and | TAccess of CompilationPath list [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "Accessibility(...)" @@ -2122,7 +2122,7 @@ and } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override __.ToString() = sprintf "TyparOptionalData(...)" @@ -2156,22 +2156,22 @@ and mutable typar_opt_data: TyparOptionalData option } /// The name of the type parameter - member x.Name = x.typar_id.idText + member x.Name = x.typar_id.idText /// The range of the identifier for the type parameter definition - member x.Range = x.typar_id.idRange + member x.Range = x.typar_id.idRange /// The identifier for a type parameter definition - member x.Id = x.typar_id + member x.Id = x.typar_id /// The unique stamp of the type parameter - member x.Stamp = x.typar_stamp + member x.Stamp = x.typar_stamp /// The inferred equivalence for the type inference variable, if any. - member x.Solution = x.typar_solution + member x.Solution = x.typar_solution /// The inferred constraints for the type inference variable, if any - member x.Constraints = + member x.Constraints = match x.typar_opt_data with | Some optData -> optData.typar_constraints | _ -> [] @@ -2181,10 +2181,10 @@ and /// Indicates if the type variable can be solved or given new constraints. The status of a type variable /// generally always evolves towards being either rigid or solved. - member x.Rigidity = x.typar_flags.Rigidity + member x.Rigidity = x.typar_flags.Rigidity /// Indicates if a type parameter is needed at runtime and may not be eliminated - member x.DynamicReq = x.typar_flags.DynamicReq + member x.DynamicReq = x.typar_flags.DynamicReq /// Indicates that whether or not a generic type definition satisfies the equality constraint is dependent on whether this type variable satisfies the equality constraint. member x.EqualityConditionalOn = x.typar_flags.EqualityConditionalOn @@ -2193,30 +2193,30 @@ and member x.ComparisonConditionalOn = x.typar_flags.ComparisonConditionalOn /// Indicates if the type variable has a static "head type" requirement, i.e. ^a variables used in FSharp.Core and member constraints. - member x.StaticReq = x.typar_flags.StaticReq + member x.StaticReq = x.typar_flags.StaticReq /// Indicates if the type inference variable was generated after an error when type checking expressions or patterns - member x.IsFromError = x.typar_flags.IsFromError + member x.IsFromError = x.typar_flags.IsFromError /// Indicates that whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) - member x.IsCompatFlex = x.typar_flags.IsCompatFlex + member x.IsCompatFlex = x.typar_flags.IsCompatFlex /// Set whether this type parameter is a compat-flex type parameter (i.e. where "expr :> tp" only emits an optional warning) - member x.SetIsCompatFlex(b) = x.typar_flags <- x.typar_flags.WithCompatFlex(b) + member x.SetIsCompatFlex(b) = x.typar_flags <- x.typar_flags.WithCompatFlex(b) /// Indicates whether a type variable can be instantiated by types or units-of-measure. - member x.Kind = x.typar_flags.Kind + member x.Kind = x.typar_flags.Kind /// Indicates whether a type variable is erased in compiled .NET IL code, i.e. whether it is a unit-of-measure variable - member x.IsErased = match x.Kind with TyparKind.Type -> false | _ -> true + member x.IsErased = match x.Kind with TyparKind.Type -> false | _ -> true /// The declared attributes of the type parameter. Empty for type inference variables and parameters from .NET - member x.Attribs = + member x.Attribs = match x.typar_opt_data with | Some optData -> optData.typar_attribs | _ -> [] - member x.SetAttribs attribs = + member x.SetAttribs attribs = match attribs, x.typar_opt_data with | [], None -> () | [], Some { typar_il_name = None; typar_xmldoc = XmlDoc [||]; typar_constraints = [] } -> @@ -2224,17 +2224,17 @@ and | _, Some optData -> optData.typar_attribs <- attribs | _ -> x.typar_opt_data <- Some { typar_il_name = None; typar_xmldoc = XmlDoc.Empty; typar_constraints = []; typar_attribs = attribs } - member x.XmlDoc = + member x.XmlDoc = match x.typar_opt_data with | Some optData -> optData.typar_xmldoc | _ -> XmlDoc.Empty - member x.ILName = + member x.ILName = match x.typar_opt_data with | Some optData -> optData.typar_il_name | _ -> None - member x.SetILName il_name = + member x.SetILName il_name = match x.typar_opt_data with | Some optData -> optData.typar_il_name <- il_name | _ -> x.typar_opt_data <- Some { typar_il_name = il_name; typar_xmldoc = XmlDoc.Empty; typar_constraints = []; typar_attribs = [] } @@ -2253,7 +2253,7 @@ and /// Creates a type variable that contains empty data, and is not yet linked. Only used during unpickling of F# metadata. - static member NewUnlinked() : Typar = + static member NewUnlinked() : Typar = { typar_id = Unchecked.defaultof<_> typar_flags = Unchecked.defaultof<_> typar_stamp = -1L @@ -2299,25 +2299,25 @@ and member x.SetIdent id = x.typar_id <- id /// Sets the rigidity of a type variable - member x.SetRigidity b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, b, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn) + member x.SetRigidity b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, b, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn) /// Sets whether a type variable is compiler generated - member x.SetCompilerGenerated b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, b, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn) + member x.SetCompilerGenerated b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, b, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn) /// Sets whether a type variable has a static requirement - member x.SetStaticReq b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, b, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn) + member x.SetStaticReq b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, b, flags.DynamicReq, flags.EqualityConditionalOn, flags.ComparisonConditionalOn) /// Sets whether a type variable is required at runtime - member x.SetDynamicReq b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, b , flags.EqualityConditionalOn, flags.ComparisonConditionalOn) + member x.SetDynamicReq b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, b, flags.EqualityConditionalOn, flags.ComparisonConditionalOn) /// Sets whether the equality constraint of a type definition depends on this type variable - member x.SetEqualityDependsOn b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, b , flags.ComparisonConditionalOn) + member x.SetEqualityDependsOn b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, b, flags.ComparisonConditionalOn) /// Sets whether the comparison constraint of a type definition depends on this type variable member x.SetComparisonDependsOn b = let flags = x.typar_flags in x.typar_flags <- TyparFlags(flags.Kind, flags.Rigidity, flags.IsFromError, flags.IsCompilerGenerated, flags.StaticReq, flags.DynamicReq, flags.EqualityConditionalOn, b) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = x.Name @@ -2325,13 +2325,13 @@ and [] TyparConstraint = /// Indicates a constraint that a type is a subtype of the given type - | CoercesTo of TType * range + | CoercesTo of TType * range /// Indicates a default value for an inference type variable should it be neither generalized nor solved - | DefaultsTo of int * TType * range + | DefaultsTo of int * TType * range /// Indicates a constraint that a type has a 'null' value - | SupportsNull of range + | SupportsNull of range /// Indicates a constraint that a type has a member with the given signature | MayResolveMember of TraitConstraintInfo * range @@ -2339,35 +2339,35 @@ and /// Indicates a constraint that a type is a non-Nullable value type /// These are part of .NET's model of generic constraints, and in order to /// generate verifiable code we must attach them to F# generalized type variables as well. - | IsNonNullableStruct of range + | IsNonNullableStruct of range /// Indicates a constraint that a type is a reference type - | IsReferenceType of range + | IsReferenceType of range /// Indicates a constraint that a type is a simple choice between one of the given ground types. Only arises from 'printf' format strings. See format.fs - | SimpleChoice of TTypes * range + | SimpleChoice of TTypes * range /// Indicates a constraint that a type has a parameterless constructor | RequiresDefaultConstructor of range /// Indicates a constraint that a type is an enum with the given underlying - | IsEnum of TType * range + | IsEnum of TType * range /// Indicates a constraint that a type implements IComparable, with special rules for some known structural container types - | SupportsComparison of range + | SupportsComparison of range /// Indicates a constraint that a type does not have the Equality(false) attribute, or is not a structural type with this attribute, with special rules for some known structural container types - | SupportsEquality of range + | SupportsEquality of range /// Indicates a constraint that a type is a delegate from the given tuple of args to the given return type - | IsDelegate of TType * TType * range + | IsDelegate of TType * TType * range /// Indicates a constraint that a type is .NET unmanaged type - | IsUnmanaged of range + | IsUnmanaged of range // %+A formatting is used, so this is not needed //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -2394,7 +2394,7 @@ and and set v = (let (TTrait(_, _, _, _, _, sln)) = x in sln.Value <- v) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TTrait(" + x.MemberName + ")" @@ -2406,16 +2406,16 @@ and /// FSMethSln(ty, vref, minst) /// /// Indicates a trait is solved by an F# method. - /// ty -- the type and its instantiation - /// vref -- the method that solves the trait constraint + /// ty -- the type and its instantiation + /// vref -- the method that solves the trait constraint /// minst -- the generic method instantiation | FSMethSln of TType * ValRef * TypeInst /// FSRecdFieldSln(tinst, rfref, isSetProp) /// /// Indicates a trait is solved by an F# record field. - /// tinst -- the instantiation of the declaring type - /// rfref -- the reference to the record field + /// tinst -- the instantiation of the declaring type + /// rfref -- the reference to the record field /// isSetProp -- indicates if this is a set of a record field | FSRecdFieldSln of TypeInst * RecdFieldRef * bool @@ -2425,10 +2425,10 @@ and /// ILMethSln(ty, extOpt, ilMethodRef, minst) /// /// Indicates a trait is solved by a .NET method. - /// ty -- the type and its instantiation - /// extOpt -- information about an extension member, if any + /// ty -- the type and its instantiation + /// extOpt -- information about an extension member, if any /// ilMethodRef -- the method that solves the trait constraint - /// minst -- the generic method instantiation + /// minst -- the generic method instantiation | ILMethSln of TType * ILTypeRef option * ILMethodRef * TypeInst /// ClosedExprSln(expr) @@ -2441,7 +2441,7 @@ and // %+A formatting is used, so this is not needed //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -2461,7 +2461,7 @@ and [] TotalArgCount: int } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "ValLinkagePartialKey(" + x.LogicalName + ")" @@ -2478,7 +2478,7 @@ and member x.TypeForLinkage = typeForLinkage [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "ValLinkageFullKey(" + partialKey.LogicalName + ")" @@ -2536,7 +2536,7 @@ and } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "ValOptionalData(...)" @@ -2574,13 +2574,13 @@ and [] val_attribs = [] } /// Range of the definition (implementation) of the value, used by Visual Studio - member x.DefinitionRange = + member x.DefinitionRange = match x.val_opt_data with | Some { val_other_range = Some(m, true) } -> m | _ -> x.val_range /// Range of the definition (signature) of the value, used by Visual Studio - member x.SigRange = + member x.SigRange = match x.val_opt_data with | Some { val_other_range = Some(m, false) } -> m | _ -> x.val_range @@ -2596,19 +2596,19 @@ and [] /// May be a type variable or type containing type variables during type inference. // // Note: this data is mutated during inference by adjustAllUsesOfRecValue when we replace the inferred type with a schema. - member x.Type = x.val_type + member x.Type = x.val_type /// How visible is this value, function or member? - member x.Accessibility = + member x.Accessibility = match x.val_opt_data with | Some optData -> optData.val_access - | _ -> TAccess [] + | _ -> TAccess [] /// The value of a value or member marked with [] - member x.LiteralValue = + member x.LiteralValue = match x.val_opt_data with | Some optData -> optData.val_const - | _ -> None + | _ -> None /// Records the "extra information" for a value compiled as a method. /// @@ -2628,9 +2628,9 @@ and [] member x.ValReprInfo: ValReprInfo option = match x.val_opt_data with | Some optData -> optData.val_repr_info - | _ -> None + | _ -> None - member x.Id = ident(x.LogicalName, x.Range) + member x.Id = ident(x.LogicalName, x.Range) /// Is this represented as a "top level" static binding (i.e. a static field, static member, /// instance member), rather than an "inner" binding that may result in a closure. @@ -2640,7 +2640,7 @@ and [] /// binding to be IsCompiledAsTopLevel. Second, even immediately after type checking we expect /// some non-module, non-member bindings to be marked IsCompiledAsTopLevel, e.g. 'y' in /// 'let x = let y = 1 in y + y' (NOTE: check this, don't take it as gospel) - member x.IsCompiledAsTopLevel = x.ValReprInfo.IsSome + member x.IsCompiledAsTopLevel = x.ValReprInfo.IsSome /// The partial information used to index the methods of all those in a ModuleOrNamespace. member x.GetLinkagePartialKey() : ValLinkagePartialKey = @@ -2657,37 +2657,37 @@ and [] ValLinkageFullKey(key, (if x.IsMember then Some x.Type else None)) /// Is this a member definition or module definition? - member x.IsMemberOrModuleBinding = x.val_flags.IsMemberOrModuleBinding + member x.IsMemberOrModuleBinding = x.val_flags.IsMemberOrModuleBinding /// Indicates if this is an F#-defined extension member - member x.IsExtensionMember = x.val_flags.IsExtensionMember + member x.IsExtensionMember = x.val_flags.IsExtensionMember /// The quotation expression associated with a value given the [] tag - member x.ReflectedDefinition = + member x.ReflectedDefinition = match x.val_opt_data with | Some optData -> optData.val_defn - | _ -> None + | _ -> None /// Is this a member, if so some more data about the member. /// /// Note, the value may still be (a) an extension member or (b) and abstract slot without /// a true body. These cases are often causes of bugs in the compiler. - member x.MemberInfo = + member x.MemberInfo = match x.val_opt_data with | Some optData -> optData.val_member_info - | _ -> None + | _ -> None /// Indicates if this is a member - member x.IsMember = x.MemberInfo.IsSome + member x.IsMember = x.MemberInfo.IsSome /// Indicates if this is a member, excluding extension members - member x.IsIntrinsicMember = x.IsMember && not x.IsExtensionMember + member x.IsIntrinsicMember = x.IsMember && not x.IsExtensionMember /// Indicates if this is an F#-defined value in a module, or an extension member, but excluding compiler generated bindings from optimizations - member x.IsModuleBinding = x.IsMemberOrModuleBinding && not x.IsMember + member x.IsModuleBinding = x.IsMemberOrModuleBinding && not x.IsMember /// Indicates if this is something compiled into a module, i.e. a user-defined value, an extension member or a compiler-generated value - member x.IsCompiledIntoModule = x.IsExtensionMember || x.IsModuleBinding + member x.IsCompiledIntoModule = x.IsExtensionMember || x.IsModuleBinding /// Indicates if this is an F#-defined instance member. /// @@ -2696,25 +2696,25 @@ and [] member x.IsInstanceMember = x.IsMember && x.MemberInfo.Value.MemberFlags.IsInstance /// Indicates if this is an F#-defined 'new' constructor member - member x.IsConstructor = + member x.IsConstructor = match x.MemberInfo with | Some(memberInfo) when not x.IsExtensionMember && (memberInfo.MemberFlags.MemberKind = MemberKind.Constructor) -> true | _ -> false /// Indicates if this is a compiler-generated class constructor member - member x.IsClassConstructor = + member x.IsClassConstructor = match x.MemberInfo with | Some(memberInfo) when not x.IsExtensionMember && (memberInfo.MemberFlags.MemberKind = MemberKind.ClassConstructor) -> true | _ -> false /// Indicates if this value was a member declared 'override' or an implementation of an interface slot - member x.IsOverrideOrExplicitImpl = + member x.IsOverrideOrExplicitImpl = match x.MemberInfo with | Some(memberInfo) when memberInfo.MemberFlags.IsOverrideOrExplicitImpl -> true | _ -> false /// Indicates if this is declared 'mutable' - member x.IsMutable = (match x.val_flags.MutabilityInfo with Immutable -> false | Mutable -> true) + member x.IsMutable = (match x.val_flags.MutabilityInfo with Immutable -> false | Mutable -> true) /// Indicates if this is inferred to be a method or function that definitely makes no critical tailcalls? member x.MakesNoCriticalTailcalls = x.val_flags.MakesNoCriticalTailcalls @@ -2735,70 +2735,70 @@ and [] member x.PermitsExplicitTypeInstantiation = x.val_flags.PermitsExplicitTypeInstantiation /// Indicates if this is a member generated from the de-sugaring of 'let' function bindings in the implicit class syntax? - member x.IsIncrClassGeneratedMember = x.IsCompilerGenerated && x.val_flags.IsIncrClassSpecialMember + member x.IsIncrClassGeneratedMember = x.IsCompilerGenerated && x.val_flags.IsIncrClassSpecialMember /// Indicates if this is a constructor member generated from the de-sugaring of implicit constructor for a class type? member x.IsIncrClassConstructor = x.IsConstructor && x.val_flags.IsIncrClassSpecialMember /// Get the information about the value used during type inference - member x.RecursiveValInfo = x.val_flags.RecursiveValInfo + member x.RecursiveValInfo = x.val_flags.RecursiveValInfo /// Indicates if this is a 'base' or 'this' value? - member x.BaseOrThisInfo = x.val_flags.BaseOrThisInfo + member x.BaseOrThisInfo = x.val_flags.BaseOrThisInfo // Indicates if this value was declared to be a type function, e.g. "let f<'a> = typeof<'a>" - member x.IsTypeFunction = x.val_flags.IsTypeFunction + member x.IsTypeFunction = x.val_flags.IsTypeFunction /// Get the inline declaration on the value - member x.InlineInfo = x.val_flags.InlineInfo + member x.InlineInfo = x.val_flags.InlineInfo /// Indicates whether the inline declaration for the value indicate that the value must be inlined? - member x.MustInline = x.InlineInfo.MustInline + member x.MustInline = x.InlineInfo.MustInline /// Indicates whether this value was generated by the compiler. /// /// Note: this is true for the overrides generated by hash/compare augmentations - member x.IsCompilerGenerated = x.val_flags.IsCompilerGenerated + member x.IsCompilerGenerated = x.val_flags.IsCompilerGenerated /// Get the declared attributes for the value - member x.Attribs = + member x.Attribs = match x.val_opt_data with | Some optData -> optData.val_attribs - | _ -> [] + | _ -> [] /// Get the declared documentation for the value - member x.XmlDoc = + member x.XmlDoc = match x.val_opt_data with | Some optData -> optData.val_xmldoc - | _ -> XmlDoc.Empty + | _ -> XmlDoc.Empty ///Get the signature for the value's XML documentation member x.XmlDocSig with get() = match x.val_opt_data with | Some optData -> optData.val_xmldocsig - | _ -> String.Empty + | _ -> String.Empty and set(v) = match x.val_opt_data with | Some optData -> optData.val_xmldocsig <- v - | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_xmldocsig = v } + | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_xmldocsig = v } /// The parent type or module, if any (None for expression bindings and parameters) - member x.DeclaringEntity = + member x.DeclaringEntity = match x.val_opt_data with | Some optData -> optData.val_declaring_entity - | _ -> ParentNone + | _ -> ParentNone /// Get the actual parent entity for the value (a module or a type), i.e. the entity under which the /// value will appear in compiled code. For extension members this is the module where the extension member /// is declared. member x.TopValDeclaringEntity = - match x.DeclaringEntity with + match x.DeclaringEntity with | Parent tcref -> tcref | ParentNone -> error(InternalError("TopValDeclaringEntity: does not have a parent", x.Range)) member x.HasDeclaringEntity = - match x.DeclaringEntity with + match x.DeclaringEntity with | Parent _ -> true | ParentNone -> false @@ -2833,8 +2833,8 @@ and [] // - in check.fs: as a boolean to detect public values for saving quotations // - in ilxgen.fs: as a boolean to detect public values for saving quotations // - in MakeExportRemapping, to build non-local references for values - member x.PublicPath = - match x.DeclaringEntity with + member x.PublicPath = + match x.DeclaringEntity with | Parent eref -> match eref.PublicPath with | None -> None @@ -2881,7 +2881,7 @@ and [] member x.ValCompiledName = match x.val_opt_data with | Some optData -> optData.val_compiled_name - | _ -> None + | _ -> None /// The name of the method in compiled code (with some exceptions where ilxgen.fs decides not to use a method impl) /// - If this is a property then this is 'get_Foo' or 'set_Foo' @@ -2907,7 +2907,7 @@ and [] // let dt = System.DateTime.Now - System.DateTime.Now // IsMemberOrModuleBinding = false, IsCompiledAsTopLevel = true, IsMember = false, CompilerGenerated=true // // However we don't need this for CompilerGenerated members such as the implementations of IComparable - if x.IsCompiledAsTopLevel && not x.IsMember && (x.IsCompilerGenerated || not x.IsMemberOrModuleBinding) then + if x.IsCompiledAsTopLevel && not x.IsMember && (x.IsCompilerGenerated || not x.IsMemberOrModuleBinding) then globalStableNameGenerator.GetUniqueCompilerGeneratedName(givenName, x.Range, x.Stamp) else givenName @@ -2916,7 +2916,7 @@ and [] /// - If this is a property then this is 'Foo' /// - If this is an implementation of an abstract slot then this is the name of the property implemented by the abstract slot member x.PropertyName = - let logicalName = x.LogicalName + let logicalName = x.LogicalName ChopPropertyName logicalName /// The name of the method. @@ -2941,58 +2941,58 @@ and [] member x.DisplayName = DemangleOperatorName x.CoreDisplayName - member x.SetValRec b = x.val_flags <- x.val_flags.WithRecursiveValInfo b + member x.SetValRec b = x.val_flags <- x.val_flags.WithRecursiveValInfo b - member x.SetIsMemberOrModuleBinding() = x.val_flags <- x.val_flags.WithIsMemberOrModuleBinding + member x.SetIsMemberOrModuleBinding() = x.val_flags <- x.val_flags.WithIsMemberOrModuleBinding - member x.SetMakesNoCriticalTailcalls() = x.val_flags <- x.val_flags.WithMakesNoCriticalTailcalls + member x.SetMakesNoCriticalTailcalls() = x.val_flags <- x.val_flags.WithMakesNoCriticalTailcalls - member x.SetHasBeenReferenced() = x.val_flags <- x.val_flags.WithHasBeenReferenced + member x.SetHasBeenReferenced() = x.val_flags <- x.val_flags.WithHasBeenReferenced member x.SetIsCompiledAsStaticPropertyWithoutField() = x.val_flags <- x.val_flags.WithIsCompiledAsStaticPropertyWithoutField - member x.SetIsFixed() = x.val_flags <- x.val_flags.WithIsFixed + member x.SetIsFixed() = x.val_flags <- x.val_flags.WithIsFixed - member x.SetValReprInfo info = + member x.SetValReprInfo info = match x.val_opt_data with | Some optData -> optData.val_repr_info <- info - | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_repr_info = info } + | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_repr_info = info } - member x.SetType ty = x.val_type <- ty + member x.SetType ty = x.val_type <- ty - member x.SetOtherRange m = + member x.SetOtherRange m = match x.val_opt_data with | Some optData -> optData.val_other_range <- Some m - | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_other_range = Some m } + | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_other_range = Some m } - member x.SetDeclaringEntity parent = + member x.SetDeclaringEntity parent = match x.val_opt_data with | Some optData -> optData.val_declaring_entity <- parent - | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_declaring_entity = parent } + | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_declaring_entity = parent } - member x.SetAttribs attribs = + member x.SetAttribs attribs = match x.val_opt_data with | Some optData -> optData.val_attribs <- attribs - | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_attribs = attribs } + | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_attribs = attribs } - member x.SetMemberInfo member_info = + member x.SetMemberInfo member_info = match x.val_opt_data with | Some optData -> optData.val_member_info <- Some member_info - | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_member_info = Some member_info } + | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_member_info = Some member_info } - member x.SetValDefn val_defn = + member x.SetValDefn val_defn = match x.val_opt_data with | Some optData -> optData.val_defn <- Some val_defn - | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_defn = Some val_defn } + | _ -> x.val_opt_data <- Some { Val.NewEmptyValOptData() with val_defn = Some val_defn } /// Create a new value with empty, unlinked data. Only used during unpickling of F# metadata. - static member NewUnlinked() : Val = - { val_logical_name = Unchecked.defaultof<_> - val_range = Unchecked.defaultof<_> - val_type = Unchecked.defaultof<_> - val_stamp = Unchecked.defaultof<_> - val_flags = Unchecked.defaultof<_> - val_opt_data = Unchecked.defaultof<_> } + static member NewUnlinked() : Val = + { val_logical_name = Unchecked.defaultof<_> + val_range = Unchecked.defaultof<_> + val_type = Unchecked.defaultof<_> + val_stamp = Unchecked.defaultof<_> + val_flags = Unchecked.defaultof<_> + val_opt_data = Unchecked.defaultof<_> } /// Create a new value with the given backing data. Only used during unpickling of F# metadata. @@ -3003,11 +3003,11 @@ and [] /// Set all the data on a value member x.SetData (tg: ValData) = - x.val_logical_name <- tg.val_logical_name - x.val_range <- tg.val_range - x.val_type <- tg.val_type - x.val_stamp <- tg.val_stamp - x.val_flags <- tg.val_flags + x.val_logical_name <- tg.val_logical_name + x.val_range <- tg.val_range + x.val_type <- tg.val_type + x.val_stamp <- tg.val_stamp + x.val_flags <- tg.val_flags match tg.val_opt_data with | Some tg -> x.val_opt_data <- @@ -3028,7 +3028,7 @@ and [] member x.IsLinked = match box x.val_logical_name with null -> false | _ -> true [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = x.LogicalName @@ -3043,13 +3043,13 @@ and /// Updated with the full implemented slotsig after interface implementation relation is checked mutable ImplementedSlotSigs: SlotSig list - /// Gets updated with 'true' if an abstract slot is implemented in the file being typechecked. Internal only. + /// Gets updated with 'true' if an abstract slot is implemented in the file being typechecked. Internal only. mutable IsImplemented: bool MemberFlags: MemberFlags } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "ValMemberInfo(...)" @@ -3077,18 +3077,18 @@ and and [] - ValPublicPath = + ValPublicPath = | ValPubPath of PublicPath * ValLinkageFullKey [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override __.ToString() = sprintf "ValPubPath(...)" /// Index into the namespace/module structure of a particular CCU and [] - NonLocalEntityRef = + NonLocalEntityRef = | NonLocalEntityRef of CcuThunk * string[] /// Try to find the entity corresponding to the given path in the given CCU @@ -3149,7 +3149,7 @@ and assert (j >= 0) assert (j <= path.Length - 1) let matched = - [ for resolver in resolvers do + [ for resolver in resolvers do let moduleOrNamespace = if j = 0 then null else path.[0..j-1] let typename = path.[j] let resolution = ExtensionTyping.TryLinkProvidedType(resolver, moduleOrNamespace, typename, m) @@ -3162,7 +3162,7 @@ and // Inject namespaces until we're an position j, and then inject the type. // Note: this is similar to code in CompileOps.fs let rec injectNamespacesFromIToJ (entity: Entity) k = - if k = j then + if k = j then let newEntity = Construct.NewProvidedTycon(resolutionEnvironment, st, ccu.ImportProvidedType, false, m) entity.ModuleOrNamespaceType.AddProvidedTypeEntity(newEntity) newEntity @@ -3202,7 +3202,7 @@ and if ccu.IsUnresolvedReference then ValueNone else - match NonLocalEntityRef.TryDerefEntityPath(ccu, path, 0, ccu.Contents) with + match NonLocalEntityRef.TryDerefEntityPath(ccu, path, 0, ccu.Contents) with | ValueSome _ as r -> r | ValueNone -> // OK, the lookup failed. Check if we can redirect through a type forwarder on this assembly. @@ -3256,7 +3256,7 @@ and nleref.Deref.ModuleOrNamespaceType [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = x.DisplayName @@ -3379,79 +3379,79 @@ and member x.TypeReprInfo = x.Deref.TypeReprInfo /// The information about the r.h.s. of an F# exception definition, if any. - member x.ExceptionInfo = x.Deref.ExceptionInfo + member x.ExceptionInfo = x.Deref.ExceptionInfo /// Indicates if the entity represents an F# exception declaration. - member x.IsExceptionDecl = x.Deref.IsExceptionDecl + member x.IsExceptionDecl = x.Deref.IsExceptionDecl /// Get the type parameters for an entity that is a type declaration, otherwise return the empty list. /// /// Lazy because it may read metadata, must provide a context "range" in case error occurs reading metadata. - member x.Typars m = x.Deref.Typars m + member x.Typars m = x.Deref.Typars m /// Get the type parameters for an entity that is a type declaration, otherwise return the empty list. - member x.TyparsNoRange = x.Deref.TyparsNoRange + member x.TyparsNoRange = x.Deref.TyparsNoRange /// Indicates if this entity is an F# type abbreviation definition - member x.TypeAbbrev = x.Deref.TypeAbbrev + member x.TypeAbbrev = x.Deref.TypeAbbrev /// Indicates if this entity is an F# type abbreviation definition - member x.IsTypeAbbrev = x.Deref.IsTypeAbbrev + member x.IsTypeAbbrev = x.Deref.IsTypeAbbrev /// Get the value representing the accessibility of the r.h.s. of an F# type definition. member x.TypeReprAccessibility = x.Deref.TypeReprAccessibility /// Get the cache of the compiled ILTypeRef representation of this module or type. - member x.CompiledReprCache = x.Deref.CompiledReprCache + 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 /// Get the value representing the accessibility of an F# type definition or module. - member x.Accessibility = x.Deref.Accessibility + member x.Accessibility = x.Deref.Accessibility /// Indicates the type prefers the "tycon" syntax for display etc. - member x.IsPrefixDisplay = x.Deref.IsPrefixDisplay + member x.IsPrefixDisplay = x.Deref.IsPrefixDisplay /// Indicates the "tycon blob" is actually a module - member x.IsModuleOrNamespace = x.Deref.IsModuleOrNamespace + member x.IsModuleOrNamespace = x.Deref.IsModuleOrNamespace /// Indicates if the entity is a namespace - member x.IsNamespace = x.Deref.IsNamespace + member x.IsNamespace = x.Deref.IsNamespace /// Indicates if the entity is an F# module definition - member x.IsModule = x.Deref.IsModule + member x.IsModule = x.Deref.IsModule /// Get a blob of data indicating how this type is nested inside other namespaces, modules and types. - member x.CompilationPathOpt = x.Deref.CompilationPathOpt + member x.CompilationPathOpt = x.Deref.CompilationPathOpt #if !NO_EXTENSIONTYPING /// Indicates if the entity is a provided namespace fragment - member x.IsProvided = x.Deref.IsProvided + member x.IsProvided = x.Deref.IsProvided /// Indicates if the entity is a provided namespace fragment - member x.IsProvidedNamespace = x.Deref.IsProvidedNamespace + member x.IsProvidedNamespace = x.Deref.IsProvidedNamespace /// Indicates if the entity is an erased provided type definition - member x.IsProvidedErasedTycon = x.Deref.IsProvidedErasedTycon + member x.IsProvidedErasedTycon = x.Deref.IsProvidedErasedTycon /// Indicates if the entity is an erased provided type definition that incorporates a static instantiation (and therefore in some sense compiler generated) - member x.IsStaticInstantiationTycon = x.Deref.IsStaticInstantiationTycon + member x.IsStaticInstantiationTycon = x.Deref.IsStaticInstantiationTycon /// Indicates if the entity is a generated provided type definition, i.e. not erased. member x.IsProvidedGeneratedTycon = x.Deref.IsProvidedGeneratedTycon #endif /// Get a blob of data indicating how this type is nested inside other namespaces, modules and types. - member x.CompilationPath = x.Deref.CompilationPath + member x.CompilationPath = x.Deref.CompilationPath /// Get a table of fields for all the F#-defined record, struct and class fields in this type definition, including /// static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. - member x.AllFieldTable = x.Deref.AllFieldTable + member x.AllFieldTable = x.Deref.AllFieldTable /// Get an array of fields for all the F#-defined record, struct and class fields in this type definition, including /// static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. - member x.AllFieldsArray = x.Deref.AllFieldsArray + member x.AllFieldsArray = x.Deref.AllFieldsArray /// Get a list of fields for all the F#-defined record, struct and class fields in this type definition, including /// static fields, 'val' declarations and hidden fields from the compilation of implicit class constructions. @@ -3471,28 +3471,28 @@ and member x.AllInstanceFieldsAsList = x.Deref.AllInstanceFieldsAsList /// Get a field by index in definition order - member x.GetFieldByIndex n = x.Deref.GetFieldByIndex n + member x.GetFieldByIndex n = x.Deref.GetFieldByIndex n /// Get a field by name. - member x.GetFieldByName n = x.Deref.GetFieldByName n + member x.GetFieldByName n = x.Deref.GetFieldByName n /// Get the union cases and other union-type information for a type, if any - member x.UnionTypeInfo = x.Deref.UnionTypeInfo + member x.UnionTypeInfo = x.Deref.UnionTypeInfo /// Get the union cases for a type, if any - member x.UnionCasesArray = x.Deref.UnionCasesArray + member x.UnionCasesArray = x.Deref.UnionCasesArray /// Get the union cases for a type, if any, as a list - member x.UnionCasesAsList = x.Deref.UnionCasesAsList + member x.UnionCasesAsList = x.Deref.UnionCasesAsList /// Get a union case of a type by name - member x.GetUnionCaseByName n = x.Deref.GetUnionCaseByName n + member x.GetUnionCaseByName n = x.Deref.GetUnionCaseByName n /// Get the blob of information associated with an F# object-model type definition, i.e. class, interface, struct etc. member x.FSharpObjectModelTypeInfo = x.Deref.FSharpObjectModelTypeInfo /// Gets the immediate interface definitions of an F# type definition. Further interfaces may be supported through class and interface inheritance. - member x.ImmediateInterfacesOfFSharpTycon = x.Deref.ImmediateInterfacesOfFSharpTycon + member x.ImmediateInterfacesOfFSharpTycon = x.Deref.ImmediateInterfacesOfFSharpTycon /// Gets the immediate interface types of an F# type definition. Further interfaces may be supported through class and interface inheritance. member x.ImmediateInterfaceTypesOfFSharpTycon = x.Deref.ImmediateInterfaceTypesOfFSharpTycon @@ -3505,19 +3505,19 @@ and /// Note: result is a indexed table, and for each name the results are in reverse declaration order member x.MembersOfFSharpTyconByName = x.Deref.MembersOfFSharpTyconByName - /// Indicates if this is a struct or enum type definition , i.e. a value type definition - member x.IsStructOrEnumTycon = x.Deref.IsStructOrEnumTycon + /// Indicates if this is a struct or enum type definition, i.e. a value type definition + member x.IsStructOrEnumTycon = x.Deref.IsStructOrEnumTycon /// Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll which uses /// an assembly-code representation for the type, e.g. the primitive array type constructor. - member x.IsAsmReprTycon = x.Deref.IsAsmReprTycon + member x.IsAsmReprTycon = x.Deref.IsAsmReprTycon /// Indicates if this is an F# type definition which is one of the special types in FSharp.Core.dll like 'float<_>' which /// defines a measure type with a relation to an existing non-measure type as a representation. - member x.IsMeasureableReprTycon = x.Deref.IsMeasureableReprTycon + member x.IsMeasureableReprTycon = x.Deref.IsMeasureableReprTycon /// Indicates if the entity is erased, either a measure definition, or an erased provided type definition - member x.IsErased = x.Deref.IsErased + member x.IsErased = x.Deref.IsErased /// Gets any implicit hash/equals (with comparer argument) methods added to an F# record, union or struct type definition. member x.GeneratedHashAndEqualsWithComparerValues = x.Deref.GeneratedHashAndEqualsWithComparerValues @@ -3532,60 +3532,60 @@ and member x.GeneratedHashAndEqualsValues = x.Deref.GeneratedHashAndEqualsValues /// Indicate if this is a type definition backed by Abstract IL metadata. - member x.IsILTycon = x.Deref.IsILTycon + member x.IsILTycon = x.Deref.IsILTycon /// Get the Abstract IL scope, nesting and metadata for this /// type definition, assuming it is backed by Abstract IL metadata. - member x.ILTyconInfo = x.Deref.ILTyconInfo + member x.ILTyconInfo = x.Deref.ILTyconInfo /// Get the Abstract IL metadata for this type definition, assuming it is backed by Abstract IL metadata. - member x.ILTyconRawMetadata = x.Deref.ILTyconRawMetadata + member x.ILTyconRawMetadata = x.Deref.ILTyconRawMetadata /// Indicate if this is a type whose r.h.s. is known to be a union type definition. - member x.IsUnionTycon = x.Deref.IsUnionTycon + member x.IsUnionTycon = x.Deref.IsUnionTycon /// Indicates if this is an F# type definition whose r.h.s. is known to be a record type definition. - member x.IsRecordTycon = x.Deref.IsRecordTycon + member x.IsRecordTycon = x.Deref.IsRecordTycon /// Indicates if this is an F# type definition whose r.h.s. is known to be some kind of F# object model definition member x.IsFSharpObjectModelTycon = x.Deref.IsFSharpObjectModelTycon /// The on-demand analysis about whether the entity has the IsByRefLike attribute - member x.TryIsByRefLike = x.Deref.TryIsByRefLike + member x.TryIsByRefLike = x.Deref.TryIsByRefLike /// Set the on-demand analysis about whether the entity has the IsByRefLike attribute - member x.SetIsByRefLike b = x.Deref.SetIsByRefLike b + member x.SetIsByRefLike b = x.Deref.SetIsByRefLike b /// The on-demand analysis about whether the entity has the IsByRefLike attribute - member x.TryIsReadOnly = x.Deref.TryIsReadOnly + member x.TryIsReadOnly = x.Deref.TryIsReadOnly /// Set the on-demand analysis about whether the entity has the IsReadOnly attribute or is otherwise determined to be a readonly struct - member x.SetIsReadOnly b = x.Deref.SetIsReadOnly b + member x.SetIsReadOnly b = x.Deref.SetIsReadOnly b /// Indicates if this is an F# type definition whose r.h.s. definition is unknown (i.e. a traditional ML 'abstract' type in a signature, /// which in F# is called a 'unknown representation' type). - member x.IsHiddenReprTycon = x.Deref.IsHiddenReprTycon + member x.IsHiddenReprTycon = x.Deref.IsHiddenReprTycon /// Indicates if this is an F#-defined interface type definition - member x.IsFSharpInterfaceTycon = x.Deref.IsFSharpInterfaceTycon + member x.IsFSharpInterfaceTycon = x.Deref.IsFSharpInterfaceTycon /// Indicates if this is an F#-defined delegate type definition - member x.IsFSharpDelegateTycon = x.Deref.IsFSharpDelegateTycon + member x.IsFSharpDelegateTycon = x.Deref.IsFSharpDelegateTycon /// Indicates if this is an F#-defined enum type definition - member x.IsFSharpEnumTycon = x.Deref.IsFSharpEnumTycon + member x.IsFSharpEnumTycon = x.Deref.IsFSharpEnumTycon /// Indicates if this is a .NET-defined enum type definition - member x.IsILEnumTycon = x.Deref.IsILEnumTycon + member x.IsILEnumTycon = x.Deref.IsILEnumTycon /// Indicates if this is an enum type definition - member x.IsEnumTycon = x.Deref.IsEnumTycon + member x.IsEnumTycon = x.Deref.IsEnumTycon - /// Indicates if this is an F#-defined struct or enum type definition , i.e. a value type definition - member x.IsFSharpStructOrEnumTycon = x.Deref.IsFSharpStructOrEnumTycon + /// Indicates if this is an F#-defined struct or enum type definition, i.e. a value type definition + member x.IsFSharpStructOrEnumTycon = x.Deref.IsFSharpStructOrEnumTycon - /// Indicates if this is a .NET-defined struct or enum type definition , i.e. a value type definition - member x.IsILStructOrEnumTycon = x.Deref.IsILStructOrEnumTycon + /// Indicates if this is a .NET-defined struct or enum type definition, i.e. a value type definition + member x.IsILStructOrEnumTycon = x.Deref.IsILStructOrEnumTycon /// Indicates if we have pre-determined that a type definition has a default constructor. member x.PreEstablishedHasDefaultConstructor = x.Deref.PreEstablishedHasDefaultConstructor @@ -3593,18 +3593,18 @@ and /// Indicates if we have pre-determined that a type definition has a self-referential constructor using 'as x' member x.HasSelfReferentialConstructor = x.Deref.HasSelfReferentialConstructor - member x.UnionCasesAsRefList = x.UnionCasesAsList |> List.map x.MakeNestedUnionCaseRef + member x.UnionCasesAsRefList = x.UnionCasesAsList |> List.map x.MakeNestedUnionCaseRef member x.TrueInstanceFieldsAsRefList = x.TrueInstanceFieldsAsList |> List.map x.MakeNestedRecdFieldRef - member x.AllFieldAsRefList = x.AllFieldsAsList |> List.map x.MakeNestedRecdFieldRef + member x.AllFieldAsRefList = x.AllFieldsAsList |> List.map x.MakeNestedRecdFieldRef - member x.MakeNestedRecdFieldRef (rf: RecdField) = RFRef (x, rf.Name) + member x.MakeNestedRecdFieldRef (rf: RecdField) = RFRef (x, rf.Name) - member x.MakeNestedUnionCaseRef (uc: UnionCase) = UCRef (x, uc.Id.idText) + member x.MakeNestedUnionCaseRef (uc: UnionCase) = UCRef (x, uc.Id.idText) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = if x.IsLocalRef then @@ -3614,9 +3614,9 @@ and /// note: ModuleOrNamespaceRef and TyconRef are type equivalent -and ModuleOrNamespaceRef = EntityRef +and ModuleOrNamespaceRef = EntityRef -and TyconRef = EntityRef +and TyconRef = EntityRef /// References are either local or nonlocal and @@ -3640,7 +3640,7 @@ and if obj.ReferenceEquals(vr.binding, null) then let res = let nlr = vr.nlr - let e = nlr.EnclosingEntity.Deref + let e = nlr.EnclosingEntity.Deref let possible = e.ModuleOrNamespaceType.TryLinkVal(nlr.EnclosingEntity.nlr.Ccu, nlr.ItemKey) match possible with | ValueNone -> error (InternalUndefinedItemRef (FSComp.SR.tastUndefinedItemRefVal, e.DisplayNameWithStaticParameters, nlr.AssemblyName, sprintf "%+A" nlr.ItemKey.PartialKey)) @@ -3665,48 +3665,48 @@ and /// The type of the value. May be a TType_forall for a generic value. /// May be a type variable or type containing type variables during type inference. - member x.Type = x.Deref.Type + member x.Type = x.Deref.Type /// Get the type of the value including any generic type parameters - member x.TypeScheme = x.Deref.TypeScheme + member x.TypeScheme = x.Deref.TypeScheme /// Get the type of the value after removing any generic type parameters - member x.TauType = x.Deref.TauType + member x.TauType = x.Deref.TauType - member x.Typars = x.Deref.Typars + member x.Typars = x.Deref.Typars - member x.LogicalName = x.Deref.LogicalName + member x.LogicalName = x.Deref.LogicalName - member x.DisplayName = x.Deref.DisplayName + member x.DisplayName = x.Deref.DisplayName - member x.CoreDisplayName = x.Deref.CoreDisplayName + member x.CoreDisplayName = x.Deref.CoreDisplayName - member x.Range = x.Deref.Range + member x.Range = x.Deref.Range /// Get the value representing the accessibility of an F# type definition or module. - member x.Accessibility = x.Deref.Accessibility + member x.Accessibility = x.Deref.Accessibility /// The parent type or module, if any (None for expression bindings and parameters) - member x.DeclaringEntity = x.Deref.DeclaringEntity + member x.DeclaringEntity = x.Deref.DeclaringEntity /// Get the apparent parent entity for the value, i.e. the entity under with which the /// value is associated. For extension members this is the nominal type the member extends. /// For other values it is just the actual parent. - member x.ApparentEnclosingEntity = x.Deref.ApparentEnclosingEntity + member x.ApparentEnclosingEntity = x.Deref.ApparentEnclosingEntity - member x.DefinitionRange = x.Deref.DefinitionRange + member x.DefinitionRange = x.Deref.DefinitionRange - member x.SigRange = x.Deref.SigRange + member x.SigRange = x.Deref.SigRange /// The value of a value or member marked with [] - member x.LiteralValue = x.Deref.LiteralValue + member x.LiteralValue = x.Deref.LiteralValue - member x.Id = x.Deref.Id + member x.Id = x.Deref.Id /// Get the name of the value, assuming it is compiled as a property. /// - If this is a property then this is 'Foo' /// - If this is an implementation of an abstract slot then this is the name of the property implemented by the abstract slot - member x.PropertyName = x.Deref.PropertyName + member x.PropertyName = x.Deref.PropertyName /// Indicates whether this value represents a property getter. member x.IsPropertyGetterMethod = @@ -3721,61 +3721,61 @@ and | 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 + member x.Stamp = x.Deref.Stamp /// Is this represented as a "top level" static binding (i.e. a static field, static member, /// instance member), rather than an "inner" binding that may result in a closure. - member x.IsCompiledAsTopLevel = x.Deref.IsCompiledAsTopLevel + member x.IsCompiledAsTopLevel = x.Deref.IsCompiledAsTopLevel /// Indicates if this member is an F#-defined dispatch slot. - member x.IsDispatchSlot = x.Deref.IsDispatchSlot + member x.IsDispatchSlot = x.Deref.IsDispatchSlot /// The name of the method in compiled code (with some exceptions where ilxgen.fs decides not to use a method impl) - member x.CompiledName = x.Deref.CompiledName + member x.CompiledName = x.Deref.CompiledName /// Get the public path to the value, if any? Should be set if and only if /// IsMemberOrModuleBinding is set. - member x.PublicPath = x.Deref.PublicPath + member x.PublicPath = x.Deref.PublicPath /// The quotation expression associated with a value given the [] tag - member x.ReflectedDefinition = x.Deref.ReflectedDefinition + member x.ReflectedDefinition = x.Deref.ReflectedDefinition /// Indicates if this is an F#-defined 'new' constructor member - member x.IsConstructor = x.Deref.IsConstructor + member x.IsConstructor = x.Deref.IsConstructor /// Indicates if this value was a member declared 'override' or an implementation of an interface slot - member x.IsOverrideOrExplicitImpl = x.Deref.IsOverrideOrExplicitImpl + member x.IsOverrideOrExplicitImpl = x.Deref.IsOverrideOrExplicitImpl /// Is this a member, if so some more data about the member. - member x.MemberInfo = x.Deref.MemberInfo + member x.MemberInfo = x.Deref.MemberInfo /// Indicates if this is a member - member x.IsMember = x.Deref.IsMember + member x.IsMember = x.Deref.IsMember /// Indicates if this is an F#-defined value in a module, or an extension member, but excluding compiler generated bindings from optimizations - member x.IsModuleBinding = x.Deref.IsModuleBinding + member x.IsModuleBinding = x.Deref.IsModuleBinding /// Indicates if this is an F#-defined instance member. /// /// Note, the value may still be (a) an extension member or (b) and abstract slot without /// a true body. These cases are often causes of bugs in the compiler. - member x.IsInstanceMember = x.Deref.IsInstanceMember + member x.IsInstanceMember = x.Deref.IsInstanceMember /// Indicates if this value is declared 'mutable' - member x.IsMutable = x.Deref.IsMutable + member x.IsMutable = x.Deref.IsMutable /// Indicates if this value allows the use of an explicit type instantiation (i.e. does it itself have explicit type arguments, /// or does it have a signature?) - member x.PermitsExplicitTypeInstantiation = x.Deref.PermitsExplicitTypeInstantiation + member x.PermitsExplicitTypeInstantiation = x.Deref.PermitsExplicitTypeInstantiation /// Indicates if this is inferred to be a method or function that definitely makes no critical tailcalls? - member x.MakesNoCriticalTailcalls = x.Deref.MakesNoCriticalTailcalls + member x.MakesNoCriticalTailcalls = x.Deref.MakesNoCriticalTailcalls /// Is this a member definition or module definition? - member x.IsMemberOrModuleBinding = x.Deref.IsMemberOrModuleBinding + member x.IsMemberOrModuleBinding = x.Deref.IsMemberOrModuleBinding /// Indicates if this is an F#-defined extension member - member x.IsExtensionMember = x.Deref.IsExtensionMember + member x.IsExtensionMember = x.Deref.IsExtensionMember /// Indicates if this is a constructor member generated from the de-sugaring of implicit constructor for a class type? member x.IsIncrClassConstructor = x.Deref.IsIncrClassConstructor @@ -3784,55 +3784,55 @@ and member x.IsIncrClassGeneratedMember = x.Deref.IsIncrClassGeneratedMember /// Get the information about a recursive value used during type inference - member x.RecursiveValInfo = x.Deref.RecursiveValInfo + member x.RecursiveValInfo = x.Deref.RecursiveValInfo /// Indicates if this is a 'base' or 'this' value? - member x.BaseOrThisInfo = x.Deref.BaseOrThisInfo + member x.BaseOrThisInfo = x.Deref.BaseOrThisInfo // Indicates if this value was declared to be a type function, e.g. "let f<'a> = typeof<'a>" - member x.IsTypeFunction = x.Deref.IsTypeFunction + member x.IsTypeFunction = x.Deref.IsTypeFunction /// Records the "extra information" for a value compiled as a method. /// /// This indicates the number of arguments in each position for a curried function. - member x.ValReprInfo = x.Deref.ValReprInfo + member x.ValReprInfo = x.Deref.ValReprInfo /// Get the inline declaration on the value - member x.InlineInfo = x.Deref.InlineInfo + member x.InlineInfo = x.Deref.InlineInfo /// Indicates whether the inline declaration for the value indicate that the value must be inlined? - member x.MustInline = x.Deref.MustInline + member x.MustInline = x.Deref.MustInline /// Indicates whether this value was generated by the compiler. /// /// Note: this is true for the overrides generated by hash/compare augmentations - member x.IsCompilerGenerated = x.Deref.IsCompilerGenerated + member x.IsCompilerGenerated = x.Deref.IsCompilerGenerated /// Get the declared attributes for the value - member x.Attribs = x.Deref.Attribs + member x.Attribs = x.Deref.Attribs /// Get the declared documentation for the value - member x.XmlDoc = x.Deref.XmlDoc + member x.XmlDoc = x.Deref.XmlDoc /// Get or set the signature for the value's XML documentation - member x.XmlDocSig = x.Deref.XmlDocSig + member x.XmlDocSig = x.Deref.XmlDocSig /// Get the actual parent entity for the value (a module or a type), i.e. the entity under which the /// value will appear in compiled code. For extension members this is the module where the extension member /// is declared. - member x.TopValDeclaringEntity = x.Deref.TopValDeclaringEntity + member x.TopValDeclaringEntity = x.Deref.TopValDeclaringEntity // Can be false for members after error recovery - member x.HasDeclaringEntity = x.Deref.HasDeclaringEntity + member x.HasDeclaringEntity = x.Deref.HasDeclaringEntity /// Get the apparent parent entity for a member - member x.MemberApparentEntity = x.Deref.MemberApparentEntity + member x.MemberApparentEntity = x.Deref.MemberApparentEntity /// Get the number of 'this'/'self' object arguments for the member. Instance extension members return '1'. - member x.NumObjArgs = x.Deref.NumObjArgs + member x.NumObjArgs = x.Deref.NumObjArgs [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = if x.IsLocalRef then x.ResolvedTarget.DisplayName @@ -3892,7 +3892,7 @@ and member x.FieldByIndex n = x.UnionCase.FieldTable.FieldByIndex n [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = x.CaseName @@ -3919,7 +3919,7 @@ and | None -> error(InternalError(sprintf "field %s not found in type %s" id tcref.LogicalName, tcref.Range)) /// Try to dereference the reference - member x.TryRecdField = x.TyconRef.TryDeref |> ValueOptionInternal.bind (fun tcref -> tcref.GetFieldByName x.FieldName |> ValueOptionInternal.ofOption) + member x.TryRecdField = x.TyconRef.TryDeref |> ValueOptionInternal.bind (fun tcref -> tcref.GetFieldByName x.FieldName |> ValueOptionInternal.ofOption) /// Get the attributes associated with the compiled property of the record field member x.PropertyAttribs = x.RecdField.PropertyAttribs @@ -3942,7 +3942,7 @@ and error(InternalError(sprintf "field %s not found in type %s" id tcref.LogicalName, tcref.Range)) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = x.FieldName @@ -3974,14 +3974,14 @@ and /// TType_fun(domainType, rangeType). /// /// Indicates the type is a function type - | TType_fun of TType * TType + | TType_fun of TType * TType /// TType_ucase(unionCaseRef, typeInstantiation) /// /// Indicates the type is a non-F#-visible type representing a "proof" that a union value belongs to a particular union case /// These types are not user-visible and will never appear as an inferred type. They are the types given to /// the temporaries arising out of pattern matching on union values. - | TType_ucase of UnionCaseRef * TypeInst + | TType_ucase of UnionCaseRef * TypeInst /// Indicates the type is a variable type, whether declared, generalized or an inference type parameter | TType_var of Typar @@ -3993,23 +3993,23 @@ and /// See https://github.com/Microsoft/visualfsharp/issues/2561 member x.GetAssemblyName() = match x with - | TType_forall (_tps, ty) -> ty.GetAssemblyName() - | TType_app (tcref, _tinst) -> tcref.CompilationPath.ILScopeRef.QualifiedName + | TType_forall (_tps, ty) -> ty.GetAssemblyName() + | TType_app (tcref, _tinst) -> tcref.CompilationPath.ILScopeRef.QualifiedName | TType_tuple (_tupInfo, _tinst) -> "" | TType_anon (anonInfo, _tinst) -> defaultArg anonInfo.Assembly.QualifiedName "" - | TType_fun (_d, _r) -> "" - | TType_measure _ms -> "" - | TType_var tp -> tp.Solution |> function Some sln -> sln.GetAssemblyName() | None -> "" - | TType_ucase (_uc, _tinst) -> + | TType_fun (_d, _r) -> "" + | TType_measure _ms -> "" + | TType_var tp -> tp.Solution |> function Some sln -> sln.GetAssemblyName() | None -> "" + | TType_ucase (_uc, _tinst) -> let (TILObjectReprData(scope, _nesting, _definition)) = _uc.Tycon.ILTyconInfo scope.QualifiedName [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = match x with - | TType_forall (_tps, ty) -> "forall ... " + ty.ToString() + | TType_forall (_tps, ty) -> "forall ... " + ty.ToString() | TType_app (tcref, tinst) -> tcref.DisplayName + (match tinst with [] -> "" | tys -> "<" + String.concat "," (List.map string tys) + ">") | TType_tuple (tupInfo, tinst) -> (match tupInfo with @@ -4036,7 +4036,7 @@ and [] AnonRecdTypeInfo = // Mutability for pickling/unpickling only { mutable Assembly: CcuThunk mutable TupInfo: TupInfo - mutable SortedIds: Ident[] + mutable SortedIds: Ident[] mutable Stamp: Stamp mutable SortedNames: string[] } @@ -4044,11 +4044,11 @@ and [] AnonRecdTypeInfo = static member Create(ccu: CcuThunk, tupInfo, ids: Ident[]) = let sortedIds = ids |> Array.sortBy (fun id -> id.idText) // Hash all the data to form a unique stamp - let stamp = + let stamp = sha1HashInt64 [| for c in ccu.AssemblyName do yield byte c; yield byte (int32 c >>> 8) match tupInfo with - | TupInfo.Const b -> yield (if b then 0uy else 1uy) + | TupInfo.Const b -> yield (if b then 0uy else 1uy) for id in sortedIds do for c in id.idText do yield byte c; yield byte (int32 c >>> 8) |] let sortedNames = Array.map textOfId sortedIds @@ -4056,7 +4056,7 @@ and [] AnonRecdTypeInfo = /// Get the ILTypeRef for the generated type implied by the anonymous type member x.ILTypeRef = - let ilTypeName = sprintf "<>f__AnonymousType%s%u`%d'" (match x.TupInfo with TupInfo.Const b -> if b then "1000" else "") (uint32 x.Stamp) x.SortedIds.Length + let ilTypeName = sprintf "<>f__AnonymousType%s%u`%d'" (match x.TupInfo with TupInfo.Const b -> if b then "1000" else "") (uint32 x.Stamp) x.SortedIds.Length mkILTyRef(x.Assembly.ILScopeRef, ilTypeName) static member NewUnlinked() : AnonRecdTypeInfo = @@ -4064,7 +4064,7 @@ and [] AnonRecdTypeInfo = TupInfo = Unchecked.defaultof<_> SortedIds = Unchecked.defaultof<_> Stamp = Unchecked.defaultof<_> - SortedNames = Unchecked.defaultof<_> } + SortedNames = Unchecked.defaultof<_> } member x.Link d = let sortedNames = Array.map textOfId d.SortedIds @@ -4103,7 +4103,7 @@ and // %+A formatting is used, so this is not needed //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -4159,32 +4159,32 @@ and TypeForwarders: CcuTypeForwarderTable } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = sprintf "CcuData(%A)" x.FileName /// Represents a table of .NET CLI type forwarders for an assembly and CcuTypeForwarderTable = Map> -and CcuReference = string // ILAssemblyRef +and CcuReference = string // ILAssemblyRef /// A relinkable handle to the contents of a compilation unit. Relinking is performed by mutation. // /// A compilation unit is, more or less, the new material created in one -/// invocation of the compiler. Due to static linking assemblies may hold more +/// invocation of the compiler. Due to static linking assemblies may hold more /// than one compilation unit (i.e. when two assemblies are merged into a compilation -/// the resulting assembly will contain 3 CUs). Compilation units are also created for referenced +/// the resulting assembly will contain 3 CUs). Compilation units are also created for referenced /// .NET assemblies. /// /// References to items such as type constructors are via /// cross-compilation-unit thunks, which directly reference the data structures that define -/// these modules. Thus, when saving out values to disk we only wish -/// to save out the "current" part of the term graph. When reading values +/// these modules. Thus, when saving out values to disk we only wish +/// to save out the "current" part of the term graph. When reading values /// back in we "fixup" the links to previously referenced modules. /// /// All non-local accesses to the data structures are mediated -/// by ccu-thunks. Ultimately, a ccu-thunk is either a (named) element of +/// by ccu-thunks. Ultimately, a ccu-thunk is either a (named) element of /// the data structure, or it is a delayed fixup, i.e. an invalid dangling /// reference that has not had an appropriate fixup applied. and @@ -4199,7 +4199,7 @@ and /// must be in the explicit references in the project. mutable orphanfixup: bool - name: CcuReference } + name: CcuReference } member ccu.Deref = if isNull (ccu.target :> obj) || ccu.orphanfixup then @@ -4219,23 +4219,23 @@ and with get() = ccu.Deref.UsesFSharp20PlusQuotations and set v = ccu.Deref.UsesFSharp20PlusQuotations <- v - member ccu.AssemblyName = ccu.name + member ccu.AssemblyName = ccu.name /// Holds the data indicating how this assembly/module is referenced from the code being compiled. - member ccu.ILScopeRef = ccu.Deref.ILScopeRef + member ccu.ILScopeRef = ccu.Deref.ILScopeRef /// A unique stamp for this DLL - member ccu.Stamp = ccu.Deref.Stamp + member ccu.Stamp = ccu.Deref.Stamp /// Holds the filename for the DLL, if any - member ccu.FileName = ccu.Deref.FileName + member ccu.FileName = ccu.Deref.FileName - /// Try to get the .NET Assembly, if known. May not be present for `IsFSharp` for in-memory cross-project references - member ccu.TryGetILModuleDef() = ccu.Deref.TryGetILModuleDef() + /// Try to get the .NET Assembly, if known. May not be present for `IsFSharp` for in-memory cross-project references + member ccu.TryGetILModuleDef() = ccu.Deref.TryGetILModuleDef() #if !NO_EXTENSIONTYPING /// Is the CCu an EST injected assembly - member ccu.IsProviderGenerated = ccu.Deref.IsProviderGenerated + 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 @@ -4243,20 +4243,20 @@ and #endif /// The fully qualified assembly reference string to refer to this assembly. This is persisted in quotations - member ccu.QualifiedName = ccu.Deref.QualifiedName + member ccu.QualifiedName = ccu.Deref.QualifiedName /// A hint as to where does the code for the CCU live (e.g what was the tcConfig.implicitIncludeDir at compilation time for this DLL?) member ccu.SourceCodeDirectory = ccu.Deref.SourceCodeDirectory /// Indicates that this DLL was compiled using the F# compiler and has F# metadata - member ccu.IsFSharp = ccu.Deref.IsFSharp + member ccu.IsFSharp = ccu.Deref.IsFSharp /// A handle to the full specification of the contents of the module contained in this ccu // NOTE: may contain transient state during typechecking - member ccu.Contents = ccu.Deref.Contents + 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 @@ -4268,13 +4268,13 @@ and static member Create(nm, x) = { target = x orphanfixup = false - name = nm } + name = nm } /// Create a CCU with the given name but where the contents have not yet been specified static member CreateDelayed(nm) = { target = Unchecked.defaultof<_> orphanfixup = false - name = nm } + name = nm } /// Fixup a CCU to have the given contents member x.Fixup(avail: CcuThunk) = @@ -4282,8 +4282,8 @@ and match box x.target with | null -> () | _ -> - // In the IDE we tolerate a double-fixup of FSHarp.Core when editing the FSharp.Core project itself - if x.AssemblyName <> "FSharp.Core" then + // In the IDE we tolerate a double-fixup of FSHarp.Core when editing the FSharp.Core project itself + if x.AssemblyName <> "FSharp.Core" then errorR(Failure("internal error: Fixup: the ccu thunk for assembly "+x.AssemblyName+" not delayed!")) assert (avail.AssemblyName = x.AssemblyName) @@ -4299,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 @@ -4312,7 +4312,7 @@ and ccu.Deref.MemberSignatureEquality ty1 ty2 [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override ccu.ToString() = ccu.AssemblyName @@ -4327,7 +4327,7 @@ and | UnresolvedCcu of string [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = match x with ResolvedCcu ccu -> ccu.ToString() | UnresolvedCcu s -> "unresolved " + s @@ -4342,7 +4342,7 @@ and usesQuotations: bool } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override __.ToString() = "PickledCcuInfo(...)" @@ -4366,7 +4366,7 @@ and // %+A formatting is used, so this is not needed //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -4378,7 +4378,7 @@ and | Attrib of TyconRef * AttribKind * AttribExpr list * AttribNamedArg list * bool * AttributeTargets option * range [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() member x.TyconRef = (let (Attrib(tcref, _, _, _, _, _, _)) = x in tcref) @@ -4393,7 +4393,7 @@ and | AttribExpr of Expr * Expr [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = sprintf "AttribExpr(...)" @@ -4404,35 +4404,35 @@ and | AttribNamedArg of (string*TType*bool*AttribExpr) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = sprintf "AttribNamedArg(...)" /// Constants in expressions and [] Const = - | Bool of bool - | SByte of sbyte - | Byte of byte - | Int16 of int16 - | UInt16 of uint16 - | Int32 of int32 - | UInt32 of uint32 - | Int64 of int64 - | UInt64 of uint64 - | IntPtr of int64 - | UIntPtr of uint64 - | Single of single - | Double of double - | Char of char - | String of string - | Decimal of Decimal + | Bool of bool + | SByte of sbyte + | Byte of byte + | Int16 of int16 + | UInt16 of uint16 + | Int32 of int32 + | UInt32 of uint32 + | Int64 of int64 + | UInt64 of uint64 + | IntPtr of int64 + | UIntPtr of uint64 + | Single of single + | Double of double + | Char of char + | String of string + | Decimal of Decimal | Unit | Zero // null/zero-bit-pattern /// Decision trees. Pattern matching has been compiled down to -/// a decision tree by this point. The right-hand-sides (actions) of -/// a decision tree by this point. The right-hand-sides (actions) of +/// a decision tree by this point. The right-hand-sides (actions) of +/// a decision tree by this point. The right-hand-sides (actions) of /// the decision tree are labelled by integers that are unique for that /// particular tree. and @@ -4446,8 +4446,8 @@ and /// must be the address of the expression being tested. /// cases -- The list of tests and their subsequent decision trees /// default -- The default decision tree, if any - /// range -- (precise documentation needed) - | TDSwitch of Expr * DecisionTreeCase list * DecisionTree option * range + /// range -- (precise documentation needed) + | TDSwitch of Expr * DecisionTreeCase list * DecisionTree option * range /// TDSuccess(results, targets) /// @@ -4467,7 +4467,7 @@ and // %+A formatting is used, so this is not needed //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -4484,7 +4484,7 @@ and member x.CaseTree = let (TCase(_, d)) = x in d [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = sprintf "DecisionTreeCase(...)" @@ -4512,16 +4512,16 @@ and /// /// Run the active pattern and bind a successful result to a /// variable in the remaining tree. - /// activePatExpr -- The active pattern function being called, perhaps applied to some active pattern parameters. - /// activePatResTys -- The result types (case types) of the active pattern. + /// activePatExpr -- The active pattern function being called, perhaps applied to some active pattern parameters. + /// activePatResTys -- The result types (case types) of the active pattern. /// activePatIdentity -- The value and the types it is applied to. If there are any active pattern parameters then this is empty. - /// idx -- The case number of the active pattern which the test relates to. + /// idx -- The case number of the active pattern which the test relates to. /// activePatternInfo -- The extracted info for the active pattern. | ActivePatternCase of Expr * TTypes * (ValRef * TypeInst) option * int * ActivePatternInfo // %+A formatting is used, so this is not needed //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -4532,7 +4532,7 @@ and | TTarget of Vals * Expr * SequencePointInfoForTarget [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = sprintf "DecisionTreeTarget(...)" @@ -4546,16 +4546,16 @@ and | TBind of Val * Expr * SequencePointInfoForBinding /// The value being bound - member x.Var = (let (TBind(v, _, _)) = x in v) + member x.Var = (let (TBind(v, _, _)) = x in v) /// The expression the value is being bound to - member x.Expr = (let (TBind(_, e, _)) = x in e) + member x.Expr = (let (TBind(_, e, _)) = x in e) /// The information about whether to emit a sequence point for the binding member x.SequencePointInfo = (let (TBind(_, _, sp)) = x in sp) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = sprintf "TBind(%s, ...)" x.Var.CompiledName @@ -4576,7 +4576,7 @@ and member x.CaseIndex = (let (APElemRef(_, _, n)) = x in n) [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override __.ToString() = "ActivePatternElemRef(...)" @@ -4584,27 +4584,27 @@ and /// than a closure or a local), including argument names, attributes etc. and [] - ValReprInfo = + ValReprInfo = /// ValReprInfo (numTypars, args, result) - | ValReprInfo of TyparReprInfo list * ArgReprInfo list list * ArgReprInfo + | ValReprInfo of TyparReprInfo list * ArgReprInfo list list * ArgReprInfo /// Get the extra information about the arguments for the value - member x.ArgInfos = (let (ValReprInfo(_, args, _)) = x in args) + member x.ArgInfos = (let (ValReprInfo(_, args, _)) = x in args) /// Get the number of curried arguments of the value member x.NumCurriedArgs = (let (ValReprInfo(_, args, _)) = x in args.Length) /// Get the number of type parameters of the value - member x.NumTypars = (let (ValReprInfo(n, _, _)) = x in n.Length) + member x.NumTypars = (let (ValReprInfo(n, _, _)) = x in n.Length) /// Indicates if the value has no arguments - neither type parameters nor value arguments - member x.HasNoArgs = (let (ValReprInfo(n, args, _)) = x in n.IsEmpty && args.IsEmpty) + member x.HasNoArgs = (let (ValReprInfo(n, args, _)) = x in n.IsEmpty && args.IsEmpty) /// Get the number of tupled arguments in each curried argument position - member x.AritiesOfArgs = (let (ValReprInfo(_, args, _)) = x in List.map List.length args) + member x.AritiesOfArgs = (let (ValReprInfo(_, args, _)) = x in List.map List.length args) /// Get the kind of each type parameter - member x.KindsOfTypars = (let (ValReprInfo(n, _, _)) = x in n |> List.map (fun (TyparReprInfo(_, k)) -> k)) + member x.KindsOfTypars = (let (ValReprInfo(n, _, _)) = x in n |> List.map (fun (TyparReprInfo(_, k)) -> k)) /// Get the total number of arguments member x.TotalArgCount = @@ -4620,7 +4620,7 @@ and loop args 0 [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override __.ToString() = "ValReprInfo(...)" @@ -4634,10 +4634,10 @@ and 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() + member x.DebugText = x.ToString() override __.ToString() = "ArgReprInfo(...)" @@ -4674,7 +4674,7 @@ and /// arguments, e.g. if compiled as a toplevel static method. | Lambda of Unique * Val option * Val option * Val list * Expr * range * TType - /// Type lambdas. These are used for the r.h.s. of polymorphic 'let' bindings and + /// Type lambdas. These are used for the r.h.s. of polymorphic 'let' bindings and /// for expressions that implement first-class polymorphic values. | TyLambda of Unique * Typars * Expr * range * TType @@ -4694,13 +4694,13 @@ and // Object expressions: A closure that implements an interface or a base type. // The base object type might be a delegate type. | Obj of - (* unique *) Unique * - (* object type *) TType * (* <-- NOTE: specifies type parameters for base type *) - (* base val *) Val option * - (* ctor call *) Expr * - (* overrides *) ObjExprMethod list * - (* extra interfaces *) (TType * ObjExprMethod list) list * - range + unique: Unique * + objTy: TType * (* <-- NOTE: specifies type parameters for base type *) + baseVal: Val option * + ctorCall: Expr * + overrides: ObjExprMethod list * + interfaceImpls: (TType * ObjExprMethod list) list * + range: range /// Matches are a more complicated form of "let" with multiple possible destinations /// and possibly multiple ways to get to each destination. @@ -4725,7 +4725,7 @@ and | Quote of Expr * (ILTypeRef list * TTypes * Exprs * ExprData) option ref * bool * range * TType /// Typechecking residue: Indicates a free choice of typars that arises due to - /// minimization of polymorphism at let-rec bindings. These are + /// minimization of polymorphism at let-rec bindings. These are /// resolved to a concrete instantiation on subsequent rewrites. | TyChoose of Typars * Expr * range @@ -4737,7 +4737,7 @@ and // Prefer to use the default formatting of this union type //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() // //override __.ToString() = "Expr(...)" @@ -4810,7 +4810,7 @@ and | UnionCaseFieldGetAddr of UnionCaseRef * int * readonly: bool /// An operation representing a field-get from a union value. The value is not assumed to have been proven to be of the corresponding union case. - | UnionCaseFieldSet of UnionCaseRef * int + | UnionCaseFieldSet of UnionCaseRef * int /// An operation representing a field-get from an F# exception value. | ExnFieldGet of TyconRef * int @@ -4861,7 +4861,7 @@ and // Prefer to use the default formatting of this union type //[] - //member x.DebugText = x.ToString() + //member x.DebugText = x.ToString() // //override __.ToString() = "TOp(...)" @@ -4905,7 +4905,7 @@ and LValueOperation = /// In C syntax this is: *localv_ptr | LByrefGet - /// In C syntax this is: localv = e , note == *(&localv) = e == LAddrOf; LByrefSet + /// In C syntax this is: localv = e, note == *(&localv) = e == LAddrOf; LByrefSet | LSet /// In C syntax this is: *localv_ptr = e @@ -4958,7 +4958,7 @@ and member x.Id = let (TObjExprMethod(slotsig, _, _, _, _, m)) = x in mkSynId m slotsig.Name [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = sprintf "TObjExprMethod(%s, ...)" x.Id.idText @@ -4971,20 +4971,20 @@ and | TSlotSig of string * TType * Typars * Typars * SlotParam list list * TType option - member ss.Name = let (TSlotSig(nm, _, _, _, _, _)) = ss in nm + member ss.Name = let (TSlotSig(nm, _, _, _, _, _)) = ss in nm - member ss.ImplementedType = let (TSlotSig(_, ty, _, _, _, _)) = ss in ty + member ss.ImplementedType = let (TSlotSig(_, ty, _, _, _, _)) = ss in ty - member ss.ClassTypars = let (TSlotSig(_, _, ctps, _, _, _)) = ss in ctps + member ss.ClassTypars = let (TSlotSig(_, _, ctps, _, _, _)) = ss in ctps - member ss.MethodTypars = let (TSlotSig(_, _, _, mtps, _, _)) = ss in mtps + member ss.MethodTypars = let (TSlotSig(_, _, _, mtps, _, _)) = ss in mtps - member ss.FormalParams = let (TSlotSig(_, _, _, _, ps, _)) = ss in ps + member ss.FormalParams = let (TSlotSig(_, _, _, _, ps, _)) = ss in ps member ss.FormalReturnType = let (TSlotSig(_, _, _, _, _, rt)) = ss in rt [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override ss.ToString() = sprintf "TSlotSig(%s, ...)" ss.Name @@ -4994,12 +4994,12 @@ and and [] SlotParam = - | TSlotParam of string option * TType * bool (* in *) * bool (* out *) * bool (* optional *) * Attribs + | TSlotParam of string option * TType * bool (* in *) * bool (* out *) * bool (* optional *) * Attribs member x.Type = let (TSlotParam(_, ty, _, _, _, _)) = x in ty [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TSlotParam(...)" @@ -5017,7 +5017,7 @@ and member x.Type = let (ModuleOrNamespaceExprWithSig(mtyp, _, _)) = x in mtyp [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "ModuleOrNamespaceExprWithSig(...)" @@ -5029,20 +5029,20 @@ and | TMAbstract of ModuleOrNamespaceExprWithSig /// Indicates the module fragment is made of several module fragments in succession - | TMDefs of ModuleOrNamespaceExpr list + | TMDefs of ModuleOrNamespaceExpr list /// Indicates the module fragment is a 'let' definition - | TMDefLet of Binding * range + | TMDefLet of Binding * range /// Indicates the module fragment is an evaluation of expression for side-effects - | TMDefDo of Expr * range + | 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 //[] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = sprintf "%+A" x @@ -5061,7 +5061,7 @@ and ModuleOrNamespaceExpr [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override __.ToString() = "ModuleOrNamespaceBinding(...)" @@ -5074,7 +5074,7 @@ and | TImplFile of QualifiedNameOfFile * ScopedPragma list * ModuleOrNamespaceExprWithSig * bool * bool * StampMap [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TImplFile(...)" @@ -5086,12 +5086,12 @@ and | TypedAssemblyAfterOptimization of (TypedImplFile * (* optimizeDuringCodeGen: *) (Expr -> Expr)) list [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "TypedAssemblyAfterOptimization(...)" //--------------------------------------------------------------------------- -// Freevars. Computed and cached by later phases (never computed type checking). Cached in terms. Not pickled. +// Freevars. Computed and cached by later phases (never computed type checking). Cached in terms. Not pickled. //--------------------------------------------------------------------------- /// Represents a set of free local values. @@ -5128,7 +5128,7 @@ and FreeTypars: FreeTypars } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "FreeTyvars(...)" @@ -5167,12 +5167,12 @@ and FreeTyvars: FreeTyvars } [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "FreeVars(...)" -/// Specifies the compiled representations of type and exception definitions. Basically -/// just an ILTypeRef. Computed and cached by later phases. Stored in +/// Specifies the compiled representations of type and exception definitions. Basically +/// just an ILTypeRef. Computed and cached by later phases. Stored in /// type and exception definitions. Not pickled. Store an optional ILType object for /// non-generic types. and @@ -5201,7 +5201,7 @@ and | ILAsmOpen of ILType [] - member x.DebugText = x.ToString() + member x.DebugText = x.ToString() override x.ToString() = "CompiledTypeRepr(...)" @@ -5238,9 +5238,9 @@ module ValReprInfo = // Basic properties via functions (old style) //--------------------------------------------------------------------------- -let typeOfVal (v: Val) = v.Type +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 nameOfVal (v: Val) = v.LogicalName let arityOfVal (v: Val) = (match v.ValReprInfo with None -> ValReprInfo.emptyValData | Some arities -> arities) let tupInfoRef = TupInfo.Const false @@ -5255,15 +5255,15 @@ let mkRawStructTupleTy tys = TType_tuple (tupInfoStruct, tys) // make up the entire compilation unit //--------------------------------------------------------------------------- -let mapTImplFile f (TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = TImplFile(fragName, pragmas, f moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes) +let mapTImplFile f (TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = TImplFile(fragName, pragmas, f moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes) let mapAccImplFile f z (TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes)) = let moduleExpr, z = f z moduleExpr in TImplFile(fragName, pragmas, moduleExpr, hasExplicitEntryPoint, isScript, anonRecdTypes), z -let foldTImplFile f z (TImplFile(_, _, moduleExpr, _, _, _)) = f z moduleExpr +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) @@ -5324,7 +5324,7 @@ type EntityRef with 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 } @@ -5359,11 +5359,11 @@ let mkTyparTy (tp: Typar) = let copyTypar (tp: Typar) = let optData = tp.typar_opt_data |> Option.map (fun tg -> { typar_il_name = tg.typar_il_name; typar_xmldoc = tg.typar_xmldoc; typar_constraints = tg.typar_constraints; typar_attribs = tg.typar_attribs }) - Typar.New { typar_id = tp.typar_id - typar_flags = tp.typar_flags - typar_stamp = newStamp() + Typar.New { typar_id = tp.typar_id + typar_flags = tp.typar_flags + typar_stamp = newStamp() typar_solution = tp.typar_solution - typar_astype = Unchecked.defaultof<_> + typar_astype = Unchecked.defaultof<_> // Be careful to clone the mutable optional data too typar_opt_data = optData } @@ -5426,13 +5426,13 @@ let stripUnitEqns unt = stripUnitEqnsAux false unt // the item is globally stable ("published") or not. //--------------------------------------------------------------------------- -let mkLocalValRef (v: Val) = VRefLocal v +let mkLocalValRef (v: Val) = VRefLocal v let mkLocalModRef (v: ModuleOrNamespace) = ERefLocal v -let mkLocalEntityRef (v: Entity) = ERefLocal v +let mkLocalEntityRef (v: Entity) = ERefLocal v 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 -> @@ -5499,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) -> @@ -5508,7 +5508,7 @@ let fslibEntityRefEq fslibCcu (eref1: EntityRef) (eref2: EntityRef) = | Some pp2 -> fslibRefEq nlr1 pp2 | None -> false | (ERefLocal e1, ERefLocal e2) -> - match e1.PublicPath , e2.PublicPath with + match e1.PublicPath, e2.PublicPath with | Some pp1, Some pp2 -> pubPathEq pp1 pp2 | _ -> false | _ -> false @@ -5531,7 +5531,7 @@ let fslibValRefEq fslibCcu vref1 vref2 = // This relies on the fact that the compiler doesn't use any references to // entities in fslib that are overloaded, or, if they are overloaded, then value identity // is not significant - nlr1.ItemKey.PartialKey = nm2.PartialKey && + nlr1.ItemKey.PartialKey = nm2.PartialKey && fslibRefEq nlr1.EnclosingEntity.nlr pp2 | _ -> false @@ -5568,7 +5568,7 @@ let primEntityRefEq compilingFslib fslibCcu (x: EntityRef) (y: EntityRef) = let primUnionCaseRefEq compilingFslib fslibCcu (UCRef(tcr1, c1) as uc1) (UCRef(tcr2, c2) as uc2) = uc1 === uc2 || (primEntityRefEq compilingFslib fslibCcu tcr1 tcr2 && c1 = c2) -/// Primitive routine to compare two ValRef's for equality. On the whole value identity is not particularly +/// Primitive routine to compare two ValRef's for equality. On the whole value identity is not particularly /// significant in F#. However it is significant for /// (a) Active Patterns /// (b) detecting uses of "special known values" from FSharp.Core.dll, such as 'seq' @@ -5593,12 +5593,12 @@ let primValRefEq compilingFslib fslibCcu (x: ValRef) (y: ValRef) = //--------------------------------------------------------------------------- let fullCompPathOfModuleOrNamespace (m: ModuleOrNamespace) = - let (CompPath(scoref, cpath)) = m.CompilationPath + let (CompPath(scoref, cpath)) = m.CompilationPath CompPath(scoref, cpath@[(m.LogicalName, m.ModuleOrNamespaceType.ModuleOrNamespaceKind)]) // Can cpath2 be accessed given a right to access cpath1. That is, is cpath2 a nested type or namespace of cpath1. Note order of arguments. let inline canAccessCompPathFrom (CompPath(scoref1, cpath1)) (CompPath(scoref2, cpath2)) = - let rec loop p1 p2 = + let rec loop p1 p2 = match p1, p2 with | (a1, k1)::rest1, (a2, k2)::rest2 -> (a1=a2) && (k1=k2) && loop rest1 rest2 | [], _ -> true @@ -5614,7 +5614,7 @@ let canAccessFrom (TAccess x) cpath = let canAccessFromEverywhere (TAccess x) = x.IsEmpty let canAccessFromSomewhere (TAccess _) = true -let isLessAccessible (TAccess aa) (TAccess bb) = +let isLessAccessible (TAccess aa) (TAccess bb) = not (aa |> List.forall(fun a -> bb |> List.exists (fun b -> canAccessCompPathFrom a b))) /// Given (newPath, oldPath) replace oldPath by newPath in the TAccess. @@ -5641,7 +5641,7 @@ let MakeUnionCasesTable ucs: TyconUnionCases = let MakeRecdFieldsTable ucs: TyconRecdFields = { FieldsByIndex = Array.ofList ucs - FieldsByName = ucs |> NameMap.ofKeyedList (fun rfld -> rfld.Name) } + FieldsByName = ucs |> NameMap.ofKeyedList (fun rfld -> rfld.Name) } let MakeUnionCases ucs: TyconUnionData = @@ -5700,7 +5700,7 @@ let NewExn cpath (id: Ident) access repr attribs doc = | _ -> Some { Entity.NewEmptyEntityOptData() with entity_xmldoc = doc; entity_accessiblity = access; entity_tycon_repr_accessibility = access; entity_exn_info = repr } } /// Create a new TAST RecdField node for an F# class, struct or record field -let NewRecdField stat konst id nameGenerated ty isMutable isVolatile pattribs fattribs docOption access secret = +let NewRecdField stat konst id nameGenerated ty isMutable isVolatile pattribs fattribs docOption access secret = { rfield_mutable=isMutable rfield_pattribs=pattribs rfield_fattribs=fattribs @@ -5764,24 +5764,24 @@ let NewVal let stamp = newStamp() Val.New - { val_stamp = stamp + { val_stamp = stamp val_logical_name = logicalName - val_range = m - val_flags = ValFlags(recValInfo, baseOrThis, isCompGen, inlineInfo, isMutable, isModuleOrMemberBinding, isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal) - val_type = ty - val_opt_data = + val_range = m + val_flags = ValFlags(recValInfo, baseOrThis, isCompGen, inlineInfo, isMutable, isModuleOrMemberBinding, isExtensionMember, isIncrClassSpecialMember, isTyFunc, allowTypeInst, isGeneratedEventVal) + val_type = ty + val_opt_data = match compiledName, arity, konst, access, doc, specialRepr, actualParent, attribs with | None, None, None, TAccess [], XmlDoc [||], None, ParentNone, [] -> None | _ -> Some { Val.NewEmptyValOptData() with - val_compiled_name = (match compiledName with Some v when v <> logicalName -> compiledName | _ -> None) - val_repr_info = arity - val_const = konst - val_access = access - val_xmldoc = doc - val_member_info = specialRepr + val_compiled_name = (match compiledName with Some v when v <> logicalName -> compiledName | _ -> None) + val_repr_info = arity + val_const = konst + val_access = access + val_xmldoc = doc + val_member_info = specialRepr val_declaring_entity = actualParent - val_attribs = attribs } + val_attribs = attribs } } @@ -5799,7 +5799,7 @@ let NewCcuContents sref m nm mty = /// We pass the new tycon to 'f' in case it needs to reparent the /// contents of the tycon. let NewModifiedTycon f (orig: Tycon) = - let data = { orig with entity_stamp = newStamp() } + let data = { orig with entity_stamp = newStamp() } Tycon.New "NewModifiedTycon" (f data) /// Create a module Tycon based on an existing one using the function 'f'. @@ -5817,8 +5817,8 @@ let NewModifiedVal f (orig: Val) = let data' = f { orig with val_stamp=stamp } Val.New data' -let NewClonedModuleOrNamespace orig = NewModifiedModuleOrNamespace (fun mty -> mty) orig -let NewClonedTycon orig = NewModifiedTycon (fun d -> d) orig +let NewClonedModuleOrNamespace orig = NewModifiedModuleOrNamespace (fun mty -> mty) orig +let NewClonedTycon orig = NewModifiedTycon (fun d -> d) orig //------------------------------------------------------------------------------ @@ -5828,8 +5828,8 @@ 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) = - match mty1.ModuleOrNamespaceKind, mty2.ModuleOrNamespaceKind with + let rec CombineModuleOrNamespaceTypes path m (mty1: ModuleOrNamespaceType) (mty2: ModuleOrNamespaceType) = + match mty1.ModuleOrNamespaceKind, mty2.ModuleOrNamespaceKind with | Namespace, Namespace -> let kind = mty1.ModuleOrNamespaceKind let tab1 = mty1.AllEntitiesByLogicalMangledName diff --git a/tests/scripts/codingConventions.fsx b/tests/scripts/codingConventions.fsx index 46ddf3804d6..9f5a997e020 100644 --- a/tests/scripts/codingConventions.fsx +++ b/tests/scripts/codingConventions.fsx @@ -101,3 +101,19 @@ let spaceBeforeColon = printfn "Top files that have extra space before colon:\n%A" (Array.truncate 10 spaceBeforeColon) +printfn "------ Internal spacing----------" + + +let internalSpacing = + let re = Regex("[^ ] [^ ]") + 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 internal spacing in lines:\n%A" (Array.truncate 10 internalSpacing) + From a8080a6b0fdaed20272d2dd47ab5ddd0ebf46169 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Wed, 27 Mar 2019 14:09:48 -0700 Subject: [PATCH 13/27] fix build variable typo (#6382) --- eng/build-utils.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/build-utils.ps1 b/eng/build-utils.ps1 index 845169db12a..c76c9421c19 100644 --- a/eng/build-utils.ps1 +++ b/eng/build-utils.ps1 @@ -13,7 +13,7 @@ $binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $false } $nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { $false } $bootstrapDir = if (Test-Path variable:bootstrapDir) { $bootstrapDir } else { "" } $bootstrapConfiguration = if (Test-Path variable:bootstrapConfiguration) { $bootstrapConfiguration } else { "Proto" } -$bootstrapTrm = if (Test-Path variable:bootstrapTfm) { $bootstrapConfiguration } else { "net46" } +$bootstrapTfm = if (Test-Path variable:bootstrapTfm) { $bootstrapTfm } else { "net46" } $properties = if (Test-Path variable:properties) { $properties } else { @() } function GetProjectOutputBinary([string]$fileName, [string]$projectName = "", [string]$configuration = $script:configuration, [string]$tfm = "net46", [string]$rid = "", [bool]$published = $false) { From 65461d7fd1a430bbc4c869741654e762b35d155a Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Thu, 28 Mar 2019 06:00:40 -0700 Subject: [PATCH 14/27] Always build FSharp.Core.UnitTests against the FSharp.Core in the repository (#6384) --- FSharpBuild.Directory.Build.props | 4 ++++ eng/Build.ps1 | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/FSharpBuild.Directory.Build.props b/FSharpBuild.Directory.Build.props index c38700df06c..31d24301299 100644 --- a/FSharpBuild.Directory.Build.props +++ b/FSharpBuild.Directory.Build.props @@ -3,6 +3,10 @@ + + true + + $(RepoRoot)src diff --git a/eng/Build.ps1 b/eng/Build.ps1 index 04afc1b1d46..26c55741ab1 100644 --- a/eng/Build.ps1 +++ b/eng/Build.ps1 @@ -46,6 +46,7 @@ param ( [switch][Alias('test')]$testDesktop, [switch]$testCoreClr, [switch]$testFSharpQA, + [switch]$testFSharpCore, [switch]$testVs, [switch]$testAll, @@ -76,6 +77,7 @@ function Print-Usage() { Write-Host " -testDesktop Run tests against full .NET Framework" Write-Host " -testCoreClr Run tests against CoreCLR" Write-Host " -testFSharpQA Run F# Cambridge tests" + Write-Host " -testFSharpCore Run FSharpCore unit tests" Write-Host " -testVs Run F# editor unit tests" Write-Host "" Write-Host "Advanced settings:" @@ -271,6 +273,14 @@ try { Pop-Location } + if ($testFSharpCore) { + Write-Host "Environment Variables" + Get-Childitem Env: + TestUsingNUnit -testProject "$RepoRoot\tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj" -targetFramework $desktopTargetFramework + TestUsingNUnit -testProject "$RepoRoot\tests\FSharp.Core.UnitTests\FSharp.Core.UnitTests.fsproj" -targetFramework $coreclrTargetFramework + } + + if ($testVs) { Write-Host "Environment Variables" Get-Childitem Env: From 134d868af44580bcb6cb02a122e0d7c65f0703cb Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Thu, 28 Mar 2019 12:21:23 -0700 Subject: [PATCH 15/27] Re-enable ngen for desktop compiler builds (#6386) * Re-enable ngen for desktop compilers * Go even earlier * Cooler mechanism --- FSharpBuild.Directory.Build.targets | 2 +- eng/targets/NGenBinaries.targets | 33 +++++++++++++++++++ src/fsharp/FSharp.Build/FSharp.Build.fsproj | 1 + ...Sharp.Compiler.Interactive.Settings.fsproj | 1 + .../FSharp.Compiler.Private.fsproj | 1 + .../FSharp.Compiler.Server.Shared.fsproj | 1 + src/fsharp/FSharp.Core/FSharp.Core.fsproj | 1 + src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj | 1 + 8 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 eng/targets/NGenBinaries.targets diff --git a/FSharpBuild.Directory.Build.targets b/FSharpBuild.Directory.Build.targets index c9f98da4493..ebd6f0d47d5 100644 --- a/FSharpBuild.Directory.Build.targets +++ b/FSharpBuild.Directory.Build.targets @@ -1,7 +1,7 @@ - + diff --git a/eng/targets/NGenBinaries.targets b/eng/targets/NGenBinaries.targets new file mode 100644 index 00000000000..6e4ad9799f6 --- /dev/null +++ b/eng/targets/NGenBinaries.targets @@ -0,0 +1,33 @@ + + + + + true + true + false + + + + + $(windir)\Microsoft.NET\Framework64\v4.0.30319\ngen.exe + $(windir)\Microsoft.NET\Framework\v4.0.30319\ngen.exe + $(WindowsSDK_ExecutablePath_x86)sn.exe + + + + + + + + + + + \ No newline at end of file diff --git a/src/fsharp/FSharp.Build/FSharp.Build.fsproj b/src/fsharp/FSharp.Build/FSharp.Build.fsproj index 4bf0eb97289..d46efd025e6 100644 --- a/src/fsharp/FSharp.Build/FSharp.Build.fsproj +++ b/src/fsharp/FSharp.Build/FSharp.Build.fsproj @@ -10,6 +10,7 @@ $(NoWarn);45;55;62;75;1204 true $(OtherFlags) --maxerrors:20 --extraoptimizationloops:1 + true diff --git a/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj b/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj index 3569093c47f..f54cd37330d 100644 --- a/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj +++ b/src/fsharp/FSharp.Compiler.Interactive.Settings/FSharp.Compiler.Interactive.Settings.fsproj @@ -10,6 +10,7 @@ $(NoWarn);45;55;62;75;1182;1204 true $(OtherFlags) --maxerrors:20 --extraoptimizationloops:1 + true diff --git a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj index ce3e578f7ae..2c5f4d1abc5 100644 --- a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj +++ b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj @@ -15,6 +15,7 @@ true true true + true diff --git a/src/fsharp/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj b/src/fsharp/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj index 2940172c7e6..fd1a2470534 100644 --- a/src/fsharp/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj +++ b/src/fsharp/FSharp.Compiler.Server.Shared/FSharp.Compiler.Server.Shared.fsproj @@ -4,6 +4,7 @@ net46 + true diff --git a/src/fsharp/FSharp.Core/FSharp.Core.fsproj b/src/fsharp/FSharp.Core/FSharp.Core.fsproj index b7f089b3e0c..440850ed55c 100644 --- a/src/fsharp/FSharp.Core/FSharp.Core.fsproj +++ b/src/fsharp/FSharp.Core/FSharp.Core.fsproj @@ -12,6 +12,7 @@ BUILDING_WITH_LKG;$(DefineConstants) $(OtherFlags) --warnon:1182 --compiling-fslib --compiling-fslib-40 --maxerrors:20 --extraoptimizationloops:1 true + true diff --git a/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj b/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj index 868b379f234..b310a33b43c 100644 --- a/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj +++ b/src/fsharp/fsiAnyCpu/fsiAnyCpu.fsproj @@ -12,6 +12,7 @@ $(OtherFlags) --warnon:1182 --maxerrors:20 --extraoptimizationloops:1 ..\fsi\fsi.res true + true From 4d335797bbc3eff58cfaf2d9d1bec0a14ca3c959 Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Thu, 28 Mar 2019 17:24:14 -0700 Subject: [PATCH 16/27] Add fsi to proto build, move version validation to ci only (#6387) --- eng/Build.ps1 | 6 +++--- eng/build-utils.ps1 | 4 +--- proto.proj | 4 ++++ 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/eng/Build.ps1 b/eng/Build.ps1 index 26c55741ab1..865cf231575 100644 --- a/eng/Build.ps1 +++ b/eng/Build.ps1 @@ -189,10 +189,10 @@ function UpdatePath() { } function VerifyAssemblyVersions() { - $fsiPath = Join-Path $ArtifactsDir "bin\fsi\$configuration\net46\fsi.exe" + $fsiPath = Join-Path $ArtifactsDir "bin\fsi\Proto\net46\fsi.exe" - # desktop fsi isn't always built - if (Test-Path $fsiPath) { + # Only verify versions on CI or official build + if ($ci -or $official) { $asmVerCheckPath = "$RepoRoot\scripts" Exec-Console $fsiPath """$asmVerCheckPath\AssemblyVersionCheck.fsx"" -- ""$ArtifactsDir""" } diff --git a/eng/build-utils.ps1 b/eng/build-utils.ps1 index c76c9421c19..304eac5a3e5 100644 --- a/eng/build-utils.ps1 +++ b/eng/build-utils.ps1 @@ -249,9 +249,7 @@ function Make-BootstrapBuild() { $projectPath = "$RepoRoot\proto.proj" Run-MSBuild $projectPath "/restore /t:Build" -logFileName "Bootstrap" -configuration $bootstrapConfiguration Copy-Item "$ArtifactsDir\bin\fsc\$bootstrapConfiguration\$bootstrapTfm\*" -Destination $dir - - Write-Host "Cleaning Bootstrap compiler artifacts" - Run-MSBuild $projectPath "/t:Clean" -logFileName "BootstrapClean" -configuration $bootstrapConfiguration + Copy-Item "$ArtifactsDir\bin\fsi\$bootstrapConfiguration\$bootstrapTfm\*" -Destination $dir return $dir } diff --git a/proto.proj b/proto.proj index c60f17d8426..bbad2c34cc5 100644 --- a/proto.proj +++ b/proto.proj @@ -14,6 +14,10 @@ TargetFramework=net46 TargetFramework=netcoreapp2.1 + + TargetFramework=net46 + TargetFramework=netcoreapp2.1 + From f1aee5fbaea584c153ec3edcdde80b7db600a526 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Fri, 29 Mar 2019 00:33:42 +0000 Subject: [PATCH 17/27] update FCS dependencies (#6388) * update FCS dependencies * update FCS dependencies * fix up build * code review --- .../FSharp.Compiler.Service.MSBuild.v12.fsproj | 4 ++-- ...FSharp.Compiler.Service.ProjectCracker.fsproj | 10 +++++----- ...Sharp.Compiler.Service.ProjectCracker.targets | 4 ++-- ...rp.Compiler.Service.ProjectCrackerTool.fsproj | 4 ++-- .../CSharp_Analysis/CSharp_Analysis.csproj | 2 +- .../FSharp.Compiler.Service.Tests.fsproj | 6 +++--- .../FSharp.Compiler.Service.fsproj | 6 +++--- fcs/README.md | 10 +++++++--- fcs/RELEASE_NOTES.md | 5 ++++- fcs/build.fsx | 2 +- fcs/docsrc/content/caches.fsx | 2 +- fcs/docsrc/content/compiler.fsx | 2 +- fcs/docsrc/content/corelib.fsx | 2 +- fcs/docsrc/content/editor.fsx | 2 +- fcs/docsrc/content/filesystem.fsx | 2 +- fcs/docsrc/content/interactive.fsx | 2 +- fcs/docsrc/content/ja/compiler.fsx | 2 +- fcs/docsrc/content/ja/corelib.fsx | 2 +- fcs/docsrc/content/ja/editor.fsx | 2 +- fcs/docsrc/content/ja/filesystem.fsx | 2 +- fcs/docsrc/content/ja/interactive.fsx | 2 +- fcs/docsrc/content/ja/project.fsx | 2 +- fcs/docsrc/content/ja/symbols.fsx | 2 +- fcs/docsrc/content/ja/tokenizer.fsx | 2 +- fcs/docsrc/content/ja/untypedtree.fsx | 2 +- fcs/docsrc/content/project.fsx | 4 ++-- fcs/docsrc/content/queue.fsx | 2 +- fcs/docsrc/content/react.fsx | 10 +++++----- fcs/docsrc/content/symbols.fsx | 2 +- fcs/docsrc/content/tokenizer.fsx | 2 +- fcs/docsrc/content/typedtree.fsx | 2 +- fcs/docsrc/content/untypedtree.fsx | 2 +- fcs/docsrc/tools/generate.fsx | 2 +- fcs/docsrc/tools/generate.ja.fsx | 6 +++--- fcs/paket.dependencies | 4 ++-- fcs/paket.lock | 2 +- fcs/samples/EditorService/EditorService.fsproj | 6 +++--- fcs/samples/FscExe/FscExe.fsproj | 6 +++--- fcs/samples/FsiExe/FsiExe.fsproj | 6 +++--- .../InteractiveService/InteractiveService.fsproj | 6 +++--- fcs/samples/Tokenizer/Tokenizer.fsproj | 6 +++--- fcs/samples/UntypedTree/UntypedTree.fsproj | 6 +++--- src/absil/illib.fs | 8 -------- src/fsharp/NameResolution.fs | 2 +- src/fsharp/Optimizer.fs | 2 +- src/fsharp/QuotationTranslator.fs | 2 +- src/fsharp/symbols/Symbols.fs | 16 ++++++++-------- src/fsharp/tast.fs | 10 +++++++--- 48 files changed, 100 insertions(+), 97 deletions(-) diff --git a/fcs/FSharp.Compiler.Service.MSBuild.v12/FSharp.Compiler.Service.MSBuild.v12.fsproj b/fcs/FSharp.Compiler.Service.MSBuild.v12/FSharp.Compiler.Service.MSBuild.v12.fsproj index 1126a60f2b6..1c82ed8fcda 100644 --- a/fcs/FSharp.Compiler.Service.MSBuild.v12/FSharp.Compiler.Service.MSBuild.v12.fsproj +++ b/fcs/FSharp.Compiler.Service.MSBuild.v12/FSharp.Compiler.Service.MSBuild.v12.fsproj @@ -5,7 +5,7 @@ - net45 + net461 true $(DefineConstants);CROSS_PLATFORM_COMPILER $(DefineConstants);ENABLE_MONO_SUPPORT @@ -28,7 +28,7 @@ - + $(FSharpSourcesRoot)\..\fcs\dependencies\MSBuild.v12.0\Microsoft.Build.Framework.dll diff --git a/fcs/FSharp.Compiler.Service.ProjectCracker/FSharp.Compiler.Service.ProjectCracker.fsproj b/fcs/FSharp.Compiler.Service.ProjectCracker/FSharp.Compiler.Service.ProjectCracker.fsproj index c132ae80bb1..648f66924df 100644 --- a/fcs/FSharp.Compiler.Service.ProjectCracker/FSharp.Compiler.Service.ProjectCracker.fsproj +++ b/fcs/FSharp.Compiler.Service.ProjectCracker/FSharp.Compiler.Service.ProjectCracker.fsproj @@ -2,7 +2,7 @@ - net45 + net461 true @@ -20,14 +20,14 @@ ProjectCrackerOptions.fs - - - + + + - + \ No newline at end of file diff --git a/fcs/FSharp.Compiler.Service.ProjectCrackerTool/FSharp.Compiler.Service.ProjectCracker.targets b/fcs/FSharp.Compiler.Service.ProjectCrackerTool/FSharp.Compiler.Service.ProjectCracker.targets index 45e62e6f25a..bd1c93e7979 100644 --- a/fcs/FSharp.Compiler.Service.ProjectCrackerTool/FSharp.Compiler.Service.ProjectCracker.targets +++ b/fcs/FSharp.Compiler.Service.ProjectCrackerTool/FSharp.Compiler.Service.ProjectCracker.targets @@ -1,7 +1,7 @@ - - + + diff --git a/fcs/FSharp.Compiler.Service.ProjectCrackerTool/FSharp.Compiler.Service.ProjectCrackerTool.fsproj b/fcs/FSharp.Compiler.Service.ProjectCrackerTool/FSharp.Compiler.Service.ProjectCrackerTool.fsproj index 9f690c58ea1..648aacb3c21 100644 --- a/fcs/FSharp.Compiler.Service.ProjectCrackerTool/FSharp.Compiler.Service.ProjectCrackerTool.fsproj +++ b/fcs/FSharp.Compiler.Service.ProjectCrackerTool/FSharp.Compiler.Service.ProjectCrackerTool.fsproj @@ -6,7 +6,7 @@ Exe - net45 + net461 true $(DefineConstants);CROSS_PLATFORM_COMPILER $(DefineConstants);ENABLE_MONO_SUPPORT @@ -23,7 +23,7 @@ - + $(FSharpSourcesRoot)\..\fcs\dependencies\MSBuild.v12.0\Microsoft.Build.Framework.dll false diff --git a/fcs/FSharp.Compiler.Service.Tests/CSharp_Analysis/CSharp_Analysis.csproj b/fcs/FSharp.Compiler.Service.Tests/CSharp_Analysis/CSharp_Analysis.csproj index fc00709da42..30d3c96317f 100644 --- a/fcs/FSharp.Compiler.Service.Tests/CSharp_Analysis/CSharp_Analysis.csproj +++ b/fcs/FSharp.Compiler.Service.Tests/CSharp_Analysis/CSharp_Analysis.csproj @@ -1,7 +1,7 @@  - net45;netstandard2.0 + net461;netstandard2.0 false $(NoWarn);0067;1591 diff --git a/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj b/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj index edb85fcf648..85e345669c4 100644 --- a/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj +++ b/fcs/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj @@ -5,7 +5,7 @@ - net46;netcoreapp2.0 + net461;netcoreapp2.0 true $(NoWarn);44;75; true @@ -78,7 +78,7 @@ - + @@ -86,7 +86,7 @@ - + diff --git a/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj b/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj index 602050c09a4..166dc7976b7 100644 --- a/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj +++ b/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj @@ -6,7 +6,7 @@ - net45;netstandard2.0 + net461;netstandard2.0 true $(DefineConstants);COMPILER_SERVICE_AS_DLL $(DefineConstants);COMPILER @@ -635,7 +635,7 @@ - + @@ -647,7 +647,7 @@ - + diff --git a/fcs/README.md b/fcs/README.md index 8f86342739e..ac97222a3c6 100644 --- a/fcs/README.md +++ b/fcs/README.md @@ -12,12 +12,16 @@ Basically we are packaging up the compiler as a DLL and publishing it as a NuGet There are subtle differences between FSharp.Compiler.Service and FSharp.Compiler.Private (shipped with the Visual F# Tools) - FCS has a public API -- FCS is built against **.NET 4.5** and **FSharp.Core 4.0.0.0** to give broader reach + +- FCS is built against **.NET 4.6.1** and **FSharp.Core NuGet 4.6.2** to give broader reach + - FCS has a NuGet package -- FCS has a .NET Standard 1.6 version in the nuget package + +- FCS has a .NET Standard 2.0 version in the nuget package + - FCS testing also tests the "Project Cracker" (see below) -- FCS doesn't add the System.ValueTuple.dll reference by default, see ``#if COMPILER_SERVICE_AS_DLL`` in compiler codebase +- FCS doesn't add the System.ValueTuple.dll reference by default, see ``#if COMPILER_SERVICE_AS_DLL`` in compiler codebase ## Version Numbers diff --git a/fcs/RELEASE_NOTES.md b/fcs/RELEASE_NOTES.md index 67ac7bcc6b9..d925996ddfe 100644 --- a/fcs/RELEASE_NOTES.md +++ b/fcs/RELEASE_NOTES.md @@ -1,3 +1,6 @@ +#### 23.0.1 + * FSharp.Compiler.Service nuget now uses net461, netstandard2.0 and FSharp.Core 4.6.2 + #### 22.0.3 * [Add entity.DeclaringEntity](https://github.com/Microsoft/visualfsharp/pull/4633), [FCS feature request](https://github.com/fsharp/FSharp.Compiler.Service/issues/830) @@ -10,7 +13,7 @@ #### 21.0.1 * Use new .NET SDK project files - * FSharp.Compiler.Service nuget now uses net45 and netstandard2.0 + * FSharp.Compiler.Service nuget now uses net461 and netstandard2.0 * FSharp.Compiler.Service netstandard2.0 now supports type providers #### 19.0.1 diff --git a/fcs/build.fsx b/fcs/build.fsx index 50735795d88..d1d575c4f76 100644 --- a/fcs/build.fsx +++ b/fcs/build.fsx @@ -31,7 +31,7 @@ let dotnetExePath = if File.Exists(pathToCli) then pathToCli else - DotNetCli.InstallDotNetSDK "2.1.504" + DotNetCli.InstallDotNetSDK "2.2.105" let runDotnet workingDir args = let result = diff --git a/fcs/docsrc/content/caches.fsx b/fcs/docsrc/content/caches.fsx index b2cd9317753..a0a198896cb 100644 --- a/fcs/docsrc/content/caches.fsx +++ b/fcs/docsrc/content/caches.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Notes on the FSharpChecker caches ================================================= diff --git a/fcs/docsrc/content/compiler.fsx b/fcs/docsrc/content/compiler.fsx index a934bc82094..c87f755ed35 100644 --- a/fcs/docsrc/content/compiler.fsx +++ b/fcs/docsrc/content/compiler.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Hosted Compiler =============== diff --git a/fcs/docsrc/content/corelib.fsx b/fcs/docsrc/content/corelib.fsx index 61c249d2ac5..4e175e95eec 100644 --- a/fcs/docsrc/content/corelib.fsx +++ b/fcs/docsrc/content/corelib.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Notes on FSharp.Core.dll ================================================= diff --git a/fcs/docsrc/content/editor.fsx b/fcs/docsrc/content/editor.fsx index 70b6abff459..b8af9d0117b 100644 --- a/fcs/docsrc/content/editor.fsx +++ b/fcs/docsrc/content/editor.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Editor services ================================== diff --git a/fcs/docsrc/content/filesystem.fsx b/fcs/docsrc/content/filesystem.fsx index 6c968803bbe..6c4d973d497 100644 --- a/fcs/docsrc/content/filesystem.fsx +++ b/fcs/docsrc/content/filesystem.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Virtualized File System ========================================== diff --git a/fcs/docsrc/content/interactive.fsx b/fcs/docsrc/content/interactive.fsx index 94a004b36fd..301f77f34e3 100644 --- a/fcs/docsrc/content/interactive.fsx +++ b/fcs/docsrc/content/interactive.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Interactive Service: Embedding F# Interactive ============================================= diff --git a/fcs/docsrc/content/ja/compiler.fsx b/fcs/docsrc/content/ja/compiler.fsx index db49ab825d0..788c715294f 100644 --- a/fcs/docsrc/content/ja/compiler.fsx +++ b/fcs/docsrc/content/ja/compiler.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** コンパイラの組み込み ==================== diff --git a/fcs/docsrc/content/ja/corelib.fsx b/fcs/docsrc/content/ja/corelib.fsx index fc47377cfaa..4dcd09e1154 100644 --- a/fcs/docsrc/content/ja/corelib.fsx +++ b/fcs/docsrc/content/ja/corelib.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** コンパイラサービス: FSharp.Core.dll についてのメモ ================================================== diff --git a/fcs/docsrc/content/ja/editor.fsx b/fcs/docsrc/content/ja/editor.fsx index 439791d3c5e..f8a33e9a75a 100644 --- a/fcs/docsrc/content/ja/editor.fsx +++ b/fcs/docsrc/content/ja/editor.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** コンパイラサービス: エディタサービス ==================================== diff --git a/fcs/docsrc/content/ja/filesystem.fsx b/fcs/docsrc/content/ja/filesystem.fsx index 453a145ebaf..6a75cb61961 100644 --- a/fcs/docsrc/content/ja/filesystem.fsx +++ b/fcs/docsrc/content/ja/filesystem.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** コンパイラサービス: ファイルシステム仮想化 ========================================== diff --git a/fcs/docsrc/content/ja/interactive.fsx b/fcs/docsrc/content/ja/interactive.fsx index c67b5f27464..59bae44f01b 100644 --- a/fcs/docsrc/content/ja/interactive.fsx +++ b/fcs/docsrc/content/ja/interactive.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** インタラクティブサービス: F# Interactiveの組み込み ================================================== diff --git a/fcs/docsrc/content/ja/project.fsx b/fcs/docsrc/content/ja/project.fsx index 0249107d9c4..8b70e3df5f7 100644 --- a/fcs/docsrc/content/ja/project.fsx +++ b/fcs/docsrc/content/ja/project.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** コンパイラサービス: プロジェクトの分析 ====================================== diff --git a/fcs/docsrc/content/ja/symbols.fsx b/fcs/docsrc/content/ja/symbols.fsx index c4a5097394e..ff62b0de6b2 100644 --- a/fcs/docsrc/content/ja/symbols.fsx +++ b/fcs/docsrc/content/ja/symbols.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** コンパイラサービス: シンボルの処理 ================================== diff --git a/fcs/docsrc/content/ja/tokenizer.fsx b/fcs/docsrc/content/ja/tokenizer.fsx index 405bdef14ad..4daf29b7ead 100644 --- a/fcs/docsrc/content/ja/tokenizer.fsx +++ b/fcs/docsrc/content/ja/tokenizer.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** コンパイラサービス:F#トークナイザを使用する ============================================ diff --git a/fcs/docsrc/content/ja/untypedtree.fsx b/fcs/docsrc/content/ja/untypedtree.fsx index 54c78975025..447e3742fff 100644 --- a/fcs/docsrc/content/ja/untypedtree.fsx +++ b/fcs/docsrc/content/ja/untypedtree.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../../artifacts/bin/fcs/net45" +#I "../../../../artifacts/bin/fcs/net461" (** コンパイラサービス:型無し構文木の処理 ====================================== diff --git a/fcs/docsrc/content/project.fsx b/fcs/docsrc/content/project.fsx index fc9439e6ad7..72bf7993f4b 100644 --- a/fcs/docsrc/content/project.fsx +++ b/fcs/docsrc/content/project.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Project Analysis ================================== @@ -324,7 +324,7 @@ into the output folder of your application by the build process. If you install using Paket or NuGet, then this will be configured for you automatically. If not, you should reference the provided `.targets` file manually in your application. This can be found in the NuGet -package at `build/net45/FSharp.Compiler.Service.ProjectCrackerTool.targets`. +package at `build/net461/FSharp.Compiler.Service.ProjectCrackerTool.targets`. The reason for this split was so the analysis of an F# project file is performed out of process, in order that the necessary assembly diff --git a/fcs/docsrc/content/queue.fsx b/fcs/docsrc/content/queue.fsx index 31ac1526d6c..ccc7ccabbff 100644 --- a/fcs/docsrc/content/queue.fsx +++ b/fcs/docsrc/content/queue.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Notes on the FSharpChecker operations queue ================================================= diff --git a/fcs/docsrc/content/react.fsx b/fcs/docsrc/content/react.fsx index 2dfa557238d..ef5ccbf4952 100644 --- a/fcs/docsrc/content/react.fsx +++ b/fcs/docsrc/content/react.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Reacting to Changes ============================================ @@ -19,7 +19,7 @@ referenced DLLs may change on disk, or referenced files may change. The ``FSharpChecker`` component from FSharp.Compiler.Service does _not_ actively "listen" to changes in the file system. However ``FSharpChecker`` _does_ repeatedly ask for time stamps from the file system which it uses to decide if recomputation is needed. -FCS doesn�t listen for changes directly - for example, it creates no ``FileWatcher`` object (and the +FCS doesn't listen for changes directly - for example, it creates no ``FileWatcher`` object (and the ``IFileSystem`` API has no ability to create such objects). This is partly for legacy reasons, and partly because some hosts forbid the creation of FileWatcher objects. @@ -33,7 +33,7 @@ stays up-to-date when changes are observed. If you want to more actively listen for changes, then you should add watchers for the files specified in the ``DependencyFiles`` property of ``FSharpCheckFileResults`` and ``FSharpCheckProjectResults``. -Here�s what you need to do: +Here�s what you need to do: * When your client notices an CHANGE event on a DependencyFile, it should schedule a refresh call to perform the ParseAndCheckFileInProject (or other operation) again. This will result in fresh FileSystem calls to compute time stamps. @@ -42,8 +42,8 @@ Here for all active projects in which the file occurs. This will result in fresh FileSystem calls to compute time stamps, and fresh calls to compute whether files exist. -* Generally clients don�t listen for DELETE events on files. Although it would be logically more consistent - to do so, in practice it�s very irritating for a "project clean" to invalidate all intellisense and +* Generally clients don�t listen for DELETE events on files. Although it would be logically more consistent + to do so, in practice it�s very irritating for a "project clean" to invalidate all intellisense and cause lots of red squiggles. Some source control tools also make a change by removing and adding files, which is best noticed as a single change event. diff --git a/fcs/docsrc/content/symbols.fsx b/fcs/docsrc/content/symbols.fsx index 60eb199f990..74701e8b73d 100644 --- a/fcs/docsrc/content/symbols.fsx +++ b/fcs/docsrc/content/symbols.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Working with symbols ============================================ diff --git a/fcs/docsrc/content/tokenizer.fsx b/fcs/docsrc/content/tokenizer.fsx index f562c8b0574..7a46a3c91f6 100644 --- a/fcs/docsrc/content/tokenizer.fsx +++ b/fcs/docsrc/content/tokenizer.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Using the F# tokenizer ========================================= diff --git a/fcs/docsrc/content/typedtree.fsx b/fcs/docsrc/content/typedtree.fsx index b5d20b4dab3..43bb55ba730 100644 --- a/fcs/docsrc/content/typedtree.fsx +++ b/fcs/docsrc/content/typedtree.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Processing typed expression tree ================================================= diff --git a/fcs/docsrc/content/untypedtree.fsx b/fcs/docsrc/content/untypedtree.fsx index 4dd89a8d8a9..959e14fb944 100644 --- a/fcs/docsrc/content/untypedtree.fsx +++ b/fcs/docsrc/content/untypedtree.fsx @@ -1,5 +1,5 @@ (*** hide ***) -#I "../../../artifacts/bin/fcs/net45" +#I "../../../artifacts/bin/fcs/net461" (** Compiler Services: Processing untyped syntax tree ================================================= diff --git a/fcs/docsrc/tools/generate.fsx b/fcs/docsrc/tools/generate.fsx index 000f25f6a47..3ef4b0a1bde 100644 --- a/fcs/docsrc/tools/generate.fsx +++ b/fcs/docsrc/tools/generate.fsx @@ -32,7 +32,7 @@ open FSharp.MetadataFormat let root = "." // Paths with template/source/output locations -let bin = __SOURCE_DIRECTORY__ @@ "../../../release/fcs/net45" +let bin = __SOURCE_DIRECTORY__ @@ "../../../release/fcs/net461" let content = __SOURCE_DIRECTORY__ @@ "../content" let output = __SOURCE_DIRECTORY__ @@ "../../../docs" let files = __SOURCE_DIRECTORY__ @@ "../files" diff --git a/fcs/docsrc/tools/generate.ja.fsx b/fcs/docsrc/tools/generate.ja.fsx index feaeb592d35..bf9f77ce99e 100644 --- a/fcs/docsrc/tools/generate.ja.fsx +++ b/fcs/docsrc/tools/generate.ja.fsx @@ -18,9 +18,9 @@ let info = // For typical project, no changes are needed below // -------------------------------------------------------------------------------------- -#I "../../packages/FSharpVSPowerTools.Core/lib/net45" +#I "../../packages/FSharpVSPowerTools.Core/lib/net461" #I "../../packages/FSharp.Formatting/lib/net40" -#I "../../packages/FSharp.Compiler.Service/lib/net45" +#I "../../packages/FSharp.Compiler.Service/lib/net461" #I "../../packages/FAKE/tools" #r "FSharpVSPowerTools.Core.dll" #r "System.Web.Razor.dll" @@ -41,7 +41,7 @@ open FSharp.MetadataFormat let root = "." // Paths with template/source/output locations -let bin = __SOURCE_DIRECTORY__ @@ "../../../release/fcs/net45" +let bin = __SOURCE_DIRECTORY__ @@ "../../../release/fcs/net461" let content = __SOURCE_DIRECTORY__ @@ "../content/ja" let outputJa = __SOURCE_DIRECTORY__ @@ "../../../docs/ja" let files = __SOURCE_DIRECTORY__ @@ "../files" diff --git a/fcs/paket.dependencies b/fcs/paket.dependencies index ccaead9f031..284a402166f 100644 --- a/fcs/paket.dependencies +++ b/fcs/paket.dependencies @@ -1,6 +1,6 @@ -framework: net45, net46 +framework: net461 source https://www.nuget.org/api/v2/ -nuget FAKE +nuget FAKE 4.64.6 nuget FSharp.Formatting diff --git a/fcs/paket.lock b/fcs/paket.lock index 1ead25b452a..908c7de8d1f 100644 --- a/fcs/paket.lock +++ b/fcs/paket.lock @@ -1,4 +1,4 @@ -RESTRICTION: || (== net45) (== net46) +RESTRICTION: == net461 NUGET remote: https://www.nuget.org/api/v2 FAKE (4.64.6) diff --git a/fcs/samples/EditorService/EditorService.fsproj b/fcs/samples/EditorService/EditorService.fsproj index 447906070f0..25795d9299c 100644 --- a/fcs/samples/EditorService/EditorService.fsproj +++ b/fcs/samples/EditorService/EditorService.fsproj @@ -2,7 +2,7 @@ - net46;netcoreapp2.0 + net461;netcoreapp2.0 true Exe false @@ -12,11 +12,11 @@ - + - + diff --git a/fcs/samples/FscExe/FscExe.fsproj b/fcs/samples/FscExe/FscExe.fsproj index b2b146913a1..a160f690d2f 100644 --- a/fcs/samples/FscExe/FscExe.fsproj +++ b/fcs/samples/FscExe/FscExe.fsproj @@ -2,7 +2,7 @@ - net46 + net461 true Exe false @@ -14,10 +14,10 @@ - + - + diff --git a/fcs/samples/FsiExe/FsiExe.fsproj b/fcs/samples/FsiExe/FsiExe.fsproj index aae2ba03182..4ce18ab142c 100644 --- a/fcs/samples/FsiExe/FsiExe.fsproj +++ b/fcs/samples/FsiExe/FsiExe.fsproj @@ -2,7 +2,7 @@ - net46 + net461 true Exe false @@ -16,10 +16,10 @@ - + - + diff --git a/fcs/samples/InteractiveService/InteractiveService.fsproj b/fcs/samples/InteractiveService/InteractiveService.fsproj index 387439fcfdd..75686578f21 100644 --- a/fcs/samples/InteractiveService/InteractiveService.fsproj +++ b/fcs/samples/InteractiveService/InteractiveService.fsproj @@ -2,7 +2,7 @@ - net46 + net461 true Exe false @@ -12,10 +12,10 @@ - + - + diff --git a/fcs/samples/Tokenizer/Tokenizer.fsproj b/fcs/samples/Tokenizer/Tokenizer.fsproj index 387439fcfdd..75686578f21 100644 --- a/fcs/samples/Tokenizer/Tokenizer.fsproj +++ b/fcs/samples/Tokenizer/Tokenizer.fsproj @@ -2,7 +2,7 @@ - net46 + net461 true Exe false @@ -12,10 +12,10 @@ - + - + diff --git a/fcs/samples/UntypedTree/UntypedTree.fsproj b/fcs/samples/UntypedTree/UntypedTree.fsproj index 387439fcfdd..75686578f21 100644 --- a/fcs/samples/UntypedTree/UntypedTree.fsproj +++ b/fcs/samples/UntypedTree/UntypedTree.fsproj @@ -2,7 +2,7 @@ - net46 + net461 true Exe false @@ -12,10 +12,10 @@ - + - + diff --git a/src/absil/illib.fs b/src/absil/illib.fs index da0b39dfb1c..b05bcab5640 100644 --- a/src/absil/illib.fs +++ b/src/absil/illib.fs @@ -488,20 +488,12 @@ module ResizeArray = /// in order to prevent long-term storage of those values chunkBySize maxArrayItemCount f inp - -/// Because FSharp.Compiler.Service is a library that will target FSharp.Core 4.5.2 for the forseeable future, -/// we need to stick these functions in this module rather than using the module functions for ValueOption -/// that come after FSharp.Core 4.5.2. module ValueOptionInternal = let inline ofOption x = match x with Some x -> ValueSome x | None -> ValueNone let inline bind f x = match x with ValueSome x -> f x | ValueNone -> ValueNone - let inline isSome x = match x with ValueSome _ -> true | ValueNone -> false - - let inline isNone x = match x with ValueSome _ -> false | ValueNone -> true - type String with member inline x.StartsWithOrdinal(value) = x.StartsWith(value, StringComparison.Ordinal) diff --git a/src/fsharp/NameResolution.fs b/src/fsharp/NameResolution.fs index ff9dbbe52e2..872109989a7 100644 --- a/src/fsharp/NameResolution.fs +++ b/src/fsharp/NameResolution.fs @@ -1100,7 +1100,7 @@ let AddEntityForProvidedType (amap: Import.ImportMap, modref: ModuleOrNamespaceR let tycon = Construct.NewProvidedTycon(resolutionEnvironment, st, importProvidedType, isSuppressRelocate, m) modref.ModuleOrNamespaceType.AddProvidedTypeEntity(tycon) let tcref = modref.NestedTyconRef tycon - System.Diagnostics.Debug.Assert(ValueOptionInternal.isSome modref.TryDeref) + System.Diagnostics.Debug.Assert(modref.TryDeref.IsSome) tcref diff --git a/src/fsharp/Optimizer.fs b/src/fsharp/Optimizer.fs index 250fda33d06..769c3e5c4ae 100644 --- a/src/fsharp/Optimizer.fs +++ b/src/fsharp/Optimizer.fs @@ -3187,7 +3187,7 @@ and OptimizeBinding cenv isRec env (TBind(vref, expr, spBind)) = | None -> false | Some mbrTyconRef -> // Check we can deref system_MarshalByRefObject_tcref. When compiling against the Silverlight mscorlib we can't - if ValueOptionInternal.isSome mbrTyconRef.TryDeref then + if mbrTyconRef.TryDeref.IsSome then // Check if this is a subtype of MarshalByRefObject assert (cenv.g.system_MarshalByRefObject_ty.IsSome) ExistsSameHeadTypeInHierarchy cenv.g cenv.amap vref.Range (generalizedTyconRef tcref) cenv.g.system_MarshalByRefObject_ty.Value diff --git a/src/fsharp/QuotationTranslator.fs b/src/fsharp/QuotationTranslator.fs index 6166906244f..cd71d0b7598 100644 --- a/src/fsharp/QuotationTranslator.fs +++ b/src/fsharp/QuotationTranslator.fs @@ -66,7 +66,7 @@ type QuotationGenerationScope = static member ComputeQuotationFormat g = let deserializeExValRef = ValRefForIntrinsic g.deserialize_quoted_FSharp_40_plus_info - if ValueOptionInternal.isSome deserializeExValRef.TryDeref then + if deserializeExValRef.TryDeref.IsSome then QuotationSerializationFormat.FSharp_40_Plus else QuotationSerializationFormat.FSharp_20_Plus diff --git a/src/fsharp/symbols/Symbols.fs b/src/fsharp/symbols/Symbols.fs index 7adcdfbee4e..e55e073e07e 100644 --- a/src/fsharp/symbols/Symbols.fs +++ b/src/fsharp/symbols/Symbols.fs @@ -86,7 +86,7 @@ module Impl = let entityIsUnresolved(entity:EntityRef) = match entity with | ERefNonLocal(NonLocalEntityRef(ccu, _)) -> - ccu.IsUnresolvedReference && ValueOptionInternal.isNone entity.TryDeref + ccu.IsUnresolvedReference && entity.TryDeref.IsNone | _ -> false let checkEntityIsResolved(entity:EntityRef) = @@ -759,11 +759,11 @@ and FSharpUnionCase(cenv, v: UnionCaseRef) = let isUnresolved() = - entityIsUnresolved v.TyconRef || ValueOptionInternal.isNone v.TryUnionCase + entityIsUnresolved v.TyconRef || v.TryUnionCase.IsNone let checkIsResolved() = checkEntityIsResolved v.TyconRef - if ValueOptionInternal.isNone v.TryUnionCase then + if v.TryUnionCase.IsNone then invalidOp (sprintf "The union case '%s' could not be found in the target type" v.CaseName) member __.IsUnresolved = @@ -878,8 +878,8 @@ and FSharpField(cenv: SymbolEnv, d: FSharpFieldData) = d.TryDeclaringTyconRef |> Option.exists entityIsUnresolved || match d with | AnonField _ -> false - | RecdOrClass v -> ValueOptionInternal.isNone v.TryRecdField - | Union (v, _) -> ValueOptionInternal.isNone v.TryUnionCase + | RecdOrClass v -> v.TryRecdField.IsNone + | Union (v, _) -> v.TryUnionCase.IsNone | ILField _ -> false let checkIsResolved() = @@ -887,10 +887,10 @@ and FSharpField(cenv: SymbolEnv, d: FSharpFieldData) = match d with | AnonField _ -> () | RecdOrClass v -> - if ValueOptionInternal.isNone v.TryRecdField then + if v.TryRecdField.IsNone then invalidOp (sprintf "The record field '%s' could not be found in the target type" v.FieldName) | Union (v, _) -> - if ValueOptionInternal.isNone v.TryUnionCase then + if v.TryUnionCase.IsNone then invalidOp (sprintf "The union case '%s' could not be found in the target type" v.CaseName) | ILField _ -> () @@ -1382,7 +1382,7 @@ and FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item) = let isUnresolved() = match fsharpInfo() with | None -> false - | Some v -> ValueOptionInternal.isNone v.TryDeref + | Some v -> v.TryDeref.IsNone let checkIsResolved() = if isUnresolved() then diff --git a/src/fsharp/tast.fs b/src/fsharp/tast.fs index 687c81ce145..766bff82f6b 100644 --- a/src/fsharp/tast.fs +++ b/src/fsharp/tast.fs @@ -3309,7 +3309,7 @@ and ValueSome tcr.binding /// Is the destination assembly available? - member tcr.CanDeref = ValueOptionInternal.isSome tcr.TryDeref + member tcr.CanDeref = tcr.TryDeref.IsSome /// Gets the data indicating the compiled representation of a type or module in terms of Abstract IL data structures. member x.CompiledRepresentation = x.Deref.CompiledRepresentation @@ -3860,7 +3860,9 @@ and | None -> error(InternalError(sprintf "union case %s not found in type %s" x.CaseName x.TyconRef.LogicalName, x.TyconRef.Range)) /// Try to dereference the reference - member x.TryUnionCase = x.TyconRef.TryDeref |> ValueOptionInternal.bind (fun tcref -> tcref.GetUnionCaseByName x.CaseName |> ValueOptionInternal.ofOption) + member x.TryUnionCase = + x.TyconRef.TryDeref + |> ValueOptionInternal.bind (fun tcref -> tcref.GetUnionCaseByName x.CaseName |> ValueOptionInternal.ofOption) /// Get the attributes associated with the union case member x.Attribs = x.UnionCase.Attribs @@ -3919,7 +3921,9 @@ and | None -> error(InternalError(sprintf "field %s not found in type %s" id tcref.LogicalName, tcref.Range)) /// Try to dereference the reference - member x.TryRecdField = x.TyconRef.TryDeref |> ValueOptionInternal.bind (fun tcref -> tcref.GetFieldByName x.FieldName |> ValueOptionInternal.ofOption) + member x.TryRecdField = + x.TyconRef.TryDeref + |> ValueOptionInternal.bind (fun tcref -> tcref.GetFieldByName x.FieldName |> ValueOptionInternal.ofOption) /// Get the attributes associated with the compiled property of the record field member x.PropertyAttribs = x.RecdField.PropertyAttribs From 8dfc02febb4d9905c378447855715c00d1edc9fa Mon Sep 17 00:00:00 2001 From: Don Syme Date: Fri, 29 Mar 2019 00:57:50 +0000 Subject: [PATCH 18/27] update FsLexYacc to 8.0.1 source (by diret copy) (#6355) --- src/buildtools/fslex/fslex.fs | 114 ++++++++++++++--------------- src/buildtools/fslex/fslexast.fs | 2 +- src/buildtools/fsyacc/fsyacc.fs | 22 +++--- src/buildtools/fsyacc/fsyaccast.fs | 6 +- 4 files changed, 70 insertions(+), 74 deletions(-) diff --git a/src/buildtools/fslex/fslex.fs b/src/buildtools/fslex/fslex.fs index e35f9559143..98966fdfaf3 100644 --- a/src/buildtools/fslex/fslex.fs +++ b/src/buildtools/fslex/fslex.fs @@ -13,7 +13,7 @@ open System.Collections.Generic open System.IO //------------------------------------------------------------------ -// This code is duplicated from FSharp.Compiler.UnicodeLexing +// This code is duplicated from Microsoft.FSharp.Compiler.UnicodeLexing type Lexbuf = LexBuffer @@ -32,7 +32,7 @@ let UnicodeFileAsLexbuf (filename,codePage : int option) : FileStream * StreamRe | None -> new StreamReader(stream,true) | Some n -> new StreamReader(stream,System.Text.Encoding.GetEncoding(n)) let lexbuf = LexBuffer.FromFunction(reader.Read) - lexbuf.EndPos <- Position.FirstLine(filename); + lexbuf.EndPos <- Position.FirstLine(filename) stream, reader, lexbuf //------------------------------------------------------------------ @@ -43,15 +43,15 @@ let out = ref None let inputCodePage = ref None let light = ref None -let mutable lexlib = "Microsoft.FSharp.Text.Lexing" +let mutable lexlib = "FSharp.Text.Lexing" let usage = - [ ArgInfo ("-o", ArgType.String (fun s -> out := Some s), "Name the output file."); - ArgInfo ("--codepage", ArgType.Int (fun i -> inputCodePage := Some i), "Assume input lexer specification file is encoded with the given codepage."); - ArgInfo ("--light", ArgType.Unit (fun () -> light := Some true), "(ignored)"); - ArgInfo ("--light-off", ArgType.Unit (fun () -> light := Some false), "Add #light \"off\" to the top of the generated file"); - ArgInfo ("--lexlib", ArgType.String (fun s -> lexlib <- s), "Specify the namespace for the implementation of the lexer table interpreter (default Microsoft.FSharp.Text.Lexing)"); - ArgInfo ("--unicode", ArgType.Set unicode, "Produce a lexer for use with 16-bit unicode characters."); + [ ArgInfo ("-o", ArgType.String (fun s -> out := Some s), "Name the output file.") + ArgInfo ("--codepage", ArgType.Int (fun i -> inputCodePage := Some i), "Assume input lexer specification file is encoded with the given codepage.") + ArgInfo ("--light", ArgType.Unit (fun () -> light := Some true), "(ignored)") + ArgInfo ("--light-off", ArgType.Unit (fun () -> light := Some false), "Add #light \"off\" to the top of the generated file") + ArgInfo ("--lexlib", ArgType.String (fun s -> lexlib <- s), "Specify the namespace for the implementation of the lexer table interpreter (default FSharp.Text.Lexing)") + ArgInfo ("--unicode", ArgType.Set unicode, "Produce a lexer for use with 16-bit unicode characters.") ] let _ = ArgParser.Parse(usage, (fun x -> match !input with Some _ -> failwith "more than one input given" | None -> input := Some x), "fslex ") @@ -59,16 +59,15 @@ let _ = ArgParser.Parse(usage, (fun x -> match !input with Some _ -> failwith "m let outputInt (os: TextWriter) (n:int) = os.Write(string n) let outputCodedUInt16 (os: #TextWriter) (n:int) = - os.Write n; - os.Write "us; "; + os.Write n + os.Write "us; " let sentinel = 255 * 256 + 255 let lineCount = ref 0 let cfprintfn (os: #TextWriter) fmt = Printf.kfprintf (fun () -> incr lineCount; os.WriteLine()) os fmt -[] -let main(args: string[]) = +let main() = try let filename = (match !input with Some x -> x | None -> failwith "no input given") let domain = if !unicode then "Unicode" else "Ascii" @@ -82,14 +81,14 @@ let main(args: string[]) = eprintf "%s(%d,%d): error: %s" filename lexbuf.StartPos.Line lexbuf.StartPos.Column (match e with | Failure s -> s - | _ -> e.Message); + | _ -> e.Message) exit 1 - printfn "compiling to dfas (can take a while...)"; + printfn "compiling to dfas (can take a while...)" let perRuleData, dfaNodes = AST.Compile spec let dfaNodes = dfaNodes |> List.sortBy (fun n -> n.Id) - printfn "%d states" dfaNodes.Length; - printfn "writing output"; + printfn "%d states" dfaNodes.Length + printfn "writing output" let output = match !out with @@ -99,21 +98,21 @@ let main(args: string[]) = use os = System.IO.File.CreateText output if (!light = Some(false)) || (!light = None && (Path.HasExtension(output) && Path.GetExtension(output) = ".ml")) then - cfprintfn os "#light \"off\""; + cfprintfn os "#light \"off\"" let printLinesIfCodeDefined (code,pos:Position) = if pos <> Position.Empty // If bottom code is unspecified, then position is empty. then - cfprintfn os "# %d \"%s\"" pos.Line pos.FileName; - cfprintfn os "%s" code; + cfprintfn os "# %d \"%s\"" pos.Line pos.FileName + cfprintfn os "%s" code printLinesIfCodeDefined spec.TopCode let code = fst spec.TopCode - lineCount := !lineCount + code.Replace("\r","").Split([| '\n' |]).Length; - cfprintfn os "# %d \"%s\"" !lineCount output; + lineCount := !lineCount + code.Replace("\r","").Split([| '\n' |]).Length + cfprintfn os "# %d \"%s\"" !lineCount output - cfprintfn os "let trans : uint16[] array = "; - cfprintfn os " [| "; + cfprintfn os "let trans : uint16[] array = " + cfprintfn os " [| " if !unicode then let specificUnicodeChars = GetSpecificUnicodeChars() // This emits a (numLowUnicodeChars+NumUnicodeCategories+(2*#specificUnicodeChars)+1) * #states array of encoded UInt16 values @@ -128,8 +127,8 @@ let main(args: string[]) = // // For the SpecificUnicodeChars the entries are char/next-state pairs. for state in dfaNodes do - cfprintfn os " (* State %d *)" state.Id; - fprintf os " [| "; + cfprintfn os " (* State %d *)" state.Id + fprintf os " [| " let trans = let dict = new Dictionary<_,_>() state.Transitions |> List.iter dict.Add @@ -141,15 +140,15 @@ let main(args: string[]) = outputCodedUInt16 os sentinel for i = 0 to numLowUnicodeChars-1 do let c = char i - emit (EncodeChar c); + emit (EncodeChar c) for c in specificUnicodeChars do - outputCodedUInt16 os (int c); - emit (EncodeChar c); + outputCodedUInt16 os (int c) + emit (EncodeChar c) for i = 0 to NumUnicodeCategories-1 do - emit (EncodeUnicodeCategoryIndex i); - emit Eof; + emit (EncodeUnicodeCategoryIndex i) + emit Eof cfprintfn os "|];" - done; + done else // Each row for the ASCII table has format @@ -160,8 +159,8 @@ let main(args: string[]) = // This emits a (256+1) * #states array of encoded UInt16 values for state in dfaNodes do - cfprintfn os " (* State %d *)" state.Id; - fprintf os " [|"; + cfprintfn os " (* State %d *)" state.Id + fprintf os " [|" let trans = let dict = new Dictionary<_,_>() state.Transitions |> List.iter dict.Add @@ -173,52 +172,51 @@ let main(args: string[]) = outputCodedUInt16 os sentinel for i = 0 to 255 do let c = char i - emit (EncodeChar c); - emit Eof; + emit (EncodeChar c) + emit Eof cfprintfn os "|];" - done; + done - cfprintfn os " |] "; + cfprintfn os " |] " - fprintf os "let actions : uint16[] = [|"; + fprintf os "let actions : uint16[] = [|" for state in dfaNodes do if state.Accepted.Length > 0 then outputCodedUInt16 os (snd state.Accepted.Head) else outputCodedUInt16 os sentinel - done; - cfprintfn os "|]"; - cfprintfn os "let _fslex_tables = %s.%sTables.Create(trans,actions)" lexlib domain; + done + cfprintfn os "|]" + cfprintfn os "let _fslex_tables = %s.%sTables.Create(trans,actions)" lexlib domain - cfprintfn os "let rec _fslex_dummy () = _fslex_dummy() "; + cfprintfn os "let rec _fslex_dummy () = _fslex_dummy() " // These actions push the additional start state and come first, because they are then typically inlined into later // rules. This means more tailcalls are taken as direct branches, increasing efficiency and // improving stack usage on platforms that do not take tailcalls. for ((startNode, actions),(ident,args,_)) in List.zip perRuleData spec.Rules do - cfprintfn os "(* Rule %s *)" ident; - cfprintfn os "and %s %s (lexbuf : %s.LexBuffer<_>) = _fslex_%s %s %d lexbuf" ident (String.Join(" ",Array.ofList args)) lexlib ident (String.Join(" ",Array.ofList args)) startNode.Id; - for ((startNode, actions),(ident,args,_)) in List.zip perRuleData spec.Rules do - cfprintfn os "(* Rule %s *)" ident; - cfprintfn os "and _fslex_%s %s _fslex_state lexbuf =" ident (String.Join(" ",Array.ofList args)); - cfprintfn os " match _fslex_tables.Interpret(_fslex_state,lexbuf) with" ; - actions |> Seq.iteri (fun i (code,pos) -> - cfprintfn os " | %d -> ( " i; - cfprintfn os "# %d \"%s\"" pos.Line pos.FileName; + cfprintfn os "// Rule %s" ident + cfprintfn os "and %s %s lexbuf =" ident (String.Join(" ",Array.ofList args)) + cfprintfn os " match _fslex_tables.Interpret(%d,lexbuf) with" startNode.Id + actions |> Seq.iteri (fun i (code:string, pos) -> + cfprintfn os " | %d -> ( " i + cfprintfn os "# %d \"%s\"" pos.Line pos.FileName let lines = code.Split([| '\r'; '\n' |], StringSplitOptions.RemoveEmptyEntries) for line in lines do - cfprintfn os " %s" line; - cfprintfn os "# %d \"%s\"" !lineCount output; + cfprintfn os " %s" line + cfprintfn os "# %d \"%s\"" !lineCount output cfprintfn os " )") cfprintfn os " | _ -> failwith \"%s\"" ident - cfprintfn os ""; + cfprintfn os "" printLinesIfCodeDefined spec.BottomCode - cfprintfn os "# 3000000 \"%s\"" output; - 0 + cfprintfn os "# 3000000 \"%s\"" output with e -> - eprintf "FSLEX: error FSL000: %s" (match e with Failure s -> s | e -> e.ToString()); + eprintf "FSLEX: error FSL000: %s" (match e with Failure s -> s | e -> e.ToString()) exit 1 + + +let result = main() diff --git a/src/buildtools/fslex/fslexast.fs b/src/buildtools/fslex/fslexast.fs index db9727cb970..64e914a013b 100644 --- a/src/buildtools/fslex/fslexast.fs +++ b/src/buildtools/fslex/fslexast.fs @@ -3,7 +3,7 @@ module internal FsLexYacc.FsLex.AST open System.Collections.Generic -open Microsoft.FSharp.Text +open FSharp.Text open Microsoft.FSharp.Collections open Internal.Utilities open Internal.Utilities.Text.Lexing diff --git a/src/buildtools/fsyacc/fsyacc.fs b/src/buildtools/fsyacc/fsyacc.fs index b4d0a39093e..41d816794d9 100644 --- a/src/buildtools/fsyacc/fsyacc.fs +++ b/src/buildtools/fsyacc/fsyacc.fs @@ -12,7 +12,7 @@ open FsLexYacc.FsYacc open FsLexYacc.FsYacc.AST //------------------------------------------------------------------ -// This code is duplicated from FSharp.Compiler.UnicodeLexing +// This code is duplicated from Microsoft.FSharp.Compiler.UnicodeLexing type Lexbuf = LexBuffer @@ -47,8 +47,8 @@ let compat = ref false let log = ref false let light = ref None let inputCodePage = ref None -let mutable lexlib = "Microsoft.FSharp.Text.Lexing" -let mutable parslib = "Microsoft.FSharp.Text.Parsing" +let mutable lexlib = "FSharp.Text.Lexing" +let mutable parslib = "FSharp.Text.Parsing" let usage = [ ArgInfo("-o", ArgType.String (fun s -> out := Some s), "Name the output file."); @@ -60,8 +60,8 @@ let usage = ArgInfo("--light-off", ArgType.Unit (fun () -> light := Some false), "Add #light \"off\" to the top of the generated file"); ArgInfo("--ml-compatibility", ArgType.Set compat, "Support the use of the global state from the 'Parsing' module in FSharp.PowerPack.dll."); ArgInfo("--tokens", ArgType.Set tokenize, "Simply tokenize the specification file itself."); - ArgInfo("--lexlib", ArgType.String (fun s -> lexlib <- s), "Specify the namespace for the implementation of the lexer (default: Microsoft.FSharp.Text.Lexing)"); - ArgInfo("--parslib", ArgType.String (fun s -> parslib <- s), "Specify the namespace for the implementation of the parser table interpreter (default: Microsoft.FSharp.Text.Parsing)"); + ArgInfo("--lexlib", ArgType.String (fun s -> lexlib <- s), "Specify the namespace for the implementation of the lexer (default: FSharp.Text.Lexing)"); + ArgInfo("--parslib", ArgType.String (fun s -> parslib <- s), "Specify the namespace for the implementation of the parser table interpreter (default: FSharp.Text.Parsing)"); ArgInfo("--codepage", ArgType.Int (fun i -> inputCodePage := Some i), "Assume input lexer specification file is encoded with the given codepage."); ] let _ = ArgParser.Parse(usage,(fun x -> match !input with Some _ -> failwith "more than one input given" | None -> input := Some x),"fsyacc ") @@ -523,11 +523,9 @@ let main() = logf (fun oso -> oso.Close()) -[] -let result(args: string[]) = - try - main() - 0 +let result = + try main() with e -> - eprintf "FSYACC: error FSY000: %s" (match e with Failure s -> s | e -> e.Message); - 1 + eprintf "FSYACC: error FSY000: %s" (match e with Failure s -> s | e -> e.Message); + exit 1 + diff --git a/src/buildtools/fsyacc/fsyaccast.fs b/src/buildtools/fsyacc/fsyaccast.fs index f4edc399723..deb2d3ef8a1 100644 --- a/src/buildtools/fsyacc/fsyaccast.fs +++ b/src/buildtools/fsyacc/fsyaccast.fs @@ -39,7 +39,7 @@ type Symbols = Symbol list //--------------------------------------------------------------------- // Output Raw Parser Spec AST -let StringOfSym sym = match sym with Terminal s -> "'" + s + "'" | NonTerminal s -> s +let StringOfSym sym = match sym with Terminal s -> "'" ^ s ^ "'" | NonTerminal s -> s let OutputSym os sym = fprintf os "%s" (StringOfSym sym) @@ -353,7 +353,7 @@ let CompilerLalrParserSpec logf (spec : ProcessedParserSpec) = stopWatch.Start() // Augment the grammar - let fakeStartNonTerminals = spec.StartSymbols |> List.map(fun nt -> "_start" + nt) + let fakeStartNonTerminals = spec.StartSymbols |> List.map(fun nt -> "_start"^nt) let nonTerminals = fakeStartNonTerminals@spec.NonTerminals let endOfInputTerminal = "$$" let dummyLookahead = "#" @@ -466,7 +466,7 @@ let CompilerLalrParserSpec logf (spec : ProcessedParserSpec) = let IsStartItem item0 = fakeStartNonTerminalsSet.Contains(ntIdx_of_item0 item0) let IsKernelItem item0 = (IsStartItem item0 || dotIdx_of_item0 item0 <> 0) - let StringOfSym sym = match sym with PTerminal s -> "'" + termTab.OfIndex s + "'" | PNonTerminal s -> ntTab.OfIndex s + let StringOfSym sym = match sym with PTerminal s -> "'" ^ termTab.OfIndex s ^ "'" | PNonTerminal s -> ntTab.OfIndex s let OutputSym os sym = fprintf os "%s" (StringOfSym sym) From 165b736b91173fcb37e8c92af7479d9854be21f6 Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Fri, 29 Mar 2019 10:16:28 -0700 Subject: [PATCH 19/27] Improve Portable PDB debugging in FSharp.Private.Compiler.dll (#6383) * Fix portable pdb writing * enable portable pdbs for fsharp.private.compiler.dll * feedback * Release build --- src/absil/ilwritepdb.fs | 55 ++++++++++++++----- .../FSharp.Compiler.Private.fsproj | 8 --- src/fsharp/ast.fs | 5 +- src/utils/prim-parsing.fs | 49 ++++++++++------- 4 files changed, 75 insertions(+), 42 deletions(-) diff --git a/src/absil/ilwritepdb.fs b/src/absil/ilwritepdb.fs index 09c765ed416..0ff7e74cc1c 100644 --- a/src/absil/ilwritepdb.fs +++ b/src/absil/ilwritepdb.fs @@ -369,36 +369,63 @@ let generatePortablePdb (embedAllSource: bool) (embedSourceList: string list) (s builder.WriteCompressedInteger( 0 ) builder.WriteCompressedInteger( MetadataTokens.GetRowNumber(DocumentHandle.op_Implicit(getDocumentHandle (sps.[i].Document))) ) else + //============================================================================================================================================= // Sequence-point-record - let offsetDelta = - if i > 0 then sps.[i].Offset - sps.[i - 1].Offset // delta from previous offset - else sps.[i].Offset // delta IL offset - - if i < 1 || offsetDelta <> 0 then // ILOffset must not be 0 + // Validate these with magic numbers according to the portable pdb spec Sequence point dexcription: + // https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#methoddebuginformation-table-0x31 + // + // So the spec is actually bit iffy!!!!! (More like guidelines really. ) + // It uses code similar to this to validate the values + // if (result < 0 || result >= ushort.MaxValue) // be errorfull + // Spec Says 0x10000 and value max = 0xFFFF but it can't even be = to maxvalue, and so the range is 0 .. 0xfffe inclusive + //============================================================================================================================================= + + let capValue v maxValue = + if v < 0 then 0 + elif v > maxValue then maxValue + else v + + let capOffset v = capValue v 0xfffe + let capLine v = capValue v 0x1ffffffe + let capColumn v = capValue v 0xfffe + + let offset = capOffset sps.[i].Offset + let startLine = capLine sps.[i].Line + let endLine = capLine sps.[i].EndLine + let startColumn = capColumn sps.[i].Column + let endColumn = capColumn sps.[i].EndColumn + + let offsetDelta = // delta from previous offset + if i > 0 then offset - capOffset sps.[i - 1].Offset + else offset + + if i < 1 || offsetDelta > 0 then builder.WriteCompressedInteger(offsetDelta) - if sps.[i].Line = 0xfeefee && sps.[i].EndLine = 0xfeefee then // Hidden-sequence-point-record + // Hidden-sequence-point-record + if startLine = 0xfeefee || endLine = 0xfeefee || (startColumn = 0 && endColumn = 0) + then builder.WriteCompressedInteger(0) builder.WriteCompressedInteger(0) else // Non-hidden-sequence-point-record - let deltaLines = sps.[i].EndLine - sps.[i].Line // lines + let deltaLines = endLine - startLine // lines builder.WriteCompressedInteger(deltaLines) - let deltaColumns = sps.[i].EndColumn - sps.[i].Column // Columns + let deltaColumns = endColumn - startColumn // Columns if deltaLines = 0 then builder.WriteCompressedInteger(deltaColumns) else builder.WriteCompressedSignedInteger(deltaColumns) if previousNonHiddenStartLine < 0 then // delta Start Line & Column: - builder.WriteCompressedInteger(sps.[i].Line) - builder.WriteCompressedInteger(sps.[i].Column) + builder.WriteCompressedInteger(startLine) + builder.WriteCompressedInteger(startColumn) else - builder.WriteCompressedSignedInteger(sps.[i].Line - previousNonHiddenStartLine) - builder.WriteCompressedSignedInteger(sps.[i].Column - previousNonHiddenStartColumn) + builder.WriteCompressedSignedInteger(startLine - previousNonHiddenStartLine) + builder.WriteCompressedSignedInteger(startColumn - previousNonHiddenStartColumn) - previousNonHiddenStartLine <- sps.[i].Line - previousNonHiddenStartColumn <- sps.[i].Column + previousNonHiddenStartLine <- startLine + previousNonHiddenStartColumn <- startColumn getDocumentHandle singleDocumentIndex, metadata.GetOrAddBlob(builder) diff --git a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj index 2c5f4d1abc5..2aa2ffd100f 100644 --- a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj +++ b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj @@ -14,14 +14,6 @@ $(OtherFlags) --warnon:1182 --maxerrors:20 --extraoptimizationloops:1 true true - true - true - - - - - full - false diff --git a/src/fsharp/ast.fs b/src/fsharp/ast.fs index a5068dae2d6..561900cdb80 100644 --- a/src/fsharp/ast.fs +++ b/src/fsharp/ast.fs @@ -805,7 +805,10 @@ and /// Get the syntactic range of source code covered by this construct. member e.Range = match e with - | SynExpr.Paren (range=m) + | SynExpr.Paren (_, leftParenRange, rightParenRange, r) -> + match rightParenRange with + | Some rightParenRange when leftParenRange.FileIndex <> rightParenRange.FileIndex -> leftParenRange + | _ -> r | SynExpr.Quote (range=m) | SynExpr.Const (range=m) | SynExpr.Typed (range=m) diff --git a/src/utils/prim-parsing.fs b/src/utils/prim-parsing.fs index c9ff1bb595f..9ce01bff907 100644 --- a/src/utils/prim-parsing.fs +++ b/src/utils/prim-parsing.fs @@ -361,38 +361,49 @@ module internal Implementation = #if DEBUG if Flags.debug then Console.Write("reduce popping {0} values/states, lookahead {1}", n, report haveLookahead lookaheadToken) #endif - for i = 0 to n - 1 do + // For every range to reduce merge it + for i = 0 to n - 1 do if valueStack.IsEmpty then failwith "empty symbol stack" - let topVal = valueStack.Peep() + let topVal = valueStack.Peep() // Grab topVal valueStack.Pop() stateStack.Pop() - ruleValues.[(n-i)-1] <- topVal.value - ruleStartPoss.[(n-i)-1] <- topVal.startPos - ruleEndPoss.[(n-i)-1] <- topVal.endPos - if i = 0 then lhsPos.[1] <- topVal.endPos - if i = n - 1 then lhsPos.[0] <- topVal.startPos - - // Use the lookahead token to populate the locations if the rhs is empty - if n = 0 then + + let ruleIndex = (n-i)-1 + ruleValues.[ruleIndex] <- topVal.value + ruleStartPoss.[ruleIndex] <- topVal.startPos + ruleEndPoss.[ruleIndex] <- topVal.endPos + + if i = 0 then + // Initial range + lhsPos.[0] <- topVal.startPos + lhsPos.[1] <- topVal.endPos + elif topVal.startPos.FileIndex = lhsPos.[1].FileIndex && topVal.startPos.Line <= lhsPos.[1].Line then + // Reduce range if same file as the initial end point + lhsPos.[0] <- topVal.startPos + + // Use the lookahead token to populate the locations if the rhs is empty + if n = 0 then if haveLookahead then - lhsPos.[0] <- lookaheadStartPos - lhsPos.[1] <- lookaheadEndPos + lhsPos.[0] <- lookaheadStartPos + lhsPos.[1] <- lookaheadEndPos else lhsPos.[0] <- lexbuf.StartPos lhsPos.[1] <- lexbuf.EndPos - try - // printf "reduce %d\n" prod - let redResult = reduction parseState - valueStack.Push(ValueInfo(redResult, lhsPos.[0], lhsPos.[1])) + try + // printf "reduce %d\n" prod + let redResult = reduction parseState + let valueInfo = ValueInfo(redResult, lhsPos.[0], lhsPos.[1]) + valueStack.Push(valueInfo) let currState = stateStack.Peep() let newGotoState = gotoTable.Read(int tables.productionToNonTerminalTable.[prod], currState) stateStack.Push(newGotoState) + #if DEBUG if Flags.debug then Console.WriteLine(" goto state {0}", newGotoState) #endif - with - | Accept res -> - finished <- true + with + | Accept res -> + finished <- true valueStack.Push(ValueInfo(res, lhsPos.[0], lhsPos.[1])) | RecoverableParseError -> #if DEBUG From d40409750d528e6de8fb34dd656fc624f26463d0 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Sat, 30 Mar 2019 01:07:06 -0700 Subject: [PATCH 20/27] remove PDB project hack (#6399) #6383 seems to have fixed it. --- .../FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj index 2aa2ffd100f..2117cda30c4 100644 --- a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj +++ b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj @@ -16,11 +16,6 @@ true - - - false - - $(BaseOutputPath)\$(Configuration)\$(TargetFramework) From c594473bce92d921692df3d77a935c961c4840c2 Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Sat, 30 Mar 2019 20:09:52 -0700 Subject: [PATCH 21/27] Enable readline mode for coreclr (#6401) --- FSharp.Profiles.props | 1 - src/fsharp/fsi/fsi.fs | 9 +-------- src/fsharp/fsi/fsimain.fs | 4 ---- 3 files changed, 1 insertion(+), 13 deletions(-) diff --git a/FSharp.Profiles.props b/FSharp.Profiles.props index f3e0bc12d36..534ba96c04f 100644 --- a/FSharp.Profiles.props +++ b/FSharp.Profiles.props @@ -39,7 +39,6 @@ $(DefineConstants);FX_NO_WINFORMS $(DefineConstants);FX_NO_INDENTED_TEXT_WRITER $(DefineConstants);FX_REDUCED_EXCEPTIONS - $(DefineConstants);FX_REDUCED_CONSOLE $(DefineConstants);FX_RESHAPED_REFEMIT $(DefineConstants);FX_RESHAPED_GLOBALIZATION $(DefineConstants);FX_RESHAPED_REFLECTION diff --git a/src/fsharp/fsi/fsi.fs b/src/fsharp/fsi/fsi.fs index b5341a5d64b..59c39c77b85 100644 --- a/src/fsharp/fsi/fsi.fs +++ b/src/fsharp/fsi/fsi.fs @@ -586,12 +586,9 @@ let internal directoryName (s:string) = /// Process the command line options type internal FsiCommandLineOptions(fsi: FsiEvaluationSessionHostConfig, argv: string[], tcConfigB, fsiConsoleOutput: FsiConsoleOutput) = let mutable enableConsoleKeyProcessing = -#if FX_REDUCED_CONSOLE - false -#else // Mono on Win32 doesn't implement correct console processing not (runningOnMono && System.Environment.OSVersion.Platform = System.PlatformID.Win32NT) -#endif + let mutable gui = not runningOnMono // override via "--gui", on by default except when on Mono #if DEBUG let mutable showILCode = false // show modul il code @@ -1346,10 +1343,8 @@ module internal NativeMethods = type ControlEventHandler = delegate of int -> bool -#if !FX_REDUCED_CONSOLE [] extern bool SetConsoleCtrlHandler(ControlEventHandler _callback,bool _add) -#endif // One strange case: when a TAE happens a strange thing // occurs the next read from stdin always returns @@ -2398,7 +2393,6 @@ type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], i let timeReporter = FsiTimeReporter(outWriter) -#if !FX_REDUCED_CONSOLE //---------------------------------------------------------------------------- // Console coloring //---------------------------------------------------------------------------- @@ -2406,7 +2400,6 @@ type FsiEvaluationSession (fsi: FsiEvaluationSessionHostConfig, argv:string[], i // Testing shows "console coloring" is broken on some Mono configurations (e.g. Mono 2.4 Suse LiveCD). // To support fsi usage, the console coloring is switched off by default on Mono. do if runningOnMono then enableConsoleColoring <- false -#endif //---------------------------------------------------------------------------- diff --git a/src/fsharp/fsi/fsimain.fs b/src/fsharp/fsi/fsimain.fs index 8bb27f1c63e..56ab81077cb 100644 --- a/src/fsharp/fsi/fsimain.fs +++ b/src/fsharp/fsi/fsimain.fs @@ -156,16 +156,12 @@ let evaluateSession(argv: string[]) = Console.ReadKey() |> ignore #endif -#if !FX_REDUCED_CONSOLE // When VFSI is running, set the input/output encoding to UTF8. // Otherwise, unicode gets lost during redirection. // It is required only under Net4.5 or above (with unicode console feature). if argv |> Array.exists (fun x -> x.Contains "fsi-server") then Console.InputEncoding <- System.Text.Encoding.UTF8 Console.OutputEncoding <- System.Text.Encoding.UTF8 -#else - ignore argv -#endif try // Create the console reader From 132af3e939f80dd1e175e43d157b5e1f8a897112 Mon Sep 17 00:00:00 2001 From: Will Smith Date: Sat, 30 Mar 2019 20:10:29 -0700 Subject: [PATCH 22/27] Making ILVersionInfo a struct (#6392) * Making ILVersionInfo a struct * Fixing tests --- src/absil/il.fs | 37 ++++++++------ src/absil/il.fsi | 10 +++- src/absil/ilprint.fs | 10 ++-- src/absil/ilread.fs | 14 +++--- src/absil/ilreflect.fs | 4 +- src/absil/ilwrite.fs | 23 ++++----- src/fsharp/TastOps.fs | 14 +++--- src/fsharp/TastPickle.fs | 6 ++- src/fsharp/fsc.fs | 14 +++--- .../ProductVersion.fs | 50 +++++++++---------- 10 files changed, 100 insertions(+), 82 deletions(-) diff --git a/src/absil/il.fs b/src/absil/il.fs index 751e21f64de..5f648282107 100644 --- a/src/absil/il.fs +++ b/src/absil/il.fs @@ -319,7 +319,16 @@ let sha1HashInt64 s = SHA1.sha1HashInt64 s // // -------------------------------------------------------------------- -type ILVersionInfo = uint16 * uint16 * uint16 * uint16 +[] +type ILVersionInfo = + + val Major: uint16 + val Minor: uint16 + val Build: uint16 + val Revision: uint16 + + new(major, minor, build, revision) = + { Major = major; Minor = minor; Build = build; Revision = revision } type Locale = string @@ -410,7 +419,7 @@ type ILAssemblyRef(data) = let version = match aname.Version with | null -> None - | v -> Some (uint16 v.Major, uint16 v.Minor, uint16 v.Build, uint16 v.Revision) + | v -> Some (ILVersionInfo (uint16 v.Major, uint16 v.Minor, uint16 v.Build, uint16 v.Revision)) let retargetable = aname.Flags = System.Reflection.AssemblyNameFlags.Retargetable @@ -423,15 +432,15 @@ type ILAssemblyRef(data) = add(aref.Name) match aref.Version with | None -> () - | Some (a, b, c, d) -> + | Some (version) -> add ", Version=" - add (string (int a)) + add (string (int version.Major)) add "." - add (string (int b)) + add (string (int version.Minor)) add "." - add (string (int c)) + add (string (int version.Build)) add "." - add (string (int d)) + add (string (int version.Revision)) add ", Culture=" match aref.Locale with | None -> add "neutral" @@ -3559,7 +3568,7 @@ let et_MVAR = 0x1Euy let et_CMOD_REQD = 0x1Fuy let et_CMOD_OPT = 0x20uy -let formatILVersion ((a, b, c, d):ILVersionInfo) = sprintf "%d.%d.%d.%d" (int a) (int b) (int c) (int d) +let formatILVersion (version: ILVersionInfo) = sprintf "%d.%d.%d.%d" (int version.Major) (int version.Minor) (int version.Build) (int version.Revision) let encodeCustomAttrString s = let arr = string_as_utf8_bytes s @@ -4249,17 +4258,17 @@ let parseILVersion (vstr : string) = let zero32 n = if n < 0 then 0us else uint16(n) // since the minor revision will be -1 if none is specified, we need to truncate to 0 to not break existing code let minorRevision = if version.Revision = -1 then 0us else uint16(version.MinorRevision) - (zero32 version.Major, zero32 version.Minor, zero32 version.Build, minorRevision) + ILVersionInfo(zero32 version.Major, zero32 version.Minor, zero32 version.Build, minorRevision) -let compareILVersions (a1, a2, a3, a4) ((b1, b2, b3, b4) : ILVersionInfo) = - let c = compare a1 b1 +let compareILVersions (version1 : ILVersionInfo) (version2 : ILVersionInfo) = + let c = compare version1.Major version2.Major if c <> 0 then c else - let c = compare a2 b2 + let c = compare version1.Minor version2.Minor if c <> 0 then c else - let c = compare a3 b3 + let c = compare version1.Build version2.Build if c <> 0 then c else - let c = compare a4 b4 + let c = compare version1.Revision version2.Revision if c <> 0 then c else 0 diff --git a/src/absil/il.fsi b/src/absil/il.fsi index 81ea5622514..87fd66932a6 100644 --- a/src/absil/il.fsi +++ b/src/absil/il.fsi @@ -53,7 +53,15 @@ type PublicKey = member KeyToken: byte[] static member KeyAsToken: byte[] -> PublicKey -type ILVersionInfo = uint16 * uint16 * uint16 * uint16 +[] +type ILVersionInfo = + + val Major: uint16 + val Minor: uint16 + val Build: uint16 + val Revision: uint16 + + new : major: uint16 * minor: uint16 * build: uint16 * revision: uint16 -> ILVersionInfo [] type ILAssemblyRef = diff --git a/src/absil/ilprint.fs b/src/absil/ilprint.fs index 5614522f02b..511d2f9e885 100644 --- a/src/absil/ilprint.fs +++ b/src/absil/ilprint.fs @@ -982,15 +982,15 @@ and goutput_lambdas env os lambdas = and goutput_tdefs contents enc env os (td: ILTypeDefs) = List.iter (goutput_tdef enc env contents os) td.AsList -let output_ver os (a,b,c,d) = +let output_ver os (version: ILVersionInfo) = output_string os " .ver " - output_u16 os a + output_u16 os version.Major output_string os " : " - output_u16 os b + output_u16 os version.Minor output_string os " : " - output_u16 os c + output_u16 os version.Build output_string os " : " - output_u16 os d + output_u16 os version.Revision let output_locale os s = output_string os " .Locale "; output_qstring os s diff --git a/src/absil/ilread.fs b/src/absil/ilread.fs index 165f97948dd..e2cf38f107f 100644 --- a/src/absil/ilread.fs +++ b/src/absil/ilread.fs @@ -1667,7 +1667,7 @@ and seekReadAssemblyManifest (ctxt: ILMetadataReader) pectxt idx = AuxModuleHashAlgorithm=hash SecurityDeclsStored= ctxt.securityDeclsReader_Assembly PublicKey= pubkey - Version= Some (v1, v2, v3, v4) + Version= Some (ILVersionInfo (v1, v2, v3, v4)) Locale= readStringHeapOption ctxt localeIdx CustomAttrsStored = ctxt.customAttrsReader_Assembly MetadataIndex = idx @@ -1700,12 +1700,12 @@ and seekReadAssemblyRefUncached ctxtH idx = | Some blob -> Some (if (flags &&& 0x0001) <> 0x0 then PublicKey blob else PublicKeyToken blob) ILAssemblyRef.Create - (name=nm, - hash=readBlobHeapOption ctxt hashValueIdx, - publicKey=publicKey, - retargetable=((flags &&& 0x0100) <> 0x0), - version=Some(v1, v2, v3, v4), - locale=readStringHeapOption ctxt localeIdx) + (name = nm, + hash = readBlobHeapOption ctxt hashValueIdx, + publicKey = publicKey, + retargetable = ((flags &&& 0x0100) <> 0x0), + version = Some (ILVersionInfo (v1, v2, v3, v4)), + locale = readStringHeapOption ctxt localeIdx) and seekReadModuleRef (ctxt: ILMetadataReader) mdv idx = let (nameIdx) = seekReadModuleRefRow ctxt mdv idx diff --git a/src/absil/ilreflect.fs b/src/absil/ilreflect.fs index 474997be4e7..8c4b895fdb8 100644 --- a/src/absil/ilreflect.fs +++ b/src/absil/ilreflect.fs @@ -310,8 +310,8 @@ let convAssemblyRef (aref: ILAssemblyRef) = | None -> () | Some (PublicKey bytes) -> asmName.SetPublicKey(bytes) | Some (PublicKeyToken bytes) -> asmName.SetPublicKeyToken(bytes)) - let setVersion (major, minor, build, rev) = - asmName.Version <- System.Version (int32 major, int32 minor, int32 build, int32 rev) + let setVersion (version: ILVersionInfo) = + asmName.Version <- System.Version (int32 version.Major, int32 version.Minor, int32 version.Build, int32 version.Revision) Option.iter setVersion aref.Version // asmName.ProcessorArchitecture <- System.Reflection.ProcessorArchitecture.MSIL #if !FX_RESHAPED_GLOBALIZATION diff --git a/src/absil/ilwrite.fs b/src/absil/ilwrite.fs index a8b879ce2b4..b684c308f2a 100644 --- a/src/absil/ilwrite.fs +++ b/src/absil/ilwrite.fs @@ -709,10 +709,10 @@ let rec GetIdxForTypeDef cenv key = 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), - (match aref.Version with None -> 0us | Some (_, _, z, _) -> z), - (match aref.Version with None -> 0us | Some (_, _, _, w) -> w), + ((match aref.Version with None -> 0us | Some (version) -> version.Major), + (match aref.Version with None -> 0us | Some (version) -> version.Minor), + (match aref.Version with None -> 0us | Some (version) -> version.Build), + (match aref.Version with None -> 0us | Some (version) -> version.Revision), ((match aref.PublicKey with Some (PublicKey _) -> 0x0001 | _ -> 0x0000) ||| (if aref.Retargetable then 0x0100 else 0x0000)), BlobIndex (match aref.PublicKey with @@ -2822,10 +2822,10 @@ and GenExportedTypesPass3 cenv (ce: ILExportedTypesAndForwarders) = and GetManifsetAsAssemblyRow cenv m = UnsharedRow [|ULong m.AuxModuleHashAlgorithm - UShort (match m.Version with None -> 0us | Some (x, _, _, _) -> x) - UShort (match m.Version with None -> 0us | Some (_, y, _, _) -> y) - UShort (match m.Version with None -> 0us | Some (_, _, z, _) -> z) - UShort (match m.Version with None -> 0us | Some (_, _, _, w) -> w) + UShort (match m.Version with None -> 0us | Some (version) -> version.Major) + UShort (match m.Version with None -> 0us | Some (version) -> version.Minor) + UShort (match m.Version with None -> 0us | Some (version) -> version.Build) + UShort (match m.Version with None -> 0us | Some (version) -> version.Revision) ULong ( (match m.AssemblyLongevity with | ILAssemblyLongevity.Unspecified -> 0x0000 @@ -3091,9 +3091,8 @@ let writeILMetadataAndCode (generatePdb, desiredMetadataVersion, ilg, emitTailca let (mdtableVersionMajor, mdtableVersionMinor) = metadataSchemaVersionSupportedByCLRVersion desiredMetadataVersion - let version = - let (a, b, c, _) = desiredMetadataVersion - System.Text.Encoding.UTF8.GetBytes (sprintf "v%d.%d.%d" a b c) + let version = + System.Text.Encoding.UTF8.GetBytes (sprintf "v%d.%d.%d" desiredMetadataVersion.Major desiredMetadataVersion.Minor desiredMetadataVersion.Build) let paddedVersionLength = align 0x4 (Array.length version) @@ -3634,7 +3633,7 @@ let writeBinaryAndReportMappings (outfile, | ILScopeRef.Module(_) -> failwith "Expected mscorlib to be ILScopeRef.Assembly was ILScopeRef.Module" | ILScopeRef.Assembly(aref) -> match aref.Version with - | Some (2us, _, _, _) -> parseILVersion "2.0.50727.0" + | Some (version) when version.Major = 2us -> parseILVersion "2.0.50727.0" | Some v -> v | None -> failwith "Expected msorlib to have a version number" diff --git a/src/fsharp/TastOps.fs b/src/fsharp/TastOps.fs index cb5050592d3..df39365b1de 100644 --- a/src/fsharp/TastOps.fs +++ b/src/fsharp/TastOps.fs @@ -7004,13 +7004,13 @@ 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) (version: ILVersionInfo) = mkILCustomAttribute g.ilg (tref_SignatureDataVersionAttr(), [g.ilg.typ_Int32;g.ilg.typ_Int32;g.ilg.typ_Int32], - [ILAttribElem.Int32 (int32 v1) - ILAttribElem.Int32 (int32 v2) - ILAttribElem.Int32 (int32 v3)], []) + [ILAttribElem.Int32 (int32 version.Major) + ILAttribElem.Int32 (int32 version.Minor) + ILAttribElem.Int32 (int32 version.Build)], []) let tname_AutoOpenAttr = FSharpLib.Core + ".AutoOpenAttribute" @@ -7040,11 +7040,11 @@ let TryFindInternalsVisibleToAttr ilg cattr = else None -let IsMatchingSignatureDataVersionAttr ilg ((v1, v2, v3, _) : ILVersionInfo) cattr = +let IsMatchingSignatureDataVersionAttr ilg (version: ILVersionInfo) cattr = IsSignatureDataVersionAttr cattr && match decodeILAttribData ilg cattr with - | [ILAttribElem.Int32 u1; ILAttribElem.Int32 u2;ILAttribElem.Int32 u3 ], _ -> - (v1 = uint16 u1) && (v2 = uint16 u2) && (v3 = uint16 u3) + | [ILAttribElem.Int32 u1; ILAttribElem.Int32 u2;ILAttribElem.Int32 u3 ], _ -> + (version.Major = uint16 u1) && (version.Minor = uint16 u2) && (version.Build = uint16 u3) | _ -> warning(Failure(FSComp.SR.tastUnexpectedDecodeOfInterfaceDataVersionAttribute())) false diff --git a/src/fsharp/TastPickle.fs b/src/fsharp/TastPickle.fs index 8e210613e65..d1b44c792f8 100755 --- a/src/fsharp/TastPickle.fs +++ b/src/fsharp/TastPickle.fs @@ -903,7 +903,7 @@ let p_ILPublicKey x st = | PublicKey b -> p_byte 0 st; p_bytes b st | PublicKeyToken b -> p_byte 1 st; p_bytes b st -let p_ILVersion x st = p_tup4 p_uint16 p_uint16 p_uint16 p_uint16 x st +let p_ILVersion (x: ILVersionInfo) st = p_tup4 p_uint16 p_uint16 p_uint16 p_uint16 (x.Major, x.Minor, x.Build, x.Revision) st let p_ILModuleRef (x: ILModuleRef) st = p_tup3 p_string p_bool (p_option p_bytes) (x.Name, x.HasMetadata, x.Hash) st @@ -926,7 +926,9 @@ let u_ILPublicKey st = | 1 -> u_bytes st |> PublicKeyToken | _ -> ufailwith st "u_ILPublicKey" -let u_ILVersion st = u_tup4 u_uint16 u_uint16 u_uint16 u_uint16 st +let u_ILVersion st = + let (major, minor, build, revision) = u_tup4 u_uint16 u_uint16 u_uint16 u_uint16 st + ILVersionInfo(major, minor, build, revision) let u_ILModuleRef st = let (a, b, c) = u_tup3 u_string u_bool (u_option u_bytes) st diff --git a/src/fsharp/fsc.fs b/src/fsharp/fsc.fs index f88d7789ee5..1babf797800 100644 --- a/src/fsharp/fsc.fs +++ b/src/fsharp/fsc.fs @@ -533,18 +533,18 @@ module VersionResourceFormat = for child in children do yield! child |] - let Version((v1, v2, v3, v4):ILVersionInfo) = + let Version(version: ILVersionInfo) = [| // DWORD dwFileVersionMS // Specifies the most significant 32 bits of the file's binary // version number. This member is used with dwFileVersionLS to form a 64-bit value used // for numeric comparisons. - yield! i32 (int32 v1 <<< 16 ||| int32 v2) + yield! i32 (int32 version.Major <<< 16 ||| int32 version.Minor) // DWORD dwFileVersionLS // Specifies the least significant 32 bits of the file's binary // version number. This member is used with dwFileVersionMS to form a 64-bit value used // for numeric comparisons. - yield! i32 (int32 v3 <<< 16 ||| int32 v4) + yield! i32 (int32 version.Build <<< 16 ||| int32 version.Revision) |] let String(string, value) = @@ -824,7 +824,7 @@ module MainModuleBuilder = let productVersion findStringAttr (fileVersion: ILVersionInfo) = let attrName = "System.Reflection.AssemblyInformationalVersionAttribute" - let toDotted (v1, v2, v3, v4) = sprintf "%d.%d.%d.%d" v1 v2 v3 v4 + let toDotted (version: ILVersionInfo) = sprintf "%d.%d.%d.%d" version.Major version.Minor version.Build version.Revision match findStringAttr attrName with | None | Some "" -> fileVersion |> toDotted | Some (AttributeHelpers.ILVersion(v)) -> v |> toDotted @@ -840,7 +840,7 @@ module MainModuleBuilder = |> Seq.takeWhile ((<>) 0us) |> Seq.toList match validParts @ [0us; 0us; 0us; 0us] with - | major :: minor :: build :: rev :: _ -> (major, minor, build, rev) + | major :: minor :: build :: rev :: _ -> ILVersionInfo(major, minor, build, rev) | x -> failwithf "error converting product version '%s' to binary, tried '%A' " version x @@ -986,8 +986,8 @@ module MainModuleBuilder = // specify the major language, and the high-order 6 bits specify the sublanguage. // For a table of valid identifiers see Language Identifiers. // // see e.g. http://msdn.microsoft.com/en-us/library/aa912040.aspx 0000 is neutral and 04b0(hex)=1252(dec) is the code page. - [ ("000004b0", [ yield ("Assembly Version", (let v1, v2, v3, v4 = assemblyVersion in sprintf "%d.%d.%d.%d" v1 v2 v3 v4)) - yield ("FileVersion", (let v1, v2, v3, v4 = fileVersionInfo in sprintf "%d.%d.%d.%d" v1 v2 v3 v4)) + [ ("000004b0", [ yield ("Assembly Version", (sprintf "%d.%d.%d.%d" assemblyVersion.Major assemblyVersion.Minor assemblyVersion.Build assemblyVersion.Revision)) + yield ("FileVersion", (sprintf "%d.%d.%d.%d" fileVersionInfo.Major fileVersionInfo.Minor fileVersionInfo.Build fileVersionInfo.Revision)) yield ("ProductVersion", productVersionString) match tcConfig.outputFile with | Some f -> yield ("OriginalFilename", Path.GetFileName(f)) diff --git a/tests/FSharp.Compiler.UnitTests/ProductVersion.fs b/tests/FSharp.Compiler.UnitTests/ProductVersion.fs index fe95e82a977..1dbc2d19a1d 100644 --- a/tests/FSharp.Compiler.UnitTests/ProductVersion.fs +++ b/tests/FSharp.Compiler.UnitTests/ProductVersion.fs @@ -16,23 +16,23 @@ module FileVersionTest = [] let parseILVersion () = - "0.0.0.0" |> parseILVersion |> Assert.areEqual (0us,0us,0us,0us) - "1.2.3.4" |> parseILVersion |> Assert.areEqual (1us,2us,3us,4us) + "0.0.0.0" |> parseILVersion |> Assert.areEqual (ILVersionInfo(0us,0us,0us,0us)) + "1.2.3.4" |> parseILVersion |> Assert.areEqual (ILVersionInfo(1us,2us,3us,4us)) [] let ``should use AssemblyFileVersionAttribute if set`` () = let findStringAttr n = n |> Assert.areEqual fileVersionAttrName; Some "1.2.3.4" - fileVersion findStringAttr (1us,0us,0us,0us) |> Assert.areEqual (1us,2us,3us,4us) + fileVersion findStringAttr (ILVersionInfo(1us,0us,0us,0us)) |> Assert.areEqual (ILVersionInfo(1us,2us,3us,4us)) [] let ``should fallback if AssemblyFileVersionAttribute is not a valid version`` () = - fileVersion (fun _ -> Some "1.2a.3.3") (3us,7us,8us,6us) - |> Assert.areEqual (3us,7us,8us,6us) + fileVersion (fun _ -> Some "1.2a.3.3") (ILVersionInfo(3us,7us,8us,6us)) + |> Assert.areEqual (ILVersionInfo(3us,7us,8us,6us)) [] let ``should fallback to assemblyVersion if AssemblyFileVersionAttribute not set`` () = let findStringAttr n = n |> Assert.areEqual fileVersionAttrName; None; - fileVersion findStringAttr (1us,0us,0us,4us) |> Assert.areEqual (1us,0us,0us,4us) + fileVersion findStringAttr (ILVersionInfo(1us,0us,0us,4us)) |> Assert.areEqual (ILVersionInfo(1us,0us,0us,4us)) module ProductVersionTest = @@ -43,25 +43,25 @@ module ProductVersionTest = let ``should use AssemblyInformationalVersionAttribute if set`` () = let mutable args = [] let findStrAttr x = args <- List.append args [x]; Some "12.34.56.78" - productVersion findStrAttr (1us,0us,0us,6us) |> Assert.areEqual "12.34.56.78" + productVersion findStrAttr (ILVersionInfo(1us,0us,0us,6us)) |> Assert.areEqual "12.34.56.78" args |> Assert.areEqual [ informationalVersionAttrName ] [] let ``should fallback if AssemblyInformationalVersionAttribute is not a valid version`` () = - productVersion (fun _ -> Some "1.2.3-main (build #12)") (1us,0us,0us,6us) + productVersion (fun _ -> Some "1.2.3-main (build #12)") (ILVersionInfo(1us,0us,0us,6us)) |> Assert.areEqual "1.2.3-main (build #12)" [] let ``should fallback to fileVersion if AssemblyInformationalVersionAttribute not set or empty`` () = - productVersion (fun _ -> None) (3us,2us,1us,0us) |> Assert.areEqual "3.2.1.0" - productVersion (fun _ -> Some "") (3us,2us,1us,0us) |> Assert.areEqual "3.2.1.0" + productVersion (fun _ -> None) (ILVersionInfo(3us,2us,1us,0us)) |> Assert.areEqual "3.2.1.0" + productVersion (fun _ -> Some "") (ILVersionInfo(3us,2us,1us,0us)) |> Assert.areEqual "3.2.1.0" let validValues () = let max = System.UInt16.MaxValue - [ "1.2.3.4", (1us,2us,3us,4us) - "0.0.0.0", (0us,0us,0us,0us) - "3213.57843.32382.59493", (3213us,57843us,32382us,59493us) - (sprintf "%d.%d.%d.%d" max max max max), (max,max,max,max) ] + [ "1.2.3.4", ILVersionInfo(1us,2us,3us,4us) + "0.0.0.0", ILVersionInfo(0us,0us,0us,0us) + "3213.57843.32382.59493", ILVersionInfo(3213us,57843us,32382us,59493us) + (sprintf "%d.%d.%d.%d" max max max max), ILVersionInfo(max,max,max,max) ] [] let ``should use values if valid major.minor.revision.build version format`` () = @@ -69,17 +69,17 @@ module ProductVersionTest = v |> productVersionToILVersionInfo |> Assert.areEqual expected let invalidValues () = - [ "1.2.3.4", (1us,2us,3us,4us) - "1.2.3.4a", (1us,2us,3us,0us) - "1.2.c3.4", (1us,2us,0us,0us) - "1.2-d.3.4", (1us,0us,0us,0us) - "1dd.2.3.4", (0us,0us,0us,0us) - "1dd.2da.d3hj.dd4ds", (0us,0us,0us,0us) - "1.5.6.7.dasd", (1us,5us,6us,7us) - "9.3", (9us,3us,0us,0us) - "", (0us,0us,0us,0us) - "70000.80000.90000.100000", (0us,0us,0us,0us) - (sprintf "%d.70000.80000.90000" System.UInt16.MaxValue), (System.UInt16.MaxValue,0us,0us,0us) ] + [ "1.2.3.4", ILVersionInfo(1us,2us,3us,4us) + "1.2.3.4a", ILVersionInfo(1us,2us,3us,0us) + "1.2.c3.4", ILVersionInfo(1us,2us,0us,0us) + "1.2-d.3.4", ILVersionInfo(1us,0us,0us,0us) + "1dd.2.3.4", ILVersionInfo(0us,0us,0us,0us) + "1dd.2da.d3hj.dd4ds", ILVersionInfo(0us,0us,0us,0us) + "1.5.6.7.dasd", ILVersionInfo(1us,5us,6us,7us) + "9.3", ILVersionInfo(9us,3us,0us,0us) + "", ILVersionInfo(0us,0us,0us,0us) + "70000.80000.90000.100000", ILVersionInfo(0us,0us,0us,0us) + (sprintf "%d.70000.80000.90000" System.UInt16.MaxValue), ILVersionInfo(System.UInt16.MaxValue,0us,0us,0us) ] [] let ``should zero starting from first invalid version part`` () = From 0058f88769ab1585c131680eb94a33cf37a71438 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Mon, 1 Apr 2019 17:29:18 +0100 Subject: [PATCH 23/27] whitespace cleanup (#6408) * whitespace cleanup * whitespace cleanup --- src/absil/ilprint.fs | 606 ++--- src/fsharp/FSharp.Core/Linq.fs | 958 +++---- src/fsharp/FSharp.Core/Query.fs | 1990 ++++++++------- src/fsharp/FSharp.Core/array.fs | 298 +-- src/fsharp/FSharp.Core/async.fs | 10 +- src/fsharp/FSharp.Core/eventmodule.fs | 12 +- .../FSharp.Core/fslib-extra-pervasives.fs | 24 +- src/fsharp/FSharp.Core/list.fs | 330 +-- src/fsharp/FSharp.Core/local.fs | 691 +++-- src/fsharp/FSharp.Core/map.fs | 1420 ++++++----- src/fsharp/FSharp.Core/prim-types.fs | 122 +- src/fsharp/FSharp.Core/printf.fs | 483 ++-- src/fsharp/FSharp.Core/quotations.fs | 2262 +++++++++-------- src/fsharp/FSharp.Core/reflect.fs | 1179 ++++----- src/fsharp/FSharp.Core/set.fs | 1573 ++++++------ tests/scripts/codingConventions.fsx | 2 +- 16 files changed, 6184 insertions(+), 5776 deletions(-) diff --git a/src/absil/ilprint.fs b/src/absil/ilprint.fs index 511d2f9e885..e2ed4e9302e 100644 --- a/src/absil/ilprint.fs +++ b/src/absil/ilprint.fs @@ -1,15 +1,15 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. -module internal FSharp.Compiler.AbstractIL.ILAsciiWriter +module internal FSharp.Compiler.AbstractIL.ILAsciiWriter open Internal.Utilities -open FSharp.Compiler.AbstractIL -open FSharp.Compiler.AbstractIL.Internal +open FSharp.Compiler.AbstractIL +open FSharp.Compiler.AbstractIL.Internal open FSharp.Compiler.AbstractIL.Internal.Library -open FSharp.Compiler.AbstractIL.Diagnostics -open FSharp.Compiler.AbstractIL.Extensions.ILX.Types -open FSharp.Compiler.AbstractIL.Internal.AsciiConstants -open FSharp.Compiler.AbstractIL.IL +open FSharp.Compiler.AbstractIL.Diagnostics +open FSharp.Compiler.AbstractIL.Extensions.ILX.Types +open FSharp.Compiler.AbstractIL.Internal.AsciiConstants +open FSharp.Compiler.AbstractIL.IL open System.Text open System.IO @@ -18,23 +18,23 @@ open System.Reflection #if DEBUG let pretty () = true -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Pretty printing // -------------------------------------------------------------------- -let tyvar_generator = - let i = ref 0 - fun n -> +let tyvar_generator = + let i = ref 0 + fun n -> incr i; n + string !i -// Carry an environment because the way we print method variables -// depends on the gparams of the current scope. -type ppenv = +// Carry an environment because the way we print method variables +// depends on the gparams of the current scope. +type ppenv = { ilGlobals: ILGlobals ppenvClassFormals: int ppenvMethodFormals: int } -let ppenv_enter_method mgparams env = +let ppenv_enter_method mgparams env = {env with ppenvMethodFormals=mgparams} let ppenv_enter_tdef gparams env = @@ -42,40 +42,40 @@ let ppenv_enter_tdef gparams env = let mk_ppenv ilg = { ilGlobals = ilg; ppenvClassFormals = 0; ppenvMethodFormals = 0 } -let debug_ppenv = mk_ppenv +let debug_ppenv = mk_ppenv let ppenv_enter_modul env = { env with ppenvClassFormals=0; ppenvMethodFormals=0 } -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- // Pretty printing - output streams -// -------------------------------------------------------------------- +// -------------------------------------------------------------------- -let output_string (os: TextWriter) (s:string) = os.Write s +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 = +let output_hex_digit os i = assert (i >= 0 && i < 16) - if i > 9 then output_char os (char (int32 'A' + (i-10))) + if i > 9 then output_char os (char (int32 'A' + (i-10))) else output_char os (char (int32 '0' + i)) let output_qstring os s = output_char os '"' for i = 0 to String.length s - 1 do let c = String.get s i - if (c >= '\000' && c <= '\031') || (c >= '\127' && c <= '\255') then + if (c >= '\000' && c <= '\031') || (c >= '\127' && c <= '\255') then let c' = int32 c output_char os '\\' output_int os (c'/64) output_int os ((c' % 64) / 8) - output_int os (c' % 8) - else if (c = '"') then + output_int os (c' % 8) + else if (c = '"') then output_char os '\\'; output_char os '"' - else if (c = '\\') then + else if (c = '\\') then output_char os '\\'; output_char os '\\' - else + else output_char os c done output_char os '"' @@ -83,24 +83,24 @@ let output_sqstring os s = output_char os '\'' for i = 0 to String.length s - 1 do let c = s.[i] - if (c >= '\000' && c <= '\031') || (c >= '\127' && c <= '\255') then + if (c >= '\000' && c <= '\031') || (c >= '\127' && c <= '\255') then let c' = int32 c output_char os '\\' output_int os (c'/64) output_int os ((c' % 64) / 8) - output_int os (c' % 8) - else if (c = '\\') then + output_int os (c' % 8) + else if (c = '\\') then output_char os '\\'; output_char os '\\' - else if (c = '\'') then + else if (c = '\'') then output_char os '\\'; output_char os '\'' - else + else output_char os c done output_char os '\'' let output_seq sep f os (a:seq<_>) = use e = a.GetEnumerator() - if e.MoveNext() then + if e.MoveNext() then f os e.Current while e.MoveNext() do output_string os sep @@ -125,19 +125,19 @@ 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 string_of_type_name (_, n) = n -let output_byte os i = +let output_byte os i = output_hex_digit os (i / 16) output_hex_digit os (i % 16) -let output_bytes os (bytes:byte[]) = +let output_bytes os (bytes:byte[]) = for i = 0 to bytes.Length - 1 do output_byte os (Bytes.get bytes i) output_string os " " -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) @@ -151,56 +151,56 @@ 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_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_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 +let rec goutput_scoref _env os = function | ILScopeRef.Local -> () | ILScopeRef.Assembly aref -> output_string os "["; output_sqstring os aref.Name; output_string os "]" | ILScopeRef.Module mref -> - output_string os "[.module "; output_sqstring os mref.Name; output_string os "]" + output_string os "[.module "; output_sqstring os mref.Name; output_string os "]" -and goutput_type_name_ref env os (scoref,enc,n) = +and goutput_type_name_ref env os (scoref, enc, n) = goutput_scoref env os scoref output_seq "/" output_sqstring os (enc@[n]) -and goutput_tref env os (x:ILTypeRef) = - goutput_type_name_ref env os (x.Scope,x.Enclosing,x.Name) +and goutput_tref env os (x:ILTypeRef) = + goutput_type_name_ref env os (x.Scope, x.Enclosing, x.Name) and goutput_typ env os ty = - match ty with + match ty with | 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 - let mgparams = env.ppenvMethodFormals - if int tv < cgparams then + | 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 + let mgparams = env.ppenvMethodFormals + 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) - else + 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_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_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" @@ -215,7 +215,7 @@ and goutput_typ env os ty = output_string os " " goutput_gactuals env os tspec.GenericArgs | ILType.Void -> output_string os "void" - | ILType.Array (bounds,ty) -> + | ILType.Array (bounds, ty) -> goutput_typ env os ty output_string os "[" output_arr_bounds os bounds @@ -224,11 +224,11 @@ and goutput_typ env os ty = output_string os "method " goutput_typ env os csig.ReturnType output_string os " *(" - output_seq "," (goutput_typ env) os csig.ArgTypes + output_seq ", " (goutput_typ env) os csig.ArgTypes output_string os ")" | _ -> output_string os "NaT" - -and output_tyvar os d = + +and output_tyvar os d = output_u16 os d; () and goutput_ldtoken_info env os = function @@ -237,11 +237,11 @@ and goutput_ldtoken_info env os = function | ILToken.ILField x -> output_string os "field "; goutput_fspec env os x and goutput_typ_with_shortened_class_syntax env os = function - ILType.Boxed tspec when tspec.GenericArgs = [] -> + ILType.Boxed tspec when tspec.GenericArgs = [] -> goutput_tref env os tspec.TypeRef | typ2 -> goutput_typ env os typ2 -and goutput_gactuals env os inst = +and goutput_gactuals env os inst = if not (List.isEmpty inst) then output_string os "<" output_seq ", " (goutput_gactual env) os inst @@ -249,34 +249,34 @@ and goutput_gactuals env os inst = and goutput_gactual env os ty = goutput_typ env os ty -and goutput_tspec env os tspec = +and goutput_tspec env os tspec = output_string os "class " goutput_tref env os tspec.TypeRef output_string os " " goutput_gactuals env os tspec.GenericArgs -and output_arr_bounds os = function +and output_arr_bounds os = function | bounds when bounds = ILArrayShape.SingleDimensional -> () | ILArrayShape l -> - output_seq "," + output_seq ", " (fun os -> function - | (None,None) -> output_string os "" - | (None,Some sz) -> + | (None, None) -> output_string os "" + | (None, Some sz) -> output_int os sz - | (Some lower,None) -> + | (Some lower, None) -> output_int os lower output_string os " ... " - | (Some lower,Some d) -> + | (Some lower, Some d) -> output_int os lower output_string os " ... " output_int os d) - os + os l - -and goutput_permission _env os p = - let output_security_action os x = - output_string os - (match x with + +and goutput_permission _env os p = + let output_security_action os x = + output_string os + (match x with | ILSecurityAction.Request -> "request" | ILSecurityAction.Demand -> "demand" | ILSecurityAction.Assert-> "assert" @@ -291,32 +291,32 @@ and goutput_permission _env os p = | ILSecurityAction.PreJitDeny-> "prejitdeny" | ILSecurityAction.NonCasDemand-> "noncasdemand" | ILSecurityAction.NonCasLinkDemand-> "noncaslinkdemand" - | ILSecurityAction.NonCasInheritance-> "noncasinheritance" + | ILSecurityAction.NonCasInheritance-> "noncasinheritance" | ILSecurityAction.LinkDemandChoice -> "linkdemandchoice" | ILSecurityAction.InheritanceDemandChoice -> "inheritancedemandchoice" - | ILSecurityAction.DemandChoice -> "demandchoice") + | ILSecurityAction.DemandChoice -> "demandchoice") - match p with - | ILSecurityDecl (sa,b) -> + match p with + | ILSecurityDecl (sa, b) -> output_string os " .permissionset " - output_security_action os sa - output_string os " = (" - output_bytes os b - output_string os ")" - + output_security_action os sa + output_string os " = (" + output_bytes os b + output_string os ")" + and goutput_security_decls env os (ps: ILSecurityDecls) = output_seq " " (goutput_permission env) os ps.AsList -and goutput_gparam env os (gf: ILGenericParameterDef) = +and goutput_gparam env os (gf: ILGenericParameterDef) = output_string os (tyvar_generator gf.Name) - output_parens (output_seq "," (goutput_typ env)) os gf.Constraints + output_parens (output_seq ", " (goutput_typ env)) os gf.Constraints -and goutput_gparams env os b = - if not (isNil b) then - output_string os "<"; output_seq "," (goutput_gparam env) os b; output_string os ">"; () +and goutput_gparams env os b = + if not (isNil b) then + output_string os "<"; output_seq ", " (goutput_gparam env) os b; output_string os ">"; () and output_bcc os bcc = - output_string os - (match bcc with + output_string os + (match bcc with | ILArgConvention.FastCall -> "fastcall " | ILArgConvention.StdCall -> "stdcall " | ILArgConvention.ThisCall -> "thiscall " @@ -324,103 +324,103 @@ and output_bcc os bcc = | ILArgConvention.Default -> " " | ILArgConvention.VarArg -> "vararg ") -and output_callconv os (Callconv (hasthis,cc)) = - output_string os - (match hasthis with - ILThisConvention.Instance -> "instance " +and output_callconv os (Callconv (hasthis, cc)) = + output_string os + (match hasthis with + ILThisConvention.Instance -> "instance " | ILThisConvention.InstanceExplicit -> "explicit " - | ILThisConvention.Static -> "") + | ILThisConvention.Static -> "") output_bcc os cc -and goutput_dlocref env os (dref:ILType) = - match dref with - | dref when - dref.IsNominal && +and goutput_dlocref env os (dref:ILType) = + match dref with + | dref when + dref.IsNominal && isTypeNameForGlobalFunctions dref.TypeRef.Name && - dref.TypeRef.Scope = ILScopeRef.Local -> + dref.TypeRef.Scope = ILScopeRef.Local -> () - | dref when - dref.IsNominal && + | dref when + dref.IsNominal && isTypeNameForGlobalFunctions dref.TypeRef.Name -> goutput_scoref env os dref.TypeRef.Scope output_string os "::" - | ty ->goutput_typ_with_shortened_class_syntax env os ty; output_string os "::" + | ty ->goutput_typ_with_shortened_class_syntax env os ty; output_string os "::" and goutput_callsig env os (csig:ILCallingSignature) = output_callconv os csig.CallingConv output_string os " " goutput_typ env os csig.ReturnType - output_parens (output_seq "," (goutput_typ env)) os csig.ArgTypes + output_parens (output_seq ", " (goutput_typ env)) os csig.ArgTypes and goutput_mref env os (mref:ILMethodRef) = output_callconv os mref.CallingConv output_string os " " goutput_typ_with_shortened_class_syntax env os mref.ReturnType output_string os " " - // no quotes for ".ctor" - let name = mref.Name + // no quotes for ".ctor" + let name = mref.Name if name = ".ctor" || name = ".cctor" then output_string os name else output_id os name - output_parens (output_seq "," (goutput_typ env)) os mref.ArgTypes + output_parens (output_seq ", " (goutput_typ env)) os mref.ArgTypes -and goutput_mspec env os (mspec:ILMethodSpec) = - let fenv = +and goutput_mspec env os (mspec:ILMethodSpec) = + let fenv = ppenv_enter_method mspec.GenericArity - (ppenv_enter_tdef (mkILFormalTypars mspec.DeclaringType.GenericArgs) env) + (ppenv_enter_tdef (mkILFormalTypars mspec.DeclaringType.GenericArgs) env) output_callconv os mspec.CallingConv output_string os " " goutput_typ fenv os mspec.FormalReturnType output_string os " " goutput_dlocref env os mspec.DeclaringType output_string os " " - let name = mspec.Name + let name = mspec.Name if name = ".ctor" || name = ".cctor" then output_string os name else output_id os name goutput_gactuals env os mspec.GenericArgs - output_parens (output_seq "," (goutput_typ fenv)) os mspec.FormalArgTypes + output_parens (output_seq ", " (goutput_typ fenv)) os mspec.FormalArgTypes and goutput_vararg_mspec env os (mspec, varargs) = - match varargs with + match varargs with | None -> goutput_mspec env os mspec - | Some varargs' -> - let fenv = + | Some varargs' -> + let fenv = ppenv_enter_method mspec.GenericArity - (ppenv_enter_tdef (mkILFormalTypars mspec.DeclaringType.GenericArgs) env) + (ppenv_enter_tdef (mkILFormalTypars mspec.DeclaringType.GenericArgs) env) output_callconv os mspec.CallingConv output_string os " " goutput_typ fenv os mspec.FormalReturnType output_string os " " goutput_dlocref env os mspec.DeclaringType - let name = mspec.Name + let name = mspec.Name if name = ".ctor" || name = ".cctor" then output_string os name else output_id os name goutput_gactuals env os mspec.GenericArgs output_string os "(" - output_seq "," (goutput_typ fenv) os mspec.FormalArgTypes - output_string os ",...," - output_seq "," (goutput_typ fenv) os varargs' + output_seq ", " (goutput_typ fenv) os mspec.FormalArgTypes + output_string os ", ..., " + output_seq ", " (goutput_typ fenv) os varargs' output_string os ")" -and goutput_vararg_sig env os (csig:ILCallingSignature,varargs:ILVarArgs) = - match varargs with +and goutput_vararg_sig env os (csig:ILCallingSignature, varargs:ILVarArgs) = + match varargs with | None -> goutput_callsig env os csig; () - | Some varargs' -> + | Some varargs' -> goutput_typ env os csig.ReturnType output_string os " (" - let argtys = csig.ArgTypes + let argtys = csig.ArgTypes if argtys.Length <> 0 then output_seq ", " (goutput_typ env) os argtys - output_string os ",...," - output_seq "," (goutput_typ env) os varargs' + output_string os ", ..., " + output_seq ", " (goutput_typ env) os varargs' output_string os ")" and goutput_fspec env os (x:ILFieldSpec) = - let fenv = ppenv_enter_tdef (mkILFormalTypars x.DeclaringType.GenericArgs) env + let fenv = ppenv_enter_tdef (mkILFormalTypars x.DeclaringType.GenericArgs) env goutput_typ fenv os x.FormalType output_string os " " goutput_dlocref env os x.DeclaringType output_id os x.Name - -let output_member_access os access = - output_string os - (match access with + +let output_member_access os access = + output_string os + (match access with | ILMemberAccess.Public -> "public" | ILMemberAccess.Private -> "private" | ILMemberAccess.Family -> "family" @@ -429,14 +429,14 @@ let output_member_access os access = | ILMemberAccess.FamilyOrAssembly -> "famorassem" | ILMemberAccess.Assembly -> "assembly") -let output_type_access os access = - match access with +let output_type_access os access = + match access with | ILTypeDefAccess.Public -> output_string os "public" | ILTypeDefAccess.Private -> output_string os "private" | ILTypeDefAccess.Nested ilMemberAccess -> output_string os "nested "; output_member_access os ilMemberAccess -let output_encoding os e = - match e with +let output_encoding os e = + match e with | ILDefaultPInvokeEncoding.Ansi -> output_string os " ansi " | ILDefaultPInvokeEncoding.Auto -> output_string os " autochar " | ILDefaultPInvokeEncoding.Unicode -> output_string os " unicode " @@ -454,29 +454,29 @@ let output_field_init os = function | ILFieldInit.UInt64 x-> output_string os "= uint64"; output_parens output_u64 os x | ILFieldInit.Single x-> output_string os "= float32"; output_parens output_ieee32 os x | ILFieldInit.Double x-> output_string os "= float64"; output_parens output_ieee64 os x - | ILFieldInit.Null-> output_string os "= nullref" + | ILFieldInit.Null-> output_string os "= nullref" let output_at os b = Printf.fprintf os " at (* no labels for data available, data = %a *)" (output_parens output_bytes) b let output_option f os = function None -> () | Some x -> f os x - -let goutput_alternative_ref env os (alt: IlxUnionAlternative) = + +let goutput_alternative_ref env os (alt: IlxUnionAlternative) = output_id os alt.Name - alt.FieldDefs |> output_parens (output_array "," (fun os fdef -> goutput_typ env os fdef.Type)) os + alt.FieldDefs |> output_parens (output_array ", " (fun os fdef -> goutput_typ env os fdef.Type)) os -let goutput_curef env os (IlxUnionRef(_,tref,alts,_,_)) = +let goutput_curef env os (IlxUnionRef(_, tref, alts, _, _)) = output_string os " .classunion import " goutput_tref env os tref - output_parens (output_array "," (goutput_alternative_ref env)) os alts - -let goutput_cuspec env os (IlxUnionSpec(IlxUnionRef(_,tref,_,_,_),i)) = + output_parens (output_array ", " (goutput_alternative_ref env)) os alts + +let goutput_cuspec env os (IlxUnionSpec(IlxUnionRef(_, tref, _, _, _), i)) = output_string os "class /* classunion */ " goutput_tref env os tref goutput_gactuals env os i -let output_basic_type os x = - output_string os +let output_basic_type os x = + output_string os (match x with | DT_I1 -> "i1" | DT_U1 -> "u1" @@ -493,9 +493,9 @@ let output_basic_type os x = | DT_U -> "u" | DT_REF -> "ref") -let output_custom_attr_data os data = +let output_custom_attr_data os data = output_string os " = "; output_parens output_bytes os data - + let goutput_custom_attr env os (attr: ILAttribute) = output_string os " .custom " goutput_mspec env os attr.Method @@ -507,8 +507,8 @@ let goutput_custom_attrs env os (attrs : ILAttributes) = let goutput_fdef _tref env os (fd: ILFieldDef) = output_string os " .field " - match fd.Offset with Some i -> output_string os "["; output_i32 os i; output_string os "] " | None -> () - match fd.Marshal with Some _i -> output_string os "// marshal attribute not printed\n"; | None -> () + match fd.Offset with Some i -> output_string os "["; output_i32 os i; output_string os "] " | None -> () + match fd.Marshal with Some _i -> output_string os "// marshal attribute not printed\n"; | None -> () output_member_access os fd.Access output_string os " " if fd.IsStatic then output_string os " static " @@ -540,17 +540,17 @@ let output_after_tailcall os = function | Tailcall -> output_string os " ret " | _ -> () let rec goutput_apps env os = function - | Apps_tyapp (actual,cs) -> + | Apps_tyapp (actual, cs) -> output_angled (goutput_gactual env) os actual output_string os " " - output_angled (goutput_gparam env) os (mkILSimpleTypar "T") + 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 @@ -563,37 +563,37 @@ 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 -let output_code_label os lab = +let output_code_label os lab = output_string os (formatCodeLabel lab) -let goutput_local env os (l: ILLocal) = +let goutput_local env os (l: ILLocal) = goutput_typ env os l.Type if l.IsPinned then output_string os " pinned" -let goutput_param env os (l: ILParameter) = - match l.Name with +let goutput_param env os (l: ILParameter) = + match l.Name with 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 = - output_parens (output_seq "," (goutput_param env)) os ps +let goutput_params env os ps = + output_parens (output_seq ", " (goutput_param env)) os ps -let goutput_freevar env os l = - goutput_typ env os l.fvType; output_string os " "; output_sqstring os l.fvName +let goutput_freevar env os l = + goutput_typ env os l.fvType; output_string os " "; output_sqstring os l.fvName -let goutput_freevars env os ps = - output_parens (output_seq "," (goutput_freevar env)) os ps +let goutput_freevars env os ps = + output_parens (output_seq ", " (goutput_freevar env)) os ps -let output_source os (s:ILSourceMarker) = - if s.Document.File <> "" then +let output_source os (s:ILSourceMarker) = + if s.Document.File <> "" then output_string os " .line " output_int os s.Line - if s.Column <> -1 then + if s.Column <> -1 then output_string os " : " output_int os s.Column output_string os " /* - " output_int os s.EndLine - if s.Column <> -1 then + if s.Column <> -1 then output_string os " : " output_int os s.EndColumn output_string os "*/ " @@ -604,9 +604,9 @@ let rec goutput_instr env os inst = match inst with | si when isNoArgInstr si -> output_lid os (wordsOfNoArgInstr si) - | I_brcmp (cmp,tg1) -> - output_string os - (match cmp with + | I_brcmp (cmp, tg1) -> + output_string os + (match cmp with | BI_beq -> "beq" | BI_bgt -> "bgt" | BI_bgt_un -> "bgt.un" @@ -623,159 +623,159 @@ let rec goutput_instr env os inst = output_code_label os tg1 | I_br tg -> output_string os "/* br "; output_code_label os tg; output_string os "*/" | I_leave tg -> output_string os "leave "; output_code_label os tg - | I_call (tl,mspec,varargs) -> + | I_call (tl, mspec, varargs) -> output_tailness os tl output_string os "call " - goutput_vararg_mspec env os (mspec,varargs) + goutput_vararg_mspec env os (mspec, varargs) output_after_tailcall os tl - | I_calli (tl,mref,varargs) -> + | I_calli (tl, mref, varargs) -> output_tailness os tl output_string os "calli " - goutput_vararg_sig env os (mref,varargs) + goutput_vararg_sig env os (mref, varargs) output_after_tailcall os tl | I_ldarg u16 -> output_string os "ldarg"; output_short_u16 os u16 | I_ldarga u16 -> output_string os "ldarga "; output_u16 os u16 - | (AI_ldc (dt, ILConst.I4 x)) -> + | (AI_ldc (dt, ILConst.I4 x)) -> output_string os "ldc."; output_basic_type os dt; output_short_i32 os x - | (AI_ldc (dt, ILConst.I8 x)) -> + | (AI_ldc (dt, ILConst.I8 x)) -> output_string os "ldc."; output_basic_type os dt; output_string os " "; output_i64 os x - | (AI_ldc (dt, ILConst.R4 x)) -> + | (AI_ldc (dt, ILConst.R4 x)) -> output_string os "ldc."; output_basic_type os dt; output_string os " "; output_ieee32 os x - | (AI_ldc (dt, ILConst.R8 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_ldvirtftn mspec -> output_string os "ldvirtftn "; goutput_mspec env os mspec - | I_ldind (al,vol,dt) -> + | I_ldind (al, vol, dt) -> output_alignment os al output_volatility os vol output_string os "ldind." - output_basic_type os dt - | I_cpblk (al,vol) -> + output_basic_type os dt + | I_cpblk (al, vol) -> output_alignment os al output_volatility os vol output_string os "cpblk" - | I_initblk (al,vol) -> + | I_initblk (al, vol) -> output_alignment os al output_volatility os vol output_string os "initblk" | I_ldloc u16 -> output_string os "ldloc"; output_short_u16 os u16 | I_ldloca u16 -> output_string os "ldloca "; output_u16 os u16 | I_starg u16 -> output_string os "starg "; output_u16 os u16 - | I_stind (al,vol,dt) -> + | I_stind (al, vol, dt) -> output_alignment os al output_volatility os vol output_string os "stind." - output_basic_type os dt + output_basic_type os dt | I_stloc u16 -> output_string os "stloc"; output_short_u16 os u16 - | I_switch l -> output_string os "switch "; output_parens (output_seq "," output_code_label) os l - | I_callvirt (tl,mspec,varargs) -> + | I_switch l -> output_string os "switch "; output_parens (output_seq ", " output_code_label) os l + | I_callvirt (tl, mspec, varargs) -> output_tailness os tl output_string os "callvirt " - goutput_vararg_mspec env os (mspec,varargs) + goutput_vararg_mspec env os (mspec, varargs) output_after_tailcall os tl - | I_callconstraint (tl,ty,mspec,varargs) -> + | I_callconstraint (tl, ty, mspec, varargs) -> output_tailness os tl output_string os "constraint. " goutput_typ env os ty output_string os " callvirt " - goutput_vararg_mspec env os (mspec,varargs) + goutput_vararg_mspec env os (mspec, varargs) output_after_tailcall os tl | I_castclass ty -> output_string os "castclass "; goutput_typ env os ty | I_isinst ty -> output_string os "isinst "; goutput_typ env os ty - | I_ldfld (al,vol,fspec) -> + | I_ldfld (al, vol, fspec) -> output_alignment os al output_volatility os vol output_string os "ldfld " goutput_fspec env os fspec - | I_ldflda fspec -> - output_string os "ldflda " + | I_ldflda fspec -> + output_string os "ldflda " goutput_fspec env os fspec - | I_ldsfld (vol,fspec) -> + | I_ldsfld (vol, fspec) -> output_volatility os vol output_string os "ldsfld " goutput_fspec env os fspec - | I_ldsflda fspec -> + | I_ldsflda fspec -> output_string os "ldsflda " goutput_fspec env os fspec - | I_stfld (al,vol,fspec) -> + | I_stfld (al, vol, fspec) -> output_alignment os al output_volatility os vol output_string os "stfld " goutput_fspec env os fspec - | I_stsfld (vol,fspec) -> + | I_stsfld (vol, fspec) -> output_volatility os vol output_string os "stsfld " goutput_fspec env os fspec - | I_ldtoken tok -> output_string os "ldtoken "; goutput_ldtoken_info env os tok + | I_ldtoken tok -> output_string os "ldtoken "; goutput_ldtoken_info env os tok | I_refanyval ty -> output_string os "refanyval "; goutput_typ env os ty | I_refanytype -> output_string os "refanytype" | I_mkrefany typ -> output_string os "mkrefany "; goutput_typ env os typ - | I_ldstr s -> + | I_ldstr s -> output_string os "ldstr " output_string os s - | I_newobj (mspec,varargs) -> - // newobj: IL has a special rule that the CC is always implicitly "instance" and need - // not be mentioned explicitly + | I_newobj (mspec, varargs) -> + // newobj: IL has a special rule that the CC is always implicitly "instance" and need + // not be mentioned explicitly output_string os "newobj " - goutput_vararg_mspec env os (mspec,varargs) - | I_stelem dt -> output_string os "stelem."; output_basic_type os dt - | I_ldelem dt -> output_string os "ldelem."; output_basic_type os dt + goutput_vararg_mspec env os (mspec, varargs) + | I_stelem dt -> output_string os "stelem."; output_basic_type os dt + | I_ldelem dt -> output_string os "ldelem."; output_basic_type os dt - | I_newarr (shape,typ) -> - if shape = ILArrayShape.SingleDimensional then + | I_newarr (shape, typ) -> + if shape = ILArrayShape.SingleDimensional then output_string os "newarr " goutput_typ_with_shortened_class_syntax env os typ - else + else output_string os "newobj void " - goutput_dlocref env os (mkILArrTy(typ,shape)) + goutput_dlocref env os (mkILArrTy(typ, shape)) output_string os ".ctor" - let rank = shape.Rank - output_parens (output_array "," (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) - | I_stelem_any (shape,dt) -> - if shape = ILArrayShape.SingleDimensional then - output_string os "stelem.any "; goutput_typ env os dt - else + let rank = shape.Rank + output_parens (output_array ", " (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) + | I_stelem_any (shape, dt) -> + if shape = ILArrayShape.SingleDimensional then + output_string os "stelem.any "; goutput_typ env os dt + else output_string os "call instance void " - goutput_dlocref env os (mkILArrTy(dt,shape)) + goutput_dlocref env os (mkILArrTy(dt, shape)) output_string os "Set" - let rank = shape.Rank + let rank = shape.Rank let arr = Array.create (rank + 1) EcmaMscorlibILGlobals.typ_Int32 arr.[rank] <- dt - output_parens (output_array "," (goutput_typ env)) os arr - | I_ldelem_any (shape,tok) -> - if shape = ILArrayShape.SingleDimensional then - output_string os "ldelem.any "; goutput_typ env os tok - else + output_parens (output_array ", " (goutput_typ env)) os arr + | I_ldelem_any (shape, tok) -> + if shape = ILArrayShape.SingleDimensional then + output_string os "ldelem.any "; goutput_typ env os tok + else output_string os "call instance " goutput_typ env os tok output_string os " " - goutput_dlocref env os (mkILArrTy(tok,shape)) + goutput_dlocref env os (mkILArrTy(tok, shape)) output_string os "Get" - let rank = shape.Rank - output_parens (output_array "," (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) - | I_ldelema (ro,_,shape,tok) -> + let rank = shape.Rank + output_parens (output_array ", " (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) + | I_ldelema (ro, _, shape, tok) -> if ro = ReadonlyAddress then output_string os "readonly. " - if shape = ILArrayShape.SingleDimensional then - output_string os "ldelema "; goutput_typ env os tok - else + if shape = ILArrayShape.SingleDimensional then + output_string os "ldelema "; goutput_typ env os tok + else output_string os "call instance " goutput_typ env os (ILType.Byref tok) output_string os " " - goutput_dlocref env os (mkILArrTy(tok,shape)) + goutput_dlocref env os (mkILArrTy(tok, shape)) output_string os "Address" - let rank = shape.Rank - output_parens (output_array "," (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) - + let rank = shape.Rank + output_parens (output_array ", " (goutput_typ env)) os (Array.create ( rank) EcmaMscorlibILGlobals.typ_Int32) + | I_box tok -> output_string os "box "; goutput_typ env os tok | I_unbox tok -> output_string os "unbox "; goutput_typ env os tok | I_unbox_any tok -> output_string os "unbox.any "; goutput_typ env os tok | I_initobj tok -> output_string os "initobj "; goutput_typ env os tok - | I_ldobj (al,vol,tok) -> + | I_ldobj (al, vol, tok) -> output_alignment os al output_volatility os vol output_string os "ldobj " goutput_typ env os tok - | I_stobj (al,vol,tok) -> + | I_stobj (al, vol, tok) -> output_alignment os al output_volatility os vol output_string os "stobj " @@ -784,7 +784,7 @@ let rec goutput_instr env os inst = | I_sizeof tok -> output_string os "sizeof "; goutput_typ env os tok | I_seqpoint s -> output_source os s | EI_ilzero ty -> output_string os "ilzero "; goutput_typ env os ty - | _ -> + | _ -> output_string os "" @@ -793,31 +793,31 @@ let goutput_ilmbody env os (il: ILMethodBody) = output_string os " .maxstack " output_i32 os il.MaxStack output_string os "\n" - if il.Locals.Length <> 0 then + if il.Locals.Length <> 0 then output_string os " .locals(" - output_seq ",\n " (goutput_local env) os il.Locals + 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 " else output_string os "runtime " - + output_string os (if md.IsInternalCall then "internalcall " else " ") output_string os (if md.IsManaged then "managed " else " ") output_string os (if md.IsForwardRef then "forwardref " else " ") - output_string os " \n{ \n" + output_string os " \n{ \n" goutput_security_decls env os md.SecurityDecls goutput_custom_attrs env os md.CustomAttrs - match md.Body.Contents with + match md.Body.Contents with | MethodBody.IL il -> goutput_ilmbody env os il | _ -> () if is_entrypoint then output_string os " .entrypoint" output_string os "\n" output_string os "}\n" - + let goutput_mdef env os (md:ILMethodDef) = - let attrs = + let attrs = if md.IsVirtual then "virtual " + (if md.IsFinal then "final " else "") + @@ -829,18 +829,18 @@ let goutput_mdef env os (md:ILMethodDef) = elif md.IsConstructor then "rtspecialname" elif md.IsStatic then "static " + - (match md.Body.Contents with - MethodBody.PInvoke (attr) -> + (match md.Body.Contents with + MethodBody.PInvoke (attr) -> "pinvokeimpl(\"" + attr.Where.Name + "\" as \"" + attr.Name + "\"" + - (match attr.CallingConv with + (match attr.CallingConv with | PInvokeCallingConvention.None -> "" | PInvokeCallingConvention.Cdecl -> " cdecl" | PInvokeCallingConvention.Stdcall -> " stdcall" - | PInvokeCallingConvention.Thiscall -> " thiscall" + | PInvokeCallingConvention.Thiscall -> " thiscall" | PInvokeCallingConvention.Fastcall -> " fastcall" | PInvokeCallingConvention.WinApi -> " winapi" ) + - (match attr.CharEncoding with + (match attr.CharEncoding with | PInvokeCharEncoding.None -> "" | PInvokeCharEncoding.Ansi -> " ansi" | PInvokeCharEncoding.Unicode -> " unicode" @@ -849,12 +849,12 @@ let goutput_mdef env os (md:ILMethodDef) = (if attr.NoMangle then " nomangle" else "") + (if attr.LastError then " lasterr" else "") + ")" - | _ -> + | _ -> "") - elif md.IsClassInitializer then "specialname rtspecialname static" + elif md.IsClassInitializer then "specialname rtspecialname static" else "" - let is_entrypoint = md.IsEntryPoint - let menv = ppenv_enter_method (List.length md.GenericParams) env + let is_entrypoint = md.IsEntryPoint + let menv = ppenv_enter_method (List.length md.GenericParams) env output_string os " .method " if md.IsHideBySig then output_string os "hidebysig " if md.IsReqSecObj then output_string os "reqsecobj " @@ -868,7 +868,7 @@ let goutput_mdef env os (md:ILMethodDef) = output_string os " " (goutput_typ menv) os md.Return.Type output_string os " " - output_id os md.Name + output_id os md.Name output_string os " " (goutput_gparams env) os md.GenericParams output_string os " " @@ -888,19 +888,19 @@ let goutput_pdef env os (pd: ILPropertyDef) = output_string os "\n\tsetter: " (match pd.SetMethod with None -> () | Some mref -> goutput_mref env os mref) -let goutput_superclass env os = function +let goutput_superclass env os = function None -> () | Some typ -> output_string os "extends "; (goutput_typ_with_shortened_class_syntax env) os typ let goutput_superinterfaces env os imp = if not (List.isEmpty imp) then output_string os "implements " - output_seq "," (goutput_typ_with_shortened_class_syntax env) os imp + output_seq ", " (goutput_typ_with_shortened_class_syntax env) os imp let goutput_implements env os (imp:ILTypes) = if not (List.isEmpty imp) then output_string os "implements " - output_seq "," (goutput_typ_with_shortened_class_syntax env) os imp + output_seq ", " (goutput_typ_with_shortened_class_syntax env) os imp let the = function Some x -> x | None -> failwith "the" @@ -909,29 +909,29 @@ let output_type_layout_info os info = if info.Pack <> None then (output_string os " .pack "; output_u16 os (the info.Pack)) let splitTypeLayout = function - | ILTypeDefLayout.Auto -> "auto",(fun _os () -> ()) + | 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) - -let goutput_fdefs tref env os (fdefs: ILFieldDefs) = + +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) = +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) = +let goutput_pdefs env os (pdefs: ILPropertyDefs) = List.iter (fun f -> (goutput_pdef env) os f; output_string os "\n" ) pdefs.AsList let rec goutput_tdef enc env contents os (cd: ILTypeDef) = - let env = ppenv_enter_tdef cd.GenericParams env - let layout_attr,pp_layout_decls = splitTypeLayout cd.Layout - if isTypeNameForGlobalFunctions cd.Name then - if contents then - let tref = (mkILNestedTyRef (ILScopeRef.Local,enc,cd.Name)) + let env = ppenv_enter_tdef cd.GenericParams env + let layout_attr, pp_layout_decls = splitTypeLayout cd.Layout + if isTypeNameForGlobalFunctions cd.Name then + if contents then + let tref = (mkILNestedTyRef (ILScopeRef.Local, enc, cd.Name)) goutput_mdefs env os cd.Methods goutput_fdefs tref env os cd.Fields goutput_pdefs env os cd.Properties - else + else output_string os "\n" if cd.IsInterface then output_string os ".class interface " else output_string os ".class " @@ -947,15 +947,15 @@ let rec goutput_tdef enc env contents os (cd: ILTypeDef) = if cd.IsAbstract then output_string os "abstract " if cd.IsSerializable then output_string os "serializable " if cd.IsComInterop then output_string os "import " - output_sqstring os cd.Name + output_sqstring os cd.Name goutput_gparams env os cd.GenericParams output_string os "\n\t" goutput_superclass env os cd.Extends output_string os "\n\t" goutput_implements env os cd.Implements output_string os "\n{\n " - if contents then - let tref = (mkILNestedTyRef (ILScopeRef.Local,enc,cd.Name)) + if contents then + let tref = (mkILNestedTyRef (ILScopeRef.Local, enc, cd.Name)) goutput_custom_attrs env os cd.CustomAttrs goutput_security_decls env os cd.SecurityDecls pp_layout_decls os () @@ -967,18 +967,18 @@ let rec goutput_tdef enc env contents os (cd: ILTypeDef) = and output_init_semantics os f = if f &&& TypeAttributes.BeforeFieldInit <> enum 0 then output_string os "beforefieldinit" -and goutput_lambdas env os lambdas = +and goutput_lambdas env os lambdas = match lambdas with - | Lambdas_forall (gf,l) -> + | Lambdas_forall (gf, l) -> 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 | Lambdas_return typ -> output_string os "--> "; (goutput_typ env) os typ - + and goutput_tdefs contents enc env os (td: ILTypeDefs) = List.iter (goutput_tdef enc env contents os) td.AsList @@ -994,12 +994,12 @@ let output_ver os (version: ILVersionInfo) = let output_locale os s = output_string os " .Locale "; output_qstring os s -let output_hash os x = - output_string os " .hash = "; output_parens output_bytes os x -let output_publickeytoken os x = - output_string os " .publickeytoken = "; output_parens output_bytes os x -let output_publickey os x = - output_string os " .publickey = "; output_parens output_bytes os x +let output_hash os x = + output_string os " .hash = "; output_parens output_bytes os x +let output_publickeytoken os x = + output_string os " .publickeytoken = "; output_parens output_bytes os x +let output_publickey os x = + output_string os " .publickey = "; output_parens output_bytes os x let output_publickeyinfo os = function | PublicKey k -> output_publickey os k @@ -1021,29 +1021,29 @@ let output_modref os (modref:ILModuleRef) = output_sqstring os modref.Name output_option output_hash os modref.Hash -let goutput_resource env os r = +let goutput_resource env os r = output_string os " .mresource " output_string os (match r.Access with ILResourceAccess.Public -> " public " | ILResourceAccess.Private -> " private ") output_sqstring os r.Name output_string os " { " goutput_custom_attrs env os r.CustomAttrs - match r.Location with - | ILResourceLocation.LocalIn _ - | ILResourceLocation.LocalOut _ -> + match r.Location with + | ILResourceLocation.LocalIn _ + | ILResourceLocation.LocalOut _ -> output_string os " /* loc nyi */ " - | ILResourceLocation.File (mref,off) -> + | ILResourceLocation.File (mref, off) -> output_string os " .file " output_sqstring os mref.Name output_string os " at " - output_i32 os off - | ILResourceLocation.Assembly aref -> + output_i32 os off + | ILResourceLocation.Assembly aref -> output_string os " .assembly extern " output_sqstring os aref.Name output_string os " }\n " -let goutput_manifest env os m = +let goutput_manifest env os m = output_string os " .assembly " - match m.AssemblyLongevity with + match m.AssemblyLongevity with | ILAssemblyLongevity.Unspecified -> () | ILAssemblyLongevity.Library -> output_string os "library " | ILAssemblyLongevity.PlatformAppDomain -> output_string os "platformappdomain " @@ -1060,25 +1060,25 @@ let goutput_manifest env os m = let output_module_fragment_aux _refs os (ilg: ILGlobals) modul = - try + try let env = mk_ppenv ilg - let env = ppenv_enter_modul env + 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() let output_module_fragment os (ilg: ILGlobals) modul = - let refs = computeILRefs modul + let refs = computeILRefs modul output_module_fragment_aux refs os ilg modul refs -let output_module_refs os refs = +let output_module_refs os refs = List.iter (fun x -> output_assemblyRef os x; output_string os "\n") refs.AssemblyReferences List.iter (fun x -> output_modref os x; output_string os "\n") refs.ModuleReferences - -let goutput_module_manifest env os modul = + +let goutput_module_manifest env os modul = output_string os " .module "; output_sqstring os modul.Name goutput_custom_attrs env os modul.CustomAttrs output_string os " .imagebase "; output_i32 os modul.ImageBase @@ -1090,20 +1090,20 @@ let goutput_module_manifest env os modul = output_option (goutput_manifest env) os modul.Manifest let output_module os (ilg: ILGlobals) modul = - try - let refs = computeILRefs modul + try + let refs = computeILRefs modul let env = mk_ppenv ilg - let env = ppenv_enter_modul env + let env = ppenv_enter_modul env 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 #endif - - - + + + diff --git a/src/fsharp/FSharp.Core/Linq.fs b/src/fsharp/FSharp.Core/Linq.fs index 8b6b5124c4d..84802d1cd11 100644 --- a/src/fsharp/FSharp.Core/Linq.fs +++ b/src/fsharp/FSharp.Core/Linq.fs @@ -49,93 +49,101 @@ module NullableOperators = let (?<>?) (x : Nullable<'T>) (y: Nullable<'T>) = not (x ?=? y) - - let inline (?+) (x : Nullable<_>) y = if x.HasValue then Nullable(x.Value + y) else Nullable() + let inline (+?) x (y: Nullable<_>) = if y.HasValue then Nullable(x + y.Value) else Nullable() + let inline (?+?) (x : Nullable<_>) (y: Nullable<_>) = if x.HasValue && y.HasValue then Nullable(x.Value + y.Value) else Nullable() let inline (?-) (x : Nullable<_>) y = if x.HasValue then Nullable(x.Value - y) else Nullable() + let inline (-?) x (y: Nullable<_>) = if y.HasValue then Nullable(x - y.Value) else Nullable() + let inline (?-?) (x : Nullable<_>) (y: Nullable<_>) = if x.HasValue && y.HasValue then Nullable(x.Value - y.Value) else Nullable() let inline ( ?* ) (x : Nullable<_>) y = if x.HasValue then Nullable(x.Value * y) else Nullable() + let inline ( *? ) x (y: Nullable<_>) = if y.HasValue then Nullable(x * y.Value) else Nullable() + let inline ( ?*? ) (x : Nullable<_>) (y: Nullable<_>) = if x.HasValue && y.HasValue then Nullable(x.Value * y.Value) else Nullable() let inline ( ?% ) (x : Nullable<_>) y = if x.HasValue then Nullable(x.Value % y) else Nullable() + let inline ( %? ) x (y: Nullable<_>) = if y.HasValue then Nullable(x % y.Value) else Nullable() + let inline ( ?%? ) (x : Nullable<_>) (y: Nullable<_>) = if x.HasValue && y.HasValue then Nullable(x.Value % y.Value) else Nullable() let inline ( ?/ ) (x : Nullable<_>) y = if x.HasValue then Nullable(x.Value / y) else Nullable() + let inline ( /? ) x (y: Nullable<_>) = if y.HasValue then Nullable(x / y.Value) else Nullable() + let inline ( ?/? ) (x : Nullable<_>) (y: Nullable<_>) = if x.HasValue && y.HasValue then Nullable(x.Value / y.Value) else Nullable() [] [] module Nullable = - open System - - [] - let inline uint8 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.byte value.Value) else Nullable() - - [] - let inline int8 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.sbyte value.Value) else Nullable() - - [] - let inline byte (value:Nullable<_>) = if value.HasValue then Nullable(Operators.byte value.Value) else Nullable() - - [] - let inline sbyte (value:Nullable<_>) = if value.HasValue then Nullable(Operators.sbyte value.Value) else Nullable() - - [] - let inline int16 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.int16 value.Value) else Nullable() - - [] - let inline uint16 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.uint16 value.Value) else Nullable() - - [] - let inline int (value:Nullable<_>) = if value.HasValue then Nullable(Operators.int value.Value) else Nullable() - - [] - let inline enum (value:Nullable< int32 >) = if value.HasValue then Nullable(Operators.enum value.Value) else Nullable() - - [] - let inline int32 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.int32 value.Value) else Nullable() - - [] - let inline uint32 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.uint32 value.Value) else Nullable() - - [] - let inline int64 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.int64 value.Value) else Nullable() - - [] - let inline uint64 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.uint64 value.Value) else Nullable() - - [] - let inline float32 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.float32 value.Value) else Nullable() - - [] - let inline float (value:Nullable<_>) = if value.HasValue then Nullable(Operators.float value.Value) else Nullable() - - [] - let inline single (value:Nullable<_>) = if value.HasValue then Nullable(Operators.float32 value.Value) else Nullable() - - [] - let inline double (value:Nullable<_>) = if value.HasValue then Nullable(Operators.float value.Value) else Nullable() - - [] - let inline nativeint (value:Nullable<_>) = if value.HasValue then Nullable(Operators.nativeint value.Value) else Nullable() - - [] - let inline unativeint (value:Nullable<_>) = if value.HasValue then Nullable(Operators.unativeint value.Value) else Nullable() - - [] - let inline decimal (value:Nullable<_>) = if value.HasValue then Nullable(Operators.decimal value.Value) else Nullable() - - [] - let inline char (value:Nullable<_>) = if value.HasValue then Nullable(Operators.char value.Value) else Nullable() + open System + + [] + let inline uint8 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.byte value.Value) else Nullable() + + [] + let inline int8 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.sbyte value.Value) else Nullable() + + [] + let inline byte (value:Nullable<_>) = if value.HasValue then Nullable(Operators.byte value.Value) else Nullable() + + [] + let inline sbyte (value:Nullable<_>) = if value.HasValue then Nullable(Operators.sbyte value.Value) else Nullable() + + [] + let inline int16 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.int16 value.Value) else Nullable() + + [] + let inline uint16 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.uint16 value.Value) else Nullable() + + [] + let inline int (value:Nullable<_>) = if value.HasValue then Nullable(Operators.int value.Value) else Nullable() + + [] + let inline enum (value:Nullable< int32 >) = if value.HasValue then Nullable(Operators.enum value.Value) else Nullable() + + [] + let inline int32 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.int32 value.Value) else Nullable() + + [] + let inline uint32 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.uint32 value.Value) else Nullable() + + [] + let inline int64 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.int64 value.Value) else Nullable() + + [] + let inline uint64 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.uint64 value.Value) else Nullable() + + [] + let inline float32 (value:Nullable<_>) = if value.HasValue then Nullable(Operators.float32 value.Value) else Nullable() + + [] + let inline float (value:Nullable<_>) = if value.HasValue then Nullable(Operators.float value.Value) else Nullable() + + [] + let inline single (value:Nullable<_>) = if value.HasValue then Nullable(Operators.float32 value.Value) else Nullable() + + [] + let inline double (value:Nullable<_>) = if value.HasValue then Nullable(Operators.float value.Value) else Nullable() + + [] + let inline nativeint (value:Nullable<_>) = if value.HasValue then Nullable(Operators.nativeint value.Value) else Nullable() + + [] + let inline unativeint (value:Nullable<_>) = if value.HasValue then Nullable(Operators.unativeint value.Value) else Nullable() + + [] + let inline decimal (value:Nullable<_>) = if value.HasValue then Nullable(Operators.decimal value.Value) else Nullable() + + [] + let inline char (value:Nullable<_>) = if value.HasValue then Nullable(Operators.char value.Value) else Nullable() namespace Microsoft.FSharp.Linq.RuntimeHelpers @@ -162,17 +170,17 @@ open ReflectionAdapters module LeafExpressionConverter = // The following is recognized as a LINQ 'member initialization pattern' in a quotation. - let MemberInitializationHelper (_x:'T) : 'T = raise (NotSupportedException "This function should not be called directly") + let MemberInitializationHelper (_x:'T) : 'T = raise (NotSupportedException "This function should not be called directly") // The following is recognized as a LINQ 'member initialization pattern' in a quotation. - let NewAnonymousObjectHelper (_x:'T) : 'T = raise (NotSupportedException "This function should not be called directly") + let NewAnonymousObjectHelper (_x:'T) : 'T = raise (NotSupportedException "This function should not be called directly") // This is used to mark expressions inserted to satisfy C#'s design where, inside C#-compiler generated // LINQ expressions, they pass an argument or type T to an argument expecting Expression. let ImplicitExpressionConversionHelper (_x:'T) : Expression<'T> = raise (NotSupportedException "This function should not be called directly") - [] - type ConvEnv = + [] + type ConvEnv = { varEnv : Map } let asExpr x = (x :> Expression) @@ -181,182 +189,182 @@ module LeafExpressionConverter = let isNamedType(typ:Type) = not (typ.IsArray || typ.IsByRef || typ.IsPointer) - let equivHeadTypes (ty1:Type) (ty2:Type) = + let equivHeadTypes (ty1:Type) (ty2:Type) = isNamedType(ty1) && - if ty1.IsGenericType then + if ty1.IsGenericType then ty2.IsGenericType && (ty1.GetGenericTypeDefinition()).Equals(ty2.GetGenericTypeDefinition()) - else + else ty1.Equals(ty2) let isFunctionType typ = equivHeadTypes typ (typeof<(int -> int)>) - let getFunctionType typ = + let getFunctionType typ = if not (isFunctionType typ) then invalidArg "typ" "cannot convert recursion except for function types" let tyargs = typ.GetGenericArguments() tyargs.[0], tyargs.[1] - - let GetGenericMethodDefinition (methInfo:MethodInfo) = + + let GetGenericMethodDefinition (methInfo:MethodInfo) = if methInfo.IsGenericMethod then methInfo.GetGenericMethodDefinition() else methInfo - let StringConcat = - methodhandleof (fun (x:obj, y:obj) -> String.Concat (x,y)) + let StringConcat = + methodhandleof (fun (x:obj, y:obj) -> String.Concat (x, y)) |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo - - let SubstHelperRaw (q:Expr, x:Var[], y:obj[]) : Expr = - let d = Map.ofArray (Array.zip x y) + + let SubstHelperRaw (q:Expr, x:Var[], y:obj[]) : Expr = + let d = Map.ofArray (Array.zip x y) q.Substitute(fun v -> v |> d.TryFind |> Option.map (fun x -> Expr.Value(x, v.Type))) - - let SubstHelper<'T> (q:Expr, x:Var[], y:obj[]) : Expr<'T> = SubstHelperRaw(q,x,y) |> Expr.Cast - - let showAll = + + let SubstHelper<'T> (q:Expr, x:Var[], y:obj[]) : Expr<'T> = + SubstHelperRaw(q, x, y) |> Expr.Cast + + let showAll = #if FX_RESHAPED_REFLECTION true #else - BindingFlags.Public ||| BindingFlags.NonPublic + BindingFlags.Public ||| BindingFlags.NonPublic #endif - let NullableConstructor = typedefof>.GetConstructors().[0] + let NullableConstructor = + typedefof>.GetConstructors().[0] let SpecificCallToMethodInfo (minfo: System.Reflection.MethodInfo) = - let isg1 = minfo.IsGenericMethod + let isg1 = minfo.IsGenericMethod let gmd = if isg1 then minfo.GetGenericMethodDefinition() else null - (fun tm -> + (fun tm -> match tm with - | Call(obj,minfo2,args) + | Call(obj, minfo2, args) when ( #if !FX_NO_REFLECTION_METADATA_TOKENS minfo.MetadataToken = minfo2.MetadataToken && #endif if isg1 then minfo2.IsGenericMethod && gmd = minfo2.GetGenericMethodDefinition() else minfo = minfo2 - ) -> - Some(obj,(minfo2.GetGenericArguments() |> Array.toList),args) + ) -> + Some (obj, (minfo2.GetGenericArguments() |> Array.toList), args) | _ -> None) - let (|SpecificCallToMethod|_|) (mhandle: System.RuntimeMethodHandle) = + let (|SpecificCallToMethod|_|) (mhandle: System.RuntimeMethodHandle) = let minfo = (System.Reflection.MethodInfo.GetMethodFromHandle mhandle) :?> MethodInfo SpecificCallToMethodInfo minfo - let (|GenericEqualityQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> LanguagePrimitives.GenericEquality x y)) - let (|EqualsQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x = y)) - let (|GreaterQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x > y)) - let (|GreaterEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x >= y)) - let (|LessQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x < y)) - let (|LessEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x <= y)) - let (|NotEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x <> y)) - - let (|StaticEqualsQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int,y:int) -> NonStructuralComparison.(=) x y)) - let (|StaticGreaterQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int,y:int) -> NonStructuralComparison.(>) x y)) - let (|StaticGreaterEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int,y:int) -> NonStructuralComparison.(>=) x y)) - let (|StaticLessQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int,y:int) -> NonStructuralComparison.(<) x y)) - let (|StaticLessEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int,y:int) -> NonStructuralComparison.(<=) x y)) - let (|StaticNotEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int,y:int) -> NonStructuralComparison.(<>) x y)) - - let (|NullableEqualsQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?= ) x y)) - let (|NullableNotEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?<> ) x y)) - let (|NullableGreaterQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?> ) x y)) - let (|NullableGreaterEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?>= ) x y)) - let (|NullableLessQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?< ) x y)) - let (|NullableLessEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?<= ) x y)) - - let (|NullableEqualsNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?=? ) x y)) - let (|NullableNotEqNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?<>? ) x y)) - let (|NullableGreaterNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?>? ) x y)) - let (|NullableGreaterEqNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?>=? ) x y)) - let (|NullableLessNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ? NullableOperators.( ?<=? ) x y)) - - let (|EqualsNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( =? ) x y)) - let (|NotEqNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( <>? ) x y)) - let (|GreaterNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( >? ) x y)) - let (|GreaterEqNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( >=? ) x y)) - let (|LessNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( NullableOperators.( <=? ) x y)) - - let (|MakeDecimalQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (a1,a2,a3,a4,a5) -> LanguagePrimitives.IntrinsicFunctions.MakeDecimal a1 a2 a3 a4 a5)) - - - let (|NullablePlusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?+ ) x y)) - let (|NullablePlusNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?+? ) x y)) - let (|PlusNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( +? ) x y)) - - let (|NullableMinusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?- ) x y)) - let (|NullableMinusNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?-? ) x y)) - let (|MinusNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( -? ) x y)) - - let (|NullableMultiplyQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?* ) x y)) - let (|NullableMultiplyNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?*? ) x y)) - let (|MultiplyNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( *? ) x y)) - - let (|NullableDivideQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?/ ) x y)) - let (|NullableDivideNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?/? ) x y)) - let (|DivideNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( /? ) x y)) - - let (|NullableModuloQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?% ) x y)) - let (|NullableModuloNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( ?%? ) x y)) - let (|ModuloNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> NullableOperators.( %? ) x y)) - - let (|NotQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> not x)) - let (|NegQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int) -> -x)) - let (|PlusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x + y)) - let (|DivideQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x / y)) - let (|MinusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x - y)) - let (|MultiplyQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x * y)) - let (|ModuloQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x % y)) - let (|ShiftLeftQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x <<< y)) - let (|ShiftRightQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x >>> y)) - let (|BitwiseAndQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x &&& y)) - let (|BitwiseOrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x ||| y)) - let (|BitwiseXorQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> x ^^^ y)) - let (|BitwiseNotQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> ~~~ x)) - let (|CheckedNeg|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.( ~-) x)) - let (|CheckedPlusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> Checked.( + ) x y)) - let (|CheckedMinusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> Checked.( - ) x y)) - let (|CheckedMultiplyQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> Checked.( * ) x y)) - - let (|ConvCharQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.char x)) - let (|ConvDecimalQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.decimal x)) - let (|ConvFloatQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.float x)) - let (|ConvFloat32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.float32 x)) - let (|ConvSByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.sbyte x)) - - - let (|ConvInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.int16 x)) - let (|ConvInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.int32 x)) - let (|ConvIntQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.int x)) - let (|ConvInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.int64 x)) - let (|ConvByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.byte x)) - let (|ConvUInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.uint16 x)) - let (|ConvUInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.uint32 x)) - let (|ConvUInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.uint64 x)) - - let (|ConvInt8Q|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators").GetMethod("ToSByte")) - let (|ConvUInt8Q|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators").GetMethod("ToByte")) - let (|ConvDoubleQ|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators").GetMethod("ToDouble")) - let (|ConvSingleQ|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators").GetMethod("ToSingle")) - - let (|ConvNullableCharQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.char x)) - let (|ConvNullableDecimalQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.decimal x)) - let (|ConvNullableFloatQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.float x)) - let (|ConvNullableDoubleQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.double x)) - let (|ConvNullableFloat32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.float32 x)) - let (|ConvNullableSingleQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.single x)) - let (|ConvNullableSByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.sbyte x)) - let (|ConvNullableInt8Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int8 x)) - let (|ConvNullableInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int16 x)) - let (|ConvNullableInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int32 x)) - let (|ConvNullableIntQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int x)) - let (|ConvNullableInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int64 x)) - let (|ConvNullableByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.byte x)) - let (|ConvNullableUInt8Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.uint8 x)) - let (|ConvNullableUInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.uint16 x)) - let (|ConvNullableUInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.uint32 x)) - let (|ConvNullableUInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.uint64 x)) + let (|GenericEqualityQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> LanguagePrimitives.GenericEquality x y)) + let (|EqualsQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x = y)) + let (|GreaterQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x > y)) + let (|GreaterEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x >= y)) + let (|LessQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x < y)) + let (|LessEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x <= y)) + let (|NotEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x <> y)) + + let (|StaticEqualsQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int, y:int) -> NonStructuralComparison.(=) x y)) + let (|StaticGreaterQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int, y:int) -> NonStructuralComparison.(>) x y)) + let (|StaticGreaterEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int, y:int) -> NonStructuralComparison.(>=) x y)) + let (|StaticLessQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int, y:int) -> NonStructuralComparison.(<) x y)) + let (|StaticLessEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int, y:int) -> NonStructuralComparison.(<=) x y)) + let (|StaticNotEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int, y:int) -> NonStructuralComparison.(<>) x y)) + + let (|NullableEqualsQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?= ) x y)) + let (|NullableNotEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?<> ) x y)) + let (|NullableGreaterQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?> ) x y)) + let (|NullableGreaterEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?>= ) x y)) + let (|NullableLessQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?< ) x y)) + let (|NullableLessEqQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?<= ) x y)) + + let (|NullableEqualsNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?=? ) x y)) + let (|NullableNotEqNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?<>? ) x y)) + let (|NullableGreaterNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?>? ) x y)) + let (|NullableGreaterEqNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?>=? ) x y)) + let (|NullableLessNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ? NullableOperators.( ?<=? ) x y)) + + let (|EqualsNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( =? ) x y)) + let (|NotEqNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( <>? ) x y)) + let (|GreaterNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( >? ) x y)) + let (|GreaterEqNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( >=? ) x y)) + let (|LessNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( NullableOperators.( <=? ) x y)) + + let (|MakeDecimalQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (a1, a2, a3, a4, a5) -> LanguagePrimitives.IntrinsicFunctions.MakeDecimal a1 a2 a3 a4 a5)) + + let (|NullablePlusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?+ ) x y)) + let (|NullablePlusNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?+? ) x y)) + let (|PlusNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( +? ) x y)) + + let (|NullableMinusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?- ) x y)) + let (|NullableMinusNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?-? ) x y)) + let (|MinusNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( -? ) x y)) + + let (|NullableMultiplyQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?* ) x y)) + let (|NullableMultiplyNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?*? ) x y)) + let (|MultiplyNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( *? ) x y)) + + let (|NullableDivideQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?/ ) x y)) + let (|NullableDivideNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?/? ) x y)) + let (|DivideNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( /? ) x y)) + + let (|NullableModuloQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?% ) x y)) + let (|NullableModuloNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( ?%? ) x y)) + let (|ModuloNullableQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> NullableOperators.( %? ) x y)) + + let (|NotQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> not x)) + let (|NegQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x:int) -> -x)) + let (|PlusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x + y)) + let (|DivideQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x / y)) + let (|MinusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x - y)) + let (|MultiplyQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x * y)) + let (|ModuloQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x % y)) + let (|ShiftLeftQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x <<< y)) + let (|ShiftRightQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x >>> y)) + let (|BitwiseAndQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x &&& y)) + let (|BitwiseOrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x ||| y)) + let (|BitwiseXorQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> x ^^^ y)) + let (|BitwiseNotQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> ~~~ x)) + let (|CheckedNeg|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.( ~-) x)) + let (|CheckedPlusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> Checked.( + ) x y)) + let (|CheckedMinusQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> Checked.( - ) x y)) + let (|CheckedMultiplyQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> Checked.( * ) x y)) + + let (|ConvCharQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.char x)) + let (|ConvDecimalQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.decimal x)) + let (|ConvFloatQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.float x)) + let (|ConvFloat32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.float32 x)) + let (|ConvSByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.sbyte x)) + + let (|ConvInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.int16 x)) + let (|ConvInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.int32 x)) + let (|ConvIntQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.int x)) + let (|ConvInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.int64 x)) + let (|ConvByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.byte x)) + let (|ConvUInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.uint16 x)) + let (|ConvUInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.uint32 x)) + let (|ConvUInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.uint64 x)) + + let (|ConvInt8Q|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators").GetMethod("ToSByte")) + let (|ConvUInt8Q|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators").GetMethod("ToByte")) + let (|ConvDoubleQ|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators").GetMethod("ToDouble")) + let (|ConvSingleQ|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators").GetMethod("ToSingle")) + + let (|ConvNullableCharQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.char x)) + let (|ConvNullableDecimalQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.decimal x)) + let (|ConvNullableFloatQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.float x)) + let (|ConvNullableDoubleQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.double x)) + let (|ConvNullableFloat32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.float32 x)) + let (|ConvNullableSingleQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.single x)) + let (|ConvNullableSByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.sbyte x)) + let (|ConvNullableInt8Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int8 x)) + let (|ConvNullableInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int16 x)) + let (|ConvNullableInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int32 x)) + let (|ConvNullableIntQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int x)) + let (|ConvNullableInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.int64 x)) + let (|ConvNullableByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.byte x)) + let (|ConvNullableUInt8Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.uint8 x)) + let (|ConvNullableUInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.uint16 x)) + let (|ConvNullableUInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.uint32 x)) + let (|ConvNullableUInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.uint64 x)) // LINQ expressions can't do native integer operations, so we don't convert these - //let (|ConvNullableIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.nativeint x)) - //let (|ConvNullableUIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.unativeint x)) + //let (|ConvNullableIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.nativeint x)) + //let (|ConvNullableUIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.unativeint x)) let (|UnboxGeneric|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> LanguagePrimitives.IntrinsicFunctions.UnboxGeneric x)) @@ -375,313 +383,319 @@ module LeafExpressionConverter = let (|ImplicitExpressionConversionHelperQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> ImplicitExpressionConversionHelper x)) let (|MemberInitializationHelperQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> MemberInitializationHelper x)) let (|NewAnonymousObjectHelperQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> NewAnonymousObjectHelper x)) - let (|ArrayLookupQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x,y) -> LanguagePrimitives.IntrinsicFunctions.GetArray x y)) + let (|ArrayLookupQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> LanguagePrimitives.IntrinsicFunctions.GetArray x y)) + //let (|ArrayAssignQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun -> LanguagePrimitives.IntrinsicFunctions.SetArray : int[] -> int -> int -> unit)) - //let (|ArrayTypeQ|_|) (ty:System.Type) = if ty.IsArray && ty.GetArrayRank() = 1 then Some(ty.GetElementType()) else None - let substHelperMeth = - methodhandleof (fun (x:Expr,y:Var[],z:obj[]) -> SubstHelper (x,y,z)) - |> System.Reflection.MethodInfo.GetMethodFromHandle + //let (|ArrayTypeQ|_|) (ty:System.Type) = if ty.IsArray && ty.GetArrayRank() = 1 then Some (ty.GetElementType()) else None + let substHelperMeth = + methodhandleof (fun (x:Expr, y:Var[], z:obj[]) -> SubstHelper (x, y, z)) + |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo - let substHelperRawMeth = - methodhandleof (fun (x:Expr,y:Var[],z:obj[]) -> SubstHelperRaw (x,y,z)) - |> System.Reflection.MethodInfo.GetMethodFromHandle + let substHelperRawMeth = + methodhandleof (fun (x:Expr, y:Var[], z:obj[]) -> SubstHelperRaw (x, y, z)) + |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo let (-->) ty1 ty2 = Reflection.FSharpType.MakeFunctionType(ty1, ty2) /// Extract member initialization expression stored in 'MemberInitializationHelper' (by QueryExtensions.fs) let rec (|Sequentials|) = function - | Patterns.Sequential(a,Sequentials (b,c)) -> (a :: b, c) + | Patterns.Sequential(a, Sequentials (b, c)) -> (a :: b, c) | a -> [], a let (|MemberInitializationQ|_|) = function - | MemberInitializationHelperQ (None, _, [ Sequentials (propSets, init) ]) -> Some(init, propSets) + | MemberInitializationHelperQ (None, _, [ Sequentials (propSets, init) ]) -> Some (init, propSets) | _ -> None - + /// Extract construction of anonymous object noted by use of in 'NewAnonymousObjectHelper' (by QueryExtensions.fs) let (|NewAnonymousObjectQ|_|) = function - | NewAnonymousObjectHelperQ (None, _, [ Patterns.NewObject(ctor,args) ]) -> Some(ctor,args) + | NewAnonymousObjectHelperQ (None, _, [ Patterns.NewObject(ctor, args) ]) -> Some (ctor, args) | _ -> None - - /// Extract nullable constructions + + /// Extract nullable constructions let (|NullableConstruction|_|) = function - | NewObject(c,[arg]) when equivHeadTypes c.DeclaringType (typeof>) -> Some arg + | NewObject(c, [arg]) when equivHeadTypes c.DeclaringType (typeof>) -> Some arg | _ -> None - + /// Convert F# quotations to LINQ expression trees. /// A more polished LINQ-Quotation translator will be published /// concert with later versions of LINQ. - let rec ConvExprToLinqInContext (env:ConvEnv) (inp:Expr) = + let rec ConvExprToLinqInContext (env:ConvEnv) (inp:Expr) = //printf "ConvExprToLinqInContext : %A\n" inp - match inp with - - // Generic cases - | Patterns.Var v -> - try - Map.find v env.varEnv - with - | :? KeyNotFoundException -> invalidOp ("The variable '"+ v.Name + "' was not found in the translation context'") - - | DerivedPatterns.AndAlso(x1, x2) -> Expression.AndAlso(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | DerivedPatterns.OrElse(x1, x2) -> Expression.OrElse(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | Patterns.Value(x, ty) -> Expression.Constant(x, ty) |> asExpr - - | UnboxGeneric(_, [toTy], [x]) - | Patterns.Coerce(x, toTy) -> - let converted = ConvExprToLinqInContext env x - + match inp with + + // Generic cases + | Patterns.Var v -> + try + Map.find v env.varEnv + with + | :? KeyNotFoundException -> invalidOp ("The variable '"+ v.Name + "' was not found in the translation context'") + + | DerivedPatterns.AndAlso(x1, x2) -> + Expression.AndAlso(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + + | DerivedPatterns.OrElse(x1, x2) -> + Expression.OrElse(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + + | Patterns.Value(x, ty) -> + Expression.Constant(x, ty) |> asExpr + + | UnboxGeneric(_, [toTy], [x]) + | Patterns.Coerce(x, toTy) -> + let converted = ConvExprToLinqInContext env x + // Most of conversion scenarios in C# are covered by Expression.Convert if x.Type.Equals toTy then converted // source and target types match - do nothing elif not (x.Type.IsValueType || toTy.IsValueType) && toTy.IsAssignableFrom x.Type then converted // converting reference type to supertype - do nothing else Expression.Convert(converted, toTy) |> asExpr // emit Expression.Convert - | Patterns.TypeTest(x, toTy) -> + | Patterns.TypeTest(x, toTy) -> Expression.TypeIs(ConvExprToLinqInContext env x, toTy) |> asExpr - + | TypeTestGeneric(_, [toTy], [x]) -> Expression.TypeIs(ConvExprToLinqInContext env x, toTy) |> asExpr - + // Expr.*Get - | Patterns.FieldGet(objOpt, fieldInfo) -> + | Patterns.FieldGet(objOpt, fieldInfo) -> Expression.Field(ConvObjArg env objOpt None, fieldInfo) |> asExpr - | Patterns.TupleGet(arg, n) -> - let argP = ConvExprToLinqInContext env arg - let rec build ty argP n = - match Reflection.FSharpValue.PreComputeTuplePropertyInfo(ty, n) with - | propInfo, None -> - Expression.Property(argP, propInfo) |> asExpr - | propInfo, Some(nestedTy, n2) -> + | Patterns.TupleGet(arg, n) -> + let argP = ConvExprToLinqInContext env arg + let rec build ty argP n = + match Reflection.FSharpValue.PreComputeTuplePropertyInfo(ty, n) with + | propInfo, None -> + Expression.Property(argP, propInfo) |> asExpr + | propInfo, Some (nestedTy, n2) -> build nestedTy (Expression.Property(argP, propInfo) |> asExpr) n2 build arg.Type argP n - - | Patterns.PropertyGet(objOpt, propInfo, args) -> - let coerceTo = - if objOpt.IsSome && FSharpType.IsUnion propInfo.DeclaringType && FSharpType.IsUnion propInfo.DeclaringType.BaseType then + + | Patterns.PropertyGet(objOpt, propInfo, args) -> + let coerceTo = + if objOpt.IsSome && FSharpType.IsUnion propInfo.DeclaringType && FSharpType.IsUnion propInfo.DeclaringType.BaseType then Some propInfo.DeclaringType - else + else None - match args with - | [] -> + match args with + | [] -> Expression.Property(ConvObjArg env objOpt coerceTo, propInfo) |> asExpr - | _ -> + | _ -> let argsP = ConvExprsToLinq env args Expression.Call(ConvObjArg env objOpt coerceTo, propInfo.GetGetMethod(true), argsP) |> asExpr // Expr.(Call, Application) - | Patterns.Call(objOpt, minfo, args) -> + | Patterns.Call(objOpt, minfo, args) -> - match inp with + match inp with // Special cases for this translation // Object initialization generated by LinqQueries | MemberInitializationQ(ctor, propInfos) -> let bindings = [| for p in propInfos -> - match p with + match p with | Patterns.PropertySet(_, pinfo, args, assign) -> if args <> [] then raise (NotSupportedException "Parameterized properties not supported in member initialization.") Expression.Bind(pinfo, ConvExprToLinqInContext env assign) :> MemberBinding - | _ -> + | _ -> raise (NotSupportedException "Expected PropertySet in member initialization") |] match ConvExprToLinqInContext env ctor with | :? NewExpression as converted -> Expression.MemberInit(converted, bindings) |> asExpr - | _ -> raise (NotSupportedException "Expected Constructor call in member initialization") - + | _ -> raise (NotSupportedException "Expected Constructor call in member initialization") + // Anonymous type initialization generated by LinqQueries | NewAnonymousObjectQ(ctor, args) -> - let argsR = ConvExprsToLinq env args + let argsR = ConvExprsToLinq env args let props = ctor.DeclaringType.GetProperties() Expression.New(ctor, argsR, [| for p in props -> (p :> MemberInfo) |]) |> asExpr - - - // Do the same thing as C# compiler for string addition - | PlusQ (_, [ty1;ty2;ty3],[x1;x2]) when (ty1 = typeof) && (ty2 = typeof) && (ty3 = typeof) -> + + + // Do the same thing as C# compiler for string addition + | PlusQ (_, [ty1; ty2; ty3], [x1; x2]) when (ty1 = typeof) && (ty2 = typeof) && (ty3 = typeof) -> Expression.Add(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2, StringConcat) |> asExpr - | GenericEqualityQ (_, _,[x1;x2]) - | EqualsQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.Equal - | NotEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.NotEqual - | GreaterQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.GreaterThan - | GreaterEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.GreaterThanOrEqual - | LessQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.LessThan - | LessEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.LessThanOrEqual - | NotQ (_, _, [x1]) -> Expression.Not(ConvExprToLinqInContext env x1) |> asExpr - - | StaticEqualsQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.Equal - | StaticNotEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.NotEqual - | StaticGreaterQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.GreaterThan - | StaticGreaterEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.GreaterThanOrEqual - | StaticLessQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.LessThan - | StaticLessEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.LessThanOrEqual - - | NullableEqualsQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.Equal - | NullableNotEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.NotEqual - | NullableGreaterQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.GreaterThan - | NullableGreaterEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.GreaterThanOrEqual - | NullableLessQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.LessThan - | NullableLessEqQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.LessThanOrEqual - - | EqualsNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.Equal - | NotEqNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.NotEqual - | GreaterNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.GreaterThan - | GreaterEqNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.GreaterThanOrEqual - | LessNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.LessThan - | LessEqNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.LessThanOrEqual - - | NullableEqualsNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.Equal - | NullableNotEqNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.NotEqual - | NullableGreaterNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.GreaterThan - | NullableGreaterEqNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.GreaterThanOrEqual - | NullableLessNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.LessThan - | NullableLessEqNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.LessThanOrEqual - + | GenericEqualityQ (_, _, [x1; x2]) + | EqualsQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.Equal + | NotEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.NotEqual + | GreaterQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.GreaterThan + | GreaterEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.GreaterThanOrEqual + | LessQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.LessThan + | LessEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.LessThanOrEqual + | NotQ (_, _, [x1]) -> Expression.Not(ConvExprToLinqInContext env x1) |> asExpr + + | StaticEqualsQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.Equal + | StaticNotEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.NotEqual + | StaticGreaterQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.GreaterThan + | StaticGreaterEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.GreaterThanOrEqual + | StaticLessQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.LessThan + | StaticLessEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.LessThanOrEqual + + | NullableEqualsQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.Equal + | NullableNotEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.NotEqual + | NullableGreaterQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.GreaterThan + | NullableGreaterEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.GreaterThanOrEqual + | NullableLessQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.LessThan + | NullableLessEqQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.LessThanOrEqual + + | EqualsNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.Equal + | NotEqNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.NotEqual + | GreaterNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.GreaterThan + | GreaterEqNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.GreaterThanOrEqual + | LessNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.LessThan + | LessEqNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.LessThanOrEqual + + | NullableEqualsNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.Equal + | NullableNotEqNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.NotEqual + | NullableGreaterNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.GreaterThan + | NullableGreaterEqNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.GreaterThanOrEqual + | NullableLessNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.LessThan + | NullableLessEqNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.LessThanOrEqual + // Detect the F# quotation encoding of decimal literals - | MakeDecimalQ (_, _, [Int32 lo; Int32 med; Int32 hi; Bool isNegative; Byte scale]) -> - Expression.Constant(new System.Decimal(lo,med,hi,isNegative,scale)) |> asExpr - - | NegQ (_, _, [x1]) -> Expression.Negate(ConvExprToLinqInContext env x1) |> asExpr - | PlusQ (_, _,[x1;x2]) -> Expression.Add(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | DivideQ (_, _,[x1;x2]) -> Expression.Divide (ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | MinusQ (_, _,[x1;x2]) -> Expression.Subtract(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | MultiplyQ (_, _,[x1;x2]) -> Expression.Multiply(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | ModuloQ (_, _,[x1;x2]) -> Expression.Modulo (ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - - | ShiftLeftQ (_, _,[x1;x2]) -> Expression.LeftShift(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | ShiftRightQ (_, _,[x1;x2]) -> Expression.RightShift(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | BitwiseAndQ (_, _,[x1;x2]) -> Expression.And(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | BitwiseOrQ (_, _,[x1;x2]) -> Expression.Or(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | BitwiseXorQ (_, _,[x1;x2]) -> Expression.ExclusiveOr(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | MakeDecimalQ (_, _, [Int32 lo; Int32 med; Int32 hi; Bool isNegative; Byte scale]) -> + Expression.Constant (new System.Decimal(lo, med, hi, isNegative, scale)) |> asExpr + + | NegQ (_, _, [x1]) -> Expression.Negate(ConvExprToLinqInContext env x1) |> asExpr + | PlusQ (_, _, [x1; x2]) -> Expression.Add(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | DivideQ (_, _, [x1; x2]) -> Expression.Divide (ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | MinusQ (_, _, [x1; x2]) -> Expression.Subtract(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | MultiplyQ (_, _, [x1; x2]) -> Expression.Multiply(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | ModuloQ (_, _, [x1; x2]) -> Expression.Modulo (ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + + | ShiftLeftQ (_, _, [x1; x2]) -> Expression.LeftShift(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | ShiftRightQ (_, _, [x1; x2]) -> Expression.RightShift(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | BitwiseAndQ (_, _, [x1; x2]) -> Expression.And(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | BitwiseOrQ (_, _, [x1; x2]) -> Expression.Or(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | BitwiseXorQ (_, _, [x1; x2]) -> Expression.ExclusiveOr(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr | BitwiseNotQ (_, _, [x1]) -> Expression.Not(ConvExprToLinqInContext env x1) |> asExpr - | CheckedNeg (_, _, [x1]) -> Expression.NegateChecked(ConvExprToLinqInContext env x1) |> asExpr - | CheckedPlusQ (_, _,[x1;x2]) -> Expression.AddChecked(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | CheckedMinusQ (_, _,[x1;x2]) -> Expression.SubtractChecked(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - | CheckedMultiplyQ (_, _,[x1;x2]) -> Expression.MultiplyChecked(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr - - - | NullablePlusQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.Add - | PlusNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.Add - | NullablePlusNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.Add - - | NullableMinusQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.Subtract - | MinusNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.Subtract - | NullableMinusNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.Subtract - - | NullableMultiplyQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.Multiply - | MultiplyNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.Multiply - | NullableMultiplyNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.Multiply - - | NullableDivideQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.Divide - | DivideNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.Divide - | NullableDivideNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.Divide - - | NullableModuloQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 true Expression.Modulo - | ModuloNullableQ (_, _,[x1;x2]) -> transBinOp env true x1 x2 false Expression.Modulo - | NullableModuloNullableQ (_, _,[x1;x2]) -> transBinOp env false x1 x2 false Expression.Modulo - - | ConvNullableCharQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | CheckedNeg (_, _, [x1]) -> Expression.NegateChecked(ConvExprToLinqInContext env x1) |> asExpr + | CheckedPlusQ (_, _, [x1; x2]) -> Expression.AddChecked(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | CheckedMinusQ (_, _, [x1; x2]) -> Expression.SubtractChecked(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + | CheckedMultiplyQ (_, _, [x1; x2]) -> Expression.MultiplyChecked(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr + + + | NullablePlusQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.Add + | PlusNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.Add + | NullablePlusNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.Add + + | NullableMinusQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.Subtract + | MinusNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.Subtract + | NullableMinusNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.Subtract + + | NullableMultiplyQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.Multiply + | MultiplyNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.Multiply + | NullableMultiplyNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.Multiply + + | NullableDivideQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.Divide + | DivideNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.Divide + | NullableDivideNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.Divide + + | NullableModuloQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 true Expression.Modulo + | ModuloNullableQ (_, _, [x1; x2]) -> transBinOp env true x1 x2 false Expression.Modulo + | NullableModuloNullableQ (_, _, [x1; x2]) -> transBinOp env false x1 x2 false Expression.Modulo + + | ConvNullableCharQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr | ConvNullableDecimalQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableFloatQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableDoubleQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableFloatQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableDoubleQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr | ConvNullableFloat32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableSingleQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableSByteQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableInt8Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableInt16Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableInt32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableIntQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableInt64Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableByteQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableUInt8Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableUInt16Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableUInt32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvNullableUInt64Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableSingleQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableSByteQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableInt8Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableInt16Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableInt32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableIntQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableInt64Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableByteQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableUInt8Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableUInt16Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableUInt32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + | ConvNullableUInt64Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr // LINQ expressions can't do native integer operations, so we don't convert these - //| ConvNullableIntPtrQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - //| ConvNullableUIntPtrQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + //| ConvNullableIntPtrQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr + //| ConvNullableUIntPtrQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof>) |> asExpr - | ConvCharQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvCharQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr | ConvDecimalQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvFloatQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvDoubleQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvFloatQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvDoubleQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr | ConvFloat32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvSingleQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvSByteQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvInt8Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvInt16Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvInt32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvIntQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvInt64Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvByteQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvUInt8Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvUInt16Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvUInt32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ConvUInt64Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr - - | CheckedConvCharQ (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr - | CheckedConvSByteQ (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr - | CheckedConvInt8Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr - | CheckedConvInt16Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr - | CheckedConvInt32Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr - | CheckedConvInt64Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr - | CheckedConvByteQ (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvSingleQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvSByteQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvInt8Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvInt16Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvInt32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvIntQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvInt64Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvByteQ (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvUInt8Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvUInt16Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvUInt32Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + | ConvUInt64Q (_, _, [x1]) -> Expression.Convert(ConvExprToLinqInContext env x1, typeof) |> asExpr + + | CheckedConvCharQ (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr + | CheckedConvSByteQ (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr + | CheckedConvInt8Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr + | CheckedConvInt16Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr + | CheckedConvInt32Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr + | CheckedConvInt64Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr + | CheckedConvByteQ (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr | CheckedConvUInt8Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr | CheckedConvUInt16Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr | CheckedConvUInt32Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr | CheckedConvUInt64Q (_, _, [x1]) -> Expression.ConvertChecked(ConvExprToLinqInContext env x1, typeof) |> asExpr - | ArrayLookupQ (_, [_;_;_],[x1;x2]) -> + | ArrayLookupQ (_, [_; _; _], [x1; x2]) -> Expression.ArrayIndex(ConvExprToLinqInContext env x1, ConvExprToLinqInContext env x2) |> asExpr // Throw away markers inserted to satisfy C#'s design where they pass an argument // or type T to an argument expecting Expression. | ImplicitExpressionConversionHelperQ (_, [_], [x1]) -> ConvExprToLinqInContext env x1 - - | _ -> - let argsP = ConvExprsToLinq env args - Expression.Call(ConvObjArg env objOpt None, minfo, argsP) |> asExpr + + | _ -> + let argsP = ConvExprsToLinq env args + Expression.Call(ConvObjArg env objOpt None, minfo, argsP) |> asExpr #if !NO_CURRIED_FUNCTION_OPTIMIZATIONS // f x1 x2 x3 x4 --> InvokeFast4 - | Patterns.Application(Patterns.Application(Patterns.Application(Patterns.Application(f, arg1), arg2), arg3), arg4) -> + | Patterns.Application(Patterns.Application(Patterns.Application(Patterns.Application(f, arg1), arg2), arg3), arg4) -> // TODO: amortize this computation based on f.Type - let meth = + let meth = let domainTy1, rangeTy = getFunctionType f.Type let domainTy2, rangeTy = getFunctionType rangeTy let domainTy3, rangeTy = getFunctionType rangeTy let domainTy4, rangeTy = getFunctionType rangeTy - let ty = domainTy1 --> domainTy2 + let ty = domainTy1 --> domainTy2 (ty.GetMethods() |> Array.find (fun minfo -> minfo.Name = "InvokeFast" && minfo.GetParameters().Length = 5)).MakeGenericMethod [| domainTy3; domainTy4; rangeTy |] - let argsP = ConvExprsToLinq env [f; arg1;arg2;arg3; arg4] + let argsP = ConvExprsToLinq env [f; arg1; arg2; arg3; arg4] Expression.Call((null:Expression), meth, argsP) |> asExpr // f x1 x2 x3 --> InvokeFast3 - | Patterns.Application(Patterns.Application(Patterns.Application(f, arg1), arg2), arg3) -> + | Patterns.Application(Patterns.Application(Patterns.Application(f, arg1), arg2), arg3) -> // TODO: amortize this computation based on f.Type - let meth = + let meth = let domainTy1, rangeTy = getFunctionType f.Type let domainTy2, rangeTy = getFunctionType rangeTy let domainTy3, rangeTy = getFunctionType rangeTy - let ty = domainTy1 --> domainTy2 + let ty = domainTy1 --> domainTy2 (ty.GetMethods() |> Array.find (fun minfo -> minfo.Name = "InvokeFast" && minfo.GetParameters().Length = 4)).MakeGenericMethod [| domainTy3; rangeTy |] - let argsP = ConvExprsToLinq env [f; arg1;arg2;arg3] + let argsP = ConvExprsToLinq env [f; arg1; arg2; arg3] Expression.Call((null:Expression), meth, argsP) |> asExpr // f x1 x2 --> InvokeFast2 - | Patterns.Application(Patterns.Application(f, arg1), arg2) -> + | Patterns.Application(Patterns.Application(f, arg1), arg2) -> // TODO: amortize this computation based on f.Type - let meth = + let meth = let domainTy1, rangeTy = getFunctionType f.Type let domainTy2, rangeTy = getFunctionType rangeTy - let ty = domainTy1 --> domainTy2 + let ty = domainTy1 --> domainTy2 (ty.GetMethods() |> Array.find (fun minfo -> minfo.Name = "InvokeFast" && minfo.GetParameters().Length = 3)).MakeGenericMethod [| rangeTy |] - let argsP = ConvExprsToLinq env [f; arg1;arg2] + let argsP = ConvExprsToLinq env [f; arg1; arg2] Expression.Call((null:Expression), meth, argsP) |> asExpr #endif // f x1 --> Invoke - | Patterns.Application(f, arg) -> + | Patterns.Application(f, arg) -> let fP = ConvExprToLinqInContext env f let argP = ConvExprToLinqInContext env arg // TODO: amortize this computation based on f.Type @@ -689,90 +703,90 @@ module LeafExpressionConverter = Expression.Call(fP, meth, [| argP |]) |> asExpr // Expr.New* - | Patterns.NewRecord(recdTy, args) -> - let ctorInfo = Reflection.FSharpValue.PreComputeRecordConstructorInfo(recdTy, showAll) + | Patterns.NewRecord(recdTy, args) -> + let ctorInfo = Reflection.FSharpValue.PreComputeRecordConstructorInfo(recdTy, showAll) Expression.New(ctorInfo, ConvExprsToLinq env args) |> asExpr - | Patterns.NewArray(ty, args) -> + | Patterns.NewArray(ty, args) -> Expression.NewArrayInit(ty, ConvExprsToLinq env args) |> asExpr - | Patterns.DefaultValue ty -> + | Patterns.DefaultValue ty -> Expression.New ty |> asExpr - | Patterns.NewUnionCase(unionCaseInfo, args) -> + | Patterns.NewUnionCase(unionCaseInfo, args) -> let methInfo = Reflection.FSharpValue.PreComputeUnionConstructorInfo(unionCaseInfo, showAll) - let argsR = ConvExprsToLinq env args + let argsR = ConvExprsToLinq env args Expression.Call((null:Expression), methInfo, argsR) |> asExpr #if !NO_PATTERN_MATCHING_IN_INPUT_LANGUAGE - | Patterns.UnionCaseTest(e, unionCaseInfo) -> + | Patterns.UnionCaseTest(e, unionCaseInfo) -> let methInfo = Reflection.FSharpValue.PreComputeUnionTagMemberInfo(unionCaseInfo.DeclaringType, showAll) - let obj = ConvExprToLinqInContext env e - let tagE = - match methInfo with - | :? PropertyInfo as p -> + let obj = ConvExprToLinqInContext env e + let tagE = + match methInfo with + | :? PropertyInfo as p -> Expression.Property(obj, p) |> asExpr - | :? MethodInfo as m -> - Expression.Call((null:Expression), m,[| obj |]) |> asExpr + | :? MethodInfo as m -> + Expression.Call((null:Expression), m, [| obj |]) |> asExpr | _ -> failwith "unreachable case" Expression.Equal(tagE, Expression.Constant(unionCaseInfo.Tag)) |> asExpr #endif - | (Patterns.NewObject(ctorInfo, args) as x) -> - match x with + | (Patterns.NewObject(ctorInfo, args) as x) -> + match x with // LINQ providers prefer C# "Nullable x" to be "Convert x", since that's what C# uses // to construct nullable values. | NullableConstruction arg -> Expression.Convert(ConvExprToLinqInContext env arg, x.Type) |> asExpr | _ -> Expression.New(ctorInfo, ConvExprsToLinq env args) |> asExpr - | Patterns.NewDelegate(dty, vs, b) -> - let vsP = List.map ConvVarToLinq vs + | Patterns.NewDelegate(dty, vs, b) -> + let vsP = List.map ConvVarToLinq vs let env = {env with varEnv = List.foldBack2 (fun (v:Var) vP -> Map.add v (vP |> asExpr)) vs vsP env.varEnv } - let bodyP = ConvExprToLinqInContext env b - Expression.Lambda(dty, bodyP, vsP) |> asExpr + let bodyP = ConvExprToLinqInContext env b + Expression.Lambda(dty, bodyP, vsP) |> asExpr - | Patterns.NewTuple args -> + | Patterns.NewTuple args -> let tupTy = args |> List.map (fun arg -> arg.Type) |> Array.ofList |> Reflection.FSharpType.MakeTupleType - let argsP = ConvExprsToLinq env args - let rec build ty (argsP: Expression[]) = - match Reflection.FSharpValue.PreComputeTupleConstructorInfo ty with - | ctorInfo, None -> Expression.New(ctorInfo, argsP) |> asExpr - | ctorInfo, Some(nestedTy) -> + let argsP = ConvExprsToLinq env args + let rec build ty (argsP: Expression[]) = + match Reflection.FSharpValue.PreComputeTupleConstructorInfo ty with + | ctorInfo, None -> Expression.New(ctorInfo, argsP) |> asExpr + | ctorInfo, Some (nestedTy) -> let n = ctorInfo.GetParameters().Length - 1 Expression.New(ctorInfo, Array.append argsP.[0..n-1] [| build nestedTy argsP.[n..] |]) |> asExpr build tupTy argsP - | Patterns.IfThenElse(g, t, e) -> + | Patterns.IfThenElse(g, t, e) -> Expression.Condition(ConvExprToLinqInContext env g, ConvExprToLinqInContext env t, ConvExprToLinqInContext env e) |> asExpr - | Patterns.QuoteTyped x -> + | Patterns.QuoteTyped x -> let fvs = x.GetFreeVars() - - Expression.Call(substHelperMeth.MakeGenericMethod [| x.Type |], - [| (Expression.Constant x) |> asExpr; - (Expression.NewArrayInit(typeof, [| for fv in fvs -> Expression.Constant fv |> asExpr |]) |> asExpr); - (Expression.NewArrayInit(typeof, [| for fv in fvs -> Expression.Convert(env.varEnv.[fv], typeof) |> asExpr |]) |> asExpr) |]) + + Expression.Call(substHelperMeth.MakeGenericMethod [| x.Type |], + [| (Expression.Constant x) |> asExpr + (Expression.NewArrayInit(typeof, [| for fv in fvs -> Expression.Constant fv |> asExpr |]) |> asExpr) + (Expression.NewArrayInit(typeof, [| for fv in fvs -> Expression.Convert(env.varEnv.[fv], typeof) |> asExpr |]) |> asExpr) |]) |> asExpr - - | Patterns.QuoteRaw x -> + + | Patterns.QuoteRaw x -> let fvs = x.GetFreeVars() - - Expression.Call(substHelperRawMeth, - [| (Expression.Constant x) |> asExpr; - (Expression.NewArrayInit(typeof, [| for fv in fvs -> Expression.Constant fv |> asExpr |]) |> asExpr); - (Expression.NewArrayInit(typeof, [| for fv in fvs -> Expression.Convert(env.varEnv.[fv], typeof) |> asExpr |]) |> asExpr) |]) + + Expression.Call(substHelperRawMeth, + [| (Expression.Constant x) |> asExpr + (Expression.NewArrayInit(typeof, [| for fv in fvs -> Expression.Constant fv |> asExpr |]) |> asExpr) + (Expression.NewArrayInit(typeof, [| for fv in fvs -> Expression.Convert(env.varEnv.[fv], typeof) |> asExpr |]) |> asExpr) |]) |> asExpr - - | Patterns.Let (v, e, b) -> + + | Patterns.Let (v, e, b) -> let vP = ConvVarToLinq v - let envinner = { env with varEnv = Map.add v (vP |> asExpr) env.varEnv } - let bodyP = ConvExprToLinqInContext envinner b + let envinner = { env with varEnv = Map.add v (vP |> asExpr) env.varEnv } + let bodyP = ConvExprToLinqInContext envinner b let eP = ConvExprToLinqInContext env e - let ty = Expression.GetFuncType [| v.Type; b.Type |] - let lam = Expression.Lambda(ty, bodyP,[| vP |]) |> asExpr - Expression.Call(lam, ty.GetMethod("Invoke", instanceBindingFlags),[| eP |]) |> asExpr + let ty = Expression.GetFuncType [| v.Type; b.Type |] + let lam = Expression.Lambda(ty, bodyP, [| vP |]) |> asExpr + Expression.Call(lam, ty.GetMethod("Invoke", instanceBindingFlags), [| eP |]) |> asExpr - | Patterns.Lambda(v, body) -> + | Patterns.Lambda(v, body) -> let vP = ConvVarToLinq v let env = { env with varEnv = Map.add v (vP |> asExpr) env.varEnv } let bodyP = ConvExprToLinqInContext env body @@ -785,34 +799,34 @@ module LeafExpressionConverter = typedefof>, tyargs let convType = lambdaTy.MakeGenericType tyargs let convDelegate = Expression.Lambda(convType, bodyP, [| vP |]) |> asExpr - Expression.Call(typeof,"ToFSharpFunc", tyargs,[| convDelegate |]) |> asExpr + Expression.Call(typeof, "ToFSharpFunc", tyargs, [| convDelegate |]) |> asExpr - | _ -> + | _ -> raise (new NotSupportedException(Printf.sprintf "Could not convert the following F# Quotation to a LINQ Expression Tree\n--------\n%A\n-------------\n" inp)) and transBinOp env addConvertLeft x1 x2 addConvertRight (exprErasedConstructor : _ * _ -> _) = let e1 = ConvExprToLinqInContext env x1 let e2 = ConvExprToLinqInContext env x2 - let e1 = if addConvertLeft then Expression.Convert(e1, typedefof>.MakeGenericType [| e1.Type |]) |> asExpr else e1 + let e1 = if addConvertLeft then Expression.Convert(e1, typedefof>.MakeGenericType [| e1.Type |]) |> asExpr else e1 let e2 = if addConvertRight then Expression.Convert(e2, typedefof>.MakeGenericType [| e2.Type |]) |> asExpr else e2 exprErasedConstructor(e1, e2) |> asExpr - and ConvObjArg env objOpt coerceTo : Expression = + and ConvObjArg env objOpt coerceTo : Expression = match objOpt with - | Some obj -> + | Some obj -> let expr = ConvExprToLinqInContext env obj - match coerceTo with + match coerceTo with | None -> expr | Some ty -> Expression.TypeAs(expr, ty) :> Expression - | None -> + | None -> null - and ConvExprsToLinq env es : Expression[] = - es |> List.map (ConvExprToLinqInContext env) |> Array.ofList + and ConvExprsToLinq env es : Expression[] = + es |> List.map (ConvExprToLinqInContext env) |> Array.ofList - and ConvVarToLinq (v: Var) = - //printf "** Expression .Parameter(%a, %a)\n" output_any ty output_any nm; + and ConvVarToLinq (v: Var) = + //printf "** Expression .Parameter(%a, %a)\n" output_any ty output_any nm Expression.Parameter(v.Type, v.Name) let ConvExprToLinq (e: Expr) = ConvExprToLinqInContext { varEnv = Map.empty } e @@ -820,25 +834,25 @@ module LeafExpressionConverter = let QuotationToExpression (e: Microsoft.FSharp.Quotations.Expr) = ConvExprToLinq e let QuotationToLambdaExpression (e: Microsoft.FSharp.Quotations.Expr<'T>) = (ConvExprToLinq e) :?> Expression<'T> - // This contorted compilation is used because LINQ's "Compile" is only allowed on lambda expressions, and LINQ + // This contorted compilation is used because LINQ's "Compile" is only allowed on lambda expressions, and LINQ // provides no other way to evaluate the expression. // // REVIEW: It is possible it is just better to interpret the expression in many common cases, e.g. property-gets, values etc. - let EvaluateQuotation (e: Microsoft.FSharp.Quotations.Expr) : obj = + let EvaluateQuotation (e: Microsoft.FSharp.Quotations.Expr) : obj = #if FX_NO_QUOTATIONS_COMPILE raise (new NotSupportedException()) #else match e with - | Value (obj,_) -> obj - | _ -> + | Value (obj, _) -> obj + | _ -> let ty = e.Type let e = Expr.NewDelegate(Expression.GetFuncType([|typeof; ty |]), [new Var("unit", typeof)], e) let linqExpr = (ConvExprToLinq e:?> LambdaExpression) let d = linqExpr.Compile() - try + try d.DynamicInvoke [| box () |] - with :? System.Reflection.TargetInvocationException as exn -> + with :? System.Reflection.TargetInvocationException as exn -> raise exn.InnerException #endif - + diff --git a/src/fsharp/FSharp.Core/Query.fs b/src/fsharp/FSharp.Core/Query.fs index 0f889072c7c..7a4f9b2f5a9 100644 --- a/src/fsharp/FSharp.Core/Query.fs +++ b/src/fsharp/FSharp.Core/Query.fs @@ -17,214 +17,266 @@ open Microsoft.FSharp.Linq.RuntimeHelpers #nowarn "64" [] -type QuerySource<'T, 'Q> (source: seq<'T>) = +type QuerySource<'T, 'Q> (source: seq<'T>) = member __.Source = source [] module Helpers = - + // This helps the somewhat complicated type inference for AverageByNullable and SumByNullable, by making both type in a '+' the same let inline plus (x:'T) (y:'T) = Checked.(+) x y - let inline checkNonNull argName arg = - match box arg with - | null -> nullArg argName + let inline checkNonNull argName arg = + match box arg with + | null -> nullArg argName | _ -> () - let checkThenBySource (source: seq<'T>) = - match source with + let checkThenBySource (source: seq<'T>) = + match source with | :? System.Linq.IOrderedEnumerable<'T> as source -> source | _ -> invalidArg "source" (SR.GetString(SR.thenByError)) - // used so we can define the implementation of QueryBuilder before the Query module (so in Query we can safely use methodhandleof) -module ForwardDeclarations = - type IQueryMethods = - abstract Execute : Expr<'T> -> 'U - abstract EliminateNestedQueries : Expr -> Expr - let mutable Query = +module ForwardDeclarations = + type IQueryMethods = + abstract Execute: Expr<'T> -> 'U + abstract EliminateNestedQueries: Expr -> Expr + + let mutable Query = { new IQueryMethods with member this.Execute(_) = failwith "IQueryMethods.Execute should never be called" member this.EliminateNestedQueries(_) = failwith "IQueryMethods.EliminateNestedQueries should never be called" } - + type QueryBuilder() = - member __.For (source:QuerySource<'T,'Q>, body: 'T -> QuerySource<'Result,'Q2>) : QuerySource<'Result,'Q> = QuerySource (Seq.collect (fun x -> (body x).Source) source.Source) - member __.Zero () = QuerySource Seq.empty - member __.Yield value = QuerySource (Seq.singleton value) - member __.YieldFrom (computation: QuerySource<'T,'Q>) : QuerySource<'T,'Q> = computation - member __.Quote (q:Quotations.Expr<'T>) = q - member __.Source (source: IQueryable<'T>) = QuerySource source - member __.Source (source: IEnumerable<'T>) : QuerySource<'T,System.Collections.IEnumerable> = QuerySource source - - member __.Contains(source:QuerySource<'T,'Q>,key) = Enumerable.Contains(source.Source, key) - member __.Select(source:QuerySource<'T,'Q>,projection) : QuerySource<'U,'Q>= QuerySource (Seq.map projection source.Source) - member __.Where(source:QuerySource<'T,'Q>,predicate) : QuerySource<'T,'Q> = QuerySource (Enumerable.Where (source.Source, Func<_,_>(predicate)) ) - member __.Last (source:QuerySource<'T,'Q>) = Enumerable.Last source.Source - member __.LastOrDefault (source:QuerySource<'T,'Q>) = Enumerable.LastOrDefault source.Source - member __.ExactlyOne (source:QuerySource<'T,'Q>) = Enumerable.Single source.Source - member __.ExactlyOneOrDefault (source:QuerySource<'T,'Q>) = Enumerable.SingleOrDefault source.Source - member __.Count (source:QuerySource<'T,'Q>) = Enumerable.Count source.Source - member __.Distinct (source : QuerySource<'T,'Q> when 'T : equality) : QuerySource<'T,'Q> = QuerySource (Enumerable.Distinct source.Source) - member __.Exists(source: QuerySource<'T,'Q>,predicate) = Enumerable.Any (source.Source, Func<_,_>(predicate)) - member __.All (source: QuerySource<'T,'Q>,predicate) = Enumerable.All (source.Source, Func<_,_>(predicate)) - member __.Head (source: QuerySource<'T,'Q>) = Enumerable.First source.Source - member __.Nth (source: QuerySource<'T,'Q>, index) = Enumerable.ElementAt (source.Source, index) - //let reduceBy projection reduction source = source |> Seq.map projection |> Seq.reduce reduction - member __.Skip (source: QuerySource<'T,'Q>,count) : QuerySource<'T,'Q> = QuerySource (Enumerable.Skip (source.Source, count)) - member __.SkipWhile (source: QuerySource<'T,'Q>,predicate) : QuerySource<'T,'Q> = QuerySource (Enumerable.SkipWhile (source.Source, Func<_,_>(predicate))) - member __.Take (source: QuerySource<'T,'Q>,count) : QuerySource<'T,'Q> = QuerySource (Enumerable.Take (source.Source, count)) - member __.TakeWhile (source: QuerySource<'T,'Q>,predicate) : QuerySource<'T,'Q> = QuerySource (Enumerable.TakeWhile (source.Source, Func<_,_>(predicate))) - member __.Find (source: QuerySource<'T,'Q>,predicate) = Enumerable.First (source.Source, Func<_,_>(predicate)) - member __.HeadOrDefault (source:QuerySource<'T,'Q>) = Enumerable.FirstOrDefault source.Source - - member __.MinBy<'T,'Q,'Key when 'Key : equality and 'Key : comparison> (source:QuerySource<'T,'Q>, valueSelector : 'T -> 'Key) = - Enumerable.Min(source.Source, Func<'T,'Key>(valueSelector)) - - member __.MaxBy<'T,'Q,'Key when 'Key : equality and 'Key : comparison> (source:QuerySource<'T,'Q>, valueSelector : 'T -> 'Key) = - Enumerable.Max(source.Source, Func<'T,'Key>(valueSelector)) - - member __.MinByNullable<'T,'Q,'Key when 'Key : equality and 'Key : comparison and 'Key : (new : unit -> 'Key) and 'Key : struct and 'Key :> ValueType> (source:QuerySource<'T,'Q>, valueSelector : 'T -> Nullable<'Key>) = + member __.For (source:QuerySource<'T, 'Q>, body: 'T -> QuerySource<'Result, 'Q2>) : QuerySource<'Result, 'Q> = + QuerySource (Seq.collect (fun x -> (body x).Source) source.Source) + + member __.Zero () = + QuerySource Seq.empty + + member __.Yield value = + QuerySource (Seq.singleton value) + + member __.YieldFrom (computation: QuerySource<'T, 'Q>) : QuerySource<'T, 'Q> = + computation + + // Indicates to the F# compiler that an implicit quotation is added to use of 'query' + member __.Quote (quotation:Quotations.Expr<'T>) = + quotation + + member __.Source (source: IQueryable<'T>) = + QuerySource source + + member __.Source (source: IEnumerable<'T>) : QuerySource<'T, System.Collections.IEnumerable> = + QuerySource source + + member __.Contains (source:QuerySource<'T, 'Q>, key) = + Enumerable.Contains(source.Source, key) + + member __.Select (source:QuerySource<'T, 'Q>, projection) : QuerySource<'U, 'Q> = + QuerySource (Seq.map projection source.Source) + + member __.Where (source:QuerySource<'T, 'Q>, predicate) : QuerySource<'T, 'Q> = + QuerySource (Enumerable.Where (source.Source, Func<_, _>(predicate)) ) + + member __.Last (source:QuerySource<'T, 'Q>) = + Enumerable.Last source.Source + + member __.LastOrDefault (source:QuerySource<'T, 'Q>) = + Enumerable.LastOrDefault source.Source + + member __.ExactlyOne (source:QuerySource<'T, 'Q>) = + Enumerable.Single source.Source + + member __.ExactlyOneOrDefault (source:QuerySource<'T, 'Q>) = + Enumerable.SingleOrDefault source.Source + + member __.Count (source:QuerySource<'T, 'Q>) = + Enumerable.Count source.Source + + member __.Distinct (source: QuerySource<'T, 'Q> when 'T : equality) : QuerySource<'T, 'Q> = + QuerySource (Enumerable.Distinct source.Source) + + member __.Exists(source: QuerySource<'T, 'Q>, predicate) = + Enumerable.Any (source.Source, Func<_, _>(predicate)) + + member __.All (source: QuerySource<'T, 'Q>, predicate) = + Enumerable.All (source.Source, Func<_, _>(predicate)) + + member __.Head (source: QuerySource<'T, 'Q>) = + Enumerable.First source.Source + + member __.Nth (source: QuerySource<'T, 'Q>, index) = + Enumerable.ElementAt (source.Source, index) + + member __.Skip (source: QuerySource<'T, 'Q>, count) : QuerySource<'T, 'Q> = + QuerySource (Enumerable.Skip (source.Source, count)) + + member __.SkipWhile (source: QuerySource<'T, 'Q>, predicate) : QuerySource<'T, 'Q> = + QuerySource (Enumerable.SkipWhile (source.Source, Func<_, _>(predicate))) + + member __.Take (source: QuerySource<'T, 'Q>, count) : QuerySource<'T, 'Q> = + QuerySource (Enumerable.Take (source.Source, count)) + + member __.TakeWhile (source: QuerySource<'T, 'Q>, predicate) : QuerySource<'T, 'Q> = + QuerySource (Enumerable.TakeWhile (source.Source, Func<_, _>(predicate))) + + member __.Find (source: QuerySource<'T, 'Q>, predicate) = + Enumerable.First (source.Source, Func<_, _>(predicate)) + + member __.HeadOrDefault (source:QuerySource<'T, 'Q>) = + Enumerable.FirstOrDefault source.Source + + member __.MinBy<'T, 'Q, 'Key when 'Key: equality and 'Key: comparison> (source:QuerySource<'T, 'Q>, valueSelector: 'T -> 'Key) = + Enumerable.Min(source.Source, Func<'T, 'Key>(valueSelector)) + + member __.MaxBy<'T, 'Q, 'Key when 'Key: equality and 'Key: comparison> (source:QuerySource<'T, 'Q>, valueSelector: 'T -> 'Key) = + Enumerable.Max(source.Source, Func<'T, 'Key>(valueSelector)) + + member __.MinByNullable<'T, 'Q, 'Key when 'Key: equality and 'Key: comparison and 'Key: (new: unit -> 'Key) and 'Key: struct and 'Key:> ValueType> (source:QuerySource<'T, 'Q>, valueSelector: 'T -> Nullable<'Key>) = Enumerable.Min(source.Source, Func<'T, Nullable<'Key>>(valueSelector)) - member __.MaxByNullable<'T,'Q,'Key when 'Key : equality and 'Key : comparison and 'Key : (new : unit -> 'Key) and 'Key : struct and 'Key :> ValueType> (source:QuerySource<'T,'Q>, valueSelector : 'T -> Nullable<'Key>) = + member __.MaxByNullable<'T, 'Q, 'Key when 'Key: equality and 'Key: comparison and 'Key: (new: unit -> 'Key) and 'Key: struct and 'Key:> ValueType> (source:QuerySource<'T, 'Q>, valueSelector: 'T -> Nullable<'Key>) = Enumerable.Max(source.Source, Func<'T, Nullable<'Key>>(valueSelector)) member inline __.SumByNullable<'T, 'Q, ^Value when ^Value :> ValueType - and ^Value : struct - and ^Value : (new : unit -> ^Value) - and ^Value : (static member ( + ) : ^Value * ^Value -> ^Value) + and ^Value : struct + and ^Value : (new : unit -> ^Value) + and ^Value : (static member ( + ) : ^Value * ^Value -> ^Value) and ^Value : (static member Zero : ^Value) and default ^Value : int> - (source: QuerySource<'T,'Q>, valueSelector : 'T -> Nullable< ^Value >) : Nullable< ^Value > = + (source: QuerySource<'T, 'Q>, valueSelector : 'T -> Nullable< ^Value >) : Nullable< ^Value > = + let source = source.Source checkNonNull "source" source - use e = source.GetEnumerator() + use e = source.GetEnumerator() let mutable acc : ^Value = LanguagePrimitives.GenericZero< (^Value) > while e.MoveNext() do - let v : Nullable< ^Value > = valueSelector e.Current - if v.HasValue then + let v : Nullable< ^Value > = valueSelector e.Current + if v.HasValue then acc <- plus acc (v.Value : ^Value) Nullable acc - member inline __.AverageByNullable< 'T, 'Q, ^Value + member inline __.AverageByNullable< 'T, 'Q, ^Value when ^Value :> ValueType - and ^Value : struct - and ^Value : (new : unit -> ^Value) - and ^Value : (static member ( + ) : ^Value * ^Value -> ^Value) - and ^Value : (static member DivideByInt : ^Value * int -> ^Value) - and ^Value : (static member Zero : ^Value) + and ^Value : struct + and ^Value : (new : unit -> ^Value) + and ^Value : (static member ( + ) : ^Value * ^Value -> ^Value) + and ^Value : (static member DivideByInt : ^Value * int -> ^Value) + and ^Value : (static member Zero : ^Value) and default ^Value : float > - - (source: QuerySource<'T,'Q>, projection: 'T -> Nullable< ^Value >) : Nullable< ^Value > = + + (source: QuerySource<'T, 'Q>, projection: 'T -> Nullable< ^Value >) : Nullable< ^Value > = + let source = source.Source checkNonNull "source" source - use e = source.GetEnumerator() + use e = source.GetEnumerator() let mutable acc = LanguagePrimitives.GenericZero< (^Value) > let mutable count = 0 while e.MoveNext() do - let v = projection e.Current - if v.HasValue then + let v = projection e.Current + if v.HasValue then acc <- plus acc v.Value count <- count + 1 if count = 0 then Nullable() else Nullable(LanguagePrimitives.DivideByInt< (^Value) > acc count) - member inline __.AverageBy< 'T, 'Q, ^Value - when ^Value : (static member ( + ) : ^Value * ^Value -> ^Value) - and ^Value : (static member DivideByInt : ^Value * int -> ^Value) - and ^Value : (static member Zero : ^Value) + member inline __.AverageBy< 'T, 'Q, ^Value + when ^Value : (static member ( + ) : ^Value * ^Value -> ^Value) + and ^Value : (static member DivideByInt : ^Value * int -> ^Value) + and ^Value : (static member Zero : ^Value) and default ^Value : float > - (source: QuerySource<'T,'Q>, projection: 'T -> ^Value) : ^Value = + (source: QuerySource<'T, 'Q>, projection: 'T -> ^Value) : ^Value = + let source = source.Source checkNonNull "source" source - use e = source.GetEnumerator() + use e = source.GetEnumerator() let mutable acc = LanguagePrimitives.GenericZero< (^U) > let mutable count = 0 while e.MoveNext() do acc <- plus acc (projection e.Current) count <- count + 1 - if count = 0 then + if count = 0 then invalidOp "source" LanguagePrimitives.DivideByInt< (^U) > acc count - member inline __.SumBy< 'T, 'Q, ^Value - when ^Value : (static member ( + ) : ^Value * ^Value -> ^Value) + member inline __.SumBy< 'T, 'Q, ^Value + when ^Value : (static member ( + ) : ^Value * ^Value -> ^Value) and ^Value : (static member Zero : ^Value) and default ^Value : int > - (source:QuerySource<'T,'Q>, projection : ('T -> ^Value)) : ^Value = + (source:QuerySource<'T, 'Q>, projection : ('T -> ^Value)) : ^Value = Seq.sumBy projection source.Source - member __.GroupBy (source: QuerySource<'T,'Q>, keySelector : _ -> 'Key) : QuerySource<_,'Q> when 'Key : equality = - QuerySource (Enumerable.GroupBy(source.Source, Func<_,_>(keySelector))) + member __.GroupBy (source: QuerySource<'T, 'Q>, keySelector : _ -> 'Key) : QuerySource<_, 'Q> when 'Key : equality = + QuerySource (Enumerable.GroupBy(source.Source, Func<_, _>(keySelector))) - member __.SortBy (source: QuerySource<'T,'Q>, keySelector : 'T -> 'Key) : QuerySource<'T,'Q> when 'Key : equality and 'Key : comparison = - QuerySource (Enumerable.OrderBy(source.Source, Func<_,_>(keySelector))) + member __.SortBy (source: QuerySource<'T, 'Q>, keySelector : 'T -> 'Key) : QuerySource<'T, 'Q> when 'Key : equality and 'Key : comparison = + QuerySource (Enumerable.OrderBy(source.Source, Func<_, _>(keySelector))) - member __.SortByDescending (source: QuerySource<'T,'Q>, keySelector : 'T -> 'Key) : QuerySource<'T,'Q> when 'Key : equality and 'Key : comparison = - QuerySource (Enumerable.OrderByDescending(source.Source, Func<_,_>(keySelector))) + member __.SortByDescending (source: QuerySource<'T, 'Q>, keySelector : 'T -> 'Key) : QuerySource<'T, 'Q> when 'Key : equality and 'Key : comparison = + QuerySource (Enumerable.OrderByDescending(source.Source, Func<_, _>(keySelector))) - member __.ThenBy (source: QuerySource<'T,'Q>, keySelector : 'T -> 'Key) : QuerySource<'T,'Q> when 'Key : equality and 'Key : comparison = - QuerySource (Enumerable.ThenBy(checkThenBySource source.Source, Func<_,_>(keySelector))) + member __.ThenBy (source: QuerySource<'T, 'Q>, keySelector : 'T -> 'Key) : QuerySource<'T, 'Q> when 'Key : equality and 'Key : comparison = + QuerySource (Enumerable.ThenBy(checkThenBySource source.Source, Func<_, _>(keySelector))) - member __.ThenByDescending (source: QuerySource<'T,'Q>, keySelector : 'T -> 'Key) : QuerySource<'T,'Q> when 'Key : equality and 'Key : comparison = - QuerySource (Enumerable.ThenByDescending(checkThenBySource source.Source, Func<_,_>(keySelector))) + member __.ThenByDescending (source: QuerySource<'T, 'Q>, keySelector : 'T -> 'Key) : QuerySource<'T, 'Q> when 'Key : equality and 'Key : comparison = + QuerySource (Enumerable.ThenByDescending(checkThenBySource source.Source, Func<_, _>(keySelector))) - member __.SortByNullable (source: QuerySource<'T,'Q>, keySelector : 'T -> Nullable<'Key>) : QuerySource<'T,'Q> when 'Key : equality and 'Key : comparison = - QuerySource (Enumerable.OrderBy(source.Source, Func<_,_>(keySelector))) + member __.SortByNullable (source: QuerySource<'T, 'Q>, keySelector : 'T -> Nullable<'Key>) : QuerySource<'T, 'Q> when 'Key : equality and 'Key : comparison = + QuerySource (Enumerable.OrderBy(source.Source, Func<_, _>(keySelector))) - member __.SortByNullableDescending (source: QuerySource<'T,'Q>, keySelector : 'T -> Nullable<'Key>) : QuerySource<'T,'Q> when 'Key : equality and 'Key : comparison = - QuerySource (Enumerable.OrderByDescending(source.Source, Func<_,_>(keySelector))) + member __.SortByNullableDescending (source: QuerySource<'T, 'Q>, keySelector : 'T -> Nullable<'Key>) : QuerySource<'T, 'Q> when 'Key : equality and 'Key : comparison = + QuerySource (Enumerable.OrderByDescending(source.Source, Func<_, _>(keySelector))) - member __.ThenByNullable (source: QuerySource<'T,'Q>, keySelector : 'T -> Nullable<'Key>) : QuerySource<'T,'Q> when 'Key : equality and 'Key : comparison = - QuerySource (Enumerable.ThenBy(checkThenBySource source.Source, Func<_,_>(keySelector))) + member __.ThenByNullable (source: QuerySource<'T, 'Q>, keySelector : 'T -> Nullable<'Key>) : QuerySource<'T, 'Q> when 'Key : equality and 'Key : comparison = + QuerySource (Enumerable.ThenBy(checkThenBySource source.Source, Func<_, _>(keySelector))) - member __.ThenByNullableDescending (source: QuerySource<'T,'Q>, keySelector : 'T -> Nullable<'Key>) : QuerySource<'T,'Q> when 'Key : equality and 'Key : comparison = - QuerySource (Enumerable.ThenByDescending(checkThenBySource source.Source, Func<_,_>(keySelector))) + member __.ThenByNullableDescending (source: QuerySource<'T, 'Q>, keySelector : 'T -> Nullable<'Key>) : QuerySource<'T, 'Q> when 'Key : equality and 'Key : comparison = + QuerySource (Enumerable.ThenByDescending(checkThenBySource source.Source, Func<_, _>(keySelector))) - member __.GroupValBy<'T,'Key,'Result, 'Q when 'Key : equality > (source:QuerySource<'T,'Q>, resultSelector: 'T -> 'Result, keySelector: 'T -> 'Key) : QuerySource,'Q> = - QuerySource (Enumerable.GroupBy(source.Source, Func<'T,'Key>(keySelector), Func<'T,'Result>(resultSelector))) + member __.GroupValBy<'T, 'Key, 'Result, 'Q when 'Key : equality > (source:QuerySource<'T, 'Q>, resultSelector: 'T -> 'Result, keySelector: 'T -> 'Key) : QuerySource, 'Q> = + QuerySource (Enumerable.GroupBy(source.Source, Func<'T, 'Key>(keySelector), Func<'T, 'Result>(resultSelector))) -#if SUPPORT_ZIP_IN_QUERIES - member __.Zip (firstSource, secondSource, elementSelector) = - Enumerable.Zip(firstSource, secondSource, Func<_,_,_>(elementSelector) ) -#endif - member __.Join (outerSource: QuerySource<_,'Q>, innerSource: QuerySource<_,'Q>, outerKeySelector, innerKeySelector, resultSelector) : QuerySource<_,'Q> = - QuerySource (Enumerable.Join(outerSource.Source, innerSource.Source, Func<_,_>(outerKeySelector), Func<_,_>(innerKeySelector), Func<_,_,_>(resultSelector))) + member __.Join (outerSource: QuerySource<_, 'Q>, innerSource: QuerySource<_, 'Q>, outerKeySelector, innerKeySelector, resultSelector) : QuerySource<_, 'Q> = + QuerySource (Enumerable.Join(outerSource.Source, innerSource.Source, Func<_, _>(outerKeySelector), Func<_, _>(innerKeySelector), Func<_, _, _>(resultSelector))) - member __.GroupJoin (outerSource: QuerySource<_,'Q>, innerSource: QuerySource<_,'Q>, outerKeySelector, innerKeySelector, resultSelector: _ -> seq<_> -> _) : QuerySource<_,'Q> = - QuerySource (Enumerable.GroupJoin(outerSource.Source, innerSource.Source, Func<_,_>(outerKeySelector), Func<_,_>(innerKeySelector), Func<_,_,_>(fun x g -> resultSelector x g))) + member __.GroupJoin (outerSource: QuerySource<_, 'Q>, innerSource: QuerySource<_, 'Q>, outerKeySelector, innerKeySelector, resultSelector: _ -> seq<_> -> _) : QuerySource<_, 'Q> = + QuerySource (Enumerable.GroupJoin(outerSource.Source, innerSource.Source, Func<_, _>(outerKeySelector), Func<_, _>(innerKeySelector), Func<_, _, _>(fun x g -> resultSelector x g))) - member __.LeftOuterJoin (outerSource:QuerySource<_,'Q>, innerSource: QuerySource<_,'Q>, outerKeySelector, innerKeySelector, resultSelector: _ -> seq<_> -> _) : QuerySource<_,'Q> = - QuerySource (Enumerable.GroupJoin(outerSource.Source, innerSource.Source, Func<_,_>(outerKeySelector), Func<_,_>(innerKeySelector), Func<_,_,_>(fun x g -> resultSelector x (g.DefaultIfEmpty())))) + member __.LeftOuterJoin (outerSource:QuerySource<_, 'Q>, innerSource: QuerySource<_, 'Q>, outerKeySelector, innerKeySelector, resultSelector: _ -> seq<_> -> _) : QuerySource<_, 'Q> = + QuerySource (Enumerable.GroupJoin(outerSource.Source, innerSource.Source, Func<_, _>(outerKeySelector), Func<_, _>(innerKeySelector), Func<_, _, _>(fun x g -> resultSelector x (g.DefaultIfEmpty())))) - member __.RunQueryAsValue (q:Quotations.Expr<'T>) : 'T = ForwardDeclarations.Query.Execute q + member __.RunQueryAsValue (q:Quotations.Expr<'T>) : 'T = + ForwardDeclarations.Query.Execute q - member __.RunQueryAsEnumerable (q:Quotations.Expr>) : IEnumerable<'T> = - let queryAfterEliminatingNestedQueries = ForwardDeclarations.Query.EliminateNestedQueries q + member __.RunQueryAsEnumerable (q:Quotations.Expr>) : IEnumerable<'T> = + let queryAfterEliminatingNestedQueries = ForwardDeclarations.Query.EliminateNestedQueries q let queryAfterCleanup = Microsoft.FSharp.Linq.RuntimeHelpers.Adapters.CleanupLeaf queryAfterEliminatingNestedQueries - (LeafExpressionConverter.EvaluateQuotation queryAfterCleanup :?> QuerySource<'T,IEnumerable>).Source + (LeafExpressionConverter.EvaluateQuotation queryAfterCleanup :?> QuerySource<'T, IEnumerable>).Source + + member __.RunQueryAsQueryable (q:Quotations.Expr>) : IQueryable<'T> = + ForwardDeclarations.Query.Execute q - member __.RunQueryAsQueryable (q:Quotations.Expr>) : IQueryable<'T> = ForwardDeclarations.Query.Execute q member this.Run q = this.RunQueryAsQueryable q -namespace Microsoft.FSharp.Linq.QueryRunExtensions +namespace Microsoft.FSharp.Linq.QueryRunExtensions open Microsoft.FSharp.Core [] - module LowPriority = + module LowPriority = type Microsoft.FSharp.Linq.QueryBuilder with [] member this.Run (q: Microsoft.FSharp.Quotations.Expr<'T>) = this.RunQueryAsValue q [] - module HighPriority = + module HighPriority = type Microsoft.FSharp.Linq.QueryBuilder with [] - member this.Run (q: Microsoft.FSharp.Quotations.Expr>) = this.RunQueryAsEnumerable q + member this.Run (q: Microsoft.FSharp.Quotations.Expr>) = this.RunQueryAsEnumerable q namespace Microsoft.FSharp.Linq @@ -258,138 +310,150 @@ open ReflectionAdapters [] module Query = - let ConvVar (v: Var) = + let ConvVar (v: Var) = Expression.Parameter(v.Type, v.Name) let asExpr x = (x :> Expression) - + let (|Getter|_|) (prop: PropertyInfo) = - match prop.GetGetMethod(true) with + match prop.GetGetMethod(true) with | null -> None | v -> Some v - // Match 'f x' - let (|SpecificCall1|_|) q = + // Match 'f x' + let (|SpecificCall1|_|) q = let (|CallQ|_|) = (|SpecificCallToMethod|_|) q function | CallQ (Some builderObj, tyargs, [arg1]) -> Some(builderObj, tyargs, arg1) - | _ -> None + | _ -> None - // Match 'f x y' or 'f (x,y)' - let (|SpecificCall2|_|) q = + // Match 'f x y' or 'f (x, y)' + let (|SpecificCall2|_|) q = let (|CallQ|_|) = (|SpecificCallToMethod|_|) q function - | CallQ (Some builderObj, tyargs, [arg1;arg2]) -> Some(builderObj, tyargs, arg1, arg2) - | _ -> None + | CallQ (Some builderObj, tyargs, [arg1; arg2]) -> Some(builderObj, tyargs, arg1, arg2) + | _ -> None - // Match 'f x y z' or 'f (x,y,z)' - let (|SpecificCall3|_|) q = + // Match 'f x y z' or 'f (x, y, z)' + let (|SpecificCall3|_|) q = let (|CallQ|_|) = (|SpecificCallToMethod|_|) q function - | CallQ (Some builderObj, tyargs, [arg1;arg2;arg3]) -> Some(builderObj, tyargs, arg1, arg2, arg3) - | _ -> None + | CallQ (Some builderObj, tyargs, [arg1; arg2; arg3]) -> Some(builderObj, tyargs, arg1, arg2, arg3) + | _ -> None - /// (fun (x,y) -> z) is represented as 'fun p -> let x = p#0 let y = p#1' etc. + /// (fun (x, y) -> z) is represented as 'fun p -> let x = p#0 let y = p#1' etc. /// This reverses this encoding, but does not de-tuple the input variable into multiple variables. let (|LambdaNoDetupling|_|) (lam: Expr) = /// Strip off the 'let' bindings for an LambdaNoDetupling let rec stripSuccessiveProjLets (p:Var) n expr = - match expr with - | Let(v1,(TupleGet(Var pA,m) as e1),rest) - when p = pA && m = n-> - let restvs,b = stripSuccessiveProjLets p (n+1) rest - (v1,e1)::restvs, b - | _ -> ([],expr) - match lam with - | Lambda(v,body) -> - let projs,b = stripSuccessiveProjLets v 0 body + match expr with + | Let(v1, (TupleGet(Var pA, m) as e1), rest) + when p = pA && m = n-> + let restvs, b = stripSuccessiveProjLets p (n+1) rest + (v1, e1)::restvs, b + | _ -> ([], expr) + match lam with + | Lambda(v, body) -> + let projs, b = stripSuccessiveProjLets v 0 body Some(v, projs, b) | _ -> None - - let restoreTupleProjections projs b = List.foldBack (fun (v,e) acc -> Expr.Let (v,e,acc)) projs b - - let (|LambdasNoDetupling|_|) (inpExpr: Expr) = - let rec loop rvs rprojs e = - match e with - | LambdaNoDetupling(v,projs,body) -> loop (v::rvs) (projs::rprojs) body - | _ -> - match rvs with + + let restoreTupleProjections projs b = List.foldBack (fun (v, e) acc -> Expr.Let (v, e, acc)) projs b + + let (|LambdasNoDetupling|_|) (inpExpr: Expr) = + let rec loop rvs rprojs e = + match e with + | LambdaNoDetupling(v, projs, body) -> loop (v::rvs) (projs::rprojs) body + | _ -> + match rvs with | [] -> None - | _ -> Some(List.rev rvs,restoreTupleProjections (List.concat (List.rev rprojs)) e) - loop [] [] inpExpr + | _ -> Some(List.rev rvs, restoreTupleProjections (List.concat (List.rev rprojs)) e) + loop [] [] inpExpr - let GetGenericMethodDefinition (methInfo:MethodInfo) = + let GetGenericMethodDefinition (methInfo:MethodInfo) = if methInfo.IsGenericMethod then methInfo.GetGenericMethodDefinition() else methInfo - let CallGenericStaticMethod (methHandle:System.RuntimeMethodHandle) = + let CallGenericStaticMethod (methHandle:System.RuntimeMethodHandle) = let methInfo = methHandle |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo - fun (tyargs: Type list, args: obj list) -> + fun (tyargs: Type list, args: obj list) -> let methInfo = if methInfo.IsGenericMethod then methInfo.MakeGenericMethod(Array.ofList tyargs) else methInfo - try + try methInfo.Invoke(null, Array.ofList args) - with :? System.Reflection.TargetInvocationException as exn -> + with :? System.Reflection.TargetInvocationException as exn -> raise exn.InnerException - let CallGenericInstanceMethod (methHandle:System.RuntimeMethodHandle) = + let CallGenericInstanceMethod (methHandle:System.RuntimeMethodHandle) = let methInfo = methHandle |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo - fun (objExpr:obj, tyargs: Type list, args: obj list) -> + fun (objExpr:obj, tyargs: Type list, args: obj list) -> let methInfo = if methInfo.IsGenericMethod then methInfo.MakeGenericMethod(Array.ofList tyargs) else methInfo - try + try methInfo.Invoke(objExpr, Array.ofList args) - with :? System.Reflection.TargetInvocationException as exn -> + with :? System.Reflection.TargetInvocationException as exn -> raise exn.InnerException - let BindGenericStaticMethod (methInfo:MethodInfo) tyargs = - if methInfo.IsGenericMethod then + let BindGenericStaticMethod (methInfo:MethodInfo) tyargs = + if methInfo.IsGenericMethod then methInfo.GetGenericMethodDefinition().MakeGenericMethod(Array.ofList tyargs) else methInfo - let MakeGenericStaticMethod (methHandle:System.RuntimeMethodHandle) = + let MakeGenericStaticMethod (methHandle:System.RuntimeMethodHandle) = let methInfo = methHandle |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo (fun (tyargs: Type list, args: Expr list) -> Expr.Call(BindGenericStaticMethod methInfo tyargs, args)) - let MakeGenericInstanceMethod (methHandle:System.RuntimeMethodHandle) = + let MakeGenericInstanceMethod (methHandle:System.RuntimeMethodHandle) = let methInfo = methHandle |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo (fun (obj:Expr, tyargs: Type list, args: Expr list) -> Expr.Call(obj, BindGenericStaticMethod methInfo tyargs, args)) - let ImplicitExpressionConversionHelperMethodInfo = + let ImplicitExpressionConversionHelperMethodInfo = methodhandleof (fun e -> LeafExpressionConverter.ImplicitExpressionConversionHelper e) - |> System.Reflection.MethodInfo.GetMethodFromHandle + |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo let MakeImplicitExpressionConversion (x:Expr) = Expr.Call(ImplicitExpressionConversionHelperMethodInfo.MakeGenericMethod [| x.Type |], [ x ]) let NT = typedefof> - let FT1 = typedefof> - let FT2 = typedefof> + + let FT1 = typedefof> + + let FT2 = typedefof> + let boolTy = typeof + let MakeNullableTy ty = NT.MakeGenericType [| ty |] + let MakeQueryFuncTy (dty, rty) = FT1.MakeGenericType [| dty; rty |] + let MakeQueryFunc2Ty (dty1, dty2, rty) = FT2.MakeGenericType [| dty1; dty2; rty |] let IEnumerableTypeDef = typedefof> + let IQueryableTypeDef = typedefof> - let QuerySourceTypeDef = typedefof> + + let QuerySourceTypeDef = typedefof> + let MakeIEnumerableTy dty= IEnumerableTypeDef.MakeGenericType [| dty|] + let MakeIQueryableTy dty= IQueryableTypeDef.MakeGenericType [| dty|] + let IsQuerySourceTy (ty: System.Type) = ty.IsGenericType && ty.GetGenericTypeDefinition() = QuerySourceTypeDef + let IsIQueryableTy (ty: System.Type) = ty.IsGenericType && ty.GetGenericTypeDefinition() = IQueryableTypeDef - let IsIEnumerableTy (ty: System.Type) = ty.IsGenericType && ty.GetGenericTypeDefinition() = IEnumerableTypeDef + let IsIEnumerableTy (ty: System.Type) = ty.IsGenericType && ty.GetGenericTypeDefinition() = IEnumerableTypeDef // Check a tag type on QuerySource is IQueryable let qTyIsIQueryable (ty : System.Type) = not (ty.Equals(typeof)) - - let FuncExprToDelegateExpr (srcTy, targetTy, v, body) = + + let FuncExprToDelegateExpr (srcTy, targetTy, v, body) = Expr.NewDelegate(Linq.Expressions.Expression.GetFuncType [| srcTy; targetTy |], [v], body) /// Project F# function expressions to Linq LambdaExpression nodes - let FuncExprToLinqFunc2Expression (srcTy, targetTy, v, body) = + let FuncExprToLinqFunc2Expression (srcTy, targetTy, v, body) = FuncExprToDelegateExpr(srcTy, targetTy, v, body) |> LeafExpressionConverter.QuotationToExpression - let FuncExprToLinqFunc2 (srcTy, targetTy, v, body) = + let FuncExprToLinqFunc2 (srcTy, targetTy, v, body) = FuncExprToDelegateExpr(srcTy, targetTy, v, body) |> LeafExpressionConverter.EvaluateQuotation let MakersCallers F = CallGenericStaticMethod F, MakeGenericStaticMethod F @@ -398,10 +462,10 @@ module Query = let MakersCallers2 FQ FE = MakersCallers FQ, MakersCallers FE - let MakeOrCallContainsOrElementAt FQ FE = + let MakeOrCallContainsOrElementAt FQ FE = let (CQ, MQ), (CE, ME) = MakersCallers2 FQ FE let Make (isIQ, srcItemTy:Type, src:Expr, key:Expr) = - if isIQ then + if isIQ then //let key = MakeImplicitExpressionConversion key MQ ([srcItemTy], [src; key]) else @@ -410,102 +474,100 @@ module Query = let Call (isIQ, srcItemTy, src:obj, key:Expr) = let key = key |> LeafExpressionConverter.EvaluateQuotation let C = if isIQ then CQ else CE - C ([srcItemTy], [src;box key]) + C ([srcItemTy], [src; box key]) Make, Call - let MakeContains, CallContains = - let FQ = methodhandleof (fun (x,y) -> System.Linq.Queryable.Contains(x,y)) - let FE = methodhandleof (fun (x,y) -> Enumerable.Contains(x, y)) + let MakeContains, CallContains = + let FQ = methodhandleof (fun (x, y) -> System.Linq.Queryable.Contains(x, y)) + let FE = methodhandleof (fun (x, y) -> Enumerable.Contains(x, y)) MakeOrCallContainsOrElementAt FQ FE - let MakeElementAt, CallElementAt = - let FQ = methodhandleof (fun (x,y) -> System.Linq.Queryable.ElementAt(x,y)) - let FE = methodhandleof (fun (x,y) -> Enumerable.ElementAt(x,y)) + let MakeElementAt, CallElementAt = + let FQ = methodhandleof (fun (x, y) -> System.Linq.Queryable.ElementAt(x, y)) + let FE = methodhandleof (fun (x, y) -> Enumerable.ElementAt(x, y)) MakeOrCallContainsOrElementAt FQ FE - let MakeOrCallMinByOrMaxBy FQ FE = + let MakeOrCallMinByOrMaxBy FQ FE = let (CQ, MQ), (CE, ME) = MakersCallers2 FQ FE let Make (isIQ, src:Expr, v:Var, valSelector:Expr) = let srcItemTy = v.Type let keyElemTy = valSelector.Type let valSelector = FuncExprToDelegateExpr (srcItemTy, keyElemTy, v, valSelector) - if isIQ then + if isIQ then let valSelector = MakeImplicitExpressionConversion valSelector - MQ ([srcItemTy;keyElemTy], [src;valSelector]) + MQ ([srcItemTy; keyElemTy], [src; valSelector]) else - ME ([srcItemTy;keyElemTy], [src;valSelector]) + ME ([srcItemTy; keyElemTy], [src; valSelector]) - let Call (isIQ, srcItemTy:Type,_keyItemTy:Type, src:obj, keyElemTy:Type, v:Var, res:Expr) = - if isIQ then + let Call (isIQ, srcItemTy:Type, _keyItemTy:Type, src:obj, keyElemTy:Type, v:Var, res:Expr) = + if isIQ then let selector = FuncExprToLinqFunc2Expression (srcItemTy, keyElemTy, v, res) - CQ ([srcItemTy;keyElemTy], [src;box selector]) - else + CQ ([srcItemTy; keyElemTy], [src; box selector]) + else let selector = FuncExprToLinqFunc2 (srcItemTy, keyElemTy, v, res) - CE ([srcItemTy;keyElemTy], [src;selector]) + CE ([srcItemTy; keyElemTy], [src; selector]) Make, Call - let (MakeMinBy: bool * Expr * Var * Expr -> Expr), (CallMinBy : bool * Type * Type * obj * Type * Var * Expr -> obj) = - let FQ = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Min(x,y)) - let FE = methodhandleof (fun (x,y:Func<_,'Result>) -> Enumerable.Min(x,y)) + let (MakeMinBy: bool * Expr * Var * Expr -> Expr), (CallMinBy : bool * Type * Type * obj * Type * Var * Expr -> obj) = + let FQ = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Min(x, y)) + let FE = methodhandleof (fun (x, y:Func<_, 'Result>) -> Enumerable.Min(x, y)) MakeOrCallMinByOrMaxBy FQ FE - - let MakeMaxBy, CallMaxBy = - let FQ = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Max(x, y)) - let FE = methodhandleof (fun (x,y: Func<_,'Result>) -> Enumerable.Max(x, y)) + let MakeMaxBy, CallMaxBy = + let FQ = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Max(x, y)) + let FE = methodhandleof (fun (x, y: Func<_, 'Result>) -> Enumerable.Max(x, y)) MakeOrCallMinByOrMaxBy FQ FE - let MakeMinByNullable, CallMinByNullable = + let MakeMinByNullable, CallMinByNullable = // Note there is no separate LINQ overload for Min on nullables - the one implementation just magically skips nullable elements - let FQ = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Min(x, y)) - let FE = methodhandleof (fun (x,y:Func<_,'Result>) -> Enumerable.Min(x, y)) + let FQ = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Min(x, y)) + let FE = methodhandleof (fun (x, y:Func<_, 'Result>) -> Enumerable.Min(x, y)) MakeOrCallMinByOrMaxBy FQ FE - let MakeMaxByNullable, CallMaxByNullable = + let MakeMaxByNullable, CallMaxByNullable = // Note there is no separate LINQ overload for Max on nullables - the one implementation just magically skips nullable elements - let FQ = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Max(x,y)) - let FE = methodhandleof (fun (x,y:Func<_,'Result>) -> Enumerable.Max(x,y)) + let FQ = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Max(x, y)) + let FE = methodhandleof (fun (x, y:Func<_, 'Result>) -> Enumerable.Max(x, y)) MakeOrCallMinByOrMaxBy FQ FE - let MakeOrCallAnyOrAllOrFirstFind FQ FE = + let MakeOrCallAnyOrAllOrFirstFind FQ FE = let (CQ, MQ), (CE, ME) = MakersCallers2 FQ FE let Make (isIQ, src:Expr, v:Var, predicate:Expr) = let srcItemTy= v.Type let predicate = FuncExprToDelegateExpr (srcItemTy, boolTy, v, predicate) - if isIQ then + if isIQ then let predicate = MakeImplicitExpressionConversion predicate MQ ([srcItemTy], [src; predicate]) else ME ([srcItemTy], [src; predicate]) let Call (isIQ, srcItemTy:Type, src:obj, v:Var, res:Expr) = - if isIQ then + if isIQ then let selector = FuncExprToLinqFunc2Expression (srcItemTy, boolTy, v, res) - CQ ([srcItemTy], [src;box selector]) - else + CQ ([srcItemTy], [src; box selector]) + else let selector = FuncExprToLinqFunc2 (srcItemTy, boolTy, v, res) - CE ([srcItemTy], [src;selector]) + CE ([srcItemTy], [src; selector]) Make, Call - let MakeAny, CallAny = - let FQ = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Any(x,y)) - let FE = methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.Any(x,y)) + let MakeAny, CallAny = + let FQ = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Any(x, y)) + let FE = methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.Any(x, y)) MakeOrCallAnyOrAllOrFirstFind FQ FE - let MakeAll, CallAll = - let FQ = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.All(x,y)) - let FE = methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.All(x,y)) + let MakeAll, CallAll = + let FQ = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.All(x, y)) + let FE = methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.All(x, y)) MakeOrCallAnyOrAllOrFirstFind FQ FE - let MakeFirstFind, CallFirstFind = - let FQ = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.First(x,y)) - let FE = methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.First(x,y)) + let MakeFirstFind, CallFirstFind = + let FQ = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.First(x, y)) + let FE = methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.First(x, y)) MakeOrCallAnyOrAllOrFirstFind FQ FE - - let MakeOrCallAverageByOrSumByGeneric (isNullable,fq_double, fq_single, fq_decimal, fq_int32, fq_int64, fe_double, fe_single, fe_decimal, fe_int32, fe_int64, FE) = + let MakeOrCallAverageByOrSumByGeneric (isNullable, fq_double, fq_single, fq_decimal, fq_int32, fq_int64, fe_double, fe_single, fe_decimal, fe_int32, fe_int64, FE) = let (cq_double, mq_double), (ce_double, me_double) = MakersCallers2 fq_double fe_double let (cq_single, mq_single), (ce_single, me_single) = MakersCallers2 fq_single fe_single let (cq_decimal, mq_decimal), (ce_decimal, me_decimal) = MakersCallers2 fq_decimal fe_decimal @@ -515,569 +577,605 @@ module Query = let (CE, ME) = MakersCallersInstance FE let failDueToUnsupportedInputTypeInSumByOrAverageBy() = invalidOp (SR.GetString(SR.failDueToUnsupportedInputTypeInSumByOrAverageBy)) - let Make (qb:Expr,isIQ, src:Expr, v:Var, res:Expr) = + let Make (qb:Expr, isIQ, src:Expr, v:Var, res:Expr) = let srcItemTy = v.Type let resTy = res.Type - let resTyNoNullable = - if isNullable then - assert resTy.IsGenericType; - assert (resTy.GetGenericTypeDefinition() = typedefof>); + let resTyNoNullable = + if isNullable then + assert resTy.IsGenericType + assert (resTy.GetGenericTypeDefinition() = typedefof>) resTy.GetGenericArguments().[0] - else + else resTy let selector = FuncExprToDelegateExpr (srcItemTy, resTy, v, res) - if isIQ then + if isIQ then let selector = MakeImplicitExpressionConversion selector - let maker = - match resTyNoNullable with - | ty when ty = typeof -> mq_double - | ty when ty = typeof -> mq_single - | ty when ty = typeof -> mq_decimal - | ty when ty = typeof -> mq_int32 - | ty when ty = typeof -> mq_int64 + let maker = + match resTyNoNullable with + | ty when ty = typeof -> mq_double + | ty when ty = typeof -> mq_single + | ty when ty = typeof -> mq_decimal + | ty when ty = typeof -> mq_int32 + | ty when ty = typeof -> mq_int64 | _ -> failDueToUnsupportedInputTypeInSumByOrAverageBy() - maker ([srcItemTy], [src;selector]) + maker ([srcItemTy], [src; selector]) else // Try to dynamically invoke a LINQ method if one exists, since these may be optimized over arrays etc. - match resTyNoNullable with - | ty when ty = typeof -> me_double ([srcItemTy], [src;selector]) - | ty when ty = typeof -> me_single ([srcItemTy], [src;selector]) - | ty when ty = typeof -> me_decimal ([srcItemTy], [src;selector]) - | ty when ty = typeof -> me_int32 ([srcItemTy], [src;selector]) - | ty when ty = typeof -> me_int64 ([srcItemTy], [src;selector]) - | _ -> - // The F# implementation needs a QuerySource as a parameter. + match resTyNoNullable with + | ty when ty = typeof -> me_double ([srcItemTy], [src; selector]) + | ty when ty = typeof -> me_single ([srcItemTy], [src; selector]) + | ty when ty = typeof -> me_decimal ([srcItemTy], [src; selector]) + | ty when ty = typeof -> me_int32 ([srcItemTy], [src; selector]) + | ty when ty = typeof -> me_int64 ([srcItemTy], [src; selector]) + | _ -> + // The F# implementation needs a QuerySource as a parameter. let qTy = typeof - let ctor = typedefof>.MakeGenericType([|srcItemTy;qTy|]).GetConstructors().[0] - let src = Expr.NewObject(ctor, [src]) - // The F# implementation needs an FSharpFunc as a parameter. - let selector = Expr.Lambda(v, res) - ME (qb, [srcItemTy;qTy;resTyNoNullable], [src;selector]) - - let Call (qb:obj,isIQ, srcItemTy:Type, resTyNoNullable:Type, src:obj, resTy:Type, v:Var, res:Expr) = - if isIQ then + let ctor = typedefof>.MakeGenericType([|srcItemTy; qTy|]).GetConstructors().[0] + let src = Expr.NewObject(ctor, [src]) + // The F# implementation needs an FSharpFunc as a parameter. + let selector = Expr.Lambda(v, res) + ME (qb, [srcItemTy; qTy; resTyNoNullable], [src; selector]) + + let Call (qb:obj, isIQ, srcItemTy:Type, resTyNoNullable:Type, src:obj, resTy:Type, v:Var, res:Expr) = + if isIQ then let selector = FuncExprToLinqFunc2Expression (srcItemTy, resTy, v, res) - let caller = - match resTyNoNullable with - | ty when ty = typeof -> cq_double - | ty when ty = typeof -> cq_single - | ty when ty = typeof -> cq_decimal - | ty when ty = typeof -> cq_int32 - | ty when ty = typeof -> cq_int64 + let caller = + match resTyNoNullable with + | ty when ty = typeof -> cq_double + | ty when ty = typeof -> cq_single + | ty when ty = typeof -> cq_decimal + | ty when ty = typeof -> cq_int32 + | ty when ty = typeof -> cq_int64 | _ -> failDueToUnsupportedInputTypeInSumByOrAverageBy() - caller ([srcItemTy], [src;box selector]) : obj + caller ([srcItemTy], [src; box selector]) : obj else // Try to dynamically invoke a LINQ method if one exists, since these may be optimized over arrays etc. - let linqMethOpt = - match resTyNoNullable with - | ty when ty = typeof -> Some ce_double - | ty when ty = typeof -> Some ce_single - | ty when ty = typeof -> Some ce_decimal - | ty when ty = typeof -> Some ce_int32 + let linqMethOpt = + match resTyNoNullable with + | ty when ty = typeof -> Some ce_double + | ty when ty = typeof -> Some ce_single + | ty when ty = typeof -> Some ce_decimal + | ty when ty = typeof -> Some ce_int32 | ty when ty = typeof -> Some ce_int64 | _ -> None - match linqMethOpt with - | Some ce -> + match linqMethOpt with + | Some ce -> // A LINQ method needs a Delegate as a parameter let selector = FuncExprToLinqFunc2 (srcItemTy, resTy, v, res) - ce ([srcItemTy], [src;selector]) - | None -> - // The F# implementation needs a QuerySource as a parameter. + ce ([srcItemTy], [src; selector]) + | None -> + // The F# implementation needs a QuerySource as a parameter. let qTy = typeof - let ctor = typedefof>.MakeGenericType([|srcItemTy;qTy|]).GetConstructors().[0] - let srcE = - try + let ctor = typedefof>.MakeGenericType([|srcItemTy; qTy|]).GetConstructors().[0] + let srcE = + try ctor.Invoke [|src|] - with :? System.Reflection.TargetInvocationException as exn -> + with :? System.Reflection.TargetInvocationException as exn -> raise exn.InnerException - - // The F# implementation needs an FSharpFunc as a parameter. + + // The F# implementation needs an FSharpFunc as a parameter. let selectorE = Expr.Lambda (v, res) |> LeafExpressionConverter.EvaluateQuotation - CE (qb, [srcItemTy;qTy;resTy], [srcE;selectorE]) + CE (qb, [srcItemTy; qTy; resTy], [srcE; selectorE]) Make, Call - let MakeAverageBy, CallAverageBy = - let FQ_double = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Average(x,y)) - let FQ_single = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Average(x,y)) - let FQ_decimal = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Average(x,y)) - let FQ_int32 = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Average(x,y)) - let FQ_int64 = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Average(x,y)) - let FE_double = methodhandleof (fun (x,y:Func<_,double>) -> Enumerable.Average(x,y)) - let FE_single = methodhandleof (fun (x,y:Func<_,single>) -> Enumerable.Average(x,y)) - let FE_decimal = methodhandleof (fun (x,y:Func<_,decimal>) -> Enumerable.Average(x,y)) - let FE_int32 = methodhandleof (fun (x,y:Func<_,int32>) -> Enumerable.Average(x,y)) - let FE_int64 = methodhandleof (fun (x,y:Func<_,int64>) -> Enumerable.Average(x,y)) - let FE = methodhandleof (fun (query:QueryBuilder,arg1:QuerySource<_,_>,arg2:_->double) -> query.AverageBy(arg1,arg2)) - MakeOrCallAverageByOrSumByGeneric (false,FQ_double, FQ_single, FQ_decimal, FQ_int32, FQ_int64, FE_double, FE_single, FE_decimal, FE_int32, FE_int64, FE) - - let MakeAverageByNullable, CallAverageByNullable = - let FQ_double = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Average(x,y)) - let FQ_single = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Average(x,y)) - let FQ_decimal = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Average(x,y)) - let FQ_int32 = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Average(x,y)) - let FQ_int64 = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Average(x,y)) - let FE_double = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Average(x,y)) - let FE_single = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Average(x,y)) - let FE_decimal = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Average(x,y)) - let FE_int32 = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Average(x,y)) - let FE_int64 = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Average(x,y)) - let FE = methodhandleof (fun (query:QueryBuilder, arg1:QuerySource<_,_>, arg2:_->Nullable) -> query.AverageByNullable(arg1,arg2)) - MakeOrCallAverageByOrSumByGeneric (true,FQ_double, FQ_single, FQ_decimal, FQ_int32, FQ_int64, FE_double, FE_single, FE_decimal, FE_int32, FE_int64, FE) - - - let MakeSumBy, CallSumBy = - let FQ_double = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Sum(x,y)) - let FQ_single = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Sum(x,y)) - let FQ_decimal = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Sum(x,y)) - let FQ_int32 = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Sum(x,y)) - let FQ_int64 = methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Sum(x,y)) - let FE_double = methodhandleof (fun (x,y:Func<_,double>) -> Enumerable.Sum(x,y)) - let FE_single = methodhandleof (fun (x,y:Func<_,single>) -> Enumerable.Sum(x,y)) - let FE_decimal = methodhandleof (fun (x,y:Func<_,decimal>) -> Enumerable.Sum(x,y)) - let FE_int32 = methodhandleof (fun (x,y:Func<_,int32>) -> Enumerable.Sum(x,y)) - let FE_int64 = methodhandleof (fun (x,y:Func<_,int64>) -> Enumerable.Sum(x,y)) - let FE = methodhandleof (fun (query:QueryBuilder, arg1:QuerySource<_,_>, arg2:_->double) -> query.SumBy(arg1,arg2)) - MakeOrCallAverageByOrSumByGeneric (false,FQ_double, FQ_single, FQ_decimal, FQ_int32, FQ_int64, FE_double, FE_single, FE_decimal, FE_int32, FE_int64, FE) - - let MakeSumByNullable, CallSumByNullable = - let FQ_double = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Sum(x,y)) - let FQ_single = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Sum(x,y)) - let FQ_decimal = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Sum(x,y)) - let FQ_int32 = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Sum(x,y)) - let FQ_int64 = methodhandleof (fun (x,y:Expression>>) -> System.Linq.Queryable.Sum(x,y)) - let FE_double = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Sum(x,y)) - let FE_single = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Sum(x,y)) - let FE_decimal = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Sum(x,y)) - let FE_int32 = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Sum(x,y)) - let FE_int64 = methodhandleof (fun (x,y:Func<_,Nullable>) -> Enumerable.Sum(x,y)) - let FE = methodhandleof (fun (query:QueryBuilder, arg1:QuerySource<_,_>, arg2:_->Nullable) -> query.SumByNullable(arg1,arg2)) - MakeOrCallAverageByOrSumByGeneric (true,FQ_double, FQ_single, FQ_decimal, FQ_int32, FQ_int64, FE_double, FE_single, FE_decimal, FE_int32, FE_int64, FE) - - let MakeOrCallSimpleOp FQ FE = + let MakeAverageBy, CallAverageBy = + let FQ_double = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Average(x, y)) + let FQ_single = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Average(x, y)) + let FQ_decimal = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Average(x, y)) + let FQ_int32 = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Average(x, y)) + let FQ_int64 = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Average(x, y)) + let FE_double = methodhandleof (fun (x, y:Func<_, double>) -> Enumerable.Average(x, y)) + let FE_single = methodhandleof (fun (x, y:Func<_, single>) -> Enumerable.Average(x, y)) + let FE_decimal = methodhandleof (fun (x, y:Func<_, decimal>) -> Enumerable.Average(x, y)) + let FE_int32 = methodhandleof (fun (x, y:Func<_, int32>) -> Enumerable.Average(x, y)) + let FE_int64 = methodhandleof (fun (x, y:Func<_, int64>) -> Enumerable.Average(x, y)) + let FE = methodhandleof (fun (query:QueryBuilder, arg1:QuerySource<_, _>, arg2:_->double) -> query.AverageBy(arg1, arg2)) + MakeOrCallAverageByOrSumByGeneric (false, FQ_double, FQ_single, FQ_decimal, FQ_int32, FQ_int64, FE_double, FE_single, FE_decimal, FE_int32, FE_int64, FE) + + let MakeAverageByNullable, CallAverageByNullable = + let FQ_double = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Average(x, y)) + let FQ_single = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Average(x, y)) + let FQ_decimal = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Average(x, y)) + let FQ_int32 = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Average(x, y)) + let FQ_int64 = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Average(x, y)) + let FE_double = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Average(x, y)) + let FE_single = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Average(x, y)) + let FE_decimal = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Average(x, y)) + let FE_int32 = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Average(x, y)) + let FE_int64 = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Average(x, y)) + let FE = methodhandleof (fun (query:QueryBuilder, arg1:QuerySource<_, _>, arg2:_->Nullable) -> query.AverageByNullable(arg1, arg2)) + MakeOrCallAverageByOrSumByGeneric (true, FQ_double, FQ_single, FQ_decimal, FQ_int32, FQ_int64, FE_double, FE_single, FE_decimal, FE_int32, FE_int64, FE) + + + let MakeSumBy, CallSumBy = + let FQ_double = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Sum(x, y)) + let FQ_single = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Sum(x, y)) + let FQ_decimal = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Sum(x, y)) + let FQ_int32 = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Sum(x, y)) + let FQ_int64 = methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Sum(x, y)) + let FE_double = methodhandleof (fun (x, y:Func<_, double>) -> Enumerable.Sum(x, y)) + let FE_single = methodhandleof (fun (x, y:Func<_, single>) -> Enumerable.Sum(x, y)) + let FE_decimal = methodhandleof (fun (x, y:Func<_, decimal>) -> Enumerable.Sum(x, y)) + let FE_int32 = methodhandleof (fun (x, y:Func<_, int32>) -> Enumerable.Sum(x, y)) + let FE_int64 = methodhandleof (fun (x, y:Func<_, int64>) -> Enumerable.Sum(x, y)) + let FE = methodhandleof (fun (query:QueryBuilder, arg1:QuerySource<_, _>, arg2:_->double) -> query.SumBy(arg1, arg2)) + MakeOrCallAverageByOrSumByGeneric (false, FQ_double, FQ_single, FQ_decimal, FQ_int32, FQ_int64, FE_double, FE_single, FE_decimal, FE_int32, FE_int64, FE) + + let MakeSumByNullable, CallSumByNullable = + let FQ_double = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Sum(x, y)) + let FQ_single = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Sum(x, y)) + let FQ_decimal = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Sum(x, y)) + let FQ_int32 = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Sum(x, y)) + let FQ_int64 = methodhandleof (fun (x, y:Expression>>) -> System.Linq.Queryable.Sum(x, y)) + let FE_double = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Sum(x, y)) + let FE_single = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Sum(x, y)) + let FE_decimal = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Sum(x, y)) + let FE_int32 = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Sum(x, y)) + let FE_int64 = methodhandleof (fun (x, y:Func<_, Nullable>) -> Enumerable.Sum(x, y)) + let FE = methodhandleof (fun (query:QueryBuilder, arg1:QuerySource<_, _>, arg2:_->Nullable) -> query.SumByNullable(arg1, arg2)) + MakeOrCallAverageByOrSumByGeneric (true, FQ_double, FQ_single, FQ_decimal, FQ_int32, FQ_int64, FE_double, FE_single, FE_decimal, FE_int32, FE_int64, FE) + + let MakeOrCallSimpleOp FQ FE = let (CQ, MQ), (CE, ME) = MakersCallers2 FQ FE let Make (isIQ, srcItemTy, src:Expr) = - if isIQ then - MQ ([srcItemTy], [src]) - else + if isIQ then + MQ ([srcItemTy], [src]) + else ME ([srcItemTy], [src]) let Call (isIQ, srcItemTy, src) = (if isIQ then CQ else CE) ([srcItemTy], [src]) Make, Call - let MakeFirst, CallFirst = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.First x)) (methodhandleof (fun x -> Enumerable.First x)) - let MakeFirstOrDefault, CallFirstOrDefault = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.FirstOrDefault x)) (methodhandleof (fun x -> Enumerable.FirstOrDefault x)) - let MakeLast, CallLast = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Last x)) (methodhandleof (fun x -> Enumerable.Last x)) - let MakeLastOrDefault, CallLastOrDefault = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.LastOrDefault x)) (methodhandleof (fun x -> Enumerable.LastOrDefault x)) - let MakeSingle, CallSingle = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Single x)) (methodhandleof (fun x -> Enumerable.Single x)) + let MakeFirst, CallFirst = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.First x)) (methodhandleof (fun x -> Enumerable.First x)) + + let MakeFirstOrDefault, CallFirstOrDefault = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.FirstOrDefault x)) (methodhandleof (fun x -> Enumerable.FirstOrDefault x)) + + let MakeLast, CallLast = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Last x)) (methodhandleof (fun x -> Enumerable.Last x)) + + let MakeLastOrDefault, CallLastOrDefault = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.LastOrDefault x)) (methodhandleof (fun x -> Enumerable.LastOrDefault x)) + + let MakeSingle, CallSingle = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Single x)) (methodhandleof (fun x -> Enumerable.Single x)) + let MakeSingleOrDefault, CallSingleOrDefault = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.SingleOrDefault x)) (methodhandleof (fun x -> Enumerable.SingleOrDefault x)) - let MakeCount, CallCount = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Count x)) (methodhandleof (fun x -> Enumerable.Count x)) + + let MakeCount, CallCount = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Count x)) (methodhandleof (fun x -> Enumerable.Count x)) let MakeDefaultIfEmpty = MakeGenericStaticMethod (methodhandleof (fun x -> Enumerable.DefaultIfEmpty(x))) - + /// Indicates if we can eliminate redundant 'Select(x=>x)' nodes - type CanEliminate = + type CanEliminate = /// Inside a query construct, can eliminate redundant 'Select' - | Yes = 0 + | Yes = 0 /// At the very outer of a query or nested query - can't eliminate redundant 'Select' | No = 1 - let MakeSelect = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Select(x,y))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.Select(x,y))) - fun (canElim,isIQ, src:Expr, v:Var, f:Expr) -> - + let MakeSelect = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Select(x, y))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.Select(x, y))) + fun (canElim, isIQ, src:Expr, v:Var, f:Expr) -> + // Eliminate degenerate 'Select(x => x)', except for the very outer-most cases - match f with + match f with | Patterns.Var(v2) when v = v2 && canElim = CanEliminate.Yes -> src - | _ -> + | _ -> let srcItemTy = v.Type let targetTy = f.Type let selector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, targetTy), [v], f) - - if isIQ then + + if isIQ then let selector = MakeImplicitExpressionConversion selector - FQ ([srcItemTy;targetTy], [src;selector]) + FQ ([srcItemTy; targetTy], [src; selector]) else //printfn "found FE" - FE ([srcItemTy;targetTy], [src;selector]) - - - let MakeAppend = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y) -> System.Linq.Queryable.Concat(x,y))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y) -> Enumerable.Concat(x,y))) - fun (isIQ, srcItemTy, src1:Expr, src2:Expr) -> - if isIQ then - FQ ([srcItemTy], [src1;src2]) - else - FE ([srcItemTy], [src1;src2]) - - let MakeAsQueryable = + FE ([srcItemTy; targetTy], [src; selector]) + + let MakeAppend = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y) -> System.Linq.Queryable.Concat(x, y))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y) -> Enumerable.Concat(x, y))) + fun (isIQ, srcItemTy, src1:Expr, src2:Expr) -> + if isIQ then + FQ ([srcItemTy], [src1; src2]) + else + FE ([srcItemTy], [src1; src2]) + + let MakeAsQueryable = let F = MakeGenericStaticMethod (methodhandleof (fun (x:seq<_>) -> System.Linq.Queryable.AsQueryable x)) - fun (ty, src) -> + fun (ty, src) -> F ([ty], [src]) - let MakeEnumerableEmpty = + let MakeEnumerableEmpty = let F = MakeGenericStaticMethod (methodhandleof (fun _x -> Enumerable.Empty())) - fun (ty) -> + fun (ty) -> F ([ty], []) - let MakeEmpty = - fun (ty) -> + let MakeEmpty = + fun (ty) -> MakeAsQueryable (ty, MakeEnumerableEmpty ty) - let MakeSelectMany = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x:IQueryable<_>,y:Expression>,z:Expression>) -> System.Linq.Queryable.SelectMany(x,y,z))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x:IEnumerable<_>,y:Func<_,_>,z:Func<_,_,_>) -> Enumerable.SelectMany(x,y,z))) - fun (isIQ, resTy:Type, src:Expr, srcItemVar:Var, interimSelectorBody:Expr, interimVar:Var, targetSelectorBody:Expr) -> + let MakeSelectMany = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x:IQueryable<_>, y:Expression>, z:Expression>) -> System.Linq.Queryable.SelectMany(x, y, z))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x:IEnumerable<_>, y:Func<_, _>, z:Func<_, _, _>) -> Enumerable.SelectMany(x, y, z))) + fun (isIQ, resTy:Type, src:Expr, srcItemVar:Var, interimSelectorBody:Expr, interimVar:Var, targetSelectorBody:Expr) -> let srcItemTy = srcItemVar.Type let interimTy = interimVar.Type let interimSelector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, MakeIEnumerableTy interimTy), [srcItemVar], interimSelectorBody) - let targetSelector = Expr.NewDelegate(MakeQueryFunc2Ty(srcItemTy, interimTy, resTy), [srcItemVar;interimVar], targetSelectorBody) + let targetSelector = Expr.NewDelegate(MakeQueryFunc2Ty(srcItemTy, interimTy, resTy), [srcItemVar; interimVar], targetSelectorBody) - if isIQ then + if isIQ then let interimSelector = MakeImplicitExpressionConversion interimSelector let targetSelector = MakeImplicitExpressionConversion targetSelector - FQ ([srcItemTy;interimTy;resTy], [src;interimSelector;targetSelector]) + FQ ([srcItemTy; interimTy; resTy], [src; interimSelector; targetSelector]) else - FE ([srcItemTy;interimTy;resTy], [src;interimSelector;targetSelector]) + FE ([srcItemTy; interimTy; resTy], [src; interimSelector; targetSelector]) - - let MakeWhere = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.Where(x,y))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.Where(x,y))) - fun (isIQ, src:Expr, v:Var, f) -> + let MakeWhere = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.Where(x, y))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.Where(x, y))) + fun (isIQ, src:Expr, v:Var, f) -> let selector = Expr.NewDelegate(MakeQueryFuncTy(v.Type, typeof), [v], f) - if isIQ then + if isIQ then let selector = MakeImplicitExpressionConversion selector - FQ ([v.Type], [src;selector]) + FQ ([v.Type], [src; selector]) else - FE ([v.Type], [src;selector]) - - + FE ([v.Type], [src; selector]) - let MakeOrderByOrThenBy FQ FE = - fun (isIQ, src:Expr, v:Var, keySelector:Expr) -> + let MakeOrderByOrThenBy FQ FE = + fun (isIQ, src:Expr, v:Var, keySelector:Expr) -> let srcItemTy = v.Type let keyItemTy = keySelector.Type let selector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, keyItemTy), [v], keySelector) - if isIQ then + if isIQ then let selector = MakeImplicitExpressionConversion selector - FQ ([srcItemTy;keyItemTy], [src;selector]) + FQ ([srcItemTy; keyItemTy], [src; selector]) else - FE ([srcItemTy;keyItemTy], [src;selector]) + FE ([srcItemTy; keyItemTy], [src; selector]) - let MakeOrderBy = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.OrderBy(x,y))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.OrderBy(x,y))) + let MakeOrderBy = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.OrderBy(x, y))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.OrderBy(x, y))) MakeOrderByOrThenBy FQ FE - let MakeOrderByDescending = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.OrderByDescending(x,y))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.OrderByDescending(x,y))) + let MakeOrderByDescending = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.OrderByDescending(x, y))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.OrderByDescending(x, y))) MakeOrderByOrThenBy FQ FE - let MakeThenBy = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.ThenBy(x,y))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.ThenBy(x,y))) + let MakeThenBy = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.ThenBy(x, y))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.ThenBy(x, y))) MakeOrderByOrThenBy FQ FE - let MakeThenByDescending = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.ThenByDescending(x,y))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.ThenByDescending(x,y))) + let MakeThenByDescending = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.ThenByDescending(x, y))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.ThenByDescending(x, y))) MakeOrderByOrThenBy FQ FE // The keyItemTy differentiates these let MakeOrderByNullable = MakeOrderBy + let MakeOrderByNullableDescending = MakeOrderByDescending + let MakeThenByNullable = MakeThenBy + let MakeThenByNullableDescending = MakeThenByDescending - let GenMakeSkipWhileOrTakeWhile FQ FE = + let GenMakeSkipWhileOrTakeWhile FQ FE = let FQ = MakeGenericStaticMethod FQ let FE = MakeGenericStaticMethod FE - fun (isIQ, src:Expr, v:Var, predicate) -> + fun (isIQ, src:Expr, v:Var, predicate) -> let srcItemTy = v.Type let selector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, boolTy), [v], predicate) - if isIQ then + if isIQ then let selector = MakeImplicitExpressionConversion selector - FQ ([srcItemTy], [src;selector]) + FQ ([srcItemTy], [src; selector]) else - FE ([srcItemTy], [src;selector]) + FE ([srcItemTy], [src; selector]) - - let MakeSkipOrTake FQ FE = + let MakeSkipOrTake FQ FE = let FQ = MakeGenericStaticMethod FQ let FE = MakeGenericStaticMethod FE - fun (isIQ, srcItemTy, src:Expr, count) -> - if isIQ then - FQ ([srcItemTy], [src;count]) + fun (isIQ, srcItemTy, src:Expr, count) -> + if isIQ then + FQ ([srcItemTy], [src; count]) else - FE ([srcItemTy], [src;count]) + FE ([srcItemTy], [src; count]) - let MakeSkip = - MakeSkipOrTake (methodhandleof (fun (x,y) -> System.Linq.Queryable.Skip (x,y))) - (methodhandleof (fun (x,y) -> Enumerable.Skip (x,y))) + let MakeSkip = + MakeSkipOrTake + (methodhandleof (fun (x, y) -> System.Linq.Queryable.Skip (x, y))) + (methodhandleof (fun (x, y) -> Enumerable.Skip (x, y))) - let MakeTake = - MakeSkipOrTake (methodhandleof (fun (x,y) -> System.Linq.Queryable.Take (x,y))) - (methodhandleof (fun (x,y) -> Enumerable.Take (x,y))) + let MakeTake = + MakeSkipOrTake + (methodhandleof (fun (x, y) -> System.Linq.Queryable.Take (x, y))) + (methodhandleof (fun (x, y) -> Enumerable.Take (x, y))) - let MakeSkipWhile = - GenMakeSkipWhileOrTakeWhile (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.SkipWhile(x,y))) - (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.SkipWhile(x,y))) + let MakeSkipWhile = + GenMakeSkipWhileOrTakeWhile + (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.SkipWhile(x, y))) + (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.SkipWhile(x, y))) - let MakeTakeWhile = - GenMakeSkipWhileOrTakeWhile (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.TakeWhile(x,y))) - (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.TakeWhile(x,y))) + let MakeTakeWhile = + GenMakeSkipWhileOrTakeWhile + (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.TakeWhile(x, y))) + (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.TakeWhile(x, y))) - let MakeDistinct = + let MakeDistinct = let FQ = MakeGenericStaticMethod (methodhandleof (fun x -> System.Linq.Queryable.Distinct x)) let FE = MakeGenericStaticMethod (methodhandleof (fun x -> Enumerable.Distinct x)) - fun (isIQ, srcItemTy, src:Expr) -> - if isIQ then + fun (isIQ, srcItemTy, src:Expr) -> + if isIQ then FQ ([srcItemTy], [src]) else FE ([srcItemTy], [src]) - let MakeGroupBy = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y:Expression>) -> System.Linq.Queryable.GroupBy(x,y))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y:Func<_,_>) -> Enumerable.GroupBy(x,y))) - fun (isIQ, src:Expr, v:Var, keySelector:Expr) -> + let MakeGroupBy = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y:Expression>) -> System.Linq.Queryable.GroupBy(x, y))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y:Func<_, _>) -> Enumerable.GroupBy(x, y))) + fun (isIQ, src:Expr, v:Var, keySelector:Expr) -> let srcItemTy = v.Type let keyTy = keySelector.Type - let keySelector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, keyTy), [v], keySelector) + let keySelector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, keyTy), [v], keySelector) - if isIQ then + if isIQ then let keySelector = MakeImplicitExpressionConversion keySelector - FQ ([srcItemTy;keyTy], [src;keySelector]) + FQ ([srcItemTy; keyTy], [src; keySelector]) else - FE ([srcItemTy;keyTy], [src;keySelector]) + FE ([srcItemTy; keyTy], [src; keySelector]) - let MakeGroupValBy = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y:Expression>, z:Expression>) -> System.Linq.Queryable.GroupBy(x,y,z))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y:Func<_,_>, z:Func<_,_>) -> Enumerable.GroupBy(x,y,z))) - fun (isIQ, srcItemTy, keyTy, elementTy, src:Expr, v1, keySelector, v2, elementSelector) -> - let keySelector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, keyTy), [v1], keySelector) - let elementSelector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, elementTy), [v2], elementSelector) + let MakeGroupValBy = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (x, y:Expression>, z:Expression>) -> System.Linq.Queryable.GroupBy(x, y, z))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (x, y:Func<_, _>, z:Func<_, _>) -> Enumerable.GroupBy(x, y, z))) + fun (isIQ, srcItemTy, keyTy, elementTy, src:Expr, v1, keySelector, v2, elementSelector) -> + let keySelector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, keyTy), [v1], keySelector) + let elementSelector = Expr.NewDelegate(MakeQueryFuncTy(srcItemTy, elementTy), [v2], elementSelector) - if isIQ then + if isIQ then let keySelector = MakeImplicitExpressionConversion keySelector let elementSelector = MakeImplicitExpressionConversion elementSelector - FQ ([srcItemTy;keyTy;elementTy], [src;keySelector;elementSelector]) + FQ ([srcItemTy; keyTy; elementTy], [src; keySelector; elementSelector]) else - FE ([srcItemTy;keyTy;elementTy], [src;keySelector;elementSelector]) + FE ([srcItemTy; keyTy; elementTy], [src; keySelector; elementSelector]) -#if SUPPORT_ZIP_IN_QUERIES - let MakeZip = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (x,y, z:Expression>) -> System.Linq.Queryable.Zip(x,y,z))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (x,y, z:Func<_,_,_>) -> Enumerable.Zip(x,y,z))) - fun (firstSourceTy, secondSourceTy, resTy, firstSource:Expr, secondSource:Expr, firstElementVar, secondElementVar, elementSelector) -> - let elementSelector = Expr.NewDelegate(MakeQueryFunc2Ty(firstSourceTy, secondSourceTy, resTy), [firstElementVar;secondElementVar], elementSelector) + let MakeJoin = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (a1, a2, a3:Expression>, a4:Expression>, a5:Expression>) -> System.Linq.Queryable.Join(a1, a2, a3, a4, a5))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (a1, a2, a3:Func<_, _>, a4:Func<_, _>, a5:Func<_, _, _>) -> Enumerable.Join(a1, a2, a3, a4, a5))) + fun (isIQ, outerSourceTy, innerSourceTy, keyTy, resTy, outerSource:Expr, innerSource:Expr, outerKeyVar, outerKeySelector, innerKeyVar, innerKeySelector, outerResultKeyVar, innerResultKeyVar, elementSelector) -> + let outerKeySelector = Expr.NewDelegate(MakeQueryFuncTy(outerSourceTy, keyTy), [outerKeyVar], outerKeySelector) + let innerKeySelector = Expr.NewDelegate(MakeQueryFuncTy(innerSourceTy, keyTy), [innerKeyVar], innerKeySelector) + let elementSelector = Expr.NewDelegate(MakeQueryFunc2Ty(outerSourceTy, innerSourceTy, resTy), [outerResultKeyVar; innerResultKeyVar], elementSelector) - if typeof.IsAssignableFrom(firstSource.Type) && typeof.IsAssignableFrom(secondSource.Type) then - let elementSelector = MakeImplicitExpressionConversion elementSelector - FQ ([firstSourceTy;secondSourceTy;resTy], [firstSource;secondSource;elementSelector]) - else - FE ([firstSourceTy;secondSourceTy;resTy], [firstSource;secondSource;elementSelector]) -#endif - - - - let MakeJoin = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (a1,a2,a3:Expression>,a4:Expression>,a5:Expression>) -> System.Linq.Queryable.Join(a1,a2,a3,a4,a5))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (a1,a2,a3:Func<_,_>,a4:Func<_,_>,a5:Func<_,_,_>) -> Enumerable.Join(a1,a2,a3,a4,a5))) - fun (isIQ, outerSourceTy, innerSourceTy, keyTy, resTy, outerSource:Expr, innerSource:Expr, outerKeyVar, outerKeySelector, innerKeyVar, innerKeySelector, outerResultKeyVar, innerResultKeyVar, elementSelector) -> - let outerKeySelector = Expr.NewDelegate(MakeQueryFuncTy(outerSourceTy, keyTy), [outerKeyVar], outerKeySelector) - let innerKeySelector = Expr.NewDelegate(MakeQueryFuncTy(innerSourceTy, keyTy), [innerKeyVar], innerKeySelector) - let elementSelector = Expr.NewDelegate(MakeQueryFunc2Ty(outerSourceTy, innerSourceTy, resTy), [outerResultKeyVar;innerResultKeyVar], elementSelector) - - if isIQ then + if isIQ then let outerKeySelector = MakeImplicitExpressionConversion outerKeySelector let innerKeySelector = MakeImplicitExpressionConversion innerKeySelector let elementSelector = MakeImplicitExpressionConversion elementSelector - FQ ([outerSourceTy;innerSourceTy;keyTy;resTy], [outerSource;innerSource;outerKeySelector;innerKeySelector;elementSelector]) + FQ ([outerSourceTy; innerSourceTy; keyTy; resTy], [outerSource; innerSource; outerKeySelector; innerKeySelector; elementSelector]) else - FE ([outerSourceTy;innerSourceTy;keyTy;resTy], [outerSource;innerSource;outerKeySelector;innerKeySelector;elementSelector]) - - - - let MakeGroupJoin = - let FQ = MakeGenericStaticMethod (methodhandleof (fun (a1,a2,a3:Expression>,a4:Expression>,a5:Expression>) -> System.Linq.Queryable.GroupJoin(a1,a2,a3,a4,a5))) - let FE = MakeGenericStaticMethod (methodhandleof (fun (a1,a2,a3:Func<_,_>,a4:Func<_,_>,a5:Func<_,_,_>) -> Enumerable.GroupJoin(a1,a2,a3,a4,a5))) - fun (isIQ, outerSourceTy, innerSourceTy, keyTy, resTy, outerSource:Expr, innerSource:Expr, outerKeyVar, outerKeySelector, innerKeyVar, innerKeySelector, outerResultKeyVar, innerResultGroupVar, elementSelector) -> - let outerKeySelector = Expr.NewDelegate(MakeQueryFuncTy(outerSourceTy, keyTy), [outerKeyVar], outerKeySelector) - let innerKeySelector = Expr.NewDelegate(MakeQueryFuncTy(innerSourceTy, keyTy), [innerKeyVar], innerKeySelector) - let elementSelector = Expr.NewDelegate(MakeQueryFunc2Ty(outerSourceTy, MakeIEnumerableTy(innerSourceTy), resTy), [outerResultKeyVar;innerResultGroupVar], elementSelector) - if isIQ then + FE ([outerSourceTy; innerSourceTy; keyTy; resTy], [outerSource; innerSource; outerKeySelector; innerKeySelector; elementSelector]) + + let MakeGroupJoin = + let FQ = MakeGenericStaticMethod (methodhandleof (fun (a1, a2, a3:Expression>, a4:Expression>, a5:Expression>) -> System.Linq.Queryable.GroupJoin(a1, a2, a3, a4, a5))) + let FE = MakeGenericStaticMethod (methodhandleof (fun (a1, a2, a3:Func<_, _>, a4:Func<_, _>, a5:Func<_, _, _>) -> Enumerable.GroupJoin(a1, a2, a3, a4, a5))) + fun (isIQ, outerSourceTy, innerSourceTy, keyTy, resTy, outerSource:Expr, innerSource:Expr, outerKeyVar, outerKeySelector, innerKeyVar, innerKeySelector, outerResultKeyVar, innerResultGroupVar, elementSelector) -> + let outerKeySelector = Expr.NewDelegate(MakeQueryFuncTy(outerSourceTy, keyTy), [outerKeyVar], outerKeySelector) + let innerKeySelector = Expr.NewDelegate(MakeQueryFuncTy(innerSourceTy, keyTy), [innerKeyVar], innerKeySelector) + let elementSelector = Expr.NewDelegate(MakeQueryFunc2Ty(outerSourceTy, MakeIEnumerableTy(innerSourceTy), resTy), [outerResultKeyVar; innerResultGroupVar], elementSelector) + if isIQ then let outerKeySelector = MakeImplicitExpressionConversion outerKeySelector let innerKeySelector = MakeImplicitExpressionConversion innerKeySelector let elementSelector = MakeImplicitExpressionConversion elementSelector - FQ ([outerSourceTy;innerSourceTy;keyTy;resTy], [outerSource;innerSource;outerKeySelector;innerKeySelector;elementSelector]) + FQ ([outerSourceTy; innerSourceTy; keyTy; resTy], [outerSource; innerSource; outerKeySelector; innerKeySelector; elementSelector]) else - FE ([outerSourceTy;innerSourceTy;keyTy;resTy], [outerSource;innerSource;outerKeySelector;innerKeySelector;elementSelector]) - - + FE ([outerSourceTy; innerSourceTy; keyTy; resTy], [outerSource; innerSource; outerKeySelector; innerKeySelector; elementSelector]) - let RewriteExpr f (q : Expr) = - let rec walk (p : Expr) = - match f walk p with + let RewriteExpr f (q : Expr) = + let rec walk (p : Expr) = + match f walk p with | Some r -> r - | None -> - match p with + | None -> + match p with | ExprShape.ShapeCombination(comb, args) -> ExprShape.RebuildShapeCombination(comb, List.map walk args) | ExprShape.ShapeLambda(v, body) -> Expr.Lambda(v, walk body) | ExprShape.ShapeVar _ -> p walk q - - let (|LetExprReduction|_|) (p : Expr) = - match p with + let (|LetExprReduction|_|) (p : Expr) = + match p with | Let(v, e, body) -> let body = body.Substitute (fun v2 -> if v = v2 then Some e else None) Some body - + | _ -> None + let (|MacroReduction|_|) (p : Expr) = - let (|MacroReduction|_|) (p : Expr) = - match p with - | Applications(Lambdas(vs, body), args) when vs.Length = args.Length && List.forall2 (fun vs args -> List.length vs = List.length args) vs args -> + match p with + | Applications(Lambdas(vs, body), args) + when vs.Length = args.Length + && (vs, args) ||> List.forall2 (fun vs args -> vs.Length = args.Length) -> let tab = Map.ofSeq (List.concat (List.map2 List.zip vs args)) - let body = body.Substitute tab.TryFind + let body = body.Substitute tab.TryFind Some body // Macro - | PropertyGet(None, Getter(MethodWithReflectedDefinition(body)), []) -> + | PropertyGet(None, Getter(MethodWithReflectedDefinition(body)), []) -> Some body // Macro - | Call(None, MethodWithReflectedDefinition(Lambdas(vs, body)), args) -> - let tab = Map.ofSeq (List.concat (List.map2 (fun (vs:Var list) arg -> match vs, arg with [v], arg -> [(v, arg)] | vs, NewTuple(args) -> List.zip vs args | _ -> List.zip vs [arg]) vs args)) - let body = body.Substitute tab.TryFind + | Call(None, MethodWithReflectedDefinition(Lambdas(vs, body)), args) -> + let tab = + (vs, args) + ||> List.map2 (fun vs arg -> + match vs, arg with + | [v], arg -> [(v, arg)] + | vs, NewTuple(args) -> List.zip vs args + | _ -> List.zip vs [arg]) + |> List.concat |> Map.ofSeq + let body = body.Substitute tab.TryFind Some body - // Macro - eliminate 'let'. + // Macro - eliminate 'let'. // // Always eliminate these: - // - function definitions + // - function definitions // // Always eliminate these, which are representations introduced by F# quotations: // - let v1 = v2 // - let v1 = tupledArg.Item* // - let copyOfStruct = ... - | Let(v, e, body) when (match e with + | Let(v, e, body) when (match e with | Lambda _ -> true - | Var _ -> true - | TupleGet(Var tv, _) when tv.Name = "tupledArg" -> true + | Var _ -> true + | TupleGet(Var tv, _) when tv.Name = "tupledArg" -> true | _ when v.Name = "copyOfStruct" && v.Type.IsValueType -> true | _ -> false) -> let body = body.Substitute (fun v2 -> if v = v2 then Some e else None) Some body - + | _ -> None /// Expand 'let' and other 'macro' definitions in leaf expressions, because LINQ can't cope with them - let MacroExpand q = + let MacroExpand q = q |> RewriteExpr (fun walk p -> - match p with + match p with // Macro reduction - eliminate any 'let' in leaf expressions | MacroReduction reduced -> Some (walk reduced) | _ -> None) - let (|CallQueryBuilderRunQueryable|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b :QueryBuilder, v) -> b.Run(v))) - let (|CallQueryBuilderRunValue|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b : QueryBuilder, v : Expr<'a>) -> b.Run(v)) : 'a) // type annotations here help overload resolution - let (|CallQueryBuilderRunEnumerable|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b : QueryBuilder, v : Expr> ) -> b.Run(v))) // type annotations here help overload resolution - let (|CallQueryBuilderFor|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b:QueryBuilder,source:QuerySource,body) -> b.For(source,body))) - let (|CallQueryBuilderYield|_|) : Quotations.Expr -> _ = (|SpecificCall1|_|) (methodhandleof (fun (b:QueryBuilder,value) -> b.Yield value)) - let (|CallQueryBuilderYieldFrom|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b:QueryBuilder,values) -> b.YieldFrom values)) - let (|CallQueryBuilderZero|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b:QueryBuilder) -> b.Zero())) - let (|CallQueryBuilderSourceIQueryable|_|) : Quotations.Expr -> _ = (|SpecificCall1|_|) (methodhandleof (fun (b:QueryBuilder,value:IQueryable<_>) -> b.Source value)) - let (|CallQueryBuilderSourceIEnumerable|_|) : Quotations.Expr -> _ = (|SpecificCall1|_|) (methodhandleof (fun (b:QueryBuilder,value:IEnumerable<_>) -> b.Source value)) - - let (|CallSortBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.SortBy(arg1,arg2))) - let (|CallSortByDescending|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.SortByDescending(arg1,arg2))) - let (|CallThenBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.ThenBy(arg1,arg2) )) - let (|CallThenByDescending|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.ThenByDescending(arg1,arg2))) - - let (|CallSortByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.SortByNullable(arg1,arg2))) - let (|CallSortByNullableDescending|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.SortByNullableDescending(arg1,arg2))) - let (|CallThenByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.ThenByNullable(arg1,arg2))) - let (|CallThenByNullableDescending|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.ThenByNullableDescending(arg1,arg2))) - - let (|CallGroupBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.GroupBy(arg1,arg2))) - let (|CallGroupValBy|_|) = (|SpecificCall3|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2,arg3) -> query.GroupValBy(arg1,arg2,arg3))) - let (|CallMinBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.MinBy(arg1,arg2))) - let (|CallMaxBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.MaxBy(arg1,arg2))) - let (|CallMinByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.MinByNullable(arg1,arg2))) - let (|CallMaxByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.MaxByNullable(arg1,arg2))) - let (|CallWhere|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.Where(arg1,arg2))) - let (|CallHeadOrDefault|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder,arg1) -> query.HeadOrDefault arg1)) - let (|CallLast|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder,arg1) -> query.Last arg1)) - let (|CallLastOrDefault|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder,arg1) -> query.LastOrDefault arg1)) - let (|CallExactlyOne|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder,arg1) -> query.ExactlyOne arg1)) - let (|CallExactlyOneOrDefault|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder,source) -> query.ExactlyOneOrDefault source)) - let (|CallSelect|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.Select(arg1,arg2))) - let (|CallExists|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.Exists(arg1,arg2))) - let (|CallForAll|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.All(arg1,arg2))) - let (|CallDistinct|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder,keySelector) -> query.Distinct(keySelector))) - let (|CallTake|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.Take(arg1,arg2))) - let (|CallTakeWhile|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.TakeWhile(arg1,arg2))) - let (|CallContains|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.Contains(arg1,arg2))) - let (|CallNth|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.Nth(arg1,arg2))) - let (|CallSkip|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.Skip(arg1,arg2))) - let (|CallSkipWhile|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.SkipWhile(arg1,arg2))) -#if SUPPORT_ZIP_IN_QUERIES - let (|CallZip|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2,arg3) -> query.Zip(arg1,arg2,arg3))) -#endif - let (|CallJoin|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2,arg3,arg4,arg5) -> query.Join(arg1,arg2,arg3,arg4,arg5))) - let (|CallGroupJoin|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2,arg3,arg4,arg5) -> query.GroupJoin(arg1,arg2,arg3,arg4,arg5))) - let (|CallLeftOuterJoin|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2,arg3,arg4,arg5) -> query.LeftOuterJoin(arg1,arg2,arg3,arg4,arg5))) - let (|CallAverageBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1:QuerySource,arg2:(double->double)) -> query.AverageBy(arg1,arg2))) - let (|CallSumBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1:QuerySource,arg2:(double->double)) -> query.SumBy(arg1,arg2))) + let (|CallQueryBuilderRunQueryable|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b :QueryBuilder, v) -> b.Run(v))) + + let (|CallQueryBuilderRunValue|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b : QueryBuilder, v : Expr<'a>) -> b.Run(v)) : 'a) + + let (|CallQueryBuilderRunEnumerable|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b : QueryBuilder, v : Expr> ) -> b.Run(v))) + + let (|CallQueryBuilderFor|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b:QueryBuilder, source:QuerySource, body) -> b.For(source, body))) + + let (|CallQueryBuilderYield|_|) : Quotations.Expr -> _ = (|SpecificCall1|_|) (methodhandleof (fun (b:QueryBuilder, value) -> b.Yield value)) + + let (|CallQueryBuilderYieldFrom|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b:QueryBuilder, values) -> b.YieldFrom values)) + + let (|CallQueryBuilderZero|_|) : Quotations.Expr -> _ = (|SpecificCallToMethod|_|) (methodhandleof (fun (b:QueryBuilder) -> b.Zero())) + + let (|CallQueryBuilderSourceIQueryable|_|) : Quotations.Expr -> _ = (|SpecificCall1|_|) (methodhandleof (fun (b:QueryBuilder, value:IQueryable<_>) -> b.Source value)) + + let (|CallQueryBuilderSourceIEnumerable|_|) : Quotations.Expr -> _ = (|SpecificCall1|_|) (methodhandleof (fun (b:QueryBuilder, value:IEnumerable<_>) -> b.Source value)) + + let (|CallSortBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.SortBy(arg1, arg2))) + + let (|CallSortByDescending|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.SortByDescending(arg1, arg2))) + + let (|CallThenBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.ThenBy(arg1, arg2) )) + + let (|CallThenByDescending|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.ThenByDescending(arg1, arg2))) + + let (|CallSortByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.SortByNullable(arg1, arg2))) + + let (|CallSortByNullableDescending|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.SortByNullableDescending(arg1, arg2))) + + let (|CallThenByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.ThenByNullable(arg1, arg2))) + + let (|CallThenByNullableDescending|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.ThenByNullableDescending(arg1, arg2))) + + let (|CallGroupBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.GroupBy(arg1, arg2))) + + let (|CallGroupValBy|_|) = (|SpecificCall3|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2, arg3) -> query.GroupValBy(arg1, arg2, arg3))) + + let (|CallMinBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.MinBy(arg1, arg2))) + + let (|CallMaxBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.MaxBy(arg1, arg2))) + + let (|CallMinByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.MinByNullable(arg1, arg2))) + + let (|CallMaxByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.MaxByNullable(arg1, arg2))) + + let (|CallWhere|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.Where(arg1, arg2))) + + let (|CallHeadOrDefault|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder, arg1) -> query.HeadOrDefault arg1)) + + let (|CallLast|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder, arg1) -> query.Last arg1)) + + let (|CallLastOrDefault|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder, arg1) -> query.LastOrDefault arg1)) + + let (|CallExactlyOne|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder, arg1) -> query.ExactlyOne arg1)) + + let (|CallExactlyOneOrDefault|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder, source) -> query.ExactlyOneOrDefault source)) + + let (|CallSelect|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.Select(arg1, arg2))) + + let (|CallExists|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.Exists(arg1, arg2))) + + let (|CallForAll|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.All(arg1, arg2))) + + let (|CallDistinct|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder, keySelector) -> query.Distinct(keySelector))) + + let (|CallTake|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.Take(arg1, arg2))) + + let (|CallTakeWhile|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.TakeWhile(arg1, arg2))) + + let (|CallContains|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.Contains(arg1, arg2))) + + let (|CallNth|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.Nth(arg1, arg2))) + + let (|CallSkip|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.Skip(arg1, arg2))) + + let (|CallSkipWhile|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.SkipWhile(arg1, arg2))) + + let (|CallJoin|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2, arg3, arg4, arg5) -> query.Join(arg1, arg2, arg3, arg4, arg5))) + + let (|CallGroupJoin|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2, arg3, arg4, arg5) -> query.GroupJoin(arg1, arg2, arg3, arg4, arg5))) + + let (|CallLeftOuterJoin|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2, arg3, arg4, arg5) -> query.LeftOuterJoin(arg1, arg2, arg3, arg4, arg5))) + + let (|CallAverageBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1:QuerySource, arg2:(double->double)) -> query.AverageBy(arg1, arg2))) + + let (|CallSumBy|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1:QuerySource, arg2:(double->double)) -> query.SumBy(arg1, arg2))) + + let (|CallAverageByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1:QuerySource, arg2:(double->Nullable)) -> query.AverageByNullable(arg1, arg2))) + + let (|CallSumByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1:QuerySource, arg2:(double->Nullable)) -> query.SumByNullable(arg1, arg2))) + + let (|CallCount|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder, arg1) -> query.Count(arg1))) - let (|CallAverageByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1:QuerySource,arg2:(double->Nullable)) -> query.AverageByNullable(arg1,arg2))) - let (|CallSumByNullable|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1:QuerySource,arg2:(double->Nullable)) -> query.SumByNullable(arg1,arg2))) + let (|CallHead|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder, arg1) -> query.Head(arg1))) - let (|CallCount|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder,arg1) -> query.Count(arg1))) - let (|CallHead|_|) = (|SpecificCall1|_|) (methodhandleof (fun (query:QueryBuilder,arg1) -> query.Head(arg1))) - let (|CallFind|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder,arg1,arg2) -> query.Find(arg1,arg2))) + let (|CallFind|_|) = (|SpecificCall2|_|) (methodhandleof (fun (query:QueryBuilder, arg1, arg2) -> query.Find(arg1, arg2))) - let (|ZeroOnElseBranch|_|) = function + let (|ZeroOnElseBranch|_|) = function // This is the shape for 'match e with ... -> ... | _ -> ()' - | Patterns.Sequential(Patterns.Value(null, _), CallQueryBuilderZero _) + | Patterns.Sequential(Patterns.Value(null, _), CallQueryBuilderZero _) // This is the shape for from 'if/then' | CallQueryBuilderZero _ -> Some() | _ -> None /// Given an expression involving mutable tuples logically corresponding to a "yield" or "select" with the given /// immutable-to-mutable conversion information, convert it back to an expression involving immutable tuples or records. - let rec ConvMutableToImmutable conv mutExpr = - match conv with - | TupleConv convs -> + let rec ConvMutableToImmutable conv mutExpr = + match conv with + | TupleConv convs -> Expr.NewTuple (convs |> List.mapi (fun i conv -> ConvMutableToImmutable conv (AnonymousObjectGet (mutExpr, i)))) - | RecordConv (typ, convs) -> + | RecordConv (typ, convs) -> Expr.NewRecord(typ, convs |> List.mapi (fun i conv -> ConvMutableToImmutable conv (AnonymousObjectGet (mutExpr, i)))) - | SeqConv conv -> + | SeqConv conv -> // At this point, we know the input is either an IQueryable or an IEnumerable. // If it is an IQueryable, we must return an IQueryable. let isIQ = IsIQueryableTy mutExpr.Type assert (IsIEnumerableTy mutExpr.Type || IsIQueryableTy mutExpr.Type) let mutElemTy = mutExpr.Type.GetGenericArguments().[0] - let mutExpr = if isIQ then Expr.Coerce(mutExpr,MakeIEnumerableTy mutElemTy) else mutExpr + let mutExpr = if isIQ then Expr.Coerce(mutExpr, MakeIEnumerableTy mutElemTy) else mutExpr // Generate "source.Select(fun v -> ...)" (remembering that Select is an extension member, i.e. static) let mutVar = new Var("v", mutElemTy) let mutToImmutConvExpr = ConvMutableToImmutable conv (Expr.Var mutVar) - let immutExpr = MakeSelect (CanEliminate.Yes,false,mutExpr,mutVar,mutToImmutConvExpr) + let immutExpr = MakeSelect (CanEliminate.Yes, false, mutExpr, mutVar, mutToImmutConvExpr) let immutElemTy = mutToImmutConvExpr.Type - let immutExprCoerced = if isIQ then MakeAsQueryable(immutElemTy,immutExpr) else immutExpr + let immutExprCoerced = if isIQ then MakeAsQueryable(immutElemTy, immutExpr) else immutExpr immutExprCoerced - | GroupingConv (immutKeyTy, immutElemTy, conv) -> + | GroupingConv (immutKeyTy, immutElemTy, conv) -> assert (mutExpr.Type.GetGenericTypeDefinition() = typedefof>) let mutElemTy = mutExpr.Type.GetGenericArguments().[1] @@ -1086,15 +1184,15 @@ module Query = // Generate "source.Select(fun v -> ...)" (remembering that Select is an extension member, i.e. static) let var = new Var("v", mutElemTy) let convExpr = ConvMutableToImmutable conv (Expr.Var var) - + // Construct an IGrouping - let args = + let args = [ Expr.PropertyGet(mutExpr, mutExpr.Type.GetProperty "Key") MakeSelect(CanEliminate.Yes, false, mutExpr, var, convExpr) ] Expr.Coerce(Expr.NewObject(immutGroupingTy.GetConstructors().[0], args), immutIGroupingTy) - | NoConv -> + | NoConv -> mutExpr /// Given the expressions for a function (fun immutConsumingVar -> immutConsumingExpr) operating over immutable tuple and record @@ -1102,13 +1200,13 @@ module Query = /// data says how immutable types have been replaced by mutable types in the type of the input variable. /// /// For example, if 'conv' is NoConv, then the input function will be returned unchanged. - /// + /// /// If 'conv' is a TupleConv, then the input function will accept immutable tuples, and the output - /// function will accept mutable tuples. In this case, the function is implemented by replacing + /// function will accept mutable tuples. In this case, the function is implemented by replacing /// uses of the immutConsumingVar in the body of immutConsumingExpr with a tuple expression built /// from the elements of mutConsumingVar, and then simplifying the overall result. - let ConvertImmutableConsumerToMutableConsumer conv (immutConsumingVar:Var, immutConsumingExpr:Expr) : Var * Expr = - match conv with + let ConvertImmutableConsumerToMutableConsumer conv (immutConsumingVar:Var, immutConsumingExpr:Expr) : Var * Expr = + match conv with | NoConv -> (immutConsumingVar, immutConsumingExpr) | _ -> let mutConsumingVarType = ConvImmutableTypeToMutableType conv immutConsumingVar.Type @@ -1120,131 +1218,135 @@ module Query = let mutConsumingExpr = SimplifyConsumingExpr mutConsumingExprBeforeSimplification mutConsumingVar, mutConsumingExpr - let (|AnyNestedQuery|_|) e = - match e with - | CallQueryBuilderRunValue (None, _, [_; QuoteTyped e ]) - | CallQueryBuilderRunEnumerable (None, _, [_; QuoteTyped e ]) + let (|AnyNestedQuery|_|) e = + match e with + | CallQueryBuilderRunValue (None, _, [_; QuoteTyped e ]) + | CallQueryBuilderRunEnumerable (None, _, [_; QuoteTyped e ]) | CallQueryBuilderRunQueryable (Some _, _, [ QuoteTyped e ]) -> Some e | _ -> None - let (|EnumerableNestedQuery|_|) e = - match e with - | CallQueryBuilderRunEnumerable (None, _, [_; QuoteTyped e ]) + let (|EnumerableNestedQuery|_|) e = + match e with + | CallQueryBuilderRunEnumerable (None, _, [_; QuoteTyped e ]) | CallQueryBuilderRunQueryable (Some _, _, [ QuoteTyped e ]) -> Some e | _ -> None - /// Represents the result of TransInner - either a normal expression, or something we're about to turn into + /// Represents the result of TransInner - either a normal expression, or something we're about to turn into /// a 'Select'. The 'Select' case can be eliminated if it is about to be the result of a SelectMany by /// changing - /// src.SelectMany(x => ix.Select(y => res)) + /// src.SelectMany(x => ix.Select(y => res)) /// to - /// src.SelectMany(x => ix, (x,y) => res) - [] - type TransInnerResult = + /// src.SelectMany(x => ix, (x, y) => res) + [] + type TransInnerResult = | Select of CanEliminate * bool * TransInnerResult * Var * Expr | Other of Expr | Source of Expr + static member MakeSelect (canElim, isQTy, mutSource, mutSelectorVar, mutSelectorBody) = // We can eliminate a Select if it is either selecting on a non-source or is being added in a inner position. - let canElim = - match mutSource with + let canElim = + match mutSource with | TransInnerResult.Source _ -> canElim | _ -> CanEliminate.Yes - // We eliminate the Select here to keep the information in 'mutSource' available, i.e. whether + // We eliminate the Select here to keep the information in 'mutSource' available, i.e. whether // the mutSource is a TransInnerResult.Source after elimination - match mutSelectorBody with + match mutSelectorBody with | Patterns.Var(v2) when mutSelectorVar = v2 && canElim = CanEliminate.Yes -> mutSource | _ -> Select(canElim, isQTy, mutSource, mutSelectorVar, mutSelectorBody) /// Commit the result of TransInner in the case where the result was not immediately inside a 'SelectMany' - let rec CommitTransInnerResult c = - match c with - | TransInnerResult.Source(res) -> res - | TransInnerResult.Other(res) -> res - | TransInnerResult.Select(canElim, isQTy, mutSource, mutSelectorVar, mutSelectorBody) -> - MakeSelect(canElim,isQTy, CommitTransInnerResult mutSource, mutSelectorVar, mutSelectorBody) - - /// Given a the inner of query expression in terms of query.For, query.Select, query.Yield, query.Where etc., - /// and including immutable tuples and immutable records, build an equivalent query expression - /// in terms of LINQ operators, operating over mutable tuples. Return the conversion + let rec CommitTransInnerResult c = + match c with + | TransInnerResult.Source res -> res + | TransInnerResult.Other res -> res + | TransInnerResult.Select(canElim, isQTy, mutSource, mutSelectorVar, mutSelectorBody) -> + MakeSelect(canElim, isQTy, CommitTransInnerResult mutSource, mutSelectorVar, mutSelectorBody) + + /// Given a the inner of query expression in terms of query.For, query.Select, query.Yield, query.Where etc., + /// and including immutable tuples and immutable records, build an equivalent query expression + /// in terms of LINQ operators, operating over mutable tuples. Return the conversion /// information for the immutable-to-mutable conversion performed so we can undo it where needed. /// /// Here 'inner' refers the the part of the query that produces a sequence of results. /// /// The output query will use either Queryable.* or Enumerable.* operators depending on whether /// the inputs to the queries have type IQueryable or IEnumerable. - let rec TransInner canElim check (immutQuery:Expr) = + let rec TransInner canElim check (immutQuery:Expr) = //assert (IsIQueryableTy immutQuery.Type || IsQuerySourceTy immutQuery.Type || IsIEnumerableTy immutQuery.Type) // printfn "TransInner: %A" tm - match immutQuery with + match immutQuery with - // Look through coercions, e.g. to IEnumerable - | Coerce (expr,_ty) -> + // Look through coercions, e.g. to IEnumerable + | Coerce (expr, _ty) -> TransInner canElim check expr - // Rewrite "for" into SelectMany. If the body of a "For" is nothing but Yield/IfThenElse, + // Rewrite "for" into SelectMany. If the body of a "For" is nothing but Yield/IfThenElse, // then it can be rewritten to Select + Where. // - // If the original body of the "for" in the text of the F# query expression uses "where" or - // any other custom operator, then the body of the "for" as presented to the quotation + // If the original body of the "for" in the text of the F# query expression uses "where" or + // any other custom operator, then the body of the "for" as presented to the quotation // rewrite has had the custom operator translation mechanism applied. In this case, the // body of the "for" will simply contain "yield". - - | CallQueryBuilderFor (_, [_;qTy;immutResElemTy;_], [immutSource; Lambda(immutSelectorVar, immutSelector) ]) -> - + + | CallQueryBuilderFor (_, [_; qTy; immutResElemTy; _], [immutSource; Lambda(immutSelectorVar, immutSelector) ]) -> + let mutSource, sourceConv = TransInner CanEliminate.Yes check immutSource // If the body of a "For" is nothing but Yield/IfThenElse/Where, then it can be fully rewritten away. - let rec TransFor mutSource immutSelector = - match immutSelector with + let rec TransFor mutSource immutSelector = + match immutSelector with - // query.For (source, (fun selectorVar -> yield res)) @> + // query.For (source, (fun selectorVar -> yield res)) @> // ~~> TRANS(source.Select(selectorVar -> res) - | CallQueryBuilderYield(_, _, immutSelectorBody) -> + | CallQueryBuilderYield(_, _, immutSelectorBody) -> - let mutSelectorVar, mutSelectorBody = ConvertImmutableConsumerToMutableConsumer sourceConv (immutSelectorVar, MacroExpand immutSelectorBody) + let mutSelectorVar, mutSelectorBody = ConvertImmutableConsumerToMutableConsumer sourceConv (immutSelectorVar, MacroExpand immutSelectorBody) let mutSelectorBody, selectorConv = ProduceMoreMutables TransInnerNoCheck mutSelectorBody let mutSelectorBody = CleanupLeaf mutSelectorBody TransInnerResult.MakeSelect (canElim, qTyIsIQueryable qTy, mutSource, mutSelectorVar, mutSelectorBody), selectorConv - | LetExprReduction reduced -> TransFor mutSource reduced - | MacroReduction reduced -> TransFor mutSource reduced + | LetExprReduction reduced -> + TransFor mutSource reduced + + | MacroReduction reduced -> + TransFor mutSource reduced - // query.For (source, (fun selectorVar -> if g then selectorBody else query.Zero())) @> + // query.For (source, (fun selectorVar -> if g then selectorBody else query.Zero())) @> // ~~> TRANS(query.For (source.Where(fun selectorVar -> g), (fun selectorVar -> selectorBody)) - | CallWhere (_, _, immutSelectorBody, Lambda(_, immutPredicateBody)) - | IfThenElse(immutPredicateBody, immutSelectorBody, ZeroOnElseBranch) -> + | CallWhere (_, _, immutSelectorBody, Lambda(_, immutPredicateBody)) + | IfThenElse (immutPredicateBody, immutSelectorBody, ZeroOnElseBranch) -> - let mutSelectorVar, mutPredicateBody = ConvertImmutableConsumerToMutableConsumer sourceConv (immutSelectorVar, MacroExpand immutPredicateBody) + let mutSelectorVar, mutPredicateBody = ConvertImmutableConsumerToMutableConsumer sourceConv (immutSelectorVar, MacroExpand immutPredicateBody) let mutSource = MakeWhere(qTyIsIQueryable qTy, CommitTransInnerResult mutSource, mutSelectorVar, mutPredicateBody) TransFor (TransInnerResult.Other mutSource) immutSelectorBody - // query.For (source, (fun selectorVar -> immutSelectorBody)) @> + // query.For (source, (fun selectorVar -> immutSelectorBody)) @> // ~~> source.SelectMany(fun selectorVar -> immutSelectorBody) | immutSelectorBody -> - let mutSelectorVar, immutSelectorBody = ConvertImmutableConsumerToMutableConsumer sourceConv (immutSelectorVar, MacroExpand immutSelectorBody) + let mutSelectorVar, immutSelectorBody = ConvertImmutableConsumerToMutableConsumer sourceConv (immutSelectorVar, MacroExpand immutSelectorBody) let (mutSelectorBodyInfo:TransInnerResult), selectorConv = TransInner CanEliminate.Yes check immutSelectorBody let mutElemTy = ConvImmutableTypeToMutableType selectorConv immutResElemTy /// Commit the result of TransInner in the case where the result is immediately inside a 'SelectMany' - let (mutInterimSelectorBodyPreCoerce:Expr), mutInterimVar, mutTargetSelector = - match mutSelectorBodyInfo with + let (mutInterimSelectorBodyPreCoerce:Expr), mutInterimVar, mutTargetSelector = + match mutSelectorBodyInfo with | TransInnerResult.Select(_, _, mutInterimSelectorSource, mutInterimVar, mutTargetSelector) -> CommitTransInnerResult mutInterimSelectorSource, mutInterimVar, mutTargetSelector - | _ -> + | _ -> let mutInterimSelectorBody = CommitTransInnerResult mutSelectorBodyInfo let mutInterimVar = Var("x", mutElemTy) let mutTargetSelector = Expr.Var(mutInterimVar) mutInterimSelectorBody, mutInterimVar, mutTargetSelector - + // IQueryable.SelectMany expects an IEnumerable return - let mutInterimSelectorBody = + let mutInterimSelectorBody = let mutSelectorBodyTy = mutInterimSelectorBodyPreCoerce.Type - if mutSelectorBodyTy.IsGenericType && mutSelectorBodyTy.GetGenericTypeDefinition() = typedefof> then + if mutSelectorBodyTy.IsGenericType && mutSelectorBodyTy.GetGenericTypeDefinition() = typedefof> then mutInterimSelectorBodyPreCoerce else let mutSeqTy = MakeIEnumerableTy mutInterimVar.Type @@ -1253,14 +1355,14 @@ module Query = TransFor mutSource immutSelector - - // These occur in the F# quotation form of F# sequence expressions - | CallWhere (_, [_;qTy], immutSource, Lambda(immutSelectorVar, immutPredicateBody)) -> + + // These occur in the F# quotation form of F# sequence expressions + | CallWhere (_, [_; qTy], immutSource, Lambda(immutSelectorVar, immutPredicateBody)) -> let mutSource, sourceConv, mutSelectorVar, mutPredicateBody = TransInnerApplicativeAndCommit check immutSource (immutSelectorVar, immutPredicateBody) TransInnerResult.Other(MakeWhere(qTyIsIQueryable qTy, mutSource, mutSelectorVar, mutPredicateBody)), sourceConv - | CallSelect (_, [_;qTy;_], mutSource, Lambda(immutSelectorVar, immutSelectorBody)) -> + | CallSelect (_, [_; qTy; _], mutSource, Lambda(immutSelectorVar, immutSelectorBody)) -> let mutSource, _sourceConv, mutSelectorVar, mutSelectorBody = TransInnerApplicative check mutSource (immutSelectorVar, immutSelectorBody) let mutSelectorBody, selectorConv = ProduceMoreMutables TransInnerNoCheck mutSelectorBody @@ -1270,228 +1372,269 @@ module Query = | CallQueryBuilderYieldFrom (_, _, [source]) -> TransInner canElim check source - | CallQueryBuilderYield(_, [elemTy; qTy], immutSelectorBody) -> + | CallQueryBuilderYield (_, [elemTy; qTy], immutSelectorBody) -> let immutSelectorBody = CleanupLeaf immutSelectorBody - let enumExpr = Expr.Coerce(Expr.NewArray(elemTy,[ immutSelectorBody ]), MakeIEnumerableTy elemTy) - let expr = - if qTyIsIQueryable qTy then + let enumExpr = Expr.Coerce(Expr.NewArray(elemTy, [ immutSelectorBody ]), MakeIEnumerableTy elemTy) + let expr = + if qTyIsIQueryable qTy then MakeAsQueryable(elemTy, enumExpr) else - enumExpr + enumExpr TransInnerResult.Other(expr), NoConv - | IfThenElse(g, t, e) -> - match MacroExpand e with - | ZeroOnElseBranch -> + | IfThenElse (g, t, e) -> + match MacroExpand e with + | ZeroOnElseBranch -> let t, tConv = TransInnerAndCommit CanEliminate.Yes check t TransInnerResult.Other(Expr.IfThenElse(g, t, MakeEmpty t.Type)), tConv - | _ -> + | _ -> if check then raise (NotSupportedException (SR.GetString(SR.unsupportedIfThenElse)) ) - else TransInnerResult.Other(e), NoConv - - | CallSortBy (_, [_;qTy;_], source, Lambda(v, keySelector)) -> + TransInnerResult.Other(e), NoConv + + | CallSortBy (_, [_; qTy; _], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeOrderBy (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallSortByDescending (_, [_;qTy;_], source, Lambda(v, keySelector)) -> + | CallSortByDescending (_, [_; qTy; _], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeOrderByDescending (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallThenBy (_, [_;qTy;_], source, Lambda(v, keySelector)) -> + | CallThenBy (_, [_; qTy; _], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeThenBy (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallThenByDescending (_, [_;qTy;_], source, Lambda(v, keySelector)) -> + | CallThenByDescending (_, [_; qTy; _], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeThenByDescending (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallSortByNullable (_, [_;qTy;_], source, Lambda(v, keySelector)) -> + | CallSortByNullable (_, [_; qTy; _], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeOrderByNullable (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallSortByNullableDescending(_, [_;qTy;_], source, Lambda(v, keySelector)) -> + | CallSortByNullableDescending(_, [_; qTy; _], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeOrderByNullableDescending(qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallThenByNullable (_, [_;qTy;_], source, Lambda(v, keySelector)) -> + | CallThenByNullable (_, [_; qTy; _], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeThenByNullable (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallThenByNullableDescending (_, [_;qTy;_], source, Lambda(v, keySelector)) -> + | CallThenByNullableDescending (_, [_; qTy; _], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeThenByNullableDescending (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallDistinct (_, [srcItemTy; qTy], source) -> - let source, sourceConv = TransInnerAndCommit CanEliminate.Yes check source - TransInnerResult.Other(MakeDistinct(qTyIsIQueryable qTy, ConvImmutableTypeToMutableType sourceConv srcItemTy,source)), sourceConv + | CallDistinct (_, [srcItemTy; qTy], source) -> + let source, sourceConv = TransInnerAndCommit CanEliminate.Yes check source + let srcItemTyR = ConvImmutableTypeToMutableType sourceConv srcItemTy + TransInnerResult.Other(MakeDistinct(qTyIsIQueryable qTy, srcItemTyR, source)), sourceConv - | CallSkip(_, [srcItemTy; qTy], source, count) -> - let source, sourceConv = TransInnerAndCommit CanEliminate.Yes check source - TransInnerResult.Other(MakeSkip(qTyIsIQueryable qTy, ConvImmutableTypeToMutableType sourceConv srcItemTy, source, MacroExpand count)), sourceConv + | CallSkip(_, [srcItemTy; qTy], source, count) -> + let source, sourceConv = TransInnerAndCommit CanEliminate.Yes check source + let srcItemTyR = ConvImmutableTypeToMutableType sourceConv srcItemTy + TransInnerResult.Other(MakeSkip(qTyIsIQueryable qTy, srcItemTyR, source, MacroExpand count)), sourceConv - | CallTake(_, [srcItemTy; qTy], source, count) -> - let source, sourceConv = TransInnerAndCommit CanEliminate.Yes check source - TransInnerResult.Other(MakeTake(qTyIsIQueryable qTy, ConvImmutableTypeToMutableType sourceConv srcItemTy, source, MacroExpand count)), sourceConv + | CallTake(_, [srcItemTy; qTy], source, count) -> + let source, sourceConv = TransInnerAndCommit CanEliminate.Yes check source + let srcItemTyR = ConvImmutableTypeToMutableType sourceConv srcItemTy + TransInnerResult.Other(MakeTake(qTyIsIQueryable qTy, srcItemTyR, source, MacroExpand count)), sourceConv - | CallSkipWhile(_, [_; qTy], source, Lambda(v, keySelector)) -> + | CallSkipWhile(_, [_; qTy], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeSkipWhile (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallTakeWhile(_, [_; qTy], source, Lambda(v, keySelector)) -> + | CallTakeWhile(_, [_; qTy], source, Lambda(v, keySelector)) -> let source, sourceConv, v, keySelector = TransInnerApplicativeAndCommit check source (v, keySelector) TransInnerResult.Other(MakeTakeWhile (qTyIsIQueryable qTy, source, v, keySelector)), sourceConv - | CallGroupBy(_, [_; qTy; _], immutSource, Lambda(immutVar, immutKeySelector)) -> + | CallGroupBy(_, [_; qTy; _], immutSource, Lambda(immutVar, immutKeySelector)) -> let mutSource, sourceConv = TransInnerAndCommit CanEliminate.Yes check immutSource - let mutVar, mutKeySelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar, MacroExpand immutKeySelector) - let conv = match sourceConv with NoConv -> NoConv | _ -> GroupingConv(immutKeySelector.Type,immutVar.Type,sourceConv) + let mutVar, mutKeySelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar, MacroExpand immutKeySelector) + let conv = + match sourceConv with + | NoConv -> NoConv + | _ -> GroupingConv(immutKeySelector.Type, immutVar.Type, sourceConv) TransInnerResult.Other(MakeGroupBy(qTyIsIQueryable qTy, mutSource, mutVar, mutKeySelector)), conv - | CallGroupValBy(_, [_; _; _; qTy], immutSource, Lambda(immutVar1, immutElementSelector), Lambda(immutVar2, immutKeySelector)) -> + | CallGroupValBy + (_, [_; _; _; qTy], + immutSource, + Lambda(immutVar1, immutElementSelector), + Lambda(immutVar2, immutKeySelector)) -> let mutSource, sourceConv = TransInnerAndCommit CanEliminate.Yes check immutSource - let mutVar2, mutKeySelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar2, MacroExpand immutKeySelector) - let mutVar1, mutElementSelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar1, MacroExpand immutElementSelector) + let mutVar2, mutKeySelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar2, MacroExpand immutKeySelector) + let mutVar1, mutElementSelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar1, MacroExpand immutElementSelector) let mutElementSelector, selectorConv = ProduceMoreMutables TransInnerNoCheck mutElementSelector let mutElementSelector = CleanupLeaf mutElementSelector - let conv = match selectorConv with NoConv -> NoConv | _ -> GroupingConv (immutKeySelector.Type,immutElementSelector.Type,selectorConv) + let conv = + match selectorConv with + | NoConv -> NoConv + | _ -> GroupingConv (immutKeySelector.Type, immutElementSelector.Type, selectorConv) TransInnerResult.Other(MakeGroupValBy(qTyIsIQueryable qTy, mutVar1.Type, mutKeySelector.Type, mutElementSelector.Type, mutSource, mutVar2, mutKeySelector, mutVar1, mutElementSelector)), conv -#if SUPPORT_ZIP_IN_QUERIES - | CallZip(None, [ firstSourceTy; secondSourceTy; resTy ], [firstSource;secondSource;LambdasNoDetupling([firstElementVar;secondElementVar], elementSelector)])-> - - MakeZip(firstSourceTy, secondSourceTy, resTy, TransInner CanEliminate.Yes firstSource, TransInner CanEliminate.Yes secondSource, firstElementVar, secondElementVar, MacroExpand elementSelector) -#endif - - | CallJoin(_, [_; qTy; _; _; _], [immutOuterSource;immutInnerSource; - Lambda(immutOuterKeyVar, immutOuterKeySelector); - Lambda(immutInnerKeyVar, immutInnerKeySelector); - LambdasNoDetupling([immutOuterResultGroupVar;immutInnerResultKeyVar], immutElementSelector)])-> + | CallJoin(_, [_; qTy; _; _; _], + [ immutOuterSource + immutInnerSource + Lambda(immutOuterKeyVar, immutOuterKeySelector) + Lambda(immutInnerKeyVar, immutInnerKeySelector) + LambdasNoDetupling([immutOuterResultGroupVar; immutInnerResultKeyVar], immutElementSelector)]) -> - let (mutOuterSource, outerSourceConv, mutInnerSource, innerSourceConv, mutOuterKeyVar:Var, mutOuterKeySelector, mutInnerKeyVar:Var, mutInnerKeySelector:Expr) = + let (mutOuterSource, outerSourceConv, mutInnerSource, innerSourceConv, mutOuterKeyVar:Var, mutOuterKeySelector, mutInnerKeyVar:Var, mutInnerKeySelector:Expr) = TransJoinInputs check (immutOuterSource, immutInnerSource, immutOuterKeyVar, immutOuterKeySelector, immutInnerKeyVar, immutInnerKeySelector) - let mutOuterResultVar,mutElementSelector = ConvertImmutableConsumerToMutableConsumer outerSourceConv (immutOuterResultGroupVar, MacroExpand immutElementSelector) - let mutInnerResultKeyVar,mutElementSelector = ConvertImmutableConsumerToMutableConsumer innerSourceConv (immutInnerResultKeyVar, mutElementSelector) + let mutOuterResultVar, mutElementSelector = ConvertImmutableConsumerToMutableConsumer outerSourceConv (immutOuterResultGroupVar, MacroExpand immutElementSelector) + let mutInnerResultKeyVar, mutElementSelector = ConvertImmutableConsumerToMutableConsumer innerSourceConv (immutInnerResultKeyVar, mutElementSelector) let mutElementSelector, elementSelectorConv = ProduceMoreMutables TransInnerNoCheck mutElementSelector let mutElementSelector = CleanupLeaf mutElementSelector - TransInnerResult.Other(MakeJoin(qTyIsIQueryable qTy, mutOuterKeyVar.Type, mutInnerKeyVar.Type, mutInnerKeySelector.Type, mutElementSelector.Type, mutOuterSource, mutInnerSource, mutOuterKeyVar, mutOuterKeySelector, mutInnerKeyVar, mutInnerKeySelector, mutOuterResultVar, mutInnerResultKeyVar, mutElementSelector)),elementSelectorConv - | CallGroupJoin(_, [_; qTy; _; _; _], [immutOuterSource;immutInnerSource;Lambda(immutOuterKeyVar, immutOuterKeySelector);Lambda(immutInnerKeyVar, immutInnerKeySelector);LambdasNoDetupling([immutOuterResultGroupVar;immutInnerResultGroupVar], immutElementSelector)])-> + let joinExpr = + MakeJoin + (qTyIsIQueryable qTy, mutOuterKeyVar.Type, mutInnerKeyVar.Type, mutInnerKeySelector.Type, + mutElementSelector.Type, mutOuterSource, mutInnerSource, mutOuterKeyVar, mutOuterKeySelector, + mutInnerKeyVar, mutInnerKeySelector, mutOuterResultVar, mutInnerResultKeyVar, mutElementSelector) + + TransInnerResult.Other joinExpr, elementSelectorConv - let (mutOuterSource, outerSourceConv, mutInnerSource, innerSourceConv, mutOuterKeyVar:Var, mutOuterKeySelector, mutInnerKeyVar:Var, mutInnerKeySelector:Expr) = + | CallGroupJoin + (_, [_; qTy; _; _; _], + [ immutOuterSource + immutInnerSource + Lambda(immutOuterKeyVar, immutOuterKeySelector) + Lambda(immutInnerKeyVar, immutInnerKeySelector) + LambdasNoDetupling([immutOuterResultGroupVar; immutInnerResultGroupVar], immutElementSelector)]) -> + + let (mutOuterSource, outerSourceConv, mutInnerSource, innerSourceConv, mutOuterKeyVar:Var, mutOuterKeySelector, mutInnerKeyVar:Var, mutInnerKeySelector:Expr) = TransJoinInputs check (immutOuterSource, immutInnerSource, immutOuterKeyVar, immutOuterKeySelector, immutInnerKeyVar, immutInnerKeySelector) - let mutOuterResultGroupVar,mutElementSelector = ConvertImmutableConsumerToMutableConsumer outerSourceConv (immutOuterResultGroupVar, MacroExpand immutElementSelector) - let innerGroupConv = MakeSeqConv innerSourceConv - let mutInnerResultKeyVar,mutElementSelector = ConvertImmutableConsumerToMutableConsumer innerGroupConv (immutInnerResultGroupVar, mutElementSelector) + let mutOuterResultGroupVar, mutElementSelector = ConvertImmutableConsumerToMutableConsumer outerSourceConv (immutOuterResultGroupVar, MacroExpand immutElementSelector) + let innerGroupConv = MakeSeqConv innerSourceConv + let mutInnerResultKeyVar, mutElementSelector = ConvertImmutableConsumerToMutableConsumer innerGroupConv (immutInnerResultGroupVar, mutElementSelector) let mutElementSelector, elementSelectorConv = ProduceMoreMutables TransInnerNoCheck mutElementSelector let mutElementSelector = CleanupLeaf mutElementSelector - TransInnerResult.Other(MakeGroupJoin(qTyIsIQueryable qTy, mutOuterKeyVar.Type, mutInnerKeyVar.Type, mutInnerKeySelector.Type, mutElementSelector.Type, mutOuterSource, mutInnerSource, mutOuterKeyVar, mutOuterKeySelector, mutInnerKeyVar, mutInnerKeySelector, mutOuterResultGroupVar, mutInnerResultKeyVar, mutElementSelector)), elementSelectorConv + let joinExpr = + MakeGroupJoin + (qTyIsIQueryable qTy, mutOuterKeyVar.Type, mutInnerKeyVar.Type, + mutInnerKeySelector.Type, mutElementSelector.Type, mutOuterSource, + mutInnerSource, mutOuterKeyVar, mutOuterKeySelector, mutInnerKeyVar, + mutInnerKeySelector, mutOuterResultGroupVar, mutInnerResultKeyVar, mutElementSelector) + + TransInnerResult.Other joinExpr, elementSelectorConv - | CallLeftOuterJoin(_, [ _; qTy; immutInnerSourceTy; _; _], [immutOuterSource;immutInnerSource;Lambda(immutOuterKeyVar, immutOuterKeySelector);Lambda(immutInnerKeyVar, immutInnerKeySelector);LambdasNoDetupling([immutOuterResultGroupVar;immutInnerResultGroupVar], immutElementSelector)])-> + | CallLeftOuterJoin + (_, [ _; qTy; immutInnerSourceTy; _; _], + [ immutOuterSource + immutInnerSource + Lambda(immutOuterKeyVar, immutOuterKeySelector) + Lambda(immutInnerKeyVar, immutInnerKeySelector) + LambdasNoDetupling([immutOuterResultGroupVar; immutInnerResultGroupVar], immutElementSelector)]) -> // Replace uses of 'innerResultGroupVar' with 'innerResultGroupVar.DefaultIfEmpty()' and call MakeGroupJoin let immutElementSelector = immutElementSelector.Substitute (fun v -> if v = immutInnerResultGroupVar then Some (MakeDefaultIfEmpty ([immutInnerSourceTy], [Expr.Var immutInnerResultGroupVar])) else None) - let (mutOuterSource, outerSourceConv, mutInnerSource, innerSourceConv, mutOuterKeyVar:Var, mutOuterKeySelector, mutInnerKeyVar:Var, mutInnerKeySelector:Expr) = + let (mutOuterSource, outerSourceConv, mutInnerSource, innerSourceConv, mutOuterKeyVar:Var, mutOuterKeySelector, mutInnerKeyVar:Var, mutInnerKeySelector:Expr) = TransJoinInputs check (immutOuterSource, immutInnerSource, immutOuterKeyVar, immutOuterKeySelector, immutInnerKeyVar, immutInnerKeySelector) - let mutOuterResultGroupVar,mutElementSelector = ConvertImmutableConsumerToMutableConsumer outerSourceConv (immutOuterResultGroupVar, MacroExpand immutElementSelector) - let mutInnerResultKeyVar,mutElementSelector = ConvertImmutableConsumerToMutableConsumer innerSourceConv (immutInnerResultGroupVar, mutElementSelector) + let mutOuterResultGroupVar, mutElementSelector = ConvertImmutableConsumerToMutableConsumer outerSourceConv (immutOuterResultGroupVar, MacroExpand immutElementSelector) + let mutInnerResultKeyVar, mutElementSelector = ConvertImmutableConsumerToMutableConsumer innerSourceConv (immutInnerResultGroupVar, mutElementSelector) let mutElementSelector, elementSelectorConv = ProduceMoreMutables TransInnerNoCheck mutElementSelector let mutElementSelector = CleanupLeaf mutElementSelector - TransInnerResult.Other(MakeGroupJoin(qTyIsIQueryable qTy, mutOuterKeyVar.Type, mutInnerKeyVar.Type, mutInnerKeySelector.Type, mutElementSelector.Type, mutOuterSource, mutInnerSource, mutOuterKeyVar, mutOuterKeySelector, mutInnerKeyVar, mutInnerKeySelector, mutOuterResultGroupVar, mutInnerResultKeyVar, mutElementSelector)), elementSelectorConv + let joinExpr = + MakeGroupJoin + (qTyIsIQueryable qTy, mutOuterKeyVar.Type, mutInnerKeyVar.Type, mutInnerKeySelector.Type, + mutElementSelector.Type, mutOuterSource, mutInnerSource, mutOuterKeyVar, mutOuterKeySelector, + mutInnerKeyVar, mutInnerKeySelector, mutOuterResultGroupVar, mutInnerResultKeyVar, mutElementSelector) - | LetExprReduction reduced -> TransInner canElim check reduced - | MacroReduction reduced -> TransInner canElim check reduced + TransInnerResult.Other joinExpr, elementSelectorConv + | LetExprReduction reduced -> + TransInner canElim check reduced - | CallQueryBuilderSourceIQueryable(_, _,expr) -> // expr when typeof.IsAssignableFrom(expr.Type) -> + | MacroReduction reduced -> + TransInner canElim check reduced + | CallQueryBuilderSourceIQueryable(_, _, expr) -> TransInnerResult.Source(expr), NoConv - | CallQueryBuilderSourceIEnumerable (_, _, expr) -> // expr when typeof.IsAssignableFrom(expr.Type) -> - //raise (NotSupportedException (Printf.sprintf "Unexpected use of query.Source with IEnumerable input: %A" immutQuery)) + | CallQueryBuilderSourceIEnumerable (_, _, expr) -> TransInnerResult.Source(expr), NoConv - | Call (_, meth, _) when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryCall),meth.ToString()))) + | Call (_, meth, _) when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryCall), meth.ToString()))) - | PropertyGet (_, pinfo, _) when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryProperty),pinfo.ToString()))) + | PropertyGet (_, pinfo, _) when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryProperty), pinfo.ToString()))) - | NewObject(ty,_) when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstructKind),"new " + ty.ToString()))) + | NewObject(ty, _) when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstructKind), "new " + ty.ToString()))) - | NewArray(ty,_) when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstructKind),"NewArray(" + ty.Name + ",...)"))) + | NewArray(ty, _) when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstructKind), "NewArray(" + ty.Name + ", ...)"))) - | NewTuple _ when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstructKind),"NewTuple(...)"))) + | NewTuple _ when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstructKind), "NewTuple(...)"))) - | FieldGet (_,field) when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstructKind),"FieldGet(" + field.Name + ",...)"))) + | FieldGet (_, field) when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstructKind), "FieldGet(" + field.Name + ", ...)"))) - | LetRecursive _ when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct),"LetRecursive(...)"))) + | LetRecursive _ when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct), "LetRecursive(...)"))) - | NewRecord _ when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct),"NewRecord(...)"))) + | NewRecord _ when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct), "NewRecord(...)"))) - | NewDelegate _ when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct),"NewDelegate(...)"))) + | NewDelegate _ when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct), "NewDelegate(...)"))) - | NewTuple _ when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct),"NewTuple(...)"))) + | NewTuple _ when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct), "NewTuple(...)"))) - | NewUnionCase (ucase,_) when check -> - raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct),"NewUnionCase(" + ucase.Name + "...)"))) + | NewUnionCase (ucase, _) when check -> + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct), "NewUnionCase(" + ucase.Name + "...)"))) // Error cases - | e -> - if check then raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct),immutQuery.ToString()))) - else TransInnerResult.Source(e),NoConv - + | _ -> + if check then + raise (NotSupportedException (String.Format(SR.GetString(SR.unsupportedQueryConstruct), immutQuery.ToString()))) + TransInnerResult.Source immutQuery, NoConv - and TransInnerAndCommit canElim check x = + and TransInnerAndCommit canElim check x = let info, conv = TransInner canElim check x CommitTransInnerResult info, conv - and TransNone x = (x,NoConv) + and TransNone x = (x, NoConv) - // We translate nested queries directly in order to + // We translate nested queries directly in order to // propagate a immutable-->mutable-->immutable translation if any. // - /// This is used on recursive translations of yielded elements to translate nested queries - /// in 'yield' position and still propagate information about a possible imutable->mutable->mutable + /// This is used on recursive translations of yielded elements to translate nested queries + /// in 'yield' position and still propagate information about a possible imutable->mutable->mutable // translation. - // e.g. yield (1,query { ... }) - and TransInnerNoCheck e = - match e with - | EnumerableNestedQuery nestedQuery -> + // e.g. yield (1, query { ... }) + and TransInnerNoCheck e = + match e with + | EnumerableNestedQuery nestedQuery -> let replNestedQuery, conv = TransInnerAndCommit CanEliminate.Yes false nestedQuery - let replNestedQuery = + let replNestedQuery = let tyArg = replNestedQuery.Type.GetGenericArguments().[0] let IQueryableTySpec = MakeIQueryableTy tyArg - // if result type of nested query is derived from IQueryable but not IQueryable itself (i.e. IOrderedQueryable) + // if result type of nested query is derived from IQueryable but not IQueryable itself (i.e. IOrderedQueryable) // then add coercion to IQueryable so result type will match expected signature of QuerySource.Run if (IQueryableTySpec.IsAssignableFrom replNestedQuery.Type) && not (IQueryableTySpec.Equals replNestedQuery.Type) then Expr.Coerce(replNestedQuery, IQueryableTySpec) else replNestedQuery replNestedQuery, MakeSeqConv conv - | _ -> + | _ -> e, NoConv - and TransJoinInputs check (immutOuterSource, immutInnerSource, immutOuterKeyVar, immutOuterKeySelector, immutInnerKeyVar, immutInnerKeySelector) = + and TransJoinInputs check (immutOuterSource, immutInnerSource, immutOuterKeyVar, immutOuterKeySelector, immutInnerKeyVar, immutInnerKeySelector) = let mutOuterSource, outerSourceConv = TransInnerAndCommit CanEliminate.Yes check immutOuterSource let mutInnerSource, innerSourceConv = TransInnerAndCommit CanEliminate.Yes check immutInnerSource - let mutOuterKeyVar, mutOuterKeySelector = ConvertImmutableConsumerToMutableConsumer outerSourceConv (immutOuterKeyVar, MacroExpand immutOuterKeySelector) - let mutInnerKeyVar, mutInnerKeySelector = ConvertImmutableConsumerToMutableConsumer innerSourceConv (immutInnerKeyVar, MacroExpand immutInnerKeySelector) + let mutOuterKeyVar, mutOuterKeySelector = ConvertImmutableConsumerToMutableConsumer outerSourceConv (immutOuterKeyVar, MacroExpand immutOuterKeySelector) + let mutInnerKeyVar, mutInnerKeySelector = ConvertImmutableConsumerToMutableConsumer innerSourceConv (immutInnerKeyVar, MacroExpand immutInnerKeySelector) // Keys may be composite tuples - convert them to be mutables. Note, if there is a tuple on one side, there must be a tuple on the other side. let mutOuterKeySelector, _ = ProduceMoreMutables TransNone mutOuterKeySelector @@ -1500,187 +1643,190 @@ module Query = let mutInnerKeySelector = CleanupLeaf mutInnerKeySelector mutOuterSource, outerSourceConv, mutInnerSource, innerSourceConv, mutOuterKeyVar, mutOuterKeySelector, mutInnerKeyVar, mutInnerKeySelector - /// Given a query expression in terms of query.For, query.Select, query.Yield, query.Where etc., - /// and including immutable tuples and immutable records, build an equivalent query expression - /// in terms of LINQ operators, operating over mutable tuples. Return the conversion + /// Given a query expression in terms of query.For, query.Select, query.Yield, query.Where etc., + /// and including immutable tuples and immutable records, build an equivalent query expression + /// in terms of LINQ operators, operating over mutable tuples. Return the conversion /// information for the immutable-to-mutable conversion performed so we can undo it where needed. /// /// Further, assume that the elements produced by the query will be consumed by the function "(fun immutConsumingVar -> immutConsumingExpr)" - /// and produce the expressions for a new function that consume the results directly. - and TransInnerApplicative check source (immutConsumingVar, immutConsumingExpr) = + /// and produce the expressions for a new function that consume the results directly. + and TransInnerApplicative check source (immutConsumingVar, immutConsumingExpr) = let source, sourceConv = TransInner CanEliminate.Yes check source - let mutConsumingVar, mutConsumingExpr = ConvertImmutableConsumerToMutableConsumer sourceConv (immutConsumingVar, MacroExpand immutConsumingExpr) + let mutConsumingVar, mutConsumingExpr = ConvertImmutableConsumerToMutableConsumer sourceConv (immutConsumingVar, MacroExpand immutConsumingExpr) source, sourceConv, mutConsumingVar, mutConsumingExpr - and TransInnerApplicativeAndCommit check source (immutConsumingVar, immutConsumingExpr) = + and TransInnerApplicativeAndCommit check source (immutConsumingVar, immutConsumingExpr) = let source, sourceConv, mutConsumingVar, mutConsumingExpr = TransInnerApplicative check source (immutConsumingVar, immutConsumingExpr) CommitTransInnerResult source, sourceConv, mutConsumingVar, mutConsumingExpr - /// Given a query expression in terms of query.For, query.Select, query.Yield, query.Where etc., - /// and including immutable tuples and immutable records, build an equivalent query expression + /// Given a query expression in terms of query.For, query.Select, query.Yield, query.Where etc., + /// and including immutable tuples and immutable records, build an equivalent query expression /// in terms of LINQ operators, operating over mutable tuples. If necessary, also add a "postifx" in-memory transformation /// converting the data back to immutable tuples and records. - let TransInnerWithFinalConsume canElim immutSource = + let TransInnerWithFinalConsume canElim immutSource = let mutSource, sourceConv = TransInnerAndCommit canElim true immutSource - match sourceConv with - | NoConv -> + match sourceConv with + | NoConv -> mutSource - | _ -> - // This function is used with inputs of - // - QuerySource<_,_> (for operators like Min) + | _ -> + // This function is used with inputs of + // - QuerySource<_, _> (for operators like Min) // - IQueryable<_> (for operators like MinBy) // - IEnumerable<_> (for nested queries) let immutSourceTy = immutSource.Type - let immutSourceElemTy = - assert immutSourceTy.IsGenericType; - assert (IsQuerySourceTy immutSourceTy || IsIQueryableTy immutSourceTy || IsIEnumerableTy immutSourceTy); + let immutSourceElemTy = + assert immutSourceTy.IsGenericType + assert (IsQuerySourceTy immutSourceTy || IsIQueryableTy immutSourceTy || IsIEnumerableTy immutSourceTy) immutSource.Type.GetGenericArguments().[0] - let immutVar = Var("after",immutSourceElemTy) - let mutVar, mutToImmutSelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar, Expr.Var immutVar) + let immutVar = Var("after", immutSourceElemTy) + let mutVar, mutToImmutSelector = ConvertImmutableConsumerToMutableConsumer sourceConv (immutVar, Expr.Var immutVar) let immutExprEnumerable = MakeSelect(CanEliminate.Yes, false, mutSource, mutVar, mutToImmutSelector) - let mustReturnIQueryable = - IsQuerySourceTy immutSourceTy && qTyIsIQueryable (immutSourceTy.GetGenericArguments().[1]) || + let mustReturnIQueryable = + IsQuerySourceTy immutSourceTy && qTyIsIQueryable (immutSourceTy.GetGenericArguments().[1]) || IsIQueryableTy immutSourceTy - let immutExprFinal = - if mustReturnIQueryable then MakeAsQueryable(immutSourceElemTy,immutExprEnumerable) + let immutExprFinal = + if mustReturnIQueryable then MakeAsQueryable(immutSourceElemTy, immutExprEnumerable) else immutExprEnumerable immutExprFinal - /// Like TransInnerApplicativeAndCommit but (a) assumes the query is nested and (b) throws away the conversion information, + /// Like TransInnerApplicativeAndCommit but (a) assumes the query is nested and (b) throws away the conversion information, /// i.e. assumes that the function "(fun immutConsumingVar -> immutConsumingExpr)" is the only consumption of the query. - let TransNestedInnerWithConsumer immutSource (immutConsumingVar, immutConsumingExpr) = + let TransNestedInnerWithConsumer immutSource (immutConsumingVar, immutConsumingExpr) = let mutSource, _sourceConv, mutConsumingVar, mutConsumingExpr = TransInnerApplicativeAndCommit true immutSource (immutConsumingVar, immutConsumingExpr) mutSource, mutConsumingVar, mutConsumingExpr - /// Translate nested query combinator calls to LINQ calls. - let rec TransNestedOuter canElim quot = + /// Translate nested query combinator calls to LINQ calls. + let rec TransNestedOuter canElim quot = match quot with - | CallMinBy (_, [_; qTy; _], source, Lambda(v, valSelector)) -> + | CallMinBy (_, [_; qTy; _], source, Lambda(v, valSelector)) -> let source, v, valSelector = TransNestedInnerWithConsumer source (v, valSelector) - MakeMinBy (qTyIsIQueryable qTy, source, v, valSelector) + MakeMinBy (qTyIsIQueryable qTy, source, v, valSelector) - | CallMaxBy (_, [_; qTy; _], source, Lambda(v, valSelector)) -> + | CallMaxBy (_, [_; qTy; _], source, Lambda(v, valSelector)) -> let source, v, valSelector = TransNestedInnerWithConsumer source (v, valSelector) - MakeMaxBy (qTyIsIQueryable qTy, source, v, valSelector) + MakeMaxBy (qTyIsIQueryable qTy, source, v, valSelector) - | CallMinByNullable (_, [_; qTy; _], source, Lambda(v, valSelector)) -> + | CallMinByNullable (_, [_; qTy; _], source, Lambda(v, valSelector)) -> let source, v, valSelector = TransNestedInnerWithConsumer source (v, valSelector) - MakeMinByNullable (qTyIsIQueryable qTy, source, v, valSelector) + MakeMinByNullable (qTyIsIQueryable qTy, source, v, valSelector) - | CallMaxByNullable (_, [_; qTy; _], source, Lambda(v, valSelector)) -> + | CallMaxByNullable (_, [_; qTy; _], source, Lambda(v, valSelector)) -> let source, v, valSelector = TransNestedInnerWithConsumer source (v, valSelector) - MakeMaxByNullable (qTyIsIQueryable qTy, source, v, valSelector) + MakeMaxByNullable (qTyIsIQueryable qTy, source, v, valSelector) - | CallCount (_, [srcItemTy; qTy], source) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source - MakeCount (qTyIsIQueryable qTy, srcItemTy, source) + | CallCount (_, [srcItemTy; qTy], source) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source + MakeCount (qTyIsIQueryable qTy, srcItemTy, source) - | CallHead (_, [srcItemTy; qTy], source) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source - MakeFirst (qTyIsIQueryable qTy, srcItemTy, source) + | CallHead (_, [srcItemTy; qTy], source) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source + MakeFirst (qTyIsIQueryable qTy, srcItemTy, source) - | CallLast (_, [srcItemTy; qTy], source) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source - MakeLast (qTyIsIQueryable qTy, srcItemTy, source) + | CallLast (_, [srcItemTy; qTy], source) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source + MakeLast (qTyIsIQueryable qTy, srcItemTy, source) - | CallHeadOrDefault (_, [srcItemTy; qTy], source) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source + | CallHeadOrDefault (_, [srcItemTy; qTy], source) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source MakeFirstOrDefault (qTyIsIQueryable qTy, srcItemTy, source) - | CallLastOrDefault (_, [srcItemTy; qTy], source) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source - MakeLastOrDefault (qTyIsIQueryable qTy, srcItemTy, source) + | CallLastOrDefault (_, [srcItemTy; qTy], source) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source + MakeLastOrDefault (qTyIsIQueryable qTy, srcItemTy, source) - | CallExactlyOne (_, [srcItemTy; qTy], source) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source - MakeSingle (qTyIsIQueryable qTy, srcItemTy, source) + | CallExactlyOne (_, [srcItemTy; qTy], source) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source + MakeSingle (qTyIsIQueryable qTy, srcItemTy, source) - | CallExactlyOneOrDefault (_, [srcItemTy; qTy], source) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source + | CallExactlyOneOrDefault (_, [srcItemTy; qTy], source) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source MakeSingleOrDefault(qTyIsIQueryable qTy, srcItemTy, source) - | CallAverageBy (qb, [_; qTy; _], source, Lambda(v, valSelector)) -> + | CallAverageBy (qb, [_; qTy; _], source, Lambda(v, valSelector)) -> let source, v, valSelector = TransNestedInnerWithConsumer source (v, valSelector) - MakeAverageBy (qb, qTyIsIQueryable qTy, source, v, valSelector) + MakeAverageBy (qb, qTyIsIQueryable qTy, source, v, valSelector) - | CallAverageByNullable (qb, [_; qTy; _], source, Lambda(v, valSelector)) -> + | CallAverageByNullable (qb, [_; qTy; _], source, Lambda(v, valSelector)) -> let source, v, valSelector = TransNestedInnerWithConsumer source (v, valSelector) MakeAverageByNullable(qb, qTyIsIQueryable qTy, source, v, valSelector) - | CallSumBy (qb, [_; qTy; _], source, Lambda(v, valSelector)) -> + | CallSumBy (qb, [_; qTy; _], source, Lambda(v, valSelector)) -> let source, v, valSelector = TransNestedInnerWithConsumer source (v, valSelector) - MakeSumBy (qb, qTyIsIQueryable qTy, source, v, valSelector) + MakeSumBy (qb, qTyIsIQueryable qTy, source, v, valSelector) - | CallSumByNullable (qb, [_; qTy; _], source, Lambda(v, valSelector)) -> + | CallSumByNullable (qb, [_; qTy; _], source, Lambda(v, valSelector)) -> let source, v, valSelector = TransNestedInnerWithConsumer source (v, valSelector) - MakeSumByNullable (qb, qTyIsIQueryable qTy, source, v, valSelector) + MakeSumByNullable (qb, qTyIsIQueryable qTy, source, v, valSelector) - | CallExists (_, [_; qTy], source, Lambda(v, predicate)) -> + | CallExists (_, [_; qTy], source, Lambda(v, predicate)) -> let source, v, predicate = TransNestedInnerWithConsumer source (v, predicate) - MakeAny (qTyIsIQueryable qTy, source, v, predicate) + MakeAny (qTyIsIQueryable qTy, source, v, predicate) - | CallForAll (_, [_; qTy], source, Lambda(v, predicate)) -> + | CallForAll (_, [_; qTy], source, Lambda(v, predicate)) -> let source, v, predicate = TransNestedInnerWithConsumer source (v, predicate) - MakeAll (qTyIsIQueryable qTy, source, v, predicate) + MakeAll (qTyIsIQueryable qTy, source, v, predicate) - | CallFind (_, [_; qTy], source, Lambda(v, predicate)) -> + | CallFind (_, [_; qTy], source, Lambda(v, predicate)) -> let source, v, predicate = TransNestedInnerWithConsumer source (v, predicate) - MakeFirstFind (qTyIsIQueryable qTy, source, v, predicate) + MakeFirstFind (qTyIsIQueryable qTy, source, v, predicate) - | CallContains (_, [srcItemTy; qTy], source, valToFindExpr) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source - MakeContains (qTyIsIQueryable qTy, srcItemTy, source, MacroExpand valToFindExpr) + | CallContains (_, [srcItemTy; qTy], source, valToFindExpr) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source + MakeContains (qTyIsIQueryable qTy, srcItemTy, source, MacroExpand valToFindExpr) - | CallNth (_, [srcItemTy; qTy], source, valCountExpr) -> - let source = TransInnerWithFinalConsume CanEliminate.Yes source - MakeElementAt (qTyIsIQueryable qTy, srcItemTy, source, MacroExpand valCountExpr) + | CallNth (_, [srcItemTy; qTy], source, valCountExpr) -> + let source = TransInnerWithFinalConsume CanEliminate.Yes source + MakeElementAt (qTyIsIQueryable qTy, srcItemTy, source, MacroExpand valCountExpr) - | LetExprReduction reduced -> TransNestedOuter canElim reduced - | MacroReduction reduced -> TransNestedOuter canElim reduced + | LetExprReduction reduced -> + TransNestedOuter canElim reduced + + | MacroReduction reduced -> + TransNestedOuter canElim reduced + + | source -> + TransInnerWithFinalConsume canElim source - | source -> - TransInnerWithFinalConsume canElim source - // Nested queries appear as query { .... } // [[ query { ... } ]] = TransNestedOuter canElim[[q]] // -- This is the primary translation for nested sequences. - let EliminateNestedQueries q = - q |> RewriteExpr (fun walk p -> - match p with - | AnyNestedQuery e -> Some (walk (TransNestedOuter CanEliminate.No e)) + let EliminateNestedQueries q = + q |> RewriteExpr (fun walk p -> + match p with + | AnyNestedQuery e -> Some (walk (TransNestedOuter CanEliminate.No e)) | _ -> None) - + /// Evaluate the inner core of a query that actually produces a sequence of results. /// Do this by converting to an expression tree for a LINQ query and evaluating that. - let EvalNonNestedInner canElim (queryProducingSequence:Expr) = + let EvalNonNestedInner canElim (queryProducingSequence:Expr) = let linqQuery = TransInnerWithFinalConsume canElim queryProducingSequence - let linqQueryAfterEliminatingNestedQueries = EliminateNestedQueries linqQuery + let linqQueryAfterEliminatingNestedQueries = EliminateNestedQueries linqQuery #if !FX_NO_SYSTEM_CONSOLE #if DEBUG - let debug() = - Printf.printfn "----------------------queryProducingSequence-------------------------" + let debug() = + Printf.printfn "----------------------queryProducingSequence-------------------------" Printf.printfn "%A" queryProducingSequence - Printf.printfn "--------------------------linqQuery (before nested)------------------" - Printf.printfn "%A" linqQuery - Printf.printfn "--------------------------linqQuery (after nested)-------------------" - Printf.printfn "%A" linqQueryAfterEliminatingNestedQueries + Printf.printfn "--------------------------linqQuery (before nested)------------------" + Printf.printfn "%A" linqQuery + Printf.printfn "--------------------------linqQuery (after nested)-------------------" + Printf.printfn "%A" linqQueryAfterEliminatingNestedQueries #endif #endif - let result = - try + let result = + try LeafExpressionConverter.EvaluateQuotation linqQueryAfterEliminatingNestedQueries - with e -> + with e -> #if !FX_NO_SYSTEM_CONSOLE #if DEBUG debug() - Printf.printfn "--------------------------error--------------------------------------" + Printf.printfn "--------------------------error--------------------------------------" Printf.printfn "%A" (e.ToString()) - Printf.printfn "---------------------------------------------------------------------" + Printf.printfn "---------------------------------------------------------------------" #endif #endif reraise () @@ -1689,37 +1835,99 @@ module Query = result /// Evaluate the outer calls of a query until the inner core that actually produces a sequence of results is reached. - let rec EvalNonNestedOuter canElim (tm:Expr) = + let rec EvalNonNestedOuter canElim (tm:Expr) = match tm with - - | CallMinBy (_, [srcItemTy; qTy; keyItemTy], source, Lambda(v, valSelector)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallMinBy (qTyIsIQueryable qTy, srcItemTy, keyItemTy, sourcev, keyItemTy, v, MacroExpand valSelector) - | CallMaxBy (_, [srcItemTy; qTy; keyItemTy], source, Lambda(v, valSelector)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallMaxBy (qTyIsIQueryable qTy, srcItemTy, keyItemTy, sourcev, keyItemTy, v, MacroExpand valSelector) - | CallMinByNullable (_, [srcItemTy; qTy; keyItemTy ], source, Lambda(v, valSelector)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallMinByNullable (qTyIsIQueryable qTy, srcItemTy, keyItemTy, sourcev, MakeNullableTy keyItemTy, v, MacroExpand valSelector) - | CallMaxByNullable (_, [srcItemTy; qTy; keyItemTy ], source, Lambda(v, valSelector)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallMaxByNullable (qTyIsIQueryable qTy, srcItemTy, keyItemTy, sourcev, MakeNullableTy keyItemTy, v, MacroExpand valSelector) - | CallCount (_, [srcItemTy; qTy], source) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallCount (qTyIsIQueryable qTy, srcItemTy, sourcev) - | CallHead (_, [srcItemTy; qTy], source) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallFirst (qTyIsIQueryable qTy, srcItemTy, sourcev) - | CallLast (_, [srcItemTy; qTy], source) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallLast (qTyIsIQueryable qTy, srcItemTy, sourcev) - | CallHeadOrDefault (_, [srcItemTy; qTy], source) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallFirstOrDefault (qTyIsIQueryable qTy, srcItemTy, sourcev) - | CallLastOrDefault (_, [srcItemTy; qTy], source) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallLastOrDefault (qTyIsIQueryable qTy, srcItemTy, sourcev) - | CallExactlyOne (_, [srcItemTy; qTy], source) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallSingle (qTyIsIQueryable qTy, srcItemTy, sourcev) - | CallExactlyOneOrDefault (_, [srcItemTy; qTy], source) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallSingleOrDefault(qTyIsIQueryable qTy, srcItemTy, sourcev) - - | CallAverageBy (qb, [srcItemTy; qTy; resTy], source, Lambda(v, valSelector)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallAverageBy (qb, qTyIsIQueryable qTy, srcItemTy, resTy, sourcev, resTy, v, MacroExpand valSelector) - | CallAverageByNullable (qb, [srcItemTy; qTy; resTyNoNullable], source, Lambda(v, valSelector)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallAverageByNullable(qb, qTyIsIQueryable qTy, srcItemTy, resTyNoNullable, sourcev, MakeNullableTy resTyNoNullable, v, MacroExpand valSelector) - | CallSumBy (qb, [srcItemTy; qTy; resTy], source, Lambda(v, valSelector)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallSumBy (qb, qTyIsIQueryable qTy, srcItemTy, resTy, sourcev, resTy, v, MacroExpand valSelector) - | CallSumByNullable (qb, [srcItemTy; qTy; resTyNoNullable], source, Lambda(v, valSelector)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallSumByNullable (qb, qTyIsIQueryable qTy, srcItemTy, resTyNoNullable, sourcev, MakeNullableTy resTyNoNullable, v, MacroExpand valSelector) - | CallExists (_, [srcItemTy; qTy], source, Lambda(v, predicate)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallAny (qTyIsIQueryable qTy, srcItemTy, sourcev, v, MacroExpand predicate) - | CallForAll (_, [srcItemTy; qTy], source, Lambda(v, predicate)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallAll (qTyIsIQueryable qTy, srcItemTy, sourcev, v, MacroExpand predicate) - | CallFind (_, [srcItemTy; qTy], source, Lambda(v, f)) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallFirstFind (qTyIsIQueryable qTy, srcItemTy, sourcev, v, MacroExpand f) - | CallContains (_, [srcItemTy; qTy], source, v) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallContains (qTyIsIQueryable qTy, srcItemTy, sourcev, MacroExpand v) - | CallNth (_, [srcItemTy; qTy], source, v) -> let sourcev = EvalNonNestedInner CanEliminate.Yes source in CallElementAt (qTyIsIQueryable qTy, srcItemTy, sourcev, MacroExpand v) - - | LetExprReduction reduced -> EvalNonNestedOuter canElim reduced - | MacroReduction reduced -> EvalNonNestedOuter canElim reduced - - | source -> EvalNonNestedInner canElim source - - let QueryExecute (p : Expr<'T>) : 'U = + + | CallMinBy (_, [srcItemTy; qTy; keyItemTy], source, Lambda(v, valSelector)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallMinBy (qTyIsIQueryable qTy, srcItemTy, keyItemTy, sourcev, keyItemTy, v, MacroExpand valSelector) + + | CallMaxBy (_, [srcItemTy; qTy; keyItemTy], source, Lambda(v, valSelector)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallMaxBy (qTyIsIQueryable qTy, srcItemTy, keyItemTy, sourcev, keyItemTy, v, MacroExpand valSelector) + + | CallMinByNullable (_, [srcItemTy; qTy; keyItemTy ], source, Lambda(v, valSelector)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallMinByNullable (qTyIsIQueryable qTy, srcItemTy, keyItemTy, sourcev, MakeNullableTy keyItemTy, v, MacroExpand valSelector) + + | CallMaxByNullable (_, [srcItemTy; qTy; keyItemTy ], source, Lambda(v, valSelector)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallMaxByNullable (qTyIsIQueryable qTy, srcItemTy, keyItemTy, sourcev, MakeNullableTy keyItemTy, v, MacroExpand valSelector) + + | CallCount (_, [srcItemTy; qTy], source) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallCount (qTyIsIQueryable qTy, srcItemTy, sourcev) + + | CallHead (_, [srcItemTy; qTy], source) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallFirst (qTyIsIQueryable qTy, srcItemTy, sourcev) + + | CallLast (_, [srcItemTy; qTy], source) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallLast (qTyIsIQueryable qTy, srcItemTy, sourcev) + + | CallHeadOrDefault (_, [srcItemTy; qTy], source) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallFirstOrDefault (qTyIsIQueryable qTy, srcItemTy, sourcev) + + | CallLastOrDefault (_, [srcItemTy; qTy], source) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallLastOrDefault (qTyIsIQueryable qTy, srcItemTy, sourcev) + + | CallExactlyOne (_, [srcItemTy; qTy], source) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallSingle (qTyIsIQueryable qTy, srcItemTy, sourcev) + + | CallExactlyOneOrDefault (_, [srcItemTy; qTy], source) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallSingleOrDefault(qTyIsIQueryable qTy, srcItemTy, sourcev) + + | CallAverageBy (qb, [srcItemTy; qTy; resTy], source, Lambda(v, valSelector)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallAverageBy (qb, qTyIsIQueryable qTy, srcItemTy, resTy, sourcev, resTy, v, MacroExpand valSelector) + + | CallAverageByNullable (qb, [srcItemTy; qTy; resTyNoNullable], source, Lambda(v, valSelector)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallAverageByNullable(qb, qTyIsIQueryable qTy, srcItemTy, resTyNoNullable, sourcev, MakeNullableTy resTyNoNullable, v, MacroExpand valSelector) + + | CallSumBy (qb, [srcItemTy; qTy; resTy], source, Lambda(v, valSelector)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallSumBy (qb, qTyIsIQueryable qTy, srcItemTy, resTy, sourcev, resTy, v, MacroExpand valSelector) + + | CallSumByNullable (qb, [srcItemTy; qTy; resTyNoNullable], source, Lambda(v, valSelector)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallSumByNullable (qb, qTyIsIQueryable qTy, srcItemTy, resTyNoNullable, sourcev, MakeNullableTy resTyNoNullable, v, MacroExpand valSelector) + + | CallExists (_, [srcItemTy; qTy], source, Lambda(v, predicate)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallAny (qTyIsIQueryable qTy, srcItemTy, sourcev, v, MacroExpand predicate) + + | CallForAll (_, [srcItemTy; qTy], source, Lambda(v, predicate)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallAll (qTyIsIQueryable qTy, srcItemTy, sourcev, v, MacroExpand predicate) + + | CallFind (_, [srcItemTy; qTy], source, Lambda(v, f)) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallFirstFind (qTyIsIQueryable qTy, srcItemTy, sourcev, v, MacroExpand f) + + | CallContains (_, [srcItemTy; qTy], source, v) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallContains (qTyIsIQueryable qTy, srcItemTy, sourcev, MacroExpand v) + + | CallNth (_, [srcItemTy; qTy], source, v) -> + let sourcev = EvalNonNestedInner CanEliminate.Yes source + CallElementAt (qTyIsIQueryable qTy, srcItemTy, sourcev, MacroExpand v) + + | LetExprReduction reduced -> + EvalNonNestedOuter canElim reduced + + | MacroReduction reduced -> + EvalNonNestedOuter canElim reduced + + | source -> + EvalNonNestedInner canElim source + + let QueryExecute (p: Expr<'T>) : 'U = // We use Unchecked.unbox to allow headOrDefault, lastOrDefault and exactlyOneOrDefault to return Unchecked.defaultof<_> values for F# types Unchecked.unbox (EvalNonNestedOuter CanEliminate.No p) @@ -1729,5 +1937,5 @@ module Query = member this.Execute(q) = QueryExecute q member this.EliminateNestedQueries(e) = EliminateNestedQueries e } - + diff --git a/src/fsharp/FSharp.Core/array.fs b/src/fsharp/FSharp.Core/array.fs index 13c3353ca06..c56879873c4 100644 --- a/src/fsharp/FSharp.Core/array.fs +++ b/src/fsharp/FSharp.Core/array.fs @@ -30,13 +30,13 @@ namespace Microsoft.FSharp.Collections let length (array: _[]) = array.Length [] - let inline last (array : 'T[]) = + let inline last (array: 'T[]) = checkNonNull "array" array if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString array.[array.Length-1] [] - let tryLast (array : 'T[]) = + let tryLast (array: 'T[]) = checkNonNull "array" array if array.Length = 0 then None else Some array.[array.Length-1] @@ -50,7 +50,7 @@ namespace Microsoft.FSharp.Collections Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count [] - let create (count:int) (value:'T) = + let create (count: int) (value: 'T) = if count < 0 then invalidArgInputMustBeNonNegative "count" count let array: 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count for i = 0 to Operators.Checked.(-) array.Length 1 do // use checked arithmetic here to satisfy FxCop @@ -58,7 +58,7 @@ namespace Microsoft.FSharp.Collections array [] - let tryHead (array : 'T[]) = + let tryHead (array: 'T[]) = checkNonNull "array" array if array.Length = 0 then None else Some array.[0] @@ -69,7 +69,7 @@ namespace Microsoft.FSharp.Collections (array.Length = 0) [] - let tail (array : 'T[]) = + let tail (array: 'T[]) = checkNonNull "array" array if array.Length = 0 then invalidArg "array" (SR.GetString(SR.notEnoughElements)) Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 1 (array.Length - 1) array @@ -77,12 +77,12 @@ namespace Microsoft.FSharp.Collections [] let empty<'T> : 'T [] = [| |] - [] + [] [] - let inline blit (source : 'T[]) (sourceIndex:int) (target: 'T[]) (targetIndex:int) (count:int) = + let inline blit (source: 'T[]) (sourceIndex: int) (target: 'T[]) (targetIndex: int) (count: int) = Array.Copy(source, sourceIndex, target, targetIndex, count) - let concatArrays (arrs : 'T[][]) : 'T[] = + let concatArrays (arrs: 'T[][]) : 'T[] = let mutable acc = 0 for h in arrs do acc <- acc + h.Length @@ -93,7 +93,7 @@ namespace Microsoft.FSharp.Collections for i = 0 to arrs.Length-1 do let h = arrs.[i] let len = h.Length - Array.Copy(h,0,res,j,len) + Array.Copy(h, 0, res, j, len) j <- j + len res @@ -107,13 +107,13 @@ namespace Microsoft.FSharp.Collections [] let replicate count initial = if count < 0 then invalidArgInputMustBeNonNegative "count" count - let arr : 'T array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count + let arr: 'T array = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count for i = 0 to arr.Length-1 do arr.[i] <- initial arr [] - let collect (mapping : 'T -> 'U[]) (array : 'T[]) : 'U[]= + let collect (mapping: 'T -> 'U[]) (array: 'T[]) : 'U[]= checkNonNull "array" array let len = array.Length let result = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked<'U[]> len @@ -122,24 +122,24 @@ namespace Microsoft.FSharp.Collections concatArrays result [] - let splitAt index (array:'T[]) = + let splitAt index (array: 'T[]) = checkNonNull "array" array if index < 0 then invalidArgInputMustBeNonNegative "index" index if array.Length < index then raise <| InvalidOperationException (SR.GetString(SR.notEnoughElements)) if index = 0 then let right = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 array.Length array - [||],right + [||], right elif index = array.Length then let left = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 array.Length array - left,[||] + left, [||] else let res1 = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 index array let res2 = Microsoft.FSharp.Primitives.Basics.Array.subUnchecked index (array.Length-index) array - res1,res2 + res1, res2 [] - let take count (array : 'T[]) = + let take count (array: 'T[]) = checkNonNull "array" array if count < 0 then invalidArgInputMustBeNonNegative "count" count if count = 0 then @@ -162,7 +162,7 @@ namespace Microsoft.FSharp.Collections Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 count array - let inline countByImpl (comparer:IEqualityComparer<'SafeKey>) (projection:'T->'SafeKey) (getKey:'SafeKey->'Key) (array:'T[]) = + let inline countByImpl (comparer: IEqualityComparer<'SafeKey>) (projection: 'T->'SafeKey) (getKey: 'SafeKey->'Key) (array: 'T[]) = let length = array.Length if length = 0 then Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked 0 else @@ -182,13 +182,15 @@ namespace Microsoft.FSharp.Collections res // We avoid wrapping a StructBox, because under 64 JIT we get some "hard" tailcalls which affect performance - let countByValueType (projection:'T->'Key) (array:'T[]) = countByImpl HashIdentity.Structural<'Key> projection id array + let countByValueType (projection: 'T -> 'Key) (array: 'T[]) = + countByImpl HashIdentity.Structural<'Key> projection id array // Wrap a StructBox around all keys in case the key type is itself a type using null as a representation - let countByRefType (projection:'T->'Key) (array:'T[]) = countByImpl RuntimeHelpers.StructBox<'Key>.Comparer (fun t -> RuntimeHelpers.StructBox (projection t)) (fun sb -> sb.Value) array + let countByRefType (projection: 'T -> 'Key) (array: 'T[]) = + countByImpl RuntimeHelpers.StructBox<'Key>.Comparer (fun t -> RuntimeHelpers.StructBox (projection t)) (fun sb -> sb.Value) array [] - let countBy (projection:'T->'Key) (array:'T[]) = + let countBy (projection: 'T->'Key) (array: 'T[]) = checkNonNull "array" array #if FX_RESHAPED_REFLECTION if (typeof<'Key>).GetTypeInfo().IsValueType @@ -199,18 +201,18 @@ namespace Microsoft.FSharp.Collections else countByRefType projection array [] - let append (array1:'T[]) (array2:'T[]) = + let append (array1: 'T[]) (array2: 'T[]) = checkNonNull "array1" array1 checkNonNull "array2" array2 let n1 = array1.Length let n2 = array2.Length - let res : 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (n1 + n2) + let res: 'T[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (n1 + n2) Array.Copy(array1, 0, res, 0, n1) Array.Copy(array2, 0, res, n1, n2) res [] - let head (array : 'T[]) = + let head (array: 'T[]) = checkNonNull "array" array if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString else array.[0] @@ -239,7 +241,7 @@ namespace Microsoft.FSharp.Collections checkNonNull "array" array let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length for i = 0 to res.Length-1 do - res.[i] <- (i,array.[i]) + res.[i] <- (i, array.[i]) res [] @@ -249,7 +251,7 @@ namespace Microsoft.FSharp.Collections action array.[i] [] - let distinct (array:'T[]) = + let distinct (array: 'T[]) = checkNonNull "array" array let temp = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length let mutable i = 0 @@ -263,9 +265,9 @@ namespace Microsoft.FSharp.Collections Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 i temp [] - let inline map (mapping: 'T -> 'U) (array:'T[]) = + let inline map (mapping: 'T -> 'U) (array: 'T[]) = checkNonNull "array" array - let res : 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length + let res: 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length for i = 0 to res.Length-1 do res.[i] <- mapping array.[i] res @@ -274,13 +276,13 @@ namespace Microsoft.FSharp.Collections let iter2 action (array1: 'T[]) (array2: 'U[]) = checkNonNull "array1" array1 checkNonNull "array2" array2 - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(action) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(action) if array1.Length <> array2.Length then invalidArgDifferentArrayLength "array1" array1.Length "array2" array2.Length for i = 0 to array1.Length-1 do f.Invoke(array1.[i], array2.[i]) [] - let distinctBy projection (array:'T[]) = + let distinctBy projection (array: 'T[]) = checkNonNull "array" array let length = array.Length if length = 0 then Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked 0 else @@ -299,7 +301,7 @@ namespace Microsoft.FSharp.Collections let map2 mapping (array1: 'T[]) (array2: 'U[]) = checkNonNull "array1" array1 checkNonNull "array2" array2 - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(mapping) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(mapping) if array1.Length <> array2.Length then invalidArgDifferentArrayLength "array1" array1.Length "array2" array2.Length let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array1.Length for i = 0 to res.Length-1 do @@ -311,7 +313,7 @@ namespace Microsoft.FSharp.Collections checkNonNull "array1" array1 checkNonNull "array2" array2 checkNonNull "array3" array3 - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(mapping) + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(mapping) let len1 = array1.Length if len1 <> array2.Length || len1 <> array3.Length then invalidArg3ArraysDifferent "array1" "array2" "array3" len1 array2.Length array3.Length @@ -324,17 +326,17 @@ namespace Microsoft.FSharp.Collections let mapi2 mapping (array1: 'T[]) (array2: 'U[]) = checkNonNull "array1" array1 checkNonNull "array2" array2 - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(mapping) + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(mapping) if array1.Length <> array2.Length then invalidArgDifferentArrayLength "array1" array1.Length "array2" array2.Length let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array1.Length for i = 0 to res.Length-1 do - res.[i] <- f.Invoke(i,array1.[i], array2.[i]) + res.[i] <- f.Invoke(i, array1.[i], array2.[i]) res [] - let iteri action (array:'T[]) = + let iteri action (array: 'T[]) = checkNonNull "array" array - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(action) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(action) for i = 0 to array.Length-1 do f.Invoke(i, array.[i]) @@ -342,39 +344,39 @@ namespace Microsoft.FSharp.Collections let iteri2 action (array1: 'T[]) (array2: 'U[]) = checkNonNull "array1" array1 checkNonNull "array2" array2 - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(action) + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(action) if array1.Length <> array2.Length then invalidArgDifferentArrayLength "array1" array1.Length "array2" array2.Length for i = 0 to array1.Length-1 do - f.Invoke(i,array1.[i], array2.[i]) + f.Invoke(i, array1.[i], array2.[i]) [] - let mapi (mapping : int -> 'T -> 'U) (array: 'T[]) = + let mapi (mapping: int -> 'T -> 'U) (array: 'T[]) = checkNonNull "array" array - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(mapping) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(mapping) let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked array.Length for i = 0 to array.Length-1 do - res.[i] <- f.Invoke(i,array.[i]) + res.[i] <- f.Invoke(i, array.[i]) res [] - let mapFold<'T,'State,'Result> (mapping : 'State -> 'T -> 'Result * 'State) state array = + let mapFold<'T, 'State, 'Result> (mapping: 'State -> 'T -> 'Result * 'State) state array = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.mapFold mapping state array [] - let mapFoldBack<'T,'State,'Result> (mapping : 'T -> 'State -> 'Result * 'State) array state = + let mapFoldBack<'T, 'State, 'Result> (mapping: 'T -> 'State -> 'Result * 'State) array state = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.mapFoldBack mapping array state [] - let exists (predicate: 'T -> bool) (array:'T[]) = + let exists (predicate: 'T -> bool) (array: 'T[]) = checkNonNull "array" array let len = array.Length let rec loop i = i < len && (predicate array.[i] || loop (i+1)) len > 0 && loop 0 [] - let inline contains value (array:'T[]) = + let inline contains value (array: 'T[]) = checkNonNull "array" array let mutable state = false let mutable i = 0 @@ -387,14 +389,14 @@ namespace Microsoft.FSharp.Collections let exists2 predicate (array1: _[]) (array2: _[]) = checkNonNull "array1" array1 checkNonNull "array2" array2 - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(predicate) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(predicate) let len1 = array1.Length if len1 <> array2.Length then invalidArgDifferentArrayLength "array1" array1.Length "array2" array2.Length let rec loop i = i < len1 && (f.Invoke(array1.[i], array2.[i]) || loop (i+1)) loop 0 [] - let forall (predicate: 'T -> bool) (array:'T[]) = + let forall (predicate: 'T -> bool) (array: 'T[]) = checkNonNull "array" array let len = array.Length let rec loop i = i >= len || (predicate array.[i] && loop (i+1)) @@ -404,16 +406,16 @@ namespace Microsoft.FSharp.Collections let forall2 predicate (array1: _[]) (array2: _[]) = checkNonNull "array1" array1 checkNonNull "array2" array2 - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(predicate) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(predicate) let len1 = array1.Length if len1 <> array2.Length then invalidArgDifferentArrayLength "array1" array1.Length "array2" array2.Length let rec loop i = i >= len1 || (f.Invoke(array1.[i], array2.[i]) && loop (i+1)) loop 0 - let inline groupByImpl (comparer:IEqualityComparer<'SafeKey>) (keyf:'T->'SafeKey) (getKey:'SafeKey->'Key) (array: 'T[]) = + let inline groupByImpl (comparer: IEqualityComparer<'SafeKey>) (keyf: 'T->'SafeKey) (getKey: 'SafeKey->'Key) (array: 'T[]) = let length = array.Length if length = 0 then Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked 0 else - let dict = Dictionary<_,ResizeArray<_>> comparer + let dict = Dictionary<_, ResizeArray<_>> comparer // Build the groupings for i = 0 to length - 1 do @@ -437,13 +439,13 @@ namespace Microsoft.FSharp.Collections result // We avoid wrapping a StructBox, because under 64 JIT we get some "hard" tailcalls which affect performance - let groupByValueType (keyf:'T->'Key) (array:'T[]) = groupByImpl HashIdentity.Structural<'Key> keyf id array + let groupByValueType (keyf: 'T->'Key) (array: 'T[]) = groupByImpl HashIdentity.Structural<'Key> keyf id array // Wrap a StructBox around all keys in case the key type is itself a type using null as a representation - let groupByRefType (keyf:'T->'Key) (array:'T[]) = groupByImpl RuntimeHelpers.StructBox<'Key>.Comparer (fun t -> RuntimeHelpers.StructBox (keyf t)) (fun sb -> sb.Value) array + let groupByRefType (keyf: 'T->'Key) (array: 'T[]) = groupByImpl RuntimeHelpers.StructBox<'Key>.Comparer (fun t -> RuntimeHelpers.StructBox (keyf t)) (fun sb -> sb.Value) array [] - let groupBy (projection:'T->'Key) (array:'T[]) = + let groupBy (projection: 'T->'Key) (array: 'T[]) = checkNonNull "array" array #if FX_RESHAPED_REFLECTION if (typeof<'Key>).GetTypeInfo().IsValueType @@ -490,7 +492,7 @@ namespace Microsoft.FSharp.Collections if i <> array.Length then - let chunk1 : 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked ((array.Length >>> 2) + 1) + let chunk1: 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked ((array.Length >>> 2) + 1) chunk1.[0] <- first let mutable count = 1 i <- i + 1 @@ -503,7 +505,7 @@ namespace Microsoft.FSharp.Collections i <- i + 1 if i < array.Length then - let chunk2 : 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (array.Length-i) + let chunk2: 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (array.Length-i) count <- 0 while i < array.Length do let element = array.[i] @@ -513,9 +515,9 @@ namespace Microsoft.FSharp.Collections count <- count + 1 i <- i + 1 - let res : 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (chunk1.Length + count) - Array.Copy(chunk1,res,chunk1.Length) - Array.Copy(chunk2,0,res,chunk1.Length,count) + let res: 'U[] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (chunk1.Length + count) + Array.Copy(chunk1, res, chunk1.Length) + Array.Copy(chunk2, 0, res, chunk1.Length, count) res else Microsoft.FSharp.Primitives.Basics.Array.subUnchecked 0 count chunk1 @@ -526,12 +528,12 @@ namespace Microsoft.FSharp.Collections // a bitarray to store the results of the filtering of every element of the array. This means // that the only additional temporary garbage that needs to be allocated is {array.Length/8} bytes. // - // Other optimizations include: + // Other optimizations include: // - arrays < 32 elements don't allocate any garbage at all // - when the predicate yields consecutive runs of true data that is >= 32 elements (and fall // into maskArray buckets) are copied in chunks using System.Array.Copy module Filter = - let private populateMask<'a> (f:'a->bool) (src:array<'a>) (maskArray:array) = + let private populateMask<'a> (f: 'a->bool) (src: array<'a>) (maskArray: array) = let mutable count = 0 for maskIdx = 0 to maskArray.Length-1 do let srcIdx = maskIdx * 32 @@ -571,7 +573,7 @@ namespace Microsoft.FSharp.Collections maskArray.[maskIdx] <- mask count - let private createMask<'a> (f:'a->bool) (src:array<'a>) (maskArrayOut:byref>) (leftoverMaskOut:byref) = + let private createMask<'a> (f: 'a->bool) (src: array<'a>) (maskArrayOut: byref>) (leftoverMaskOut: byref) = let maskArrayLength = src.Length / 0x20 // null when there are less than 32 items in src array. @@ -599,7 +601,7 @@ namespace Microsoft.FSharp.Collections leftoverMaskOut <- leftoverMask count - let private populateDstViaMask<'a> (src:array<'a>) (maskArray:array) (dst:array<'a>) = + let private populateDstViaMask<'a> (src: array<'a>) (maskArray: array) (dst: array<'a>) = let mutable dstIdx = 0 let mutable batchCount = 0 for maskIdx = 0 to maskArray.Length-1 do @@ -657,7 +659,7 @@ namespace Microsoft.FSharp.Collections dstIdx - let private filterViaMask (maskArray:array) (leftoverMask:uint32) (count:int) (src:array<_>) = + let private filterViaMask (maskArray: array) (leftoverMask: uint32) (count: int) (src: array<_>) = let dst = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count let mutable dstIdx = 0 @@ -675,7 +677,7 @@ namespace Microsoft.FSharp.Collections dst - let filter f (src:array<_>) = + let filter f (src: array<_>) = let mutable maskArray = Unchecked.defaultof<_> let mutable leftOverMask = Unchecked.defaultof<_> match createMask f src &maskArray &leftOverMask with @@ -691,7 +693,7 @@ namespace Microsoft.FSharp.Collections let where predicate (array: _[]) = filter predicate array [] - let except (itemsToExclude: seq<_>) (array:_[]) = + let except (itemsToExclude: seq<_>) (array: _[]) = checkNonNull "itemsToExclude" itemsToExclude checkNonNull "array" array @@ -742,7 +744,7 @@ namespace Microsoft.FSharp.Collections loop 0 [] - let skip count (array:'T[]) = + let skip count (array: 'T[]) = checkNonNull "array" array if count > array.Length then invalidArgOutOfRange "count" count "array.Length" array.Length if count = array.Length then @@ -772,30 +774,30 @@ namespace Microsoft.FSharp.Collections Microsoft.FSharp.Primitives.Basics.Array.tryFindBack predicate array [] - let findIndexBack predicate (array : _[]) = + let findIndexBack predicate (array: _[]) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.findIndexBack predicate array [] - let tryFindIndexBack predicate (array : _[]) = + let tryFindIndexBack predicate (array: _[]) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.tryFindIndexBack predicate array [] - let windowed windowSize (array:'T[]) = + let windowed windowSize (array: 'T[]) = checkNonNull "array" array if windowSize <= 0 then invalidArgInputMustBePositive "windowSize" windowSize let len = array.Length if windowSize > len then empty else - let res : 'T[][] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (len - windowSize + 1) + let res: 'T[][] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (len - windowSize + 1) for i = 0 to len - windowSize do res.[i] <- Microsoft.FSharp.Primitives.Basics.Array.subUnchecked i windowSize array res [] - let chunkBySize chunkSize (array:'T[]) = + let chunkBySize chunkSize (array: 'T[]) = checkNonNull "array" array if chunkSize <= 0 then invalidArgInputMustBePositive "chunkSize" chunkSize let len = array.Length @@ -805,7 +807,7 @@ namespace Microsoft.FSharp.Collections [| copy array |] else let chunkCount = (len - 1) / chunkSize + 1 - let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked chunkCount : 'T[][] + let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked chunkCount: 'T[][] for i = 0 to len / chunkSize - 1 do res.[i] <- Microsoft.FSharp.Primitives.Basics.Array.subUnchecked (i * chunkSize) chunkSize array if len % chunkSize <> 0 then @@ -813,7 +815,7 @@ namespace Microsoft.FSharp.Collections res [] - let splitInto count (array:_[]) = + let splitInto count (array: _[]) = checkNonNull "array" array if count <= 0 then invalidArgInputMustBePositive "count" count Microsoft.FSharp.Primitives.Basics.Array.splitInto count array @@ -826,7 +828,7 @@ namespace Microsoft.FSharp.Collections if len1 <> array2.Length then invalidArgDifferentArrayLength "array1" array1.Length "array2" array2.Length let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len1 for i = 0 to res.Length-1 do - res.[i] <- (array1.[i],array2.[i]) + res.[i] <- (array1.[i], array2.[i]) res [] @@ -838,7 +840,7 @@ namespace Microsoft.FSharp.Collections if len1 <> array2.Length || len1 <> array3.Length then invalidArg3ArraysDifferent "array1" "array2" "array3" len1 array2.Length array3.Length let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len1 for i = 0 to res.Length-1 do - res.[i] <- (array1.[i],array2.[i],array3.[i]) + res.[i] <- (array1.[i], array2.[i], array3.[i]) res [] @@ -850,16 +852,16 @@ namespace Microsoft.FSharp.Collections let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (len1 * len2) for i = 0 to array1.Length-1 do for j = 0 to array2.Length-1 do - res.[i * len2 + j] <- (array1.[i],array2.[j]) + res.[i * len2 + j] <- (array1.[i], array2.[j]) res [] - let unfold<'T,'State> (generator:'State -> ('T*'State) option) (state:'State) = + let unfold<'T, 'State> (generator: 'State -> ('T*'State) option) (state: 'State) = let res = ResizeArray<_>() let rec loop state = match generator state with | None -> () - | Some (x,s') -> + | Some (x, s') -> res.Add(x) loop s' loop state @@ -872,10 +874,10 @@ namespace Microsoft.FSharp.Collections let res1 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len let res2 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len for i = 0 to array.Length-1 do - let x,y = array.[i] + let x, y = array.[i] res1.[i] <- x res2.[i] <- y - res1,res2 + res1, res2 [] let unzip3 (array: _[]) = @@ -885,11 +887,11 @@ namespace Microsoft.FSharp.Collections let res2 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len let res3 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len for i = 0 to array.Length-1 do - let x,y,z = array.[i] + let x, y, z = array.[i] res1.[i] <- x res2.[i] <- y res3.[i] <- z - res1,res2,res3 + res1, res2, res3 [] let rev (array: _[]) = @@ -902,74 +904,74 @@ namespace Microsoft.FSharp.Collections res [] - let fold<'T,'State> (folder : 'State -> 'T -> 'State) (state: 'State) (array:'T[]) = + let fold<'T, 'State> (folder: 'State -> 'T -> 'State) (state: 'State) (array: 'T[]) = checkNonNull "array" array - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(folder) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(folder) let mutable state = state for i = 0 to array.Length-1 do - state <- f.Invoke(state,array.[i]) + state <- f.Invoke(state, array.[i]) state [] - let foldBack<'T,'State> (folder : 'T -> 'State -> 'State) (array:'T[]) (state: 'State) = + let foldBack<'T, 'State> (folder: 'T -> 'State -> 'State) (array: 'T[]) (state: 'State) = checkNonNull "array" array - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(folder) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(folder) let mutable res = state for i = array.Length-1 downto 0 do - res <- f.Invoke(array.[i],res) + res <- f.Invoke(array.[i], res) res [] - let foldBack2<'T1,'T2,'State> folder (array1:'T1[]) (array2:'T2 []) (state: 'State) = + let foldBack2<'T1, 'T2, 'State> folder (array1: 'T1[]) (array2: 'T2 []) (state: 'State) = checkNonNull "array1" array1 checkNonNull "array2" array2 - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(folder) + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(folder) let mutable res = state let len = array1.Length if len <> array2.Length then invalidArgDifferentArrayLength "array1" len "array2" array2.Length for i = len-1 downto 0 do - res <- f.Invoke(array1.[i],array2.[i],res) + res <- f.Invoke(array1.[i], array2.[i], res) res [] - let fold2<'T1,'T2,'State> folder (state: 'State) (array1:'T1[]) (array2:'T2 []) = + let fold2<'T1, 'T2, 'State> folder (state: 'State) (array1: 'T1[]) (array2: 'T2 []) = checkNonNull "array1" array1 checkNonNull "array2" array2 - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(folder) + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(folder) let mutable state = state if array1.Length <> array2.Length then invalidArgDifferentArrayLength "array1" array1.Length "array2" array2.Length for i = 0 to array1.Length-1 do - state <- f.Invoke(state,array1.[i],array2.[i]) + state <- f.Invoke(state, array1.[i], array2.[i]) state - let foldSubRight f (array : _[]) start fin acc = + let foldSubRight f (array: _[]) start fin acc = checkNonNull "array" array - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) let mutable res = acc for i = fin downto start do - res <- f.Invoke(array.[i],res) + res <- f.Invoke(array.[i], res) res - let scanSubLeft f initState (array : _[]) start fin = + let scanSubLeft f initState (array: _[]) start fin = checkNonNull "array" array - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) let mutable state = initState let res = create (2+fin-start) initState for i = start to fin do - state <- f.Invoke(state,array.[i]) + state <- f.Invoke(state, array.[i]) res.[i - start+1] <- state res [] - let scan<'T,'State> folder (state:'State) (array : 'T[]) = + let scan<'T, 'State> folder (state: 'State) (array: 'T[]) = checkNonNull "array" array let len = array.Length scanSubLeft folder state array 0 (len - 1) [] - let scanBack<'T,'State> folder (array : 'T[]) (state:'State) = + let scanBack<'T, 'State> folder (array: 'T[]) (state: 'State) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.scanSubRight folder array 0 (array.Length - 1) state @@ -980,30 +982,30 @@ namespace Microsoft.FSharp.Collections let pairwise (array: 'T[]) = checkNonNull "array" array if array.Length < 2 then empty else - init (array.Length-1) (fun i -> array.[i],array.[i+1]) + init (array.Length-1) (fun i -> array.[i], array.[i+1]) [] - let reduce reduction (array : _[]) = + let reduce reduction (array: _[]) = checkNonNull "array" array let len = array.Length if len = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString else - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(reduction) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(reduction) let mutable res = array.[0] for i = 1 to array.Length-1 do - res <- f.Invoke(res,array.[i]) + res <- f.Invoke(res, array.[i]) res [] - let reduceBack reduction (array : _[]) = + let reduceBack reduction (array: _[]) = checkNonNull "array" array let len = array.Length if len = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString else foldSubRight reduction array 0 (len - 2) array.[len - 1] [] - let sortInPlaceWith comparer (array : 'T[]) = + let sortInPlaceWith comparer (array: 'T[]) = checkNonNull "array" array let len = array.Length if len < 2 then () @@ -1017,17 +1019,17 @@ namespace Microsoft.FSharp.Collections Array.Sort(array, ComparisonIdentity.FromFunction(comparer)) [] - let sortInPlaceBy (projection: 'T -> 'U) (array : 'T[]) = + let sortInPlaceBy (projection: 'T -> 'U) (array: 'T[]) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.unstableSortInPlaceBy projection array [] - let sortInPlace (array : 'T[]) = + let sortInPlace (array: 'T[]) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.unstableSortInPlace array [] - let sortWith (comparer: 'T -> 'T -> int) (array : 'T[]) = + let sortWith (comparer: 'T -> 'T -> int) (array: 'T[]) = checkNonNull "array" array let result = copy array sortInPlaceWith comparer result @@ -1070,7 +1072,7 @@ namespace Microsoft.FSharp.Collections Seq.toArray source [] - let findIndex predicate (array : _[]) = + let findIndex predicate (array: _[]) = checkNonNull "array" array let len = array.Length let rec go n = @@ -1082,14 +1084,14 @@ namespace Microsoft.FSharp.Collections go 0 [] - let tryFindIndex predicate (array : _[]) = + let tryFindIndex predicate (array: _[]) = checkNonNull "array" array let len = array.Length let rec go n = if n >= len then None elif predicate array.[n] then Some n else go (n+1) go 0 [] - let permute indexMap (array : _[]) = + let permute indexMap (array: _[]) = checkNonNull "array" array Microsoft.FSharp.Primitives.Basics.Array.permute indexMap array @@ -1102,7 +1104,7 @@ namespace Microsoft.FSharp.Collections acc [] - let inline sumBy (projection: 'T -> ^U) (array:'T[]) : ^U = + let inline sumBy (projection: 'T -> ^U) (array: 'T[]) : ^U = checkNonNull "array" array let mutable acc = LanguagePrimitives.GenericZero< ^U> for i = 0 to array.Length - 1 do @@ -1110,7 +1112,7 @@ namespace Microsoft.FSharp.Collections acc [] - let inline min (array:_[]) = + let inline min (array: _[]) = checkNonNull "array" array if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString let mutable acc = array.[0] @@ -1121,7 +1123,7 @@ namespace Microsoft.FSharp.Collections acc [] - let inline minBy projection (array:_[]) = + let inline minBy projection (array: _[]) = checkNonNull "array" array if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString let mutable accv = array.[0] @@ -1135,7 +1137,7 @@ namespace Microsoft.FSharp.Collections accv [] - let inline max (array:_[]) = + let inline max (array: _[]) = checkNonNull "array" array if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString let mutable acc = array.[0] @@ -1146,7 +1148,7 @@ namespace Microsoft.FSharp.Collections acc [] - let inline maxBy projection (array:_[]) = + let inline maxBy projection (array: _[]) = checkNonNull "array" array if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString let mutable accv = array.[0] @@ -1160,7 +1162,7 @@ namespace Microsoft.FSharp.Collections accv [] - let inline average (array:'T[]) = + let inline average (array: 'T[]) = checkNonNull "array" array if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString let mutable acc = LanguagePrimitives.GenericZero< ^T> @@ -1169,7 +1171,7 @@ namespace Microsoft.FSharp.Collections LanguagePrimitives.DivideByInt< ^T> acc array.Length [] - let inline averageBy (projection : 'T -> ^U) (array:'T[]) : ^U = + let inline averageBy (projection: 'T -> ^U) (array: 'T[]) : ^U = checkNonNull "array" array if array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputArrayEmptyString let mutable acc = LanguagePrimitives.GenericZero< ^U> @@ -1178,7 +1180,7 @@ namespace Microsoft.FSharp.Collections LanguagePrimitives.DivideByInt< ^U> acc array.Length [] - let inline compareWith (comparer:'T -> 'T -> int) (array1: 'T[]) (array2: 'T[]) = + let inline compareWith (comparer: 'T -> 'T -> int) (array1: 'T[]) (array2: 'T[]) = checkNonNull "array1" array1 checkNonNull "array2" array2 @@ -1203,7 +1205,7 @@ namespace Microsoft.FSharp.Collections else 1 [] - let sub (array:'T[]) (startIndex:int) (count:int) = + let sub (array: 'T[]) (startIndex: int) (count: int) = checkNonNull "array" array if startIndex < 0 then invalidArgInputMustBeNonNegative "startIndex" startIndex if count < 0 then invalidArgInputMustBeNonNegative "count" count @@ -1211,25 +1213,25 @@ namespace Microsoft.FSharp.Collections Microsoft.FSharp.Primitives.Basics.Array.subUnchecked startIndex count array [] - let item index (array:_[]) = + let item index (array: _[]) = array.[index] [] - let tryItem index (array:'T[]) = + let tryItem index (array: 'T[]) = checkNonNull "array" array if index < 0 || index >= array.Length then None else Some(array.[index]) [] - let get (array:_[]) index = + let get (array: _[]) index = array.[index] [] - let set (array:_[]) index value = + let set (array: _[]) index value = array.[index] <- value [] - let fill (target:'T[]) (targetIndex:int) (count:int) (value:'T) = + let fill (target: 'T[]) (targetIndex: int) (count: int) (value: 'T) = checkNonNull "target" target if targetIndex < 0 then invalidArgInputMustBeNonNegative "targetIndex" targetIndex if count < 0 then invalidArgInputMustBeNonNegative "count" count @@ -1237,19 +1239,19 @@ namespace Microsoft.FSharp.Collections target.[i] <- value [] - let exactlyOne (array:'T[]) = + let exactlyOne (array: 'T[]) = checkNonNull "array" array if array.Length = 1 then array.[0] elif array.Length = 0 then invalidArg "array" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString else invalidArg "array" (SR.GetString(SR.inputSequenceTooLong)) [] - let tryExactlyOne (array:'T[]) = + let tryExactlyOne (array: 'T[]) = checkNonNull "array" array if array.Length = 1 then Some array.[0] else None - let transposeArrays (array:'T[][]) = + let transposeArrays (array: 'T[][]) = let len = array.Length if len = 0 then Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked 0 else let lenInner = array.[0].Length @@ -1258,7 +1260,7 @@ namespace Microsoft.FSharp.Collections if lenInner <> array.[j].Length then invalidArgDifferentArrayLength "array.[0]" lenInner (String.Format("array.[{0}]", j)) array.[j].Length - let result : 'T[][] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked lenInner + let result: 'T[][] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked lenInner for i in 0..lenInner-1 do result.[i] <- Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len for j in 0..len-1 do @@ -1266,14 +1268,14 @@ namespace Microsoft.FSharp.Collections result [] - let transpose (arrays:seq<'T[]>) = + let transpose (arrays: seq<'T[]>) = checkNonNull "arrays" arrays match arrays with | :? ('T[][]) as ts -> ts |> transposeArrays // avoid a clone, since we only read the array | _ -> arrays |> Seq.toArray |> transposeArrays [] - let truncate count (array:'T[]) = + let truncate count (array: 'T[]) = checkNonNull "array" array if count <= 0 then empty else @@ -1289,20 +1291,20 @@ namespace Microsoft.FSharp.Collections checkNonNull "array" array let inputLength = array.Length - let isChosen : bool [] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength - let results : 'U [] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength + let isChosen: bool [] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength + let results: 'U [] = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength let mutable outputLength = 0 Parallel.For(0, inputLength, - (fun () ->0), + (fun () ->0), (fun i _ count -> match chooser array.[i] with | None -> count | Some v -> isChosen.[i] <- true; results.[i] <- v - count+1), - Action (fun x -> System.Threading.Interlocked.Add(&outputLength,x) |> ignore ) + count+1), + Action (fun x -> System.Threading.Interlocked.Add(&outputLength, x) |> ignore ) ) |> ignore let output = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked outputLength @@ -1314,7 +1316,7 @@ namespace Microsoft.FSharp.Collections output [] - let collect (mapping : 'T -> 'U[]) (array : 'T[]) : 'U[]= + let collect (mapping: 'T -> 'U[]) (array: 'T[]) : 'U[]= checkNonNull "array" array let inputLength = array.Length let result = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength @@ -1323,7 +1325,7 @@ namespace Microsoft.FSharp.Collections concatArrays result [] - let map (mapping: 'T -> 'U) (array : 'T[]) : 'U[]= + let map (mapping: 'T -> 'U) (array: 'T[]) : 'U[]= checkNonNull "array" array let inputLength = array.Length let result = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength @@ -1334,7 +1336,7 @@ namespace Microsoft.FSharp.Collections [] let mapi mapping (array: 'T[]) = checkNonNull "array" array - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(mapping) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(mapping) let inputLength = array.Length let result = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked inputLength Parallel.For(0, inputLength, fun i -> @@ -1342,14 +1344,14 @@ namespace Microsoft.FSharp.Collections result [] - let iter action (array : 'T[]) = + let iter action (array: 'T[]) = checkNonNull "array" array Parallel.For (0, array.Length, fun i -> action array.[i]) |> ignore [] - let iteri action (array : 'T[]) = + let iteri action (array: 'T[]) = checkNonNull "array" array - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(action) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(action) Parallel.For (0, array.Length, fun i -> f.Invoke(i, array.[i])) |> ignore [] @@ -1359,7 +1361,7 @@ namespace Microsoft.FSharp.Collections result [] - let partition predicate (array : 'T[]) = + let partition predicate (array: 'T[]) = checkNonNull "array" array let inputLength = array.Length @@ -1367,14 +1369,14 @@ namespace Microsoft.FSharp.Collections let mutable trueLength = 0 Parallel.For(0, inputLength, - (fun () -> 0), + (fun () -> 0), (fun i _ trueCount -> if predicate array.[i] then isTrue.[i] <- true trueCount + 1 else - trueCount), - Action (fun x -> System.Threading.Interlocked.Add(&trueLength,x) |> ignore) ) |> ignore + trueCount), + Action (fun x -> System.Threading.Interlocked.Add(&trueLength, x) |> ignore) ) |> ignore let res1 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked trueLength let res2 = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked (inputLength - trueLength) diff --git a/src/fsharp/FSharp.Core/async.fs b/src/fsharp/FSharp.Core/async.fs index 4fe2d48d6fc..0e94edde2af 100644 --- a/src/fsharp/FSharp.Core/async.fs +++ b/src/fsharp/FSharp.Core/async.fs @@ -714,7 +714,7 @@ namespace Microsoft.FSharp.Control member x.GetWaitHandle() = lock syncRoot (fun () -> if disposed then - raise (System.ObjectDisposedException("ResultCell")); + raise (System.ObjectDisposedException("ResultCell")) match resEvent with | null -> // Start in signalled state if a result is already present. @@ -727,7 +727,7 @@ namespace Microsoft.FSharp.Control member x.Close() = lock syncRoot (fun () -> if not disposed then - disposed <- true; + disposed <- true match resEvent with | null -> () | ev -> @@ -735,7 +735,7 @@ namespace Microsoft.FSharp.Control ev.Dispose() System.GC.SuppressFinalize(ev) #else - ev.Close(); + ev.Close() #endif resEvent <- null) @@ -760,7 +760,7 @@ namespace Microsoft.FSharp.Control if disposed then [] else - result <- Some res; + result <- Some res // If the resEvent exists then set it. If not we can skip setting it altogether and it won't be // created match resEvent with @@ -1426,7 +1426,7 @@ namespace Microsoft.FSharp.Control ctxt.trampolineHolder.ExecuteWithTrampoline (fun () -> savedCont (not timeOut)) |> unfake), state=null, millisecondsTimeOutInterval=millisecondsTimeout, - executeOnlyOnce=true)); + executeOnlyOnce=true)) fake()) with _ -> if latch.Enter() then diff --git a/src/fsharp/FSharp.Core/eventmodule.fs b/src/fsharp/FSharp.Core/eventmodule.fs index da359843d5c..1d615a307c3 100644 --- a/src/fsharp/FSharp.Core/eventmodule.fs +++ b/src/fsharp/FSharp.Core/eventmodule.fs @@ -16,26 +16,26 @@ namespace Microsoft.FSharp.Control [] let map mapping (sourceEvent: IEvent<'Delegate,'T>) = let ev = new Event<_>() - sourceEvent.Add(fun x -> ev.Trigger(mapping x)); + sourceEvent.Add(fun x -> ev.Trigger(mapping x)) ev.Publish [] let filter predicate (sourceEvent: IEvent<'Delegate,'T>) = let ev = new Event<_>() - sourceEvent.Add(fun x -> if predicate x then ev.Trigger x); + sourceEvent.Add(fun x -> if predicate x then ev.Trigger x) ev.Publish [] let partition predicate (sourceEvent: IEvent<'Delegate,'T>) = let ev1 = new Event<_>() let ev2 = new Event<_>() - sourceEvent.Add(fun x -> if predicate x then ev1.Trigger x else ev2.Trigger x); + sourceEvent.Add(fun x -> if predicate x then ev1.Trigger x else ev2.Trigger x) ev1.Publish,ev2.Publish [] let choose chooser (sourceEvent: IEvent<'Delegate,'T>) = let ev = new Event<_>() - sourceEvent.Add(fun x -> match chooser x with None -> () | Some r -> ev.Trigger r); + sourceEvent.Add(fun x -> match chooser x with None -> () | Some r -> ev.Trigger r) ev.Publish [] @@ -46,7 +46,7 @@ namespace Microsoft.FSharp.Control let z = !state let z = collector z msg state := z; - ev.Trigger(z)); + ev.Trigger(z)) ev.Publish [] @@ -75,7 +75,7 @@ namespace Microsoft.FSharp.Control let split (splitter : 'T -> Choice<'U1,'U2>) (sourceEvent: IEvent<'Delegate,'T>) = let ev1 = new Event<_>() let ev2 = new Event<_>() - sourceEvent.Add(fun x -> match splitter x with Choice1Of2 y -> ev1.Trigger(y) | Choice2Of2 z -> ev2.Trigger(z)); + sourceEvent.Add(fun x -> match splitter x with Choice1Of2 y -> ev1.Trigger(y) | Choice2Of2 z -> ev2.Trigger(z)) ev1.Publish,ev2.Publish diff --git a/src/fsharp/FSharp.Core/fslib-extra-pervasives.fs b/src/fsharp/FSharp.Core/fslib-extra-pervasives.fs index b4271f4a267..dd8d087345e 100644 --- a/src/fsharp/FSharp.Core/fslib-extra-pervasives.fs +++ b/src/fsharp/FSharp.Core/fslib-extra-pervasives.fs @@ -56,9 +56,9 @@ module ExtraTopLevelOperators = member s.Keys = let keys = t.Keys { new ICollection<'Key> with - member s.Add(x) = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))); - member s.Clear() = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))); - member s.Remove(x) = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))); + member s.Add(x) = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))) + member s.Clear() = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))) + member s.Remove(x) = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))) member s.Contains(x) = t.ContainsKey (makeSafeKey x) member s.CopyTo(arr,i) = let mutable n = 0 @@ -93,9 +93,9 @@ module ExtraTopLevelOperators = member __.ContainsKey k = t.ContainsKey (makeSafeKey k) interface ICollection> with - member s.Add(_) = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))); - member s.Clear() = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))); - member s.Remove(_) = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))); + member s.Add(_) = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))) + member s.Clear() = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))) + member s.Remove(_) = raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))) member s.Contains(KeyValue(k,v)) = ICollection_Contains t (KeyValuePair<_,_>(makeSafeKey k,v)) member s.CopyTo(arr,i) = let mutable n = 0 @@ -204,11 +204,11 @@ module ExtraTopLevelOperators = for j in 0..(n-1) do res.[0,j] <- firstRowArr.[j] for i in 1..(m-1) do - checkNonNullInvalidArg "rows" (SR.GetString(SR.nullsNotAllowedInArray)) rowsArr.[i] - let rowiArr = getArray rowsArr.[i] - if rowiArr.Length <> n then invalidArg "vals" (SR.GetString(SR.arraysHadDifferentLengths)) - for j in 0..(n-1) do - res.[i,j] <- rowiArr.[j] + checkNonNullInvalidArg "rows" (SR.GetString(SR.nullsNotAllowedInArray)) rowsArr.[i] + let rowiArr = getArray rowsArr.[i] + if rowiArr.Length <> n then invalidArg "vals" (SR.GetString(SR.arraysHadDifferentLengths)) + for j in 0..(n-1) do + res.[i,j] <- rowiArr.[j] res // -------------------------------------------------------------------- @@ -285,7 +285,6 @@ module ExtraTopLevelOperators = [] let (|Lazy|) (input:Lazy<_>) = input.Force() - let query = Microsoft.FSharp.Linq.QueryBuilder() @@ -297,7 +296,6 @@ namespace Microsoft.FSharp.Core.CompilerServices open System.Collections.Generic open Microsoft.FSharp.Core - /// Represents the product of two measure expressions when returned as a generic argument of a provided type. [] type MeasureProduct<'Measure1, 'Measure2>() = class end diff --git a/src/fsharp/FSharp.Core/list.fs b/src/fsharp/FSharp.Core/list.fs index 6092567f1f4..9a7233228ad 100644 --- a/src/fsharp/FSharp.Core/list.fs +++ b/src/fsharp/FSharp.Core/list.fs @@ -15,7 +15,7 @@ namespace Microsoft.FSharp.Collections [] [] - module List = + module List = let inline checkNonNull argName arg = match box arg with @@ -26,9 +26,9 @@ namespace Microsoft.FSharp.Collections [] let length (list: 'T list) = list.Length - + [] - let rec last (list : 'T list) = + let rec last (list: 'T list) = match list with | [x] -> x | _ :: tail -> last tail @@ -56,7 +56,7 @@ namespace Microsoft.FSharp.Collections let rec loop srcList = match srcList with | [] -> () - | h::t -> + | h :: t -> let safeKey = projection h let mutable prev = 0 if dict.TryGetValue(safeKey, &prev) then dict.[safeKey] <- prev + 1 else dict.[safeKey] <- 1 @@ -90,27 +90,27 @@ namespace Microsoft.FSharp.Collections let indexed list = Microsoft.FSharp.Primitives.Basics.List.indexed list [] - let mapFold<'T,'State,'Result> (mapping:'State -> 'T -> 'Result * 'State) state list = + let mapFold<'T, 'State, 'Result> (mapping:'State -> 'T -> 'Result * 'State) state list = Microsoft.FSharp.Primitives.Basics.List.mapFold mapping state list [] - let mapFoldBack<'T,'State,'Result> (mapping:'T -> 'State -> 'Result * 'State) list state = + let mapFoldBack<'T, 'State, 'Result> (mapping:'T -> 'State -> 'Result * 'State) list state = match list with | [] -> [], state - | [h] -> let h',s' = mapping h state in [h'], s' + | [h] -> let h', s' = mapping h state in [h'], s' | _ -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(mapping) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(mapping) let rec loop res list = match list, res with | [], _ -> res - | h::t, (list', acc') -> - let h',s' = f.Invoke(h,acc') - loop (h'::list', s') t + | h :: t, (list', acc') -> + let h', s' = f.Invoke(h, acc') + loop (h' :: list', s') t loop ([], state) (rev list) [] let iter action list = Microsoft.FSharp.Primitives.Basics.List.iter action list - + [] let distinct (list:'T list) = Microsoft.FSharp.Primitives.Basics.List.distinctWithComparer HashIdentity.Structural<'T> list @@ -127,24 +127,24 @@ namespace Microsoft.FSharp.Collections let empty<'T> = ([ ] : 'T list) [] - let head list = match list with x::_ -> x | [] -> invalidArg "list" (SR.GetString(SR.inputListWasEmpty)) + let head list = match list with x :: _ -> x | [] -> invalidArg "list" (SR.GetString(SR.inputListWasEmpty)) [] - let tryHead list = match list with x::_ -> Some x | [] -> None + let tryHead list = match list with x :: _ -> Some x | [] -> None [] - let tail list = match list with _::t -> t | [] -> invalidArg "list" (SR.GetString(SR.inputListWasEmpty)) + let tail list = match list with _ :: t -> t | [] -> invalidArg "list" (SR.GetString(SR.inputListWasEmpty)) [] let isEmpty list = match list with [] -> true | _ -> false - + [] let append list1 list2 = list1 @ list2 [] let rec item index list = match list with - | h::t when index >= 0 -> + | h :: t when index >= 0 -> if index = 0 then h else item (index - 1) t | _ -> invalidArg "index" (SR.GetString(SR.indexOutOfBounds)) @@ -152,7 +152,7 @@ namespace Microsoft.FSharp.Collections [] let rec tryItem index list = match list with - | h::t when index >= 0 -> + | h :: t when index >= 0 -> if index = 0 then Some h else tryItem (index - 1) t | _ -> None @@ -162,12 +162,12 @@ namespace Microsoft.FSharp.Collections [] let choose chooser list = Microsoft.FSharp.Primitives.Basics.List.choose chooser list - + [] let splitAt index (list:'T list) = Microsoft.FSharp.Primitives.Basics.List.splitAt index list [] - let take count (list : 'T list) = Microsoft.FSharp.Primitives.Basics.List.take count list + let take count (list: 'T list) = Microsoft.FSharp.Primitives.Basics.List.take count list [] let takeWhile predicate (list: 'T list) = Microsoft.FSharp.Primitives.Basics.List.takeWhile predicate list @@ -178,53 +178,53 @@ namespace Microsoft.FSharp.Collections [] let init length initializer = Microsoft.FSharp.Primitives.Basics.List.init length initializer - let rec initConstAcc n x acc = - if n <= 0 then acc else initConstAcc (n-1) x (x::acc) - + let rec initConstAcc n x acc = + if n <= 0 then acc else initConstAcc (n-1) x (x :: acc) + [] - let replicate count initial = + let replicate count initial = if count < 0 then invalidArg "count" (SR.GetString(SR.inputMustBeNonNegative)) - initConstAcc count initial [] + initConstAcc count initial [] [] - let iter2 action list1 list2 = - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(action) - let rec loop list1 list2 = - match list1,list2 with - | [],[] -> () - | h1::t1, h2::t2 -> f.Invoke(h1,h2); loop t1 t2 - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + let iter2 action list1 list2 = + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(action) + let rec loop list1 list2 = + match list1, list2 with + | [], [] -> () + | h1 :: t1, h2 :: t2 -> f.Invoke(h1, h2); loop t1 t2 + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length loop list1 list2 [] - let iteri2 action list1 list2 = - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(action) - let rec loop n list1 list2 = - match list1,list2 with - | [],[] -> () - | h1::t1, h2::t2 -> f.Invoke(n,h1,h2); loop (n+1) t1 t2 - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + let iteri2 action list1 list2 = + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(action) + let rec loop n list1 list2 = + match list1, list2 with + | [], [] -> () + | h1 :: t1, h2 :: t2 -> f.Invoke(n, h1, h2); loop (n+1) t1 t2 + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length loop 0 list1 list2 [] - let map3 mapping list1 list2 list3 = + let map3 mapping list1 list2 list3 = Microsoft.FSharp.Primitives.Basics.List.map3 mapping list1 list2 list3 [] - let mapi2 mapping list1 list2 = + let mapi2 mapping list1 list2 = Microsoft.FSharp.Primitives.Basics.List.mapi2 mapping list1 list2 [] let map2 mapping list1 list2 = Microsoft.FSharp.Primitives.Basics.List.map2 mapping list1 list2 [] - let fold<'T,'State> folder (state:'State) (list: 'T list) = - match list with + let fold<'T, 'State> folder (state:'State) (list: 'T list) = + match list with | [] -> state - | _ -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(folder) + | _ -> + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(folder) let mutable acc = state for x in list do acc <- f.Invoke(acc, x) @@ -235,126 +235,126 @@ namespace Microsoft.FSharp.Collections Microsoft.FSharp.Primitives.Basics.List.pairwise list [] - let reduce reduction list = - match list with + let reduce reduction list = + match list with | [] -> invalidArg "list" (SR.GetString(SR.inputListWasEmpty)) - | h::t -> fold reduction h t + | h :: t -> fold reduction h t [] - let scan<'T,'State> folder (state:'State) (list:'T list) = + let scan<'T, 'State> folder (state:'State) (list:'T list) = Microsoft.FSharp.Primitives.Basics.List.scan folder state list [] let inline singleton value = [value] [] - let fold2<'T1,'T2,'State> folder (state:'State) (list1:list<'T1>) (list2:list<'T2>) = - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(folder) + let fold2<'T1, 'T2, 'State> folder (state:'State) (list1:list<'T1>) (list2:list<'T2>) = + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(folder) let rec loop acc list1 list2 = - match list1,list2 with - | [],[] -> acc - | h1::t1, h2::t2 -> loop (f.Invoke(acc,h1,h2)) t1 t2 - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + match list1, list2 with + | [], [] -> acc + | h1 :: t1, h2 :: t2 -> loop (f.Invoke(acc, h1, h2)) t1 t2 + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length loop state list1 list2 - let foldArraySubRight (f:OptimizedClosures.FSharpFunc<'T,_,_>) (arr: 'T[]) start fin acc = + let foldArraySubRight (f:OptimizedClosures.FSharpFunc<'T, _, _>) (arr: 'T[]) start fin acc = let mutable state = acc for i = fin downto start do state <- f.Invoke(arr.[i], state) state - // this version doesn't causes stack overflow - it uses a private stack + // this version doesn't causes stack overflow - it uses a private stack [] - let foldBack<'T,'State> folder (list:'T list) (state:'State) = - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(folder) - match list with + let foldBack<'T, 'State> folder (list:'T list) (state:'State) = + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(folder) + match list with | [] -> state - | [h] -> f.Invoke(h,state) - | [h1;h2] -> f.Invoke(h1,f.Invoke(h2,state)) - | [h1;h2;h3] -> f.Invoke(h1,f.Invoke(h2,f.Invoke(h3,state))) - | [h1;h2;h3;h4] -> f.Invoke(h1,f.Invoke(h2,f.Invoke(h3,f.Invoke(h4,state)))) - | _ -> - // It is faster to allocate and iterate an array than to create all those - // highly nested stacks. It also means we won't get stack overflows here. + | [h] -> f.Invoke(h, state) + | [h1; h2] -> f.Invoke(h1, f.Invoke(h2, state)) + | [h1; h2; h3] -> f.Invoke(h1, f.Invoke(h2, f.Invoke(h3, state))) + | [h1; h2; h3; h4] -> f.Invoke(h1, f.Invoke(h2, f.Invoke(h3, f.Invoke(h4, state)))) + | _ -> + // It is faster to allocate and iterate an array than to create all those + // highly nested stacks. It also means we won't get stack overflows here. let arr = toArray list let arrn = arr.Length foldArraySubRight f arr 0 (arrn - 1) state [] - let reduceBack reduction list = - match list with + let reduceBack reduction list = + match list with | [] -> invalidArg "list" (SR.GetString(SR.inputListWasEmpty)) - | _ -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(reduction) + | _ -> + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(reduction) let arr = toArray list let arrn = arr.Length foldArraySubRight f arr 0 (arrn - 2) arr.[arrn - 1] - let scanArraySubRight<'T,'State> (f:OptimizedClosures.FSharpFunc<'T,'State,'State>) (arr:_[]) start fin initState = + let scanArraySubRight<'T, 'State> (f:OptimizedClosures.FSharpFunc<'T, 'State, 'State>) (arr:_[]) start fin initState = let mutable state = initState let mutable res = [state] for i = fin downto start do - state <- f.Invoke(arr.[i], state); + state <- f.Invoke(arr.[i], state) res <- state :: res res [] - let scanBack<'T,'State> folder (list:'T list) (state:'State) = - match list with + let scanBack<'T, 'State> folder (list:'T list) (state:'State) = + match list with | [] -> [state] - | [h] -> + | [h] -> [folder h state; state] - | _ -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(folder) - // It is faster to allocate and iterate an array than to create all those - // highly nested stacks. It also means we won't get stack overflows here. + | _ -> + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(folder) + // It is faster to allocate and iterate an array than to create all those + // highly nested stacks. It also means we won't get stack overflows here. let arr = toArray list let arrn = arr.Length scanArraySubRight f arr 0 (arrn - 1) state - let foldBack2UsingArrays (f:OptimizedClosures.FSharpFunc<_,_,_,_>) list1 list2 acc = + let foldBack2UsingArrays (f:OptimizedClosures.FSharpFunc<_, _, _, _>) list1 list2 acc = let arr1 = toArray list1 let arr2 = toArray list2 let n1 = arr1.Length let n2 = arr2.Length - if n1 <> n2 then - invalidArgFmt "list1, list2" + if n1 <> n2 then + invalidArgFmt "list1, list2" "{0}\nlist1.Length = {1}, list2.Length = {2}" [|SR.GetString SR.listsHadDifferentLengths; arr1.Length; arr2.Length|] let mutable res = acc for i = n1 - 1 downto 0 do - res <- f.Invoke(arr1.[i],arr2.[i],res) + res <- f.Invoke(arr1.[i], arr2.[i], res) res [] - let rec foldBack2<'T1,'T2,'State> folder (list1:'T1 list) (list2:'T2 list) (state:'State) = - match list1,list2 with - | [],[] -> state - | h1::rest1, k1::rest2 -> - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(folder) - match rest1, rest2 with - | [],[] -> f.Invoke(h1,k1,state) - | [h2],[k2] -> f.Invoke(h1,k1,f.Invoke(h2,k2,state)) - | [h2;h3],[k2;k3] -> f.Invoke(h1,k1,f.Invoke(h2,k2,f.Invoke(h3,k3,state))) - | [h2;h3;h4],[k2;k3;k4] -> f.Invoke(h1,k1,f.Invoke(h2,k2,f.Invoke(h3,k3,f.Invoke(h4,k4,state)))) + let rec foldBack2<'T1, 'T2, 'State> folder (list1:'T1 list) (list2:'T2 list) (state:'State) = + match list1, list2 with + | [], [] -> state + | h1 :: rest1, k1 :: rest2 -> + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(folder) + match rest1, rest2 with + | [], [] -> f.Invoke(h1, k1, state) + | [h2], [k2] -> f.Invoke(h1, k1, f.Invoke(h2, k2, state)) + | [h2; h3], [k2; k3] -> f.Invoke(h1, k1, f.Invoke(h2, k2, f.Invoke(h3, k3, state))) + | [h2; h3; h4], [k2; k3; k4] -> f.Invoke(h1, k1, f.Invoke(h2, k2, f.Invoke(h3, k3, f.Invoke(h4, k4, state)))) | _ -> foldBack2UsingArrays f list1 list2 state - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length - let rec forall2aux (f:OptimizedClosures.FSharpFunc<_,_,_>) list1 list2 = - match list1,list2 with - | [],[] -> true - | h1::t1, h2::t2 -> f.Invoke(h1,h2) && forall2aux f t1 t2 - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + let rec forall2aux (f:OptimizedClosures.FSharpFunc<_, _, _>) list1 list2 = + match list1, list2 with + | [], [] -> true + | h1 :: t1, h2 :: t2 -> f.Invoke(h1, h2) && forall2aux f t1 t2 + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length [] - let forall2 predicate list1 list2 = - match list1,list2 with - | [],[] -> true - | _ -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(predicate) + let forall2 predicate list1 list2 = + match list1, list2 with + | [], [] -> true + | _ -> + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(predicate) forall2aux f list1 list2 [] @@ -362,34 +362,34 @@ namespace Microsoft.FSharp.Collections [] let exists predicate list = Microsoft.FSharp.Primitives.Basics.List.exists predicate list - + [] let inline contains value source = let rec contains e xs1 = match xs1 with | [] -> false - | h1::t1 -> e = h1 || contains e t1 + | h1 :: t1 -> e = h1 || contains e t1 contains value source - let rec exists2aux (f:OptimizedClosures.FSharpFunc<_,_,_>) list1 list2 = - match list1,list2 with - | [],[] -> false - | h1::t1, h2::t2 ->f.Invoke(h1,h2) || exists2aux f t1 t2 + let rec exists2aux (f:OptimizedClosures.FSharpFunc<_, _, _>) list1 list2 = + match list1, list2 with + | [], [] -> false + | h1 :: t1, h2 :: t2 ->f.Invoke(h1, h2) || exists2aux f t1 t2 | _ -> invalidArg "list2" (SR.GetString(SR.listsHadDifferentLengths)) [] - let rec exists2 predicate list1 list2 = - match list1,list2 with - | [],[] -> false - | _ -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(predicate) + let rec exists2 predicate list1 list2 = + match list1, list2 with + | [], [] -> false + | _ -> + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(predicate) exists2aux f list1 list2 [] - let rec find predicate list = match list with [] -> indexNotFound() | h::t -> if predicate h then h else find predicate t + let rec find predicate list = match list with [] -> indexNotFound() | h :: t -> if predicate h then h else find predicate t [] - let rec tryFind predicate list = match list with [] -> None | h::t -> if predicate h then Some h else tryFind predicate t + let rec tryFind predicate list = match list with [] -> None | h :: t -> if predicate h then Some h else tryFind predicate t [] let findBack predicate list = list |> toArray |> Microsoft.FSharp.Primitives.Basics.Array.findBack predicate @@ -398,21 +398,21 @@ namespace Microsoft.FSharp.Collections let tryFindBack predicate list = list |> toArray |> Microsoft.FSharp.Primitives.Basics.Array.tryFindBack predicate [] - let rec tryPick chooser list = - match list with - | [] -> None - | h::t -> - match chooser h with - | None -> tryPick chooser t + let rec tryPick chooser list = + match list with + | [] -> None + | h :: t -> + match chooser h with + | None -> tryPick chooser t | r -> r [] - let rec pick chooser list = - match list with + let rec pick chooser list = + match list with | [] -> indexNotFound() - | h::t -> - match chooser h with - | None -> pick chooser t + | h :: t -> + match chooser h with + | None -> pick chooser t | Some r -> r [] @@ -451,7 +451,7 @@ namespace Microsoft.FSharp.Collections [] let partition predicate list = Microsoft.FSharp.Primitives.Basics.List.partition predicate list - + [] let unzip list = Microsoft.FSharp.Primitives.Basics.List.unzip list @@ -479,7 +479,7 @@ namespace Microsoft.FSharp.Collections let rec loop i lst = match lst with | _ when i = 0 -> lst - | _::t -> loop (i-1) t + | _ :: t -> loop (i-1) t | [] -> invalidArgOutOfRange "count" count "distance past the list" i loop count list @@ -500,18 +500,18 @@ namespace Microsoft.FSharp.Collections [] let sortBy projection list = - match list with + match list with | [] | [_] -> list - | _ -> + | _ -> let array = Microsoft.FSharp.Primitives.Basics.List.toArray list Microsoft.FSharp.Primitives.Basics.Array.stableSortInPlaceBy projection array Microsoft.FSharp.Primitives.Basics.List.ofArray array - + [] let sort list = - match list with + match list with | [] | [_] -> list - | _ -> + | _ -> let array = Microsoft.FSharp.Primitives.Basics.List.toArray list Microsoft.FSharp.Primitives.Basics.Array.stableSortInPlace array Microsoft.FSharp.Primitives.Basics.List.ofArray array @@ -533,15 +533,15 @@ namespace Microsoft.FSharp.Collections let toSeq list = Seq.ofList list [] - let findIndex predicate list = - let rec loop n = function[] -> indexNotFound() | h::t -> if predicate h then n else loop (n+1) t + let findIndex predicate list = + let rec loop n = function[] -> indexNotFound() | h :: t -> if predicate h then n else loop (n+1) t loop 0 list [] - let tryFindIndex predicate list = - let rec loop n = function[] -> None | h::t -> if predicate h then Some n else loop (n+1) t + let tryFindIndex predicate list = + let rec loop n = function[] -> None | h :: t -> if predicate h then Some n else loop (n+1) t loop 0 list - + [] let findIndexBack predicate list = list |> toArray |> Microsoft.FSharp.Primitives.Basics.Array.findIndexBack predicate @@ -550,7 +550,7 @@ namespace Microsoft.FSharp.Collections [] let inline sum (list:list<'T>) = - match list with + match list with | [] -> LanguagePrimitives.GenericZero< 'T > | t -> let mutable acc = LanguagePrimitives.GenericZero< 'T > @@ -560,7 +560,7 @@ namespace Microsoft.FSharp.Collections [] let inline sumBy (projection: 'T -> 'U) (list:list<'T>) = - match list with + match list with | [] -> LanguagePrimitives.GenericZero< 'U > | t -> let mutable acc = LanguagePrimitives.GenericZero< 'U > @@ -570,9 +570,9 @@ namespace Microsoft.FSharp.Collections [] let inline max (list:list<_>) = - match list with + match list with | [] -> invalidArg "list" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString - | h::t -> + | h :: t -> let mutable acc = h for x in t do if x > acc then @@ -581,9 +581,9 @@ namespace Microsoft.FSharp.Collections [] let inline maxBy projection (list:list<_>) = - match list with + match list with | [] -> invalidArg "list" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString - | h::t -> + | h :: t -> let mutable acc = h let mutable accv = projection h for x in t do @@ -592,12 +592,12 @@ namespace Microsoft.FSharp.Collections acc <- x accv <- currv acc - + [] let inline min (list:list<_>) = - match list with + match list with | [] -> invalidArg "list" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString - | h::t -> + | h :: t -> let mutable acc = h for x in t do if x < acc then @@ -606,9 +606,9 @@ namespace Microsoft.FSharp.Collections [] let inline minBy projection (list:list<_>) = - match list with + match list with | [] -> invalidArg "list" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString - | h::t -> + | h :: t -> let mutable acc = h let mutable accv = projection h for x in t do @@ -620,7 +620,7 @@ namespace Microsoft.FSharp.Collections [] let inline average (list:list<'T>) = - match list with + match list with | [] -> invalidArg "source" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString | xs -> let mutable sum = LanguagePrimitives.GenericZero< 'T > @@ -631,8 +631,8 @@ namespace Microsoft.FSharp.Collections LanguagePrimitives.DivideByInt sum count [] - let inline averageBy (projection : 'T -> 'U) (list:list<'T>) = - match list with + let inline averageBy (projection: 'T -> 'U) (list:list<'T>) = + match list with | [] -> invalidArg "source" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString | xs -> let mutable sum = LanguagePrimitives.GenericZero< 'U > @@ -665,20 +665,20 @@ namespace Microsoft.FSharp.Collections let permute indexMap list = list |> toArray |> Microsoft.FSharp.Primitives.Basics.Array.permute indexMap |> ofArray [] - let exactlyOne (list : list<_>) = + let exactlyOne (list: list<_>) = match list with | [x] -> x - | [] -> invalidArg "source" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString + | [] -> invalidArg "source" LanguagePrimitives.ErrorStrings.InputSequenceEmptyString | _ -> invalidArg "source" (SR.GetString(SR.inputSequenceTooLong)) [] - let tryExactlyOne (list : list<_>) = + let tryExactlyOne (list: list<_>) = match list with | [x] -> Some x | _ -> None [] - let transpose (lists : seq<'T list>) = + let transpose (lists: seq<'T list>) = checkNonNull "lists" lists Microsoft.FSharp.Primitives.Basics.List.transpose (ofSeq lists) @@ -686,4 +686,4 @@ namespace Microsoft.FSharp.Collections let truncate count list = Microsoft.FSharp.Primitives.Basics.List.truncate count list [] - let unfold<'T,'State> (generator:'State -> ('T*'State) option) (state:'State) = Microsoft.FSharp.Primitives.Basics.List.unfold generator state + let unfold<'T, 'State> (generator:'State -> ('T*'State) option) (state:'State) = Microsoft.FSharp.Primitives.Basics.List.unfold generator state diff --git a/src/fsharp/FSharp.Core/local.fs b/src/fsharp/FSharp.Core/local.fs index 42297795184..9fb452907f4 100644 --- a/src/fsharp/FSharp.Core/local.fs +++ b/src/fsharp/FSharp.Core/local.fs @@ -8,97 +8,97 @@ module internal DetailedExceptions = open Microsoft.FSharp.Core /// takes an argument, a formatting string, a param array to splice into the formatting string - let inline invalidArgFmt (arg:string) (format:string) paramArray = - let msg = String.Format (format,paramArray) - raise (new ArgumentException (msg,arg)) + let inline invalidArgFmt (arg:string) (format:string) paramArray = + let msg = String.Format (format, paramArray) + raise (new ArgumentException (msg, arg)) /// takes a formatting string and a param array to splice into the formatting string let inline invalidOpFmt (format:string) paramArray = - let msg = String.Format (format,paramArray) + let msg = String.Format (format, paramArray) raise (new InvalidOperationException(msg)) /// throws an invalid argument exception and returns the difference between the lists' lengths let invalidArgDifferentListLength (arg1:string) (arg2:string) (diff:int) = invalidArgFmt arg1 - "{0}\n{1} is {2} {3} shorter than {4}" + "{0}\n{1} is {2} {3} shorter than {4}" [|SR.GetString SR.listsHadDifferentLengths; arg1; diff; (if diff=1 then "element" else "elements"); arg2|] /// throws an invalid argument exception and returns the length of the 3 arrays - let invalidArg3ListsDifferent (arg1:string) (arg2:string) (arg3:string) (len1:int) (len2:int) (len3:int) = + let invalidArg3ListsDifferent (arg1:string) (arg2:string) (arg3:string) (len1:int) (len2:int) (len3:int) = invalidArgFmt (String.Concat [|arg1; ", "; arg2; ", "; arg3|]) - "{0}\n {1}.Length = {2}, {3}.Length = {4}, {5}.Length = {6}" + "{0}\n {1}.Length = {2}, {3}.Length = {4}, {5}.Length = {6}" [|SR.GetString SR.listsHadDifferentLengths; arg1; len1; arg2; len2; arg3; len3|] - /// throws an invalid operation exception and returns how many elements the + /// throws an invalid operation exception and returns how many elements the /// list is shorter than the index - let invalidOpListNotEnoughElements (index:int) = - invalidOpFmt - "{0}\nThe list was {1} {2} shorter than the index" + let invalidOpListNotEnoughElements (index:int) = + invalidOpFmt + "{0}\nThe list was {1} {2} shorter than the index" [|SR.GetString SR.notEnoughElements; index; (if index=1 then "element" else "elements")|] - + /// eg. tried to {skip} {2} {elements} past the end of the seq. Seq.Length = {10} let invalidOpExceededSeqLength (fnName:string) (diff:int) (len:int) = - invalidOpFmt "{0}\ntried to {1} {2} {3} past the end of the seq\nSeq.Length = {4}" - [|SR.GetString SR.notEnoughElements; fnName; diff; (if diff=1 then "element" else "elements");len|] + invalidOpFmt "{0}\ntried to {1} {2} {3} past the end of the seq\nSeq.Length = {4}" + [|SR.GetString SR.notEnoughElements; fnName; diff; (if diff=1 then "element" else "elements");len|] /// throws an invalid argument exception and returns the arg's value let inline invalidArgInputMustBeNonNegative (arg:string) (count:int) = invalidArgFmt arg "{0}\n{1} = {2}" [|LanguagePrimitives.ErrorStrings.InputMustBeNonNegativeString ; arg; count|] - + /// throws an invalid argument exception and returns the arg's value let inline invalidArgInputMustBePositive (arg:string) (count:int) = invalidArgFmt arg "{0}\n{1} = {2}" [|SR.GetString SR.inputMustBePositive; arg; count|] /// throws an invalid argument exception and returns the out of range index, /// a text description of the range, and the bound of the range - /// e.g. sourceIndex = -4, source axis-0 lower bound = 0" + /// e.g. sourceIndex = -4, source axis-0 lower bound = 0" let invalidArgOutOfRange (arg:string) (index:int) (text:string) (bound:int) = invalidArgFmt arg - "{0}\n{1} = {2}, {3} = {4}" + "{0}\n{1} = {2}, {3} = {4}" [|SR.GetString SR.outOfRange; arg; index; text; bound|] /// throws an invalid argument exception and returns the difference between the lists' lengths let invalidArgDifferentArrayLength (arg1:string) (len1:int) (arg2:string) (len2:int) = invalidArgFmt arg1 - "{0}\n{1}.Length = {2}, {3}.Length = {4}" + "{0}\n{1}.Length = {2}, {3}.Length = {4}" [|SR.GetString SR.arraysHadDifferentLengths; arg1; len1; arg2; len2 |] /// throws an invalid argument exception and returns the lengths of the 3 arrays - let invalidArg3ArraysDifferent (arg1:string) (arg2:string) (arg3:string) (len1:int) (len2:int) (len3:int) = + let invalidArg3ArraysDifferent (arg1:string) (arg2:string) (arg3:string) (len1:int) (len2:int) (len3:int) = invalidArgFmt (String.Concat [|arg1; ", "; arg2; ", "; arg3|]) - "{0}\n {1}.Length = {2}, {3}.Length = {4}, {5}.Length = {6}" + "{0}\n {1}.Length = {2}, {3}.Length = {4}, {5}.Length = {6}" [|SR.GetString SR.arraysHadDifferentLengths; arg1; len1; arg2; len2; arg3; len3|] -namespace Microsoft.FSharp.Primitives.Basics +namespace Microsoft.FSharp.Primitives.Basics open Microsoft.FSharp.Core open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators open Microsoft.FSharp.Collections open Microsoft.FSharp.Core.Operators -open System.Diagnostics.CodeAnalysis +open System.Diagnostics.CodeAnalysis open System.Collections.Generic -module internal List = +module internal List = let arrayZeroCreate (n:int) = (# "newarr !0" type ('T) n : 'T array #) - [] + [] let nonempty x = match x with [] -> false | _ -> true - let rec iter f x = match x with [] -> () | h::t -> f h; iter f t + let rec iter f x = match x with [] -> () | h :: t -> f h; iter f t // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let inline setFreshConsTail cons t = cons.(::).1 <- t + let inline setFreshConsTail cons t = cons.( :: ).1 <- t let inline freshConsNoTail h = h :: (# "ldnull" : 'T list #) - let rec distinctToFreshConsTail cons (hashSet:HashSet<_>) list = + let rec distinctToFreshConsTail cons (hashSet:HashSet<_>) list = match list with | [] -> setFreshConsTail cons [] - | x::rest -> + | x :: rest -> if hashSet.Add x then let cons2 = freshConsNoTail x setFreshConsTail cons cons2 @@ -110,17 +110,17 @@ module internal List = match list with | [] -> [] | [h] -> [h] - | x::rest -> + | x :: rest -> let hashSet = HashSet<'T>(comparer) hashSet.Add x |> ignore let cons = freshConsNoTail x distinctToFreshConsTail cons hashSet rest cons - let rec distinctByToFreshConsTail cons (hashSet:HashSet<_>) keyf list = + let rec distinctByToFreshConsTail cons (hashSet:HashSet<_>) keyf list = match list with | [] -> setFreshConsTail cons [] - | x::rest -> + | x :: rest -> if hashSet.Add(keyf x) then let cons2 = freshConsNoTail x setFreshConsTail cons cons2 @@ -128,18 +128,18 @@ module internal List = else distinctByToFreshConsTail cons hashSet keyf rest - let distinctByWithComparer (comparer: IEqualityComparer<'Key>) (keyf:'T -> 'Key) (list:'T list) = + let distinctByWithComparer (comparer: IEqualityComparer<'Key>) (keyf:'T -> 'Key) (list:'T list) = match list with | [] -> [] | [h] -> [h] - | x::rest -> + | x :: rest -> let hashSet = HashSet<'Key>(comparer) hashSet.Add(keyf x) |> ignore let cons = freshConsNoTail x distinctByToFreshConsTail cons hashSet keyf rest cons - - let countBy (dict:Dictionary<_, int>) (keyf:'T -> 'Key) = + + let countBy (dict:Dictionary<_, int>) (keyf:'T -> 'Key) = // No need to dispose enumerator Dispose does nothing. let mutable ie = dict.GetEnumerator() if not (ie.MoveNext()) then [] @@ -154,47 +154,47 @@ module internal List = cons <- cons2 setFreshConsTail cons [] res - - let rec pairwiseToFreshConsTail cons list lastvalue = + + let rec pairwiseToFreshConsTail cons list lastvalue = match list with | [] -> setFreshConsTail cons [] | [h] -> setFreshConsTail cons [(lastvalue, h)] - | h::t -> + | h :: t -> let cons2 = freshConsNoTail (lastvalue, h) setFreshConsTail cons cons2 pairwiseToFreshConsTail cons2 t h - let pairwise list = + let pairwise list = match list with | [] -> [] | [_] -> [] - | x1::x2::t -> + | x1 :: x2 :: t -> let cons = freshConsNoTail (x1, x2) pairwiseToFreshConsTail cons t x2 cons let rec chooseToFreshConsTail cons f xs = - match xs with + match xs with | [] -> setFreshConsTail cons [] - | h::t -> - match f h with - | None -> chooseToFreshConsTail cons f t - | Some x -> + | h :: t -> + match f h with + | None -> chooseToFreshConsTail cons f t + | Some x -> let cons2 = freshConsNoTail x setFreshConsTail cons cons2 chooseToFreshConsTail cons2 f t let rec choose f xs = - match xs with + match xs with | [] -> [] - | h::t -> + | h :: t -> match f h with | None -> choose f t - | Some x -> + | Some x -> let cons = freshConsNoTail x chooseToFreshConsTail cons f t cons - + let groupBy (comparer:IEqualityComparer<'SafeKey>) (keyf:'T->'SafeKey) (getKey:'SafeKey->'Key) (list: 'T list) = match list with | [] -> [] @@ -205,19 +205,19 @@ module internal List = // Build the groupings let rec loop list = match list with - | v :: t -> + | v :: t -> let safeKey = keyf v match dict.TryGetValue(safeKey) with - | true, prev -> + | true, prev -> let cons2 = freshConsNoTail v setFreshConsTail prev.[1] cons2 prev.[1] <- cons2 | _ -> let res = freshConsNoTail v dict.[safeKey] <- [|res; res |] // First index stores the result list; second index is the most recent cons. - + loop t | _ -> () - loop list + loop list let mutable ie = dict.GetEnumerator() if not (ie.MoveNext()) then [] @@ -235,124 +235,124 @@ module internal List = setFreshConsTail cons [] res - let rec mapToFreshConsTail cons f x = + let rec mapToFreshConsTail cons f x = match x with - | [] -> + | [] -> setFreshConsTail cons [] - | h::t -> + | h :: t -> let cons2 = freshConsNoTail (f h) setFreshConsTail cons cons2 mapToFreshConsTail cons2 f t - let map mapping x = + let map mapping x = match x with | [] -> [] | [h] -> [mapping h] - | h::t -> + | h :: t -> let cons = freshConsNoTail (mapping h) mapToFreshConsTail cons mapping t cons - let rec mapiToFreshConsTail cons (f:OptimizedClosures.FSharpFunc<_,_,_>) x i = + let rec mapiToFreshConsTail cons (f:OptimizedClosures.FSharpFunc<_, _, _>) x i = match x with - | [] -> + | [] -> setFreshConsTail cons [] - | h::t -> - let cons2 = freshConsNoTail (f.Invoke(i,h)) + | h :: t -> + let cons2 = freshConsNoTail (f.Invoke(i, h)) setFreshConsTail cons cons2 mapiToFreshConsTail cons2 f t (i+1) - let mapi f x = + let mapi f x = match x with | [] -> [] | [h] -> [f 0 h] - | h::t -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) - let cons = freshConsNoTail (f.Invoke(0,h)) + | h :: t -> + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) + let cons = freshConsNoTail (f.Invoke(0, h)) mapiToFreshConsTail cons f t 1 cons - let rec map2ToFreshConsTail cons (f:OptimizedClosures.FSharpFunc<_,_,_>) xs1 xs2 = - match xs1,xs2 with - | [],[] -> + let rec map2ToFreshConsTail cons (f:OptimizedClosures.FSharpFunc<_, _, _>) xs1 xs2 = + match xs1, xs2 with + | [], [] -> setFreshConsTail cons [] - | h1::t1, h2::t2 -> - let cons2 = freshConsNoTail (f.Invoke(h1,h2)) + | h1 :: t1, h2 :: t2 -> + let cons2 = freshConsNoTail (f.Invoke(h1, h2)) setFreshConsTail cons cons2 map2ToFreshConsTail cons2 f t1 t2 - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length - - let map2 mapping xs1 xs2 = - match xs1,xs2 with - | [],[] -> [] - | h1::t1, h2::t2 -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(mapping) - let cons = freshConsNoTail (f.Invoke(h1,h2)) + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + + let map2 mapping xs1 xs2 = + match xs1, xs2 with + | [], [] -> [] + | h1 :: t1, h2 :: t2 -> + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(mapping) + let cons = freshConsNoTail (f.Invoke(h1, h2)) map2ToFreshConsTail cons f t1 t2 cons - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length - let rec map3ToFreshConsTail cons (f:OptimizedClosures.FSharpFunc<_,_,_,_>) xs1 xs2 xs3 = - match xs1,xs2,xs3 with - | [],[],[] -> + let rec map3ToFreshConsTail cons (f:OptimizedClosures.FSharpFunc<_, _, _, _>) xs1 xs2 xs3 = + match xs1, xs2, xs3 with + | [], [], [] -> setFreshConsTail cons [] - | h1::t1, h2::t2, h3::t3 -> - let cons2 = freshConsNoTail (f.Invoke(h1,h2,h3)) + | h1 :: t1, h2 :: t2, h3 :: t3 -> + let cons2 = freshConsNoTail (f.Invoke(h1, h2, h3)) setFreshConsTail cons cons2 map3ToFreshConsTail cons2 f t1 t2 t3 - | xs1,xs2,xs3 -> - invalidArg3ListsDifferent "list1" "list2" "list3" xs1.Length xs2.Length xs3.Length - - let map3 mapping xs1 xs2 xs3 = - match xs1,xs2,xs3 with - | [],[],[] -> [] - | h1::t1, h2::t2, h3::t3 -> - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(mapping) - let cons = freshConsNoTail (f.Invoke(h1,h2,h3)) + | xs1, xs2, xs3 -> + invalidArg3ListsDifferent "list1" "list2" "list3" xs1.Length xs2.Length xs3.Length + + let map3 mapping xs1 xs2 xs3 = + match xs1, xs2, xs3 with + | [], [], [] -> [] + | h1 :: t1, h2 :: t2, h3 :: t3 -> + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(mapping) + let cons = freshConsNoTail (f.Invoke(h1, h2, h3)) map3ToFreshConsTail cons f t1 t2 t3 cons - | xs1,xs2,xs3 -> - invalidArg3ListsDifferent "list1" "list2" "list3" xs1.Length xs2.Length xs3.Length + | xs1, xs2, xs3 -> + invalidArg3ListsDifferent "list1" "list2" "list3" xs1.Length xs2.Length xs3.Length - let rec mapi2ToFreshConsTail n cons (f:OptimizedClosures.FSharpFunc<_,_,_,_>) xs1 xs2 = - match xs1,xs2 with - | [],[] -> + let rec mapi2ToFreshConsTail n cons (f:OptimizedClosures.FSharpFunc<_, _, _, _>) xs1 xs2 = + match xs1, xs2 with + | [], [] -> setFreshConsTail cons [] - | h1::t1, h2::t2 -> - let cons2 = freshConsNoTail (f.Invoke(n,h1,h2)) + | h1 :: t1, h2 :: t2 -> + let cons2 = freshConsNoTail (f.Invoke(n, h1, h2)) setFreshConsTail cons cons2 mapi2ToFreshConsTail (n + 1) cons2 f t1 t2 - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length - - let mapi2 f xs1 xs2 = - match xs1,xs2 with - | [],[] -> [] - | h1::t1, h2::t2 -> - let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f) - let cons = freshConsNoTail (f.Invoke(0, h1,h2)) + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + + let mapi2 f xs1 xs2 = + match xs1, xs2 with + | [], [] -> [] + | h1 :: t1, h2 :: t2 -> + let f = OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(f) + let cons = freshConsNoTail (f.Invoke(0, h1, h2)) mapi2ToFreshConsTail 1 cons f t1 t2 cons - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length - - let rec scanToFreshConsTail cons xs s (f: OptimizedClosures.FSharpFunc<_,_,_>) = + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + + let rec scanToFreshConsTail cons xs s (f: OptimizedClosures.FSharpFunc<_, _, _>) = match xs with | [] -> setFreshConsTail cons [] - | h::t -> - let newState = f.Invoke(s,h) + | h :: t -> + let newState = f.Invoke(s, h) let cons2 = freshConsNoTail newState setFreshConsTail cons cons2 scanToFreshConsTail cons2 t newState f - let scan f (s:'State) (list:'T list) = - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) - match list with + let scan f (s:'State) (list:'T list) = + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) + match list with | [] -> [s] - | _ -> + | _ -> let cons = freshConsNoTail s scanToFreshConsTail cons list s f cons @@ -361,17 +361,17 @@ module internal List = match xs with | [] -> setFreshConsTail cons [] - | h::t -> - let cons2 = freshConsNoTail (i,h) + | h :: t -> + let cons2 = freshConsNoTail (i, h) setFreshConsTail cons cons2 indexedToFreshConsTail cons2 t (i+1) let indexed xs = match xs with | [] -> [] - | [h] -> [(0,h)] - | h::t -> - let cons = freshConsNoTail (0,h) + | [h] -> [(0, h)] + | h :: t -> + let cons = freshConsNoTail (0, h) indexedToFreshConsTail cons t 1 cons @@ -380,8 +380,8 @@ module internal List = | [] -> setFreshConsTail cons [] acc - | h::t -> - let x',s' = f.Invoke(acc,h) + | h :: t -> + let x', s' = f.Invoke(acc, h) let cons2 = freshConsNoTail x' setFreshConsTail cons cons2 mapFoldToFreshConsTail cons2 f s' t @@ -390,77 +390,77 @@ module internal List = match xs with | [] -> [], acc | [h] -> - let x',s' = f acc h - [x'],s' - | h::t -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) - let x',s' = f.Invoke(acc,h) + let x', s' = f acc h + [x'], s' + | h :: t -> + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) + let x', s' = f.Invoke(acc, h) let cons = freshConsNoTail x' let s' = mapFoldToFreshConsTail cons f s' t cons, s' - let rec forall predicate xs1 = - match xs1 with + let rec forall predicate xs1 = + match xs1 with | [] -> true - | h1::t1 -> predicate h1 && forall predicate t1 + | h1 :: t1 -> predicate h1 && forall predicate t1 - let rec exists predicate xs1 = - match xs1 with + let rec exists predicate xs1 = + match xs1 with | [] -> false - | h1::t1 -> predicate h1 || exists predicate t1 + | h1 :: t1 -> predicate h1 || exists predicate t1 - let rec revAcc xs acc = - match xs with + let rec revAcc xs acc = + match xs with | [] -> acc - | h::t -> revAcc t (h::acc) + | h :: t -> revAcc t (h :: acc) - let rev xs = - match xs with + let rev xs = + match xs with | [] -> xs | [_] -> xs - | h1::h2::t -> revAcc t [h2;h1] + | h1 :: h2 :: t -> revAcc t [h2;h1] // return the last cons it the chain - let rec appendToFreshConsTail cons xs = - match xs with - | [] -> + let rec appendToFreshConsTail cons xs = + match xs with + | [] -> setFreshConsTail cons xs // note, xs = [] cons - | h::t -> + | h :: t -> let cons2 = freshConsNoTail h setFreshConsTail cons cons2 appendToFreshConsTail cons2 t // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec collectToFreshConsTail (f:'T -> 'U list) (list:'T list) cons = - match list with - | [] -> + let rec collectToFreshConsTail (f:'T -> 'U list) (list:'T list) cons = + match list with + | [] -> setFreshConsTail cons [] - | h::t -> + | h :: t -> collectToFreshConsTail f t (appendToFreshConsTail cons (f h)) - let rec collect (f:'T -> 'U list) (list:'T list) = + let rec collect (f:'T -> 'U list) (list:'T list) = match list with | [] -> [] | [h] -> f h | _ -> let cons = freshConsNoTail (Unchecked.defaultof<'U>) collectToFreshConsTail f list cons - cons.Tail + cons.Tail let rec allPairsToFreshConsTailSingle x ys cons = match ys with | [] -> cons - | h2::t2 -> - let cons2 = freshConsNoTail (x,h2) + | h2 :: t2 -> + let cons2 = freshConsNoTail (x, h2) setFreshConsTail cons cons2 allPairsToFreshConsTailSingle x t2 cons2 let rec allPairsToFreshConsTail xs ys cons = match xs with | [] -> setFreshConsTail cons [] - | h::t -> + | h :: t -> let p = allPairsToFreshConsTailSingle h ys cons allPairsToFreshConsTail t ys p @@ -475,53 +475,53 @@ module internal List = // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec filterToFreshConsTail cons f l = - match l with - | [] -> + let rec filterToFreshConsTail cons f l = + match l with + | [] -> setFreshConsTail cons l // note, l = nil - | h::t -> - if f h then - let cons2 = freshConsNoTail h + | h :: t -> + if f h then + let cons2 = freshConsNoTail h setFreshConsTail cons cons2 filterToFreshConsTail cons2 f t - else + else filterToFreshConsTail cons f t - - let rec filter predicate l = - match l with + + let rec filter predicate l = + match l with | [] -> l | h :: ([] as nil) -> if predicate h then l else nil - | h::t -> - if predicate h then - let cons = freshConsNoTail h + | h :: t -> + if predicate h then + let cons = freshConsNoTail h filterToFreshConsTail cons predicate t cons - else + else filter predicate t - let iteri action x = - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(action) - let rec loop n x = - match x with - | [] -> () - | h::t -> f.Invoke(n,h); loop (n+1) t + let iteri action x = + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(action) + let rec loop n x = + match x with + | [] -> () + | h :: t -> f.Invoke(n, h); loop (n+1) t loop 0 x // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec concatToFreshConsTail cons h1 l = - match l with + let rec concatToFreshConsTail cons h1 l = + match l with | [] -> setFreshConsTail cons h1 - | h2::t -> concatToFreshConsTail (appendToFreshConsTail cons h1) h2 t - + | h2 :: t -> concatToFreshConsTail (appendToFreshConsTail cons h1) h2 t + // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec concatToEmpty l = - match l with + let rec concatToEmpty l = + match l with | [] -> [] - | []::t -> concatToEmpty t - | (h::t1)::tt2 -> + | [] :: t -> concatToEmpty t + | (h :: t1) :: tt2 -> let res = freshConsNoTail h concatToFreshConsTail res t1 tt2 res @@ -532,13 +532,13 @@ module internal List = let rec loop i l = match l with | [] -> () - | h::t -> + | h :: t -> res.[i] <- h loop (i+1) t loop 0 l res - let ofArray (arr:'T[]) = + let ofArray (arr:'T[]) = let mutable res = ([]: 'T list) for i = arr.Length-1 downto 0 do res <- arr.[i] :: res @@ -561,26 +561,25 @@ module internal List = setFreshConsTail cons [] res - let concat (l : seq<_>) = + let concat (l : seq<_>) = match ofSeq l with | [] -> [] | [h] -> h | [h1;h2] -> h1 @ h2 | l -> concatToEmpty l - let rec initToFreshConsTail cons i n f = - if i < n then + let rec initToFreshConsTail cons i n f = + if i < n then let cons2 = freshConsNoTail (f i) setFreshConsTail cons cons2 - initToFreshConsTail cons2 (i+1) n f - else + initToFreshConsTail cons2 (i+1) n f + else setFreshConsTail cons [] - - - let init count f = + + let init count f = if count < 0 then invalidArgInputMustBeNonNegative "count" count - if count = 0 then [] - else + if count = 0 then [] + else let res = freshConsNoTail (f 0) initToFreshConsTail res 1 count f res @@ -589,17 +588,17 @@ module internal List = if n = 0 then setFreshConsTail cons [] else match l with | [] -> invalidOpListNotEnoughElements n - | x::xs -> + | x :: xs -> let cons2 = freshConsNoTail x setFreshConsTail cons cons2 takeFreshConsTail cons2 (n - 1) xs - + let take n l = if n < 0 then invalidArgInputMustBeNonNegative "count" n - if n = 0 then [] else + if n = 0 then [] else match l with | [] -> invalidOpListNotEnoughElements n - | x::xs -> + | x :: xs -> let cons = freshConsNoTail x takeFreshConsTail cons (n - 1) xs cons @@ -615,73 +614,73 @@ module internal List = let cons2 = freshConsNoTail x setFreshConsTail cons cons2 splitAtFreshConsTail cons2 (index - 1) xs - + let splitAt index l = if index < 0 then invalidArgInputMustBeNonNegative "index" index if index = 0 then [], l else match l with | [] -> invalidOp (SR.GetString SR.inputListWasEmpty) - | [_] -> - if index = 1 then l, [] else - invalidOpListNotEnoughElements (index-1) - | x::xs -> + | [_] -> + if index = 1 then l, [] else + invalidOpListNotEnoughElements (index-1) + | x :: xs -> if index = 1 then [x], xs else let cons = freshConsNoTail x let tail = splitAtFreshConsTail cons (index - 1) xs - cons, tail - + cons, tail + // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec partitionToFreshConsTails consL consR p l = - match l with - | [] -> + let rec partitionToFreshConsTails consL consR p l = + match l with + | [] -> setFreshConsTail consL l // note, l = nil setFreshConsTail consR l // note, l = nil - - | h::t -> + + | h :: t -> let cons' = freshConsNoTail h - if p h then + if p h then setFreshConsTail consL cons' partitionToFreshConsTails cons' consR p t - else + else setFreshConsTail consR cons' partitionToFreshConsTails consL cons' p t - - let rec partitionToFreshConsTailLeft consL p l = - match l with - | [] -> + + let rec partitionToFreshConsTailLeft consL p l = + match l with + | [] -> setFreshConsTail consL l // note, l = nil l // note, l = nil - | h::t -> - let cons' = freshConsNoTail h - if p h then + | h :: t -> + let cons' = freshConsNoTail h + if p h then setFreshConsTail consL cons' partitionToFreshConsTailLeft cons' p t - else + else partitionToFreshConsTails consL cons' p t cons' - let rec partitionToFreshConsTailRight consR p l = - match l with - | [] -> + let rec partitionToFreshConsTailRight consR p l = + match l with + | [] -> setFreshConsTail consR l // note, l = nil l // note, l = nil - | h::t -> - let cons' = freshConsNoTail h - if p h then + | h :: t -> + let cons' = freshConsNoTail h + if p h then partitionToFreshConsTails cons' consR p t cons' - else + else setFreshConsTail consR cons' partitionToFreshConsTailRight cons' p t - let partition predicate l = - match l with - | [] -> l,l - | h :: ([] as nil) -> if predicate h then l,nil else nil,l - | h::t -> - let cons = freshConsNoTail h - if predicate h + let partition predicate l = + match l with + | [] -> l, l + | h :: ([] as nil) -> if predicate h then l, nil else nil, l + | h :: t -> + let cons = freshConsNoTail h + if predicate h then cons, (partitionToFreshConsTailLeft cons predicate t) else (partitionToFreshConsTailRight cons predicate t), cons @@ -691,13 +690,13 @@ module internal List = setFreshConsTail headsCons [] setFreshConsTail tailsCons [] headCount - | head::tail -> + | head :: tail -> match head with | [] -> setFreshConsTail headsCons [] setFreshConsTail tailsCons [] headCount - | h::t -> + | h :: t -> let headsCons2 = freshConsNoTail h setFreshConsTail headsCons headsCons2 let tailsCons2 = freshConsNoTail t @@ -707,8 +706,8 @@ module internal List = /// Split off the heads of the lists let transposeGetHeads list = match list with - | [] -> [],[],0 - | head::tail -> + | [] -> [], [], 0 + | head :: tail -> match head with | [] -> let mutable j = 0 @@ -716,8 +715,8 @@ module internal List = j <- j + 1 if not t.IsEmpty then invalidArgDifferentListLength "list.[0]" (System.String.Format("list.[{0}]", j)) t.Length - [],[],0 - | h::t -> + [], [], 0 + | h :: t -> let headsCons = freshConsNoTail h let tailsCons = freshConsNoTail t let headCount = transposeGetHeadsFreshConsTail headsCons tailsCons tail 1 @@ -729,9 +728,9 @@ module internal List = | [] -> setFreshConsTail cons [] | _ -> match transposeGetHeads list with - | [],_,_ -> + | [], _, _ -> setFreshConsTail cons [] - | heads,tails,headCount -> + | heads, tails, headCount -> if headCount < expectedCount then invalidArgDifferentListLength (System.String.Format("list.[{0}]", headCount)) "list.[0]" <| tails.[0].Length + 1 let cons2 = freshConsNoTail heads @@ -754,19 +753,19 @@ module internal List = if count = 0 then setFreshConsTail cons [] else match list with | [] -> setFreshConsTail cons [] - | h::t -> + | h :: t -> let cons2 = freshConsNoTail h setFreshConsTail cons cons2 truncateToFreshConsTail cons2 (count-1) t let truncate count list = - if count <= 0 then + if count <= 0 then [] else match list with | [] | [_] -> list - | h::t -> + | h :: t -> let cons = freshConsNoTail h truncateToFreshConsTail cons (count-1) t cons @@ -774,7 +773,7 @@ module internal List = let rec unfoldToFreshConsTail cons f s = match f s with | None -> setFreshConsTail cons [] - | Some (x,s') -> + | Some (x, s') -> let cons2 = freshConsNoTail x setFreshConsTail cons cons2 unfoldToFreshConsTail cons2 f s' @@ -782,19 +781,19 @@ module internal List = let unfold (f:'State -> ('T * 'State) option) (s:'State) = match f s with | None -> [] - | Some (x,s') -> + | Some (x, s') -> let cons = freshConsNoTail x unfoldToFreshConsTail cons f s' cons // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec unzipToFreshConsTail cons1a cons1b x = - match x with - | [] -> + let rec unzipToFreshConsTail cons1a cons1b x = + match x with + | [] -> setFreshConsTail cons1a [] setFreshConsTail cons1b [] - | (h1,h2)::t -> + | (h1, h2) :: t -> let cons2a = freshConsNoTail h1 let cons2b = freshConsNoTail h2 setFreshConsTail cons1a cons2a @@ -803,25 +802,25 @@ module internal List = // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let unzip x = - match x with - | [] -> - [],[] - | (h1,h2)::t -> + let unzip x = + match x with + | [] -> + [], [] + | (h1, h2) :: t -> let res1a = freshConsNoTail h1 let res1b = freshConsNoTail h2 unzipToFreshConsTail res1a res1b t - res1a,res1b + res1a, res1b // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec unzip3ToFreshConsTail cons1a cons1b cons1c x = - match x with - | [] -> + let rec unzip3ToFreshConsTail cons1a cons1b cons1c x = + match x with + | [] -> setFreshConsTail cons1a [] setFreshConsTail cons1b [] setFreshConsTail cons1c [] - | (h1,h2,h3)::t -> + | (h1, h2, h3) :: t -> let cons2a = freshConsNoTail h1 let cons2b = freshConsNoTail h2 let cons2c = freshConsNoTail h3 @@ -832,16 +831,16 @@ module internal List = // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let unzip3 x = - match x with - | [] -> - [],[],[] - | (h1,h2,h3)::t -> + let unzip3 x = + match x with + | [] -> + [], [], [] + | (h1, h2, h3) :: t -> let res1a = freshConsNoTail h1 let res1b = freshConsNoTail h2 - let res1c = freshConsNoTail h3 + let res1c = freshConsNoTail h3 unzip3ToFreshConsTail res1a res1b res1c t - res1a,res1b,res1c + res1a, res1b, res1c let rec windowedToFreshConsTail cons windowSize i list = if i = 0 then @@ -866,7 +865,7 @@ module internal List = | [] -> setFreshConsTail chunkCons [] setFreshConsTail resCons [] - | h::t -> + | h :: t -> let cons = freshConsNoTail h if i = chunkSize then setFreshConsTail chunkCons [] @@ -881,7 +880,7 @@ module internal List = if chunkSize <= 0 then invalidArgInputMustBePositive "chunkSize" chunkSize match list with | [] -> [] - | head::tail -> + | head :: tail -> let chunkCons = freshConsNoTail head let res = freshConsNoTail chunkCons chunkBySizeToFreshConsTail chunkCons res chunkSize 1 tail @@ -892,7 +891,7 @@ module internal List = | [] -> setFreshConsTail chunkCons [] setFreshConsTail resCons [] - | h::t -> + | h :: t -> let cons = freshConsNoTail h if (i < lenModCount && j = lenDivCount + 1) || (i >= lenModCount && j = lenDivCount) then setFreshConsTail chunkCons [] @@ -916,59 +915,59 @@ module internal List = // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec zipToFreshConsTail cons xs1 xs2 = - match xs1,xs2 with - | [],[] -> + let rec zipToFreshConsTail cons xs1 xs2 = + match xs1, xs2 with + | [], [] -> setFreshConsTail cons [] - | h1::t1, h2::t2 -> - let cons2 = freshConsNoTail (h1,h2) + | h1 :: t1, h2 :: t2 -> + let cons2 = freshConsNoTail (h1, h2) setFreshConsTail cons cons2 zipToFreshConsTail cons2 t1 t2 - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let zip xs1 xs2 = - match xs1,xs2 with - | [],[] -> [] - | h1::t1, h2::t2 -> - let res = freshConsNoTail (h1,h2) + let zip xs1 xs2 = + match xs1, xs2 with + | [], [] -> [] + | h1 :: t1, h2 :: t2 -> + let res = freshConsNoTail (h1, h2) zipToFreshConsTail res t1 t2 res - | [],xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length - | xs1,[] -> invalidArgDifferentListLength "list2" "list1" xs1.Length + | [], xs2 -> invalidArgDifferentListLength "list1" "list2" xs2.Length + | xs1, [] -> invalidArgDifferentListLength "list2" "list1" xs1.Length // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let rec zip3ToFreshConsTail cons xs1 xs2 xs3 = - match xs1,xs2,xs3 with - | [],[],[] -> + let rec zip3ToFreshConsTail cons xs1 xs2 xs3 = + match xs1, xs2, xs3 with + | [], [], [] -> setFreshConsTail cons [] - | h1::t1, h2::t2, h3::t3 -> - let cons2 = freshConsNoTail (h1,h2,h3) + | h1 :: t1, h2 :: t2, h3 :: t3 -> + let cons2 = freshConsNoTail (h1, h2, h3) setFreshConsTail cons cons2 zip3ToFreshConsTail cons2 t1 t2 t3 - | xs1,xs2,xs3 -> - invalidArg3ListsDifferent "list1" "list2" "list3" xs1.Length xs2.Length xs3.Length + | xs1, xs2, xs3 -> + invalidArg3ListsDifferent "list1" "list2" "list3" xs1.Length xs2.Length xs3.Length // optimized mutation-based implementation. This code is only valid in fslib, where mutation of private // tail cons cells is permitted in carefully written library code. - let zip3 xs1 xs2 xs3 = - match xs1,xs2,xs3 with - | [],[],[] -> + let zip3 xs1 xs2 xs3 = + match xs1, xs2, xs3 with + | [], [], [] -> [] - | h1::t1, h2::t2, h3::t3 -> - let res = freshConsNoTail (h1,h2,h3) + | h1 :: t1, h2 :: t2, h3 :: t3 -> + let res = freshConsNoTail (h1, h2, h3) zip3ToFreshConsTail res t1 t2 t3 res - | xs1,xs2,xs3 -> - invalidArg3ListsDifferent "list1" "list2" "list3" xs1.Length xs2.Length xs3.Length + | xs1, xs2, xs3 -> + invalidArg3ListsDifferent "list1" "list2" "list3" xs1.Length xs2.Length xs3.Length let rec takeWhileFreshConsTail cons p l = match l with | [] -> setFreshConsTail cons [] - | x::xs -> + | x :: xs -> if p x then let cons2 = freshConsNoTail x setFreshConsTail cons cons2 @@ -980,13 +979,13 @@ module internal List = match l with | [] -> l | x :: ([] as nil) -> if p x then l else nil - | x::xs -> + | x :: xs -> if not (p x) then [] else let cons = freshConsNoTail x takeWhileFreshConsTail cons p xs cons -module internal Array = +module internal Array = open System @@ -994,13 +993,13 @@ module internal Array = LanguagePrimitives.FastGenericComparerCanBeNull<'t> // The input parameter should be checked by callers if necessary - let inline zeroCreateUnchecked (count:int) = + let inline zeroCreateUnchecked (count:int) = (# "newarr !0" type ('T) count : 'T array #) - let inline init (count:int) (f: int -> 'T) = + let inline init (count:int) (f: int -> 'T) = if count < 0 then invalidArgInputMustBeNonNegative "count" count - let arr = (zeroCreateUnchecked count : 'T array) - for i = 0 to arr.Length-1 do + let arr = (zeroCreateUnchecked count : 'T array) + for i = 0 to arr.Length-1 do arr.[i] <- f i arr @@ -1034,15 +1033,15 @@ module internal Array = else loop (i - 1) loop (array.Length - 1) - let permute indexMap (arr : _[]) = + let permute indexMap (arr : _[]) = let res = zeroCreateUnchecked arr.Length let inv = zeroCreateUnchecked arr.Length - for i = 0 to arr.Length - 1 do - let j = indexMap i + for i = 0 to arr.Length - 1 do + let j = indexMap i if j < 0 || j >= arr.Length then invalidArg "indexMap" (SR.GetString(SR.notAPermutation)) res.[j] <- arr.[i] inv.[j] <- 1uy - for i = 0 to arr.Length - 1 do + for i = 0 to arr.Length - 1 do if inv.[i] <> 1uy then invalidArg "indexMap" (SR.GetString(SR.notAPermutation)) res @@ -1050,11 +1049,11 @@ module internal Array = match array.Length with | 0 -> [| |], acc | len -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) let mutable acc = acc let res = zeroCreateUnchecked len for i = 0 to array.Length-1 do - let h',s' = f.Invoke(acc,array.[i]) + let h', s' = f.Invoke(acc, array.[i]) res.[i] <- h' acc <- s' res, acc @@ -1063,17 +1062,17 @@ module internal Array = match array.Length with | 0 -> [| |], acc | len -> - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) let mutable acc = acc let res = zeroCreateUnchecked len for i = len - 1 downto 0 do - let h',s' = f.Invoke(array.[i],acc) + let h', s' = f.Invoke(array.[i], acc) res.[i] <- h' acc <- s' res, acc let scanSubRight f (array : _[]) start fin initState = - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) let mutable state = initState let res = zeroCreateUnchecked (fin-start+2) res.[fin - start + 1] <- state @@ -1083,25 +1082,25 @@ module internal Array = res let unstableSortInPlaceBy (projection: 'T -> 'U) (array : array<'T>) = - let len = array.Length - if len < 2 then () + let len = array.Length + if len < 2 then () else let keys = zeroCreateUnchecked array.Length - for i = 0 to array.Length - 1 do + for i = 0 to array.Length - 1 do keys.[i] <- projection array.[i] - Array.Sort<_,_>(keys, array, fastComparerForArraySort()) + Array.Sort<_, _>(keys, array, fastComparerForArraySort()) - let unstableSortInPlace (array : array<'T>) = - let len = array.Length - if len < 2 then () + let unstableSortInPlace (array : array<'T>) = + let len = array.Length + if len < 2 then () else Array.Sort<_>(array, fastComparerForArraySort()) let stableSortWithKeysAndComparer (cFast:IComparer<'Key>) (c:IComparer<'Key>) (array:array<'T>) (keys:array<'Key>) = // 'places' is an array or integers storing the permutation performed by the sort - let places = zeroCreateUnchecked array.Length - for i = 0 to array.Length - 1 do - places.[i] <- i - System.Array.Sort<_,_>(keys, places, cFast) + let places = zeroCreateUnchecked array.Length + for i = 0 to array.Length - 1 do + places.[i] <- i + System.Array.Sort<_, _>(keys, places, cFast) // 'array2' is a copy of the original values let array2 = (array.Clone() :?> array<'T>) @@ -1109,17 +1108,17 @@ module internal Array = let mutable i = 0 let len = array.Length let intCompare = fastComparerForArraySort() - - while i < len do + + while i < len do let mutable j = i let ki = keys.[i] - while j < len && (j = i || c.Compare(ki, keys.[j]) = 0) do + while j < len && (j = i || c.Compare(ki, keys.[j]) = 0) do j <- j + 1 // Copy the values into the result array and re-sort the chunk if needed by the original place indexes for n = i to j - 1 do array.[n] <- array2.[places.[n]] if j - i >= 2 then - Array.Sort<_,_>(places, array, i, j-i, intCompare) + Array.Sort<_, _>(places, array, i, j-i, intCompare) i <- j let stableSortWithKeys (array:array<'T>) (keys:array<'Key>) = @@ -1128,26 +1127,26 @@ module internal Array = stableSortWithKeysAndComparer cFast c array keys let stableSortInPlaceBy (projection: 'T -> 'U) (array : array<'T>) = - let len = array.Length - if len < 2 then () + let len = array.Length + if len < 2 then () else // 'keys' is an array storing the projected keys let keys = zeroCreateUnchecked array.Length - for i = 0 to array.Length - 1 do + for i = 0 to array.Length - 1 do keys.[i] <- projection array.[i] stableSortWithKeys array keys let stableSortInPlace (array : array<'T>) = - let len = array.Length - if len < 2 then () + let len = array.Length + if len < 2 then () else let cFast = LanguagePrimitives.FastGenericComparerCanBeNull<'T> - match cFast with - | null -> + match cFast with + | null -> // An optimization for the cases where the keys and values coincide and do not have identity, e.g. are integers // In this case an unstable sort is just as good as a stable sort (and faster) - Array.Sort<_,_>(array, null) - | _ -> + Array.Sort<_, _>(array, null) + | _ -> // 'keys' is an array storing the projected keys let keys = (array.Clone() :?> array<'T>) stableSortWithKeys array keys @@ -1156,8 +1155,8 @@ module internal Array = let len = array.Length if len > 1 then let keys = (array.Clone() :?> array<'T>) - let comparer = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(comparer) - let c = { new IComparer<'T> with member __.Compare(x,y) = comparer.Invoke(x,y) } + let comparer = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(comparer) + let c = { new IComparer<'T> with member __.Compare(x, y) = comparer.Invoke(x, y) } stableSortWithKeysAndComparer c c array keys let inline subUnchecked startIndex count (array : 'T[]) = diff --git a/src/fsharp/FSharp.Core/map.fs b/src/fsharp/FSharp.Core/map.fs index 9b2fbc9d832..93504de7f7c 100644 --- a/src/fsharp/FSharp.Core/map.fs +++ b/src/fsharp/FSharp.Core/map.fs @@ -2,754 +2,832 @@ namespace Microsoft.FSharp.Collections - open System - open System.Collections.Generic - open System.Diagnostics - open Microsoft.FSharp.Core - open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators +open System +open System.Collections.Generic +open System.Diagnostics +open System.Text +open Microsoft.FSharp.Core +open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators + +[] +[] +type MapTree<'Key, 'Value when 'Key : comparison > = + | MapEmpty + | MapOne of 'Key * 'Value + | MapNode of 'Key * 'Value * MapTree<'Key, 'Value> * MapTree<'Key, 'Value> * int + +[] +module MapTree = + + let rec sizeAux acc m = + match m with + | MapEmpty -> acc + | MapOne _ -> acc + 1 + | MapNode (_, _, l, r, _) -> sizeAux (sizeAux (acc+1) l) r + + let size x = sizeAux 0 x - [] - [] - type MapTree<'Key,'Value when 'Key : comparison > = - | MapEmpty - | MapOne of 'Key * 'Value - | MapNode of 'Key * 'Value * MapTree<'Key,'Value> * MapTree<'Key,'Value> * int - // REVIEW: performance rumour has it that the data held in MapNode and MapOne should be - // exactly one cache line. It is currently ~7 and 4 words respectively. - - [] - module MapTree = - - let rec sizeAux acc m = - match m with - | MapEmpty -> acc - | MapOne _ -> acc + 1 - | MapNode(_,_,l,r,_) -> sizeAux (sizeAux (acc+1) l) r - - let size x = sizeAux 0 x - - - #if TRACE_SETS_AND_MAPS - let mutable traceCount = 0 - let mutable numOnes = 0 - let mutable numNodes = 0 - let mutable numAdds = 0 - let mutable numRemoves = 0 - let mutable numLookups = 0 - let mutable numUnions = 0 - let mutable totalSizeOnNodeCreation = 0.0 - let mutable totalSizeOnMapAdd = 0.0 - let mutable totalSizeOnMapLookup = 0.0 - let mutable largestMapSize = 0 - let mutable largestMapStackTrace = Unchecked.defaultof<_> - let report() = - traceCount <- traceCount + 1 - if traceCount % 1000000 = 0 then - System.Console.WriteLine("#MapOne = {0}, #MapNode = {1}, #Add = {2}, #Remove = {3}, #Unions = {4}, #Lookups = {5}, avMapTreeSizeOnNodeCreation = {6}, avMapSizeOnCreation = {7}, avMapSizeOnLookup = {8}",numOnes,numNodes,numAdds,numRemoves,numUnions,numLookups,(totalSizeOnNodeCreation / float (numNodes + numOnes)),(totalSizeOnMapAdd / float numAdds),(totalSizeOnMapLookup / float numLookups)) - System.Console.WriteLine("#largestMapSize = {0}, largestMapStackTrace = {1}",largestMapSize, largestMapStackTrace) - - let MapOne n = - report(); - numOnes <- numOnes + 1; - totalSizeOnNodeCreation <- totalSizeOnNodeCreation + 1.0; - MapTree.MapOne n - - let MapNode (x,l,v,r,h) = - report(); - numNodes <- numNodes + 1; - let n = MapTree.MapNode(x,l,v,r,h) - totalSizeOnNodeCreation <- totalSizeOnNodeCreation + float (size n); - n - #endif - - let empty = MapEmpty - - let height (m: MapTree<'Key, 'Value>) = - match m with - | MapEmpty -> 0 - | MapOne _ -> 1 - | MapNode(_,_,_,_,h) -> h - - let isEmpty (m: MapTree<'Key, 'Value>) = - match m with - | MapEmpty -> true - | _ -> false +#if TRACE_SETS_AND_MAPS + let mutable traceCount = 0 + let mutable numOnes = 0 + let mutable numNodes = 0 + let mutable numAdds = 0 + let mutable numRemoves = 0 + let mutable numLookups = 0 + let mutable numUnions = 0 + let mutable totalSizeOnNodeCreation = 0.0 + let mutable totalSizeOnMapAdd = 0.0 + let mutable totalSizeOnMapLookup = 0.0 + let mutable largestMapSize = 0 + let mutable largestMapStackTrace = Unchecked.defaultof<_> + + let report() = + traceCount <- traceCount + 1 + if traceCount % 1000000 = 0 then + System.Console.WriteLine( + "#MapOne = {0}, #MapNode = {1}, #Add = {2}, #Remove = {3}, #Unions = {4}, #Lookups = {5}, avMapTreeSizeOnNodeCreation = {6}, avMapSizeOnCreation = {7}, avMapSizeOnLookup = {8}", + numOnes, numNodes, numAdds, numRemoves, numUnions, numLookups, + (totalSizeOnNodeCreation / float (numNodes + numOnes)), (totalSizeOnMapAdd / float numAdds), + (totalSizeOnMapLookup / float numLookups)) + System.Console.WriteLine("#largestMapSize = {0}, largestMapStackTrace = {1}", largestMapSize, largestMapStackTrace) + + let MapOne n = + report() + numOnes <- numOnes + 1 + totalSizeOnNodeCreation <- totalSizeOnNodeCreation + 1.0 + MapTree.MapOne n + + let MapNode (x, l, v, r, h) = + report() + numNodes <- numNodes + 1 + let n = MapTree.MapNode (x, l, v, r, h) + totalSizeOnNodeCreation <- totalSizeOnNodeCreation + float (size n) + n +#endif - let mk l k v r : MapTree<'Key, 'Value> = - match l,r with - | MapEmpty,MapEmpty -> MapOne(k,v) - | _ -> - let hl = height l - let hr = height r - let m = if hl < hr then hr else hl - MapNode(k,v,l,r,m+1) - - let rebalance t1 (k: 'Key) (v: 'Value) t2 = - let t1h = height t1 - let t2h = height t2 - if t2h > t1h + 2 then (* right is heavier than left *) - match t2 with - | MapNode(t2k,t2v,t2l,t2r,_) -> - (* one of the nodes must have height > height t1 + 1 *) - if height t2l > t1h + 1 then (* balance left: combination *) - match t2l with - | MapNode(t2lk,t2lv,t2ll,t2lr,_) -> - mk (mk t1 k v t2ll) t2lk t2lv (mk t2lr t2k t2v t2r) - | _ -> failwith "rebalance" - else (* rotate left *) - mk (mk t1 k v t2l) t2k t2v t2r - | _ -> failwith "rebalance" - else - if t1h > t2h + 2 then (* left is heavier than right *) - match t1 with - | MapNode(t1k,t1v,t1l,t1r,_) -> - (* one of the nodes must have height > height t2 + 1 *) - if height t1r > t2h + 1 then - (* balance right: combination *) + let empty = MapEmpty + + let height (m: MapTree<'Key, 'Value>) = + match m with + | MapEmpty -> 0 + | MapOne _ -> 1 + | MapNode (_, _, _, _, h) -> h + + let isEmpty (m: MapTree<'Key, 'Value>) = + match m with + | MapEmpty -> true + | _ -> false + + let mk l k v r : MapTree<'Key, 'Value> = + match l, r with + | MapEmpty, MapEmpty -> MapOne (k, v) + | _ -> + let hl = height l + let hr = height r + let m = if hl < hr then hr else hl + MapNode (k, v, l, r, m+1) + + let rebalance t1 (k: 'Key) (v: 'Value) t2 = + let t1h = height t1 + let t2h = height t2 + if t2h > t1h + 2 then (* right is heavier than left *) + match t2 with + | MapNode (t2k, t2v, t2l, t2r, _) -> + // one of the nodes must have height > height t1 + 1 + if height t2l > t1h + 1 then + // balance left: combination + match t2l with + | MapNode (t2lk, t2lv, t2ll, t2lr, _) -> + mk (mk t1 k v t2ll) t2lk t2lv (mk t2lr t2k t2v t2r) + | _ -> failwith "rebalance" + else + // rotate left + mk (mk t1 k v t2l) t2k t2v t2r + | _ -> failwith "rebalance" + else + if t1h > t2h + 2 then (* left is heavier than right *) + match t1 with + | MapNode (t1k, t1v, t1l, t1r, _) -> + // one of the nodes must have height > height t2 + 1 + if height t1r > t2h + 1 then + // balance right: combination match t1r with - | MapNode(t1rk,t1rv,t1rl,t1rr,_) -> + | MapNode (t1rk, t1rv, t1rl, t1rr, _) -> mk (mk t1l t1k t1v t1rl) t1rk t1rv (mk t1rr k v t2) | _ -> failwith "rebalance" - else + else mk t1l t1k t1v (mk t1r k v t2) - | _ -> failwith "rebalance" - else mk t1 k v t2 - - let rec add (comparer: IComparer<'Key>) k (v: 'Value) (m: MapTree<'Key, 'Value>) = + | _ -> failwith "rebalance" + else mk t1 k v t2 + + let rec add (comparer: IComparer<'Key>) k (v: 'Value) (m: MapTree<'Key, 'Value>) = + match m with + | MapEmpty -> MapOne (k, v) + | MapOne (k2, _) -> + let c = comparer.Compare(k, k2) + if c < 0 then MapNode (k, v, MapEmpty, m, 2) + elif c = 0 then MapOne (k, v) + else MapNode (k, v, m, MapEmpty, 2) + | MapNode (k2, v2, l, r, h) -> + let c = comparer.Compare(k, k2) + if c < 0 then rebalance (add comparer k v l) k2 v2 r + elif c = 0 then MapNode (k, v, l, r, h) + else rebalance l k2 v2 (add comparer k v r) + + let rec tryGetValue (comparer: IComparer<'Key>) k (v: byref<'Value>) (m: MapTree<'Key, 'Value>) = + match m with + | MapEmpty -> false + | MapOne (k2, v2) -> + let c = comparer.Compare(k, k2) + if c = 0 then v <- v2; true + else false + | MapNode (k2, v2, l, r, _) -> + let c = comparer.Compare(k, k2) + if c < 0 then tryGetValue comparer k &v l + elif c = 0 then v <- v2; true + else tryGetValue comparer k &v r + + let find (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) = + let mutable v = Unchecked.defaultof<'Value> + if tryGetValue comparer k &v m then + v + else + raise (KeyNotFoundException()) + + let tryFind (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) = + let mutable v = Unchecked.defaultof<'Value> + if tryGetValue comparer k &v m then + Some v + else + None + + let partition1 (comparer: IComparer<'Key>) (f: OptimizedClosures.FSharpFunc<_, _, _>) k v (acc1, acc2) = + if f.Invoke (k, v) then (add comparer k v acc1, acc2) else (acc1, add comparer k v acc2) + + let rec partitionAux (comparer: IComparer<'Key>) (f: OptimizedClosures.FSharpFunc<_, _, _>) m acc = + match m with + | MapEmpty -> acc + | MapOne (k, v) -> partition1 comparer f k v acc + | MapNode (k, v, l, r, _) -> + let acc = partitionAux comparer f r acc + let acc = partition1 comparer f k v acc + partitionAux comparer f l acc + + let partition (comparer: IComparer<'Key>) f m = + partitionAux comparer (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) m (empty, empty) + + let filter1 (comparer: IComparer<'Key>) (f: OptimizedClosures.FSharpFunc<_, _, _>) k v acc = + if f.Invoke (k, v) then add comparer k v acc else acc + + let rec filterAux (comparer: IComparer<'Key>) (f: OptimizedClosures.FSharpFunc<_, _, _>) m acc = + match m with + | MapEmpty -> acc + | MapOne (k, v) -> filter1 comparer f k v acc + | MapNode (k, v, l, r, _) -> + let acc = filterAux comparer f l acc + let acc = filter1 comparer f k v acc + filterAux comparer f r acc + + let filter (comparer: IComparer<'Key>) f m = + filterAux comparer (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) m empty + + let rec spliceOutSuccessor (m: MapTree<'Key, 'Value>) = + match m with + | MapEmpty -> failwith "internal error: Map.spliceOutSuccessor" + | MapOne (k2, v2) -> k2, v2, MapEmpty + | MapNode (k2, v2, l, r, _) -> + match l with + | MapEmpty -> k2, v2, r + | _ -> let k3, v3, l' = spliceOutSuccessor l in k3, v3, mk l' k2 v2 r + + let rec remove (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) = + match m with + | MapEmpty -> empty + | MapOne (k2, _) -> + let c = comparer.Compare(k, k2) + if c = 0 then MapEmpty else m + | MapNode (k2, v2, l, r, _) -> + let c = comparer.Compare(k, k2) + if c < 0 then rebalance (remove comparer k l) k2 v2 r + elif c = 0 then + match l, r with + | MapEmpty, _ -> r + | _, MapEmpty -> l + | _ -> + let sk, sv, r' = spliceOutSuccessor r + mk l sk sv r' + else rebalance l k2 v2 (remove comparer k r) + + let rec mem (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) = + match m with + | MapEmpty -> false + | MapOne (k2, _) -> (comparer.Compare(k, k2) = 0) + | MapNode (k2, _, l, r, _) -> + let c = comparer.Compare(k, k2) + if c < 0 then mem comparer k l + else (c = 0 || mem comparer k r) + + let rec iterOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) (m: MapTree<'Key, 'Value>) = + match m with + | MapEmpty -> () + | MapOne (k2, v2) -> f.Invoke (k2, v2) + | MapNode (k2, v2, l, r, _) -> iterOpt f l; f.Invoke (k2, v2); iterOpt f r + + let iter f m = + iterOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) m + + let rec tryPickOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) m = + match m with + | MapEmpty -> None + | MapOne (k2, v2) -> f.Invoke (k2, v2) + | MapNode (k2, v2, l, r, _) -> + match tryPickOpt f l with + | Some _ as res -> res + | None -> + match f.Invoke (k2, v2) with + | Some _ as res -> res + | None -> + tryPickOpt f r + + let tryPick f m = + tryPickOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) m + + let rec existsOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) m = + match m with + | MapEmpty -> false + | MapOne (k2, v2) -> f.Invoke (k2, v2) + | MapNode (k2, v2, l, r, _) -> existsOpt f l || f.Invoke (k2, v2) || existsOpt f r + + let exists f m = + existsOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) m + + let rec forallOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) m = + match m with + | MapEmpty -> true + | MapOne (k2, v2) -> f.Invoke (k2, v2) + | MapNode (k2, v2, l, r, _) -> forallOpt f l && f.Invoke (k2, v2) && forallOpt f r + + let forall f m = + forallOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) m + + let rec map f m = + match m with + | MapEmpty -> empty + | MapOne (k, v) -> MapOne (k, f v) + | MapNode (k, v, l, r, h) -> + let l2 = map f l + let v2 = f v + let r2 = map f r + MapNode (k, v2, l2, r2, h) + + let rec mapiOpt (f: OptimizedClosures.FSharpFunc<_, _, _>) m = + match m with + | MapEmpty -> empty + | MapOne (k, v) -> MapOne (k, f.Invoke (k, v)) + | MapNode (k, v, l, r, h) -> + let l2 = mapiOpt f l + let v2 = f.Invoke (k, v) + let r2 = mapiOpt f r + MapNode (k, v2, l2, r2, h) + + let mapi f m = + mapiOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) m + + let rec foldBackOpt (f: OptimizedClosures.FSharpFunc<_, _, _, _>) m x = + match m with + | MapEmpty -> x + | MapOne (k, v) -> f.Invoke (k, v, x) + | MapNode (k, v, l, r, _) -> + let x = foldBackOpt f r x + let x = f.Invoke (k, v, x) + foldBackOpt f l x + + let foldBack f m x = + foldBackOpt (OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(f)) m x + + let rec foldOpt (f: OptimizedClosures.FSharpFunc<_, _, _, _>) x m = + match m with + | MapEmpty -> x + | MapOne (k, v) -> f.Invoke (x, k, v) + | MapNode (k, v, l, r, _) -> + let x = foldOpt f x l + let x = f.Invoke (x, k, v) + foldOpt f x r + + let fold f x m = + foldOpt (OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(f)) x m + + let foldSectionOpt (comparer: IComparer<'Key>) lo hi (f: OptimizedClosures.FSharpFunc<_, _, _, _>) m x = + let rec foldFromTo (f: OptimizedClosures.FSharpFunc<_, _, _, _>) m x = match m with - | MapEmpty -> MapOne(k,v) - | MapOne(k2,_) -> - let c = comparer.Compare(k,k2) - if c < 0 then MapNode (k,v,MapEmpty,m,2) - elif c = 0 then MapOne(k,v) - else MapNode (k,v,m,MapEmpty,2) - | MapNode(k2,v2,l,r,h) -> - let c = comparer.Compare(k,k2) - if c < 0 then rebalance (add comparer k v l) k2 v2 r - elif c = 0 then MapNode(k,v,l,r,h) - else rebalance l k2 v2 (add comparer k v r) - - let rec tryGetValue (comparer: IComparer<'Key>) k (v: byref<'Value>) (m: MapTree<'Key, 'Value>) = + | MapEmpty -> x + | MapOne (k, v) -> + let cLoKey = comparer.Compare(lo, k) + let cKeyHi = comparer.Compare(k, hi) + let x = if cLoKey <= 0 && cKeyHi <= 0 then f.Invoke (k, v, x) else x + x + | MapNode (k, v, l, r, _) -> + let cLoKey = comparer.Compare(lo, k) + let cKeyHi = comparer.Compare(k, hi) + let x = if cLoKey < 0 then foldFromTo f l x else x + let x = if cLoKey <= 0 && cKeyHi <= 0 then f.Invoke (k, v, x) else x + let x = if cKeyHi < 0 then foldFromTo f r x else x + x + + if comparer.Compare(lo, hi) = 1 then x else foldFromTo f m x + + let foldSection (comparer: IComparer<'Key>) lo hi f m x = + foldSectionOpt comparer lo hi (OptimizedClosures.FSharpFunc<_, _, _, _>.Adapt(f)) m x + + let toList m = + let rec loop m acc = match m with - | MapEmpty -> false - | MapOne(k2,v2) -> - let c = comparer.Compare(k,k2) - if c = 0 then v <- v2; true - else false - | MapNode(k2,v2,l,r,_) -> - let c = comparer.Compare(k,k2) - if c < 0 then tryGetValue comparer k &v l - elif c = 0 then v <- v2; true - else tryGetValue comparer k &v r - - let find (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) = - let mutable v = Unchecked.defaultof<'Value> - if tryGetValue comparer k &v m then - v - else - raise (KeyNotFoundException()) - - let tryFind (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) = - let mutable v = Unchecked.defaultof<'Value> - if tryGetValue comparer k &v m then - Some v - else - None - - let partition1 (comparer: IComparer<'Key>) (f:OptimizedClosures.FSharpFunc<_,_,_>) k v (acc1,acc2) = - if f.Invoke(k, v) then (add comparer k v acc1,acc2) else (acc1,add comparer k v acc2) - - let rec partitionAux (comparer: IComparer<'Key>) (f:OptimizedClosures.FSharpFunc<_,_,_>) s acc = - match s with | MapEmpty -> acc - | MapOne(k,v) -> partition1 comparer f k v acc - | MapNode(k,v,l,r,_) -> - let acc = partitionAux comparer f r acc - let acc = partition1 comparer f k v acc - partitionAux comparer f l acc + | MapOne (k, v) -> (k, v):: acc + | MapNode (k, v, l, r, _) -> loop l ((k, v):: loop r acc) + loop m [] + + let toArray m = + m |> toList |> Array.ofList + + let ofList comparer l = + List.fold (fun acc (k, v) -> add comparer k v acc) empty l + + let rec mkFromEnumerator comparer acc (e : IEnumerator<_>) = + if e.MoveNext() then + let (x, y) = e.Current + mkFromEnumerator comparer (add comparer x y acc) e + else acc + + let ofArray comparer (arr : array<_>) = + let mutable res = empty + for (x, y) in arr do + res <- add comparer x y res + res + + let ofSeq comparer (c : seq<'Key * 'T>) = + match c with + | :? array<'Key * 'T> as xs -> ofArray comparer xs + | :? list<'Key * 'T> as xs -> ofList comparer xs + | _ -> + use ie = c.GetEnumerator() + mkFromEnumerator comparer empty ie + + let copyToArray m (arr: _[]) i = + let j = ref i + m |> iter (fun x y -> arr.[!j] <- KeyValuePair(x, y); j := !j + 1) + + /// Imperative left-to-right iterators. + [] + type MapIterator<'Key, 'Value when 'Key : comparison > = + { /// invariant: always collapseLHS result + mutable stack: MapTree<'Key, 'Value> list + + /// true when MoveNext has been called + mutable started : bool } + + // collapseLHS: + // a) Always returns either [] or a list starting with MapOne. + // b) The "fringe" of the set stack is unchanged. + let rec collapseLHS stack = + match stack with + | [] -> [] + | MapEmpty :: rest -> collapseLHS rest + | MapOne _ :: _ -> stack + | (MapNode (k, v, l, r, _)) :: rest -> collapseLHS (l :: MapOne (k, v) :: r :: rest) + + let mkIterator m = + { stack = collapseLHS [m]; started = false } + + let notStarted() = + raise (InvalidOperationException(SR.GetString(SR.enumerationNotStarted))) + + let alreadyFinished() = + raise (InvalidOperationException(SR.GetString(SR.enumerationAlreadyFinished))) + + let current i = + if i.started then + match i.stack with + | MapOne (k, v) :: _ -> new KeyValuePair<_, _>(k, v) + | [] -> alreadyFinished() + | _ -> failwith "Please report error: Map iterator, unexpected stack for current" + else + notStarted() + + let rec moveNext i = + if i.started then + match i.stack with + | MapOne _ :: rest -> + i.stack <- collapseLHS rest + not i.stack.IsEmpty + | [] -> false + | _ -> failwith "Please report error: Map iterator, unexpected stack for moveNext" + else + i.started <- true (* The first call to MoveNext "starts" the enumeration. *) + not i.stack.IsEmpty + + let mkIEnumerator m = + let mutable i = mkIterator m + { new IEnumerator<_> with + member __.Current = current i + + interface System.Collections.IEnumerator with + member __.Current = box (current i) + member __.MoveNext() = moveNext i + member __.Reset() = i <- mkIterator m + + interface System.IDisposable with + member __.Dispose() = ()} + +[>)>] +[] +[] +[] +[] +type Map<[]'Key, []'Value when 'Key : comparison >(comparer: IComparer<'Key>, tree: MapTree<'Key, 'Value>) = - let partition (comparer: IComparer<'Key>) f s = partitionAux comparer (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) s (empty,empty) +#if !FX_NO_BINARY_SERIALIZATION + [] + // This type is logically immutable. This field is only mutated during deserialization. + let mutable comparer = comparer + + [] + // This type is logically immutable. This field is only mutated during deserialization. + let mutable tree = tree + + // This type is logically immutable. This field is only mutated during serialization and deserialization. + // + // WARNING: The compiled name of this field may never be changed because it is part of the logical + // WARNING: permanent serialization format for this type. + let mutable serializedData = null +#endif - let filter1 (comparer: IComparer<'Key>) (f:OptimizedClosures.FSharpFunc<_,_,_>) k v acc = if f.Invoke(k, v) then add comparer k v acc else acc + // We use .NET generics per-instantiation static fields to avoid allocating a new object for each empty + // set (it is just a lookup into a .NET table of type-instantiation-indexed static fields). + static let empty = + let comparer = LanguagePrimitives.FastGenericComparer<'Key> + new Map<'Key, 'Value>(comparer, MapTree<_, _>.MapEmpty) - let rec filterAux (comparer: IComparer<'Key>) (f:OptimizedClosures.FSharpFunc<_,_,_>) s acc = - match s with - | MapEmpty -> acc - | MapOne(k,v) -> filter1 comparer f k v acc - | MapNode(k,v,l,r,_) -> - let acc = filterAux comparer f l acc - let acc = filter1 comparer f k v acc - filterAux comparer f r acc +#if !FX_NO_BINARY_SERIALIZATION + [] + member __.OnSerializing(context: System.Runtime.Serialization.StreamingContext) = + ignore(context) + serializedData <- MapTree.toArray tree |> Array.map (fun (k, v) -> KeyValuePair(k, v)) + + // Do not set this to null, since concurrent threads may also be serializing the data + //[] + //member __.OnSerialized(context: System.Runtime.Serialization.StreamingContext) = + // serializedData <- null + + [] + member __.OnDeserialized(context: System.Runtime.Serialization.StreamingContext) = + ignore(context) + comparer <- LanguagePrimitives.FastGenericComparer<'Key> + tree <- serializedData |> Array.map (fun (KeyValue(k, v)) -> (k, v)) |> MapTree.ofArray comparer + serializedData <- null +#endif - let filter (comparer: IComparer<'Key>) f s = filterAux comparer (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) s empty + static member Empty : Map<'Key, 'Value> = + empty - let rec spliceOutSuccessor (m: MapTree<'Key, 'Value>) = - match m with - | MapEmpty -> failwith "internal error: Map.spliceOutSuccessor" - | MapOne(k2,v2) -> k2,v2,MapEmpty - | MapNode(k2,v2,l,r,_) -> - match l with - | MapEmpty -> k2,v2,r - | _ -> let k3,v3,l' = spliceOutSuccessor l in k3,v3,mk l' k2 v2 r - - let rec remove (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) = - match m with - | MapEmpty -> empty - | MapOne(k2,_) -> - let c = comparer.Compare(k,k2) - if c = 0 then MapEmpty else m - | MapNode(k2,v2,l,r,_) -> - let c = comparer.Compare(k,k2) - if c < 0 then rebalance (remove comparer k l) k2 v2 r - elif c = 0 then - match l,r with - | MapEmpty,_ -> r - | _,MapEmpty -> l - | _ -> - let sk,sv,r' = spliceOutSuccessor r - mk l sk sv r' - else rebalance l k2 v2 (remove comparer k r) - - let rec mem (comparer: IComparer<'Key>) k (m: MapTree<'Key, 'Value>) = - match m with - | MapEmpty -> false - | MapOne(k2,_) -> (comparer.Compare(k,k2) = 0) - | MapNode(k2,_,l,r,_) -> - let c = comparer.Compare(k,k2) - if c < 0 then mem comparer k l - else (c = 0 || mem comparer k r) - - let rec iterOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) (m: MapTree<'Key, 'Value>) = - match m with - | MapEmpty -> () - | MapOne(k2,v2) -> f.Invoke(k2, v2) - | MapNode(k2,v2,l,r,_) -> iterOpt f l; f.Invoke(k2, v2); iterOpt f r + static member Create(ie : IEnumerable<_>) : Map<'Key, 'Value> = + let comparer = LanguagePrimitives.FastGenericComparer<'Key> + new Map<_, _>(comparer, MapTree.ofSeq comparer ie) - let iter f m = iterOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m + new (elements : seq<_>) = + let comparer = LanguagePrimitives.FastGenericComparer<'Key> + new Map<_, _>(comparer, MapTree.ofSeq comparer elements) - let rec tryPickOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m = - match m with - | MapEmpty -> None - | MapOne(k2,v2) -> f.Invoke(k2, v2) - | MapNode(k2,v2,l,r,_) -> - match tryPickOpt f l with - | Some _ as res -> res - | None -> - match f.Invoke(k2, v2) with - | Some _ as res -> res - | None -> - tryPickOpt f r - - let tryPick f m = tryPickOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m - - let rec existsOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m = - match m with - | MapEmpty -> false - | MapOne(k2,v2) -> f.Invoke(k2, v2) - | MapNode(k2,v2,l,r,_) -> existsOpt f l || f.Invoke(k2, v2) || existsOpt f r + [] + member internal m.Comparer = comparer - let exists f m = existsOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m + //[] + member internal m.Tree = tree - let rec forallOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m = - match m with - | MapEmpty -> true - | MapOne(k2,v2) -> f.Invoke(k2, v2) - | MapNode(k2,v2,l,r,_) -> forallOpt f l && f.Invoke(k2, v2) && forallOpt f r + member m.Add(key, value) : Map<'Key, 'Value> = +#if TRACE_SETS_AND_MAPS + MapTree.report() + MapTree.numAdds <- MapTree.numAdds + 1 + let size = MapTree.size m.Tree + 1 + MapTree.totalSizeOnMapAdd <- MapTree.totalSizeOnMapAdd + float size + if size > MapTree.largestMapSize then + MapTree.largestMapSize <- size + MapTree.largestMapStackTrace <- System.Diagnostics.StackTrace().ToString() +#endif + new Map<'Key, 'Value>(comparer, MapTree.add comparer key value tree) - let forall f m = forallOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m + [] + member m.IsEmpty = MapTree.isEmpty tree - let rec map f m = - match m with - | MapEmpty -> empty - | MapOne(k,v) -> MapOne(k,f v) - | MapNode(k,v,l,r,h) -> - let l2 = map f l - let v2 = f v - let r2 = map f r - MapNode(k,v2,l2, r2,h) - - let rec mapiOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m = - match m with - | MapEmpty -> empty - | MapOne(k,v) -> MapOne(k, f.Invoke(k, v)) - | MapNode(k,v,l,r,h) -> - let l2 = mapiOpt f l - let v2 = f.Invoke(k, v) - let r2 = mapiOpt f r - MapNode(k,v2, l2, r2,h) - - let mapi f m = mapiOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m - - let rec foldBackOpt (f:OptimizedClosures.FSharpFunc<_,_,_,_>) m x = - match m with - | MapEmpty -> x - | MapOne(k,v) -> f.Invoke(k,v,x) - | MapNode(k,v,l,r,_) -> - let x = foldBackOpt f r x - let x = f.Invoke(k,v,x) - foldBackOpt f l x + member m.Item + with get(key : 'Key) = +#if TRACE_SETS_AND_MAPS + MapTree.report() + MapTree.numLookups <- MapTree.numLookups + 1 + MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree) +#endif + MapTree.find comparer key tree - let foldBack f m x = foldBackOpt (OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)) m x + member m.TryPick f = + MapTree.tryPick f tree - let rec foldOpt (f:OptimizedClosures.FSharpFunc<_,_,_,_>) x m = - match m with - | MapEmpty -> x - | MapOne(k,v) -> f.Invoke(x,k,v) - | MapNode(k,v,l,r,_) -> - let x = foldOpt f x l - let x = f.Invoke(x,k,v) - foldOpt f x r - - let fold f x m = foldOpt (OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)) x m - - let foldSectionOpt (comparer: IComparer<'Key>) lo hi (f:OptimizedClosures.FSharpFunc<_,_,_,_>) m x = - let rec foldFromTo (f:OptimizedClosures.FSharpFunc<_,_,_,_>) m x = - match m with - | MapEmpty -> x - | MapOne(k,v) -> - let cLoKey = comparer.Compare(lo,k) - let cKeyHi = comparer.Compare(k,hi) - let x = if cLoKey <= 0 && cKeyHi <= 0 then f.Invoke(k, v, x) else x - x - | MapNode(k,v,l,r,_) -> - let cLoKey = comparer.Compare(lo,k) - let cKeyHi = comparer.Compare(k,hi) - let x = if cLoKey < 0 then foldFromTo f l x else x - let x = if cLoKey <= 0 && cKeyHi <= 0 then f.Invoke(k, v, x) else x - let x = if cKeyHi < 0 then foldFromTo f r x else x - x - - if comparer.Compare(lo,hi) = 1 then x else foldFromTo f m x - - let foldSection (comparer: IComparer<'Key>) lo hi f m x = - foldSectionOpt comparer lo hi (OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)) m x - - let toList m = - let rec loop m acc = - match m with - | MapEmpty -> acc - | MapOne(k,v) -> (k,v)::acc - | MapNode(k,v,l,r,_) -> loop l ((k,v)::loop r acc) - loop m [] - let toArray m = m |> toList |> Array.ofList - let ofList comparer l = List.fold (fun acc (k,v) -> add comparer k v acc) empty l - - let rec mkFromEnumerator comparer acc (e : IEnumerator<_>) = - if e.MoveNext() then - let (x,y) = e.Current - mkFromEnumerator comparer (add comparer x y acc) e - else acc - - let ofArray comparer (arr : array<_>) = - let mutable res = empty - for (x,y) in arr do - res <- add comparer x y res - res - - let ofSeq comparer (c : seq<'Key * 'T>) = - match c with - | :? array<'Key * 'T> as xs -> ofArray comparer xs - | :? list<'Key * 'T> as xs -> ofList comparer xs - | _ -> - use ie = c.GetEnumerator() - mkFromEnumerator comparer empty ie - - - let copyToArray s (arr: _[]) i = - let j = ref i - s |> iter (fun x y -> arr.[!j] <- KeyValuePair(x,y); j := !j + 1) - - - /// Imperative left-to-right iterators. - [] - type MapIterator<'Key,'Value when 'Key : comparison > = - { /// invariant: always collapseLHS result - mutable stack: MapTree<'Key,'Value> list; - /// true when MoveNext has been called - mutable started : bool } - - // collapseLHS: - // a) Always returns either [] or a list starting with MapOne. - // b) The "fringe" of the set stack is unchanged. - let rec collapseLHS stack = - match stack with - | [] -> [] - | MapEmpty :: rest -> collapseLHS rest - | MapOne _ :: _ -> stack - | (MapNode(k,v,l,r,_)) :: rest -> collapseLHS (l :: MapOne (k,v) :: r :: rest) - - let mkIterator s = { stack = collapseLHS [s]; started = false } - - let notStarted() = raise (InvalidOperationException(SR.GetString(SR.enumerationNotStarted))) - let alreadyFinished() = raise (InvalidOperationException(SR.GetString(SR.enumerationAlreadyFinished))) - - let current i = - if i.started then - match i.stack with - | MapOne (k,v) :: _ -> new KeyValuePair<_,_>(k,v) - | [] -> alreadyFinished() - | _ -> failwith "Please report error: Map iterator, unexpected stack for current" - else - notStarted() - - let rec moveNext i = - if i.started then - match i.stack with - | MapOne _ :: rest -> i.stack <- collapseLHS rest - not i.stack.IsEmpty - | [] -> false - | _ -> failwith "Please report error: Map iterator, unexpected stack for moveNext" - else - i.started <- true (* The first call to MoveNext "starts" the enumeration. *) - not i.stack.IsEmpty - - let mkIEnumerator s = - let i = ref (mkIterator s) - { new IEnumerator<_> with - member __.Current = current !i - interface System.Collections.IEnumerator with - member __.Current = box (current !i) - member __.MoveNext() = moveNext !i - member __.Reset() = i := mkIterator s - interface System.IDisposable with - member __.Dispose() = ()} - - - - [>)>] - [] - [] - [] - [] - type Map<[]'Key,[]'Value when 'Key : comparison >(comparer: IComparer<'Key>, tree: MapTree<'Key,'Value>) = + member m.Exists predicate = + MapTree.exists predicate tree -#if !FX_NO_BINARY_SERIALIZATION - [] - // This type is logically immutable. This field is only mutated during deserialization. - let mutable comparer = comparer - - [] - // This type is logically immutable. This field is only mutated during deserialization. - let mutable tree = tree - - // This type is logically immutable. This field is only mutated during serialization and deserialization. - // - // WARNING: The compiled name of this field may never be changed because it is part of the logical - // WARNING: permanent serialization format for this type. - let mutable serializedData = null -#endif + member m.Filter predicate = + new Map<'Key, 'Value>(comparer, MapTree.filter comparer predicate tree) - // We use .NET generics per-instantiation static fields to avoid allocating a new object for each empty - // set (it is just a lookup into a .NET table of type-instantiation-indexed static fields). - static let empty = - let comparer = LanguagePrimitives.FastGenericComparer<'Key> - new Map<'Key,'Value>(comparer,MapTree<_,_>.MapEmpty) + member m.ForAll predicate = + MapTree.forall predicate tree -#if !FX_NO_BINARY_SERIALIZATION - [] - member __.OnSerializing(context: System.Runtime.Serialization.StreamingContext) = - ignore(context) - serializedData <- MapTree.toArray tree |> Array.map (fun (k,v) -> KeyValuePair(k,v)) - - // Do not set this to null, since concurrent threads may also be serializing the data - //[] - //member __.OnSerialized(context: System.Runtime.Serialization.StreamingContext) = - // serializedData <- null - - [] - member __.OnDeserialized(context: System.Runtime.Serialization.StreamingContext) = - ignore(context) - comparer <- LanguagePrimitives.FastGenericComparer<'Key> - tree <- serializedData |> Array.map (fun (KeyValue(k,v)) -> (k,v)) |> MapTree.ofArray comparer - serializedData <- null -#endif + member m.Fold f acc = + MapTree.foldBack f tree acc - static member Empty : Map<'Key,'Value> = empty + member m.FoldSection (lo:'Key) (hi:'Key) f (acc:'z) = + MapTree.foldSection comparer lo hi f tree acc - static member Create(ie : IEnumerable<_>) : Map<'Key,'Value> = - let comparer = LanguagePrimitives.FastGenericComparer<'Key> - new Map<_,_>(comparer,MapTree.ofSeq comparer ie) - - static member Create() : Map<'Key,'Value> = empty + member m.Iterate f = + MapTree.iter f tree - new(elements : seq<_>) = - let comparer = LanguagePrimitives.FastGenericComparer<'Key> - new Map<_,_>(comparer,MapTree.ofSeq comparer elements) - - [] - member internal m.Comparer = comparer + member m.MapRange f = + new Map<'Key, 'b>(comparer, MapTree.map f tree) - //[] - member internal m.Tree = tree + member m.Map f = + new Map<'Key, 'b>(comparer, MapTree.mapi f tree) - member m.Add(key,value) : Map<'Key,'Value> = + member m.Partition predicate : Map<'Key, 'Value> * Map<'Key, 'Value> = + let r1, r2 = MapTree.partition comparer predicate tree + new Map<'Key, 'Value>(comparer, r1), new Map<'Key, 'Value>(comparer, r2) + + member m.Count = + MapTree.size tree + + member m.ContainsKey(key) = #if TRACE_SETS_AND_MAPS - MapTree.report() - MapTree.numAdds <- MapTree.numAdds + 1 - let size = MapTree.size m.Tree + 1 - MapTree.totalSizeOnMapAdd <- MapTree.totalSizeOnMapAdd + float size - if size > MapTree.largestMapSize then - MapTree.largestMapSize <- size - MapTree.largestMapStackTrace <- System.Diagnostics.StackTrace().ToString() + MapTree.report() + MapTree.numLookups <- MapTree.numLookups + 1 + MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree) #endif - new Map<'Key,'Value>(comparer,MapTree.add comparer key value tree) + MapTree.mem comparer key tree - [] - member m.IsEmpty = MapTree.isEmpty tree + member m.Remove key = + new Map<'Key, 'Value>(comparer, MapTree.remove comparer key tree) - member m.Item - with get(key : 'Key) = + member m.TryGetValue(key, [] value: byref<'Value>) = + MapTree.tryGetValue comparer key &value tree + + member m.TryFind(key) = #if TRACE_SETS_AND_MAPS - MapTree.report() - MapTree.numLookups <- MapTree.numLookups + 1 - MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree) + MapTree.report() + MapTree.numLookups <- MapTree.numLookups + 1 + MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree) #endif - MapTree.find comparer key tree + MapTree.tryFind comparer key tree + + member m.ToList() = + MapTree.toList tree + + member m.ToArray() = + MapTree.toArray tree + + static member ofList(l) : Map<'Key, 'Value> = + let comparer = LanguagePrimitives.FastGenericComparer<'Key> + new Map<_, _>(comparer, MapTree.ofList comparer l) + + member this.ComputeHashCode() = + let combineHash x y = (x <<< 1) + y + 631 + let mutable res = 0 + for (KeyValue(x, y)) in this do + res <- combineHash res (hash x) + res <- combineHash res (Unchecked.hash y) + res + + override this.Equals(that) = + match that with + | :? Map<'Key, 'Value> as that -> + use e1 = (this :> seq<_>).GetEnumerator() + use e2 = (that :> seq<_>).GetEnumerator() + let rec loop () = + let m1 = e1.MoveNext() + let m2 = e2.MoveNext() + (m1 = m2) && (not m1 || + (let e1c, e2c = e1.Current, e2.Current + ((e1c.Key = e2c.Key) && (Unchecked.equals e1c.Value e2c.Value) && loop()))) + loop() + | _ -> false + + override this.GetHashCode() = this.ComputeHashCode() + + interface IEnumerable> with + member __.GetEnumerator() = MapTree.mkIEnumerator tree + + interface System.Collections.IEnumerable with + member __.GetEnumerator() = (MapTree.mkIEnumerator tree :> System.Collections.IEnumerator) + + interface IDictionary<'Key, 'Value> with + member m.Item + with get x = m.[x] + and set x v = ignore(x, v); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) - member m.TryPick(f) = MapTree.tryPick f tree + // REVIEW: this implementation could avoid copying the Values to an array + member m.Keys = ([| for kvp in m -> kvp.Key |] :> ICollection<'Key>) - member m.Exists(f) = MapTree.exists f tree + // REVIEW: this implementation could avoid copying the Values to an array + member m.Values = ([| for kvp in m -> kvp.Value |] :> ICollection<'Value>) - member m.Filter(f) : Map<'Key,'Value> = new Map<'Key,'Value>(comparer,MapTree.filter comparer f tree) + member m.Add(k, v) = ignore(k, v); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) - member m.ForAll(f) = MapTree.forall f tree + member m.ContainsKey(k) = m.ContainsKey(k) - member m.Fold f acc = MapTree.foldBack f tree acc + member m.TryGetValue(k, r) = m.TryGetValue(k, &r) - member m.FoldSection (lo:'Key) (hi:'Key) f (acc:'z) = MapTree.foldSection comparer lo hi f tree acc + member m.Remove(k : 'Key) = ignore(k); (raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) : bool) - member m.Iterate f = MapTree.iter f tree + interface ICollection> with + member __.Add(x) = ignore(x); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) - member m.MapRange f = new Map<'Key,'b>(comparer,MapTree.map f tree) + member __.Clear() = raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) - member m.Map f = new Map<'Key,'b>(comparer,MapTree.mapi f tree) + member __.Remove(x) = ignore(x); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) - member m.Partition(f) : Map<'Key,'Value> * Map<'Key,'Value> = - let r1,r2 = MapTree.partition comparer f tree in - new Map<'Key,'Value>(comparer,r1), new Map<'Key,'Value>(comparer,r2) + member m.Contains(x) = m.ContainsKey(x.Key) && Unchecked.equals m.[x.Key] x.Value - member m.Count = MapTree.size tree + member __.CopyTo(arr, i) = MapTree.copyToArray tree arr i - member m.ContainsKey(key) = -#if TRACE_SETS_AND_MAPS - MapTree.report() - MapTree.numLookups <- MapTree.numLookups + 1 - MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree) -#endif - MapTree.mem comparer key tree + member __.IsReadOnly = true - member m.Remove(key) : Map<'Key,'Value> = - new Map<'Key,'Value>(comparer,MapTree.remove comparer key tree) + member m.Count = m.Count - member m.TryGetValue(key, [] value:byref<'Value>) = - MapTree.tryGetValue comparer key &value tree + interface System.IComparable with + member m.CompareTo(obj: obj) = + match obj with + | :? Map<'Key, 'Value> as m2-> + Seq.compareWith + (fun (kvp1 : KeyValuePair<_, _>) (kvp2 : KeyValuePair<_, _>)-> + let c = comparer.Compare(kvp1.Key, kvp2.Key) in + if c <> 0 then c else Unchecked.compare kvp1.Value kvp2.Value) + m m2 + | _ -> + invalidArg "obj" (SR.GetString(SR.notComparable)) - member m.TryFind(key) = -#if TRACE_SETS_AND_MAPS - MapTree.report() - MapTree.numLookups <- MapTree.numLookups + 1 - MapTree.totalSizeOnMapLookup <- MapTree.totalSizeOnMapLookup + float (MapTree.size tree) -#endif - MapTree.tryFind comparer key tree - - member m.ToList() = MapTree.toList tree - - member m.ToArray() = MapTree.toArray tree - - static member ofList(l) : Map<'Key,'Value> = - let comparer = LanguagePrimitives.FastGenericComparer<'Key> - new Map<_,_>(comparer,MapTree.ofList comparer l) - - member this.ComputeHashCode() = - let combineHash x y = (x <<< 1) + y + 631 - let mutable res = 0 - for (KeyValue(x,y)) in this do - res <- combineHash res (hash x) - res <- combineHash res (Unchecked.hash y) - res - - override this.Equals(that) = - match that with - | :? Map<'Key,'Value> as that -> - use e1 = (this :> seq<_>).GetEnumerator() - use e2 = (that :> seq<_>).GetEnumerator() - let rec loop () = - let m1 = e1.MoveNext() - let m2 = e2.MoveNext() - (m1 = m2) && (not m1 || let e1c, e2c = e1.Current, e2.Current in ((e1c.Key = e2c.Key) && (Unchecked.equals e1c.Value e2c.Value) && loop())) - loop() - | _ -> false - - override this.GetHashCode() = this.ComputeHashCode() - - interface IEnumerable> with - member __.GetEnumerator() = MapTree.mkIEnumerator tree - - interface System.Collections.IEnumerable with - member __.GetEnumerator() = (MapTree.mkIEnumerator tree :> System.Collections.IEnumerator) - - interface IDictionary<'Key, 'Value> with - member m.Item - with get x = m.[x] - and set x v = ignore(x,v); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) - - // REVIEW: this implementation could avoid copying the Values to an array - member s.Keys = ([| for kvp in s -> kvp.Key |] :> ICollection<'Key>) - - // REVIEW: this implementation could avoid copying the Values to an array - member s.Values = ([| for kvp in s -> kvp.Value |] :> ICollection<'Value>) - - member s.Add(k,v) = ignore(k,v); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) - member s.ContainsKey(k) = s.ContainsKey(k) - member s.TryGetValue(k,r) = s.TryGetValue(k,&r) - member s.Remove(k : 'Key) = ignore(k); (raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))) : bool) - - interface ICollection> with - member __.Add(x) = ignore(x); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))); - member __.Clear() = raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))); - member __.Remove(x) = ignore(x); raise (NotSupportedException(SR.GetString(SR.mapCannotBeMutated))); - member s.Contains(x) = s.ContainsKey(x.Key) && Unchecked.equals s.[x.Key] x.Value - member __.CopyTo(arr,i) = MapTree.copyToArray tree arr i - member s.IsReadOnly = true - member s.Count = s.Count - - interface System.IComparable with - member m.CompareTo(obj: obj) = - match obj with - | :? Map<'Key,'Value> as m2-> - Seq.compareWith - (fun (kvp1 : KeyValuePair<_,_>) (kvp2 : KeyValuePair<_,_>)-> - let c = comparer.Compare(kvp1.Key,kvp2.Key) in - if c <> 0 then c else Unchecked.compare kvp1.Value kvp2.Value) - m m2 - | _ -> - invalidArg "obj" (SR.GetString(SR.notComparable)) - - interface IReadOnlyCollection> with - member s.Count = s.Count - - interface IReadOnlyDictionary<'Key, 'Value> with - member s.Item with get(key) = s.[key] - member s.Keys = seq { for kvp in s -> kvp.Key } - member s.TryGetValue(key, value:byref<'Value>) = s.TryGetValue(key, &value) - member s.Values = seq { for kvp in s -> kvp.Value } - member s.ContainsKey key = s.ContainsKey key - - override x.ToString() = - match List.ofSeq (Seq.truncate 4 x) with - | [] -> "map []" - | [KeyValue h1] -> System.Text.StringBuilder().Append("map [").Append(LanguagePrimitives.anyToStringShowingNull h1).Append("]").ToString() - | [KeyValue h1;KeyValue h2] -> System.Text.StringBuilder().Append("map [").Append(LanguagePrimitives.anyToStringShowingNull h1).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h2).Append("]").ToString() - | [KeyValue h1;KeyValue h2;KeyValue h3] -> System.Text.StringBuilder().Append("map [").Append(LanguagePrimitives.anyToStringShowingNull h1).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h2).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h3).Append("]").ToString() - | KeyValue h1 :: KeyValue h2 :: KeyValue h3 :: _ -> System.Text.StringBuilder().Append("map [").Append(LanguagePrimitives.anyToStringShowingNull h1).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h2).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h3).Append("; ... ]").ToString() - - and - [] - MapDebugView<'Key,'Value when 'Key : comparison>(v: Map<'Key,'Value>) = - - [] - member x.Items = - v |> Seq.truncate 10000 |> Seq.map KeyValuePairDebugFriendly |> Seq.toArray - - and - [] - KeyValuePairDebugFriendly<'Key,'Value>(keyValue : KeyValuePair<'Key, 'Value>) = - - [] - member x.KeyValue = keyValue - + interface IReadOnlyCollection> with + member m.Count = m.Count -namespace Microsoft.FSharp.Collections + interface IReadOnlyDictionary<'Key, 'Value> with + + member m.Item with get(key) = m.[key] + + member m.Keys = seq { for kvp in m -> kvp.Key } - open System - open System.Diagnostics - open System.Collections.Generic - open Microsoft.FSharp.Core - open Microsoft.FSharp.Core.Operators - open Microsoft.FSharp.Collections + member m.TryGetValue(key, value: byref<'Value>) = m.TryGetValue(key, &value) - [] - [] - module Map = + member m.Values = seq { for kvp in m -> kvp.Value } - [] - let isEmpty (table:Map<_,_>) = table.IsEmpty + member m.ContainsKey key = m.ContainsKey key + + override x.ToString() = + match List.ofSeq (Seq.truncate 4 x) with + | [] -> "map []" + | [KeyValue h1] -> + let txt1 = LanguagePrimitives.anyToStringShowingNull h1 + StringBuilder().Append("map [").Append(txt1).Append("]").ToString() + | [KeyValue h1; KeyValue h2] -> + let txt1 = LanguagePrimitives.anyToStringShowingNull h1 + let txt2 = LanguagePrimitives.anyToStringShowingNull h2 + StringBuilder().Append("map [").Append(txt1).Append("; ").Append(txt2).Append("]").ToString() + | [KeyValue h1; KeyValue h2; KeyValue h3] -> + let txt1 = LanguagePrimitives.anyToStringShowingNull h1 + let txt2 = LanguagePrimitives.anyToStringShowingNull h2 + let txt3 = LanguagePrimitives.anyToStringShowingNull h3 + StringBuilder().Append("map [").Append(txt1).Append("; ").Append(txt2).Append("; ").Append(txt3).Append("]").ToString() + | KeyValue h1 :: KeyValue h2 :: KeyValue h3 :: _ -> + let txt1 = LanguagePrimitives.anyToStringShowingNull h1 + let txt2 = LanguagePrimitives.anyToStringShowingNull h2 + let txt3 = LanguagePrimitives.anyToStringShowingNull h3 + StringBuilder().Append("map [").Append(txt1).Append("; ").Append(txt2).Append("; ").Append(txt3).Append("; ... ]").ToString() + +and + [] + MapDebugView<'Key, 'Value when 'Key : comparison>(v: Map<'Key, 'Value>) = - [] - let add key value (table:Map<_,_>) = table.Add(key,value) + [] + member x.Items = + v |> Seq.truncate 10000 |> Seq.map KeyValuePairDebugFriendly |> Seq.toArray - [] - let find key (table:Map<_,_>) = table.[key] +and + [] + KeyValuePairDebugFriendly<'Key, 'Value>(keyValue : KeyValuePair<'Key, 'Value>) = - [] - let tryFind key (table:Map<_,_>) = table.TryFind(key) + [] + member x.KeyValue = keyValue - [] - let remove key (table:Map<_,_>) = table.Remove(key) +[] +[] +module Map = - [] - let containsKey key (table:Map<_,_>) = table.ContainsKey(key) + [] + let isEmpty (table: Map<_, _>) = + table.IsEmpty - [] - let iter action (table:Map<_,_>) = table.Iterate(action) + [] + let add key value (table: Map<_, _>) = + table.Add (key, value) - [] - let tryPick chooser (table:Map<_,_>) = table.TryPick(chooser) + [] + let find key (table: Map<_, _>) = + table.[key] - [] - let pick chooser (table:Map<_,_>) = match tryPick chooser table with None -> raise (KeyNotFoundException()) | Some res -> res + [] + let tryFind key (table: Map<_, _>) = + table.TryFind key - [] - let exists predicate (table:Map<_,_>) = table.Exists(predicate) + [] + let remove key (table: Map<_, _>) = + table.Remove key - [] - let filter predicate (table:Map<_,_>) = table.Filter(predicate) + [] + let containsKey key (table: Map<_, _>) = + table.ContainsKey key - [] - let partition predicate (table:Map<_,_>) = table.Partition(predicate) + [] + let iter action (table: Map<_, _>) = + table.Iterate action - [] - let forall predicate (table:Map<_,_>) = table.ForAll(predicate) + [] + let tryPick chooser (table: Map<_, _>) = + table.TryPick chooser - let mapRange f (m:Map<_,_>) = m.MapRange(f) + [] + let pick chooser (table: Map<_, _>) = + match tryPick chooser table with + | None -> raise (KeyNotFoundException()) + | Some res -> res - [] - let map mapping (table:Map<_,_>) = table.Map(mapping) + [] + let exists predicate (table: Map<_, _>) = + table.Exists predicate - [] - let fold<'Key,'T,'State when 'Key : comparison> folder (state:'State) (table:Map<'Key,'T>) = MapTree.fold folder state table.Tree + [] + let filter predicate (table: Map<_, _>) = + table.Filter predicate - [] - let foldBack<'Key,'T,'State when 'Key : comparison> folder (table:Map<'Key,'T>) (state:'State) = MapTree.foldBack folder table.Tree state - - [] - let toSeq (table:Map<_,_>) = table |> Seq.map (fun kvp -> kvp.Key, kvp.Value) + [] + let partition predicate (table: Map<_, _>) = + table.Partition predicate - [] - let findKey predicate (table : Map<_,_>) = table |> toSeq |> Seq.pick (fun (k,v) -> if predicate k v then Some(k) else None) + [] + let forall predicate (table: Map<_, _>) = + table.ForAll predicate - [] - let tryFindKey predicate (table : Map<_,_>) = table |> toSeq |> Seq.tryPick (fun (k,v) -> if predicate k v then Some(k) else None) + [] + let map mapping (table: Map<_, _>) = + table.Map mapping - [] - let ofList (elements: ('Key * 'Value) list) = Map<_,_>.ofList(elements) + [] + let fold<'Key, 'T, 'State when 'Key : comparison> folder (state:'State) (table: Map<'Key, 'T>) = + MapTree.fold folder state table.Tree - [] - let ofSeq elements = Map<_,_>.Create(elements) + [] + let foldBack<'Key, 'T, 'State when 'Key : comparison> folder (table: Map<'Key, 'T>) (state:'State) = + MapTree.foldBack folder table.Tree state - [] - let ofArray (elements: ('Key * 'Value) array) = - let comparer = LanguagePrimitives.FastGenericComparer<'Key> - new Map<_,_>(comparer,MapTree.ofArray comparer elements) + [] + let toSeq (table: Map<_, _>) = + table |> Seq.map (fun kvp -> kvp.Key, kvp.Value) - [] - let toList (table:Map<_,_>) = table.ToList() + [] + let findKey predicate (table : Map<_, _>) = + table |> toSeq |> Seq.pick (fun (k, v) -> if predicate k v then Some(k) else None) - [] - let toArray (table:Map<_,_>) = table.ToArray() + [] + let tryFindKey predicate (table : Map<_, _>) = + table |> toSeq |> Seq.tryPick (fun (k, v) -> if predicate k v then Some(k) else None) - [] - let empty<'Key,'Value when 'Key : comparison> = Map<'Key,'Value>.Empty + [] + let ofList (elements: ('Key * 'Value) list) = + Map<_, _>.ofList(elements) - [] - let count (table:Map<_,_>) = table.Count + [] + let ofSeq elements = + Map<_, _>.Create(elements) + + [] + let ofArray (elements: ('Key * 'Value) array) = + let comparer = LanguagePrimitives.FastGenericComparer<'Key> + new Map<_, _>(comparer, MapTree.ofArray comparer elements) + + [] + let toList (table: Map<_, _>) = + table.ToList() + + [] + let toArray (table: Map<_, _>) = + table.ToArray() + + [] + let empty<'Key, 'Value when 'Key : comparison> = + Map<'Key, 'Value>.Empty + + [] + let count (table: Map<_, _>) = + table.Count diff --git a/src/fsharp/FSharp.Core/prim-types.fs b/src/fsharp/FSharp.Core/prim-types.fs index 7bdf69c2924..13db8650520 100644 --- a/src/fsharp/FSharp.Core/prim-types.fs +++ b/src/fsharp/FSharp.Core/prim-types.fs @@ -6,8 +6,8 @@ #nowarn "52" // The value has been copied to ensure the original is not mutated by this operation #nowarn "60" // Override implementations in augmentations are now deprecated. Override implementations should be given as part of the initial declaration of a type. #nowarn "61" // The containing type can use 'null' as a representation value for its nullary union case. This member will be compiled as a static member. -#nowarn "69" // Interface implementations in augmentations are now deprecated. Interface implementations should be given on the initial declaration of a type. -#nowarn "77" // Member constraints with the name 'Exp' are given special status by the F# compiler as certain .NET types are implicitly augmented with this member. This may result in compilation failures if you attempt to invoke the member constraint from your own code. +#nowarn "69" // Interface implementations in augmentations are now deprecated. Interface implementations should be given on the initial declaration... +#nowarn "77" // Member constraints with the name 'Exp' are given special status by the F# compiler... #nowarn "3218" // mismatch of parameter name for 'fst' and 'snd' namespace Microsoft.FSharp.Core @@ -53,152 +53,152 @@ namespace Microsoft.FSharp.Core | UseNullAsTrueValue = 8 | Event = 16 - [] + [] type SealedAttribute(value:bool) = inherit System.Attribute() member x.Value = value new() = new SealedAttribute(true) - [] + [] [] type AbstractClassAttribute() = inherit System.Attribute() - [] + [] [] type EqualityConditionalOnAttribute() = inherit System.Attribute() - [] + [] [] type ComparisonConditionalOnAttribute() = inherit System.Attribute() - [] + [] [] type AllowNullLiteralAttribute(value: bool) = inherit System.Attribute() member x.Value = value new () = new AllowNullLiteralAttribute(true) - [] + [] [] type VolatileFieldAttribute() = inherit System.Attribute() - [] + [] [] type DefaultAugmentationAttribute(value:bool) = inherit System.Attribute() member x.Value = value - [] + [] [] type CLIEventAttribute() = inherit System.Attribute() - [] + [] [] type CLIMutableAttribute() = inherit System.Attribute() - [] + [] [] type AutoSerializableAttribute(value:bool) = inherit System.Attribute() member x.Value = value - [] + [] [] type DefaultValueAttribute(check:bool) = inherit System.Attribute() member x.Check = check new() = new DefaultValueAttribute(true) - [] + [] [] type EntryPointAttribute() = inherit System.Attribute() - [] + [] [] type ReferenceEqualityAttribute() = inherit System.Attribute() - [] + [] [] type StructuralComparisonAttribute() = inherit System.Attribute() - [] + [] [] type StructuralEqualityAttribute() = inherit System.Attribute() - [] + [] [] type NoEqualityAttribute() = inherit System.Attribute() - [] + [] [] type CustomEqualityAttribute() = inherit System.Attribute() - [] + [] [] type CustomComparisonAttribute() = inherit System.Attribute() - [] + [] [] type NoComparisonAttribute() = inherit System.Attribute() - [] + [] [] type ReflectedDefinitionAttribute(includeValue: bool) = inherit System.Attribute() new() = ReflectedDefinitionAttribute(false) member x.IncludeValue = includeValue - [] + [] [] type CompiledNameAttribute(compiledName:string) = inherit System.Attribute() member x.CompiledName = compiledName - [] + [] [] type StructAttribute() = inherit System.Attribute() - [] + [] [] type MeasureAttribute() = inherit System.Attribute() - [] + [] [] type MeasureAnnotatedAbbreviationAttribute() = inherit System.Attribute() - [] + [] [] type InterfaceAttribute() = inherit System.Attribute() - [] + [] [] type ClassAttribute() = inherit System.Attribute() - [] + [] [] type LiteralAttribute() = inherit System.Attribute() - [] + [] [] type FSharpInterfaceDataVersionAttribute(major:int,minor:int,release:int) = inherit System.Attribute() @@ -206,7 +206,7 @@ namespace Microsoft.FSharp.Core member x.Minor = minor member x.Release = release - [] + [] [] type CompilationMappingAttribute(sourceConstructFlags:SourceConstructFlags, variantNumber:int, @@ -224,26 +224,26 @@ namespace Microsoft.FSharp.Core member x.TypeDefinitions = typeDefinitions member x.ResourceName = resourceName - [] + [] [] type CompilationSourceNameAttribute(sourceName:string) = inherit System.Attribute() member x.SourceName = sourceName //------------------------------------------------------------------------- - [] + [] [] type CompilationRepresentationAttribute (flags : CompilationRepresentationFlags) = inherit System.Attribute() member x.Flags = flags - [] + [] [] type ExperimentalAttribute(message:string) = inherit System.Attribute() member x.Message = message - [] + [] [] type CompilationArgumentCountsAttribute(counts:int[]) = inherit System.Attribute() @@ -251,7 +251,7 @@ namespace Microsoft.FSharp.Core let unboxPrim(x:obj) = (# "unbox.any !0" type ('T) x : 'T #) (unboxPrim(counts.Clone()) : System.Collections.Generic.IEnumerable) - [] + [] [] type CustomOperationAttribute(name:string) = inherit System.Attribute() @@ -272,18 +272,18 @@ namespace Microsoft.FSharp.Core member x.MaintainsVariableSpace with get() = maintainsVarSpace and set v = maintainsVarSpace <- v member x.MaintainsVariableSpaceUsingBind with get() = maintainsVarSpaceWithBind and set v = maintainsVarSpaceWithBind <- v - [] + [] [] type ProjectionParameterAttribute() = inherit System.Attribute() - [] + [] [] type StructuredFormatDisplayAttribute(value:string) = inherit System.Attribute() member x.Value = value - [] + [] [] type CompilerMessageAttribute(message:string, messageNumber : int) = inherit System.Attribute() @@ -294,37 +294,37 @@ namespace Microsoft.FSharp.Core member x.IsError with get() = isError and set v = isError <- v member x.IsHidden with get() = isHidden and set v = isHidden <- v - [] + [] [] type UnverifiableAttribute() = inherit System.Attribute() - [] + [] [] type NoDynamicInvocationAttribute() = inherit System.Attribute() - [] + [] [] type OptionalArgumentAttribute() = inherit System.Attribute() - [] + [] [] type GeneralizableValueAttribute() = inherit System.Attribute() - [] + [] [] type RequiresExplicitTypeArgumentsAttribute() = inherit System.Attribute() - [] + [] [] type RequireQualifiedAccessAttribute() = inherit System.Attribute() - [] + [] [] type AutoOpenAttribute(path:string) = inherit System.Attribute() @@ -334,7 +334,7 @@ namespace Microsoft.FSharp.Core /// This Attribute is used to make Value bindings like /// let x = some code /// operate like static properties. - [] + [] [] type ValueAsStaticPropertyAttribute() = inherit System.Attribute() @@ -1900,7 +1900,9 @@ namespace Microsoft.FSharp.Core // Because the function subsequently gets inlined, the calls to GenericHashWithComparerFast can be // often statically optimized or devirtualized based on the statically known type. let inline FastHashTuple2 (comparer:System.Collections.IEqualityComparer) (x1,x2) = - TupleUtils.combineTupleHashes (GenericHashWithComparerFast comparer x1) (GenericHashWithComparerFast comparer x2) + TupleUtils.combineTupleHashes + (GenericHashWithComparerFast comparer x1) + (GenericHashWithComparerFast comparer x2) /// Compiler intrinsic generated for devirtualized calls to structural hashing on tuples. // @@ -1910,7 +1912,11 @@ namespace Microsoft.FSharp.Core // Because the function subsequently gets inlined, the calls to GenericHashWithComparerFast can be // often statically optimized or devirtualized based on the statically known type. let inline FastHashTuple3 (comparer:System.Collections.IEqualityComparer) (x1,x2,x3) = - TupleUtils.combineTupleHashes (TupleUtils.combineTupleHashes (GenericHashWithComparerFast comparer x1) (GenericHashWithComparerFast comparer x2)) (GenericHashWithComparerFast comparer x3) + TupleUtils.combineTupleHashes + (TupleUtils.combineTupleHashes + (GenericHashWithComparerFast comparer x1) + (GenericHashWithComparerFast comparer x2)) + (GenericHashWithComparerFast comparer x3) /// Compiler intrinsic generated for devirtualized calls to structural hashing on tuples. // @@ -1920,7 +1926,13 @@ namespace Microsoft.FSharp.Core // Because the function subsequently gets inlined, the calls to GenericHashWithComparerFast can be // often statically optimized or devirtualized based on the statically known type. let inline FastHashTuple4 (comparer:System.Collections.IEqualityComparer) (x1,x2,x3,x4) = - TupleUtils.combineTupleHashes (TupleUtils.combineTupleHashes (GenericHashWithComparerFast comparer x1) (GenericHashWithComparerFast comparer x2)) (TupleUtils.combineTupleHashes (GenericHashWithComparerFast comparer x3) (GenericHashWithComparerFast comparer x4)) + TupleUtils.combineTupleHashes + (TupleUtils.combineTupleHashes + (GenericHashWithComparerFast comparer x1) + (GenericHashWithComparerFast comparer x2)) + (TupleUtils.combineTupleHashes + (GenericHashWithComparerFast comparer x3) + (GenericHashWithComparerFast comparer x4)) /// Compiler intrinsic generated for devirtualized calls to structural hashing on tuples. // @@ -1930,7 +1942,15 @@ namespace Microsoft.FSharp.Core // Because the function subsequently gets inlined, the calls to GenericHashWithComparerFast can be // often statically optimized or devirtualized based on the statically known type. let inline FastHashTuple5 (comparer:System.Collections.IEqualityComparer) (x1,x2,x3,x4,x5) = - TupleUtils.combineTupleHashes (TupleUtils.combineTupleHashes (TupleUtils.combineTupleHashes (GenericHashWithComparerFast comparer x1) (GenericHashWithComparerFast comparer x2)) (TupleUtils.combineTupleHashes (GenericHashWithComparerFast comparer x3) (GenericHashWithComparerFast comparer x4))) (GenericHashWithComparerFast comparer x5) + TupleUtils.combineTupleHashes + (TupleUtils.combineTupleHashes + (TupleUtils.combineTupleHashes + (GenericHashWithComparerFast comparer x1) + (GenericHashWithComparerFast comparer x2)) + (TupleUtils.combineTupleHashes + (GenericHashWithComparerFast comparer x3) + (GenericHashWithComparerFast comparer x4))) + (GenericHashWithComparerFast comparer x5) /// Compiler intrinsic generated for devirtualized calls to PER-semantic structural equality on tuples // diff --git a/src/fsharp/FSharp.Core/printf.fs b/src/fsharp/FSharp.Core/printf.fs index 0c2d6b70316..eb0996da06d 100644 --- a/src/fsharp/FSharp.Core/printf.fs +++ b/src/fsharp/FSharp.Core/printf.fs @@ -62,7 +62,7 @@ module internal PrintfImpl = | PlusForPositives = 4 | SpaceForPositives = 8 - let inline hasFlag flags (expected : FormatFlags) = (flags &&& expected) = expected + let inline hasFlag flags (expected: FormatFlags) = (flags &&& expected) = expected let inline isLeftJustify flags = hasFlag flags FormatFlags.LeftJustify let inline isPadWithZeros flags = hasFlag flags FormatFlags.PadWithZeros let inline isPlusForPositives flags = hasFlag flags FormatFlags.PlusForPositives @@ -79,10 +79,10 @@ module internal PrintfImpl = [] type FormatSpecifier = { - TypeChar : char - Precision : int - Width : int - Flags : FormatFlags + TypeChar: char + Precision: int + Width: int + Flags: FormatFlags } member this.IsStarPrecision = this.Precision = StarValue member this.IsPrecisionSpecified = this.Precision <> NotSpecifiedValue @@ -102,8 +102,10 @@ module internal PrintfImpl = /// Set of helpers to parse format string module private FormatString = + let inline isDigit c = c >= '0' && c <= '9' - let intFromString (s : string) pos = + + let intFromString (s: string) pos = let rec go acc i = if isDigit s.[i] then let n = int s.[i] - int '0' @@ -111,7 +113,7 @@ module internal PrintfImpl = else acc, i go 0 pos - let parseFlags (s : string) i : FormatFlags * int = + let parseFlags (s: string) i = let rec go flags i = match s.[i] with | '0' -> go (flags ||| FormatFlags.PadWithZeros) (i + 1) @@ -121,23 +123,23 @@ module internal PrintfImpl = | _ -> flags, i go FormatFlags.None i - let parseWidth (s : string) i : int * int = + let parseWidth (s: string) i = if s.[i] = '*' then StarValue, (i + 1) elif isDigit (s.[i]) then intFromString s i else NotSpecifiedValue, i - let parsePrecision (s : string) i : int * int = + let parsePrecision (s: string) i = if s.[i] = '.' then if s.[i + 1] = '*' then StarValue, i + 2 elif isDigit (s.[i + 1]) then intFromString s (i + 1) else raise (ArgumentException("invalid precision value")) else NotSpecifiedValue, i - let parseTypeChar (s : string) i : char * int = + let parseTypeChar (s: string) i = s.[i], (i + 1) - let findNextFormatSpecifier (s : string) i = - let rec go i (buf : Text.StringBuilder) = + let findNextFormatSpecifier (s: string) i = + let rec go i (buf: Text.StringBuilder) = if i >= s.Length then s.Length, buf.ToString() else @@ -165,44 +167,44 @@ module internal PrintfImpl = /// Abstracts generated printer from the details of particular environment: how to write text, how to produce results etc... [] type PrintfEnv<'State, 'Residue, 'Result> = - val State : 'State - new(s : 'State) = { State = s } - abstract Finish : unit -> 'Result - abstract Write : string -> unit - abstract WriteT : 'Residue -> unit + val State: 'State + new(s: 'State) = { State = s } + abstract Finish: unit -> 'Result + abstract Write: string -> unit + abstract WriteT: 'Residue -> unit type Utils = - static member inline Write (env : PrintfEnv<_, _, _>, a, b) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b) = env.Write a env.Write b - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c) = Utils.Write(env, a, b) env.Write c - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d) = Utils.Write(env, a, b) Utils.Write(env, c, d) - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d, e) = Utils.Write(env, a, b, c) Utils.Write(env, d, e) - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d, e, f) = Utils.Write(env, a, b, c, d) Utils.Write(env, e, f) - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d, e, f, g) = Utils.Write(env, a, b, c, d, e) Utils.Write(env, f, g) - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h) = Utils.Write(env, a, b, c, d, e, f) Utils.Write(env, g, h) - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i) = Utils.Write(env, a, b, c, d, e, f, g) Utils.Write(env, h, i) - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j) = Utils.Write(env, a, b, c, d, e, f, g, h) Utils.Write(env, i, j) - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j, k) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j, k) = Utils.Write(env, a, b, c, d, e, f, g, h, i) Utils.Write(env, j, k) - static member inline Write (env : PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j, k, l, m) = + static member inline Write (env: PrintfEnv<_, _, _>, a, b, c, d, e, f, g, h, i, j, k, l, m) = Utils.Write(env, a, b, c, d, e, f, g, h, i, j, k) Utils.Write(env, l, m) @@ -225,8 +227,8 @@ module internal PrintfImpl = ( s0, conv1, s1 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) -> let env = env() Utils.Write(env, s0, (conv1 a), s1) env.Finish() @@ -237,8 +239,8 @@ module internal PrintfImpl = ( s0, conv1 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) -> let env = env() Utils.Write(env, s0, (conv1 a)) env.Finish() @@ -249,8 +251,8 @@ module internal PrintfImpl = ( conv1, s1 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) -> let env = env() Utils.Write(env, (conv1 a), s1) env.Finish() @@ -261,8 +263,8 @@ module internal PrintfImpl = ( conv1 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) -> let env = env() env.Write (conv1 a) env.Finish() @@ -273,8 +275,8 @@ module internal PrintfImpl = ( s0, conv1, s1, conv2, s2 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) -> let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2) env.Finish() @@ -285,8 +287,8 @@ module internal PrintfImpl = ( s0, conv1, s1, conv2 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) -> let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b)) env.Finish() @@ -297,8 +299,8 @@ module internal PrintfImpl = ( conv1, s1, conv2, s2 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) -> let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2) env.Finish() @@ -309,8 +311,8 @@ module internal PrintfImpl = ( conv1, s1, conv2 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) -> let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b)) env.Finish() @@ -321,8 +323,8 @@ module internal PrintfImpl = ( s0, conv1, s1, conv2, s2, conv3, s3 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) -> let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3) env.Finish() @@ -333,8 +335,8 @@ module internal PrintfImpl = ( s0, conv1, s1, conv2, s2, conv3 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) -> let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c)) env.Finish() @@ -345,8 +347,8 @@ module internal PrintfImpl = ( conv1, s1, conv2, s2, conv3, s3 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) -> let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3) env.Finish() @@ -357,8 +359,8 @@ module internal PrintfImpl = ( conv1, s1, conv2, s2, conv3 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) -> let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c)) env.Finish() @@ -369,8 +371,8 @@ module internal PrintfImpl = ( s0, conv1, s1, conv2, s2, conv3, s3, conv4, s4 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D)-> let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4) env.Finish() @@ -381,8 +383,8 @@ module internal PrintfImpl = ( s0, conv1, s1, conv2, s2, conv3, s3, conv4 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D)-> let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d)) env.Finish() @@ -393,8 +395,8 @@ module internal PrintfImpl = ( conv1, s1, conv2, s2, conv3, s3, conv4, s4 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D)-> let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4) env.Finish() @@ -405,8 +407,8 @@ module internal PrintfImpl = ( conv1, s1, conv2, s2, conv3, s3, conv4 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D)-> let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d)) env.Finish() @@ -417,8 +419,8 @@ module internal PrintfImpl = ( s0, conv1, s1, conv2, s2, conv3, s3, conv4, s4, conv5, s5 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D) (e : 'E)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D) (e: 'E)-> let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4, (conv5 e), s5) env.Finish() @@ -429,8 +431,8 @@ module internal PrintfImpl = ( s0, conv1, s1, conv2, s2, conv3, s3, conv4, s4, conv5 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D) (e : 'E)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D) (e: 'E)-> let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4, (conv5 e)) env.Finish() @@ -441,8 +443,8 @@ module internal PrintfImpl = ( conv1, s1, conv2, s2, conv3, s3, conv4, s4, conv5, s5 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D) (e : 'E)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D) (e: 'E)-> let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4, (conv5 e), s5) env.Finish() @@ -453,8 +455,8 @@ module internal PrintfImpl = ( conv1, s1, conv2, s2, conv3, s3, conv4, s4, conv5 ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D) (e : 'E)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D) (e: 'E)-> let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4, (conv5 e)) env.Finish() @@ -466,8 +468,8 @@ module internal PrintfImpl = s0, conv1, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) -> let env() = let env = env() Utils.Write(env, s0, (conv1 a)) @@ -481,8 +483,8 @@ module internal PrintfImpl = conv1, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) -> let env() = let env = env() env.Write(conv1 a) @@ -496,8 +498,8 @@ module internal PrintfImpl = s0, conv1, s1, conv2, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) -> let env() = let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b)) @@ -511,8 +513,8 @@ module internal PrintfImpl = conv1, s1, conv2, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) -> let env() = let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b)) @@ -526,8 +528,8 @@ module internal PrintfImpl = s0, conv1, s1, conv2, s2, conv3, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) -> let env() = let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c)) @@ -541,8 +543,8 @@ module internal PrintfImpl = conv1, s1, conv2, s2, conv3, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) -> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) -> let env() = let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c)) @@ -556,8 +558,8 @@ module internal PrintfImpl = s0, conv1, s1, conv2, s2, conv3, s3, conv4, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D)-> let env() = let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d)) @@ -571,8 +573,8 @@ module internal PrintfImpl = conv1, s1, conv2, s2, conv3, s3, conv4, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D)-> let env() = let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d)) @@ -586,8 +588,8 @@ module internal PrintfImpl = s0, conv1, s1, conv2, s2, conv3, s3, conv4, s4, conv5, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D) (e : 'E)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D) (e: 'E)-> let env() = let env = env() Utils.Write(env, s0, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4, (conv5 e)) @@ -601,8 +603,8 @@ module internal PrintfImpl = conv1, s1, conv2, s2, conv3, s3, conv4, s4, conv5, next ) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (a : 'A) (b : 'B) (c : 'C) (d : 'D) (e : 'E)-> + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (a: 'A) (b: 'B) (c: 'C) (d: 'D) (e: 'E)-> let env() = let env = env() Utils.Write(env, (conv1 a), s1, (conv2 b), s2, (conv3 c), s3, (conv4 d), s4, (conv5 e)) @@ -611,9 +613,9 @@ module internal PrintfImpl = ) ) - static member TFinal(s1 : string, s2 : string) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (f : 'State -> 'Residue) -> + static member TFinal(s1: string, s2: string) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (f: 'State -> 'Residue) -> let env = env() env.Write(s1) env.WriteT(f env.State) @@ -621,21 +623,21 @@ module internal PrintfImpl = env.Finish() ) ) - static member TChained<'Tail>(s1 : string, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (f : 'State -> 'Residue) -> + static member TChained<'Tail>(s1: string, next: PrintfFactory<'State, 'Residue, 'Result,'Tail>) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (f: 'State -> 'Residue) -> let env() = let env = env() env.Write(s1) env.WriteT(f env.State) env - next(env) : 'Tail + next(env): 'Tail ) ) - static member LittleAFinal<'A>(s1 : string, s2 : string) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (f : 'State -> 'A ->'Residue) (a : 'A) -> + static member LittleAFinal<'A>(s1: string, s2: string) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (f: 'State -> 'A ->'Residue) (a: 'A) -> let env = env() env.Write s1 env.WriteT(f env.State a) @@ -643,31 +645,31 @@ module internal PrintfImpl = env.Finish() ) ) - static member LittleAChained<'A, 'Tail>(s1 : string, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (f : 'State -> 'A ->'Residue) (a : 'A) -> + static member LittleAChained<'A, 'Tail>(s1: string, next: PrintfFactory<'State, 'Residue, 'Result,'Tail>) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (f: 'State -> 'A ->'Residue) (a: 'A) -> let env() = let env = env() env.Write s1 env.WriteT(f env.State a) env - next env : 'Tail + next env: 'Tail ) ) - static member StarFinal1<'A>(s1 : string, conv, s2 : string) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (star1 : int) (a : 'A) -> + static member StarFinal1<'A>(s1: string, conv, s2: string) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (star1: int) (a: 'A) -> let env = env() env.Write s1 - env.Write (conv a star1 : string) + env.Write (conv a star1: string) env.Write s2 env.Finish() ) ) - static member PercentStarFinal1(s1 : string, s2 : string) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + static member PercentStarFinal1(s1: string, s2: string) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> (fun (_star1 : int) -> let env = env() env.Write s1 @@ -677,9 +679,9 @@ module internal PrintfImpl = ) ) - static member StarFinal2<'A>(s1 : string, conv, s2 : string) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (star1 : int) (star2 : int) (a : 'A) -> + static member StarFinal2<'A>(s1: string, conv, s2: string) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (star1: int) (star2: int) (a: 'A) -> let env = env() env.Write s1 env.Write (conv a star1 star2: string) @@ -689,8 +691,8 @@ module internal PrintfImpl = ) /// Handles case when '%*.*%' is used at the end of string - static member PercentStarFinal2(s1 : string, s2 : string) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + static member PercentStarFinal2(s1: string, s2: string) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> (fun (_star1 : int) (_star2 : int) -> let env = env() env.Write s1 @@ -700,9 +702,9 @@ module internal PrintfImpl = ) ) - static member StarChained1<'A, 'Tail>(s1 : string, conv, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (star1 : int) (a : 'A) -> + static member StarChained1<'A, 'Tail>(s1: string, conv, next: PrintfFactory<'State, 'Residue, 'Result,'Tail>) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (star1: int) (a: 'A) -> let env() = let env = env() env.Write s1 @@ -713,21 +715,21 @@ module internal PrintfImpl = ) /// Handles case when '%*%' is used in the middle of the string so it needs to be chained to another printing block - static member PercentStarChained1<'Tail>(s1 : string, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + static member PercentStarChained1<'Tail>(s1: string, next: PrintfFactory<'State, 'Residue, 'Result,'Tail>) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> (fun (_star1 : int) -> let env() = let env = env() env.Write s1 env.Write("%") env - next env : 'Tail + next env: 'Tail ) ) - static member StarChained2<'A, 'Tail>(s1 : string, conv, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> - (fun (star1 : int) (star2 : int) (a : 'A) -> + static member StarChained2<'A, 'Tail>(s1: string, conv, next: PrintfFactory<'State, 'Residue, 'Result,'Tail>) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + (fun (star1: int) (star2: int) (a: 'A) -> let env() = let env = env() env.Write s1 @@ -738,8 +740,8 @@ module internal PrintfImpl = ) /// Handles case when '%*.*%' is used in the middle of the string so it needs to be chained to another printing block - static member PercentStarChained2<'Tail>(s1 : string, next : PrintfFactory<'State, 'Residue, 'Result,'Tail>) = - (fun (env : unit -> PrintfEnv<'State, 'Residue, 'Result>) -> + static member PercentStarChained2<'Tail>(s1: string, next: PrintfFactory<'State, 'Residue, 'Result,'Tail>) = + (fun (env: unit -> PrintfEnv<'State, 'Residue, 'Result>) -> (fun (_star1 : int) (_star2 : int) -> let env() = let env = env() @@ -762,7 +764,7 @@ module internal PrintfImpl = [] let DefaultPrecision = 6 - let getFormatForFloat (ch : char) (prec : int) = ch.ToString() + prec.ToString() + let getFormatForFloat (ch: char) (prec: int) = ch.ToString() + prec.ToString() let normalizePrecision prec = min (max prec 0) 99 /// Contains helpers to convert printer functions to functions that prints value with respect to specified justification @@ -776,7 +778,7 @@ module internal PrintfImpl = /// pad here is function that converts T to string with respect of justification /// basic - function that converts T to string without applying justification rules /// adaptPaddedFormatted returns boxed function that has various number of arguments depending on if width\precision flags has '*' value - let inline adaptPaddedFormatted (spec : FormatSpecifier) getFormat (basic : string -> 'T -> string) (pad : string -> int -> 'T -> string) = + let inline adaptPaddedFormatted (spec: FormatSpecifier) getFormat (basic: string -> 'T -> string) (pad: string -> int -> 'T -> string) = if spec.IsStarWidth then if spec.IsStarPrecision then // width=*, prec=* @@ -816,7 +818,7 @@ module internal PrintfImpl = /// pad here is function that converts T to string with respect of justification /// basic - function that converts T to string without applying justification rules /// adaptPadded returns boxed function that has various number of arguments depending on if width flags has '*' value - let inline adaptPadded (spec : FormatSpecifier) (basic : 'T -> string) (pad : int -> 'T -> string) = + let inline adaptPadded (spec: FormatSpecifier) (basic: 'T -> string) (pad: int -> 'T -> string) = if spec.IsStarWidth then // width=*, prec=? box(fun v width -> @@ -831,7 +833,7 @@ module internal PrintfImpl = box(fun v -> basic v) - let inline withPaddingFormatted (spec : FormatSpecifier) getFormat (defaultFormat : string) (f : string -> 'T -> string) left right = + let inline withPaddingFormatted (spec: FormatSpecifier) getFormat (defaultFormat: string) (f: string -> 'T -> string) left right = if not (spec.IsWidthSpecified || spec.IsPrecisionSpecified) then box (f defaultFormat) else @@ -840,7 +842,7 @@ module internal PrintfImpl = else adaptPaddedFormatted spec getFormat f right - let inline withPadding (spec : FormatSpecifier) (f : 'T -> string) left right = + let inline withPadding (spec: FormatSpecifier) (f: 'T -> string) left right = if not (spec.IsWidthSpecified) then box f else @@ -860,14 +862,13 @@ module internal PrintfImpl = /// contains functions to handle left\right justifications for non-numeric types (strings\bools) module Basic = - let inline leftJustify f padChar = - fun (w : int) v -> - (f v : string).PadRight(w, padChar) - - let inline rightJustify f padChar = - fun (w : int) v -> - (f v : string).PadLeft(w, padChar) + let inline leftJustify (f: 'T -> string) padChar = + fun (w: int) v -> + (f v).PadRight(w, padChar) + let inline rightJustify (f: 'T -> string) padChar = + fun (w: int) v -> + (f v).PadLeft(w, padChar) /// contains functions to handle left\right and no justification case for numbers module GenericNumber = @@ -875,7 +876,7 @@ module internal PrintfImpl = /// this case can be tricky: /// - negative numbers, -7 should be printed as '-007', not '00-7' /// - positive numbers when prefix for positives is set: 7 should be '+007', not '00+7' - let inline rightJustifyWithZeroAsPadChar (str : string) isNumber isPositive w (prefixForPositives : string) = + let inline rightJustifyWithZeroAsPadChar (str: string) isNumber isPositive w (prefixForPositives: string) = System.Diagnostics.Debug.Assert(prefixForPositives.Length = 0 || prefixForPositives.Length = 1) if isNumber then if isPositive then @@ -890,12 +891,12 @@ module internal PrintfImpl = str.PadLeft(w, ' ') /// handler right justification when pad char = ' ' - let inline rightJustifyWithSpaceAsPadChar (str : string) isNumber isPositive w (prefixForPositives : string) = + let inline rightJustifyWithSpaceAsPadChar (str: string) isNumber isPositive w (prefixForPositives: string) = System.Diagnostics.Debug.Assert(prefixForPositives.Length = 0 || prefixForPositives.Length = 1) (if isNumber && isPositive then prefixForPositives + str else str).PadLeft(w, ' ') /// handles left justification with formatting with 'G'\'g' - either for decimals or with 'g'\'G' is explicitly set - let inline leftJustifyWithGFormat (str : string) isNumber isInteger isPositive w (prefixForPositives : string) padChar = + let inline leftJustifyWithGFormat (str: string) isNumber isInteger isPositive w (prefixForPositives: string) padChar = if isNumber then let str = if isPositive then prefixForPositives + str else str // NOTE: difference - for 'g' format we use isInt check to detect situations when '5.0' is printed as '5' @@ -907,7 +908,7 @@ module internal PrintfImpl = else str.PadRight(w, ' ') // pad NaNs with ' ' - let inline leftJustifyWithNonGFormat (str : string) isNumber isPositive w (prefixForPositives : string) padChar = + let inline leftJustifyWithNonGFormat (str: string) isNumber isPositive w (prefixForPositives: string) padChar = if isNumber then let str = if isPositive then prefixForPositives + str else str str.PadRight(w, padChar) @@ -915,103 +916,103 @@ module internal PrintfImpl = str.PadRight(w, ' ') // pad NaNs with ' ' /// processes given string based depending on values isNumber\isPositive - let inline noJustificationCore (str : string) isNumber isPositive prefixForPositives = + let inline noJustificationCore (str: string) isNumber isPositive prefixForPositives = if isNumber && isPositive then prefixForPositives + str else str - /// noJustification handler for f : 'T -> string - basic integer types - let inline noJustification f (prefix : string) isUnsigned = + /// noJustification handler for f: 'T -> string - basic integer types + let inline noJustification f (prefix: string) isUnsigned = if isUnsigned then fun v -> noJustificationCore (f v) true true prefix else fun v -> noJustificationCore (f v) true (isPositive v) prefix - /// noJustification handler for f : string -> 'T -> string - floating point types - let inline noJustificationWithFormat f (prefix : string) = - fun (fmt : string) v -> noJustificationCore (f fmt v) true (isPositive v) prefix + /// noJustification handler for f: string -> 'T -> string - floating point types + let inline noJustificationWithFormat f (prefix: string) = + fun (fmt: string) v -> noJustificationCore (f fmt v) true (isPositive v) prefix - /// leftJustify handler for f : 'T -> string - basic integer types - let inline leftJustify isGFormat f (prefix : string) padChar isUnsigned = + /// leftJustify handler for f: 'T -> string - basic integer types + let inline leftJustify isGFormat f (prefix: string) padChar isUnsigned = if isUnsigned then if isGFormat then - fun (w : int) v -> + fun (w: int) v -> leftJustifyWithGFormat (f v) true (isInteger v) true w prefix padChar else - fun (w : int) v -> + fun (w: int) v -> leftJustifyWithNonGFormat (f v) true true w prefix padChar else if isGFormat then - fun (w : int) v -> + fun (w: int) v -> leftJustifyWithGFormat (f v) true (isInteger v) (isPositive v) w prefix padChar else - fun (w : int) v -> + fun (w: int) v -> leftJustifyWithNonGFormat (f v) true (isPositive v) w prefix padChar - /// leftJustify handler for f : string -> 'T -> string - floating point types - let inline leftJustifyWithFormat isGFormat f (prefix : string) padChar = + /// leftJustify handler for f: string -> 'T -> string - floating point types + let inline leftJustifyWithFormat isGFormat f (prefix: string) padChar = if isGFormat then - fun (fmt : string) (w : int) v -> + fun (fmt: string) (w: int) v -> leftJustifyWithGFormat (f fmt v) true (isInteger v) (isPositive v) w prefix padChar else - fun (fmt : string) (w : int) v -> + fun (fmt: string) (w: int) v -> leftJustifyWithNonGFormat (f fmt v) true (isPositive v) w prefix padChar - /// rightJustify handler for f : 'T -> string - basic integer types - let inline rightJustify f (prefixForPositives : string) padChar isUnsigned = + /// rightJustify handler for f: 'T -> string - basic integer types + let inline rightJustify f (prefixForPositives: string) padChar isUnsigned = if isUnsigned then if padChar = '0' then - fun (w : int) v -> + fun (w: int) v -> rightJustifyWithZeroAsPadChar (f v) true true w prefixForPositives else System.Diagnostics.Debug.Assert((padChar = ' ')) - fun (w : int) v -> + fun (w: int) v -> rightJustifyWithSpaceAsPadChar (f v) true true w prefixForPositives else if padChar = '0' then - fun (w : int) v -> + fun (w: int) v -> rightJustifyWithZeroAsPadChar (f v) true (isPositive v) w prefixForPositives else System.Diagnostics.Debug.Assert((padChar = ' ')) - fun (w : int) v -> + fun (w: int) v -> rightJustifyWithSpaceAsPadChar (f v) true (isPositive v) w prefixForPositives - /// rightJustify handler for f : string -> 'T -> string - floating point types - let inline rightJustifyWithFormat f (prefixForPositives : string) padChar = + /// rightJustify handler for f: string -> 'T -> string - floating point types + let inline rightJustifyWithFormat f (prefixForPositives: string) padChar = if padChar = '0' then - fun (fmt : string) (w : int) v -> + fun (fmt: string) (w: int) v -> rightJustifyWithZeroAsPadChar (f fmt v) true (isPositive v) w prefixForPositives else System.Diagnostics.Debug.Assert((padChar = ' ')) - fun (fmt : string) (w : int) v -> + fun (fmt: string) (w: int) v -> rightJustifyWithSpaceAsPadChar (f fmt v) true (isPositive v) w prefixForPositives module Float = - let inline noJustification f (prefixForPositives : string) = - fun (fmt : string) v -> + let inline noJustification f (prefixForPositives: string) = + fun (fmt: string) v -> GenericNumber.noJustificationCore (f fmt v) (isNumber v) (isPositive v) prefixForPositives - let inline leftJustify isGFormat f (prefix : string) padChar = + let inline leftJustify isGFormat f (prefix: string) padChar = if isGFormat then - fun (fmt : string) (w : int) v -> + fun (fmt: string) (w: int) v -> GenericNumber.leftJustifyWithGFormat (f fmt v) (isNumber v) (isInteger v) (isPositive v) w prefix padChar else - fun (fmt : string) (w : int) v -> + fun (fmt: string) (w: int) v -> GenericNumber.leftJustifyWithNonGFormat (f fmt v) (isNumber v) (isPositive v) w prefix padChar - let inline rightJustify f (prefixForPositives : string) padChar = + let inline rightJustify f (prefixForPositives: string) padChar = if padChar = '0' then - fun (fmt : string) (w : int) v -> + fun (fmt: string) (w: int) v -> GenericNumber.rightJustifyWithZeroAsPadChar (f fmt v) (isNumber v) (isPositive v) w prefixForPositives else System.Diagnostics.Debug.Assert((padChar = ' ')) - fun (fmt : string) (w : int) v -> + fun (fmt: string) (w: int) v -> GenericNumber.rightJustifyWithSpaceAsPadChar (f fmt v) (isNumber v) (isPositive v) w prefixForPositives - let isDecimalFormatSpecifier (spec : FormatSpecifier) = + let isDecimalFormatSpecifier (spec: FormatSpecifier) = spec.TypeChar = 'M' - let getPadAndPrefix allowZeroPadding (spec : FormatSpecifier) = + let getPadAndPrefix allowZeroPadding (spec: FormatSpecifier) = let padChar = if allowZeroPadding && isPadWithZeros spec.Flags then '0' else ' '; let prefix = if isPlusForPositives spec.Flags then "+" @@ -1019,57 +1020,57 @@ module internal PrintfImpl = else "" padChar, prefix - let isGFormat(spec : FormatSpecifier) = + let isGFormat(spec: FormatSpecifier) = isDecimalFormatSpecifier spec || System.Char.ToLower(spec.TypeChar) = 'g' - let inline basicWithPadding (spec : FormatSpecifier) f = + let inline basicWithPadding (spec: FormatSpecifier) f = let padChar, _ = getPadAndPrefix false spec Padding.withPadding spec f (Basic.leftJustify f padChar) (Basic.rightJustify f padChar) - let inline numWithPadding (spec : FormatSpecifier) isUnsigned f = + let inline numWithPadding (spec: FormatSpecifier) isUnsigned f = let allowZeroPadding = not (isLeftJustify spec.Flags) || isDecimalFormatSpecifier spec let padChar, prefix = getPadAndPrefix allowZeroPadding spec let isGFormat = isGFormat spec Padding.withPadding spec (GenericNumber.noJustification f prefix isUnsigned) (GenericNumber.leftJustify isGFormat f prefix padChar isUnsigned) (GenericNumber.rightJustify f prefix padChar isUnsigned) - let inline decimalWithPadding (spec : FormatSpecifier) getFormat defaultFormat f = + let inline decimalWithPadding (spec: FormatSpecifier) getFormat defaultFormat f = let padChar, prefix = getPadAndPrefix true spec let isGFormat = isGFormat spec Padding.withPaddingFormatted spec getFormat defaultFormat (GenericNumber.noJustificationWithFormat f prefix) (GenericNumber.leftJustifyWithFormat isGFormat f prefix padChar) (GenericNumber.rightJustifyWithFormat f prefix padChar) - let inline floatWithPadding (spec : FormatSpecifier) getFormat defaultFormat f = + let inline floatWithPadding (spec: FormatSpecifier) getFormat defaultFormat f = let padChar, prefix = getPadAndPrefix true spec let isGFormat = isGFormat spec Padding.withPaddingFormatted spec getFormat defaultFormat (Float.noJustification f prefix) (Float.leftJustify isGFormat f prefix padChar) (Float.rightJustify f prefix padChar) let inline identity v = v - let inline toString v = (^T : (member ToString : IFormatProvider -> string)(v, invariantCulture)) - let inline toFormattedString fmt = fun (v : ^T) -> (^T : (member ToString : string * IFormatProvider -> string)(v, fmt, invariantCulture)) + let inline toString v = (^T : (member ToString: IFormatProvider -> string)(v, invariantCulture)) + let inline toFormattedString fmt = fun (v: ^T) -> (^T: (member ToString: string * IFormatProvider -> string)(v, fmt, invariantCulture)) let inline numberToString c spec alt unsignedConv = if c = 'd' || c = 'i' then - numWithPadding spec false (alt >> toString : ^T -> string) + numWithPadding spec false (alt >> toString: ^T -> string) elif c = 'u' then - numWithPadding spec true (alt >> unsignedConv >> toString : ^T -> string) + numWithPadding spec true (alt >> unsignedConv >> toString: ^T -> string) elif c = 'x' then - numWithPadding spec true (alt >> toFormattedString "x" : ^T -> string) + numWithPadding spec true (alt >> toFormattedString "x": ^T -> string) elif c = 'X' then - numWithPadding spec true (alt >> toFormattedString "X" : ^T -> string ) + numWithPadding spec true (alt >> toFormattedString "X": ^T -> string ) elif c = 'o' then - numWithPadding spec true (fun (v : ^T) -> Convert.ToString(int64(unsignedConv (alt v)), 8)) + numWithPadding spec true (fun (v: ^T) -> Convert.ToString(int64(unsignedConv (alt v)), 8)) else raise (ArgumentException()) type ObjectPrinter = - static member ObjectToString<'T>(spec : FormatSpecifier) = - basicWithPadding spec (fun (v : 'T) -> match box v with null -> "" | x -> x.ToString()) + static member ObjectToString<'T>(spec: FormatSpecifier) = + basicWithPadding spec (fun (v: 'T) -> match box v with null -> "" | x -> x.ToString()) - static member GenericToStringCore(v : 'T, opts : Microsoft.FSharp.Text.StructuredPrintfImpl.FormatOptions, bindingFlags) = + static member GenericToStringCore(v: 'T, opts: Microsoft.FSharp.Text.StructuredPrintfImpl.FormatOptions, bindingFlags) = // printfn %0A is considered to mean 'print width zero' match box v with | null -> "" | _ -> Microsoft.FSharp.Text.StructuredPrintfImpl.Display.anyToStringForPrintf opts bindingFlags (v, v.GetType()) - static member GenericToString<'T>(spec : FormatSpecifier) = + static member GenericToString<'T>(spec: FormatSpecifier) = let bindingFlags = #if FX_RESHAPED_REFLECTION isPlusForPositives spec.Flags // true - show non-public @@ -1089,65 +1090,65 @@ module internal PrintfImpl = else o match spec.IsStarWidth, spec.IsStarPrecision with | true, true -> - box (fun (v : 'T) (width : int) (prec : int) -> + box (fun (v: 'T) (width: int) (prec: int) -> let opts = { opts with PrintSize = prec } let opts = if not useZeroWidth then { opts with PrintWidth = width} else opts ObjectPrinter.GenericToStringCore(v, opts, bindingFlags) ) | true, false -> - box (fun (v : 'T) (width : int) -> + box (fun (v: 'T) (width: int) -> let opts = if not useZeroWidth then { opts with PrintWidth = width} else opts ObjectPrinter.GenericToStringCore(v, opts, bindingFlags) ) | false, true -> - box (fun (v : 'T) (prec : int) -> + box (fun (v: 'T) (prec: int) -> let opts = { opts with PrintSize = prec } ObjectPrinter.GenericToStringCore(v, opts, bindingFlags) ) | false, false -> - box (fun (v : 'T) -> + box (fun (v: 'T) -> ObjectPrinter.GenericToStringCore(v, opts, bindingFlags) ) - let basicNumberToString (ty : Type) (spec : FormatSpecifier) = + let basicNumberToString (ty: Type) (spec: FormatSpecifier) = System.Diagnostics.Debug.Assert(not spec.IsPrecisionSpecified, "not spec.IsPrecisionSpecified") let ch = spec.TypeChar match Type.GetTypeCode(ty) with - | TypeCode.Int32 -> numberToString ch spec identity (uint32 : int -> uint32) - | TypeCode.Int64 -> numberToString ch spec identity (uint64 : int64 -> uint64) - | TypeCode.Byte -> numberToString ch spec identity (byte : byte -> byte) - | TypeCode.SByte -> numberToString ch spec identity (byte : sbyte -> byte) - | TypeCode.Int16 -> numberToString ch spec identity (uint16 : int16 -> uint16) - | TypeCode.UInt16 -> numberToString ch spec identity (uint16 : uint16 -> uint16) - | TypeCode.UInt32 -> numberToString ch spec identity (uint32 : uint32 -> uint32) - | TypeCode.UInt64 -> numberToString ch spec identity (uint64 : uint64 -> uint64) + | TypeCode.Int32 -> numberToString ch spec identity (uint32: int -> uint32) + | TypeCode.Int64 -> numberToString ch spec identity (uint64: int64 -> uint64) + | TypeCode.Byte -> numberToString ch spec identity (byte: byte -> byte) + | TypeCode.SByte -> numberToString ch spec identity (byte: sbyte -> byte) + | TypeCode.Int16 -> numberToString ch spec identity (uint16: int16 -> uint16) + | TypeCode.UInt16 -> numberToString ch spec identity (uint16: uint16 -> uint16) + | TypeCode.UInt32 -> numberToString ch spec identity (uint32: uint32 -> uint32) + | TypeCode.UInt64 -> numberToString ch spec identity (uint64: uint64 -> uint64) | _ -> if ty === typeof then if IntPtr.Size = 4 then - numberToString ch spec (fun (v : IntPtr) -> v.ToInt32()) uint32 + numberToString ch spec (fun (v: IntPtr) -> v.ToInt32()) uint32 else - numberToString ch spec (fun (v : IntPtr) -> v.ToInt64()) uint64 + numberToString ch spec (fun (v: IntPtr) -> v.ToInt64()) uint64 elif ty === typeof then if IntPtr.Size = 4 then - numberToString ch spec (fun (v : UIntPtr) -> v.ToUInt32()) uint32 + numberToString ch spec (fun (v: UIntPtr) -> v.ToUInt32()) uint32 else - numberToString ch spec (fun (v : UIntPtr) -> v.ToUInt64()) uint64 + numberToString ch spec (fun (v: UIntPtr) -> v.ToUInt64()) uint64 else raise (ArgumentException(ty.Name + " not a basic integer type")) let basicFloatToString ty spec = let defaultFormat = getFormatForFloat spec.TypeChar DefaultPrecision match Type.GetTypeCode(ty) with - | TypeCode.Single -> floatWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v : float32) -> toFormattedString fmt v) - | TypeCode.Double -> floatWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v : float) -> toFormattedString fmt v) - | TypeCode.Decimal -> decimalWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v : decimal) -> toFormattedString fmt v) + | TypeCode.Single -> floatWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v: float32) -> toFormattedString fmt v) + | TypeCode.Double -> floatWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v: float) -> toFormattedString fmt v) + | TypeCode.Decimal -> decimalWithPadding spec (getFormatForFloat spec.TypeChar) defaultFormat (fun fmt (v: decimal) -> toFormattedString fmt v) | _ -> raise (ArgumentException(ty.Name + " not a basic floating point type")) let private NonPublicStatics = BindingFlags.NonPublic ||| BindingFlags.Static - let private getValueConverter (ty : Type) (spec : FormatSpecifier) : obj = + let private getValueConverter (ty: Type) (spec: FormatSpecifier) : obj = match spec.TypeChar with | 'b' -> System.Diagnostics.Debug.Assert(ty === typeof, "ty === typeof") @@ -1157,10 +1158,10 @@ module internal PrintfImpl = basicWithPadding spec stringToSafeString | 'c' -> System.Diagnostics.Debug.Assert(ty === typeof, "ty === typeof") - basicWithPadding spec (fun (c : char) -> c.ToString()) + basicWithPadding spec (fun (c: char) -> c.ToString()) | 'M' -> System.Diagnostics.Debug.Assert(ty === typeof, "ty === typeof") - decimalWithPadding spec (fun _ -> "G") "G" (fun fmt (v : decimal) -> toFormattedString fmt v) // %M ignores precision + decimalWithPadding spec (fun _ -> "G") "G" (fun fmt (v: decimal) -> toFormattedString fmt v) // %M ignores precision | 'd' | 'i' | 'x' | 'X' | 'u' | 'o'-> basicNumberToString ty spec | 'e' | 'E' @@ -1178,10 +1179,10 @@ module internal PrintfImpl = | _ -> raise (ArgumentException(SR.GetString(SR.printfBadFormatSpecifier))) - let extractCurriedArguments (ty : Type) n = + let extractCurriedArguments (ty: Type) n = System.Diagnostics.Debug.Assert(n = 1 || n = 2 || n = 3, "n = 1 || n = 2 || n = 3") let buf = Array.zeroCreate (n + 1) - let rec go (ty : Type) i = + let rec go (ty: Type) i = if i < n then match ty.GetGenericArguments() with | [| argTy; retTy|] -> @@ -1198,7 +1199,7 @@ module internal PrintfImpl = let args = Stack(10) let types = Stack(5) - let stackToArray size start count (s : Stack<_>) = + let stackToArray size start count (s: Stack<_>) = let arr = Array.zeroCreate size for i = 0 to count - 1 do arr.[start + i] <- s.Pop() @@ -1224,7 +1225,7 @@ module internal PrintfImpl = member __.PopValueUnsafe() = args.Pop() - member this.PushContinuationWithType (cont : obj, contTy : Type) = + member this.PushContinuationWithType (cont: obj, contTy: Type) = System.Diagnostics.Debug.Assert(this.IsEmpty, "this.IsEmpty") System.Diagnostics.Debug.Assert( ( @@ -1236,10 +1237,10 @@ module internal PrintfImpl = this.PushArgumentWithType(cont, contTy) - member __.PushArgument(value : obj) = + member __.PushArgument(value: obj) = args.Push value - member __.PushArgumentWithType(value : obj, ty) = + member __.PushArgumentWithType(value: obj, ty) = args.Push value types.Push ty @@ -1259,12 +1260,12 @@ module internal PrintfImpl = let mutable count = 0 let mutable optimizedArgCount = 0 #if DEBUG - let verifyMethodInfoWasTaken (mi : System.Reflection.MemberInfo) = + let verifyMethodInfoWasTaken (mi: System.Reflection.MemberInfo) = if isNull mi then ignore (System.Diagnostics.Debugger.Launch()) #endif - let buildSpecialChained(spec : FormatSpecifier, argTys : Type[], prefix : string, tail : obj, retTy) = + let buildSpecialChained(spec: FormatSpecifier, argTys: Type[], prefix: string, tail: obj, retTy) = if spec.TypeChar = 'a' then let mi = typeof>.GetMethod("LittleAChained", NonPublicStatics) #if DEBUG @@ -1304,7 +1305,7 @@ module internal PrintfImpl = let mi = mi.MakeGenericMethod argTypes mi.Invoke(null, args) - let buildSpecialFinal(spec : FormatSpecifier, argTys : Type[], prefix : string, suffix : string) = + let buildSpecialFinal(spec: FormatSpecifier, argTys: Type[], prefix: string, suffix: string) = if spec.TypeChar = 'a' then let mi = typeof>.GetMethod("LittleAFinal", NonPublicStatics) #if DEBUG @@ -1343,7 +1344,7 @@ module internal PrintfImpl = mi.Invoke(null, args) - let buildPlainFinal(args : obj[], argTypes : Type[]) = + let buildPlainFinal(args: obj[], argTypes: Type[]) = let argsCount = args.Length let methodName,args = if argsCount > 0 && args.[0].ToString() = "" then @@ -1368,7 +1369,7 @@ module internal PrintfImpl = let mi = mi.MakeGenericMethod(argTypes) mi.Invoke(null, args) - let buildPlainChained(args : obj[], argTypes : Type[]) = + let buildPlainChained(args: obj[], argTypes: Type[]) = let argsCount = args.Length let methodName,args = if argsCount > 0 && args.[0].ToString() = "" then @@ -1407,7 +1408,7 @@ module internal PrintfImpl = else buildPlainFinal(plainArgs, plainTypes) - let rec parseFromFormatSpecifier (prefix : string) (s : string) (funcTy : Type) i : int = + let rec parseFromFormatSpecifier (prefix: string) (s: string) (funcTy: Type) i: int = if i >= s.Length then 0 else @@ -1499,11 +1500,11 @@ module internal PrintfImpl = else numberOfArgs + 1 - let parseFormatString (s : string) (funcTy : System.Type) : obj = + let parseFormatString (s: string) (funcTy: System.Type) : obj = optimizedArgCount <- 0 let prefixPos, prefix = FormatString.findNextFormatSpecifier s 0 if prefixPos = s.Length then - box (fun (env : unit -> PrintfEnv<'S, 'Re, 'Res>) -> + box (fun (env: unit -> PrintfEnv<'S, 'Re, 'Res>) -> let env = env() env.Write prefix env.Finish() @@ -1516,7 +1517,7 @@ module internal PrintfImpl = else buildPlain n prefix - member __.Build<'T>(s : string) : PrintfFactory<'S, 'Re, 'Res, 'T> * int = + member __.Build<'T>(s: string) : PrintfFactory<'S, 'Re, 'Res, 'T> * int = parseFormatString s typeof<'T> :?> _, (2 * count + 1) - optimizedArgCount // second component is used in SprintfEnv as value for internal buffer /// Type of element that is stored in cache @@ -1531,13 +1532,13 @@ module internal PrintfImpl = static let generate(fmt) = PrintfBuilder<'State, 'Residue, 'Result>().Build<'T>(fmt) static let mutable map = System.Collections.Concurrent.ConcurrentDictionary>() static let getOrAddFunc = Func<_, _>(generate) - static let get(key : string) = map.GetOrAdd(key, getOrAddFunc) + static let get(key: string) = map.GetOrAdd(key, getOrAddFunc) [] [] - static val mutable private last : string * CachedItem<'T, 'State, 'Residue, 'Result> + static val mutable private last: string * CachedItem<'T, 'State, 'Residue, 'Result> - static member Get(key : Format<'T, 'State, 'Residue, 'Result>) = + static member Get(key: Format<'T, 'State, 'Residue, 'Result>) = if not (Cache<'T, 'State, 'Residue, 'Result>.last === null) && key.Value.Equals (fst Cache<'T, 'State, 'Residue, 'Result>.last) then snd Cache<'T, 'State, 'Residue, 'Result>.last @@ -1549,11 +1550,11 @@ module internal PrintfImpl = type StringPrintfEnv<'Result>(k, n) = inherit PrintfEnv(()) - let buf : string[] = Array.zeroCreate n + let buf: string[] = Array.zeroCreate n let mutable ptr = 0 override __.Finish() : 'Result = k (String.Concat(buf)) - override __.Write(s : string) = + override __.Write(s: string) = buf.[ptr] <- s ptr <- ptr + 1 override __.WriteT(s) = @@ -1566,19 +1567,19 @@ module internal PrintfImpl = let mutable c = null override __.Finish() : 'Result = k c - override __.Write(s : string) = if isNull c then c <- s else c <- c + s + override __.Write(s: string) = if isNull c then c <- s else c <- c + s override __.WriteT(s) = if isNull c then c <- s else c <- c + s type StringBuilderPrintfEnv<'Result>(k, buf) = inherit PrintfEnv(buf) override __.Finish() : 'Result = k () - override __.Write(s : string) = ignore(buf.Append(s)) + override __.Write(s: string) = ignore(buf.Append(s)) override __.WriteT(()) = () - type TextWriterPrintfEnv<'Result>(k, tw : IO.TextWriter) = + type TextWriterPrintfEnv<'Result>(k, tw: IO.TextWriter) = inherit PrintfEnv(tw) override __.Finish() : 'Result = k() - override __.Write(s : string) = tw.Write s + override __.Write(s: string) = tw.Write s override __.WriteT(()) = () let inline doPrintf fmt f = @@ -1602,7 +1603,7 @@ module Printf = type TextWriterFormat<'T> = TextWriterFormat<'T,unit> [] - let ksprintf continuation (format : StringFormat<'T, 'Result>) : 'T = + let ksprintf continuation (format: StringFormat<'T, 'Result>) : 'T = doPrintf format (fun n -> if n <= 2 then SmallStringPrintfEnv(continuation) :> PrintfEnv<_, _, _> @@ -1611,7 +1612,7 @@ module Printf = ) [] - let sprintf (format : StringFormat<'T>) = + let sprintf (format: StringFormat<'T>) = doPrintf format (fun n -> if n <= 2 then SmallStringPrintfEnv(id) :> PrintfEnv<_, _, _> diff --git a/src/fsharp/FSharp.Core/quotations.fs b/src/fsharp/FSharp.Core/quotations.fs index 7af4a9f7956..58d0ef293d9 100644 --- a/src/fsharp/FSharp.Core/quotations.fs +++ b/src/fsharp/FSharp.Core/quotations.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. namespace Microsoft.FSharp.Quotations @@ -18,7 +18,7 @@ open Microsoft.FSharp.Text.StructuredPrintfImpl open Microsoft.FSharp.Text.StructuredPrintfImpl.LayoutOps open Microsoft.FSharp.Text.StructuredPrintfImpl.TaggedTextOps -#nowarn "52" // The value has been copied to ensure the original is not mutated by this operation +#nowarn "52" // The value has been copied to ensure the original is not mutated by this operation #if FX_RESHAPED_REFLECTION open PrimReflectionAdapters @@ -29,29 +29,29 @@ open ReflectionAdapters // RAW quotations - basic data types //-------------------------------------------------------------------------- -module Helpers = +module Helpers = let qOneOrMoreRLinear q inp = - let rec queryAcc rvs e = - match q e with - | Some(v,body) -> queryAcc (v::rvs) body - | None -> - match rvs with + let rec queryAcc rvs e = + match q e with + | Some(v, body) -> queryAcc (v::rvs) body + | None -> + match rvs with | [] -> None - | _ -> Some(List.rev rvs,e) - queryAcc [] inp + | _ -> Some(List.rev rvs, e) + queryAcc [] inp let qOneOrMoreLLinear q inp = - let rec queryAcc e rvs = - match q e with - | Some(body,v) -> queryAcc body (v::rvs) - | None -> - match rvs with + let rec queryAcc e rvs = + match q e with + | Some(body, v) -> queryAcc body (v::rvs) + | None -> + match rvs with | [] -> None - | _ -> Some(e,rvs) + | _ -> Some(e, rvs) queryAcc inp [] - let mkRLinear mk (vs,body) = List.foldBack (fun v acc -> mk(v,acc)) vs body - let mkLLinear mk (body,vs) = List.fold (fun acc v -> mk(acc,v)) body vs + let mkRLinear mk (vs, body) = List.foldBack (fun v acc -> mk(v, acc)) vs body + let mkLLinear mk (body, vs) = List.fold (fun acc v -> mk(acc, v)) body vs let staticBindingFlags = BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.DeclaredOnly let staticOrInstanceBindingFlags = BindingFlags.Instance ||| BindingFlags.Static ||| BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.DeclaredOnly @@ -62,7 +62,7 @@ module Helpers = let publicOrPrivateBindingFlags = BindingFlags.Public ||| BindingFlags.NonPublic #endif - let isDelegateType (typ:Type) = + let isDelegateType (typ:Type) = if typ.IsSubclassOf(typeof) then match typ.GetMethod("Invoke", instanceBindingFlags) with | null -> false @@ -70,16 +70,16 @@ module Helpers = else false - let getDelegateInvoke ty = + let getDelegateInvoke ty = if not (isDelegateType(ty)) then invalidArg "ty" (SR.GetString(SR.delegateExpected)) ty.GetMethod("Invoke", instanceBindingFlags) - let inline checkNonNull argName (v: 'T) = - match box v with - | null -> nullArg argName + let inline checkNonNull argName (v: 'T) = + match box v with + | null -> nullArg argName | _ -> () - + let getTypesFromParamInfos (infos : ParameterInfo[]) = infos |> Array.map (fun pi -> pi.ParameterType) open Helpers @@ -87,7 +87,7 @@ open Helpers [] [] -[] +[] type Var(name: string, typ:Type, ?isMutable: bool) = inherit obj() @@ -95,70 +95,70 @@ type Var(name: string, typ:Type, ?isMutable: bool) = let mutable lastStamp = -1L // first value retrieved will be 0 fun () -> System.Threading.Interlocked.Increment &lastStamp - static let globals = new Dictionary<(string*Type),Var>(11) + static let globals = new Dictionary<(string*Type), Var>(11) let stamp = getStamp () let isMutable = defaultArg isMutable false - + member v.Name = name member v.IsMutable = isMutable member v.Type = typ member v.Stamp = stamp - - static member Global(name,typ: Type) = + + static member Global(name, typ: Type) = checkNonNull "name" name checkNonNull "typ" typ - lock globals (fun () -> + lock globals (fun () -> let mutable res = Unchecked.defaultof - let ok = globals.TryGetValue((name,typ),&res) + let ok = globals.TryGetValue((name, typ), &res) if ok then res else - let res = new Var(name,typ) - globals.[(name,typ)] <- res + let res = new Var(name, typ) + globals.[(name, typ)] <- res res) override v.ToString() = name override v.GetHashCode() = base.GetHashCode() - override v.Equals(obj:obj) = - match obj with - | :? Var as v2 -> System.Object.ReferenceEquals(v,v2) + override v.Equals(obj:obj) = + match obj with + | :? Var as v2 -> System.Object.ReferenceEquals(v, v2) | _ -> false - interface System.IComparable with - member v.CompareTo(obj:obj) = - match obj with - | :? Var as v2 -> - if System.Object.ReferenceEquals(v,v2) then 0 else - let c = compare v.Name v2.Name - if c <> 0 then c else + interface System.IComparable with + member v.CompareTo(obj:obj) = + match obj with + | :? Var as v2 -> + if System.Object.ReferenceEquals(v, v2) then 0 else + let c = compare v.Name v2.Name + if c <> 0 then c else #if !FX_NO_REFLECTION_METADATA_TOKENS // not available on Compact Framework - let c = compare v.Type.MetadataToken v2.Type.MetadataToken - if c <> 0 then c else - let c = compare v.Type.Module.MetadataToken v2.Type.Module.MetadataToken - if c <> 0 then c else + let c = compare v.Type.MetadataToken v2.Type.MetadataToken + if c <> 0 then c else + let c = compare v.Type.Module.MetadataToken v2.Type.Module.MetadataToken + if c <> 0 then c else #endif - let c = compare v.Type.Assembly.FullName v2.Type.Assembly.FullName - if c <> 0 then c else + let c = compare v.Type.Assembly.FullName v2.Type.Assembly.FullName + if c <> 0 then c else compare v.Stamp v2.Stamp | _ -> 0 -/// Represents specifications of a subset of F# expressions +/// Represents specifications of a subset of F# expressions [] type Tree = | CombTerm of ExprConstInfo * Expr list | VarTerm of Var - | LambdaTerm of Var * Expr + | LambdaTerm of Var * Expr | HoleTerm of Type * int -and +and [] - ExprConstInfo = + ExprConstInfo = | AppOp - | IfThenElseOp - | LetRecOp - | LetRecCombOp - | LetOp + | IfThenElseOp + | LetRecOp + | LetRecCombOp + | LetOp | NewRecordOp of Type | NewUnionCaseOp of UnionCaseInfo | UnionCaseTestOp of UnionCaseInfo @@ -172,56 +172,56 @@ and | StaticFieldGetOp of FieldInfo | InstanceFieldSetOp of FieldInfo | StaticFieldSetOp of FieldInfo - | NewObjectOp of ConstructorInfo - | InstanceMethodCallOp of MethodInfo - | StaticMethodCallOp of MethodInfo + | NewObjectOp of ConstructorInfo + | InstanceMethodCallOp of MethodInfo + | StaticMethodCallOp of MethodInfo | CoerceOp of Type | NewArrayOp of Type | NewDelegateOp of Type | QuoteOp of bool - | SequentialOp - | AddressOfOp + | SequentialOp + | AddressOfOp | VarSetOp - | AddressSetOp + | AddressSetOp | TypeTestOp of Type - | TryWithOp - | TryFinallyOp - | ForIntegerRangeLoopOp - | WhileLoopOp + | TryWithOp + | TryFinallyOp + | ForIntegerRangeLoopOp + | WhileLoopOp // Arbitrary spliced values - not serialized | ValueOp of obj * Type * string option - | WithValueOp of obj * Type + | WithValueOp of obj * Type | DefaultValueOp of Type - + and [] - Expr(term:Tree,attribs:Expr list) = + Expr(term:Tree, attribs:Expr list) = member x.Tree = term - member x.CustomAttributes = attribs + member x.CustomAttributes = attribs - override x.Equals(obj) = - match obj with - | :? Expr as y -> - let rec eq t1 t2 = - match t1, t2 with + override x.Equals(obj) = + match obj with + | :? Expr as y -> + let rec eq t1 t2 = + match t1, t2 with // We special-case ValueOp to ensure that ValueWithName = Value - | CombTerm(ValueOp(v1,ty1,_),[]),CombTerm(ValueOp(v2,ty2,_),[]) -> (v1 = v2) && (ty1 = ty2) - | CombTerm(c1, es1), CombTerm(c2,es2) -> c1 = c2 && es1.Length = es2.Length && (es1 = es2) + | CombTerm(ValueOp(v1, ty1, _), []), CombTerm(ValueOp(v2, ty2, _), []) -> (v1 = v2) && (ty1 = ty2) + | CombTerm(c1, es1), CombTerm(c2, es2) -> c1 = c2 && es1.Length = es2.Length && (es1 = es2) | VarTerm v1, VarTerm v2 -> (v1 = v2) - | LambdaTerm (v1,e1), LambdaTerm(v2,e2) -> (v1 = v2) && (e1 = e2) - | HoleTerm (ty1,n1), HoleTerm(ty2,n2) -> (ty1 = ty2) && (n1 = n2) + | LambdaTerm (v1, e1), LambdaTerm(v2, e2) -> (v1 = v2) && (e1 = e2) + | HoleTerm (ty1, n1), HoleTerm(ty2, n2) -> (ty1 = ty2) && (n1 = n2) | _ -> false eq x.Tree y.Tree | _ -> false - override x.GetHashCode() = - x.Tree.GetHashCode() + override x.GetHashCode() = + x.Tree.GetHashCode() override x.ToString() = x.ToString(false) - member x.ToString(full) = + member x.ToString(full) = Microsoft.FSharp.Text.StructuredPrintfImpl.Display.layout_to_string Microsoft.FSharp.Text.StructuredPrintfImpl.FormatOptions.Default (x.GetLayout(full)) - - member x.GetLayout(long) = + + member x.GetLayout(long) = let expr (e:Expr ) = e.GetLayout(long) let exprs (es:Expr list) = es |> List.map expr let parens ls = bracketL (commaListL ls) @@ -231,137 +231,137 @@ and [] let combL nm ls = combTaggedL (tagKeyword nm) ls let noneL = wordL (tagProperty "None") let someL e = combTaggedL (tagMethod "Some") [expr e] - let typeL (o: Type) = wordL (tagClass (if long then o.FullName else o.Name)) - let objL (o: 'T) = wordL (tagText (sprintf "%A" o)) + let typeL (o: Type) = wordL (tagClass (if long then o.FullName else o.Name)) + let objL (o: 'T) = wordL (tagText (sprintf "%A" o)) let varL (v:Var) = wordL (tagLocal v.Name) let (|E|) (e: Expr) = e.Tree - let (|Lambda|_|) (E x) = match x with LambdaTerm(a,b) -> Some (a,b) | _ -> None + let (|Lambda|_|) (E x) = match x with LambdaTerm(a, b) -> Some (a, b) | _ -> None let (|IteratedLambda|_|) (e: Expr) = qOneOrMoreRLinear (|Lambda|_|) e - let ucaseL (unionCase:UnionCaseInfo) = (if long then objL unionCase else wordL (tagUnionCase unionCase.Name)) - let minfoL (minfo: MethodInfo) = if long then objL minfo else wordL (tagMethod minfo.Name) + let ucaseL (unionCase:UnionCaseInfo) = (if long then objL unionCase else wordL (tagUnionCase unionCase.Name)) + let minfoL (minfo: MethodInfo) = if long then objL minfo else wordL (tagMethod minfo.Name) let cinfoL (cinfo: ConstructorInfo) = if long then objL cinfo else wordL (tagMethod cinfo.DeclaringType.Name) let pinfoL (pinfo: PropertyInfo) = if long then objL pinfo else wordL (tagProperty pinfo.Name) let finfoL (finfo: FieldInfo) = if long then objL finfo else wordL (tagField finfo.Name) - let rec (|NLambdas|_|) n (e:Expr) = - match e with - | _ when n <= 0 -> Some([],e) - | Lambda(v,NLambdas ((-) n 1) (vs,b)) -> Some(v::vs,b) + let rec (|NLambdas|_|) n (e:Expr) = + match e with + | _ when n <= 0 -> Some([], e) + | Lambda(v, NLambdas ((-) n 1) (vs, b)) -> Some(v::vs, b) | _ -> None - match x.Tree with - | CombTerm(AppOp,args) -> combL "Application" (exprs args) - | CombTerm(IfThenElseOp,args) -> combL "IfThenElse" (exprs args) - | CombTerm(LetRecOp,[IteratedLambda(vs,E(CombTerm(LetRecCombOp,b2::bs)))]) -> combL "LetRecursive" [listL (List.map2 pairL (List.map varL vs) (exprs bs) ); b2.GetLayout(long)] - | CombTerm(LetOp,[e;E(LambdaTerm(v,b))]) -> combL "Let" [varL v; e.GetLayout(long); b.GetLayout(long)] - | CombTerm(NewRecordOp(ty),args) -> combL "NewRecord" (typeL ty :: exprs args) - | CombTerm(NewUnionCaseOp(unionCase),args) -> combL "NewUnionCase" (ucaseL unionCase :: exprs args) - | CombTerm(UnionCaseTestOp(unionCase),args) -> combL "UnionCaseTest" (exprs args@ [ucaseL unionCase]) - | CombTerm(NewTupleOp _,args) -> combL "NewTuple" (exprs args) - | CombTerm(TupleGetOp (_,i),[arg]) -> combL "TupleGet" ([expr arg] @ [objL i]) - | CombTerm(ValueOp(v,_,Some nm),[]) -> combL "ValueWithName" [objL v; wordL (tagLocal nm)] - | CombTerm(ValueOp(v,_,None),[]) -> combL "Value" [objL v] - | CombTerm(WithValueOp(v,_),[defn]) -> combL "WithValue" [objL v; expr defn] - | CombTerm(InstanceMethodCallOp(minfo),obj::args) -> combL "Call" [someL obj; minfoL minfo; listL (exprs args)] - | CombTerm(StaticMethodCallOp(minfo),args) -> combL "Call" [noneL; minfoL minfo; listL (exprs args)] - | CombTerm(InstancePropGetOp(pinfo),(obj::args)) -> combL "PropertyGet" [someL obj; pinfoL pinfo; listL (exprs args)] - | CombTerm(StaticPropGetOp(pinfo),args) -> combL "PropertyGet" [noneL; pinfoL pinfo; listL (exprs args)] - | CombTerm(InstancePropSetOp(pinfo),(obj::args)) -> combL "PropertySet" [someL obj; pinfoL pinfo; listL (exprs args)] - | CombTerm(StaticPropSetOp(pinfo),args) -> combL "PropertySet" [noneL; pinfoL pinfo; listL (exprs args)] - | CombTerm(InstanceFieldGetOp(finfo),[obj]) -> combL "FieldGet" [someL obj; finfoL finfo] - | CombTerm(StaticFieldGetOp(finfo),[]) -> combL "FieldGet" [noneL; finfoL finfo] - | CombTerm(InstanceFieldSetOp(finfo),[obj;v]) -> combL "FieldSet" [someL obj; finfoL finfo; expr v;] - | CombTerm(StaticFieldSetOp(finfo),[v]) -> combL "FieldSet" [noneL; finfoL finfo; expr v;] - | CombTerm(CoerceOp(ty),[arg]) -> combL "Coerce" [ expr arg; typeL ty] - | CombTerm(NewObjectOp cinfo,args) -> combL "NewObject" ([ cinfoL cinfo ] @ exprs args) - | CombTerm(DefaultValueOp(ty),args) -> combL "DefaultValue" ([ typeL ty ] @ exprs args) - | CombTerm(NewArrayOp(ty),args) -> combL "NewArray" ([ typeL ty ] @ exprs args) - | CombTerm(TypeTestOp(ty),args) -> combL "TypeTest" ([ typeL ty] @ exprs args) - | CombTerm(AddressOfOp,args) -> combL "AddressOf" (exprs args) - | CombTerm(VarSetOp,[E(VarTerm(v)); e]) -> combL "VarSet" [varL v; expr e] - | CombTerm(AddressSetOp,args) -> combL "AddressSet" (exprs args) - | CombTerm(ForIntegerRangeLoopOp,[e1;e2;E(LambdaTerm(v,e3))]) -> combL "ForIntegerRangeLoop" [varL v; expr e1; expr e2; expr e3] - | CombTerm(WhileLoopOp,args) -> combL "WhileLoop" (exprs args) - | CombTerm(TryFinallyOp,args) -> combL "TryFinally" (exprs args) - | CombTerm(TryWithOp,[e1;Lambda(v1,e2);Lambda(v2,e3)]) -> combL "TryWith" [expr e1; varL v1; expr e2; varL v2; expr e3] - | CombTerm(SequentialOp,args) -> combL "Sequential" (exprs args) - | CombTerm(NewDelegateOp(ty),[e]) -> + match x.Tree with + | CombTerm(AppOp, args) -> combL "Application" (exprs args) + | CombTerm(IfThenElseOp, args) -> combL "IfThenElse" (exprs args) + | CombTerm(LetRecOp, [IteratedLambda(vs, E(CombTerm(LetRecCombOp, b2::bs)))]) -> combL "LetRecursive" [listL (List.map2 pairL (List.map varL vs) (exprs bs) ); b2.GetLayout(long)] + | CombTerm(LetOp, [e;E(LambdaTerm(v, b))]) -> combL "Let" [varL v; e.GetLayout(long); b.GetLayout(long)] + | CombTerm(NewRecordOp(ty), args) -> combL "NewRecord" (typeL ty :: exprs args) + | CombTerm(NewUnionCaseOp(unionCase), args) -> combL "NewUnionCase" (ucaseL unionCase :: exprs args) + | CombTerm(UnionCaseTestOp(unionCase), args) -> combL "UnionCaseTest" (exprs args@ [ucaseL unionCase]) + | CombTerm(NewTupleOp _, args) -> combL "NewTuple" (exprs args) + | CombTerm(TupleGetOp (_, i), [arg]) -> combL "TupleGet" ([expr arg] @ [objL i]) + | CombTerm(ValueOp(v, _, Some nm), []) -> combL "ValueWithName" [objL v; wordL (tagLocal nm)] + | CombTerm(ValueOp(v, _, None), []) -> combL "Value" [objL v] + | CombTerm(WithValueOp(v, _), [defn]) -> combL "WithValue" [objL v; expr defn] + | CombTerm(InstanceMethodCallOp(minfo), obj::args) -> combL "Call" [someL obj; minfoL minfo; listL (exprs args)] + | CombTerm(StaticMethodCallOp(minfo), args) -> combL "Call" [noneL; minfoL minfo; listL (exprs args)] + | CombTerm(InstancePropGetOp(pinfo), (obj::args)) -> combL "PropertyGet" [someL obj; pinfoL pinfo; listL (exprs args)] + | CombTerm(StaticPropGetOp(pinfo), args) -> combL "PropertyGet" [noneL; pinfoL pinfo; listL (exprs args)] + | CombTerm(InstancePropSetOp(pinfo), (obj::args)) -> combL "PropertySet" [someL obj; pinfoL pinfo; listL (exprs args)] + | CombTerm(StaticPropSetOp(pinfo), args) -> combL "PropertySet" [noneL; pinfoL pinfo; listL (exprs args)] + | CombTerm(InstanceFieldGetOp(finfo), [obj]) -> combL "FieldGet" [someL obj; finfoL finfo] + | CombTerm(StaticFieldGetOp(finfo), []) -> combL "FieldGet" [noneL; finfoL finfo] + | CombTerm(InstanceFieldSetOp(finfo), [obj;v]) -> combL "FieldSet" [someL obj; finfoL finfo; expr v;] + | CombTerm(StaticFieldSetOp(finfo), [v]) -> combL "FieldSet" [noneL; finfoL finfo; expr v;] + | CombTerm(CoerceOp(ty), [arg]) -> combL "Coerce" [ expr arg; typeL ty] + | CombTerm(NewObjectOp cinfo, args) -> combL "NewObject" ([ cinfoL cinfo ] @ exprs args) + | CombTerm(DefaultValueOp(ty), args) -> combL "DefaultValue" ([ typeL ty ] @ exprs args) + | CombTerm(NewArrayOp(ty), args) -> combL "NewArray" ([ typeL ty ] @ exprs args) + | CombTerm(TypeTestOp(ty), args) -> combL "TypeTest" ([ typeL ty] @ exprs args) + | CombTerm(AddressOfOp, args) -> combL "AddressOf" (exprs args) + | CombTerm(VarSetOp, [E(VarTerm(v)); e]) -> combL "VarSet" [varL v; expr e] + | CombTerm(AddressSetOp, args) -> combL "AddressSet" (exprs args) + | CombTerm(ForIntegerRangeLoopOp, [e1;e2;E(LambdaTerm(v, e3))]) -> combL "ForIntegerRangeLoop" [varL v; expr e1; expr e2; expr e3] + | CombTerm(WhileLoopOp, args) -> combL "WhileLoop" (exprs args) + | CombTerm(TryFinallyOp, args) -> combL "TryFinally" (exprs args) + | CombTerm(TryWithOp, [e1;Lambda(v1, e2);Lambda(v2, e3)]) -> combL "TryWith" [expr e1; varL v1; expr e2; varL v2; expr e3] + | CombTerm(SequentialOp, args) -> combL "Sequential" (exprs args) + | CombTerm(NewDelegateOp(ty), [e]) -> let nargs = (getDelegateInvoke ty).GetParameters().Length - if nargs = 0 then - match e with - | NLambdas 1 ([_],e) -> combL "NewDelegate" ([typeL ty] @ [expr e]) - | NLambdas 0 ([],e) -> combL "NewDelegate" ([typeL ty] @ [expr e]) + if nargs = 0 then + match e with + | NLambdas 1 ([_], e) -> combL "NewDelegate" ([typeL ty] @ [expr e]) + | NLambdas 0 ([], e) -> combL "NewDelegate" ([typeL ty] @ [expr e]) | _ -> combL "NewDelegate" [typeL ty; expr e] else - match e with - | NLambdas nargs (vs,e) -> combL "NewDelegate" ([typeL ty] @ (vs |> List.map varL) @ [expr e]) + match e with + | NLambdas nargs (vs, e) -> combL "NewDelegate" ([typeL ty] @ (vs |> List.map varL) @ [expr e]) | _ -> combL "NewDelegate" [typeL ty; expr e] - //| CombTerm(_,args) -> combL "??" (exprs args) - | VarTerm(v) -> wordL (tagLocal v.Name) - | LambdaTerm(v,b) -> combL "Lambda" [varL v; expr b] - | HoleTerm _ -> wordL (tagLocal "_") - | CombTerm(QuoteOp _,args) -> combL "Quote" (exprs args) + //| CombTerm(_, args) -> combL "??" (exprs args) + | VarTerm(v) -> wordL (tagLocal v.Name) + | LambdaTerm(v, b) -> combL "Lambda" [varL v; expr b] + | HoleTerm _ -> wordL (tagLocal "_") + | CombTerm(QuoteOp _, args) -> combL "Quote" (exprs args) | _ -> failwithf "Unexpected term in layout %A" x.Tree - + and [] - Expr<'T>(term:Tree,attribs) = - inherit Expr(term,attribs) + Expr<'T>(term:Tree, attribs) = + inherit Expr(term, attribs) member x.Raw = (x :> Expr) [] -module Patterns = +module Patterns = /// Internal type representing a deserialized object that is yet to be instantiated. Representation is /// as a computation. type Instantiable<'T> = (int -> Type) -> 'T - type ByteStream(bytes:byte[], initial:int, len:int) = - + type ByteStream(bytes:byte[], initial:int, len:int) = + let mutable pos = initial let lim = initial + len - - member b.ReadByte() = - if pos >= lim then failwith "end of stream"; + + member b.ReadByte() = + if pos >= lim then failwith "end of stream" let res = int32 bytes.[pos] - pos <- pos + 1; - res - - member b.ReadBytes n = - if pos + n > lim then failwith "ByteStream.ReadBytes: end of stream"; + pos <- pos + 1 + res + + member b.ReadBytes n = + if pos + n > lim then failwith "ByteStream.ReadBytes: end of stream" let res = bytes.[pos..pos+n-1] - pos <- pos + n; - res + pos <- pos + n + res - member b.ReadUtf8BytesAsString n = - let res = System.Text.Encoding.UTF8.GetString(bytes,pos,n) - pos <- pos + n; + member b.ReadUtf8BytesAsString n = + let res = System.Text.Encoding.UTF8.GetString(bytes, pos, n) + pos <- pos + n res - let E t = new Expr< >(t,[]) - let EA (t,attribs) = new Expr< >(t,attribs) + let E t = new Expr< >(t, []) + let EA (t, attribs) = new Expr< >(t, attribs) let ES ts = List.map E ts let (|E|) (e: Expr) = e.Tree let (|ES|) (es: list) = es |> List.map (fun e -> e.Tree) - let (|FrontAndBack|_|) es = + let (|FrontAndBack|_|) es = let rec loop acc xs = match xs with [] -> None | [h] -> Some (List.rev acc, h) | h::t -> loop (h::acc) t loop [] es - let funTyC = typeof<(obj -> obj)>.GetGenericTypeDefinition() + let funTyC = typeof<(obj -> obj)>.GetGenericTypeDefinition() let exprTyC = typedefof> let voidTy = typeof let unitTy = typeof let removeVoid a = if a = voidTy then unitTy else a let addVoid a = if a = unitTy then voidTy else a - let mkFunTy a b = + let mkFunTy a b = let (a, b) = removeVoid a, removeVoid b funTyC.MakeGenericType([| a;b |]) - let mkArrayTy (t:Type) = t.MakeArrayType(); + let mkArrayTy (t:Type) = t.MakeArrayType() let mkExprTy (t:Type) = exprTyC.MakeGenericType([| t |]) let rawExprTy = typeof @@ -370,560 +370,560 @@ module Patterns = // Active patterns for decomposing quotations //-------------------------------------------------------------------------- - let (|Comb0|_|) (E x) = match x with CombTerm(k,[]) -> Some(k) | _ -> None + let (|Comb0|_|) (E x) = match x with CombTerm(k, []) -> Some(k) | _ -> None - let (|Comb1|_|) (E x) = match x with CombTerm(k,[x]) -> Some(k,x) | _ -> None + let (|Comb1|_|) (E x) = match x with CombTerm(k, [x]) -> Some(k, x) | _ -> None - let (|Comb2|_|) (E x) = match x with CombTerm(k,[x1;x2]) -> Some(k,x1,x2) | _ -> None + let (|Comb2|_|) (E x) = match x with CombTerm(k, [x1;x2]) -> Some(k, x1, x2) | _ -> None + + let (|Comb3|_|) (E x) = match x with CombTerm(k, [x1;x2;x3]) -> Some(k, x1, x2, x3) | _ -> None - let (|Comb3|_|) (E x) = match x with CombTerm(k,[x1;x2;x3]) -> Some(k,x1,x2,x3) | _ -> None - [] - let (|Var|_|) (E x) = match x with VarTerm v -> Some v | _ -> None + let (|Var|_|) (E x) = match x with VarTerm v -> Some v | _ -> None [] - let (|Application|_|) input = match input with Comb2(AppOp,a,b) -> Some (a,b) | _ -> None + let (|Application|_|) input = match input with Comb2(AppOp, a, b) -> Some (a, b) | _ -> None [] - let (|Lambda|_|) (E x) = match x with LambdaTerm(a,b) -> Some (a,b) | _ -> None + let (|Lambda|_|) (E x) = match x with LambdaTerm(a, b) -> Some (a, b) | _ -> None [] - let (|Quote|_|) (E x) = match x with CombTerm(QuoteOp _,[a]) -> Some (a) | _ -> None + let (|Quote|_|) (E x) = match x with CombTerm(QuoteOp _, [a]) -> Some (a) | _ -> None [] - let (|QuoteRaw|_|) (E x) = match x with CombTerm(QuoteOp false,[a]) -> Some (a) | _ -> None + let (|QuoteRaw|_|) (E x) = match x with CombTerm(QuoteOp false, [a]) -> Some (a) | _ -> None [] - let (|QuoteTyped|_|) (E x) = match x with CombTerm(QuoteOp true,[a]) -> Some (a) | _ -> None + let (|QuoteTyped|_|) (E x) = match x with CombTerm(QuoteOp true, [a]) -> Some (a) | _ -> None [] - let (|IfThenElse|_|) input = match input with Comb3(IfThenElseOp,e1,e2,e3) -> Some(e1,e2,e3) | _ -> None + let (|IfThenElse|_|) input = match input with Comb3(IfThenElseOp, e1, e2, e3) -> Some(e1, e2, e3) | _ -> None [] - let (|NewTuple|_|) input = match input with E(CombTerm(NewTupleOp(_),es)) -> Some(es) | _ -> None + let (|NewTuple|_|) input = match input with E(CombTerm(NewTupleOp(_), es)) -> Some(es) | _ -> None [] - let (|DefaultValue|_|) input = match input with E(CombTerm(DefaultValueOp(ty),[])) -> Some(ty) | _ -> None + let (|DefaultValue|_|) input = match input with E(CombTerm(DefaultValueOp(ty), [])) -> Some(ty) | _ -> None [] - let (|NewRecord|_|) input = match input with E(CombTerm(NewRecordOp(x),es)) -> Some(x,es) | _ -> None + let (|NewRecord|_|) input = match input with E(CombTerm(NewRecordOp(x), es)) -> Some(x, es) | _ -> None [] - let (|NewUnionCase|_|) input = match input with E(CombTerm(NewUnionCaseOp(unionCase),es)) -> Some(unionCase,es) | _ -> None + let (|NewUnionCase|_|) input = match input with E(CombTerm(NewUnionCaseOp(unionCase), es)) -> Some(unionCase, es) | _ -> None [] - let (|UnionCaseTest|_|) input = match input with Comb1(UnionCaseTestOp(unionCase),e) -> Some(e,unionCase) | _ -> None + let (|UnionCaseTest|_|) input = match input with Comb1(UnionCaseTestOp(unionCase), e) -> Some(e, unionCase) | _ -> None [] - let (|TupleGet|_|) input = match input with Comb1(TupleGetOp(_,n),e) -> Some(e,n) | _ -> None + let (|TupleGet|_|) input = match input with Comb1(TupleGetOp(_, n), e) -> Some(e, n) | _ -> None [] - let (|Coerce|_|) input = match input with Comb1(CoerceOp ty,e1) -> Some(e1,ty) | _ -> None + let (|Coerce|_|) input = match input with Comb1(CoerceOp ty, e1) -> Some(e1, ty) | _ -> None [] - let (|TypeTest|_|) input = match input with Comb1(TypeTestOp ty,e1) -> Some(e1,ty) | _ -> None + let (|TypeTest|_|) input = match input with Comb1(TypeTestOp ty, e1) -> Some(e1, ty) | _ -> None [] - let (|NewArray|_|) input = match input with E(CombTerm(NewArrayOp ty,es)) -> Some(ty,es) | _ -> None + let (|NewArray|_|) input = match input with E(CombTerm(NewArrayOp ty, es)) -> Some(ty, es) | _ -> None [] - let (|AddressSet|_|) input = match input with E(CombTerm(AddressSetOp,[e;v])) -> Some(e,v) | _ -> None + let (|AddressSet|_|) input = match input with E(CombTerm(AddressSetOp, [e;v])) -> Some(e, v) | _ -> None [] - let (|TryFinally|_|) input = match input with E(CombTerm(TryFinallyOp,[e1;e2])) -> Some(e1,e2) | _ -> None + let (|TryFinally|_|) input = match input with E(CombTerm(TryFinallyOp, [e1;e2])) -> Some(e1, e2) | _ -> None [] - let (|TryWith|_|) input = match input with E(CombTerm(TryWithOp,[e1;Lambda(v1,e2);Lambda(v2,e3)])) -> Some(e1,v1,e2,v2,e3) | _ -> None + let (|TryWith|_|) input = match input with E(CombTerm(TryWithOp, [e1;Lambda(v1, e2);Lambda(v2, e3)])) -> Some(e1, v1, e2, v2, e3) | _ -> None [] - let (|VarSet|_| ) input = match input with E(CombTerm(VarSetOp,[E(VarTerm(v)); e])) -> Some(v,e) | _ -> None + let (|VarSet|_| ) input = match input with E(CombTerm(VarSetOp, [E(VarTerm(v)); e])) -> Some(v, e) | _ -> None [] - let (|Value|_|) input = match input with E(CombTerm(ValueOp (v,ty,_),_)) -> Some(v,ty) | _ -> None + let (|Value|_|) input = match input with E(CombTerm(ValueOp (v, ty, _), _)) -> Some(v, ty) | _ -> None [] - let (|ValueObj|_|) input = match input with E(CombTerm(ValueOp (v,_,_),_)) -> Some(v) | _ -> None + let (|ValueObj|_|) input = match input with E(CombTerm(ValueOp (v, _, _), _)) -> Some(v) | _ -> None [] - let (|ValueWithName|_|) input = - match input with - | E(CombTerm(ValueOp (v,ty,Some nm),_)) -> Some(v,ty,nm) + let (|ValueWithName|_|) input = + match input with + | E(CombTerm(ValueOp (v, ty, Some nm), _)) -> Some(v, ty, nm) | _ -> None [] - let (|WithValue|_|) input = - match input with - | E(CombTerm(WithValueOp (v,ty),[e])) -> Some(v,ty,e) + let (|WithValue|_|) input = + match input with + | E(CombTerm(WithValueOp (v, ty), [e])) -> Some(v, ty, e) | _ -> None [] - let (|AddressOf|_|) input = - match input with - | Comb1(AddressOfOp,e) -> Some(e) + let (|AddressOf|_|) input = + match input with + | Comb1(AddressOfOp, e) -> Some(e) | _ -> None [] - let (|Sequential|_|) input = - match input with - | Comb2(SequentialOp,e1,e2) -> Some(e1,e2) + let (|Sequential|_|) input = + match input with + | Comb2(SequentialOp, e1, e2) -> Some(e1, e2) | _ -> None [] - let (|ForIntegerRangeLoop|_|) input = - match input with - | Comb3(ForIntegerRangeLoopOp,e1,e2,Lambda(v, e3)) -> Some(v,e1,e2,e3) + let (|ForIntegerRangeLoop|_|) input = + match input with + | Comb3(ForIntegerRangeLoopOp, e1, e2, Lambda(v, e3)) -> Some(v, e1, e2, e3) | _ -> None [] - let (|WhileLoop|_|) input = - match input with - | Comb2(WhileLoopOp,e1,e2) -> Some(e1,e2) + let (|WhileLoop|_|) input = + match input with + | Comb2(WhileLoopOp, e1, e2) -> Some(e1, e2) | _ -> None [] - let (|PropertyGet|_|) input = - match input with - | E(CombTerm(StaticPropGetOp pinfo,args)) -> Some(None,pinfo,args) - | E(CombTerm(InstancePropGetOp pinfo,obj::args)) -> Some(Some(obj),pinfo,args) + let (|PropertyGet|_|) input = + match input with + | E(CombTerm(StaticPropGetOp pinfo, args)) -> Some(None, pinfo, args) + | E(CombTerm(InstancePropGetOp pinfo, obj::args)) -> Some(Some(obj), pinfo, args) | _ -> None [] - let (|PropertySet|_|) input = - match input with - | E(CombTerm(StaticPropSetOp pinfo, FrontAndBack(args,v))) -> Some(None,pinfo,args,v) - | E(CombTerm(InstancePropSetOp pinfo, obj::FrontAndBack(args,v))) -> Some(Some(obj),pinfo,args,v) + let (|PropertySet|_|) input = + match input with + | E(CombTerm(StaticPropSetOp pinfo, FrontAndBack(args, v))) -> Some(None, pinfo, args, v) + | E(CombTerm(InstancePropSetOp pinfo, obj::FrontAndBack(args, v))) -> Some(Some(obj), pinfo, args, v) | _ -> None [] - let (|FieldGet|_|) input = - match input with - | E(CombTerm(StaticFieldGetOp finfo,[])) -> Some(None,finfo) - | E(CombTerm(InstanceFieldGetOp finfo,[obj])) -> Some(Some(obj),finfo) + let (|FieldGet|_|) input = + match input with + | E(CombTerm(StaticFieldGetOp finfo, [])) -> Some(None, finfo) + | E(CombTerm(InstanceFieldGetOp finfo, [obj])) -> Some(Some(obj), finfo) | _ -> None [] - let (|FieldSet|_|) input = - match input with - | E(CombTerm(StaticFieldSetOp finfo,[v])) -> Some(None,finfo,v) - | E(CombTerm(InstanceFieldSetOp finfo,[obj;v])) -> Some(Some(obj),finfo,v) + let (|FieldSet|_|) input = + match input with + | E(CombTerm(StaticFieldSetOp finfo, [v])) -> Some(None, finfo, v) + | E(CombTerm(InstanceFieldSetOp finfo, [obj;v])) -> Some(Some(obj), finfo, v) | _ -> None [] - let (|NewObject|_|) input = - match input with - | E(CombTerm(NewObjectOp ty,e)) -> Some(ty,e) | _ -> None + let (|NewObject|_|) input = + match input with + | E(CombTerm(NewObjectOp ty, e)) -> Some(ty, e) | _ -> None [] - let (|Call|_|) input = - match input with - | E(CombTerm(StaticMethodCallOp minfo,args)) -> Some(None,minfo,args) - | E(CombTerm(InstanceMethodCallOp minfo,(obj::args))) -> Some(Some(obj),minfo,args) + let (|Call|_|) input = + match input with + | E(CombTerm(StaticMethodCallOp minfo, args)) -> Some(None, minfo, args) + | E(CombTerm(InstanceMethodCallOp minfo, (obj::args))) -> Some(Some(obj), minfo, args) | _ -> None - let (|LetRaw|_|) input = - match input with - | Comb2(LetOp,e1,e2) -> Some(e1,e2) + let (|LetRaw|_|) input = + match input with + | Comb2(LetOp, e1, e2) -> Some(e1, e2) | _ -> None - let (|LetRecRaw|_|) input = - match input with - | Comb1(LetRecOp,e1) -> Some(e1) + let (|LetRecRaw|_|) input = + match input with + | Comb1(LetRecOp, e1) -> Some(e1) | _ -> None [] - let (|Let|_|)input = - match input with - | LetRaw(e,Lambda(v,body)) -> Some(v,e,body) + let (|Let|_|)input = + match input with + | LetRaw(e, Lambda(v, body)) -> Some(v, e, body) | _ -> None - let (|IteratedLambda|_|) (e: Expr) = qOneOrMoreRLinear (|Lambda|_|) e + let (|IteratedLambda|_|) (e: Expr) = qOneOrMoreRLinear (|Lambda|_|) e - let rec (|NLambdas|_|) n (e:Expr) = - match e with - | _ when n <= 0 -> Some([],e) - | Lambda(v,NLambdas ((-) n 1) (vs,b)) -> Some(v::vs,b) + let rec (|NLambdas|_|) n (e:Expr) = + match e with + | _ when n <= 0 -> Some([], e) + | Lambda(v, NLambdas ((-) n 1) (vs, b)) -> Some(v::vs, b) | _ -> None [] - let (|NewDelegate|_|) input = - match input with - | Comb1(NewDelegateOp(ty),e) -> + let (|NewDelegate|_|) input = + match input with + | Comb1(NewDelegateOp(ty), e) -> let nargs = (getDelegateInvoke ty).GetParameters().Length - if nargs = 0 then - match e with - | NLambdas 1 ([_],e) -> Some(ty,[],e) // try to strip the unit parameter if there is one - | NLambdas 0 ([],e) -> Some(ty,[],e) + if nargs = 0 then + match e with + | NLambdas 1 ([_], e) -> Some(ty, [], e) // try to strip the unit parameter if there is one + | NLambdas 0 ([], e) -> Some(ty, [], e) | _ -> None else - match e with - | NLambdas nargs (vs,e) -> Some(ty,vs,e) + match e with + | NLambdas nargs (vs, e) -> Some(ty, vs, e) | _ -> None | _ -> None [] - let (|LetRecursive|_|) input = - match input with - | LetRecRaw(IteratedLambda(vs1,E(CombTerm(LetRecCombOp,body::es)))) -> Some(List.zip vs1 es,body) + let (|LetRecursive|_|) input = + match input with + | LetRecRaw(IteratedLambda(vs1, E(CombTerm(LetRecCombOp, body::es)))) -> Some(List.zip vs1 es, body) | _ -> None - + //-------------------------------------------------------------------------- // Getting the type of Raw quotations //-------------------------------------------------------------------------- // Returns record member specified by name - let getRecordProperty(ty,fieldName) = - let mems = FSharpType.GetRecordFields(ty,publicOrPrivateBindingFlags) + let getRecordProperty(ty, fieldName) = + let mems = FSharpType.GetRecordFields(ty, publicOrPrivateBindingFlags) match mems |> Array.tryFind (fun minfo -> minfo.Name = fieldName) with | Some (m) -> m | _ -> invalidArg "fieldName" (String.Format(SR.GetString(SR.QmissingRecordField), ty.FullName, fieldName)) - let getUnionCaseInfo(ty,unionCaseName) = - let cases = FSharpType.GetUnionCases(ty,publicOrPrivateBindingFlags) + let getUnionCaseInfo(ty, unionCaseName) = + let cases = FSharpType.GetUnionCases(ty, publicOrPrivateBindingFlags) match cases |> Array.tryFind (fun ucase -> ucase.Name = unionCaseName) with | Some(case) -> case | _ -> invalidArg "unionCaseName" (String.Format(SR.GetString(SR.QmissingUnionCase), ty.FullName, unionCaseName)) - - let getUnionCaseInfoField(unionCase:UnionCaseInfo,index) = - let fields = unionCase.GetFields() + + let getUnionCaseInfoField(unionCase:UnionCaseInfo, index) = + let fields = unionCase.GetFields() if index < 0 || index >= fields.Length then invalidArg "index" (SR.GetString(SR.QinvalidCaseIndex)) fields.[index] - + /// Returns type of lambda application - something like "(fun a -> ..) b" let rec typeOfAppliedLambda f = - let fty = ((typeOf f):Type) - match fty.GetGenericArguments() with + let fty = ((typeOf f):Type) + match fty.GetGenericArguments() with | [| _; b|] -> b - | _ -> raise <| System.InvalidOperationException (SR.GetString(SR.QillFormedAppOrLet)) + | _ -> raise <| System.InvalidOperationException (SR.GetString(SR.QillFormedAppOrLet)) /// Returns type of the Raw quotation or fails if the quotation is ill formed /// if 'verify' is true, verifies all branches, otherwise ignores some of them when not needed - and typeOf<'T when 'T :> Expr> (e : 'T) : Type = - let (E t) = e - match t with - | VarTerm v -> v.Type - | LambdaTerm (v,b) -> mkFunTy v.Type (typeOf b) - | HoleTerm (ty,_) -> ty - | CombTerm (c,args) -> - match c,args with - | AppOp,[f;_] -> typeOfAppliedLambda f - | LetOp,_ -> match e with Let(_,_,b) -> typeOf b | _ -> failwith "unreachable" - | IfThenElseOp,[_;t;_] -> typeOf t - | LetRecOp,_ -> match e with LetRecursive(_,b) -> typeOf b | _ -> failwith "unreachable" - | LetRecCombOp,_ -> failwith "typeOfConst: LetRecCombOp" - | NewRecordOp ty,_ -> ty - | NewUnionCaseOp unionCase,_ -> unionCase.DeclaringType - | UnionCaseTestOp _,_ -> typeof - | ValueOp (_, ty, _),_ -> ty - | WithValueOp (_, ty),_ -> ty - | TupleGetOp (ty,i),_ -> FSharpType.GetTupleElements(ty).[i] - | NewTupleOp ty,_ -> ty - | StaticPropGetOp prop,_ -> prop.PropertyType - | InstancePropGetOp prop,_ -> prop.PropertyType - | StaticPropSetOp _,_ -> typeof - | InstancePropSetOp _,_ -> typeof - | InstanceFieldGetOp fld,_ -> fld.FieldType - | StaticFieldGetOp fld,_ -> fld.FieldType - | InstanceFieldSetOp _,_ -> typeof - | StaticFieldSetOp _,_ -> typeof - | NewObjectOp ctor,_ -> ctor.DeclaringType - | InstanceMethodCallOp minfo,_ -> minfo.ReturnType |> removeVoid - | StaticMethodCallOp minfo,_ -> minfo.ReturnType |> removeVoid - | CoerceOp ty,_ -> ty - | SequentialOp,[_;b] -> typeOf b - | ForIntegerRangeLoopOp,_ -> typeof - | NewArrayOp ty,_ -> mkArrayTy ty - | NewDelegateOp ty,_ -> ty - | DefaultValueOp ty,_ -> ty - | TypeTestOp _,_ -> typeof - | QuoteOp true,[expr] -> mkExprTy (typeOf expr) - | QuoteOp false,[_] -> rawExprTy - | TryFinallyOp,[e1;_] -> typeOf e1 - | TryWithOp,[e1;_;_] -> typeOf e1 - | WhileLoopOp,_ - | VarSetOp,_ - | AddressSetOp,_ -> typeof - | AddressOfOp,[expr]-> (typeOf expr).MakeByRefType() - | (AddressOfOp | QuoteOp _ | SequentialOp | TryWithOp | TryFinallyOp | IfThenElseOp | AppOp),_ -> failwith "unreachable" + and typeOf<'T when 'T :> Expr> (e : 'T) : Type = + let (E t) = e + match t with + | VarTerm v -> v.Type + | LambdaTerm (v, b) -> mkFunTy v.Type (typeOf b) + | HoleTerm (ty, _) -> ty + | CombTerm (c, args) -> + match c, args with + | AppOp, [f;_] -> typeOfAppliedLambda f + | LetOp, _ -> match e with Let(_, _, b) -> typeOf b | _ -> failwith "unreachable" + | IfThenElseOp, [_;t;_] -> typeOf t + | LetRecOp, _ -> match e with LetRecursive(_, b) -> typeOf b | _ -> failwith "unreachable" + | LetRecCombOp, _ -> failwith "typeOfConst: LetRecCombOp" + | NewRecordOp ty, _ -> ty + | NewUnionCaseOp unionCase, _ -> unionCase.DeclaringType + | UnionCaseTestOp _, _ -> typeof + | ValueOp (_, ty, _), _ -> ty + | WithValueOp (_, ty), _ -> ty + | TupleGetOp (ty, i), _ -> FSharpType.GetTupleElements(ty).[i] + | NewTupleOp ty, _ -> ty + | StaticPropGetOp prop, _ -> prop.PropertyType + | InstancePropGetOp prop, _ -> prop.PropertyType + | StaticPropSetOp _, _ -> typeof + | InstancePropSetOp _, _ -> typeof + | InstanceFieldGetOp fld, _ -> fld.FieldType + | StaticFieldGetOp fld, _ -> fld.FieldType + | InstanceFieldSetOp _, _ -> typeof + | StaticFieldSetOp _, _ -> typeof + | NewObjectOp ctor, _ -> ctor.DeclaringType + | InstanceMethodCallOp minfo, _ -> minfo.ReturnType |> removeVoid + | StaticMethodCallOp minfo, _ -> minfo.ReturnType |> removeVoid + | CoerceOp ty, _ -> ty + | SequentialOp, [_;b] -> typeOf b + | ForIntegerRangeLoopOp, _ -> typeof + | NewArrayOp ty, _ -> mkArrayTy ty + | NewDelegateOp ty, _ -> ty + | DefaultValueOp ty, _ -> ty + | TypeTestOp _, _ -> typeof + | QuoteOp true, [expr] -> mkExprTy (typeOf expr) + | QuoteOp false, [_] -> rawExprTy + | TryFinallyOp, [e1;_] -> typeOf e1 + | TryWithOp, [e1;_;_] -> typeOf e1 + | WhileLoopOp, _ + | VarSetOp, _ + | AddressSetOp, _ -> typeof + | AddressOfOp, [expr]-> (typeOf expr).MakeByRefType() + | (AddressOfOp | QuoteOp _ | SequentialOp | TryWithOp | TryFinallyOp | IfThenElseOp | AppOp), _ -> failwith "unreachable" //-------------------------------------------------------------------------- // Constructors for building Raw quotations //-------------------------------------------------------------------------- - - let mkFEN op l = E(CombTerm(op,l)) - let mkFE0 op = E(CombTerm(op,[])) - let mkFE1 op x = E(CombTerm(op,[(x:>Expr)])) - let mkFE2 op (x,y) = E(CombTerm(op,[(x:>Expr);(y:>Expr)])) - let mkFE3 op (x,y,z) = E(CombTerm(op,[(x:>Expr);(y:>Expr);(z:>Expr)]) ) + + let mkFEN op l = E(CombTerm(op, l)) + let mkFE0 op = E(CombTerm(op, [])) + let mkFE1 op x = E(CombTerm(op, [(x:>Expr)])) + let mkFE2 op (x, y) = E(CombTerm(op, [(x:>Expr);(y:>Expr)])) + let mkFE3 op (x, y, z) = E(CombTerm(op, [(x:>Expr);(y:>Expr);(z:>Expr)]) ) let mkOp v () = v //-------------------------------------------------------------------------- // Type-checked constructors for building Raw quotations //-------------------------------------------------------------------------- - + // t2 is inherited from t1 / t2 implements interface t1 or t2 == t1 - let assignableFrom (t1:Type) (t2:Type) = + let assignableFrom (t1:Type) (t2:Type) = t1.IsAssignableFrom(t2) - - let checkTypesSR (expectedType: Type) (receivedType : Type) name (threeHoleSR : string) = - if (expectedType <> receivedType) then + + let checkTypesSR (expectedType: Type) (receivedType : Type) name (threeHoleSR : string) = + if (expectedType <> receivedType) then invalidArg "receivedType" (String.Format(threeHoleSR, name, expectedType, receivedType)) - let checkTypesWeakSR (expectedType: Type) (receivedType : Type) name (threeHoleSR : string) = - if (not (assignableFrom expectedType receivedType)) then + let checkTypesWeakSR (expectedType: Type) (receivedType : Type) name (threeHoleSR : string) = + if (not (assignableFrom expectedType receivedType)) then invalidArg "receivedType" (String.Format(threeHoleSR, name, expectedType, receivedType)) - - let checkArgs (paramInfos: ParameterInfo[]) (args:list) = + + let checkArgs (paramInfos: ParameterInfo[]) (args:list) = if (paramInfos.Length <> args.Length) then invalidArg "args" (SR.GetString(SR.QincorrectNumArgs)) List.iter2 - ( fun (p:ParameterInfo) a -> checkTypesWeakSR p.ParameterType (typeOf a) "args" (SR.GetString(SR.QtmmInvalidParam))) - (paramInfos |> Array.toList) + ( fun (p:ParameterInfo) a -> checkTypesWeakSR p.ParameterType (typeOf a) "args" (SR.GetString(SR.QtmmInvalidParam))) + (paramInfos |> Array.toList) args // todo: shouldn't this be "strong" type check? sometimes? - let checkAssignableFrom ty1 ty2 = + let checkAssignableFrom ty1 ty2 = if not (assignableFrom ty1 ty2) then invalidArg "ty2" (SR.GetString(SR.QincorrectType)) - let checkObj (membInfo: MemberInfo) (obj: Expr) = + let checkObj (membInfo: MemberInfo) (obj: Expr) = // The MemberInfo may be a property associated with a union // find the actual related union type let rec loop (ty:Type) = if FSharpType.IsUnion ty && FSharpType.IsUnion ty.BaseType then loop ty.BaseType else ty let declType = loop membInfo.DeclaringType if not (assignableFrom declType (typeOf obj)) then invalidArg "obj" (SR.GetString(SR.QincorrectInstanceType)) - + // Checks lambda application for correctness let checkAppliedLambda (f, v) = let fty = typeOf f - let ftyG = (if fty.IsGenericType then fty.GetGenericTypeDefinition() else fty) + let ftyG = (if fty.IsGenericType then fty.GetGenericTypeDefinition() else fty) checkTypesSR funTyC ftyG "f" (SR.GetString(SR.QtmmExpectedFunction)) let vty = (typeOf v) - match fty.GetGenericArguments() with + match fty.GetGenericArguments() with | [| a; _ |] -> checkTypesSR vty a "f" (SR.GetString(SR.QtmmFunctionArgTypeMismatch)) | _ -> invalidArg "f" (SR.GetString(SR.QinvalidFuncType)) - + // Returns option (by name) of a NewUnionCase type - let getUnionCaseFields ty str = - let cases = FSharpType.GetUnionCases(ty,publicOrPrivateBindingFlags) + let getUnionCaseFields ty str = + let cases = FSharpType.GetUnionCases(ty, publicOrPrivateBindingFlags) match cases |> Array.tryFind (fun ucase -> ucase.Name = str) with | Some(case) -> case.GetFields() | _ -> invalidArg "ty" (String.Format(SR.GetString(SR.notAUnionType), ty.FullName)) - - let checkBind(v:Var,e) = + + let checkBind(v:Var, e) = let ety = typeOf e checkTypesSR v.Type ety "let" (SR.GetString(SR.QtmmVarTypeNotMatchRHS)) - + // [Correct by definition] - let mkVar v = E(VarTerm v ) - let mkQuote(a,isTyped) = E(CombTerm(QuoteOp isTyped,[(a:>Expr)] )) - - let mkValue (v,ty) = mkFE0 (ValueOp(v,ty,None)) - let mkValueWithName (v,ty,nm) = mkFE0 (ValueOp(v,ty,Some nm)) - let mkValueWithDefn (v,ty,defn) = mkFE1 (WithValueOp(v,ty)) defn + let mkVar v = E(VarTerm v ) + let mkQuote(a, isTyped) = E(CombTerm(QuoteOp isTyped, [(a:>Expr)] )) + + let mkValue (v, ty) = mkFE0 (ValueOp(v, ty, None)) + let mkValueWithName (v, ty, nm) = mkFE0 (ValueOp(v, ty, Some nm)) + let mkValueWithDefn (v, ty, defn) = mkFE1 (WithValueOp(v, ty)) defn let mkValueG (v:'T) = mkValue(box v, typeof<'T>) - let mkLiftedValueOpG (v, ty: System.Type) = + let mkLiftedValueOpG (v, ty: System.Type) = let obj = if ty.IsEnum then System.Enum.ToObject(ty, box v) else box v ValueOp(obj, ty, None) let mkUnit () = mkValue(null, typeof) let mkAddressOf v = mkFE1 AddressOfOp v - let mkSequential (e1,e2) = mkFE2 SequentialOp (e1,e2) - let mkTypeTest (e,ty) = mkFE1 (TypeTestOp(ty)) e - let mkVarSet (v,e) = mkFE2 VarSetOp (mkVar(v),e) - let mkAddressSet (e1,e2) = mkFE2 AddressSetOp (e1,e2) - let mkLambda(var,body) = E(LambdaTerm(var,(body:>Expr))) - let mkTryWith(e1,v1,e2,v2,e3) = mkFE3 TryWithOp (e1,mkLambda(v1,e2),mkLambda(v2,e3)) - let mkTryFinally(e1,e2) = mkFE2 TryFinallyOp (e1,e2) - - let mkCoerce (ty,x) = mkFE1 (CoerceOp ty) x - let mkNull (ty) = mkFE0 (ValueOp(null,ty,None)) - - let mkApplication v = checkAppliedLambda v; mkFE2 AppOp v + let mkSequential (e1, e2) = mkFE2 SequentialOp (e1, e2) + let mkTypeTest (e, ty) = mkFE1 (TypeTestOp(ty)) e + let mkVarSet (v, e) = mkFE2 VarSetOp (mkVar(v), e) + let mkAddressSet (e1, e2) = mkFE2 AddressSetOp (e1, e2) + let mkLambda(var, body) = E(LambdaTerm(var, (body:>Expr))) + let mkTryWith(e1, v1, e2, v2, e3) = mkFE3 TryWithOp (e1, mkLambda(v1, e2), mkLambda(v2, e3)) + let mkTryFinally(e1, e2) = mkFE2 TryFinallyOp (e1, e2) + + let mkCoerce (ty, x) = mkFE1 (CoerceOp ty) x + let mkNull (ty) = mkFE0 (ValueOp(null, ty, None)) + + let mkApplication v = checkAppliedLambda v; mkFE2 AppOp v let mkLetRaw v = mkFE2 LetOp v - let mkLetRawWithCheck ((e1,e2) as v) = - checkAppliedLambda (e2,e1) + let mkLetRawWithCheck ((e1, e2) as v) = + checkAppliedLambda (e2, e1) mkLetRaw v // Tuples - let mkNewTupleWithType (ty,args:Expr list) = + let mkNewTupleWithType (ty, args:Expr list) = let mems = FSharpType.GetTupleElements ty |> Array.toList if (args.Length <> mems.Length) then invalidArg "args" (SR.GetString(SR.QtupleLengthsDiffer)) List.iter2(fun mt a -> checkTypesSR mt (typeOf a) "args" (SR.GetString(SR.QtmmTuple)) ) mems args - mkFEN (NewTupleOp ty) args - - let mkNewTuple (args) = + mkFEN (NewTupleOp ty) args + + let mkNewTuple (args) = let ty = FSharpType.MakeTupleType(Array.map typeOf (Array.ofList args)) mkFEN (NewTupleOp ty) args - - let mkTupleGet (ty,n,x) = + + let mkTupleGet (ty, n, x) = checkTypesSR ty (typeOf x) "tupleGet" (SR.GetString(SR.QtmmExprNotMatchTuple)) - let mems = FSharpType.GetTupleElements ty + let mems = FSharpType.GetTupleElements ty if (n < 0 || mems.Length <= n) then invalidArg "n" (SR.GetString(SR.QtupleAccessOutOfRange)) - mkFE1 (TupleGetOp (ty,n)) x - + mkFE1 (TupleGetOp (ty, n)) x + // Records - let mkNewRecord (ty,args:list) = - let mems = FSharpType.GetRecordFields(ty,publicOrPrivateBindingFlags) + let mkNewRecord (ty, args:list) = + let mems = FSharpType.GetRecordFields(ty, publicOrPrivateBindingFlags) if (args.Length <> mems.Length) then invalidArg "args" (SR.GetString(SR.QincompatibleRecordLength)) List.iter2 (fun (minfo:PropertyInfo) a -> checkTypesSR minfo.PropertyType (typeOf a) "recd" (SR.GetString(SR.QtmmIncorrectArgForRecord))) (Array.toList mems) args mkFEN (NewRecordOp ty) args - - - // Discriminated unions - let mkNewUnionCase (unionCase:UnionCaseInfo,args:list) = + + + // Discriminated unions + let mkNewUnionCase (unionCase:UnionCaseInfo, args:list) = if Unchecked.defaultof = unionCase then raise (new ArgumentNullException()) let sargs = unionCase.GetFields() if (args.Length <> sargs.Length) then invalidArg "args" (SR.GetString(SR.QunionNeedsDiffNumArgs)) - List.iter2 (fun (minfo:PropertyInfo) a -> checkTypesSR minfo.PropertyType (typeOf a) "sum" (SR.GetString(SR.QtmmIncorrectArgForUnion))) (Array.toList sargs) args + List.iter2 (fun (minfo:PropertyInfo) a -> checkTypesSR minfo.PropertyType (typeOf a) "sum" (SR.GetString(SR.QtmmIncorrectArgForUnion))) (Array.toList sargs) args mkFEN (NewUnionCaseOp unionCase) args - - let mkUnionCaseTest (unionCase:UnionCaseInfo,expr) = + + let mkUnionCaseTest (unionCase:UnionCaseInfo, expr) = if Unchecked.defaultof = unionCase then raise (new ArgumentNullException()) checkTypesSR unionCase.DeclaringType (typeOf expr) "UnionCaseTagTest" (SR.GetString(SR.QtmmExprTypeMismatch)) mkFE1 (UnionCaseTestOp unionCase) expr // Conditional etc.. - let mkIfThenElse (e,t,f) = + let mkIfThenElse (e, t, f) = checkTypesSR (typeOf t) (typeOf f) "cond" (SR.GetString(SR.QtmmTrueAndFalseMustMatch)) checkTypesSR (typeof) (typeOf e) "cond" (SR.GetString(SR.QtmmCondMustBeBool)) - mkFE3 IfThenElseOp (e,t,f) - - let mkNewArray (ty,args) = + mkFE3 IfThenElseOp (e, t, f) + + let mkNewArray (ty, args) = List.iter (fun a -> checkTypesSR ty (typeOf a) "newArray" (SR.GetString(SR.QtmmInitArray))) args mkFEN (NewArrayOp ty) args - - let mkInstanceFieldGet(obj,finfo:FieldInfo) = + + let mkInstanceFieldGet(obj, finfo:FieldInfo) = if Unchecked.defaultof = finfo then raise (new ArgumentNullException()) - match finfo.IsStatic with - | false -> + match finfo.IsStatic with + | false -> checkObj finfo obj mkFE1 (InstanceFieldGetOp finfo) obj | true -> invalidArg "finfo" (SR.GetString(SR.QstaticWithReceiverObject)) - - let mkStaticFieldGet (finfo:FieldInfo) = + + let mkStaticFieldGet (finfo:FieldInfo) = if Unchecked.defaultof = finfo then raise (new ArgumentNullException()) - match finfo.IsStatic with - | true -> mkFE0 (StaticFieldGetOp finfo) + match finfo.IsStatic with + | true -> mkFE0 (StaticFieldGetOp finfo) | false -> invalidArg "finfo" (SR.GetString(SR.QnonStaticNoReceiverObject)) - - let mkStaticFieldSet (finfo:FieldInfo,value:Expr) = + + let mkStaticFieldSet (finfo:FieldInfo, value:Expr) = if Unchecked.defaultof = finfo then raise (new ArgumentNullException()) checkTypesSR (typeOf value) finfo.FieldType "value" (SR.GetString(SR.QtmmBadFieldType)) - match finfo.IsStatic with + match finfo.IsStatic with | true -> mkFE1 (StaticFieldSetOp finfo) value | false -> invalidArg "finfo" (SR.GetString(SR.QnonStaticNoReceiverObject)) - - let mkInstanceFieldSet (obj,finfo:FieldInfo,value:Expr) = + + let mkInstanceFieldSet (obj, finfo:FieldInfo, value:Expr) = if Unchecked.defaultof = finfo then raise (new ArgumentNullException()) checkTypesSR (typeOf value) finfo.FieldType "value" (SR.GetString(SR.QtmmBadFieldType)) - match finfo.IsStatic with - | false -> + match finfo.IsStatic with + | false -> checkObj finfo obj - mkFE2 (InstanceFieldSetOp finfo) (obj,value) + mkFE2 (InstanceFieldSetOp finfo) (obj, value) | true -> invalidArg "finfo" (SR.GetString(SR.QstaticWithReceiverObject)) - - let mkCtorCall (ci:ConstructorInfo,args:list) = + + let mkCtorCall (ci:ConstructorInfo, args:list) = if Unchecked.defaultof = ci then raise (new ArgumentNullException()) checkArgs (ci.GetParameters()) args mkFEN (NewObjectOp ci) args let mkDefaultValue (ty:Type) = - mkFE0 (DefaultValueOp ty) + mkFE0 (DefaultValueOp ty) - let mkStaticPropGet (pinfo:PropertyInfo,args:list) = + let mkStaticPropGet (pinfo:PropertyInfo, args:list) = if Unchecked.defaultof = pinfo then raise (new ArgumentNullException()) if (not pinfo.CanRead) then invalidArg "pinfo" (SR.GetString(SR.QreadingSetOnly)) checkArgs (pinfo.GetIndexParameters()) args - match pinfo.GetGetMethod(true).IsStatic with + match pinfo.GetGetMethod(true).IsStatic with | true -> mkFEN (StaticPropGetOp pinfo) args | false -> invalidArg "pinfo" (SR.GetString(SR.QnonStaticNoReceiverObject)) - let mkInstancePropGet (obj,pinfo:PropertyInfo,args:list) = + let mkInstancePropGet (obj, pinfo:PropertyInfo, args:list) = if Unchecked.defaultof = pinfo then raise (new ArgumentNullException()) if (not pinfo.CanRead) then invalidArg "pinfo" (SR.GetString(SR.QreadingSetOnly)) checkArgs (pinfo.GetIndexParameters()) args - match pinfo.GetGetMethod(true).IsStatic with - | false -> + match pinfo.GetGetMethod(true).IsStatic with + | false -> checkObj pinfo obj mkFEN (InstancePropGetOp pinfo) (obj::args) | true -> invalidArg "pinfo" (SR.GetString(SR.QstaticWithReceiverObject)) - - let mkStaticPropSet (pinfo:PropertyInfo,args:list,value:Expr) = + + let mkStaticPropSet (pinfo:PropertyInfo, args:list, value:Expr) = if Unchecked.defaultof = pinfo then raise (new ArgumentNullException()) if (not pinfo.CanWrite) then invalidArg "pinfo" (SR.GetString(SR.QwritingGetOnly)) checkArgs (pinfo.GetIndexParameters()) args - match pinfo.GetSetMethod(true).IsStatic with + match pinfo.GetSetMethod(true).IsStatic with | true -> mkFEN (StaticPropSetOp pinfo) (args@[value]) | false -> invalidArg "pinfo" (SR.GetString(SR.QnonStaticNoReceiverObject)) - - let mkInstancePropSet (obj,pinfo:PropertyInfo,args:list,value:Expr) = + + let mkInstancePropSet (obj, pinfo:PropertyInfo, args:list, value:Expr) = if Unchecked.defaultof = pinfo then raise (new ArgumentNullException()) if (not pinfo.CanWrite) then invalidArg "pinfo" (SR.GetString(SR.QwritingGetOnly)) checkArgs (pinfo.GetIndexParameters()) args - match pinfo.GetSetMethod(true).IsStatic with - | false -> + match pinfo.GetSetMethod(true).IsStatic with + | false -> checkObj pinfo obj mkFEN (InstancePropSetOp pinfo) (obj::(args@[value])) | true -> invalidArg "pinfo" (SR.GetString(SR.QstaticWithReceiverObject)) - - let mkInstanceMethodCall (obj,minfo:MethodInfo,args:list) = + + let mkInstanceMethodCall (obj, minfo:MethodInfo, args:list) = if Unchecked.defaultof = minfo then raise (new ArgumentNullException()) checkArgs (minfo.GetParameters()) args - match minfo.IsStatic with - | false -> + match minfo.IsStatic with + | false -> checkObj minfo obj mkFEN (InstanceMethodCallOp minfo) (obj::args) | true -> invalidArg "minfo" (SR.GetString(SR.QstaticWithReceiverObject)) - - let mkStaticMethodCall (minfo:MethodInfo,args:list) = + + let mkStaticMethodCall (minfo:MethodInfo, args:list) = if Unchecked.defaultof = minfo then raise (new ArgumentNullException()) checkArgs (minfo.GetParameters()) args - match minfo.IsStatic with + match minfo.IsStatic with | true -> mkFEN (StaticMethodCallOp minfo) args | false -> invalidArg "minfo" (SR.GetString(SR.QnonStaticNoReceiverObject)) - - let mkForLoop (v:Var,lowerBound,upperBound,body) = + + let mkForLoop (v:Var, lowerBound, upperBound, body) = checkTypesSR (typeof) (typeOf lowerBound) "lowerBound" (SR.GetString(SR.QtmmLowerUpperBoundMustBeInt)) checkTypesSR (typeof) (typeOf upperBound) "upperBound" (SR.GetString(SR.QtmmLowerUpperBoundMustBeInt)) checkTypesSR (typeof) (v.Type) "for" (SR.GetString(SR.QtmmLoopBodyMustBeLambdaTakingInteger)) - mkFE3 ForIntegerRangeLoopOp (lowerBound, upperBound, mkLambda(v,body)) - - let mkWhileLoop (guard,body) = + mkFE3 ForIntegerRangeLoopOp (lowerBound, upperBound, mkLambda(v, body)) + + let mkWhileLoop (guard, body) = checkTypesSR (typeof) (typeOf guard) "guard" (SR.GetString(SR.QtmmGuardMustBeBool)) checkTypesSR (typeof) (typeOf body) "body" (SR.GetString(SR.QtmmBodyMustBeUnit)) - mkFE2 (WhileLoopOp) (guard,body) - - let mkNewDelegate (ty,e) = + mkFE2 (WhileLoopOp) (guard, body) + + let mkNewDelegate (ty, e) = let mi = getDelegateInvoke ty let ps = mi.GetParameters() let dlfun = Array.foldBack (fun (p:ParameterInfo) rty -> mkFunTy p.ParameterType rty) ps mi.ReturnType checkTypesSR dlfun (typeOf e) "ty" (SR.GetString(SR.QtmmFunTypeNotMatchDelegate)) mkFE1 (NewDelegateOp ty) e - - let mkLet (v,e,b) = - checkBind (v,e); - mkLetRaw (e,mkLambda(v,b)) - - //let mkLambdas(vs,b) = mkRLinear mkLambdaRaw (vs,(b:>Expr)) - let mkTupledApplication (f,args) = - match args with - | [] -> mkApplication (f,mkUnit()) - | [x] -> mkApplication (f,x) - | _ -> mkApplication (f,mkNewTuple args) - - let mkApplications(f: Expr,es:list>) = mkLLinear mkTupledApplication (f,es) - - let mkIteratedLambdas(vs,b) = mkRLinear mkLambda (vs,b) - + + let mkLet (v, e, b) = + checkBind (v, e) + mkLetRaw (e, mkLambda(v, b)) + + //let mkLambdas(vs, b) = mkRLinear mkLambdaRaw (vs, (b:>Expr)) + let mkTupledApplication (f, args) = + match args with + | [] -> mkApplication (f, mkUnit()) + | [x] -> mkApplication (f, x) + | _ -> mkApplication (f, mkNewTuple args) + + let mkApplications(f: Expr, es:list>) = mkLLinear mkTupledApplication (f, es) + + let mkIteratedLambdas(vs, b) = mkRLinear mkLambda (vs, b) + let mkLetRecRaw v = mkFE1 LetRecOp v let mkLetRecCombRaw v = mkFEN LetRecCombOp v - let mkLetRec (ves:(Var*Expr) list,body) = - List.iter checkBind ves; - let vs,es = List.unzip ves - mkLetRecRaw(mkIteratedLambdas (vs,mkLetRecCombRaw (body::es))) + let mkLetRec (ves:(Var*Expr) list, body) = + List.iter checkBind ves + let vs, es = List.unzip ves + mkLetRecRaw(mkIteratedLambdas (vs, mkLetRecCombRaw (body::es))) let ReflectedDefinitionsResourceNameBase = "ReflectedDefinitions" @@ -938,103 +938,104 @@ module Patterns = | Unique of 'T | Ambiguous of 'R - let typeEquals (s:Type) (t:Type) = s.Equals(t) + let typeEquals (s:Type) (t:Type) = s.Equals(t) + let typesEqual (ss:Type list) (tt:Type list) = (ss.Length = tt.Length) && List.forall2 typeEquals ss tt let instFormal (typarEnv: Type[]) (ty:Instantiable<'T>) = ty (fun i -> typarEnv.[i]) - let getGenericArguments(tc:Type) = - if tc.IsGenericType then tc.GetGenericArguments() else [| |] + let getGenericArguments(tc:Type) = + if tc.IsGenericType then tc.GetGenericArguments() else [| |] - let getNumGenericArguments(tc:Type) = + let getNumGenericArguments(tc:Type) = if tc.IsGenericType then tc.GetGenericArguments().Length else 0 - - let bindMethodBySearch (parentT:Type,nm,marity,argtys,rty) = - let methInfos = parentT.GetMethods(staticOrInstanceBindingFlags) |> Array.toList - // First, filter on name, if unique, then binding "done" - let tyargTs = getGenericArguments(parentT) + + let bindMethodBySearch (parentT:Type, nm, marity, argtys, rty) = + let methInfos = parentT.GetMethods(staticOrInstanceBindingFlags) |> Array.toList + // First, filter on name, if unique, then binding "done" + let tyargTs = getGenericArguments(parentT) let methInfos = methInfos |> List.filter (fun methInfo -> methInfo.Name = nm) - match methInfos with - | [methInfo] -> + match methInfos with + | [methInfo] -> methInfo | _ -> - // Second, type match. + // Second, type match. let select (methInfo:MethodInfo) = - // mref implied Types - let mtyargTIs = if methInfo.IsGenericMethod then methInfo.GetGenericArguments() else [| |] + // mref implied Types + let mtyargTIs = if methInfo.IsGenericMethod then methInfo.GetGenericArguments() else [| |] if mtyargTIs.Length <> marity then false (* method generic arity mismatch *) else - let typarEnv = (Array.append tyargTs mtyargTIs) - let argTs = argtys |> List.map (instFormal typarEnv) - let resT = instFormal typarEnv rty - - // methInfo implied Types - let haveArgTs = - let parameters = Array.toList (methInfo.GetParameters()) - parameters |> List.map (fun param -> param.ParameterType) - let haveResT = methInfo.ReturnType - // check for match + let typarEnv = (Array.append tyargTs mtyargTIs) + let argTs = argtys |> List.map (instFormal typarEnv) + let resT = instFormal typarEnv rty + + // methInfo implied Types + let haveArgTs = + let parameters = Array.toList (methInfo.GetParameters()) + parameters |> List.map (fun param -> param.ParameterType) + let haveResT = methInfo.ReturnType + // check for match if argTs.Length <> haveArgTs.Length then false (* method argument length mismatch *) else - let res = typesEqual (resT::argTs) (haveResT::haveArgTs) + let res = typesEqual (resT::argTs) (haveResT::haveArgTs) res - // return MethodInfo for (generic) type's (generic) method + // return MethodInfo for (generic) type's (generic) method match List.tryFind select methInfos with - | None -> raise <| System.InvalidOperationException (SR.GetString SR.QcannotBindToMethod) - | Some methInfo -> methInfo + | None -> raise <| System.InvalidOperationException (SR.GetString SR.QcannotBindToMethod) + | Some methInfo -> methInfo - let bindMethodHelper (parentT: Type, nm,marity,argtys,rty) = + let bindMethodHelper (parentT: Type, nm, marity, argtys, rty) = if isNull parentT then invalidArg "parentT" (SR.GetString(SR.QparentCannotBeNull)) - if marity = 0 then - let tyargTs = if parentT.IsGenericType then parentT.GetGenericArguments() else [| |] - let argTs = Array.ofList (List.map (instFormal tyargTs) argtys) - let resT = instFormal tyargTs rty - let methInfo = - try + if marity = 0 then + let tyargTs = if parentT.IsGenericType then parentT.GetGenericArguments() else [| |] + let argTs = Array.ofList (List.map (instFormal tyargTs) argtys) + let resT = instFormal tyargTs rty + let methInfo = + try #if FX_RESHAPED_REFLECTION - match parentT.GetMethod(nm,argTs) with -#else - match parentT.GetMethod(nm,staticOrInstanceBindingFlags,null,argTs,null) with -#endif + match parentT.GetMethod(nm, argTs) with +#else + match parentT.GetMethod(nm, staticOrInstanceBindingFlags, null, argTs, null) with +#endif | null -> None | res -> Some(res) - with :? AmbiguousMatchException -> None - match methInfo with + with :? AmbiguousMatchException -> None + match methInfo with | Some methInfo when (typeEquals resT methInfo.ReturnType) -> methInfo - | _ -> bindMethodBySearch(parentT,nm,marity,argtys,rty) - else - bindMethodBySearch(parentT,nm,marity,argtys,rty) + | _ -> bindMethodBySearch(parentT, nm, marity, argtys, rty) + else + bindMethodBySearch(parentT, nm, marity, argtys, rty) - let bindModuleProperty (ty:Type,nm) = - match ty.GetProperty(nm,staticBindingFlags) with + let bindModuleProperty (ty:Type, nm) = + match ty.GetProperty(nm, staticBindingFlags) with | null -> raise <| System.InvalidOperationException (String.Format(SR.GetString(SR.QcannotBindProperty), nm, ty.ToString())) | res -> res - + // tries to locate unique function in a given type // in case of multiple candidates returns None so bindModuleFunctionWithCallSiteArgs will be used for more precise resolution - let bindModuleFunction (ty:Type,nm) = - match ty.GetMethods(staticBindingFlags) |> Array.filter (fun mi -> mi.Name = nm) with + let bindModuleFunction (ty:Type, nm) = + match ty.GetMethods(staticBindingFlags) |> Array.filter (fun mi -> mi.Name = nm) with | [||] -> raise <| System.InvalidOperationException (String.Format(SR.GetString(SR.QcannotBindFunction), nm, ty.ToString())) | [| res |] -> Some res | _ -> None - - let bindModuleFunctionWithCallSiteArgs (ty:Type, nm, argTypes : Type list, tyArgs : Type list) = + + let bindModuleFunctionWithCallSiteArgs (ty:Type, nm, argTypes : Type list, tyArgs : Type list) = let argTypes = List.toArray argTypes let tyArgs = List.toArray tyArgs - let methInfo = - try + let methInfo = + try #if FX_RESHAPED_REFLECTION - match ty.GetMethod(nm, argTypes) with -#else - match ty.GetMethod(nm,staticOrInstanceBindingFlags,null, argTypes,null) with -#endif + match ty.GetMethod(nm, argTypes) with +#else + match ty.GetMethod(nm, staticOrInstanceBindingFlags, null, argTypes, null) with +#endif | null -> None | res -> Some(res) - with :? AmbiguousMatchException -> None - match methInfo with + with :? AmbiguousMatchException -> None + match methInfo with | Some methInfo -> methInfo | _ -> // narrow down set of candidates by removing methods with a different name\number of arguments\number of type parameters - let candidates = + let candidates = ty.GetMethods(staticBindingFlags) |> Array.filter(fun mi -> mi.Name = nm && @@ -1075,7 +1076,7 @@ module Patterns = // - parameter type is generic that after instantiation doesn't actual argument type stops computation and return FAIL as the final result let weight (mi : MethodInfo) = let parameters = mi.GetParameters() - let rec iter i acc = + let rec iter i acc = if i >= argTypes.Length then acc else let param = parameters.[i] @@ -1085,49 +1086,49 @@ module Patterns = else if param.ParameterType = argTypes.[i] then iter (i + 1) (acc + MATCH) else FAIL iter 0 0 - let solution, weight = - candidates + let solution, weight = + candidates |> Array.map (fun mi -> mi, weight mi) |> Array.maxBy snd if weight = FAIL then None else Some solution match solution with | Some mi -> mi - | None -> fail() - - let mkNamedType (tc:Type,tyargs) = - match tyargs with + | None -> fail() + + let mkNamedType (tc:Type, tyargs) = + match tyargs with | [] -> tc | _ -> tc.MakeGenericType(Array.ofList tyargs) - let inline checkNonNullResult (arg:string,err:string) y = - match box y with - | null -> raise (new ArgumentNullException(arg,err)) + let inline checkNonNullResult (arg:string, err:string) y = + match box y with + | null -> raise (new ArgumentNullException(arg, err)) | _ -> y let inst (tyargs:Type list) (i: Instantiable<'T>) = i (fun idx -> tyargs.[idx]) // Note, O(n) looks, but #tyargs is always small - - let bindPropBySearchIfCandidateIsNull (ty : Type) propName retType argTypes candidate = + + let bindPropBySearchIfCandidateIsNull (ty : Type) propName retType argTypes candidate = match candidate with | null -> - let props = + let props = ty.GetProperties(staticOrInstanceBindingFlags) - |> Array.filter (fun pi -> + |> Array.filter (fun pi -> let paramTypes = getTypesFromParamInfos (pi.GetIndexParameters()) - pi.Name = propName && - pi.PropertyType = retType && - Array.length argTypes = paramTypes.Length && + pi.Name = propName && + pi.PropertyType = retType && + Array.length argTypes = paramTypes.Length && Array.forall2 (=) argTypes paramTypes ) match props with | [| pi |] -> pi | _ -> null | pi -> pi - - let bindCtorBySearchIfCandidateIsNull (ty : Type) argTypes candidate = + + let bindCtorBySearchIfCandidateIsNull (ty : Type) argTypes candidate = match candidate with - | null -> - let ctors = + | null -> + let ctors = ty.GetConstructors(instanceBindingFlags) |> Array.filter (fun ci -> let paramTypes = getTypesFromParamInfos (ci.GetParameters()) @@ -1138,562 +1139,595 @@ module Patterns = | [| ctor |] -> ctor | _ -> null | ctor -> ctor - - let bindProp (tc,propName,retType,argTypes,tyargs) = + + let bindProp (tc, propName, retType, argTypes, tyargs) = // We search in the instantiated type, rather than searching the generic type. - let typ = mkNamedType(tc,tyargs) + let typ = mkNamedType (tc, tyargs) let argtyps : Type list = argTypes |> inst tyargs let retType : Type = retType |> inst tyargs |> removeVoid #if FX_RESHAPED_REFLECTION - try - typ.GetProperty(propName, staticOrInstanceBindingFlags) + try + typ.GetProperty(propName, staticOrInstanceBindingFlags) with :? AmbiguousMatchException -> null // more than one property found with the specified name and matching binding constraints - return null to initiate manual search |> bindPropBySearchIfCandidateIsNull typ propName retType (Array.ofList argtyps) |> checkNonNullResult ("propName", String.Format(SR.GetString(SR.QfailedToBindProperty), propName)) // fxcop may not see "propName" as an arg -#else +#else typ.GetProperty(propName, staticOrInstanceBindingFlags, null, retType, Array.ofList argtyps, null) |> checkNonNullResult ("propName", String.Format(SR.GetString(SR.QfailedToBindProperty), propName)) // fxcop may not see "propName" as an arg #endif - let bindField (tc,fldName,tyargs) = - let typ = mkNamedType(tc,tyargs) - typ.GetField(fldName,staticOrInstanceBindingFlags) |> checkNonNullResult ("fldName", String.Format(SR.GetString(SR.QfailedToBindField), fldName)) // fxcop may not see "fldName" as an arg + let bindField (tc, fldName, tyargs) = + let typ = mkNamedType (tc, tyargs) + typ.GetField(fldName, staticOrInstanceBindingFlags) |> checkNonNullResult ("fldName", String.Format(SR.GetString(SR.QfailedToBindField), fldName)) // fxcop may not see "fldName" as an arg let bindGenericCctor (tc:Type) = - tc.GetConstructor(staticBindingFlags,null,[| |],null) - |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) + tc.GetConstructor(staticBindingFlags, null, [| |], null) + |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) - let bindGenericCtor (tc:Type,argTypes:Instantiable) = - let argtyps = instFormal (getGenericArguments tc) argTypes + let bindGenericCtor (tc:Type, argTypes:Instantiable) = + let argtyps = instFormal (getGenericArguments tc) argTypes #if FX_RESHAPED_REFLECTION let argTypes = Array.ofList argtyps - tc.GetConstructor(argTypes) + tc.GetConstructor(argTypes) |> bindCtorBySearchIfCandidateIsNull tc argTypes - |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) -#else - tc.GetConstructor(instanceBindingFlags,null,Array.ofList argtyps,null) |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) + |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) +#else + tc.GetConstructor(instanceBindingFlags, null, Array.ofList argtyps, null) |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) #endif - let bindCtor (tc,argTypes:Instantiable,tyargs) = - let typ = mkNamedType(tc,tyargs) + let bindCtor (tc, argTypes:Instantiable, tyargs) = + let typ = mkNamedType (tc, tyargs) let argtyps = argTypes |> inst tyargs #if FX_RESHAPED_REFLECTION let argTypes = Array.ofList argtyps - typ.GetConstructor(argTypes) + typ.GetConstructor(argTypes) |> bindCtorBySearchIfCandidateIsNull typ argTypes - |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) -#else - typ.GetConstructor(instanceBindingFlags,null,Array.ofList argtyps,null) |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) + |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) +#else + typ.GetConstructor(instanceBindingFlags, null, Array.ofList argtyps, null) |> checkNonNullResult ("tc", SR.GetString(SR.QfailedToBindConstructor)) #endif let chop n xs = if n < 0 then invalidArg "n" (SR.GetString(SR.inputMustBeNonNegative)) - let rec split l = - match l with - | 0,xs -> [],xs - | n,x::xs -> let front,back = split (n-1,xs) - x::front,back - | _,[] -> failwith "List.chop: not enough elts list" - split (n,xs) - - let instMeth (ngmeth: MethodInfo, methTypeArgs) = - if ngmeth.GetGenericArguments().Length = 0 then ngmeth(* non generic *) - else ngmeth.MakeGenericMethod(Array.ofList methTypeArgs) - - let bindGenericMeth (tc:Type,argTypes : list>,retType,methName,numMethTyargs) = - bindMethodHelper(tc,methName,numMethTyargs,argTypes,retType) - - let bindMeth ((tc:Type,argTypes : list>,retType,methName,numMethTyargs),tyargs) = - let ntyargs = tc.GetGenericArguments().Length - let enclTypeArgs,methTypeArgs = chop ntyargs tyargs - let ty = mkNamedType(tc,enclTypeArgs) - let ngmeth = bindMethodHelper(ty,methName,numMethTyargs,argTypes,retType) - instMeth(ngmeth,methTypeArgs) - - let pinfoIsStatic (pinfo:PropertyInfo) = + let rec split l = + match l with + | 0, xs -> [], xs + | n, x::xs -> + let front, back = split (n-1, xs) + x::front, back + | _, [] -> failwith "List.chop: not enough elts list" + split (n, xs) + + let instMeth (ngmeth: MethodInfo, methTypeArgs) = + if ngmeth.GetGenericArguments().Length = 0 then ngmeth(* non generic *) + else ngmeth.MakeGenericMethod(Array.ofList methTypeArgs) + + let bindGenericMeth (tc:Type, argTypes : list>, retType, methName, numMethTyargs) = + bindMethodHelper(tc, methName, numMethTyargs, argTypes, retType) + + let bindMeth ((tc:Type, argTypes : list>, retType, methName, numMethTyargs), tyargs) = + let ntyargs = tc.GetGenericArguments().Length + let enclTypeArgs, methTypeArgs = chop ntyargs tyargs + let ty = mkNamedType (tc, enclTypeArgs) + let ngmeth = bindMethodHelper(ty, methName, numMethTyargs, argTypes, retType) + instMeth(ngmeth, methTypeArgs) + + let pinfoIsStatic (pinfo:PropertyInfo) = if pinfo.CanRead then pinfo.GetGetMethod(true).IsStatic elif pinfo.CanWrite then pinfo.GetSetMethod(true).IsStatic else false - - //-------------------------------------------------------------------------- - // Unpickling - //-------------------------------------------------------------------------- - module SimpleUnpickle = + /// Unpickling + module SimpleUnpickle = [] - type InputState = - { is: ByteStream; - istrings: string[]; - localAssembly: System.Reflection.Assembly + type InputState = + { is: ByteStream + istrings: string[] + localAssembly: System.Reflection.Assembly referencedTypeDefs: Type[] } - let u_byte_as_int st = st.is.ReadByte() + let u_byte_as_int st = st.is.ReadByte() + + let u_bool st = + let b = u_byte_as_int st + (b = 1) - let u_bool st = let b = u_byte_as_int st in (b = 1) let u_void (_: InputState) = () - let u_unit (_: InputState) = () - let prim_u_int32 st = - let b0 = (u_byte_as_int st) - let b1 = (u_byte_as_int st) - let b2 = (u_byte_as_int st) - let b3 = (u_byte_as_int st) + + let prim_u_int32 st = + let b0 = (u_byte_as_int st) + let b1 = (u_byte_as_int st) + let b2 = (u_byte_as_int st) + let b3 = (u_byte_as_int st) b0 ||| (b1 <<< 8) ||| (b2 <<< 16) ||| (b3 <<< 24) - let u_int32 st = - let b0 = u_byte_as_int st - if b0 <= 0x7F then b0 - elif b0 <= 0xbf then - let b0 = b0 &&& 0x7f - let b1 = (u_byte_as_int st) + let u_int32 st = + let b0 = u_byte_as_int st + if b0 <= 0x7F then b0 + elif b0 <= 0xbf then + let b0 = b0 &&& 0x7f + let b1 = (u_byte_as_int st) (b0 <<< 8) ||| b1 - else + else prim_u_int32 st - let u_bytes st = - let n = u_int32 st - st.is.ReadBytes(n) + let u_bytes st = + let len = u_int32 st + st.is.ReadBytes len + + let prim_u_string st = + let len = u_int32 st + st.is.ReadUtf8BytesAsString len + + let u_int st = u_int32 st - let prim_u_string st = - let len = (u_int32 st) - st.is.ReadUtf8BytesAsString(len) + let u_sbyte st = sbyte (u_int32 st) + + let u_byte st = byte (u_byte_as_int st) + + let u_int16 st = int16 (u_int32 st) - let u_int st = u_int32 st - let u_sbyte st = sbyte (u_int32 st) - let u_byte st = byte (u_byte_as_int st) - let u_int16 st = int16 (u_int32 st) let u_uint16 st = uint16 (u_int32 st) + let u_uint32 st = uint32 (u_int32 st) - let u_int64 st = - let b1 = int64 (u_int32 st) &&& 0xFFFFFFFFL - let b2 = int64 (u_int32 st) + + let u_int64 st = + let b1 = int64 (u_int32 st) &&& 0xFFFFFFFFL + let b2 = int64 (u_int32 st) b1 ||| (b2 <<< 32) - let u_uint64 st = uint64 (u_int64 st) - let u_double st = System.BitConverter.ToDouble(System.BitConverter.GetBytes(u_int64 st),0) - let u_float32 st = System.BitConverter.ToSingle(System.BitConverter.GetBytes(u_int32 st),0) + + let u_uint64 st = uint64 (u_int64 st) + + let u_double st = System.BitConverter.ToDouble(System.BitConverter.GetBytes(u_int64 st), 0) + + let u_float32 st = System.BitConverter.ToSingle(System.BitConverter.GetBytes(u_int32 st), 0) + let u_char st = char (int32 (u_uint16 st)) - let inline u_tup2 p1 p2 st = let a = p1 st in let b = p2 st in (a,b) + + let inline u_tup2 p1 p2 st = let a = p1 st in let b = p2 st in (a, b) + let inline u_tup3 p1 p2 p3 st = - let a = p1 st in let b = p2 st in let c = p3 st in (a,b,c) + 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 = - 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 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 = - 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 (a,b,c,d,e) - let u_uniq (tbl: _ array) st = - let n = u_int st - if n < 0 || n >= tbl.Length then failwith ("u_uniq: out of range, n = "+string n+ ", sizeof(tab) = " + string tbl.Length); + 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 (a, b, c, d, e) + + let u_uniq (tbl: _ array) st = + let n = u_int st + if n < 0 || n >= tbl.Length then failwith ("u_uniq: out of range, n = "+string n+ ", sizeof(tab) = " + string tbl.Length) tbl.[n] + let u_string st = u_uniq st.istrings st - let rec u_list_aux f acc st = - let tag = u_byte_as_int st + let rec u_list_aux f acc st = + let tag = u_byte_as_int st match tag with | 0 -> List.rev acc - | 1 -> let a = f st in u_list_aux f (a::acc) st + | 1 -> let a = f st in u_list_aux f (a::acc) st | n -> failwith ("u_list: found number " + string n) + let u_list f st = u_list_aux f [] st - + let unpickleObj localAssembly referencedTypeDefs u phase2bytes = - let phase2data = - let st2 = - { is = new ByteStream(phase2bytes,0,phase2bytes.Length) + let phase2data = + let st2 = + { is = new ByteStream(phase2bytes, 0, phase2bytes.Length) istrings = [| |] localAssembly=localAssembly referencedTypeDefs=referencedTypeDefs } - u_tup2 (u_list prim_u_string) u_bytes st2 - let stringTab,phase1bytes = phase2data - let st1 = - { is = new ByteStream(phase1bytes,0,phase1bytes.Length) + u_tup2 (u_list prim_u_string) u_bytes st2 + let stringTab, phase1bytes = phase2data + let st1 = + { is = new ByteStream(phase1bytes, 0, phase1bytes.Length) istrings = Array.ofList stringTab localAssembly=localAssembly - referencedTypeDefs=referencedTypeDefs } - let res = u st1 - res + referencedTypeDefs=referencedTypeDefs } + let res = u st1 + res open SimpleUnpickle let decodeFunTy args = - match args with + match args with | [d;r] -> funTyC.MakeGenericType([| d; r |]) | _ -> invalidArg "args" (SR.GetString(SR.QexpectedTwoTypes)) - let decodeArrayTy n (tys: Type list) = + let decodeArrayTy n (tys: Type list) = match tys with - | [ty] -> if (n = 1) then ty.MakeArrayType() else ty.MakeArrayType(n) + | [ty] -> if (n = 1) then ty.MakeArrayType() else ty.MakeArrayType(n) // typeof.MakeArrayType(1) returns "Int[*]" but we need "Int[]" | _ -> invalidArg "tys" (SR.GetString(SR.QexpectedOneType)) - - let mkNamedTycon (tcName,assembly:Assembly) = - match assembly.GetType(tcName) with - | null -> + + let mkNamedTycon (tcName, assembly:Assembly) = + match assembly.GetType(tcName) with + | null -> // For some reason we can get 'null' returned here even when a type with the right name exists... Hence search the slow way... - match (assembly.GetTypes() |> Array.tryFind (fun a -> a.FullName = tcName)) with + match (assembly.GetTypes() |> Array.tryFind (fun a -> a.FullName = tcName)) with | Some ty -> ty | None -> invalidArg "tcName" (String.Format(SR.GetString(SR.QfailedToBindTypeInAssembly), tcName, assembly.FullName)) // "Available types are:\n%A" tcName assembly (assembly.GetTypes() |> Array.map (fun a -> a.FullName)) | ty -> ty - let decodeNamedTy tc tsR = mkNamedType(tc,tsR) + let decodeNamedTy tc tsR = mkNamedType (tc, tsR) let mscorlib = typeof.Assembly - let u_assemblyRef st = u_string st + + let u_assemblyRef st = u_string st + let decodeAssemblyRef st a = if a = "" then mscorlib - elif a = "." then st.localAssembly - else + elif a = "." then st.localAssembly + else #if FX_RESHAPED_REFLECTION - match System.Reflection.Assembly.Load(AssemblyName(a)) with + match System.Reflection.Assembly.Load(AssemblyName(a)) with #else - match System.Reflection.Assembly.Load(a) with + match System.Reflection.Assembly.Load(a) with #endif | null -> raise <| System.InvalidOperationException(String.Format(SR.GetString(SR.QfailedToBindAssembly), a.ToString())) | assembly -> assembly - - let u_NamedType st = - let a,b = u_tup2 u_string u_assemblyRef st + + let u_NamedType st = + let a, b = u_tup2 u_string u_assemblyRef st let mutable idx = 0 - // From FSharp.Core for F# 4.0+ (4.4.0.0+), referenced type definitions can be integer indexes into a table of type definitions provided on quotation + // From FSharp.Core for F# 4.0+ (4.4.0.0+), referenced type definitions can be integer indexes into a table of type definitions provided on quotation // deserialization, avoiding the need for System.Reflection.Assembly.Load - if System.Int32.TryParse(a, &idx) && b = "" then + if System.Int32.TryParse(a, &idx) && b = "" then st.referencedTypeDefs.[idx] - else + else // escape commas found in type name, which are not already escaped // '\' is not valid in a type name except as an escape character, so logic can be pretty simple - let escapedTcName = System.Text.RegularExpressions.Regex.Replace(a, @"(? u_unit st |> (fun () -> decodeFunTy) - | 2 -> u_NamedType st |> decodeNamedTy - | 3 -> u_int st |> decodeArrayTy - | _ -> failwith "u_tyconstSpec" - - let appL fs env = List.map (fun f -> f env) fs - - let rec u_dtype st : (int -> Type) -> Type = - let tag = u_byte_as_int st - match tag with - | 0 -> u_int st |> (fun x env -> env(x)) - | 1 -> u_tup2 u_tyconstSpec (u_list u_dtype) st |> (fun (a,b) env -> a (appL b env)) - | _ -> failwith "u_dtype" - - let u_dtypes st = let a = u_list u_dtype st in appL a - - let (|NoTyArgs|)input = match input with [] -> () | _ -> failwith "incorrect number of arguments during deserialization" - let (|OneTyArg|)input = match input with [x] -> x | _ -> failwith "incorrect number of arguments during deserialization" - + let u_tyconstSpec st = + let tag = u_byte_as_int st + match tag with + | 1 -> u_void st |> (fun () -> decodeFunTy) + | 2 -> u_NamedType st |> decodeNamedTy + | 3 -> u_int st |> decodeArrayTy + | _ -> failwith "u_tyconstSpec" + + let appL fs env = + List.map (fun f -> f env) fs + + let rec u_dtype st : (int -> Type) -> Type = + let tag = u_byte_as_int st + match tag with + | 0 -> u_int st |> (fun x env -> env(x)) + | 1 -> u_tup2 u_tyconstSpec (u_list u_dtype) st |> (fun (a, b) env -> a (appL b env)) + | _ -> failwith "u_dtype" + + let u_dtypes st = let a = u_list u_dtype st in appL a + + let (|NoTyArgs|) input = match input with [] -> () | _ -> failwith "incorrect number of arguments during deserialization" + + let (|OneTyArg|) input = match input with [x] -> x | _ -> failwith "incorrect number of arguments during deserialization" + [] - type BindingEnv = + type BindingEnv = { /// Mapping from variable index to Var object for the variable - vars : Map + vars : Map /// The number of indexes in the mapping varn: int /// The active type instantiation for generic type parameters typeInst : int -> Type } - let addVar env v = - { env with vars = env.vars.Add(env.varn,v); varn=env.varn+1 } + let addVar env v = + { env with vars = env.vars.Add(env.varn, v); varn=env.varn+1 } let mkTyparSubst (tyargs:Type[]) = - let n = tyargs.Length - fun idx -> + let n = tyargs.Length + fun idx -> if idx < n then tyargs.[idx] else raise <| System.InvalidOperationException (SR.GetString(SR.QtypeArgumentOutOfRange)) - let envClosed (spliceTypes:Type[]) = - { vars = Map.empty; + let envClosed (spliceTypes:Type[]) = + { vars = Map.empty varn = 0 typeInst = mkTyparSubst spliceTypes } type Bindable<'T> = BindingEnv -> 'T - - let rec u_Expr st = - let tag = u_byte_as_int st - match tag with - | 0 -> u_tup3 u_constSpec u_dtypes (u_list u_Expr) st - |> (fun (a,b,args) (env:BindingEnv) -> - let args = List.map (fun e -> e env) args - let a = - match a with - | Unique v -> v - | Ambiguous f -> - let argTys = List.map typeOf args - f argTys - let tyargs = b env.typeInst - E(CombTerm(a tyargs, args ))) - | 1 -> let x = u_VarRef st - (fun env -> E(VarTerm (x env))) - | 2 -> let a = u_VarDecl st - let b = u_Expr st - (fun env -> let v = a env in E(LambdaTerm(v,b (addVar env v)))) - | 3 -> let a = u_dtype st - let idx = u_int st - (fun env -> E(HoleTerm(a env.typeInst, idx))) - | 4 -> let a = u_Expr st - (fun env -> mkQuote(a env, true)) - | 5 -> let a = u_Expr st - let attrs = u_list u_Expr st - (fun env -> let e = (a env) in EA(e.Tree,(e.CustomAttributes @ List.map (fun attrf -> attrf env) attrs))) - | 6 -> let a = u_dtype st - (fun env -> mkVar(Var.Global("this", a env.typeInst))) - | 7 -> let a = u_Expr st - (fun env -> mkQuote(a env, false)) + + let rec u_Expr st = + let tag = u_byte_as_int st + match tag with + | 0 -> + let a = u_constSpec st + let b = u_dtypes st + let args = u_list u_Expr st + (fun (env:BindingEnv) -> + let args = List.map (fun e -> e env) args + let a = + match a with + | Unique v -> v + | Ambiguous f -> + let argTys = List.map typeOf args + f argTys + let tyargs = b env.typeInst + E (CombTerm (a tyargs, args))) + | 1 -> + let x = u_VarRef st + (fun env -> E(VarTerm (x env))) + | 2 -> + let a = u_VarDecl st + let b = u_Expr st + (fun env -> let v = a env in E(LambdaTerm(v, b (addVar env v)))) + | 3 -> + let a = u_dtype st + let idx = u_int st + (fun env -> E(HoleTerm(a env.typeInst, idx))) + | 4 -> + let a = u_Expr st + (fun env -> mkQuote(a env, true)) + | 5 -> + let a = u_Expr st + let attrs = u_list u_Expr st + (fun env -> let e = (a env) in EA(e.Tree, (e.CustomAttributes @ List.map (fun attrf -> attrf env) attrs))) + | 6 -> + let a = u_dtype st + (fun env -> mkVar(Var.Global("this", a env.typeInst))) + | 7 -> + let a = u_Expr st + (fun env -> mkQuote(a env, false)) | _ -> failwith "u_Expr" - and u_VarDecl st = - let s,b,mut = u_tup3 u_string u_dtype u_bool st + and u_VarDecl st = + let s, b, mut = u_tup3 u_string u_dtype u_bool st (fun env -> new Var(s, b env.typeInst, mut)) - and u_VarRef st = - let i = u_int st + and u_VarRef st = + let i = u_int st (fun env -> env.vars.[i]) - and u_RecdField st = - let ty,nm = u_tup2 u_NamedType u_string st - (fun tyargs -> getRecordProperty(mkNamedType(ty,tyargs),nm)) + and u_RecdField st = + let ty, nm = u_tup2 u_NamedType u_string st + (fun tyargs -> getRecordProperty(mkNamedType (ty, tyargs), nm)) - and u_UnionCaseInfo st = - let ty,nm = u_tup2 u_NamedType u_string st - (fun tyargs -> getUnionCaseInfo(mkNamedType(ty,tyargs),nm)) + and u_UnionCaseInfo st = + let ty, nm = u_tup2 u_NamedType u_string st + (fun tyargs -> getUnionCaseInfo(mkNamedType (ty, tyargs), nm)) - and u_UnionCaseField st = - let case,i = u_tup2 u_UnionCaseInfo u_int st - (fun tyargs -> getUnionCaseInfoField(case tyargs,i)) + and u_UnionCaseField st = + let case, i = u_tup2 u_UnionCaseInfo u_int st + (fun tyargs -> getUnionCaseInfoField(case tyargs, i)) - and u_ModuleDefn st = - let (ty,nm,isProp) = u_tup3 u_NamedType u_string u_bool st - if isProp then Unique(StaticPropGetOp(bindModuleProperty(ty,nm))) - else + and u_ModuleDefn st = + let (ty, nm, isProp) = u_tup3 u_NamedType u_string u_bool st + if isProp then Unique(StaticPropGetOp(bindModuleProperty(ty, nm))) + else match bindModuleFunction(ty, nm) with | Some mi -> Unique(StaticMethodCallOp(mi)) | None -> Ambiguous(fun argTypes tyargs -> StaticMethodCallOp(bindModuleFunctionWithCallSiteArgs(ty, nm, argTypes, tyargs))) - and u_MethodInfoData st = + and u_MethodInfoData st = u_tup5 u_NamedType (u_list u_dtype) u_dtype u_string u_int st - - and u_PropInfoData st = - u_tup4 u_NamedType u_string u_dtype u_dtypes st - + + and u_PropInfoData st = + u_tup4 u_NamedType u_string u_dtype u_dtypes st + and u_CtorInfoData st = u_tup2 u_NamedType u_dtypes st - - and u_MethodBase st = - let tag = u_byte_as_int st - match tag with - | 0 -> - match u_ModuleDefn st with + + and u_MethodBase st = + let tag = u_byte_as_int st + match tag with + | 0 -> + match u_ModuleDefn st with | Unique(StaticMethodCallOp(minfo)) -> (minfo :> MethodBase) | Unique(StaticPropGetOp(pinfo)) -> (pinfo.GetGetMethod(true) :> MethodBase) | Ambiguous(_) -> raise (System.Reflection.AmbiguousMatchException()) | _ -> failwith "unreachable" - | 1 -> - let ((tc,_,_,methName,_) as data) = u_MethodInfoData st - if methName = ".cctor" then + | 1 -> + let ((tc, _, _, methName, _) as data) = u_MethodInfoData st + if methName = ".cctor" then let cinfo = bindGenericCctor tc (cinfo :> MethodBase) else let minfo = bindGenericMeth(data) (minfo :> MethodBase) - | 2 -> + | 2 -> let data = u_CtorInfoData st - let cinfo = bindGenericCtor(data) in + let cinfo = bindGenericCtor(data) in (cinfo :> MethodBase) - | _ -> failwith "u_MethodBase" + | _ -> failwith "u_MethodBase" - - and u_constSpec st = - let tag = u_byte_as_int st + + and u_constSpec st = + let tag = u_byte_as_int st if tag = 1 then - let bindModuleDefn r tyargs = + let bindModuleDefn r tyargs = match r with - | StaticMethodCallOp(minfo) -> StaticMethodCallOp(instMeth(minfo,tyargs)) + | StaticMethodCallOp(minfo) -> StaticMethodCallOp(instMeth(minfo, tyargs)) // OK to throw away the tyargs here since this only non-generic values in modules get represented by static properties - | x -> x + | x -> x match u_ModuleDefn st with | Unique(r) -> Unique(bindModuleDefn r) - | Ambiguous(f) -> Ambiguous(fun argTypes tyargs -> bindModuleDefn (f argTypes tyargs) tyargs) + | Ambiguous(f) -> Ambiguous(fun argTypes tyargs -> bindModuleDefn (f argTypes tyargs) tyargs) else - let constSpec = - match tag with - | 0 -> u_void st |> (fun () NoTyArgs -> IfThenElseOp) - | 2 -> u_void st |> (fun () NoTyArgs -> LetRecOp) - | 3 -> u_NamedType st |> (fun x tyargs -> NewRecordOp (mkNamedType(x,tyargs))) - | 4 -> u_RecdField st |> (fun prop tyargs -> InstancePropGetOp(prop tyargs)) - | 5 -> u_UnionCaseInfo st |> (fun unionCase tyargs -> NewUnionCaseOp(unionCase tyargs)) - | 6 -> u_UnionCaseField st |> (fun prop tyargs -> InstancePropGetOp(prop tyargs) ) - | 7 -> u_UnionCaseInfo st |> (fun unionCase tyargs -> UnionCaseTestOp(unionCase tyargs)) - | 8 -> u_void st |> (fun () (OneTyArg(tyarg)) -> NewTupleOp tyarg) - | 9 -> u_int st |> (fun x (OneTyArg(tyarg)) -> TupleGetOp (tyarg,x)) + let constSpec = + match tag with + | 0 -> u_void st |> (fun () NoTyArgs -> IfThenElseOp) + | 2 -> u_void st |> (fun () NoTyArgs -> LetRecOp) + | 3 -> u_NamedType st |> (fun x tyargs -> NewRecordOp (mkNamedType (x, tyargs))) + | 4 -> u_RecdField st |> (fun prop tyargs -> InstancePropGetOp(prop tyargs)) + | 5 -> u_UnionCaseInfo st |> (fun unionCase tyargs -> NewUnionCaseOp(unionCase tyargs)) + | 6 -> u_UnionCaseField st |> (fun prop tyargs -> InstancePropGetOp(prop tyargs) ) + | 7 -> u_UnionCaseInfo st |> (fun unionCase tyargs -> UnionCaseTestOp(unionCase tyargs)) + | 8 -> u_void st |> (fun () (OneTyArg(tyarg)) -> NewTupleOp tyarg) + | 9 -> u_int st |> (fun x (OneTyArg(tyarg)) -> TupleGetOp (tyarg, x)) // Note, these get type args because they may be the result of reading literal field constants - | 11 -> u_bool st |> (fun x (OneTyArg(tyarg)) -> mkLiftedValueOpG (x, tyarg)) - | 12 -> u_string st |> (fun x (OneTyArg(tyarg)) -> mkLiftedValueOpG (x, tyarg)) - | 13 -> u_float32 st |> (fun x (OneTyArg(tyarg)) -> mkLiftedValueOpG (x, tyarg)) - | 14 -> u_double st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 15 -> u_char st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 16 -> u_sbyte st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 17 -> u_byte st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 18 -> u_int16 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 19 -> u_uint16 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 20 -> u_int32 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 21 -> u_uint32 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 22 -> u_int64 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 23 -> u_uint64 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) - | 24 -> u_void st |> (fun () NoTyArgs -> mkLiftedValueOpG ((), typeof)) - | 25 -> u_PropInfoData st |> (fun (a,b,c,d) tyargs -> let pinfo = bindProp(a,b,c,d,tyargs) in if pinfoIsStatic pinfo then StaticPropGetOp(pinfo) else InstancePropGetOp(pinfo)) - | 26 -> u_CtorInfoData st |> (fun (a,b) tyargs -> NewObjectOp (bindCtor(a,b,tyargs))) - | 28 -> u_void st |> (fun () (OneTyArg(ty)) -> CoerceOp ty) - | 29 -> u_void st |> (fun () NoTyArgs -> SequentialOp) - | 30 -> u_void st |> (fun () NoTyArgs -> ForIntegerRangeLoopOp) - | 31 -> u_MethodInfoData st |> (fun p tyargs -> let minfo = bindMeth(p,tyargs) in if minfo.IsStatic then StaticMethodCallOp(minfo) else InstanceMethodCallOp(minfo)) - | 32 -> u_void st |> (fun () (OneTyArg(ty)) -> NewArrayOp ty) - | 33 -> u_void st |> (fun () (OneTyArg(ty)) -> NewDelegateOp ty) - | 34 -> u_void st |> (fun () NoTyArgs -> WhileLoopOp) - | 35 -> u_void st |> (fun () NoTyArgs -> LetOp) - | 36 -> u_RecdField st |> (fun prop tyargs -> InstancePropSetOp(prop tyargs)) - | 37 -> u_tup2 u_NamedType u_string st |> (fun (a,b) tyargs -> let finfo = bindField(a,b,tyargs) in if finfo.IsStatic then StaticFieldGetOp(finfo) else InstanceFieldGetOp(finfo)) - | 38 -> u_void st |> (fun () NoTyArgs -> LetRecCombOp) - | 39 -> u_void st |> (fun () NoTyArgs -> AppOp) - | 40 -> u_void st |> (fun () (OneTyArg(ty)) -> ValueOp(null,ty,None)) - | 41 -> u_void st |> (fun () (OneTyArg(ty)) -> DefaultValueOp(ty)) - | 42 -> u_PropInfoData st |> (fun (a,b,c,d) tyargs -> let pinfo = bindProp(a,b,c,d,tyargs) in if pinfoIsStatic pinfo then StaticPropSetOp(pinfo) else InstancePropSetOp(pinfo)) - | 43 -> u_tup2 u_NamedType u_string st |> (fun (a,b) tyargs -> let finfo = bindField(a,b,tyargs) in if finfo.IsStatic then StaticFieldSetOp(finfo) else InstanceFieldSetOp(finfo)) - | 44 -> u_void st |> (fun () NoTyArgs -> AddressOfOp) - | 45 -> u_void st |> (fun () NoTyArgs -> AddressSetOp) - | 46 -> u_void st |> (fun () (OneTyArg(ty)) -> TypeTestOp(ty)) - | 47 -> u_void st |> (fun () NoTyArgs -> TryFinallyOp) - | 48 -> u_void st |> (fun () NoTyArgs -> TryWithOp) - | 49 -> u_void st |> (fun () NoTyArgs -> VarSetOp) + | 11 -> u_bool st |> (fun x (OneTyArg(tyarg)) -> mkLiftedValueOpG (x, tyarg)) + | 12 -> u_string st |> (fun x (OneTyArg(tyarg)) -> mkLiftedValueOpG (x, tyarg)) + | 13 -> u_float32 st |> (fun x (OneTyArg(tyarg)) -> mkLiftedValueOpG (x, tyarg)) + | 14 -> u_double st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 15 -> u_char st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 16 -> u_sbyte st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 17 -> u_byte st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 18 -> u_int16 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 19 -> u_uint16 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 20 -> u_int32 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 21 -> u_uint32 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 22 -> u_int64 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 23 -> u_uint64 st |> (fun a (OneTyArg(tyarg)) -> mkLiftedValueOpG (a, tyarg)) + | 24 -> u_void st |> (fun () NoTyArgs -> mkLiftedValueOpG ((), typeof)) + | 25 -> u_PropInfoData st |> (fun (a, b, c, d) tyargs -> let pinfo = bindProp(a, b, c, d, tyargs) in if pinfoIsStatic pinfo then StaticPropGetOp(pinfo) else InstancePropGetOp(pinfo)) + | 26 -> u_CtorInfoData st |> (fun (a, b) tyargs -> NewObjectOp (bindCtor(a, b, tyargs))) + | 28 -> u_void st |> (fun () (OneTyArg(ty)) -> CoerceOp ty) + | 29 -> u_void st |> (fun () NoTyArgs -> SequentialOp) + | 30 -> u_void st |> (fun () NoTyArgs -> ForIntegerRangeLoopOp) + | 31 -> u_MethodInfoData st |> (fun p tyargs -> let minfo = bindMeth(p, tyargs) in if minfo.IsStatic then StaticMethodCallOp(minfo) else InstanceMethodCallOp(minfo)) + | 32 -> u_void st |> (fun () (OneTyArg(ty)) -> NewArrayOp ty) + | 33 -> u_void st |> (fun () (OneTyArg(ty)) -> NewDelegateOp ty) + | 34 -> u_void st |> (fun () NoTyArgs -> WhileLoopOp) + | 35 -> u_void st |> (fun () NoTyArgs -> LetOp) + | 36 -> u_RecdField st |> (fun prop tyargs -> InstancePropSetOp(prop tyargs)) + | 37 -> u_tup2 u_NamedType u_string st |> (fun (a, b) tyargs -> let finfo = bindField(a, b, tyargs) in if finfo.IsStatic then StaticFieldGetOp(finfo) else InstanceFieldGetOp(finfo)) + | 38 -> u_void st |> (fun () NoTyArgs -> LetRecCombOp) + | 39 -> u_void st |> (fun () NoTyArgs -> AppOp) + | 40 -> u_void st |> (fun () (OneTyArg(ty)) -> ValueOp(null, ty, None)) + | 41 -> u_void st |> (fun () (OneTyArg(ty)) -> DefaultValueOp(ty)) + | 42 -> u_PropInfoData st |> (fun (a, b, c, d) tyargs -> let pinfo = bindProp(a, b, c, d, tyargs) in if pinfoIsStatic pinfo then StaticPropSetOp(pinfo) else InstancePropSetOp(pinfo)) + | 43 -> u_tup2 u_NamedType u_string st |> (fun (a, b) tyargs -> let finfo = bindField(a, b, tyargs) in if finfo.IsStatic then StaticFieldSetOp(finfo) else InstanceFieldSetOp(finfo)) + | 44 -> u_void st |> (fun () NoTyArgs -> AddressOfOp) + | 45 -> u_void st |> (fun () NoTyArgs -> AddressSetOp) + | 46 -> u_void st |> (fun () (OneTyArg(ty)) -> TypeTestOp(ty)) + | 47 -> u_void st |> (fun () NoTyArgs -> TryFinallyOp) + | 48 -> u_void st |> (fun () NoTyArgs -> TryWithOp) + | 49 -> u_void st |> (fun () NoTyArgs -> VarSetOp) | _ -> failwithf "u_constSpec, unrecognized tag %d" tag Unique constSpec + let u_ReflectedDefinition = u_tup2 u_MethodBase u_Expr + let u_ReflectedDefinitions = u_list u_ReflectedDefinition - let unpickleExpr (localType: Type) referencedTypes bytes = + let unpickleExpr (localType: Type) referencedTypes bytes = unpickleObj localType.Assembly referencedTypes u_Expr bytes - let unpickleReflectedDefns localAssembly referencedTypes bytes = + let unpickleReflectedDefns localAssembly referencedTypes bytes = unpickleObj localAssembly referencedTypes u_ReflectedDefinitions bytes //-------------------------------------------------------------------------- - // General utilities that will eventually be folded into + // General utilities that will eventually be folded into // Microsoft.FSharp.Quotations.Typed //-------------------------------------------------------------------------- - - /// Fill the holes in an Expr - let rec fillHolesInRawExpr (l:Expr[]) (E t as e) = - match t with + + /// Fill the holes in an Expr + let rec fillHolesInRawExpr (l:Expr[]) (E t as e) = + match t with | VarTerm _ -> e - | LambdaTerm (v,b) -> EA(LambdaTerm(v, fillHolesInRawExpr l b ),e.CustomAttributes) - | CombTerm (op,args) -> EA(CombTerm(op, args |> List.map (fillHolesInRawExpr l)),e.CustomAttributes) - | HoleTerm (ty,idx) -> - if idx < 0 || idx >= l.Length then failwith "hole index out of range"; + | LambdaTerm (v, b) -> EA(LambdaTerm(v, fillHolesInRawExpr l b ), e.CustomAttributes) + | CombTerm (op, args) -> EA(CombTerm(op, args |> List.map (fillHolesInRawExpr l)), e.CustomAttributes) + | HoleTerm (ty, idx) -> + if idx < 0 || idx >= l.Length then failwith "hole index out of range" let h = l.[idx] match typeOf h with | expected when expected <> ty -> invalidArg "receivedType" (String.Format(SR.GetString(SR.QtmmRaw), expected, ty)) | _ -> h - let rec freeInExprAcc bvs acc (E t) = - match t with - | HoleTerm _ -> acc + let rec freeInExprAcc bvs acc (E t) = + match t with + | HoleTerm _ -> acc | CombTerm (_, ag) -> ag |> List.fold (freeInExprAcc bvs) acc | VarTerm v -> if Set.contains v bvs || Set.contains v acc then acc else Set.add v acc - | LambdaTerm (v,b) -> freeInExprAcc (Set.add v bvs) acc b + | LambdaTerm (v, b) -> freeInExprAcc (Set.add v bvs) acc b and freeInExpr e = freeInExprAcc Set.empty Set.empty e // utility for folding - let foldWhile f st (ie: seq<'T>) = + let foldWhile f st (ie: seq<'T>) = use e = ie.GetEnumerator() let mutable res = Some st while (res.IsSome && e.MoveNext()) do - res <- f (match res with Some a -> a | _ -> failwith "internal error") e.Current; - res - + res <- f (match res with Some a -> a | _ -> failwith "internal error") e.Current + res + [] exception Clash of Var /// Replace type variables and expression variables with parameters using the - /// given substitution functions/maps. - let rec substituteInExpr bvs tmsubst (E t as e) = - match t with - | CombTerm (c, args) -> - let substargs = args |> List.map (fun arg -> substituteInExpr bvs tmsubst arg) - EA(CombTerm(c, substargs),e.CustomAttributes) - | VarTerm v -> - match tmsubst v with - | None -> e - | Some e2 -> - let fvs = freeInExpr e2 + /// given substitution functions/maps. + let rec substituteInExpr bvs tmsubst (E t as e) = + match t with + | CombTerm (c, args) -> + let substargs = args |> List.map (fun arg -> substituteInExpr bvs tmsubst arg) + EA(CombTerm(c, substargs), e.CustomAttributes) + | VarTerm v -> + match tmsubst v with + | None -> e + | Some e2 -> + let fvs = freeInExpr e2 let clashes = Set.intersect fvs bvs in if clashes.IsEmpty then e2 - else raise (Clash(clashes.MinimumElement)) - | LambdaTerm (v,b) -> - try EA(LambdaTerm(v,substituteInExpr (Set.add v bvs) tmsubst b),e.CustomAttributes) + else raise (Clash(clashes.MinimumElement)) + | LambdaTerm (v, b) -> + try EA(LambdaTerm(v, substituteInExpr (Set.add v bvs) tmsubst b), e.CustomAttributes) with Clash(bv) -> if v = bv then - let v2 = new Var(v.Name,v.Type) + let v2 = new Var(v.Name, v.Type) let v2exp = E(VarTerm(v2)) - EA(LambdaTerm(v2,substituteInExpr bvs (fun v -> if v = bv then Some(v2exp) else tmsubst v) b),e.CustomAttributes) + EA(LambdaTerm(v2, substituteInExpr bvs (fun v -> if v = bv then Some(v2exp) else tmsubst v) b), e.CustomAttributes) else reraise() | HoleTerm _ -> e - let substituteRaw tmsubst e = substituteInExpr Set.empty tmsubst e + let substituteRaw tmsubst e = substituteInExpr Set.empty tmsubst e - let readToEnd (s : Stream) = - let n = int s.Length - let res = Array.zeroCreate n - let i = ref 0 - while (!i < n) do - i := !i + s.Read(res,!i,(n - !i)) - done; - res + let readToEnd (s : Stream) = + let n = int s.Length + let res = Array.zeroCreate n + let mutable i = 0 + while (i < n) do + i <- i + s.Read(res, i, (n - i)) + res - let decodedTopResources = new Dictionary(10,HashIdentity.Structural) + let decodedTopResources = new Dictionary(10, HashIdentity.Structural) #if !FX_NO_REFLECTION_METADATA_TOKENS #if FX_NO_REFLECTION_MODULE_HANDLES // not available on Silverlight [] type ModuleHandle = ModuleHandle of string * string - type System.Reflection.Module with + type System.Reflection.Module with member x.ModuleHandle = ModuleHandle(x.Assembly.FullName, x.Name) #else type ModuleHandle = System.ModuleHandle #endif #endif - + #if FX_NO_REFLECTION_METADATA_TOKENS // not available on Compact Framework [] - type ReflectedDefinitionTableKey = + type ReflectedDefinitionTableKey = // Key is declaring type * type parameters count * name * parameter types * return type // Registered reflected definitions can contain generic methods or constructors in generic types, // however TryGetReflectedDefinition can be queried with concrete instantiations of the same methods that doesn't contain type parameters. // To make these two cases match we apply the following transformations: // 1. if declaring type is generic - key will contain generic type definition, otherwise - type itself // 2. if method is instantiation of generic one - pick parameters from generic method definition, otherwise - from methods itself - // 3 if method is constructor and declaring type is generic then we'll use the following trick to treat C<'a>() and C() as the same type - // - we resolve method handle of the constructor using generic type definition - as a result for constructor from instantiated type we obtain matching constructor in generic type definition + // 3 if method is constructor and declaring type is generic then we'll use the following trick to treat C<'a>() and C() as the same type + // - we resolve method handle of the constructor using generic type definition - as a result for constructor from instantiated type we obtain matching constructor in generic type definition | Key of System.Type * int * string * System.Type[] * System.Type - static member GetKey(methodBase:MethodBase) = + static member GetKey(methodBase:MethodBase) = let isGenericType = methodBase.DeclaringType.IsGenericType - let declaringType = - if isGenericType then - methodBase.DeclaringType.GetGenericTypeDefinition() + let declaringType = + if isGenericType then + methodBase.DeclaringType.GetGenericTypeDefinition() else methodBase.DeclaringType - let tyArgsCount = - if methodBase.IsGenericMethod then - methodBase.GetGenericArguments().Length + let tyArgsCount = + if methodBase.IsGenericMethod then + methodBase.GetGenericArguments().Length else 0 #if FX_RESHAPED_REFLECTION // this is very unfortunate consequence of limited Reflection capabilities on .NETCore // what we want: having MethodBase for some concrete method or constructor we would like to locate corresponding MethodInfo\ConstructorInfo from the open generic type (canonical form). // It is necessary to build the key for the table of reflected definitions: reflection definition is saved for open generic type but user may request it using // arbitrary instantiation. - let findMethodInOpenGenericType (mb : ('T :> MethodBase)) : 'T = - let candidates = - let bindingFlags = + let findMethodInOpenGenericType (mb : ('T :> MethodBase)) : 'T = + let candidates = + let bindingFlags = (if mb.IsPublic then BindingFlags.Public else BindingFlags.NonPublic) ||| (if mb.IsStatic then BindingFlags.Static else BindingFlags.Instance) let candidates : MethodBase[] = @@ -1703,13 +1737,13 @@ module Patterns = else box (declaringType.GetMethods(bindingFlags)) ) - candidates |> Array.filter (fun c -> - c.Name = mb.Name && + candidates |> Array.filter (fun c -> + c.Name = mb.Name && (c.GetParameters().Length) = (mb.GetParameters().Length) && (c.IsGenericMethod = mb.IsGenericMethod) && (if c.IsGenericMethod then c.GetGenericArguments().Length = mb.GetGenericArguments().Length else true) ) - let solution = + let solution = if candidates.Length = 0 then failwith "Unexpected, failed to locate matching method" elif candidates.Length = 1 then candidates.[0] else @@ -1728,9 +1762,9 @@ module Patterns = // - rate is increased on EXACT_MATCHING_COST if type of argument that candidate has at position i exactly matched the type of argument for the original method. // - rate is increased on GENERIC_TYPE_MATCHING_COST if candidate has generic argument at given position and its type matched the type of argument for the original method. // - otherwise rate will be 0 - let evaluateCandidate (mb : MethodBase) : int = + let evaluateCandidate (mb : MethodBase) : int = let parameters = mb.GetParameters() - let rec loop i resultSoFar = + let rec loop i resultSoFar = if i >= parameters.Length then resultSoFar else let p = parameters.[i] @@ -1745,14 +1779,14 @@ module Patterns = loop 0 0 - Array.maxBy evaluateCandidate candidates + Array.maxBy evaluateCandidate candidates solution :?> 'T #endif match methodBase with | :? MethodInfo as mi -> - let mi = - if mi.IsGenericMethod then + let mi = + if mi.IsGenericMethod then let mi = mi.GetGenericMethodDefinition() if isGenericType then #if FX_RESHAPED_REFLECTION @@ -1766,7 +1800,7 @@ module Patterns = let paramTypes = mi.GetParameters() |> getTypesFromParamInfos Key(declaringType, tyArgsCount, methodBase.Name, paramTypes, mi.ReturnType) | :? ConstructorInfo as ci -> - let mi = + let mi = if isGenericType then #if FX_RESHAPED_REFLECTION findMethodInOpenGenericType ci @@ -1780,216 +1814,216 @@ module Patterns = | _ -> failwithf "Unexpected MethodBase type, %A" (methodBase.GetType()) // per MSDN ConstructorInfo and MethodInfo are the only derived types from MethodBase #else [] - type ReflectedDefinitionTableKey = + type ReflectedDefinitionTableKey = | Key of ModuleHandle * int - static member GetKey(methodBase:MethodBase) = - Key(methodBase.Module.ModuleHandle,methodBase.MetadataToken) + static member GetKey(methodBase:MethodBase) = + Key(methodBase.Module.ModuleHandle, methodBase.MetadataToken) #endif [] type ReflectedDefinitionTableEntry = Entry of Bindable - let reflectedDefinitionTable = new Dictionary(10,HashIdentity.Structural) + let reflectedDefinitionTable = new Dictionary(10, HashIdentity.Structural) let registerReflectedDefinitions (assem, resourceName, bytes, referencedTypes) = - let defns = unpickleReflectedDefns assem referencedTypes bytes - defns |> List.iter (fun (minfo,exprBuilder) -> + let defns = unpickleReflectedDefns assem referencedTypes bytes + defns |> List.iter (fun (minfo, exprBuilder) -> let key = ReflectedDefinitionTableKey.GetKey minfo - lock reflectedDefinitionTable (fun () -> - reflectedDefinitionTable.Add(key,Entry(exprBuilder)))) - decodedTopResources.Add((assem,resourceName),0) + lock reflectedDefinitionTable (fun () -> + reflectedDefinitionTable.Add(key, Entry(exprBuilder)))) + decodedTopResources.Add((assem, resourceName), 0) let tryGetReflectedDefinition (methodBase: MethodBase, tyargs: Type []) = checkNonNull "methodBase" methodBase - let data = + let data = let assem = methodBase.DeclaringType.Assembly let key = ReflectedDefinitionTableKey.GetKey methodBase - let ok,res = lock reflectedDefinitionTable (fun () -> reflectedDefinitionTable.TryGetValue(key)) + let ok, res = lock reflectedDefinitionTable (fun () -> reflectedDefinitionTable.TryGetValue(key)) if ok then Some res else - let qdataResources = - // dynamic assemblies don't support the GetManifestResourceNames - match assem with + let qdataResources = + // dynamic assemblies don't support the GetManifestResourceNames + match assem with | a when a.FullName = "System.Reflection.Emit.AssemblyBuilder" -> [] - | null | _ -> - let resources = + | null | _ -> + let resources = // This raises NotSupportedException for dynamic assemblies try assem.GetManifestResourceNames() with :? NotSupportedException -> [| |] [ for resourceName in resources do - if resourceName.StartsWith(ReflectedDefinitionsResourceNameBase,StringComparison.Ordinal) && - not (decodedTopResources.ContainsKey((assem,resourceName))) then + if resourceName.StartsWith(ReflectedDefinitionsResourceNameBase, StringComparison.Ordinal) && + not (decodedTopResources.ContainsKey((assem, resourceName))) then - let cmaAttribForResource = + let cmaAttribForResource = #if FX_RESHAPED_REFLECTION CustomAttributeExtensions.GetCustomAttributes(assem, typeof) |> Seq.toArray #else assem.GetCustomAttributes(typeof, false) #endif |> (function null -> [| |] | x -> x) - |> Array.tryPick (fun ca -> - match ca with - | :? CompilationMappingAttribute as cma when cma.ResourceName = resourceName -> Some cma - | _ -> None) + |> Array.tryPick (fun ca -> + match ca with + | :? CompilationMappingAttribute as cma when cma.ResourceName = resourceName -> Some cma + | _ -> None) let resourceBytes = readToEnd (assem.GetManifestResourceStream(resourceName)) - let referencedTypes = - match cmaAttribForResource with + let referencedTypes = + match cmaAttribForResource with | None -> [| |] | Some cma -> cma.TypeDefinitions - yield (resourceName,unpickleReflectedDefns assem referencedTypes resourceBytes) ] - + yield (resourceName, unpickleReflectedDefns assem referencedTypes resourceBytes) ] + // ok, add to the table - let ok,res = - lock reflectedDefinitionTable (fun () -> + let ok, res = + lock reflectedDefinitionTable (fun () -> // check another thread didn't get in first if not (reflectedDefinitionTable.ContainsKey(key)) then - qdataResources - |> List.iter (fun (resourceName,defns) -> - defns |> List.iter (fun (methodBase,exprBuilder) -> - reflectedDefinitionTable.[ReflectedDefinitionTableKey.GetKey methodBase] <- Entry(exprBuilder)); - decodedTopResources.Add((assem,resourceName),0)) + qdataResources + |> List.iter (fun (resourceName, defns) -> + defns |> List.iter (fun (methodBase, exprBuilder) -> + reflectedDefinitionTable.[ReflectedDefinitionTableKey.GetKey methodBase] <- Entry(exprBuilder)) + decodedTopResources.Add((assem, resourceName), 0)) // we know it's in the table now, if it's ever going to be there - reflectedDefinitionTable.TryGetValue(key) - ); + reflectedDefinitionTable.TryGetValue(key) + ) if ok then Some res else None - match data with - | Some (Entry(exprBuilder)) -> - let expectedNumTypars = - getNumGenericArguments(methodBase.DeclaringType) + - (match methodBase with + match data with + | Some (Entry(exprBuilder)) -> + let expectedNumTypars = + getNumGenericArguments(methodBase.DeclaringType) + + (match methodBase with | :? MethodInfo as minfo -> if minfo.IsGenericMethod then minfo.GetGenericArguments().Length else 0 | _ -> 0) - if (expectedNumTypars <> tyargs.Length) then - invalidArg "tyargs" (String.Format(SR.GetString(SR.QwrongNumOfTypeArgs), methodBase.Name, expectedNumTypars.ToString(), tyargs.Length.ToString())); + if (expectedNumTypars <> tyargs.Length) then + invalidArg "tyargs" (String.Format(SR.GetString(SR.QwrongNumOfTypeArgs), methodBase.Name, expectedNumTypars.ToString(), tyargs.Length.ToString())) Some(exprBuilder (envClosed tyargs)) | None -> None - let tryGetReflectedDefinitionInstantiated (methodBase:MethodBase) = + let tryGetReflectedDefinitionInstantiated (methodBase:MethodBase) = checkNonNull "methodBase" methodBase - match methodBase with - | :? MethodInfo as minfo -> - let tyargs = + match methodBase with + | :? MethodInfo as minfo -> + let tyargs = Array.append (getGenericArguments minfo.DeclaringType) (if minfo.IsGenericMethod then minfo.GetGenericArguments() else [| |]) tryGetReflectedDefinition (methodBase, tyargs) - | :? ConstructorInfo as cinfo -> + | :? ConstructorInfo as cinfo -> let tyargs = getGenericArguments cinfo.DeclaringType tryGetReflectedDefinition (methodBase, tyargs) - | _ -> + | _ -> tryGetReflectedDefinition (methodBase, [| |]) - let deserialize (localAssembly, referencedTypeDefs, spliceTypes, spliceExprs, bytes) : Expr = + let deserialize (localAssembly, referencedTypeDefs, spliceTypes, spliceExprs, bytes) : Expr = let expr = unpickleExpr localAssembly referencedTypeDefs bytes (envClosed spliceTypes) fillHolesInRawExpr spliceExprs expr - - - let cast (expr: Expr) : Expr<'T> = - checkTypesSR (typeof<'T>) (typeOf expr) "expr" (SR.GetString(SR.QtmmExprHasWrongType)) - new Expr<'T>(expr.Tree,expr.CustomAttributes) + + + let cast (expr: Expr) : Expr<'T> = + checkTypesSR (typeof<'T>) (typeOf expr) "expr" (SR.GetString(SR.QtmmExprHasWrongType)) + new Expr<'T>(expr.Tree, expr.CustomAttributes) open Patterns -type Expr with +type Expr with member x.Substitute substitution = substituteRaw substitution x - member x.GetFreeVars () = (freeInExpr x :> seq<_>) - member x.Type = typeOf x + member x.GetFreeVars () = (freeInExpr x :> seq<_>) + member x.Type = typeOf x - static member AddressOf (target:Expr) = - mkAddressOf target + static member AddressOf (target:Expr) = + mkAddressOf target - static member AddressSet (target:Expr, value:Expr) = - mkAddressSet (target,value) + static member AddressSet (target:Expr, value:Expr) = + mkAddressSet (target, value) - static member Application (functionExpr:Expr, argument:Expr) = - mkApplication (functionExpr,argument) + static member Application (functionExpr:Expr, argument:Expr) = + mkApplication (functionExpr, argument) - static member Applications (functionExpr:Expr, arguments) = + static member Applications (functionExpr:Expr, arguments) = mkApplications (functionExpr, arguments) - static member Call (methodInfo:MethodInfo, arguments) = + static member Call (methodInfo:MethodInfo, arguments) = checkNonNull "methodInfo" methodInfo mkStaticMethodCall (methodInfo, arguments) - static member Call (obj:Expr,methodInfo:MethodInfo, arguments) = + static member Call (obj:Expr, methodInfo:MethodInfo, arguments) = checkNonNull "methodInfo" methodInfo - mkInstanceMethodCall (obj,methodInfo,arguments) + mkInstanceMethodCall (obj, methodInfo, arguments) - static member Coerce (source:Expr, target:Type) = + static member Coerce (source:Expr, target:Type) = checkNonNull "target" target mkCoerce (target, source) - static member IfThenElse (guard:Expr, thenExpr:Expr, elseExpr:Expr) = + static member IfThenElse (guard:Expr, thenExpr:Expr, elseExpr:Expr) = mkIfThenElse (guard, thenExpr, elseExpr) - static member ForIntegerRangeLoop (loopVariable, start:Expr, endExpr:Expr, body:Expr) = + static member ForIntegerRangeLoop (loopVariable, start:Expr, endExpr:Expr, body:Expr) = mkForLoop(loopVariable, start, endExpr, body) - static member FieldGet (fieldInfo:FieldInfo) = + static member FieldGet (fieldInfo:FieldInfo) = checkNonNull "fieldInfo" fieldInfo mkStaticFieldGet fieldInfo - static member FieldGet (obj:Expr, fieldInfo:FieldInfo) = + static member FieldGet (obj:Expr, fieldInfo:FieldInfo) = checkNonNull "fieldInfo" fieldInfo mkInstanceFieldGet (obj, fieldInfo) - - static member FieldSet (fieldInfo:FieldInfo, value:Expr) = + + static member FieldSet (fieldInfo:FieldInfo, value:Expr) = checkNonNull "fieldInfo" fieldInfo mkStaticFieldSet (fieldInfo, value) - - static member FieldSet (obj:Expr, fieldInfo:FieldInfo, value:Expr) = + + static member FieldSet (obj:Expr, fieldInfo:FieldInfo, value:Expr) = checkNonNull "fieldInfo" fieldInfo mkInstanceFieldSet (obj, fieldInfo, value) static member Lambda (parameter:Var, body:Expr) = mkLambda (parameter, body) - static member Let (letVariable:Var,letExpr:Expr,body:Expr) = mkLet (letVariable, letExpr, body) + static member Let (letVariable:Var, letExpr:Expr, body:Expr) = mkLet (letVariable, letExpr, body) static member LetRecursive (bindings, body:Expr) = mkLetRec (bindings, body) - static member NewObject (constructorInfo:ConstructorInfo, arguments) = + static member NewObject (constructorInfo:ConstructorInfo, arguments) = checkNonNull "constructorInfo" constructorInfo mkCtorCall (constructorInfo, arguments) - static member DefaultValue (expressionType:Type) = + static member DefaultValue (expressionType:Type) = checkNonNull "expressionType" expressionType mkDefaultValue expressionType - static member NewTuple elements = + static member NewTuple elements = mkNewTuple elements - static member NewRecord (recordType:Type, elements) = + static member NewRecord (recordType:Type, elements) = checkNonNull "recordType" recordType mkNewRecord (recordType, elements) - static member NewArray (elementType:Type, elements) = + static member NewArray (elementType:Type, elements) = checkNonNull "elementType" elementType mkNewArray(elementType, elements) - static member NewDelegate (delegateType:Type, parameters: Var list, body: Expr) = + static member NewDelegate (delegateType:Type, parameters: Var list, body: Expr) = checkNonNull "delegateType" delegateType mkNewDelegate(delegateType, mkIteratedLambdas (parameters, body)) - static member NewUnionCase (unionCase, arguments) = + static member NewUnionCase (unionCase, arguments) = mkNewUnionCase (unionCase, arguments) - - static member PropertyGet (obj:Expr, property: PropertyInfo, ?indexerArgs) = + + static member PropertyGet (obj:Expr, property: PropertyInfo, ?indexerArgs) = checkNonNull "property" property mkInstancePropGet (obj, property, defaultArg indexerArgs []) - static member PropertyGet (property: PropertyInfo, ?indexerArgs) = + static member PropertyGet (property: PropertyInfo, ?indexerArgs) = checkNonNull "property" property mkStaticPropGet (property, defaultArg indexerArgs []) - static member PropertySet (obj:Expr, property:PropertyInfo, value:Expr, ?indexerArgs) = + static member PropertySet (obj:Expr, property:PropertyInfo, value:Expr, ?indexerArgs) = checkNonNull "property" property mkInstancePropSet(obj, property, defaultArg indexerArgs [], value) - static member PropertySet (property:PropertyInfo, value:Expr, ?indexerArgs) = + static member PropertySet (property:PropertyInfo, value:Expr, ?indexerArgs) = mkStaticPropSet(property, defaultArg indexerArgs [], value) static member Quote (inner:Expr) = mkQuote (inner, true) @@ -1998,71 +2032,71 @@ type Expr with static member QuoteTyped (inner:Expr) = mkQuote (inner, true) - static member Sequential (first:Expr, second:Expr) = + static member Sequential (first:Expr, second:Expr) = mkSequential (first, second) - static member TryWith (body:Expr, filterVar:Var, filterBody:Expr, catchVar:Var, catchBody:Expr) = + static member TryWith (body:Expr, filterVar:Var, filterBody:Expr, catchVar:Var, catchBody:Expr) = mkTryWith (body, filterVar, filterBody, catchVar, catchBody) - static member TryFinally (body:Expr, compensation:Expr) = + static member TryFinally (body:Expr, compensation:Expr) = mkTryFinally (body, compensation) - static member TupleGet (tuple:Expr, index:int) = + static member TupleGet (tuple:Expr, index:int) = mkTupleGet (typeOf tuple, index, tuple) - static member TypeTest (source: Expr, target: Type) = + static member TypeTest (source: Expr, target: Type) = checkNonNull "target" target mkTypeTest (source, target) - static member UnionCaseTest (source:Expr, unionCase: UnionCaseInfo) = + static member UnionCaseTest (source:Expr, unionCase: UnionCaseInfo) = mkUnionCaseTest (unionCase, source) - static member Value (value:'T) = + static member Value (value:'T) = mkValue (box value, typeof<'T>) - static member Value(value: obj, expressionType: Type) = + static member Value(value: obj, expressionType: Type) = checkNonNull "expressionType" expressionType mkValue(value, expressionType) - static member ValueWithName (value:'T, name:string) = + static member ValueWithName (value:'T, name:string) = checkNonNull "name" name mkValueWithName (box value, typeof<'T>, name) - static member ValueWithName(value: obj, expressionType: Type, name:string) = + static member ValueWithName(value: obj, expressionType: Type, name:string) = checkNonNull "expressionType" expressionType checkNonNull "name" name mkValueWithName(value, expressionType, name) - static member WithValue (value:'T, definition: Expr<'T>) = + static member WithValue (value:'T, definition: Expr<'T>) = let raw = mkValueWithDefn(box value, typeof<'T>, definition) - new Expr<'T>(raw.Tree,raw.CustomAttributes) + new Expr<'T>(raw.Tree, raw.CustomAttributes) - static member WithValue(value: obj, expressionType: Type, definition: Expr) = + static member WithValue(value: obj, expressionType: Type, definition: Expr) = checkNonNull "expressionType" expressionType mkValueWithDefn (value, expressionType, definition) - static member Var(variable) = + static member Var(variable) = mkVar(variable) - static member VarSet (variable, value:Expr) = + static member VarSet (variable, value:Expr) = mkVarSet (variable, value) - static member WhileLoop (guard:Expr, body:Expr) = + static member WhileLoop (guard:Expr, body:Expr) = mkWhileLoop (guard, body) - static member TryGetReflectedDefinition(methodBase:MethodBase) = + static member TryGetReflectedDefinition(methodBase:MethodBase) = checkNonNull "methodBase" methodBase tryGetReflectedDefinitionInstantiated(methodBase) static member Cast(source:Expr) = cast source - static member Deserialize(qualifyingType:Type, spliceTypes, spliceExprs, bytes: byte[]) = + static member Deserialize(qualifyingType:Type, spliceTypes, spliceExprs, bytes: byte[]) = checkNonNull "qualifyingType" qualifyingType checkNonNull "bytes" bytes deserialize (qualifyingType, [| |], Array.ofList spliceTypes, Array.ofList spliceExprs, bytes) - static member Deserialize40(qualifyingType:Type, referencedTypes, spliceTypes, spliceExprs, bytes: byte[]) = + static member Deserialize40(qualifyingType:Type, referencedTypes, spliceTypes, spliceExprs, bytes: byte[]) = checkNonNull "spliceExprs" spliceExprs checkNonNull "spliceTypes" spliceTypes checkNonNull "referencedTypeDefs" referencedTypes @@ -2070,14 +2104,14 @@ type Expr with checkNonNull "bytes" bytes deserialize (qualifyingType, referencedTypes, spliceTypes, spliceExprs, bytes) - static member RegisterReflectedDefinitions(assembly, resource, serializedValue) = - Expr.RegisterReflectedDefinitions(assembly, resource, serializedValue, [| |]) + static member RegisterReflectedDefinitions(assembly, resource, serializedValue) = + Expr.RegisterReflectedDefinitions(assembly, resource, serializedValue, [| |]) - static member RegisterReflectedDefinitions(assembly, resource, serializedValue, referencedTypes) = + static member RegisterReflectedDefinitions(assembly, resource, serializedValue, referencedTypes) = checkNonNull "assembly" assembly registerReflectedDefinitions(assembly, resource, serializedValue, referencedTypes) - static member GlobalVar<'T>(name) : Expr<'T> = + static member GlobalVar<'T>(name) : Expr<'T> = checkNonNull "name" name Expr.Var(Var.Global(name, typeof<'T>)) |> Expr.Cast @@ -2086,113 +2120,113 @@ module DerivedPatterns = open Patterns [] - let (|Bool|_|) input = match input with ValueObj(:? bool as v) -> Some(v) | _ -> None + let (|Bool|_|) input = match input with ValueObj(:? bool as v) -> Some(v) | _ -> None [] - let (|String|_|) input = match input with ValueObj(:? string as v) -> Some(v) | _ -> None + let (|String|_|) input = match input with ValueObj(:? string as v) -> Some(v) | _ -> None [] - let (|Single|_|) input = match input with ValueObj(:? single as v) -> Some(v) | _ -> None + let (|Single|_|) input = match input with ValueObj(:? single as v) -> Some(v) | _ -> None [] - let (|Double|_|) input = match input with ValueObj(:? double as v) -> Some(v) | _ -> None + let (|Double|_|) input = match input with ValueObj(:? double as v) -> Some(v) | _ -> None [] - let (|Char|_|) input = match input with ValueObj(:? char as v) -> Some(v) | _ -> None + let (|Char|_|) input = match input with ValueObj(:? char as v) -> Some(v) | _ -> None [] - let (|SByte|_|) input = match input with ValueObj(:? sbyte as v) -> Some(v) | _ -> None + let (|SByte|_|) input = match input with ValueObj(:? sbyte as v) -> Some(v) | _ -> None [] - let (|Byte|_|) input = match input with ValueObj(:? byte as v) -> Some(v) | _ -> None + let (|Byte|_|) input = match input with ValueObj(:? byte as v) -> Some(v) | _ -> None [] - let (|Int16|_|) input = match input with ValueObj(:? int16 as v) -> Some(v) | _ -> None + let (|Int16|_|) input = match input with ValueObj(:? int16 as v) -> Some(v) | _ -> None [] - let (|UInt16|_|) input = match input with ValueObj(:? uint16 as v) -> Some(v) | _ -> None + let (|UInt16|_|) input = match input with ValueObj(:? uint16 as v) -> Some(v) | _ -> None [] - let (|Int32|_|) input = match input with ValueObj(:? int32 as v) -> Some(v) | _ -> None + let (|Int32|_|) input = match input with ValueObj(:? int32 as v) -> Some(v) | _ -> None [] - let (|UInt32|_|) input = match input with ValueObj(:? uint32 as v) -> Some(v) | _ -> None + let (|UInt32|_|) input = match input with ValueObj(:? uint32 as v) -> Some(v) | _ -> None [] - let (|Int64|_|) input = match input with ValueObj(:? int64 as v) -> Some(v) | _ -> None + let (|Int64|_|) input = match input with ValueObj(:? int64 as v) -> Some(v) | _ -> None [] - let (|UInt64|_|) input = match input with ValueObj(:? uint64 as v) -> Some(v) | _ -> None + let (|UInt64|_|) input = match input with ValueObj(:? uint64 as v) -> Some(v) | _ -> None [] - let (|Unit|_|) input = match input with Comb0(ValueOp(_,ty,None)) when ty = typeof -> Some() | _ -> None + let (|Unit|_|) input = match input with Comb0(ValueOp(_, ty, None)) when ty = typeof -> Some() | _ -> None - /// (fun (x,y) -> z) is represented as 'fun p -> let x = p#0 let y = p#1' etc. + /// (fun (x, y) -> z) is represented as 'fun p -> let x = p#0 let y = p#1' etc. /// This reverses this encoding. let (|TupledLambda|_|) (lam: Expr) = /// Strip off the 'let' bindings for an TupledLambda let rec stripSuccessiveProjLets (p:Var) n expr = - match expr with - | Let(v1,TupleGet(Var(pA),m),rest) - when p = pA && m = n-> - let restvs,b = stripSuccessiveProjLets p (n+1) rest + match expr with + | Let(v1, TupleGet(Var(pA), m), rest) + when p = pA && m = n-> + let restvs, b = stripSuccessiveProjLets p (n+1) rest v1::restvs, b - | _ -> ([],expr) - match lam.Tree with - | LambdaTerm(v,body) -> - match stripSuccessiveProjLets v 0 body with - | [],b -> Some([v], b) - | letvs,b -> Some(letvs,b) + | _ -> ([], expr) + match lam.Tree with + | LambdaTerm(v, body) -> + match stripSuccessiveProjLets v 0 body with + | [], b -> Some([v], b) + | letvs, b -> Some(letvs, b) | _ -> None - let (|TupledApplication|_|) e = - match e with - | Application(f,x) -> - match x with - | Unit -> Some(f,[]) - | NewTuple(x) -> Some(f,x) - | x -> Some(f,[x]) + let (|TupledApplication|_|) e = + match e with + | Application(f, x) -> + match x with + | Unit -> Some(f, []) + | NewTuple(x) -> Some(f, x) + | x -> Some(f, [x]) | _ -> None - + [] - let (|Lambdas|_|) (input: Expr) = qOneOrMoreRLinear (|TupledLambda|_|) input + let (|Lambdas|_|) (input: Expr) = qOneOrMoreRLinear (|TupledLambda|_|) input [] - let (|Applications|_|) (input: Expr) = qOneOrMoreLLinear (|TupledApplication|_|) input + let (|Applications|_|) (input: Expr) = qOneOrMoreLLinear (|TupledApplication|_|) input /// Reverse the compilation of And and Or [] - let (|AndAlso|_|) input = - match input with - | IfThenElse(x,y,Bool(false)) -> Some(x,y) + let (|AndAlso|_|) input = + match input with + | IfThenElse(x, y, Bool(false)) -> Some(x, y) | _ -> None - + [] - let (|OrElse|_|) input = - match input with - | IfThenElse(x,Bool(true),y) -> Some(x,y) + let (|OrElse|_|) input = + match input with + | IfThenElse(x, Bool(true), y) -> Some(x, y) | _ -> None [] - let (|SpecificCall|_|) templateParameter = + let (|SpecificCall|_|) templateParameter = // Note: precomputation match templateParameter with - | (Lambdas(_,Call(_,minfo1,_)) | Call(_,minfo1,_)) -> - let isg1 = minfo1.IsGenericMethod + | (Lambdas(_, Call(_, minfo1, _)) | Call(_, minfo1, _)) -> + let isg1 = minfo1.IsGenericMethod let gmd = if isg1 then minfo1.GetGenericMethodDefinition() else null // end-of-precomputation - (fun tm -> + (fun tm -> match tm with - | Call(obj,minfo2,args) + | Call(obj, minfo2, args) #if FX_NO_REFLECTION_METADATA_TOKENS when ( // if metadata tokens are not available we'll rely only on equality of method references -#else +#else when (minfo1.MetadataToken = minfo2.MetadataToken && -#endif - if isg1 then +#endif + if isg1 then minfo2.IsGenericMethod && gmd = minfo2.GetGenericMethodDefinition() else - minfo1 = minfo2) -> - Some(obj,(minfo2.GetGenericArguments() |> Array.toList),args) + minfo1 = minfo2) -> + Some(obj, (minfo2.GetGenericArguments() |> Array.toList), args) | _ -> None) - | _ -> + | _ -> invalidArg "templateParameter" (SR.GetString(SR.QunrecognizedMethodCall)) - let private new_decimal_info = + let private new_decimal_info = methodhandleof (fun (low, medium, high, isNegative, scale) -> LanguagePrimitives.IntrinsicFunctions.MakeDecimal low medium high isNegative scale) |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo [] - let (|Decimal|_|) input = - match input with + let (|Decimal|_|) input = + match input with | Call (None, mi, [Int32 low; Int32 medium; Int32 high; Bool isNegative; Byte scale]) when mi.Name = new_decimal_info.Name && mi.DeclaringType.FullName = new_decimal_info.DeclaringType.FullName -> @@ -2200,75 +2234,75 @@ module DerivedPatterns = | _ -> None [] - let (|MethodWithReflectedDefinition|_|) (methodBase) = + let (|MethodWithReflectedDefinition|_|) (methodBase) = Expr.TryGetReflectedDefinition(methodBase) - + [] - let (|PropertyGetterWithReflectedDefinition|_|) (propertyInfo:System.Reflection.PropertyInfo) = + let (|PropertyGetterWithReflectedDefinition|_|) (propertyInfo:System.Reflection.PropertyInfo) = Expr.TryGetReflectedDefinition(propertyInfo.GetGetMethod(true)) [] - let (|PropertySetterWithReflectedDefinition|_|) (propertyInfo:System.Reflection.PropertyInfo) = + let (|PropertySetterWithReflectedDefinition|_|) (propertyInfo:System.Reflection.PropertyInfo) = Expr.TryGetReflectedDefinition(propertyInfo.GetSetMethod(true)) [] module ExprShape = open Patterns - let RebuildShapeCombination(shape:obj,arguments) = + let RebuildShapeCombination(shape:obj, arguments) = // preserve the attributes - let op,attrs = unbox(shape) - let e = - match op,arguments with - | AppOp,[f;x] -> mkApplication(f,x) - | IfThenElseOp,[g;t;e] -> mkIfThenElse(g,t,e) - | LetRecOp,[e1] -> mkLetRecRaw(e1) - | LetRecCombOp,_ -> mkLetRecCombRaw(arguments) - | LetOp,[e1;e2] -> mkLetRawWithCheck(e1,e2) - | NewRecordOp(ty),_ -> mkNewRecord(ty, arguments) - | NewUnionCaseOp(unionCase),_ -> mkNewUnionCase(unionCase, arguments) - | UnionCaseTestOp(unionCase),[arg] -> mkUnionCaseTest(unionCase,arg) - | NewTupleOp(ty),_ -> mkNewTupleWithType(ty, arguments) - | TupleGetOp(ty,i),[arg] -> mkTupleGet(ty,i,arg) - | InstancePropGetOp(pinfo),(obj::args) -> mkInstancePropGet(obj,pinfo,args) - | StaticPropGetOp(pinfo),_ -> mkStaticPropGet(pinfo,arguments) - | InstancePropSetOp(pinfo),obj::(FrontAndBack(args,v)) -> mkInstancePropSet(obj,pinfo,args,v) - | StaticPropSetOp(pinfo),(FrontAndBack(args,v)) -> mkStaticPropSet(pinfo,args,v) - | InstanceFieldGetOp(finfo),[obj] -> mkInstanceFieldGet(obj,finfo) - | StaticFieldGetOp(finfo),[] -> mkStaticFieldGet(finfo ) - | InstanceFieldSetOp(finfo),[obj;v] -> mkInstanceFieldSet(obj,finfo,v) - | StaticFieldSetOp(finfo),[v] -> mkStaticFieldSet(finfo,v) - | NewObjectOp minfo,_ -> mkCtorCall(minfo,arguments) - | DefaultValueOp(ty),_ -> mkDefaultValue(ty) - | StaticMethodCallOp(minfo),_ -> mkStaticMethodCall(minfo,arguments) - | InstanceMethodCallOp(minfo),obj::args -> mkInstanceMethodCall(obj,minfo,args) - | CoerceOp(ty),[arg] -> mkCoerce(ty,arg) - | NewArrayOp(ty),_ -> mkNewArray(ty,arguments) - | NewDelegateOp(ty),[arg] -> mkNewDelegate(ty,arg) - | SequentialOp,[e1;e2] -> mkSequential(e1,e2) - | TypeTestOp(ty),[e1] -> mkTypeTest(e1,ty) - | AddressOfOp,[e1] -> mkAddressOf(e1) - | VarSetOp,[E(VarTerm(v)); e] -> mkVarSet(v,e) - | AddressSetOp,[e1;e2] -> mkAddressSet(e1,e2) - | ForIntegerRangeLoopOp,[e1;e2;E(LambdaTerm(v,e3))] -> mkForLoop(v,e1,e2,e3) - | WhileLoopOp,[e1;e2] -> mkWhileLoop(e1,e2) - | TryFinallyOp,[e1;e2] -> mkTryFinally(e1,e2) - | TryWithOp,[e1;Lambda(v1,e2);Lambda(v2,e3)] -> mkTryWith(e1,v1,e2,v2,e3) - | QuoteOp flg,[e1] -> mkQuote(e1,flg) - | ValueOp(v,ty,None),[] -> mkValue(v,ty) - | ValueOp(v,ty,Some nm),[] -> mkValueWithName(v,ty,nm) - | WithValueOp(v,ty),[e] -> mkValueWithDefn(v,ty,e) - | _ -> raise <| System.InvalidOperationException (SR.GetString(SR.QillFormedAppOrLet)) - - - EA(e.Tree,attrs) + let op, attrs = unbox(shape) + let e = + match op, arguments with + | AppOp, [f;x] -> mkApplication(f, x) + | IfThenElseOp, [g;t;e] -> mkIfThenElse(g, t, e) + | LetRecOp, [e1] -> mkLetRecRaw(e1) + | LetRecCombOp, _ -> mkLetRecCombRaw(arguments) + | LetOp, [e1;e2] -> mkLetRawWithCheck(e1, e2) + | NewRecordOp(ty), _ -> mkNewRecord(ty, arguments) + | NewUnionCaseOp(unionCase), _ -> mkNewUnionCase(unionCase, arguments) + | UnionCaseTestOp(unionCase), [arg] -> mkUnionCaseTest(unionCase, arg) + | NewTupleOp(ty), _ -> mkNewTupleWithType(ty, arguments) + | TupleGetOp(ty, i), [arg] -> mkTupleGet(ty, i, arg) + | InstancePropGetOp(pinfo), (obj::args) -> mkInstancePropGet(obj, pinfo, args) + | StaticPropGetOp(pinfo), _ -> mkStaticPropGet(pinfo, arguments) + | InstancePropSetOp(pinfo), obj::(FrontAndBack(args, v)) -> mkInstancePropSet(obj, pinfo, args, v) + | StaticPropSetOp(pinfo), (FrontAndBack(args, v)) -> mkStaticPropSet(pinfo, args, v) + | InstanceFieldGetOp(finfo), [obj] -> mkInstanceFieldGet(obj, finfo) + | StaticFieldGetOp(finfo), [] -> mkStaticFieldGet(finfo ) + | InstanceFieldSetOp(finfo), [obj;v] -> mkInstanceFieldSet(obj, finfo, v) + | StaticFieldSetOp(finfo), [v] -> mkStaticFieldSet(finfo, v) + | NewObjectOp minfo, _ -> mkCtorCall(minfo, arguments) + | DefaultValueOp(ty), _ -> mkDefaultValue(ty) + | StaticMethodCallOp(minfo), _ -> mkStaticMethodCall(minfo, arguments) + | InstanceMethodCallOp(minfo), obj::args -> mkInstanceMethodCall(obj, minfo, args) + | CoerceOp(ty), [arg] -> mkCoerce(ty, arg) + | NewArrayOp(ty), _ -> mkNewArray(ty, arguments) + | NewDelegateOp(ty), [arg] -> mkNewDelegate(ty, arg) + | SequentialOp, [e1;e2] -> mkSequential(e1, e2) + | TypeTestOp(ty), [e1] -> mkTypeTest(e1, ty) + | AddressOfOp, [e1] -> mkAddressOf(e1) + | VarSetOp, [E(VarTerm(v)); e] -> mkVarSet(v, e) + | AddressSetOp, [e1;e2] -> mkAddressSet(e1, e2) + | ForIntegerRangeLoopOp, [e1;e2;E(LambdaTerm(v, e3))] -> mkForLoop(v, e1, e2, e3) + | WhileLoopOp, [e1;e2] -> mkWhileLoop(e1, e2) + | TryFinallyOp, [e1;e2] -> mkTryFinally(e1, e2) + | TryWithOp, [e1;Lambda(v1, e2);Lambda(v2, e3)] -> mkTryWith(e1, v1, e2, v2, e3) + | QuoteOp flg, [e1] -> mkQuote(e1, flg) + | ValueOp(v, ty, None), [] -> mkValue(v, ty) + | ValueOp(v, ty, Some nm), [] -> mkValueWithName(v, ty, nm) + | WithValueOp(v, ty), [e] -> mkValueWithDefn(v, ty, e) + | _ -> raise <| System.InvalidOperationException (SR.GetString(SR.QillFormedAppOrLet)) + + + EA(e.Tree, attrs) [] - let rec (|ShapeVar|ShapeLambda|ShapeCombination|) input = - let rec loop expr = - let (E(t)) = expr - match t with - | VarTerm v -> ShapeVar(v) - | LambdaTerm(v,b) -> ShapeLambda(v,b) - | CombTerm(op,args) -> ShapeCombination(box (op,expr.CustomAttributes),args) - | HoleTerm _ -> invalidArg "expr" (SR.GetString(SR.QunexpectedHole)) + let rec (|ShapeVar|ShapeLambda|ShapeCombination|) input = + let rec loop expr = + let (E(t)) = expr + match t with + | VarTerm v -> ShapeVar(v) + | LambdaTerm(v, b) -> ShapeLambda(v, b) + | CombTerm(op, args) -> ShapeCombination(box (op, expr.CustomAttributes), args) + | HoleTerm _ -> invalidArg "expr" (SR.GetString(SR.QunexpectedHole)) loop (input :> Expr) diff --git a/src/fsharp/FSharp.Core/reflect.fs b/src/fsharp/FSharp.Core/reflect.fs index f0d9c2854c2..14b56e5b4de 100644 --- a/src/fsharp/FSharp.Core/reflect.fs +++ b/src/fsharp/FSharp.Core/reflect.fs @@ -6,6 +6,7 @@ namespace Microsoft.FSharp.Reflection open System +open System.Collections.Generic open System.Reflection open Microsoft.FSharp.Core open Microsoft.FSharp.Core.Operators @@ -13,7 +14,7 @@ open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators open Microsoft.FSharp.Collections open Microsoft.FSharp.Primitives.Basics -module internal ReflectionUtils = +module internal ReflectionUtils = type BindingFlags = System.Reflection.BindingFlags @@ -23,28 +24,28 @@ module internal ReflectionUtils = else BindingFlags.Public - +[] module internal Impl = #if FX_RESHAPED_REFLECTION open PrimReflectionAdapters - open ReflectionAdapters + open ReflectionAdapters #endif let getBindingFlags allowAccess = ReflectionUtils.toBindingFlags (defaultArg allowAccess false) - let inline checkNonNull argName (v: 'T) = - match box v with - | null -> nullArg argName + let inline checkNonNull argName (v: 'T) = + match box v with + | null -> nullArg argName | _ -> () - - let isNamedType(typ:Type) = not (typ.IsArray || typ.IsByRef || typ.IsPointer) - let equivHeadTypes (ty1:Type) (ty2:Type) = + let isNamedType(typ: Type) = not (typ.IsArray || typ.IsByRef || typ.IsPointer) + + let equivHeadTypes (ty1: Type) (ty2: Type) = isNamedType(ty1) && - if ty1.IsGenericType then + if ty1.IsGenericType then ty2.IsGenericType && (ty1.GetGenericTypeDefinition()).Equals(ty2.GetGenericTypeDefinition()) - else + else ty1.Equals(ty2) let func = typedefof<(obj -> obj)> @@ -56,59 +57,59 @@ module internal Impl = //----------------------------------------------------------------- // GENERAL UTILITIES #if FX_RESHAPED_REFLECTION - let instanceFieldFlags = BindingFlags.Instance - let instancePropertyFlags = BindingFlags.Instance + let instanceFieldFlags = BindingFlags.Instance + let instancePropertyFlags = BindingFlags.Instance let staticPropertyFlags = BindingFlags.Static - let staticFieldFlags = BindingFlags.Static - let staticMethodFlags = BindingFlags.Static -#else - let instanceFieldFlags = BindingFlags.GetField ||| BindingFlags.Instance - let instancePropertyFlags = BindingFlags.GetProperty ||| BindingFlags.Instance + let staticFieldFlags = BindingFlags.Static + let staticMethodFlags = BindingFlags.Static +#else + let instanceFieldFlags = BindingFlags.GetField ||| BindingFlags.Instance + let instancePropertyFlags = BindingFlags.GetProperty ||| BindingFlags.Instance let staticPropertyFlags = BindingFlags.GetProperty ||| BindingFlags.Static - let staticFieldFlags = BindingFlags.GetField ||| BindingFlags.Static - let staticMethodFlags = BindingFlags.Static + let staticFieldFlags = BindingFlags.GetField ||| BindingFlags.Static + let staticMethodFlags = BindingFlags.Static #endif - let getInstancePropertyInfo (typ: Type,propName,bindingFlags) = typ.GetProperty(propName,instancePropertyFlags ||| bindingFlags) - let getInstancePropertyInfos (typ,names,bindingFlags) = names |> Array.map (fun nm -> getInstancePropertyInfo (typ,nm,bindingFlags)) + let getInstancePropertyInfo (typ: Type, propName, bindingFlags) = typ.GetProperty(propName, instancePropertyFlags ||| bindingFlags) + let getInstancePropertyInfos (typ, names, bindingFlags) = names |> Array.map (fun nm -> getInstancePropertyInfo (typ, nm, bindingFlags)) - let getInstancePropertyReader (typ: Type,propName,bindingFlags) = + let getInstancePropertyReader (typ: Type, propName, bindingFlags) = match getInstancePropertyInfo(typ, propName, bindingFlags) with | null -> None #if FX_RESHAPED_REFLECTION - | prop -> Some(fun (obj:obj) -> prop.GetValue(obj,null)) -#else - | prop -> Some(fun (obj:obj) -> prop.GetValue(obj,instancePropertyFlags ||| bindingFlags,null,null,null)) + | prop -> Some(fun (obj: obj) -> prop.GetValue (obj, null)) +#else + | prop -> Some(fun (obj: obj) -> prop.GetValue (obj, instancePropertyFlags ||| bindingFlags, null, null, null)) #endif //----------------------------------------------------------------- // ATTRIBUTE DECOMPILATION - let tryFindCompilationMappingAttribute (attrs:obj[]) = + let tryFindCompilationMappingAttribute (attrs: obj[]) = match attrs with | null | [| |] -> None | [| res |] -> let a = (res :?> CompilationMappingAttribute) in Some (a.SourceConstructFlags, a.SequenceNumber, a.VariantNumber) - | _ -> raise <| System.InvalidOperationException (SR.GetString(SR.multipleCompilationMappings)) + | _ -> raise <| System.InvalidOperationException (SR.GetString (SR.multipleCompilationMappings)) - let findCompilationMappingAttribute (attrs:obj[]) = + let findCompilationMappingAttribute (attrs: obj[]) = match tryFindCompilationMappingAttribute attrs with | None -> failwith "no compilation mapping attribute" | Some a -> a #if !FX_NO_REFLECTION_ONLY let cmaName = typeof.FullName - let assemblyName = typeof.Assembly.GetName().Name + let assemblyName = typeof.Assembly.GetName().Name let _ = assert (assemblyName = "FSharp.Core") - - let tryFindCompilationMappingAttributeFromData (attrs:System.Collections.Generic.IList) = + + let tryFindCompilationMappingAttributeFromData (attrs: IList) = match attrs with | null -> None - | _ -> + | _ -> let mutable res = None for a in attrs do - if a.Constructor.DeclaringType.FullName = cmaName then + if a.Constructor.DeclaringType.FullName = cmaName then let args = a.ConstructorArguments - let flags = - match args.Count with + let flags = + match args.Count with | 1 -> ((let x = args.[0] in x.Value :?> SourceConstructFlags), 0, 0) | 2 -> ((let x = args.[0] in x.Value :?> SourceConstructFlags), (let x = args.[1] in x.Value :?> int), 0) | 3 -> ((let x = args.[0] in x.Value :?> SourceConstructFlags), (let x = args.[1] in x.Value :?> int), (let x = args.[2] in x.Value :?> int)) @@ -120,55 +121,55 @@ module internal Impl = match tryFindCompilationMappingAttributeFromData attrs with | None -> failwith "no compilation mapping attribute" | Some a -> a -#endif +#endif - let tryFindCompilationMappingAttributeFromType (typ:Type) = + let tryFindCompilationMappingAttributeFromType (typ: Type) = #if !FX_NO_REFLECTION_ONLY let assem = typ.Assembly - if (not (isNull assem)) && assem.ReflectionOnly then + if (not (isNull assem)) && assem.ReflectionOnly then tryFindCompilationMappingAttributeFromData ( typ.GetCustomAttributesData()) else #endif - tryFindCompilationMappingAttribute ( typ.GetCustomAttributes (typeof,false)) + tryFindCompilationMappingAttribute ( typ.GetCustomAttributes (typeof, false)) - let tryFindCompilationMappingAttributeFromMemberInfo (info:MemberInfo) = + let tryFindCompilationMappingAttributeFromMemberInfo (info: MemberInfo) = #if !FX_NO_REFLECTION_ONLY let assem = info.DeclaringType.Assembly - if (not (isNull assem)) && assem.ReflectionOnly then + if (not (isNull assem)) && assem.ReflectionOnly then tryFindCompilationMappingAttributeFromData (info.GetCustomAttributesData()) else #endif - tryFindCompilationMappingAttribute (info.GetCustomAttributes (typeof,false)) + tryFindCompilationMappingAttribute (info.GetCustomAttributes (typeof, false)) - let findCompilationMappingAttributeFromMemberInfo (info:MemberInfo) = + let findCompilationMappingAttributeFromMemberInfo (info: MemberInfo) = #if !FX_NO_REFLECTION_ONLY let assem = info.DeclaringType.Assembly - if (not (isNull assem)) && assem.ReflectionOnly then + if (not (isNull assem)) && assem.ReflectionOnly then findCompilationMappingAttributeFromData (info.GetCustomAttributesData()) else #endif - findCompilationMappingAttribute (info.GetCustomAttributes (typeof,false)) + findCompilationMappingAttribute (info.GetCustomAttributes (typeof, false)) - let sequenceNumberOfMember (x: MemberInfo) = let (_,n,_) = findCompilationMappingAttributeFromMemberInfo x in n - let variantNumberOfMember (x: MemberInfo) = let (_,_,vn) = findCompilationMappingAttributeFromMemberInfo x in vn + let sequenceNumberOfMember (x: MemberInfo) = let (_, n, _) = findCompilationMappingAttributeFromMemberInfo x in n + let variantNumberOfMember (x: MemberInfo) = let (_, _, vn) = findCompilationMappingAttributeFromMemberInfo x in vn let sortFreshArray f arr = Array.sortInPlaceWith f arr; arr let isFieldProperty (prop : PropertyInfo) = match tryFindCompilationMappingAttributeFromMemberInfo(prop) with | None -> false - | Some (flags,_n,_vn) -> (flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.Field + | Some (flags, _n, _vn) -> (flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.Field - let tryFindSourceConstructFlagsOfType (typ:Type) = - match tryFindCompilationMappingAttributeFromType typ with + let tryFindSourceConstructFlagsOfType (typ: Type) = + match tryFindCompilationMappingAttributeFromType typ with | None -> None - | Some (flags,_n,_vn) -> Some flags + | Some (flags, _n, _vn) -> Some flags //----------------------------------------------------------------- - // UNION DECOMPILATION + // UNION DECOMPILATION // Get the type where the type definitions are stored - let getUnionCasesTyp (typ: Type, _bindingFlags) = + let getUnionCasesTyp (typ: Type, _bindingFlags) = #if CASES_IN_NESTED_CLASS let casesTyp = typ.GetNestedType("Cases", bindingFlags) if casesTyp.IsGenericTypeDefinition then casesTyp.MakeGenericType(typ.GetGenericArguments()) @@ -176,39 +177,39 @@ module internal Impl = #else typ #endif - - let getUnionTypeTagNameMap (typ:Type,bindingFlags) = + + let getUnionTypeTagNameMap (typ: Type, bindingFlags) = let enumTyp = typ.GetNestedType("Tags", bindingFlags) // Unions with a singleton case do not get a Tags type (since there is only one tag), hence enumTyp may be null in this case match enumTyp with - | null -> - typ.GetMethods(staticMethodFlags ||| bindingFlags) - |> Array.choose (fun minfo -> + | null -> + typ.GetMethods(staticMethodFlags ||| bindingFlags) + |> Array.choose (fun minfo -> match tryFindCompilationMappingAttributeFromMemberInfo(minfo) with | None -> None - | Some (flags,n,_vn) -> - if (flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.UnionCase then - let nm = minfo.Name - // chop "get_" or "New" off the front - let nm = - if not (isListType typ) && not (isOptionType typ) then - if nm.Length > 4 && nm.[0..3] = "get_" then nm.[4..] + | Some (flags, n, _vn) -> + if (flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.UnionCase then + let nm = minfo.Name + // chop "get_" or "New" off the front + let nm = + if not (isListType typ) && not (isOptionType typ) then + if nm.Length > 4 && nm.[0..3] = "get_" then nm.[4..] elif nm.Length > 3 && nm.[0..2] = "New" then nm.[3..] else nm else nm Some (n, nm) else - None) - | _ -> - enumTyp.GetFields(staticFieldFlags ||| bindingFlags) - |> Array.filter (fun (f:FieldInfo) -> f.IsStatic && f.IsLiteral) - |> sortFreshArray (fun f1 f2 -> compare (f1.GetValue(null) :?> int) (f2.GetValue(null) :?> int)) - |> Array.map (fun tagfield -> (tagfield.GetValue(null) :?> int),tagfield.Name) - - let getUnionCaseTyp (typ: Type, tag: int, bindingFlags) = - let tagFields = getUnionTypeTagNameMap(typ,bindingFlags) - let tagField = tagFields |> Array.pick (fun (i,f) -> if i = tag then Some f else None) - if tagFields.Length = 1 then + None) + | _ -> + enumTyp.GetFields(staticFieldFlags ||| bindingFlags) + |> Array.filter (fun (f: FieldInfo) -> f.IsStatic && f.IsLiteral) + |> sortFreshArray (fun f1 f2 -> compare (f1.GetValue (null) :?> int) (f2.GetValue (null) :?> int)) + |> Array.map (fun tagfield -> (tagfield.GetValue (null) :?> int), tagfield.Name) + + let getUnionCaseTyp (typ: Type, tag: int, bindingFlags) = + let tagFields = getUnionTypeTagNameMap(typ, bindingFlags) + let tagField = tagFields |> Array.pick (fun (i, f) -> if i = tag then Some f else None) + if tagFields.Length = 1 then typ else // special case: two-cased DU annotated with CompilationRepresentation(UseNullAsTrueValue) @@ -216,7 +217,7 @@ module internal Impl = let isTwoCasedDU = if tagFields.Length = 2 then match typ.GetCustomAttributes(typeof, false) with - | [|:? CompilationRepresentationAttribute as attr|] -> + | [|:? CompilationRepresentationAttribute as attr|] -> (attr.Flags &&& CompilationRepresentationFlags.UseNullAsTrueValue) = CompilationRepresentationFlags.UseNullAsTrueValue | _ -> false else @@ -226,165 +227,187 @@ module internal Impl = else let casesTyp = getUnionCasesTyp (typ, bindingFlags) let caseTyp = casesTyp.GetNestedType(tagField, bindingFlags) // if this is null then the union is nullary - match caseTyp with + match caseTyp with | null -> null | _ when caseTyp.IsGenericTypeDefinition -> caseTyp.MakeGenericType(casesTyp.GetGenericArguments()) | _ -> caseTyp - let getUnionTagConverter (typ:Type,bindingFlags) = - if isOptionType typ then (fun tag -> match tag with 0 -> "None" | 1 -> "Some" | _ -> invalidArg "tag" (SR.GetString(SR.outOfRange))) - elif isListType typ then (fun tag -> match tag with 0 -> "Empty" | 1 -> "Cons" | _ -> invalidArg "tag" (SR.GetString(SR.outOfRange))) - else - let tagfieldmap = getUnionTypeTagNameMap (typ,bindingFlags) |> Map.ofSeq + let getUnionTagConverter (typ: Type, bindingFlags) = + if isOptionType typ then (fun tag -> match tag with 0 -> "None" | 1 -> "Some" | _ -> invalidArg "tag" (SR.GetString (SR.outOfRange))) + elif isListType typ then (fun tag -> match tag with 0 -> "Empty" | 1 -> "Cons" | _ -> invalidArg "tag" (SR.GetString (SR.outOfRange))) + else + let tagfieldmap = getUnionTypeTagNameMap (typ, bindingFlags) |> Map.ofSeq (fun tag -> tagfieldmap.[tag]) - let isUnionType (typ:Type,bindingFlags:BindingFlags) = - isOptionType typ || - isListType typ || - match tryFindSourceConstructFlagsOfType(typ) with + let isUnionType (typ: Type, bindingFlags: BindingFlags) = + isOptionType typ || + isListType typ || + match tryFindSourceConstructFlagsOfType typ with | None -> false | Some(flags) -> (flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.SumType && // We see private representations only if BindingFlags.NonPublic is set - (if (flags &&& SourceConstructFlags.NonPublicRepresentation) <> enum(0) then + (if (flags &&& SourceConstructFlags.NonPublicRepresentation) <> enum(0) then (bindingFlags &&& BindingFlags.NonPublic) <> enum(0) - else + else true) // Check the base type - if it is also an F# type then // for the moment we know it is a Discriminated Union - let isConstructorRepr (typ:Type,bindingFlags:BindingFlags) = - let rec get (typ:Type) = isUnionType (typ,bindingFlags) || match typ.BaseType with null -> false | b -> get b - get typ + let isConstructorRepr (typ, bindingFlags) = + let rec get typ = isUnionType (typ, bindingFlags) || match typ.BaseType with null -> false | b -> get b + get typ - let unionTypeOfUnionCaseType (typ:Type,bindingFlags) = - let rec get (typ:Type) = if isUnionType (typ,bindingFlags) then typ else match typ.BaseType with null -> typ | b -> get b + let unionTypeOfUnionCaseType (typ, bindingFlags) = + let rec get typ = if isUnionType (typ, bindingFlags) then typ else match typ.BaseType with null -> typ | b -> get b get typ - let fieldsPropsOfUnionCase(typ:Type, tag:int, bindingFlags) = - if isOptionType typ then - match tag with - | 0 (* None *) -> getInstancePropertyInfos (typ,[| |],bindingFlags) - | 1 (* Some *) -> getInstancePropertyInfos (typ,[| "Value" |],bindingFlags) + let fieldsPropsOfUnionCase (typ, tag, bindingFlags) = + if isOptionType typ then + match tag with + | 0 (* None *) -> getInstancePropertyInfos (typ, [| |], bindingFlags) + | 1 (* Some *) -> getInstancePropertyInfos (typ, [| "Value" |], bindingFlags) | _ -> failwith "fieldsPropsOfUnionCase" - elif isListType typ then - match tag with - | 0 (* Nil *) -> getInstancePropertyInfos (typ,[| |],bindingFlags) - | 1 (* Cons *) -> getInstancePropertyInfos (typ,[| "Head"; "Tail" |],bindingFlags) + elif isListType typ then + match tag with + | 0 (* Nil *) -> getInstancePropertyInfos (typ, [| |], bindingFlags) + | 1 (* Cons *) -> getInstancePropertyInfos (typ, [| "Head"; "Tail" |], bindingFlags) | _ -> failwith "fieldsPropsOfUnionCase" else // Lookup the type holding the fields for the union case let caseTyp = getUnionCaseTyp (typ, tag, bindingFlags) let caseTyp = match caseTyp with null -> typ | _ -> caseTyp - caseTyp.GetProperties(instancePropertyFlags ||| bindingFlags) + caseTyp.GetProperties(instancePropertyFlags ||| bindingFlags) |> Array.filter isFieldProperty |> Array.filter (fun prop -> variantNumberOfMember prop = tag) |> sortFreshArray (fun p1 p2 -> compare (sequenceNumberOfMember p1) (sequenceNumberOfMember p2)) - - let getUnionCaseRecordReader (typ:Type,tag:int,bindingFlags) = - let props = fieldsPropsOfUnionCase(typ,tag,bindingFlags) + + let getUnionCaseRecordReader (typ: Type, tag: int, bindingFlags) = + let props = fieldsPropsOfUnionCase (typ, tag, bindingFlags) #if FX_RESHAPED_REFLECTION - (fun (obj:obj) -> props |> Array.map (fun prop -> prop.GetValue(obj,null))) -#else - (fun (obj:obj) -> props |> Array.map (fun prop -> prop.GetValue(obj,bindingFlags,null,null,null))) + (fun (obj: obj) -> props |> Array.map (fun prop -> prop.GetValue (obj, null))) +#else + (fun (obj: obj) -> props |> Array.map (fun prop -> prop.GetValue (obj, bindingFlags, null, null, null))) #endif - let getUnionTagReader (typ:Type,bindingFlags) : (obj -> int) = - if isOptionType typ then - (fun (obj:obj) -> match obj with null -> 0 | _ -> 1) + let getUnionTagReader (typ: Type, bindingFlags) : (obj -> int) = + if isOptionType typ then + (fun (obj: obj) -> match obj with null -> 0 | _ -> 1) else let tagMap = getUnionTypeTagNameMap (typ, bindingFlags) - if tagMap.Length <= 1 then - (fun (_obj:obj) -> 0) - else - match getInstancePropertyReader (typ,"Tag",bindingFlags) with - | Some reader -> (fun (obj:obj) -> reader obj :?> int) - | None -> - (fun (obj:obj) -> + if tagMap.Length <= 1 then + (fun (_obj: obj) -> 0) + else + match getInstancePropertyReader (typ, "Tag", bindingFlags) with + | Some reader -> (fun (obj: obj) -> reader obj :?> int) + | None -> + (fun (obj: obj) -> #if FX_RESHAPED_REFLECTION let m2b = typ.GetMethod("GetTag", [| typ |]) -#else +#else let m2b = typ.GetMethod("GetTag", BindingFlags.Static ||| bindingFlags, null, [| typ |], null) -#endif +#endif m2b.Invoke(null, [|obj|]) :?> int) - - let getUnionTagMemberInfo (typ:Type,bindingFlags) = - match getInstancePropertyInfo (typ,"Tag",bindingFlags) with + + let getUnionTagMemberInfo (typ: Type, bindingFlags) = + match getInstancePropertyInfo (typ, "Tag", bindingFlags) with #if FX_RESHAPED_REFLECTION | null -> (typ.GetMethod("GetTag") :> MemberInfo) -#else - | null -> (typ.GetMethod("GetTag",BindingFlags.Static ||| bindingFlags) :> MemberInfo) -#endif +#else + | null -> (typ.GetMethod("GetTag", BindingFlags.Static ||| bindingFlags) :> MemberInfo) +#endif | info -> (info :> MemberInfo) - let isUnionCaseNullary (typ:Type, tag:int, bindingFlags) = + let isUnionCaseNullary (typ: Type, tag: int, bindingFlags) = fieldsPropsOfUnionCase(typ, tag, bindingFlags).Length = 0 - let getUnionCaseConstructorMethod (typ:Type,tag:int,bindingFlags) = - let constrname = getUnionTagConverter (typ,bindingFlags) tag - let methname = - if isUnionCaseNullary (typ, tag, bindingFlags) then "get_" + constrname + let getUnionCaseConstructorMethod (typ: Type, tag: int, bindingFlags) = + let constrname = getUnionTagConverter (typ, bindingFlags) tag + let methname = + if isUnionCaseNullary (typ, tag, bindingFlags) then "get_" + constrname elif isListType typ || isOptionType typ then constrname else "New" + constrname match typ.GetMethod(methname, BindingFlags.Static ||| bindingFlags) with - | null -> raise <| System.InvalidOperationException (String.Format(SR.GetString(SR.constructorForUnionCaseNotFound), methname)) + | null -> raise <| System.InvalidOperationException (String.Format (SR.GetString (SR.constructorForUnionCaseNotFound), methname)) | meth -> meth - let getUnionCaseConstructor (typ:Type,tag:int,bindingFlags) = - let meth = getUnionCaseConstructorMethod (typ,tag,bindingFlags) - (fun args -> + let getUnionCaseConstructor (typ: Type, tag: int, bindingFlags) = + let meth = getUnionCaseConstructorMethod (typ, tag, bindingFlags) + (fun args -> #if FX_RESHAPED_REFLECTION - meth.Invoke(null,args)) -#else - meth.Invoke(null,BindingFlags.Static ||| BindingFlags.InvokeMethod ||| bindingFlags,null,args,null)) + meth.Invoke(null, args)) +#else + meth.Invoke(null, BindingFlags.Static ||| BindingFlags.InvokeMethod ||| bindingFlags, null, args, null)) #endif - let checkUnionType(unionType,bindingFlags) = - checkNonNull "unionType" unionType; - if not (isUnionType (unionType,bindingFlags)) then - if isUnionType (unionType,bindingFlags ||| BindingFlags.NonPublic) then - invalidArg "unionType" (String.Format(SR.GetString(SR.privateUnionType), unionType.FullName)) + let checkUnionType (unionType, bindingFlags) = + checkNonNull "unionType" unionType + if not (isUnionType (unionType, bindingFlags)) then + if isUnionType (unionType, bindingFlags ||| BindingFlags.NonPublic) then + invalidArg "unionType" (String.Format (SR.GetString (SR.privateUnionType), unionType.FullName)) else - invalidArg "unionType" (String.Format(SR.GetString(SR.notAUnionType), unionType.FullName)) + invalidArg "unionType" (String.Format (SR.GetString (SR.notAUnionType), unionType.FullName)) //----------------------------------------------------------------- // TUPLE DECOMPILATION - let tupleNames = [| - "System.Tuple`1"; "System.Tuple`2"; "System.Tuple`3"; - "System.Tuple`4"; "System.Tuple`5"; "System.Tuple`6"; - "System.Tuple`7"; "System.Tuple`8"; "System.Tuple" - "System.ValueTuple`1"; "System.ValueTuple`2"; "System.ValueTuple`3"; - "System.ValueTuple`4"; "System.ValueTuple`5"; "System.ValueTuple`6"; - "System.ValueTuple`7"; "System.ValueTuple`8"; "System.ValueTuple" |] - - let simpleTupleNames = [| - "Tuple`1"; "Tuple`2"; "Tuple`3"; - "Tuple`4"; "Tuple`5"; "Tuple`6"; - "Tuple`7"; "Tuple`8"; - "ValueTuple`1"; "ValueTuple`2"; "ValueTuple`3"; - "ValueTuple`4"; "ValueTuple`5"; "ValueTuple`6"; - "ValueTuple`7"; "ValueTuple`8"; |] - - let isTupleType (typ:Type) = - // We need to be careful that we only rely typ.IsGenericType, typ.Namespace and typ.Name here. - // - // Historically the FSharp.Core reflection utilities get used on implementations of - // System.Type that don't have functionality such as .IsEnum and .FullName fully implemented. - // This happens particularly over TypeBuilderInstantiation types in the ProvideTypes implementation of System.TYpe - // used in F# type providers. - typ.IsGenericType && - typ.Namespace = "System" && - simpleTupleNames |> Seq.exists typ.Name.StartsWith + let tupleNames = + [| "System.Tuple`1" + "System.Tuple`2" + "System.Tuple`3" + "System.Tuple`4" + "System.Tuple`5" + "System.Tuple`6" + "System.Tuple`7" + "System.Tuple`8" + "System.Tuple" + "System.ValueTuple`1" + "System.ValueTuple`2" + "System.ValueTuple`3" + "System.ValueTuple`4" + "System.ValueTuple`5" + "System.ValueTuple`6" + "System.ValueTuple`7" + "System.ValueTuple`8" + "System.ValueTuple" |] + + let simpleTupleNames = + [| "Tuple`1" + "Tuple`2" + "Tuple`3" + "Tuple`4" + "Tuple`5" + "Tuple`6" + "Tuple`7" + "Tuple`8" + "ValueTuple`1" + "ValueTuple`2" + "ValueTuple`3" + "ValueTuple`4" + "ValueTuple`5" + "ValueTuple`6" + "ValueTuple`7" + "ValueTuple`8" |] + + let isTupleType (typ: Type) = + // We need to be careful that we only rely typ.IsGenericType, typ.Namespace and typ.Name here. + // + // Historically the FSharp.Core reflection utilities get used on implementations of + // System.Type that don't have functionality such as .IsEnum and .FullName fully implemented. + // This happens particularly over TypeBuilderInstantiation types in the ProvideTypes implementation of System.TYpe + // used in F# type providers. + typ.IsGenericType && + typ.Namespace = "System" && + simpleTupleNames |> Seq.exists typ.Name.StartsWith let maxTuple = 8 // Which field holds the nested tuple? let tupleEncField = maxTuple - 1 let dictionaryLock = obj() - let refTupleTypes = System.Collections.Generic.Dictionary() - let valueTupleTypes = System.Collections.Generic.Dictionary() + let refTupleTypes = Dictionary() + let valueTupleTypes = Dictionary() - let rec mkTupleType isStruct (asm:Assembly) (tys:Type[]) = + let rec mkTupleType isStruct (asm: Assembly) (tys: Type[]) = let table = let makeIt n = let tupleFullName n = @@ -401,7 +424,7 @@ module internal Impl = | 6 -> asm.GetType(tupleFullName 6) | 7 -> asm.GetType(tupleFullName 7) | 8 -> asm.GetType(tupleFullName 8) - | _ -> invalidArg "tys" (SR.GetString(SR.invalidTupleTypes)) + | _ -> invalidArg "tys" (SR.GetString (SR.invalidTupleTypes)) let tables = if isStruct then valueTupleTypes else refTupleTypes match lock dictionaryLock (fun () -> tables.TryGetValue(asm)) with @@ -409,9 +432,10 @@ module internal Impl = // the Dictionary<>s here could be ConcurrentDictionary<>'s, but then // that would lock while initializing the Type array (maybe not an issue) let a = ref (Array.init 8 (fun i -> makeIt (i + 1))) - lock dictionaryLock (fun () -> match tables.TryGetValue(asm) with - | true, t -> a := t - | false, _ -> tables.Add(asm, !a)) + lock dictionaryLock (fun () -> + match tables.TryGetValue(asm) with + | true, t -> a := t + | false, _ -> tables.Add(asm, !a)) !a | true, t -> t @@ -428,19 +452,20 @@ module internal Impl = let tysB = tys.[maxTuple-1..] let tyB = mkTupleType isStruct asm tysB table.[7].MakeGenericType(Array.append tysA [| tyB |]) - | _ -> invalidArg "tys" (SR.GetString(SR.invalidTupleTypes)) + | _ -> invalidArg "tys" (SR.GetString (SR.invalidTupleTypes)) + + let rec getTupleTypeInfo (typ: Type) = + if not (isTupleType typ) then + invalidArg "typ" (String.Format (SR.GetString (SR.notATupleType), typ.FullName)) + let tyargs = typ.GetGenericArguments() + if tyargs.Length = maxTuple then + let tysA = tyargs.[0..tupleEncField-1] + let tyB = tyargs.[tupleEncField] + Array.append tysA (getTupleTypeInfo tyB) + else + tyargs - let rec getTupleTypeInfo (typ:Type) = - if not (isTupleType (typ) ) then invalidArg "typ" (String.Format(SR.GetString(SR.notATupleType), typ.FullName)); - let tyargs = typ.GetGenericArguments() - if tyargs.Length = maxTuple then - let tysA = tyargs.[0..tupleEncField-1] - let tyB = tyargs.[tupleEncField] - Array.append tysA (getTupleTypeInfo tyB) - else - tyargs - - let orderTupleProperties (props:PropertyInfo[]) = + let orderTupleProperties (props: PropertyInfo[]) = // The tuple properties are of the form: // Item1 // .. @@ -454,7 +479,7 @@ module internal Impl = #if !NETSTANDARD assert(props.Length <= maxTuple) assert(let haveNames = props |> Array.map (fun p -> p.Name) - let expectNames = Array.init props.Length (fun i -> let j = i+1 // index j = 1,2,..,props.Length <= maxTuple + let expectNames = Array.init props.Length (fun i -> let j = i+1 // index j = 1, 2, .., props.Length <= maxTuple if j Array.map (fun fi -> fi.Name) - let expectNames = Array.init fields.Length (fun i -> let j = i+1 // index j = 1,2,..,fields.Length <= maxTuple + let expectNames = Array.init fields.Length (fun i -> let j = i+1 // index j = 1, 2, .., fields.Length <= maxTuple if j orderTupleFields #if FX_RESHAPED_REFLECTION typ.GetConstructor(fields |> Array.map (fun fi -> fi.FieldType)) #else - typ.GetConstructor(BindingFlags.Public ||| BindingFlags.Instance,null,fields |> Array.map (fun fi -> fi.FieldType),null) + typ.GetConstructor(BindingFlags.Public ||| BindingFlags.Instance, null, fields |> Array.map (fun fi -> fi.FieldType), null) #endif else let props = typ.GetProperties() |> orderTupleProperties #if FX_RESHAPED_REFLECTION typ.GetConstructor(props |> Array.map (fun p -> p.PropertyType)) #else - typ.GetConstructor(BindingFlags.Public ||| BindingFlags.Instance,null,props |> Array.map (fun p -> p.PropertyType),null) + typ.GetConstructor(BindingFlags.Public ||| BindingFlags.Instance, null, props |> Array.map (fun p -> p.PropertyType), null) #endif match ctor with - | null -> raise <| ArgumentException(String.Format(SR.GetString(SR.invalidTupleTypeConstructorNotDefined), typ.FullName)) + | null -> raise (ArgumentException (String.Format (SR.GetString (SR.invalidTupleTypeConstructorNotDefined), typ.FullName))) | _ -> () ctor - let getTupleCtor(typ:Type) = + let getTupleCtor(typ: Type) = let ctor = getTupleConstructorMethod typ - (fun (args:obj[]) -> -#if FX_RESHAPED_REFLECTION + (fun (args: obj[]) -> +#if FX_RESHAPED_REFLECTION ctor.Invoke(args)) #else ctor.Invoke(BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| BindingFlags.Public, null, args, null)) #endif - let rec getTupleReader (typ:Type) = - let etys = typ.GetGenericArguments() + let rec getTupleReader (typ: Type) = + let etys = typ.GetGenericArguments() // Get the reader for the outer tuple record let reader = if typ.IsValueType then let fields = (typ.GetFields (instanceFieldFlags ||| BindingFlags.Public) |> orderTupleFields) - ((fun (obj:obj) -> fields |> Array.map (fun field -> field.GetValue(obj)))) + ((fun (obj: obj) -> fields |> Array.map (fun field -> field.GetValue (obj)))) else - let props = (typ.GetProperties(instancePropertyFlags ||| BindingFlags.Public) |> orderTupleProperties) - ((fun (obj:obj) -> props |> Array.map (fun prop -> prop.GetValue(obj,null)))) - if etys.Length < maxTuple + let props = (typ.GetProperties (instancePropertyFlags ||| BindingFlags.Public) |> orderTupleProperties) + ((fun (obj: obj) -> props |> Array.map (fun prop -> prop.GetValue (obj, null)))) + if etys.Length < maxTuple then reader else let tyBenc = etys.[tupleEncField] @@ -534,511 +559,519 @@ module internal Impl = let encVals = reader2 directVals.[tupleEncField] Array.append directVals.[0..tupleEncField-1] encVals) - let rec getTupleConstructor (typ:Type) = - let etys = typ.GetGenericArguments() + let rec getTupleConstructor (typ: Type) = + let etys = typ.GetGenericArguments() let maker1 = getTupleCtor typ - if etys.Length < maxTuple + if etys.Length < maxTuple then maker1 else let tyBenc = etys.[tupleEncField] let maker2 = getTupleConstructor(tyBenc) - (fun (args:obj[]) -> + (fun (args: obj[]) -> let encVal = maker2 args.[tupleEncField..] maker1 (Array.append args.[0..tupleEncField-1] [| encVal |])) - - let getTupleConstructorInfo (typ:Type) = - let etys = typ.GetGenericArguments() + + let getTupleConstructorInfo (typ: Type) = + let etys = typ.GetGenericArguments() let maker1 = getTupleConstructorMethod typ if etys.Length < maxTuple then - maker1,None + maker1, None else - maker1,Some(etys.[tupleEncField]) + maker1, Some(etys.[tupleEncField]) - let getTupleReaderInfo (typ:Type,index:int) = - if index < 0 then invalidArg "index" (String.Format(SR.GetString(SR.tupleIndexOutOfRange), typ.FullName, index.ToString())) + let getTupleReaderInfo (typ: Type, index: int) = + if index < 0 then + invalidArg "index" (String.Format (SR.GetString (SR.tupleIndexOutOfRange), typ.FullName, index.ToString())) let get index = if typ.IsValueType then let props = typ.GetProperties(instancePropertyFlags ||| BindingFlags.Public) |> orderTupleProperties - if index >= props.Length then invalidArg "index" (String.Format(SR.GetString(SR.tupleIndexOutOfRange), typ.FullName, index.ToString())) + if index >= props.Length then + invalidArg "index" (String.Format (SR.GetString (SR.tupleIndexOutOfRange), typ.FullName, index.ToString())) props.[index] else let props = typ.GetProperties(instancePropertyFlags ||| BindingFlags.Public) |> orderTupleProperties - if index >= props.Length then invalidArg "index" (String.Format(SR.GetString(SR.tupleIndexOutOfRange), typ.FullName, index.ToString())) + if index >= props.Length then + invalidArg "index" (String.Format (SR.GetString (SR.tupleIndexOutOfRange), typ.FullName, index.ToString())) props.[index] if index < tupleEncField then get index, None else let etys = typ.GetGenericArguments() - get tupleEncField, Some(etys.[tupleEncField],index-(maxTuple-1)) + get tupleEncField, Some(etys.[tupleEncField], index-(maxTuple-1)) - //----------------------------------------------------------------- - // FUNCTION DECOMPILATION - - - let getFunctionTypeInfo (typ:Type) = - if not (isFunctionType typ) then invalidArg "typ" (String.Format(SR.GetString(SR.notAFunctionType), typ.FullName)) + let getFunctionTypeInfo (typ: Type) = + if not (isFunctionType typ) then + invalidArg "typ" (String.Format (SR.GetString (SR.notAFunctionType), typ.FullName)) let tyargs = typ.GetGenericArguments() tyargs.[0], tyargs.[1] - //----------------------------------------------------------------- - // MODULE DECOMPILATION - - let isModuleType (typ:Type) = - match tryFindSourceConstructFlagsOfType(typ) with - | None -> false - | Some(flags) -> - (flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.Module - - let rec isClosureRepr typ = - isFunctionType typ || - (match typ.BaseType with null -> false | bty -> isClosureRepr bty) + let isModuleType (typ: Type) = + match tryFindSourceConstructFlagsOfType typ with + | None -> false + | Some(flags) -> + (flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.Module - //----------------------------------------------------------------- - // RECORD DECOMPILATION - - let isRecordType (typ:Type,bindingFlags:BindingFlags) = - match tryFindSourceConstructFlagsOfType(typ) with - | None -> false + let rec isClosureRepr typ = + isFunctionType typ || + (match typ.BaseType with null -> false | bty -> isClosureRepr bty) + + let isRecordType (typ: Type, bindingFlags: BindingFlags) = + match tryFindSourceConstructFlagsOfType typ with + | None -> false | Some(flags) -> (flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.RecordType && // We see private representations only if BindingFlags.NonPublic is set - (if (flags &&& SourceConstructFlags.NonPublicRepresentation) <> enum(0) then + (if (flags &&& SourceConstructFlags.NonPublicRepresentation) <> enum(0) then (bindingFlags &&& BindingFlags.NonPublic) <> enum(0) - else + else true) - let fieldPropsOfRecordType(typ:Type,bindingFlags) = - typ.GetProperties(instancePropertyFlags ||| bindingFlags) + let fieldPropsOfRecordType(typ: Type, bindingFlags) = + typ.GetProperties(instancePropertyFlags ||| bindingFlags) |> Array.filter isFieldProperty |> sortFreshArray (fun p1 p2 -> compare (sequenceNumberOfMember p1) (sequenceNumberOfMember p2)) - let getRecordReader(typ:Type,bindingFlags) = - let props = fieldPropsOfRecordType(typ,bindingFlags) - (fun (obj:obj) -> props |> Array.map (fun prop -> prop.GetValue(obj,null))) + let getRecordReader(typ: Type, bindingFlags) = + let props = fieldPropsOfRecordType(typ, bindingFlags) + (fun (obj: obj) -> props |> Array.map (fun prop -> prop.GetValue (obj, null))) - let getRecordConstructorMethod(typ:Type,bindingFlags) = - let props = fieldPropsOfRecordType(typ,bindingFlags) + let getRecordConstructorMethod(typ: Type, bindingFlags) = + let props = fieldPropsOfRecordType(typ, bindingFlags) #if FX_RESHAPED_REFLECTION let ctor = typ.GetConstructor(props |> Array.map (fun p -> p.PropertyType)) -#else - let ctor = typ.GetConstructor(BindingFlags.Instance ||| bindingFlags,null,props |> Array.map (fun p -> p.PropertyType),null) -#endif +#else + let ctor = typ.GetConstructor(BindingFlags.Instance ||| bindingFlags, null, props |> Array.map (fun p -> p.PropertyType), null) +#endif match ctor with - | null -> raise <| ArgumentException(String.Format(SR.GetString(SR.invalidRecordTypeConstructorNotDefined), typ.FullName)) + | null -> raise <| ArgumentException (String.Format (SR.GetString (SR.invalidRecordTypeConstructorNotDefined), typ.FullName)) | _ -> () ctor - let getRecordConstructor(typ:Type,bindingFlags) = - let ctor = getRecordConstructorMethod(typ,bindingFlags) - (fun (args:obj[]) -> + let getRecordConstructor(typ: Type, bindingFlags) = + let ctor = getRecordConstructorMethod(typ, bindingFlags) + (fun (args: obj[]) -> #if FX_RESHAPED_REFLECTION ctor.Invoke(args)) -#else - ctor.Invoke(BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| bindingFlags,null,args,null)) -#endif - - //----------------------------------------------------------------- - // EXCEPTION DECOMPILATION - +#else + ctor.Invoke(BindingFlags.InvokeMethod ||| BindingFlags.Instance ||| bindingFlags, null, args, null)) +#endif + /// EXCEPTION DECOMPILATION // Check the base type - if it is also an F# type then // for the moment we know it is a Discriminated Union - let isExceptionRepr (typ:Type,bindingFlags) = - match tryFindSourceConstructFlagsOfType(typ) with - | None -> false - | Some(flags) -> + let isExceptionRepr (typ: Type, bindingFlags) = + match tryFindSourceConstructFlagsOfType typ with + | None -> false + | Some(flags) -> ((flags &&& SourceConstructFlags.KindMask) = SourceConstructFlags.Exception) && // We see private representations only if BindingFlags.NonPublic is set - (if (flags &&& SourceConstructFlags.NonPublicRepresentation) <> enum(0) then + (if (flags &&& SourceConstructFlags.NonPublicRepresentation) <> enum(0) then (bindingFlags &&& BindingFlags.NonPublic) <> enum(0) - else + else true) - let getTypeOfReprType (typ:Type,bindingFlags) = - if isExceptionRepr(typ,bindingFlags) then typ.BaseType - elif isConstructorRepr(typ,bindingFlags) then unionTypeOfUnionCaseType(typ,bindingFlags) - elif isClosureRepr(typ) then - let rec get (typ:Type) = if isFunctionType typ then typ else match typ.BaseType with null -> typ | b -> get b - get typ + let getTypeOfReprType (typ: Type, bindingFlags) = + if isExceptionRepr (typ, bindingFlags) then typ.BaseType + elif isConstructorRepr (typ, bindingFlags) then unionTypeOfUnionCaseType(typ, bindingFlags) + elif isClosureRepr typ then + let rec get (typ: Type) = if isFunctionType typ then typ else match typ.BaseType with null -> typ | b -> get b + get typ else typ //----------------------------------------------------------------- // CHECKING ROUTINES let checkExnType (exceptionType, bindingFlags) = - if not (isExceptionRepr (exceptionType,bindingFlags)) then - if isExceptionRepr (exceptionType,bindingFlags ||| BindingFlags.NonPublic) then - invalidArg "exceptionType" (String.Format(SR.GetString(SR.privateExceptionType), exceptionType.FullName)) + if not (isExceptionRepr (exceptionType, bindingFlags)) then + if isExceptionRepr (exceptionType, bindingFlags ||| BindingFlags.NonPublic) then + invalidArg "exceptionType" (String.Format (SR.GetString (SR.privateExceptionType), exceptionType.FullName)) else - invalidArg "exceptionType" (String.Format(SR.GetString(SR.notAnExceptionType), exceptionType.FullName)) - - let checkRecordType(argName,recordType,bindingFlags) = - checkNonNull argName recordType; - if not (isRecordType (recordType,bindingFlags) ) then - if isRecordType (recordType,bindingFlags ||| BindingFlags.NonPublic) then - invalidArg argName (String.Format(SR.GetString(SR.privateRecordType), recordType.FullName)) + invalidArg "exceptionType" (String.Format (SR.GetString (SR.notAnExceptionType), exceptionType.FullName)) + + let checkRecordType (argName, recordType, bindingFlags) = + checkNonNull argName recordType + if not (isRecordType (recordType, bindingFlags) ) then + if isRecordType (recordType, bindingFlags ||| BindingFlags.NonPublic) then + invalidArg argName (String.Format (SR.GetString (SR.privateRecordType), recordType.FullName)) else - invalidArg argName (String.Format(SR.GetString(SR.notARecordType), recordType.FullName)) - - let checkTupleType(argName,(tupleType:Type)) = - checkNonNull argName tupleType; - if not (isTupleType tupleType) then invalidArg argName (String.Format(SR.GetString(SR.notATupleType), tupleType.FullName)) + invalidArg argName (String.Format (SR.GetString (SR.notARecordType), recordType.FullName)) + + let checkTupleType(argName, (tupleType: Type)) = + checkNonNull argName tupleType + if not (isTupleType tupleType) then + invalidArg argName (String.Format (SR.GetString (SR.notATupleType), tupleType.FullName)) #if FX_RESHAPED_REFLECTION open ReflectionAdapters #endif - + [] -type UnionCaseInfo(typ: System.Type, tag:int) = +type UnionCaseInfo(typ: System.Type, tag: int) = + // Cache the tag -> name map let mutable names = None - let getMethInfo() = Impl.getUnionCaseConstructorMethod (typ, tag, BindingFlags.Public ||| BindingFlags.NonPublic) - member __.Name = - match names with - | None -> (let conv = Impl.getUnionTagConverter (typ,BindingFlags.Public ||| BindingFlags.NonPublic) in names <- Some conv; conv tag) - | Some conv -> conv tag - + + let getMethInfo() = getUnionCaseConstructorMethod (typ, tag, BindingFlags.Public ||| BindingFlags.NonPublic) + + member __.Name = + match names with + | None -> + let conv = getUnionTagConverter (typ, BindingFlags.Public ||| BindingFlags.NonPublic) + names <- Some conv + conv tag + | Some conv -> + conv tag + member __.DeclaringType = typ - member __.GetFields() = - let props = Impl.fieldsPropsOfUnionCase(typ,tag,BindingFlags.Public ||| BindingFlags.NonPublic) - props + member __.GetFields() = + fieldsPropsOfUnionCase (typ, tag, BindingFlags.Public ||| BindingFlags.NonPublic) - member __.GetCustomAttributes() = getMethInfo().GetCustomAttributes(false) + member __.GetCustomAttributes() = + getMethInfo().GetCustomAttributes(false) - member __.GetCustomAttributes(attributeType) = getMethInfo().GetCustomAttributes(attributeType,false) + member __.GetCustomAttributes(attributeType) = + getMethInfo().GetCustomAttributes(attributeType, false) - member __.GetCustomAttributesData() = getMethInfo().CustomAttributes |> Seq.toArray :> System.Collections.Generic.IList<_> + member __.GetCustomAttributesData() = + getMethInfo().CustomAttributes |> Seq.toArray :> IList<_> member __.Tag = tag + override x.ToString() = typ.Name + "." + x.Name + override x.GetHashCode() = typ.GetHashCode() + tag - override __.Equals(obj:obj) = - match obj with + + override __.Equals(obj: obj) = + match obj with | :? UnionCaseInfo as uci -> uci.DeclaringType = typ && uci.Tag = tag | _ -> false - [] -type FSharpType = +type FSharpType = - static member IsTuple(typ:Type) = - Impl.checkNonNull "typ" typ - Impl.isTupleType typ + static member IsTuple(typ: Type) = + checkNonNull "typ" typ + isTupleType typ - static member IsRecord(typ:Type,?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - - Impl.checkNonNull "typ" typ - Impl.isRecordType (typ,bindingFlags) + static member IsRecord(typ: Type, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "typ" typ + isRecordType (typ, bindingFlags) - static member IsUnion(typ:Type,?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "typ" typ - let typ = Impl.getTypeOfReprType (typ,BindingFlags.Public ||| BindingFlags.NonPublic) - Impl.isUnionType (typ,bindingFlags) + static member IsUnion (typ: Type, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "typ" typ + let typ = getTypeOfReprType (typ, BindingFlags.Public ||| BindingFlags.NonPublic) + isUnionType (typ, bindingFlags) - static member IsFunction(typ:Type) = - Impl.checkNonNull "typ" typ - let typ = Impl.getTypeOfReprType (typ,BindingFlags.Public ||| BindingFlags.NonPublic) - Impl.isFunctionType typ + static member IsFunction (typ: Type) = + checkNonNull "typ" typ + let typ = getTypeOfReprType (typ, BindingFlags.Public ||| BindingFlags.NonPublic) + isFunctionType typ - static member IsModule(typ:Type) = - Impl.checkNonNull "typ" typ - Impl.isModuleType typ + static member IsModule (typ: Type) = + checkNonNull "typ" typ + isModuleType typ - static member MakeFunctionType(domain:Type,range:Type) = - Impl.checkNonNull "domain" domain - Impl.checkNonNull "range" range - Impl.func.MakeGenericType [| domain; range |] + static member MakeFunctionType (domain: Type, range: Type) = + checkNonNull "domain" domain + checkNonNull "range" range + func.MakeGenericType [| domain; range |] - static member MakeTupleType(types:Type[]) = - Impl.checkNonNull "types" types + static member MakeTupleType (types: Type[]) = + checkNonNull "types" types // No assembly passed therefore just get framework local version of Tuple let asm = typeof.Assembly - if types |> Array.exists (function null -> true | _ -> false) then - invalidArg "types" (SR.GetString(SR.nullsNotAllowedInArray)) - Impl.mkTupleType false asm types - - static member MakeTupleType (asm:Assembly, types:Type[]) = - Impl.checkNonNull "types" types - if types |> Array.exists (function null -> true | _ -> false) then - invalidArg "types" (SR.GetString(SR.nullsNotAllowedInArray)) - Impl.mkTupleType false asm types - - static member MakeStructTupleType (asm:Assembly, types:Type[]) = - Impl.checkNonNull "types" types - if types |> Array.exists (function null -> true | _ -> false) then - invalidArg "types" (SR.GetString(SR.nullsNotAllowedInArray)) - Impl.mkTupleType true asm types - - static member GetTupleElements(tupleType:Type) = - Impl.checkTupleType("tupleType",tupleType) - Impl.getTupleTypeInfo tupleType - - static member GetFunctionElements(functionType:Type) = - Impl.checkNonNull "functionType" functionType - let functionType = Impl.getTypeOfReprType (functionType,BindingFlags.Public ||| BindingFlags.NonPublic) - Impl.getFunctionTypeInfo functionType - - static member GetRecordFields(recordType:Type,?bindingFlags) = + if types |> Array.exists (function null -> true | _ -> false) then + invalidArg "types" (SR.GetString (SR.nullsNotAllowedInArray)) + mkTupleType false asm types + + static member MakeTupleType (asm: Assembly, types: Type[]) = + checkNonNull "types" types + if types |> Array.exists (function null -> true | _ -> false) then + invalidArg "types" (SR.GetString (SR.nullsNotAllowedInArray)) + mkTupleType false asm types + + static member MakeStructTupleType (asm: Assembly, types: Type[]) = + checkNonNull "types" types + if types |> Array.exists (function null -> true | _ -> false) then + invalidArg "types" (SR.GetString (SR.nullsNotAllowedInArray)) + mkTupleType true asm types + + static member GetTupleElements (tupleType: Type) = + checkTupleType("tupleType", tupleType) + getTupleTypeInfo tupleType + + static member GetFunctionElements (functionType: Type) = + checkNonNull "functionType" functionType + let functionType = getTypeOfReprType (functionType, BindingFlags.Public ||| BindingFlags.NonPublic) + getFunctionTypeInfo functionType + + static member GetRecordFields (recordType: Type, ?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkRecordType("recordType",recordType,bindingFlags) - Impl.fieldPropsOfRecordType(recordType,bindingFlags) + checkRecordType ("recordType", recordType, bindingFlags) + fieldPropsOfRecordType(recordType, bindingFlags) - static member GetUnionCases (unionType:Type,?bindingFlags) = + static member GetUnionCases (unionType: Type, ?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "unionType" unionType - let unionType = Impl.getTypeOfReprType (unionType,bindingFlags) - Impl.checkUnionType(unionType,bindingFlags); - Impl.getUnionTypeTagNameMap(unionType,bindingFlags) |> Array.mapi (fun i _ -> UnionCaseInfo(unionType,i)) + checkNonNull "unionType" unionType + let unionType = getTypeOfReprType (unionType, bindingFlags) + checkUnionType (unionType, bindingFlags) + getUnionTypeTagNameMap(unionType, bindingFlags) |> Array.mapi (fun i _ -> UnionCaseInfo(unionType, i)) - static member IsExceptionRepresentation(exceptionType:Type, ?bindingFlags) = + static member IsExceptionRepresentation (exceptionType: Type, ?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "exceptionType" exceptionType - Impl.isExceptionRepr(exceptionType,bindingFlags) + checkNonNull "exceptionType" exceptionType + isExceptionRepr (exceptionType, bindingFlags) - static member GetExceptionFields(exceptionType:Type, ?bindingFlags) = + static member GetExceptionFields (exceptionType: Type, ?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "exceptionType" exceptionType - Impl.checkExnType(exceptionType,bindingFlags) - Impl.fieldPropsOfRecordType (exceptionType,bindingFlags) + checkNonNull "exceptionType" exceptionType + checkExnType (exceptionType, bindingFlags) + fieldPropsOfRecordType (exceptionType, bindingFlags) -type DynamicFunction<'T1,'T2>() = +type DynamicFunction<'T1, 'T2>() = inherit FSharpFunc obj, obj>() - override __.Invoke(impl: obj -> obj) : obj = + override __.Invoke(impl: obj -> obj) : obj = box<('T1 -> 'T2)> (fun inp -> unbox<'T2>(impl (box<'T1>(inp)))) [] -type FSharpValue = +type FSharpValue = - static member MakeRecord(recordType:Type,values,?bindingFlags) = + static member MakeRecord (recordType: Type, values, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkRecordType ("recordType", recordType, bindingFlags) + getRecordConstructor (recordType, bindingFlags) values + + static member GetRecordField(record: obj, info: PropertyInfo) = + checkNonNull "info" info + checkNonNull "record" record + let reprty = record.GetType() + if not (isRecordType (reprty, BindingFlags.Public ||| BindingFlags.NonPublic)) then + invalidArg "record" (SR.GetString (SR.objIsNotARecord)) + info.GetValue (record, null) + + static member GetRecordFields (record: obj, ?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkRecordType("recordType",recordType,bindingFlags) - Impl.getRecordConstructor (recordType,bindingFlags) values + checkNonNull "record" record + let typ = record.GetType() + if not (isRecordType (typ, bindingFlags)) then + invalidArg "record" (SR.GetString (SR.objIsNotARecord)) + getRecordReader (typ, bindingFlags) record - static member GetRecordField(record:obj,info:PropertyInfo) = - Impl.checkNonNull "info" info; - Impl.checkNonNull "record" record; - let reprty = record.GetType() - if not (Impl.isRecordType(reprty,BindingFlags.Public ||| BindingFlags.NonPublic)) then invalidArg "record" (SR.GetString(SR.objIsNotARecord)); - info.GetValue(record,null) + static member PreComputeRecordFieldReader(info: PropertyInfo) = + checkNonNull "info" info + (fun (obj: obj) -> info.GetValue (obj, null)) - static member GetRecordFields(record:obj,?bindingFlags) = + static member PreComputeRecordReader(recordType: Type, ?bindingFlags) : (obj -> obj[]) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "record" record - let typ = record.GetType() - if not (Impl.isRecordType(typ,bindingFlags)) then invalidArg "record" (SR.GetString(SR.objIsNotARecord)); - Impl.getRecordReader (typ,bindingFlags) record - - static member PreComputeRecordFieldReader(info:PropertyInfo) = - Impl.checkNonNull "info" info - (fun (obj:obj) -> info.GetValue(obj,null)) - - static member PreComputeRecordReader(recordType:Type,?bindingFlags) : (obj -> obj[]) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkRecordType("recordType",recordType,bindingFlags) - Impl.getRecordReader (recordType,bindingFlags) - - static member PreComputeRecordConstructor(recordType:Type,?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkRecordType("recordType",recordType,bindingFlags) - Impl.getRecordConstructor (recordType,bindingFlags) - - static member PreComputeRecordConstructorInfo(recordType:Type, ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkRecordType("recordType",recordType,bindingFlags) - Impl.getRecordConstructorMethod(recordType,bindingFlags) - - static member MakeFunction(functionType:Type,implementation:(obj->obj)) = - Impl.checkNonNull "functionType" functionType - if not (Impl.isFunctionType functionType) then invalidArg "functionType" (String.Format(SR.GetString(SR.notAFunctionType), functionType.FullName)); - Impl.checkNonNull "implementation" implementation - let domain,range = Impl.getFunctionTypeInfo functionType - let dynCloMakerTy = typedefof> + checkRecordType ("recordType", recordType, bindingFlags) + getRecordReader (recordType, bindingFlags) + + static member PreComputeRecordConstructor(recordType: Type, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkRecordType ("recordType", recordType, bindingFlags) + getRecordConstructor (recordType, bindingFlags) + + static member PreComputeRecordConstructorInfo(recordType: Type, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkRecordType ("recordType", recordType, bindingFlags) + getRecordConstructorMethod(recordType, bindingFlags) + + static member MakeFunction(functionType: Type, implementation:(obj->obj)) = + checkNonNull "functionType" functionType + if not (isFunctionType functionType) then + invalidArg "functionType" (String.Format (SR.GetString (SR.notAFunctionType), functionType.FullName)) + checkNonNull "implementation" implementation + let domain, range = getFunctionTypeInfo functionType + let dynCloMakerTy = typedefof> let saverTy = dynCloMakerTy.MakeGenericType [| domain; range |] let o = Activator.CreateInstance(saverTy) let (f : (obj -> obj) -> obj) = downcast o f implementation - static member MakeTuple(tupleElements: obj[], tupleType:Type) = - Impl.checkNonNull "tupleElements" tupleElements - Impl.checkTupleType("tupleType",tupleType) - Impl.getTupleConstructor tupleType tupleElements - - static member GetTupleFields(tuple:obj) = // argument name(s) used in error message - Impl.checkNonNull "tuple" tuple - let typ = tuple.GetType() - if not (Impl.isTupleType typ ) then invalidArg "tuple" (String.Format(SR.GetString(SR.notATupleType), tuple.GetType().FullName)); - Impl.getTupleReader typ tuple - - static member GetTupleField(tuple:obj,index:int) = // argument name(s) used in error message - Impl.checkNonNull "tuple" tuple - let typ = tuple.GetType() - if not (Impl.isTupleType typ ) then invalidArg "tuple" (String.Format(SR.GetString(SR.notATupleType), tuple.GetType().FullName)); - let fields = Impl.getTupleReader typ tuple - if index < 0 || index >= fields.Length then invalidArg "index" (String.Format(SR.GetString(SR.tupleIndexOutOfRange), tuple.GetType().FullName, index.ToString())); + static member MakeTuple(tupleElements: obj[], tupleType: Type) = + checkNonNull "tupleElements" tupleElements + checkTupleType("tupleType", tupleType) + getTupleConstructor tupleType tupleElements + + static member GetTupleFields(tuple: obj) = // argument name(s) used in error message + checkNonNull "tuple" tuple + let typ = tuple.GetType() + if not (isTupleType typ ) then + invalidArg "tuple" (String.Format (SR.GetString (SR.notATupleType), tuple.GetType().FullName)) + getTupleReader typ tuple + + static member GetTupleField(tuple: obj, index: int) = // argument name(s) used in error message + checkNonNull "tuple" tuple + let typ = tuple.GetType() + if not (isTupleType typ ) then + invalidArg "tuple" (String.Format (SR.GetString (SR.notATupleType), tuple.GetType().FullName)) + let fields = getTupleReader typ tuple + if index < 0 || index >= fields.Length then + invalidArg "index" (String.Format (SR.GetString (SR.tupleIndexOutOfRange), tuple.GetType().FullName, index.ToString())) fields.[index] - - static member PreComputeTupleReader(tupleType:Type) : (obj -> obj[]) = - Impl.checkTupleType("tupleType",tupleType) - Impl.getTupleReader tupleType - - static member PreComputeTuplePropertyInfo(tupleType:Type,index:int) = - Impl.checkTupleType("tupleType",tupleType) - Impl.getTupleReaderInfo (tupleType,index) - - static member PreComputeTupleConstructor(tupleType:Type) = - Impl.checkTupleType("tupleType",tupleType) - Impl.getTupleConstructor tupleType - - static member PreComputeTupleConstructorInfo(tupleType:Type) = - Impl.checkTupleType("tupleType",tupleType) - Impl.getTupleConstructorInfo (tupleType) - - static member MakeUnion(unionCase:UnionCaseInfo,args: obj [],?bindingFlags) = + + static member PreComputeTupleReader(tupleType: Type) : (obj -> obj[]) = + checkTupleType("tupleType", tupleType) + getTupleReader tupleType + + static member PreComputeTuplePropertyInfo(tupleType: Type, index: int) = + checkTupleType("tupleType", tupleType) + getTupleReaderInfo (tupleType, index) + + static member PreComputeTupleConstructor(tupleType: Type) = + checkTupleType("tupleType", tupleType) + getTupleConstructor tupleType + + static member PreComputeTupleConstructorInfo(tupleType: Type) = + checkTupleType("tupleType", tupleType) + getTupleConstructorInfo tupleType + + static member MakeUnion(unionCase: UnionCaseInfo, args: obj [], ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "unionCase" unionCase + getUnionCaseConstructor (unionCase.DeclaringType, unionCase.Tag, bindingFlags) args + + static member PreComputeUnionConstructor (unionCase: UnionCaseInfo, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "unionCase" unionCase + getUnionCaseConstructor (unionCase.DeclaringType, unionCase.Tag, bindingFlags) + + static member PreComputeUnionConstructorInfo(unionCase: UnionCaseInfo, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "unionCase" unionCase + getUnionCaseConstructorMethod (unionCase.DeclaringType, unionCase.Tag, bindingFlags) + + static member GetUnionFields(value: obj, unionType: Type, ?bindingFlags) = let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "unionCase" unionCase; - Impl.getUnionCaseConstructor (unionCase.DeclaringType,unionCase.Tag,bindingFlags) args - - static member PreComputeUnionConstructor (unionCase:UnionCaseInfo,?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "unionCase" unionCase; - Impl.getUnionCaseConstructor (unionCase.DeclaringType,unionCase.Tag,bindingFlags) - - static member PreComputeUnionConstructorInfo(unionCase:UnionCaseInfo, ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "unionCase" unionCase; - Impl.getUnionCaseConstructorMethod (unionCase.DeclaringType,unionCase.Tag,bindingFlags) - - static member GetUnionFields(value:obj,unionType:Type,?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - let ensureType (typ:Type,obj:obj) = - match typ with - | null -> - match obj with - | null -> invalidArg "obj" (SR.GetString(SR.objIsNullAndNoType)) + let ensureType (typ: Type, obj: obj) = + match typ with + | null -> + match obj with + | null -> invalidArg "obj" (SR.GetString (SR.objIsNullAndNoType)) | _ -> obj.GetType() - | _ -> typ - - let unionType = ensureType(unionType,value) - - Impl.checkNonNull "unionType" unionType - let unionType = Impl.getTypeOfReprType (unionType,bindingFlags) - - Impl.checkUnionType(unionType,bindingFlags) - let tag = Impl.getUnionTagReader (unionType,bindingFlags) value - let flds = Impl.getUnionCaseRecordReader (unionType,tag,bindingFlags) value - UnionCaseInfo(unionType,tag), flds - - static member PreComputeUnionTagReader(unionType: Type,?bindingFlags) : (obj -> int) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "unionType" unionType - let unionType = Impl.getTypeOfReprType (unionType,bindingFlags) - Impl.checkUnionType(unionType,bindingFlags) - Impl.getUnionTagReader (unionType,bindingFlags) - - static member PreComputeUnionTagMemberInfo(unionType: Type,?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "unionType" unionType; - let unionType = Impl.getTypeOfReprType (unionType,bindingFlags) - Impl.checkUnionType(unionType,bindingFlags) - Impl.getUnionTagMemberInfo(unionType,bindingFlags) - - static member PreComputeUnionReader(unionCase: UnionCaseInfo,?bindingFlags) : (obj -> obj[]) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "unionCase" unionCase - let typ = unionCase.DeclaringType - Impl.getUnionCaseRecordReader (typ,unionCase.Tag,bindingFlags) - - static member GetExceptionFields(exn:obj, ?bindingFlags) = - let bindingFlags = defaultArg bindingFlags BindingFlags.Public - Impl.checkNonNull "exn" exn; - let typ = exn.GetType() - Impl.checkExnType(typ,bindingFlags) - Impl.getRecordReader (typ,bindingFlags) exn + | _ -> typ + + let unionType = ensureType(unionType, value) + + checkNonNull "unionType" unionType + let unionType = getTypeOfReprType (unionType, bindingFlags) + + checkUnionType (unionType, bindingFlags) + let tag = getUnionTagReader (unionType, bindingFlags) value + let flds = getUnionCaseRecordReader (unionType, tag, bindingFlags) value + UnionCaseInfo (unionType, tag), flds + + static member PreComputeUnionTagReader(unionType: Type, ?bindingFlags) : (obj -> int) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "unionType" unionType + let unionType = getTypeOfReprType (unionType, bindingFlags) + checkUnionType (unionType, bindingFlags) + getUnionTagReader (unionType, bindingFlags) + + static member PreComputeUnionTagMemberInfo(unionType: Type, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "unionType" unionType + let unionType = getTypeOfReprType (unionType, bindingFlags) + checkUnionType (unionType, bindingFlags) + getUnionTagMemberInfo (unionType, bindingFlags) + + static member PreComputeUnionReader(unionCase: UnionCaseInfo, ?bindingFlags) : (obj -> obj[]) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "unionCase" unionCase + let typ = unionCase.DeclaringType + getUnionCaseRecordReader (typ, unionCase.Tag, bindingFlags) + + static member GetExceptionFields (exn: obj, ?bindingFlags) = + let bindingFlags = defaultArg bindingFlags BindingFlags.Public + checkNonNull "exn" exn + let typ = exn.GetType() + checkExnType (typ, bindingFlags) + getRecordReader (typ, bindingFlags) exn module FSharpReflectionExtensions = type FSharpType with - static member GetExceptionFields(exceptionType:Type, ?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpType.GetExceptionFields(exceptionType, bindingFlags) + static member GetExceptionFields (exceptionType: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpType.GetExceptionFields (exceptionType, bindingFlags) - static member IsExceptionRepresentation(exceptionType:Type, ?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpType.IsExceptionRepresentation(exceptionType, bindingFlags) + static member IsExceptionRepresentation(exceptionType: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpType.IsExceptionRepresentation (exceptionType, bindingFlags) - static member GetUnionCases (unionType:Type,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpType.GetUnionCases(unionType, bindingFlags) + static member GetUnionCases (unionType: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpType.GetUnionCases (unionType, bindingFlags) - static member GetRecordFields(recordType:Type,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpType.GetRecordFields(recordType, bindingFlags) + static member GetRecordFields (recordType: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpType.GetRecordFields (recordType, bindingFlags) - static member IsUnion(typ:Type,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpType.IsUnion(typ, bindingFlags) + static member IsUnion (typ: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpType.IsUnion (typ, bindingFlags) - static member IsRecord(typ:Type,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpType.IsRecord(typ, bindingFlags) + static member IsRecord(typ: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpType.IsRecord (typ, bindingFlags) type FSharpValue with - static member MakeRecord(recordType:Type,values,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.MakeRecord(recordType, values, bindingFlags) + static member MakeRecord(recordType: Type, values, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.MakeRecord (recordType, values, bindingFlags) - static member GetRecordFields(record:obj,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.GetRecordFields(record, bindingFlags) + static member GetRecordFields (record: obj, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.GetRecordFields (record, bindingFlags) - static member PreComputeRecordReader(recordType:Type,?allowAccessToPrivateRepresentation) : (obj -> obj[]) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.PreComputeRecordReader(recordType, bindingFlags) + static member PreComputeRecordReader(recordType: Type, ?allowAccessToPrivateRepresentation) : (obj -> obj[]) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.PreComputeRecordReader (recordType, bindingFlags) - static member PreComputeRecordConstructor(recordType:Type,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.PreComputeRecordConstructor(recordType, bindingFlags) + static member PreComputeRecordConstructor(recordType: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.PreComputeRecordConstructor (recordType, bindingFlags) - static member PreComputeRecordConstructorInfo(recordType:Type, ?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.PreComputeRecordConstructorInfo(recordType, bindingFlags) + static member PreComputeRecordConstructorInfo(recordType: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.PreComputeRecordConstructorInfo (recordType, bindingFlags) - static member MakeUnion(unionCase:UnionCaseInfo,args: obj [],?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.MakeUnion(unionCase, args, bindingFlags) + static member MakeUnion(unionCase: UnionCaseInfo, args: obj [], ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.MakeUnion (unionCase, args, bindingFlags) - static member PreComputeUnionConstructor (unionCase:UnionCaseInfo,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.PreComputeUnionConstructor(unionCase, bindingFlags) + static member PreComputeUnionConstructor (unionCase: UnionCaseInfo, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.PreComputeUnionConstructor (unionCase, bindingFlags) - static member PreComputeUnionConstructorInfo(unionCase:UnionCaseInfo, ?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.PreComputeUnionConstructorInfo(unionCase, bindingFlags) + static member PreComputeUnionConstructorInfo(unionCase: UnionCaseInfo, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.PreComputeUnionConstructorInfo (unionCase, bindingFlags) - static member PreComputeUnionTagMemberInfo(unionType: Type,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.PreComputeUnionTagMemberInfo(unionType, bindingFlags) + static member PreComputeUnionTagMemberInfo(unionType: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.PreComputeUnionTagMemberInfo (unionType, bindingFlags) - static member GetUnionFields(value:obj,unionType:Type,?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.GetUnionFields(value, unionType, bindingFlags) + static member GetUnionFields(value: obj, unionType: Type, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.GetUnionFields (value, unionType, bindingFlags) - static member PreComputeUnionTagReader(unionType: Type,?allowAccessToPrivateRepresentation) : (obj -> int) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.PreComputeUnionTagReader(unionType, bindingFlags) + static member PreComputeUnionTagReader(unionType: Type, ?allowAccessToPrivateRepresentation) : (obj -> int) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.PreComputeUnionTagReader (unionType, bindingFlags) - static member PreComputeUnionReader(unionCase: UnionCaseInfo,?allowAccessToPrivateRepresentation) : (obj -> obj[]) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.PreComputeUnionReader(unionCase, bindingFlags) + static member PreComputeUnionReader(unionCase: UnionCaseInfo, ?allowAccessToPrivateRepresentation) : (obj -> obj[]) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.PreComputeUnionReader (unionCase, bindingFlags) - static member GetExceptionFields(exn:obj, ?allowAccessToPrivateRepresentation) = - let bindingFlags = Impl.getBindingFlags allowAccessToPrivateRepresentation - FSharpValue.GetExceptionFields(exn, bindingFlags) + static member GetExceptionFields (exn: obj, ?allowAccessToPrivateRepresentation) = + let bindingFlags = getBindingFlags allowAccessToPrivateRepresentation + FSharpValue.GetExceptionFields (exn, bindingFlags) diff --git a/src/fsharp/FSharp.Core/set.fs b/src/fsharp/FSharp.Core/set.fs index 394bc4963de..9ab21f29fc3 100644 --- a/src/fsharp/FSharp.Core/set.fs +++ b/src/fsharp/FSharp.Core/set.fs @@ -2,858 +2,879 @@ namespace Microsoft.FSharp.Collections - open System - open Microsoft.FSharp.Core - open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators - open Microsoft.FSharp.Core.Operators - open Microsoft.FSharp.Collections - open System.Collections - open System.Collections.Generic - open System.Diagnostics - - (* A classic functional language implementation of binary trees *) - - [] - [] - type SetTree<'T> when 'T: comparison = - | SetEmpty // height = 0 - | SetNode of 'T * SetTree<'T> * SetTree<'T> * int // height = int - | SetOne of 'T // height = 1 - // OPTIMIZATION: store SetNode(k,SetEmpty,SetEmpty,1) ---> SetOne(k) - // REVIEW: performance rumour has it that the data held in SetNode and SetOne should be - // exactly one cache line on typical architectures. They are currently - // ~6 and 3 words respectively. - - - [] - module internal SetTree = - let rec countAux s acc = - match s with - | SetNode(_,l,r,_) -> countAux l (countAux r (acc+1)) - | SetOne(_) -> acc+1 - | SetEmpty -> acc - - let count s = countAux s 0 - - #if TRACE_SETS_AND_MAPS - let mutable traceCount = 0 - let mutable numOnes = 0 - let mutable numNodes = 0 - let mutable numAdds = 0 - let mutable numRemoves = 0 - let mutable numLookups = 0 - let mutable numUnions = 0 - let mutable totalSizeOnNodeCreation = 0.0 - let mutable totalSizeOnSetAdd = 0.0 - let mutable totalSizeOnSetLookup = 0.0 - let report() = - traceCount <- traceCount + 1 - if traceCount % 10000 = 0 then - System.Console.WriteLine("#SetOne = {0}, #SetNode = {1}, #Add = {2}, #Remove = {3}, #Unions = {4}, #Lookups = {5}, avSetSizeOnNodeCreation = {6}, avSetSizeOnSetCreation = {7}, avSetSizeOnSetLookup = {8}",numOnes,numNodes,numAdds,numRemoves,numUnions,numLookups,(totalSizeOnNodeCreation / float (numNodes + numOnes)),(totalSizeOnSetAdd / float numAdds),(totalSizeOnSetLookup / float numLookups)) - - let SetOne n = - report(); - numOnes <- numOnes + 1; - totalSizeOnNodeCreation <- totalSizeOnNodeCreation + 1.0; - SetTree.SetOne n - - let SetNode (x,l,r,h) = - report(); - numNodes <- numNodes + 1; - let n = SetTree.SetNode(x,l,r,h) - totalSizeOnNodeCreation <- totalSizeOnNodeCreation + float (count n); - n - #else - let SetOne n = SetTree.SetOne n - let SetNode (x,l,r,h) = SetTree.SetNode(x,l,r,h) - - #endif - - - let height t = - match t with - | SetEmpty -> 0 - | SetOne _ -> 1 - | SetNode (_,_,_,h) -> h - - #if CHECKED - let rec checkInvariant t = - // A good sanity check, loss of balance can hit perf - match t with - | SetEmpty -> true - | SetOne _ -> true - | SetNode (k,t1,t2,h) -> - let h1 = height t1 - let h2 = height t2 - (-2 <= (h1 - h2) && (h1 - h2) <= 2) && checkInvariant t1 && checkInvariant t2 - #endif - - let tolerance = 2 - - let mk l k r = - match l,r with - | SetEmpty,SetEmpty -> SetOne (k) - | _ -> - let hl = height l - let hr = height r - let m = if hl < hr then hr else hl - SetNode(k,l,r,m+1) - - let rebalance t1 k t2 = - let t1h = height t1 - let t2h = height t2 - if t2h > t1h + tolerance then // right is heavier than left - match t2 with - | SetNode(t2k,t2l,t2r,_) -> - // one of the nodes must have height > height t1 + 1 - if height t2l > t1h + 1 then // balance left: combination - match t2l with - | SetNode(t2lk,t2ll,t2lr,_) -> - mk (mk t1 k t2ll) t2lk (mk t2lr t2k t2r) - | _ -> failwith "rebalance" - else // rotate left - mk (mk t1 k t2l) t2k t2r - | _ -> failwith "rebalance" - else - if t1h > t2h + tolerance then // left is heavier than right - match t1 with - | SetNode(t1k,t1l,t1r,_) -> - // one of the nodes must have height > height t2 + 1 - if height t1r > t2h + 1 then - // balance right: combination - match t1r with - | SetNode(t1rk,t1rl,t1rr,_) -> - mk (mk t1l t1k t1rl) t1rk (mk t1rr k t2) - | _ -> failwith "rebalance" - else - mk t1l t1k (mk t1r k t2) - | _ -> failwith "rebalance" - else mk t1 k t2 - - let rec add (comparer: IComparer<'T>) k t = - match t with - | SetNode (k2,l,r,_) -> - let c = comparer.Compare(k,k2) - if c < 0 then rebalance (add comparer k l) k2 r - elif c = 0 then t - else rebalance l k2 (add comparer k r) - | SetOne(k2) -> - // nb. no check for rebalance needed for small trees, also be sure to reuse node already allocated - let c = comparer.Compare(k,k2) - if c < 0 then SetNode (k,SetEmpty,t,2) - elif c = 0 then t - else SetNode (k,t,SetEmpty,2) - | SetEmpty -> SetOne(k) - - let rec balance comparer t1 k t2 = - // Given t1 < k < t2 where t1 and t2 are "balanced", - // return a balanced tree for . - // Recall: balance means subtrees heights differ by at most "tolerance" - match t1,t2 with - | SetEmpty,t2 -> add comparer k t2 // drop t1 = empty - | t1,SetEmpty -> add comparer k t1 // drop t2 = empty - | SetOne k1,t2 -> add comparer k (add comparer k1 t2) - | t1,SetOne k2 -> add comparer k (add comparer k2 t1) - | SetNode(k1,t11,t12,h1),SetNode(k2,t21,t22,h2) -> - // Have: (t11 < k1 < t12) < k < (t21 < k2 < t22) - // Either (a) h1,h2 differ by at most 2 - no rebalance needed. - // (b) h1 too small, i.e. h1+2 < h2 - // (c) h2 too small, i.e. h2+2 < h1 - if h1+tolerance < h2 then - // case: b, h1 too small - // push t1 into low side of t2, may increase height by 1 so rebalance - rebalance (balance comparer t1 k t21) k2 t22 - elif h2+tolerance < h1 then - // case: c, h2 too small - // push t2 into high side of t1, may increase height by 1 so rebalance - rebalance t11 k1 (balance comparer t12 k t2) - else - // case: a, h1 and h2 meet balance requirement - mk t1 k t2 - - let rec split (comparer: IComparer<'T>) pivot t = - // Given a pivot and a set t - // Return { x in t s.t. x < pivot }, pivot in t?, { x in t s.t. x > pivot } - match t with - | SetNode(k1,t11,t12,_) -> - let c = comparer.Compare(pivot,k1) - if c < 0 then // pivot t1 - let t11Lo,havePivot,t11Hi = split comparer pivot t11 - t11Lo,havePivot,balance comparer t11Hi k1 t12 - elif c = 0 then // pivot is k1 - t11,true,t12 - else // pivot t2 - let t12Lo,havePivot,t12Hi = split comparer pivot t12 - balance comparer t11 k1 t12Lo,havePivot,t12Hi - | SetOne k1 -> - let c = comparer.Compare(k1,pivot) - if c < 0 then t,false,SetEmpty // singleton under pivot - elif c = 0 then SetEmpty,true,SetEmpty // singleton is pivot - else SetEmpty,false,t // singleton over pivot - | SetEmpty -> - SetEmpty,false,SetEmpty - - let rec spliceOutSuccessor t = - match t with - | SetEmpty -> failwith "internal error: Set.spliceOutSuccessor" - | SetOne (k2) -> k2,SetEmpty - | SetNode (k2,l,r,_) -> - match l with - | SetEmpty -> k2,r - | _ -> let k3,l' = spliceOutSuccessor l in k3,mk l' k2 r - - let rec remove (comparer: IComparer<'T>) k t = - match t with - | SetEmpty -> t - | SetOne (k2) -> - let c = comparer.Compare(k,k2) - if c = 0 then SetEmpty - else t - | SetNode (k2,l,r,_) -> - let c = comparer.Compare(k,k2) - if c < 0 then rebalance (remove comparer k l) k2 r - elif c = 0 then - match l,r with - | SetEmpty,_ -> r - | _,SetEmpty -> l - | _ -> - let sk,r' = spliceOutSuccessor r - mk l sk r' - else rebalance l k2 (remove comparer k r) - - let rec mem (comparer: IComparer<'T>) k t = - match t with - | SetNode(k2,l,r,_) -> - let c = comparer.Compare(k,k2) - if c < 0 then mem comparer k l - elif c = 0 then true - else mem comparer k r - | SetOne(k2) -> (comparer.Compare(k,k2) = 0) - | SetEmpty -> false - - let rec iter f t = - match t with - | SetNode(k2,l,r,_) -> iter f l; f k2; iter f r - | SetOne(k2) -> f k2 - | SetEmpty -> () - - let rec foldBackOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) m x = - match m with - | SetNode(k,l,r,_) -> foldBackOpt f l (f.Invoke(k, (foldBackOpt f r x))) - | SetOne(k) -> f.Invoke(k, x) - | SetEmpty -> x - - let foldBack f m x = foldBackOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) m x - - let rec foldOpt (f:OptimizedClosures.FSharpFunc<_,_,_>) x m = - match m with - | SetNode(k,l,r,_) -> - let x = foldOpt f x l in - let x = f.Invoke(x, k) - foldOpt f x r - | SetOne(k) -> f.Invoke(x, k) - | SetEmpty -> x +open System +open System.Collections +open System.Collections.Generic +open System.Diagnostics +open System.Text +open Microsoft.FSharp.Core +open Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicOperators +open Microsoft.FSharp.Core.Operators +open Microsoft.FSharp.Collections + +// A functional language implementation of binary trees + +[] +[] +type SetTree<'T> when 'T: comparison = + | SetEmpty // height = 0 + | SetNode of 'T * SetTree<'T> * SetTree<'T> * int // height = int + | SetOne of 'T // height = 1 + // OPTIMIZATION: store SetNode (k, SetEmpty, SetEmpty, 1) ---> SetOne (k) + +[] +module internal SetTree = + let rec countAux s acc = + match s with + | SetNode (_, l, r, _) -> countAux l (countAux r (acc+1)) + | SetOne (_) -> acc+1 + | SetEmpty -> acc + + let count s = countAux s 0 - let fold f x m = foldOpt (OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)) x m +#if TRACE_SETS_AND_MAPS + let mutable traceCount = 0 + let mutable numOnes = 0 + let mutable numNodes = 0 + let mutable numAdds = 0 + let mutable numRemoves = 0 + let mutable numLookups = 0 + let mutable numUnions = 0 + let mutable totalSizeOnNodeCreation = 0.0 + let mutable totalSizeOnSetAdd = 0.0 + let mutable totalSizeOnSetLookup = 0.0 + + let report() = + traceCount <- traceCount + 1 + if traceCount % 10000 = 0 then + System.Console.WriteLine( + "#SetOne = {0}, #SetNode = {1}, #Add = {2}, #Remove = {3}, #Unions = {4}, #Lookups = {5}, avSetSizeOnNodeCreation = {6}, avSetSizeOnSetCreation = {7}, avSetSizeOnSetLookup = {8}", + numOnes, numNodes, numAdds, numRemoves, numUnions, numLookups, + (totalSizeOnNodeCreation / float (numNodes + numOnes)), + (totalSizeOnSetAdd / float numAdds), + (totalSizeOnSetLookup / float numLookups)) + + let SetOne n = + report() + numOnes <- numOnes + 1 + totalSizeOnNodeCreation <- totalSizeOnNodeCreation + 1.0 + SetTree.SetOne n + + let SetNode (x, l, r, h) = + report() + numNodes <- numNodes + 1 + let n = SetTree.SetNode (x, l, r, h) + totalSizeOnNodeCreation <- totalSizeOnNodeCreation + float (count n) + n +#else + let SetOne n = SetTree.SetOne n + + let SetNode (x, l, r, h) = SetTree.SetNode (x, l, r, h) +#endif - let rec forall f m = - match m with - | SetNode(k2,l,r,_) -> f k2 && forall f l && forall f r - | SetOne(k2) -> f k2 - | SetEmpty -> true + let height t = + match t with + | SetEmpty -> 0 + | SetOne _ -> 1 + | SetNode (_, _, _, h) -> h + +#if CHECKED + let rec checkInvariant t = + // A good sanity check, loss of balance can hit perf + match t with + | SetEmpty -> true + | SetOne _ -> true + | SetNode (k, t1, t2, h) -> + let h1 = height t1 + let h2 = height t2 + (-2 <= (h1 - h2) && (h1 - h2) <= 2) && checkInvariant t1 && checkInvariant t2 +#endif - let rec exists f m = + let tolerance = 2 + + let mk l k r = + match l, r with + | SetEmpty, SetEmpty -> SetOne (k) + | _ -> + let hl = height l + let hr = height r + let m = if hl < hr then hr else hl + SetNode (k, l, r, m+1) + + let rebalance t1 k t2 = + let t1h = height t1 + let t2h = height t2 + if t2h > t1h + tolerance then // right is heavier than left + match t2 with + | SetNode (t2k, t2l, t2r, _) -> + // one of the nodes must have height > height t1 + 1 + if height t2l > t1h + 1 then // balance left: combination + match t2l with + | SetNode (t2lk, t2ll, t2lr, _) -> + mk (mk t1 k t2ll) t2lk (mk t2lr t2k t2r) + | _ -> failwith "rebalance" + else // rotate left + mk (mk t1 k t2l) t2k t2r + | _ -> failwith "rebalance" + else + if t1h > t2h + tolerance then // left is heavier than right + match t1 with + | SetNode (t1k, t1l, t1r, _) -> + // one of the nodes must have height > height t2 + 1 + if height t1r > t2h + 1 then + // balance right: combination + match t1r with + | SetNode (t1rk, t1rl, t1rr, _) -> + mk (mk t1l t1k t1rl) t1rk (mk t1rr k t2) + | _ -> failwith "rebalance" + else + mk t1l t1k (mk t1r k t2) + | _ -> failwith "rebalance" + else mk t1 k t2 + + let rec add (comparer: IComparer<'T>) k t = + match t with + | SetNode (k2, l, r, _) -> + let c = comparer.Compare(k, k2) + if c < 0 then rebalance (add comparer k l) k2 r + elif c = 0 then t + else rebalance l k2 (add comparer k r) + | SetOne k2 -> + // nb. no check for rebalance needed for small trees, also be sure to reuse node already allocated + let c = comparer.Compare(k, k2) + if c < 0 then SetNode (k, SetEmpty, t, 2) + elif c = 0 then t + else SetNode (k, t, SetEmpty, 2) + | SetEmpty -> SetOne k + + let rec balance comparer t1 k t2 = + // Given t1 < k < t2 where t1 and t2 are "balanced", + // return a balanced tree for . + // Recall: balance means subtrees heights differ by at most "tolerance" + match t1, t2 with + | SetEmpty, t2 -> add comparer k t2 // drop t1 = empty + | t1, SetEmpty -> add comparer k t1 // drop t2 = empty + | SetOne k1, t2 -> add comparer k (add comparer k1 t2) + | t1, SetOne k2 -> add comparer k (add comparer k2 t1) + | SetNode (k1, t11, t12, h1), SetNode (k2, t21, t22, h2) -> + // Have: (t11 < k1 < t12) < k < (t21 < k2 < t22) + // Either (a) h1, h2 differ by at most 2 - no rebalance needed. + // (b) h1 too small, i.e. h1+2 < h2 + // (c) h2 too small, i.e. h2+2 < h1 + if h1+tolerance < h2 then + // case: b, h1 too small + // push t1 into low side of t2, may increase height by 1 so rebalance + rebalance (balance comparer t1 k t21) k2 t22 + elif h2+tolerance < h1 then + // case: c, h2 too small + // push t2 into high side of t1, may increase height by 1 so rebalance + rebalance t11 k1 (balance comparer t12 k t2) + else + // case: a, h1 and h2 meet balance requirement + mk t1 k t2 + + let rec split (comparer: IComparer<'T>) pivot t = + // Given a pivot and a set t + // Return { x in t s.t. x < pivot }, pivot in t?, { x in t s.t. x > pivot } + match t with + | SetNode (k1, t11, t12, _) -> + let c = comparer.Compare(pivot, k1) + if c < 0 then // pivot t1 + let t11Lo, havePivot, t11Hi = split comparer pivot t11 + t11Lo, havePivot, balance comparer t11Hi k1 t12 + elif c = 0 then // pivot is k1 + t11, true, t12 + else // pivot t2 + let t12Lo, havePivot, t12Hi = split comparer pivot t12 + balance comparer t11 k1 t12Lo, havePivot, t12Hi + | SetOne k1 -> + let c = comparer.Compare(k1, pivot) + if c < 0 then t, false, SetEmpty // singleton under pivot + elif c = 0 then SetEmpty, true, SetEmpty // singleton is pivot + else SetEmpty, false, t // singleton over pivot + | SetEmpty -> + SetEmpty, false, SetEmpty + + let rec spliceOutSuccessor t = + match t with + | SetEmpty -> failwith "internal error: Set.spliceOutSuccessor" + | SetOne (k2) -> k2, SetEmpty + | SetNode (k2, l, r, _) -> + match l with + | SetEmpty -> k2, r + | _ -> let k3, l' = spliceOutSuccessor l in k3, mk l' k2 r + + let rec remove (comparer: IComparer<'T>) k t = + match t with + | SetEmpty -> t + | SetOne (k2) -> + let c = comparer.Compare(k, k2) + if c = 0 then SetEmpty + else t + | SetNode (k2, l, r, _) -> + let c = comparer.Compare(k, k2) + if c < 0 then rebalance (remove comparer k l) k2 r + elif c = 0 then + match l, r with + | SetEmpty, _ -> r + | _, SetEmpty -> l + | _ -> + let sk, r' = spliceOutSuccessor r + mk l sk r' + else rebalance l k2 (remove comparer k r) + + let rec mem (comparer: IComparer<'T>) k t = + match t with + | SetNode (k2, l, r, _) -> + let c = comparer.Compare(k, k2) + if c < 0 then mem comparer k l + elif c = 0 then true + else mem comparer k r + | SetOne (k2) -> (comparer.Compare(k, k2) = 0) + | SetEmpty -> false + + let rec iter f t = + match t with + | SetNode (k2, l, r, _) -> iter f l; f k2; iter f r + | SetOne (k2) -> f k2 + | SetEmpty -> () + + let rec foldBackOpt (f:OptimizedClosures.FSharpFunc<_, _, _>) m x = + match m with + | SetNode (k, l, r, _) -> foldBackOpt f l (f.Invoke(k, (foldBackOpt f r x))) + | SetOne (k) -> f.Invoke(k, x) + | SetEmpty -> x + + let foldBack f m x = foldBackOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) m x + + let rec foldOpt (f:OptimizedClosures.FSharpFunc<_, _, _>) x m = + match m with + | SetNode (k, l, r, _) -> + let x = foldOpt f x l in + let x = f.Invoke(x, k) + foldOpt f x r + | SetOne (k) -> f.Invoke(x, k) + | SetEmpty -> x + + let fold f x m = foldOpt (OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f)) x m + + let rec forall f m = + match m with + | SetNode (k2, l, r, _) -> f k2 && forall f l && forall f r + | SetOne (k2) -> f k2 + | SetEmpty -> true + + let rec exists f m = + match m with + | SetNode (k2, l, r, _) -> f k2 || exists f l || exists f r + | SetOne (k2) -> f k2 + | SetEmpty -> false + + let isEmpty m = match m with | SetEmpty -> true | _ -> false + + let subset comparer a b = + forall (fun x -> mem comparer x b) a + + let properSubset comparer a b = + forall (fun x -> mem comparer x b) a && exists (fun x -> not (mem comparer x a)) b + + let rec filterAux comparer f s acc = + match s with + | SetNode (k, l, r, _) -> + let acc = if f k then add comparer k acc else acc + filterAux comparer f l (filterAux comparer f r acc) + | SetOne (k) -> if f k then add comparer k acc else acc + | SetEmpty -> acc + + let filter comparer f s = filterAux comparer f s SetEmpty + + let rec diffAux comparer m acc = + match acc with + | SetEmpty -> acc + | _ -> + match m with + | SetNode (k, l, r, _) -> diffAux comparer l (diffAux comparer r (remove comparer k acc)) + | SetOne (k) -> remove comparer k acc + | SetEmpty -> acc + + let diff comparer a b = diffAux comparer b a + + let rec union comparer t1 t2 = + // Perf: tried bruteForce for low heights, but nothing significant + match t1, t2 with + | SetNode (k1, t11, t12, h1), SetNode (k2, t21, t22, h2) -> // (t11 < k < t12) AND (t21 < k2 < t22) + // Divide and Conquer: + // Suppose t1 is largest. + // Split t2 using pivot k1 into lo and hi. + // Union disjoint subproblems and then combine. + if h1 > h2 then + let lo, _, hi = split comparer k1 t2 in + balance comparer (union comparer t11 lo) k1 (union comparer t12 hi) + else + let lo, _, hi = split comparer k2 t1 in + balance comparer (union comparer t21 lo) k2 (union comparer t22 hi) + | SetEmpty, t -> t + | t, SetEmpty -> t + | SetOne k1, t2 -> add comparer k1 t2 + | t1, SetOne k2 -> add comparer k2 t1 + + let rec intersectionAux comparer b m acc = + match m with + | SetNode (k, l, r, _) -> + let acc = intersectionAux comparer b r acc + let acc = if mem comparer k b then add comparer k acc else acc + intersectionAux comparer b l acc + | SetOne (k) -> + if mem comparer k b then add comparer k acc else acc + | SetEmpty -> acc + + let intersection comparer a b = intersectionAux comparer b a SetEmpty + + let partition1 comparer f k (acc1, acc2) = if f k then (add comparer k acc1, acc2) else (acc1, add comparer k acc2) + + let rec partitionAux comparer f s acc = + match s with + | SetNode (k, l, r, _) -> + let acc = partitionAux comparer f r acc + let acc = partition1 comparer f k acc + partitionAux comparer f l acc + | SetOne (k) -> partition1 comparer f k acc + | SetEmpty -> acc + + let partition comparer f s = partitionAux comparer f s (SetEmpty, SetEmpty) + + // It's easier to get many less-important algorithms right using this active pattern + let (|MatchSetNode|MatchSetEmpty|) s = + match s with + | SetNode (k2, l, r, _) -> MatchSetNode(k2, l, r) + | SetOne (k2) -> MatchSetNode(k2, SetEmpty, SetEmpty) + | SetEmpty -> MatchSetEmpty + + let rec minimumElementAux s n = + match s with + | SetNode (k, l, _, _) -> minimumElementAux l k + | SetOne (k) -> k + | SetEmpty -> n + + and minimumElementOpt s = + match s with + | SetNode (k, l, _, _) -> Some(minimumElementAux l k) + | SetOne (k) -> Some k + | SetEmpty -> None + + and maximumElementAux s n = + match s with + | SetNode (k, _, r, _) -> maximumElementAux r k + | SetOne (k) -> k + | SetEmpty -> n + + and maximumElementOpt s = + match s with + | SetNode (k, _, r, _) -> Some(maximumElementAux r k) + | SetOne (k) -> Some(k) + | SetEmpty -> None + + let minimumElement s = + match minimumElementOpt s with + | Some(k) -> k + | None -> invalidArg "s" (SR.GetString(SR.setContainsNoElements)) + + let maximumElement s = + match maximumElementOpt s with + | Some(k) -> k + | None -> invalidArg "s" (SR.GetString(SR.setContainsNoElements)) + + // Imperative left-to-right iterators. + [] + type SetIterator<'T> when 'T: comparison = + { mutable stack: SetTree<'T> list; // invariant: always collapseLHS result + mutable started: bool // true when MoveNext has been called + } + + // collapseLHS: + // a) Always returns either [] or a list starting with SetOne. + // b) The "fringe" of the set stack is unchanged. + let rec collapseLHS stack = + match stack with + | [] -> [] + | SetEmpty :: rest -> collapseLHS rest + | SetOne _ :: _ -> stack + | SetNode (k, l, r, _) :: rest -> collapseLHS (l :: SetOne k :: r :: rest) + + let mkIterator s = { stack = collapseLHS [s]; started = false } + + let notStarted() = raise (InvalidOperationException(SR.GetString(SR.enumerationNotStarted))) + + let alreadyFinished() = raise (InvalidOperationException(SR.GetString(SR.enumerationAlreadyFinished))) + + let current i = + if i.started then + match i.stack with + | SetOne k :: _ -> k + | [] -> alreadyFinished() + | _ -> failwith "Please report error: Set iterator, unexpected stack for current" + else + notStarted() + + let rec moveNext i = + if i.started then + match i.stack with + | SetOne _ :: rest -> + i.stack <- collapseLHS rest + not i.stack.IsEmpty + | [] -> false + | _ -> failwith "Please report error: Set iterator, unexpected stack for moveNext" + else + i.started <- true; // The first call to MoveNext "starts" the enumeration. + not i.stack.IsEmpty + + let mkIEnumerator s = + let i = ref (mkIterator s) + { new IEnumerator<_> with + member __.Current = current !i + interface IEnumerator with + member __.Current = box (current !i) + member __.MoveNext() = moveNext !i + member __.Reset() = i := mkIterator s + interface System.IDisposable with + member __.Dispose() = () } + + /// Set comparison. Note this can be expensive. + let rec compareStacks (comparer: IComparer<'T>) l1 l2 = + match l1, l2 with + | [], [] -> 0 + | [], _ -> -1 + | _, [] -> 1 + | (SetEmpty _ :: t1), (SetEmpty :: t2) -> compareStacks comparer t1 t2 + | (SetOne (n1k) :: t1), (SetOne (n2k) :: t2) -> + let c = comparer.Compare(n1k, n2k) + if c <> 0 then c else compareStacks comparer t1 t2 + | (SetOne (n1k) :: t1), (SetNode (n2k, SetEmpty, n2r, _) :: t2) -> + let c = comparer.Compare(n1k, n2k) + if c <> 0 then c else compareStacks comparer (SetEmpty :: t1) (n2r :: t2) + | (SetNode (n1k, (SetEmpty as emp), n1r, _) :: t1), (SetOne (n2k) :: t2) -> + let c = comparer.Compare(n1k, n2k) + if c <> 0 then c else compareStacks comparer (n1r :: t1) (emp :: t2) + | (SetNode (n1k, SetEmpty, n1r, _) :: t1), (SetNode (n2k, SetEmpty, n2r, _) :: t2) -> + let c = comparer.Compare(n1k, n2k) + if c <> 0 then c else compareStacks comparer (n1r :: t1) (n2r :: t2) + | (SetOne (n1k) :: t1), _ -> + compareStacks comparer (SetEmpty :: SetOne (n1k) :: t1) l2 + | (SetNode (n1k, n1l, n1r, _) :: t1), _ -> + compareStacks comparer (n1l :: SetNode (n1k, SetEmpty, n1r, 0) :: t1) l2 + | _, (SetOne (n2k) :: t2) -> + compareStacks comparer l1 (SetEmpty :: SetOne (n2k) :: t2) + | _, (SetNode (n2k, n2l, n2r, _) :: t2) -> + compareStacks comparer l1 (n2l :: SetNode (n2k, SetEmpty, n2r, 0) :: t2) + + let compare comparer s1 s2 = + match s1, s2 with + | SetEmpty, SetEmpty -> 0 + | SetEmpty, _ -> -1 + | _, SetEmpty -> 1 + | _ -> compareStacks comparer [s1] [s2] + + let choose s = + minimumElement s + + let toList s = + let rec loop m acc = match m with - | SetNode(k2,l,r,_) -> f k2 || exists f l || exists f r - | SetOne(k2) -> f k2 - | SetEmpty -> false - - let isEmpty m = match m with | SetEmpty -> true | _ -> false - - let subset comparer a b = forall (fun x -> mem comparer x b) a - - let psubset comparer a b = forall (fun x -> mem comparer x b) a && exists (fun x -> not (mem comparer x a)) b + | SetNode (k, l, r, _) -> loop l (k :: loop r acc) + | SetOne (k) -> k ::acc + | SetEmpty -> acc + loop s [] - let rec filterAux comparer f s acc = - match s with - | SetNode(k,l,r,_) -> - let acc = if f k then add comparer k acc else acc - filterAux comparer f l (filterAux comparer f r acc) - | SetOne(k) -> if f k then add comparer k acc else acc - | SetEmpty -> acc + let copyToArray s (arr: _[]) i = + let j = ref i + iter (fun x -> arr.[!j] <- x; j := !j + 1) s - let filter comparer f s = filterAux comparer f s SetEmpty + let toArray s = + let n = (count s) + let res = Array.zeroCreate n + copyToArray s res 0 + res - let rec diffAux comparer m acc = - match acc with - | SetEmpty -> acc - | _ -> - match m with - | SetNode(k,l,r,_) -> diffAux comparer l (diffAux comparer r (remove comparer k acc)) - | SetOne(k) -> remove comparer k acc - | SetEmpty -> acc - - let diff comparer a b = diffAux comparer b a - - let rec union comparer t1 t2 = - // Perf: tried bruteForce for low heights, but nothing significant - match t1,t2 with - | SetNode(k1,t11,t12,h1),SetNode(k2,t21,t22,h2) -> // (t11 < k < t12) AND (t21 < k2 < t22) - // Divide and Conquer: - // Suppose t1 is largest. - // Split t2 using pivot k1 into lo and hi. - // Union disjoint subproblems and then combine. - if h1 > h2 then - let lo,_,hi = split comparer k1 t2 in - balance comparer (union comparer t11 lo) k1 (union comparer t12 hi) - else - let lo,_,hi = split comparer k2 t1 in - balance comparer (union comparer t21 lo) k2 (union comparer t22 hi) - | SetEmpty,t -> t - | t,SetEmpty -> t - | SetOne k1,t2 -> add comparer k1 t2 - | t1,SetOne k2 -> add comparer k2 t1 - - let rec intersectionAux comparer b m acc = - match m with - | SetNode(k,l,r,_) -> - let acc = intersectionAux comparer b r acc - let acc = if mem comparer k b then add comparer k acc else acc - intersectionAux comparer b l acc - | SetOne(k) -> - if mem comparer k b then add comparer k acc else acc - | SetEmpty -> acc - - let intersection comparer a b = intersectionAux comparer b a SetEmpty - - let partition1 comparer f k (acc1,acc2) = if f k then (add comparer k acc1,acc2) else (acc1,add comparer k acc2) - - let rec partitionAux comparer f s acc = - match s with - | SetNode(k,l,r,_) -> - let acc = partitionAux comparer f r acc - let acc = partition1 comparer f k acc - partitionAux comparer f l acc - | SetOne(k) -> partition1 comparer f k acc - | SetEmpty -> acc - - let partition comparer f s = partitionAux comparer f s (SetEmpty,SetEmpty) - - // It's easier to get many less-important algorithms right using this active pattern - let (|MatchSetNode|MatchSetEmpty|) s = - match s with - | SetNode(k2,l,r,_) -> MatchSetNode(k2,l,r) - | SetOne(k2) -> MatchSetNode(k2,SetEmpty,SetEmpty) - | SetEmpty -> MatchSetEmpty - - let rec minimumElementAux s n = - match s with - | SetNode(k,l,_,_) -> minimumElementAux l k - | SetOne(k) -> k - | SetEmpty -> n - - and minimumElementOpt s = - match s with - | SetNode(k,l,_,_) -> Some(minimumElementAux l k) - | SetOne(k) -> Some k - | SetEmpty -> None - - and maximumElementAux s n = - match s with - | SetNode(k,_,r,_) -> maximumElementAux r k - | SetOne(k) -> k - | SetEmpty -> n - - and maximumElementOpt s = - match s with - | SetNode(k,_,r,_) -> Some(maximumElementAux r k) - | SetOne(k) -> Some(k) - | SetEmpty -> None - - let minimumElement s = - match minimumElementOpt s with - | Some(k) -> k - | None -> invalidArg "s" (SR.GetString(SR.setContainsNoElements)) - - let maximumElement s = - match maximumElementOpt s with - | Some(k) -> k - | None -> invalidArg "s" (SR.GetString(SR.setContainsNoElements)) - - - //-------------------------------------------------------------------------- - // Imperative left-to-right iterators. - //-------------------------------------------------------------------------- - - [] - type SetIterator<'T> when 'T: comparison = - { mutable stack: SetTree<'T> list; // invariant: always collapseLHS result - mutable started: bool // true when MoveNext has been called - } - - // collapseLHS: - // a) Always returns either [] or a list starting with SetOne. - // b) The "fringe" of the set stack is unchanged. - let rec collapseLHS stack = - match stack with - | [] -> [] - | SetEmpty :: rest -> collapseLHS rest - | SetOne _ :: _ -> stack - | SetNode(k,l,r,_) :: rest -> collapseLHS (l :: SetOne k :: r :: rest) - - let mkIterator s = { stack = collapseLHS [s]; started = false } - - let notStarted() = raise (InvalidOperationException(SR.GetString(SR.enumerationNotStarted))) - let alreadyFinished() = raise (InvalidOperationException(SR.GetString(SR.enumerationAlreadyFinished))) - - let current i = - if i.started then - match i.stack with - | SetOne k :: _ -> k - | [] -> alreadyFinished() - | _ -> failwith "Please report error: Set iterator, unexpected stack for current" - else - notStarted() - - let rec moveNext i = - if i.started then - match i.stack with - | SetOne _ :: rest -> - i.stack <- collapseLHS rest; - not i.stack.IsEmpty - | [] -> false - | _ -> failwith "Please report error: Set iterator, unexpected stack for moveNext" - else - i.started <- true; // The first call to MoveNext "starts" the enumeration. - not i.stack.IsEmpty - - let mkIEnumerator s = - let i = ref (mkIterator s) - { new IEnumerator<_> with - member __.Current = current !i - interface IEnumerator with - member __.Current = box (current !i) - member __.MoveNext() = moveNext !i - member __.Reset() = i := mkIterator s - interface System.IDisposable with - member __.Dispose() = () } - - //-------------------------------------------------------------------------- - // Set comparison. This can be expensive. - //-------------------------------------------------------------------------- - - let rec compareStacks (comparer: IComparer<'T>) l1 l2 = - match l1,l2 with - | [],[] -> 0 - | [],_ -> -1 - | _,[] -> 1 - | (SetEmpty _ :: t1),(SetEmpty :: t2) -> compareStacks comparer t1 t2 - | (SetOne(n1k) :: t1),(SetOne(n2k) :: t2) -> - let c = comparer.Compare(n1k,n2k) - if c <> 0 then c else compareStacks comparer t1 t2 - | (SetOne(n1k) :: t1),(SetNode(n2k,SetEmpty,n2r,_) :: t2) -> - let c = comparer.Compare(n1k,n2k) - if c <> 0 then c else compareStacks comparer (SetEmpty :: t1) (n2r :: t2) - | (SetNode(n1k,(SetEmpty as emp),n1r,_) :: t1),(SetOne(n2k) :: t2) -> - let c = comparer.Compare(n1k,n2k) - if c <> 0 then c else compareStacks comparer (n1r :: t1) (emp :: t2) - | (SetNode(n1k,SetEmpty,n1r,_) :: t1),(SetNode(n2k,SetEmpty,n2r,_) :: t2) -> - let c = comparer.Compare(n1k,n2k) - if c <> 0 then c else compareStacks comparer (n1r :: t1) (n2r :: t2) - | (SetOne(n1k) :: t1),_ -> - compareStacks comparer (SetEmpty :: SetOne(n1k) :: t1) l2 - | (SetNode(n1k,n1l,n1r,_) :: t1),_ -> - compareStacks comparer (n1l :: SetNode(n1k,SetEmpty,n1r,0) :: t1) l2 - | _,(SetOne(n2k) :: t2) -> - compareStacks comparer l1 (SetEmpty :: SetOne(n2k) :: t2) - | _,(SetNode(n2k,n2l,n2r,_) :: t2) -> - compareStacks comparer l1 (n2l :: SetNode(n2k,SetEmpty,n2r,0) :: t2) - - let compare comparer s1 s2 = - match s1,s2 with - | SetEmpty,SetEmpty -> 0 - | SetEmpty,_ -> -1 - | _,SetEmpty -> 1 - | _ -> compareStacks comparer [s1] [s2] - - let choose s = minimumElement s - - let toList s = - let rec loop m acc = - match m with - | SetNode(k,l,r,_) -> loop l (k :: loop r acc) - | SetOne(k) -> k ::acc - | SetEmpty -> acc - loop s [] - - let copyToArray s (arr: _[]) i = - let j = ref i - iter (fun x -> arr.[!j] <- x; j := !j + 1) s - - let toArray s = - let n = (count s) - let res = Array.zeroCreate n - copyToArray s res 0; - res - - - - let rec mkFromEnumerator comparer acc (e: IEnumerator<_>) = - if e.MoveNext() then + let rec mkFromEnumerator comparer acc (e: IEnumerator<_>) = + if e.MoveNext() then mkFromEnumerator comparer (add comparer e.Current acc) e - else acc - - let ofSeq comparer (c: IEnumerable<_>) = - use ie = c.GetEnumerator() - mkFromEnumerator comparer SetEmpty ie + else acc - let ofArray comparer l = Array.fold (fun acc k -> add comparer k acc) SetEmpty l + let ofSeq comparer (c: IEnumerable<_>) = + use ie = c.GetEnumerator() + mkFromEnumerator comparer SetEmpty ie + let ofArray comparer l = + Array.fold (fun acc k -> add comparer k acc) SetEmpty l - [] - [] - [>)>] - [] - [] - type Set<[]'T when 'T: comparison >(comparer:IComparer<'T>, tree: SetTree<'T>) = +[] +[] +[>)>] +[] +[] +type Set<[]'T when 'T: comparison >(comparer:IComparer<'T>, tree: SetTree<'T>) = #if !FX_NO_BINARY_SERIALIZATION - [] - // NOTE: This type is logically immutable. This field is only mutated during deserialization. - let mutable comparer = comparer - - [] - // NOTE: This type is logically immutable. This field is only mutated during deserialization. - let mutable tree = tree - - // NOTE: This type is logically immutable. This field is only mutated during serialization and deserialization. - // - // WARNING: The compiled name of this field may never be changed because it is part of the logical - // WARNING: permanent serialization format for this type. - let mutable serializedData = null + [] + // NOTE: This type is logically immutable. This field is only mutated during deserialization. + let mutable comparer = comparer + + [] + // NOTE: This type is logically immutable. This field is only mutated during deserialization. + let mutable tree = tree + + // NOTE: This type is logically immutable. This field is only mutated during serialization and deserialization. + // + // WARNING: The compiled name of this field may never be changed because it is part of the logical + // WARNING: permanent serialization format for this type. + let mutable serializedData = null #endif - // We use .NET generics per-instantiation static fields to avoid allocating a new object for each empty - // set (it is just a lookup into a .NET table of type-instantiation-indexed static fields). + // We use .NET generics per-instantiation static fields to avoid allocating a new object for each empty + // set (it is just a lookup into a .NET table of type-instantiation-indexed static fields). - static let empty: Set<'T> = - let comparer = LanguagePrimitives.FastGenericComparer<'T> - Set<'T>(comparer, SetEmpty) + static let empty: Set<'T> = + let comparer = LanguagePrimitives.FastGenericComparer<'T> + Set<'T>(comparer, SetEmpty) #if !FX_NO_BINARY_SERIALIZATION - [] - member __.OnSerializing(context: System.Runtime.Serialization.StreamingContext) = - ignore(context) - serializedData <- SetTree.toArray tree - - // Do not set this to null, since concurrent threads may also be serializing the data - //[] - //member __.OnSerialized(context: System.Runtime.Serialization.StreamingContext) = - // serializedData <- null - - [] - member __.OnDeserialized(context: System.Runtime.Serialization.StreamingContext) = - ignore(context) - comparer <- LanguagePrimitives.FastGenericComparer<'T> - tree <- SetTree.ofArray comparer serializedData - serializedData <- null + [] + member __.OnSerializing(context: System.Runtime.Serialization.StreamingContext) = + ignore(context) + serializedData <- SetTree.toArray tree + + // Do not set this to null, since concurrent threads may also be serializing the data + //[] + //member __.OnSerialized(context: System.Runtime.Serialization.StreamingContext) = + // serializedData <- null + + [] + member __.OnDeserialized(context: System.Runtime.Serialization.StreamingContext) = + ignore(context) + comparer <- LanguagePrimitives.FastGenericComparer<'T> + tree <- SetTree.ofArray comparer serializedData + serializedData <- null #endif - [] - member internal set.Comparer = comparer + [] + member internal set.Comparer = comparer - member internal set.Tree: SetTree<'T> = tree + member internal set.Tree: SetTree<'T> = tree - [] - static member Empty: Set<'T> = empty + [] + static member Empty: Set<'T> = empty - member s.Add(value): Set<'T> = + member s.Add(value): Set<'T> = #if TRACE_SETS_AND_MAPS - SetTree.report() - SetTree.numAdds <- SetTree.numAdds + 1 - SetTree.totalSizeOnSetAdd <- SetTree.totalSizeOnSetAdd + float (SetTree.count s.Tree) + SetTree.report() + SetTree.numAdds <- SetTree.numAdds + 1 + SetTree.totalSizeOnSetAdd <- SetTree.totalSizeOnSetAdd + float (SetTree.count s.Tree) #endif - Set<'T>(s.Comparer,SetTree.add s.Comparer value s.Tree ) + Set<'T>(s.Comparer, SetTree.add s.Comparer value s.Tree ) - member s.Remove(value): Set<'T> = + member s.Remove(value): Set<'T> = #if TRACE_SETS_AND_MAPS - SetTree.report() - SetTree.numRemoves <- SetTree.numRemoves + 1 + SetTree.report() + SetTree.numRemoves <- SetTree.numRemoves + 1 #endif - Set<'T>(s.Comparer,SetTree.remove s.Comparer value s.Tree) + Set<'T>(s.Comparer, SetTree.remove s.Comparer value s.Tree) - member s.Count = SetTree.count s.Tree + member s.Count = + SetTree.count s.Tree - member s.Contains(value) = + member s.Contains(value) = #if TRACE_SETS_AND_MAPS - SetTree.report() - SetTree.numLookups <- SetTree.numLookups + 1 - SetTree.totalSizeOnSetLookup <- SetTree.totalSizeOnSetLookup + float (SetTree.count s.Tree) + SetTree.report() + SetTree.numLookups <- SetTree.numLookups + 1 + SetTree.totalSizeOnSetLookup <- SetTree.totalSizeOnSetLookup + float (SetTree.count s.Tree) #endif - SetTree.mem s.Comparer value s.Tree + SetTree.mem s.Comparer value s.Tree + + member s.Iterate(x) = + SetTree.iter x s.Tree + + member s.Fold f z = + let f = OptimizedClosures.FSharpFunc<_, _, _>.Adapt(f) + SetTree.fold (fun x z -> f.Invoke(z, x)) z s.Tree + + [] + member s.IsEmpty = + SetTree.isEmpty s.Tree + + member s.Partition f : Set<'T> * Set<'T> = + match s.Tree with + | SetEmpty -> s, s + | _ -> let t1, t2 = SetTree.partition s.Comparer f s.Tree in Set(s.Comparer, t1), Set(s.Comparer, t2) + + member s.Filter f : Set<'T> = + match s.Tree with + | SetEmpty -> s + | _ -> Set(s.Comparer, SetTree.filter s.Comparer f s.Tree) + + member s.Map f : Set<'U> = + let comparer = LanguagePrimitives.FastGenericComparer<'U> + Set(comparer, SetTree.fold (fun acc k -> SetTree.add comparer (f k) acc) (SetTree<_>.SetEmpty) s.Tree) + + member s.Exists f = + SetTree.exists f s.Tree + + member s.ForAll f = + SetTree.forall f s.Tree + + [] + static member (-) (set1: Set<'T>, set2: Set<'T>) = + match set1.Tree with + | SetEmpty -> set1 (* 0 - B = 0 *) + | _ -> + match set2.Tree with + | SetEmpty -> set1 (* A - 0 = A *) + | _ -> Set(set1.Comparer, SetTree.diff set1.Comparer set1.Tree set2.Tree) + + [] + static member (+) (set1: Set<'T>, set2: Set<'T>) = +#if TRACE_SETS_AND_MAPS + SetTree.report() + SetTree.numUnions <- SetTree.numUnions + 1 +#endif + match set2.Tree with + | SetEmpty -> set1 (* A U 0 = A *) + | _ -> + match set1.Tree with + | SetEmpty -> set2 (* 0 U B = B *) + | _ -> Set(set1.Comparer, SetTree.union set1.Comparer set1.Tree set2.Tree) - member s.Iterate(x) = SetTree.iter x s.Tree + static member Intersection(a: Set<'T>, b: Set<'T>) : Set<'T> = + match b.Tree with + | SetEmpty -> b (* A INTER 0 = 0 *) + | _ -> + match a.Tree with + | SetEmpty -> a (* 0 INTER B = 0 *) + | _ -> Set(a.Comparer, SetTree.intersection a.Comparer a.Tree b.Tree) - member s.Fold f z = - let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f) - SetTree.fold (fun x z -> f.Invoke(z, x)) z s.Tree + static member Union(sets:seq>) : Set<'T> = + Seq.fold (fun s1 s2 -> s1 + s2) Set<'T>.Empty sets - [] - member s.IsEmpty = SetTree.isEmpty s.Tree + static member Intersection(sets:seq>) : Set<'T> = + Seq.reduce (fun s1 s2 -> Set.Intersection(s1, s2)) sets - member s.Partition f : Set<'T> * Set<'T> = - match s.Tree with - | SetEmpty -> s,s - | _ -> let t1,t2 = SetTree.partition s.Comparer f s.Tree in Set(s.Comparer,t1), Set(s.Comparer,t2) + static member Equality(a: Set<'T>, b: Set<'T>) = + (SetTree.compare a.Comparer a.Tree b.Tree = 0) - member s.Filter f : Set<'T> = - match s.Tree with - | SetEmpty -> s - | _ -> Set(s.Comparer,SetTree.filter s.Comparer f s.Tree) + static member Compare(a: Set<'T>, b: Set<'T>) = + SetTree.compare a.Comparer a.Tree b.Tree - member s.Map f : Set<'U> = - let comparer = LanguagePrimitives.FastGenericComparer<'U> - Set(comparer,SetTree.fold (fun acc k -> SetTree.add comparer (f k) acc) (SetTree<_>.SetEmpty) s.Tree) + [] + member x.Choose = SetTree.choose x.Tree - member s.Exists f = SetTree.exists f s.Tree + [] + member x.MinimumElement = SetTree.minimumElement x.Tree - member s.ForAll f = SetTree.forall f s.Tree + [] + member x.MaximumElement = SetTree.maximumElement x.Tree - [] - static member (-) (set1: Set<'T>, set2: Set<'T>) = - match set1.Tree with - | SetEmpty -> set1 (* 0 - B = 0 *) - | _ -> - match set2.Tree with - | SetEmpty -> set1 (* A - 0 = A *) - | _ -> Set(set1.Comparer,SetTree.diff set1.Comparer set1.Tree set2.Tree) + member x.IsSubsetOf(otherSet: Set<'T>) = + SetTree.subset x.Comparer x.Tree otherSet.Tree - [] - static member (+) (set1: Set<'T>, set2: Set<'T>) = -#if TRACE_SETS_AND_MAPS - SetTree.report() - SetTree.numUnions <- SetTree.numUnions + 1 -#endif - match set2.Tree with - | SetEmpty -> set1 (* A U 0 = A *) - | _ -> - match set1.Tree with - | SetEmpty -> set2 (* 0 U B = B *) - | _ -> Set(set1.Comparer,SetTree.union set1.Comparer set1.Tree set2.Tree) - - static member Intersection(a: Set<'T>, b: Set<'T>) : Set<'T> = - match b.Tree with - | SetEmpty -> b (* A INTER 0 = 0 *) - | _ -> - match a.Tree with - | SetEmpty -> a (* 0 INTER B = 0 *) - | _ -> Set(a.Comparer,SetTree.intersection a.Comparer a.Tree b.Tree) - - static member Union(sets:seq>) : Set<'T> = - Seq.fold (fun s1 s2 -> s1 + s2) Set<'T>.Empty sets - - static member Intersection(sets:seq>) : Set<'T> = - Seq.reduce (fun s1 s2 -> Set.Intersection(s1,s2)) sets - - static member Equality(a: Set<'T>, b: Set<'T>) = (SetTree.compare a.Comparer a.Tree b.Tree = 0) - - static member Compare(a: Set<'T>, b: Set<'T>) = SetTree.compare a.Comparer a.Tree b.Tree - - [] - member x.Choose = SetTree.choose x.Tree - - [] - member x.MinimumElement = SetTree.minimumElement x.Tree - - [] - member x.MaximumElement = SetTree.maximumElement x.Tree - - member x.IsSubsetOf(otherSet: Set<'T>) = SetTree.subset x.Comparer x.Tree otherSet.Tree - - member x.IsSupersetOf(otherSet: Set<'T>) = SetTree.subset x.Comparer otherSet.Tree x.Tree - - member x.IsProperSubsetOf(otherSet: Set<'T>) = SetTree.psubset x.Comparer x.Tree otherSet.Tree - - member x.IsProperSupersetOf(otherSet: Set<'T>) = SetTree.psubset x.Comparer otherSet.Tree x.Tree - - member x.ToList () = SetTree.toList x.Tree - - member x.ToArray () = SetTree.toArray x.Tree - - member this.ComputeHashCode() = - let combineHash x y = (x <<< 1) + y + 631 - let mutable res = 0 - for x in this do - res <- combineHash res (hash x) - abs res - - override this.GetHashCode() = this.ComputeHashCode() - - override this.Equals(that) = - match that with - | :? Set<'T> as that -> - use e1 = (this :> seq<_>).GetEnumerator() - use e2 = (that :> seq<_>).GetEnumerator() - let rec loop () = - let m1 = e1.MoveNext() - let m2 = e2.MoveNext() - (m1 = m2) && (not m1 || ((e1.Current = e2.Current) && loop())) - loop() - | _ -> false - - interface System.IComparable with - member this.CompareTo(that: obj) = SetTree.compare this.Comparer this.Tree ((that :?> Set<'T>).Tree) - - interface ICollection<'T> with - member s.Add(x) = ignore(x); raise (new System.NotSupportedException("ReadOnlyCollection")) - member s.Clear() = raise (new System.NotSupportedException("ReadOnlyCollection")) - member s.Remove(x) = ignore(x); raise (new System.NotSupportedException("ReadOnlyCollection")) - member s.Contains(x) = SetTree.mem s.Comparer x s.Tree - member s.CopyTo(arr,i) = SetTree.copyToArray s.Tree arr i - member s.IsReadOnly = true - member s.Count = s.Count - - interface IReadOnlyCollection<'T> with - member s.Count = s.Count - - interface IEnumerable<'T> with - member s.GetEnumerator() = SetTree.mkIEnumerator s.Tree - - interface IEnumerable with - override s.GetEnumerator() = (SetTree.mkIEnumerator s.Tree :> IEnumerator) - - static member Singleton(x:'T) : Set<'T> = Set<'T>.Empty.Add(x) - - new (elements : seq<'T>) = - let comparer = LanguagePrimitives.FastGenericComparer<'T> - Set(comparer,SetTree.ofSeq comparer elements) - - static member Create(elements : seq<'T>) = Set<'T>(elements) - - static member FromArray(arr : 'T array) : Set<'T> = - let comparer = LanguagePrimitives.FastGenericComparer<'T> - Set(comparer,SetTree.ofArray comparer arr) - - override x.ToString() = - match List.ofSeq (Seq.truncate 4 x) with - | [] -> "set []" - | [h1] -> System.Text.StringBuilder().Append("set [").Append(LanguagePrimitives.anyToStringShowingNull h1).Append("]").ToString() - | [h1;h2] -> System.Text.StringBuilder().Append("set [").Append(LanguagePrimitives.anyToStringShowingNull h1).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h2).Append("]").ToString() - | [h1;h2;h3] -> System.Text.StringBuilder().Append("set [").Append(LanguagePrimitives.anyToStringShowingNull h1).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h2).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h3).Append("]").ToString() - | h1 :: h2 :: h3 :: _ -> System.Text.StringBuilder().Append("set [").Append(LanguagePrimitives.anyToStringShowingNull h1).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h2).Append("; ").Append(LanguagePrimitives.anyToStringShowingNull h3).Append("; ... ]").ToString() - - and - [] - SetDebugView<'T when 'T : comparison>(v: Set<'T>) = - - [] - member x.Items = v |> Seq.truncate 1000 |> Seq.toArray + member x.IsSupersetOf(otherSet: Set<'T>) = + SetTree.subset x.Comparer otherSet.Tree x.Tree -namespace Microsoft.FSharp.Collections + member x.IsProperSubsetOf(otherSet: Set<'T>) = + SetTree.properSubset x.Comparer x.Tree otherSet.Tree + + member x.IsProperSupersetOf(otherSet: Set<'T>) = + SetTree.properSubset x.Comparer otherSet.Tree x.Tree + + member x.ToList () = SetTree.toList x.Tree + + member x.ToArray () = SetTree.toArray x.Tree + + member this.ComputeHashCode() = + let combineHash x y = (x <<< 1) + y + 631 + let mutable res = 0 + for x in this do + res <- combineHash res (hash x) + abs res + + override this.GetHashCode() = this.ComputeHashCode() + + override this.Equals(that) = + match that with + | :? Set<'T> as that -> + use e1 = (this :> seq<_>).GetEnumerator() + use e2 = (that :> seq<_>).GetEnumerator() + let rec loop () = + let m1 = e1.MoveNext() + let m2 = e2.MoveNext() + (m1 = m2) && (not m1 || ((e1.Current = e2.Current) && loop())) + loop() + | _ -> false + + interface System.IComparable with + member this.CompareTo(that: obj) = SetTree.compare this.Comparer this.Tree ((that :?> Set<'T>).Tree) + + interface ICollection<'T> with + member s.Add(x) = ignore(x); raise (new System.NotSupportedException("ReadOnlyCollection")) + + member s.Clear() = raise (new System.NotSupportedException("ReadOnlyCollection")) + + member s.Remove(x) = ignore(x); raise (new System.NotSupportedException("ReadOnlyCollection")) + + member s.Contains(x) = SetTree.mem s.Comparer x s.Tree + + member s.CopyTo(arr, i) = SetTree.copyToArray s.Tree arr i + + member s.IsReadOnly = true + + member s.Count = s.Count + + interface IReadOnlyCollection<'T> with + member s.Count = s.Count + + interface IEnumerable<'T> with + member s.GetEnumerator() = SetTree.mkIEnumerator s.Tree + + interface IEnumerable with + override s.GetEnumerator() = (SetTree.mkIEnumerator s.Tree :> IEnumerator) + + static member Singleton(x:'T) : Set<'T> = Set<'T>.Empty.Add(x) + + new (elements : seq<'T>) = + let comparer = LanguagePrimitives.FastGenericComparer<'T> + Set(comparer, SetTree.ofSeq comparer elements) + + static member Create(elements : seq<'T>) = Set<'T>(elements) + + static member FromArray(arr : 'T array) : Set<'T> = + let comparer = LanguagePrimitives.FastGenericComparer<'T> + Set(comparer, SetTree.ofArray comparer arr) + + override x.ToString() = + match List.ofSeq (Seq.truncate 4 x) with + | [] -> "set []" + | [h1] -> + let txt1 = LanguagePrimitives.anyToStringShowingNull h1 + StringBuilder().Append("set [").Append(txt1).Append("]").ToString() + | [h1; h2] -> + let txt1 = LanguagePrimitives.anyToStringShowingNull h1 + let txt2 = LanguagePrimitives.anyToStringShowingNull h2 + StringBuilder().Append("set [").Append(txt1).Append("; ").Append(txt2).Append("]").ToString() + | [h1; h2; h3] -> + let txt1 = LanguagePrimitives.anyToStringShowingNull h1 + let txt2 = LanguagePrimitives.anyToStringShowingNull h2 + let txt3 = LanguagePrimitives.anyToStringShowingNull h3 + StringBuilder().Append("set [").Append(txt1).Append("; ").Append(txt2).Append("; ").Append(txt3).Append("]").ToString() + | h1 :: h2 :: h3 :: _ -> + let txt1 = LanguagePrimitives.anyToStringShowingNull h1 + let txt2 = LanguagePrimitives.anyToStringShowingNull h2 + let txt3 = LanguagePrimitives.anyToStringShowingNull h3 + StringBuilder().Append("set [").Append(txt1).Append("; ").Append(txt2).Append("; ").Append(txt3).Append("; ... ]").ToString() + +and + [] + SetDebugView<'T when 'T : comparison>(v: Set<'T>) = + + [] + member x.Items = v |> Seq.truncate 1000 |> Seq.toArray - open Microsoft.FSharp.Core - open Microsoft.FSharp.Core.Operators - open Microsoft.FSharp.Collections +[] +[] +module Set = - [] - [] - module Set = + [] + let isEmpty (set: Set<'T>) = set.IsEmpty - [] - let isEmpty (set: Set<'T>) = set.IsEmpty + [] + let contains element (set: Set<'T>) = set.Contains(element) - [] - let contains element (set: Set<'T>) = set.Contains(element) + [] + let add value (set: Set<'T>) = set.Add(value) - [] - let add value (set: Set<'T>) = set.Add(value) + [] + let singleton value = Set<'T>.Singleton(value) - [] - let singleton value = Set<'T>.Singleton(value) + [] + let remove value (set: Set<'T>) = set.Remove(value) - [] - let remove value (set: Set<'T>) = set.Remove(value) + [] + let union (set1: Set<'T>) (set2: Set<'T>) = set1 + set2 - [] - let union (set1: Set<'T>) (set2: Set<'T>) = set1 + set2 + [] + let unionMany sets = Set.Union(sets) - [] - let unionMany sets = Set.Union(sets) + [] + let intersect (set1: Set<'T>) (set2: Set<'T>) = Set<'T>.Intersection(set1, set2) - [] - let intersect (set1: Set<'T>) (set2: Set<'T>) = Set<'T>.Intersection(set1,set2) + [] + let intersectMany sets = Set.Intersection(sets) - [] - let intersectMany sets = Set.Intersection(sets) + [] + let iter action (set: Set<'T>) = set.Iterate(action) - [] - let iter action (set: Set<'T>) = set.Iterate(action) + [] + let empty<'T when 'T : comparison> : Set<'T> = Set<'T>.Empty - [] - let empty<'T when 'T : comparison> : Set<'T> = Set<'T>.Empty + [] + let forall predicate (set: Set<'T>) = set.ForAll predicate - [] - let forall predicate (set: Set<'T>) = set.ForAll predicate + [] + let exists predicate (set: Set<'T>) = set.Exists predicate - [] - let exists predicate (set: Set<'T>) = set.Exists predicate + [] + let filter predicate (set: Set<'T>) = set.Filter predicate - [] - let filter predicate (set: Set<'T>) = set.Filter predicate + [] + let partition predicate (set: Set<'T>) = set.Partition predicate - [] - let partition predicate (set: Set<'T>) = set.Partition predicate + [] + let fold<'T, 'State when 'T : comparison> folder (state:'State) (set: Set<'T>) = SetTree.fold folder state set.Tree - [] - let fold<'T,'State when 'T : comparison> folder (state:'State) (set: Set<'T>) = SetTree.fold folder state set.Tree + [] + let foldBack<'T, 'State when 'T : comparison> folder (set: Set<'T>) (state:'State) = SetTree.foldBack folder set.Tree state - [] - let foldBack<'T,'State when 'T : comparison> folder (set: Set<'T>) (state:'State) = SetTree.foldBack folder set.Tree state + [] + let map mapping (set: Set<'T>) = set.Map mapping - [] - let map mapping (set: Set<'T>) = set.Map mapping + [] + let count (set: Set<'T>) = set.Count - [] - let count (set: Set<'T>) = set.Count + [] + let ofList elements = Set(List.toSeq elements) - [] - let ofList elements = Set(List.toSeq elements) + [] + let ofArray (array: 'T array) = Set<'T>.FromArray(array) - [] - let ofArray (array: 'T array) = Set<'T>.FromArray(array) + [] + let toList (set: Set<'T>) = set.ToList() - [] - let toList (set: Set<'T>) = set.ToList() - - [] - let toArray (set: Set<'T>) = set.ToArray() + [] + let toArray (set: Set<'T>) = set.ToArray() - [] - let toSeq (set: Set<'T>) = (set:> seq<'T>) + [] + let toSeq (set: Set<'T>) = (set:> seq<'T>) - [] - let ofSeq (elements: seq<_>) = Set(elements) + [] + let ofSeq (elements: seq<_>) = Set(elements) - [] - let difference (set1: Set<'T>) (set2: Set<'T>) = set1 - set2 + [] + let difference (set1: Set<'T>) (set2: Set<'T>) = set1 - set2 - [] - let isSubset (set1:Set<'T>) (set2: Set<'T>) = SetTree.subset set1.Comparer set1.Tree set2.Tree + [] + let isSubset (set1:Set<'T>) (set2: Set<'T>) = SetTree.subset set1.Comparer set1.Tree set2.Tree - [] - let isSuperset (set1:Set<'T>) (set2: Set<'T>) = SetTree.subset set1.Comparer set2.Tree set1.Tree + [] + let isSuperset (set1:Set<'T>) (set2: Set<'T>) = SetTree.subset set1.Comparer set2.Tree set1.Tree - [] - let isProperSubset (set1:Set<'T>) (set2: Set<'T>) = SetTree.psubset set1.Comparer set1.Tree set2.Tree + [] + let isProperSubset (set1:Set<'T>) (set2: Set<'T>) = SetTree.properSubset set1.Comparer set1.Tree set2.Tree - [] - let isProperSuperset (set1:Set<'T>) (set2: Set<'T>) = SetTree.psubset set1.Comparer set2.Tree set1.Tree + [] + let isProperSuperset (set1:Set<'T>) (set2: Set<'T>) = SetTree.properSubset set1.Comparer set2.Tree set1.Tree - [] - let minElement (set: Set<'T>) = set.MinimumElement + [] + let minElement (set: Set<'T>) = set.MinimumElement - [] - let maxElement (set: Set<'T>) = set.MaximumElement + [] + let maxElement (set: Set<'T>) = set.MaximumElement diff --git a/tests/scripts/codingConventions.fsx b/tests/scripts/codingConventions.fsx index 9f5a997e020..69097bb4b0f 100644 --- a/tests/scripts/codingConventions.fsx +++ b/tests/scripts/codingConventions.fsx @@ -3,7 +3,7 @@ open System.IO let lines = - [| for dir in [ "src/fsharp"; "src/fsharp/symbols"; "src/fsharp/service"; "src/absil" ]do + [| for dir in [ "src/fsharp"; "src/fsharp/FSharp.Core"; "src/fsharp/symbols"; "src/fsharp/service"; "src/absil" ]do for file in Directory.EnumerateFiles(__SOURCE_DIRECTORY__ + "/../../" + dir,"*.fs") do // TcGlobals.fs gets an exception let lines = File.ReadAllLines file From e1f49336e96bc447ddd2eff152e678c5cd7fe491 Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Mon, 1 Apr 2019 09:31:28 -0700 Subject: [PATCH 24/27] Use process dependencies for fsi (#6324) * Use process dependencies for fsi * default references now have full path * tweak * Desktop does not recurse dependencies * Use existing resolution logic on desktop * build from source, system.private.corelib * ci_part4 * Deal with Dev 15.0 portable pdb symbols --- .../FSharp.Compiler.Service.fsproj | 3 + .../FSharp.Compiler.Private.fsproj | 3 + src/fsharp/CompileOps.fs | 254 ++---------------- src/fsharp/DotNetFrameworkDependencies.fs | 245 +++++++++++++++++ src/fsharp/ErrorLogger.fs | 16 +- .../FSharp.Compiler.Private.fsproj | 3 + src/fsharp/service/IncrementalBuild.fs | 9 +- src/fsharp/service/service.fs | 2 +- 8 files changed, 293 insertions(+), 242 deletions(-) create mode 100644 src/fsharp/DotNetFrameworkDependencies.fs diff --git a/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj b/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj index 166dc7976b7..dcdf91eef4a 100644 --- a/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj +++ b/fcs/FSharp.Compiler.Service/FSharp.Compiler.Service.fsproj @@ -483,6 +483,9 @@ CodeGen/IlxGen.fs + + Driver\DotNetFrameworkDependencies.fs + Driver/CompileOps.fsi diff --git a/src/buildfromsource/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj b/src/buildfromsource/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj index 6be5ea1e37d..058cf0e1b61 100644 --- a/src/buildfromsource/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj +++ b/src/buildfromsource/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj @@ -454,6 +454,9 @@ + + Driver\DotNetFrameworkDependencies.fs + Driver\CompileOps.fsi diff --git a/src/fsharp/CompileOps.fs b/src/fsharp/CompileOps.fs index 33216b30e5e..e14df2d3fb6 100644 --- a/src/fsharp/CompileOps.fs +++ b/src/fsharp/CompileOps.fs @@ -45,6 +45,8 @@ open FSharp.Compiler.Tast open FSharp.Compiler.Tastops open FSharp.Compiler.TcGlobals +open FSharp.Compiler.DotNetFrameworkDependencies + #if !NO_EXTENSIONTYPING open FSharp.Compiler.ExtensionTyping open Microsoft.FSharp.Core.CompilerServices @@ -1778,223 +1780,9 @@ let OutputDiagnosticContext prefix fileLineFn os err = Printf.bprintf os "%s%s\n" prefix line Printf.bprintf os "%s%s%s\n" prefix (String.make iA '-') (String.make iLen '^') -//---------------------------------------------------------------------------- - -let GetFSharpCoreLibraryName () = "FSharp.Core" - -// If necessary assume a reference to the latest .NET Framework FSharp.Core with which those tools are built. -let GetDefaultFSharpCoreReference () = typeof>.Assembly.Location - -type private TypeInThisAssembly = class end - -// Use the ValueTuple that is executing with the compiler if it is from System.ValueTuple -// or the System.ValueTuple.dll that sits alongside the compiler. (Note we always ship one with the compiler) -let GetDefaultSystemValueTupleReference () = - try - let asm = typeof>.Assembly - if asm.FullName.StartsWithOrdinal("System.ValueTuple") then - Some asm.Location - else - let location = Path.GetDirectoryName(typeof.Assembly.Location) - let valueTuplePath = Path.Combine(location, "System.ValueTuple.dll") - if File.Exists(valueTuplePath) then - Some valueTuplePath - else - None - with _ -> None - -let GetFsiLibraryName () = "FSharp.Compiler.Interactive.Settings" - -// This list is the default set of references for "non-project" files. -// -// These DLLs are -// (a) included in the environment used for all .fsx files (see service.fs) -// (b) included in environment for files 'orphaned' from a project context -// -- for orphaned files (files in VS without a project context) -// -- for files given on a command line without --noframework set -let DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) = - [ if assumeDotNetFramework then - yield "System" - yield "System.Xml" - yield "System.Runtime.Remoting" - yield "System.Runtime.Serialization.Formatters.Soap" - yield "System.Data" - yield "System.Drawing" - yield "System.Core" - - // These are the Portable-profile and .NET Standard 1.6 dependencies of FSharp.Core.dll. These are needed - // when an F# sript references an F# profile 7, 78, 259 or .NET Standard 1.6 component which in turn refers - // to FSharp.Core for profile 7, 78, 259 or .NET Standard. - yield "System.Runtime" // lots of types - yield "System.Linq" // System.Linq.Expressions.Expression - yield "System.Reflection" // System.Reflection.ParameterInfo - yield "System.Linq.Expressions" // System.Linq.IQueryable - yield "System.Threading.Tasks" // valuetype [System.Threading.Tasks]System.Threading.CancellationToken - yield "System.IO" // System.IO.TextWriter - //yield "System.Console" // System.Console.Out etc. - yield "System.Net.Requests" // System.Net.WebResponse etc. - yield "System.Collections" // System.Collections.Generic.List - yield "System.Runtime.Numerics" // BigInteger - yield "System.Threading" // OperationCanceledException - - // always include a default reference to System.ValueTuple.dll in scripts and out-of-project sources - match GetDefaultSystemValueTupleReference() with - | None -> () - | Some v -> yield v - - yield "System.Web" - yield "System.Web.Services" - yield "System.Windows.Forms" - yield "System.Numerics" - else - yield Path.Combine(Path.GetDirectoryName(typeof.Assembly.Location), "mscorlib.dll") // mscorlib - yield typeof.Assembly.Location // System.Console - yield typeof.Assembly.Location // System.Collections - yield typeof.Assembly.Location // System.ObjectModel - yield typeof.Assembly.Location // System.IO.FileSystem - yield typeof.Assembly.Location // System.IO - yield typeof.Assembly.Location // System.Linq - yield typeof.Assembly.Location // System.Xml - yield typeof.Assembly.Location // System.Xml.Linq - yield typeof.Assembly.Location // System.Net.Requests - yield typeof.Assembly.Location // System.Runtime.Numerics - yield typeof.Assembly.Location // System.Net.Security - yield typeof.Assembly.Location // System.Security.Claims - yield typeof.Assembly.Location // System.Text.RegularExpressions.Regex - yield typeof.Assembly.Location // System.Threading.Tasks - yield typeof.Assembly.Location // System.Threading - yield typeof.Assembly.Location // FSharp.Core - ] - - -// A set of assemblies to always consider to be system assemblies. A common set of these can be used a shared -// resources between projects in the compiler services. Also all assembles where well-known system types exist -// referenced from TcGlobals must be listed here. -let SystemAssemblies () = - HashSet - [ yield "mscorlib" - yield "netstandard" - yield "System.Runtime" - yield GetFSharpCoreLibraryName() - yield "System" - yield "System.Xml" - yield "System.Runtime.Remoting" - yield "System.Runtime.Serialization.Formatters.Soap" - yield "System.Data" - yield "System.Deployment" - yield "System.Design" - yield "System.Messaging" - yield "System.Drawing" - yield "System.Net" - yield "System.Web" - yield "System.Web.Services" - yield "System.Windows.Forms" - yield "System.Core" - yield "System.Runtime" - yield "System.Observable" - yield "System.Numerics" - yield "System.ValueTuple" - - // Additions for coreclr and portable profiles - yield "System.Collections" - yield "System.Collections.Concurrent" - yield "System.Console" - yield "System.Diagnostics.Debug" - yield "System.Diagnostics.Tools" - yield "System.Globalization" - yield "System.IO" - yield "System.Linq" - yield "System.Linq.Expressions" - yield "System.Linq.Queryable" - yield "System.Net.Requests" - yield "System.Reflection" - yield "System.Reflection.Emit" - yield "System.Reflection.Emit.ILGeneration" - yield "System.Reflection.Extensions" - yield "System.Resources.ResourceManager" - yield "System.Runtime.Extensions" - yield "System.Runtime.InteropServices" - yield "System.Runtime.InteropServices.PInvoke" - yield "System.Runtime.Numerics" - yield "System.Text.Encoding" - yield "System.Text.Encoding.Extensions" - yield "System.Text.RegularExpressions" - yield "System.Threading" - yield "System.Threading.Tasks" - yield "System.Threading.Tasks.Parallel" - yield "System.Threading.Thread" - yield "System.Threading.ThreadPool" - yield "System.Threading.Timer" - - yield "FSharp.Compiler.Interactive.Settings" - yield "Microsoft.Win32.Registry" - yield "System.Diagnostics.Tracing" - yield "System.Globalization.Calendars" - yield "System.Reflection.Primitives" - yield "System.Runtime.Handles" - yield "Microsoft.Win32.Primitives" - yield "System.IO.FileSystem" - yield "System.Net.Primitives" - yield "System.Net.Sockets" - yield "System.Private.Uri" - yield "System.AppContext" - yield "System.Buffers" - yield "System.Collections.Immutable" - yield "System.Diagnostics.DiagnosticSource" - yield "System.Diagnostics.Process" - yield "System.Diagnostics.TraceSource" - yield "System.Globalization.Extensions" - yield "System.IO.Compression" - yield "System.IO.Compression.ZipFile" - yield "System.IO.FileSystem.Primitives" - yield "System.Net.Http" - yield "System.Net.NameResolution" - yield "System.Net.WebHeaderCollection" - yield "System.ObjectModel" - yield "System.Reflection.Emit.Lightweight" - yield "System.Reflection.Metadata" - yield "System.Reflection.TypeExtensions" - yield "System.Runtime.InteropServices.RuntimeInformation" - yield "System.Runtime.Loader" - yield "System.Security.Claims" - yield "System.Security.Cryptography.Algorithms" - yield "System.Security.Cryptography.Cng" - yield "System.Security.Cryptography.Csp" - yield "System.Security.Cryptography.Encoding" - yield "System.Security.Cryptography.OpenSsl" - yield "System.Security.Cryptography.Primitives" - yield "System.Security.Cryptography.X509Certificates" - yield "System.Security.Principal" - yield "System.Security.Principal.Windows" - yield "System.Threading.Overlapped" - yield "System.Threading.Tasks.Extensions" - yield "System.Xml.ReaderWriter" - yield "System.Xml.XDocument" - - ] - -// The set of references entered into the TcConfigBuilder for scripts prior to computing -// the load closure. -// -// REVIEW: it isn't clear if there is any negative effect -// of leaving an assembly off this list. -let BasicReferencesForScriptLoadClosure(useFsiAuxLib, assumeDotNetFramework) = - [ - if assumeDotNetFramework then - -#if COMPILER_SERVICE_ASSUMES_DOTNETCORE_COMPILATION - yield Path.Combine(Path.GetDirectoryName(typeof.Assembly.Location), "mscorlib.dll"); // mscorlib -#else - yield "mscorlib" -#endif - yield GetDefaultFSharpCoreReference() ] @ // Need to resolve these explicitly so they will be found in the reference assemblies directory which is where the .xml files are. - DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) @ - [ if useFsiAuxLib then yield GetFsiLibraryName () ] - let (++) x s = x @ [s] - //---------------------------------------------------------------------------- // General file name resolver //-------------------------------------------------------------------------- @@ -2357,11 +2145,7 @@ type TcConfigBuilder = static member Initial = { -#if COMPILER_SERVICE_ASSUMES_DOTNETCORE_COMPILATION - primaryAssembly = PrimaryAssembly.System_Runtime // defaut value, can be overridden using the command line switch -#else primaryAssembly = PrimaryAssembly.Mscorlib // defaut value, can be overridden using the command line switch -#endif light = None noFeedback = false stackReserveSize = None @@ -2771,11 +2555,11 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = // Look for an explicit reference to mscorlib and use that to compute clrRoot and targetFrameworkVersion let primaryAssemblyReference, primaryAssemblyExplicitFilenameOpt = computeKnownDllReference(data.primaryAssembly.Name) let fslibReference, fslibExplicitFilenameOpt = - let (_, fileNameOpt) as res = computeKnownDllReference(GetFSharpCoreLibraryName()) + let (_, fileNameOpt) as res = computeKnownDllReference(getFSharpCoreLibraryName) match fileNameOpt with | None -> // if FSharp.Core was not provided explicitly - use version that was referenced by compiler - AssemblyReference(range0, GetDefaultFSharpCoreReference(), None), None + AssemblyReference(range0, getDefaultFSharpCoreReference, None), None | _ -> res // If either mscorlib.dll/System.Runtime.dll/netstandard.dll or FSharp.Core.dll are explicitly specified then we require the --noframework flag. @@ -2813,7 +2597,7 @@ type TcConfig private (data: TcConfigBuilder, validate: bool) = #endif None, data.legacyReferenceResolver.HighestInstalledNetFrameworkVersion() - let systemAssemblies = SystemAssemblies () + let systemAssemblies = systemAssemblies // Look for an explicit reference to FSharp.Core and use that to compute fsharpBinariesDir // FUTURE: remove this, we only read the binary for the exception it raises @@ -3719,11 +3503,11 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, let assumeDotNetFramework = primaryReference.SimpleAssemblyNameIs("mscorlib") if tcConfig.framework then - for s in DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) do + for s in defaultReferencesForScriptsAndOutOfProjectSources assumeDotNetFramework do yield AssemblyReference(rangeStartup, (if s.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) then s else s+".dll"), None) if tcConfig.useFsiAuxLib then - let name = Path.Combine(tcConfig.fsharpBinariesDir, GetFsiLibraryName() + ".dll") + let name = Path.Combine(tcConfig.fsharpBinariesDir, getFsiLibraryName + ".dll") yield AssemblyReference(rangeStartup, name, None) yield! tcConfig.referencedDLLs @@ -3817,7 +3601,7 @@ let WriteSignatureData (tcConfig: TcConfig, tcGlobals, exportRemapping, ccu: Ccu let mspec = ApplyExportRemappingToEntity tcGlobals exportRemapping mspec // For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers // don't complain when they see the resource. - let rname = if ccu.AssemblyName = GetFSharpCoreLibraryName() then FSharpSignatureDataResourceName2 else FSharpSignatureDataResourceName + let rname = if ccu.AssemblyName = getFSharpCoreLibraryName then FSharpSignatureDataResourceName2 else FSharpSignatureDataResourceName PickleToResource inMem file tcGlobals ccu (rname+ccu.AssemblyName) pickleCcuInfo { mspec=mspec compileTimeWorkingDir=tcConfig.implicitIncludeDir @@ -3829,7 +3613,7 @@ let GetOptimizationData (file, ilScopeRef, ilModule, byteReader) = let WriteOptimizationData (tcGlobals, file, inMem, ccu: CcuThunk, modulInfo) = // For historical reasons, we use a different resource name for FSharp.Core, so older F# compilers // don't complain when they see the resource. - let rname = if ccu.AssemblyName = GetFSharpCoreLibraryName() then FSharpOptimizationDataResourceName2 else FSharpOptimizationDataResourceName + let rname = if ccu.AssemblyName = getFSharpCoreLibraryName then FSharpOptimizationDataResourceName2 else FSharpOptimizationDataResourceName PickleToResource inMem file tcGlobals ccu (rname+ccu.AssemblyName) Optimizer.p_CcuOptimizationInfo modulInfo //---------------------------------------------------------------------------- @@ -3942,7 +3726,13 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu if disposed then assert false 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 + let matchNameSpace (entityOpt: Entity option) n = + match entityOpt with + | None -> None + | Some entity -> + entity.ModuleOrNamespaceType.AllEntitiesByCompiledAndLogicalMangledNames.TryFind n + + match (Some ccu.Contents, nsname) ||> List.fold(matchNameSpace) with | Some ns -> match Map.tryFind tname ns.ModuleOrNamespaceType.TypesByMangledName with | Some _ -> true @@ -4759,7 +4549,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu let fslibCcu = if tcConfig.compilingFslib then // When compiling FSharp.Core.dll, the fslibCcu reference to FSharp.Core.dll is a delayed ccu thunk fixed up during type checking - CcuThunk.CreateDelayed(GetFSharpCoreLibraryName()) + CcuThunk.CreateDelayed(getFSharpCoreLibraryName) else let fslibCcuInfo = let coreLibraryReference = tcConfig.CoreLibraryDllReference() @@ -4771,7 +4561,7 @@ type TcImports(tcConfigP: TcConfigProvider, initialResolutions: TcAssemblyResolu // Are we using a "non-canonical" FSharp.Core? match tcAltResolutions.TryFindByOriginalReference coreLibraryReference with | Some resolution -> Some resolution - | _ -> tcResolutions.TryFindByOriginalReferenceText (GetFSharpCoreLibraryName()) // was the ".dll" elided? + | _ -> tcResolutions.TryFindByOriginalReferenceText (getFSharpCoreLibraryName) // was the ".dll" elided? match resolvedAssemblyRef with | Some coreLibraryResolution -> @@ -5106,7 +4896,7 @@ module private ScriptPreprocessClosure = applyCommandLineArgs tcConfigB match basicReferences with - | None -> BasicReferencesForScriptLoadClosure(useFsiAuxLib, assumeDotNetFramework) |> List.iter(fun f->tcConfigB.AddReferencedAssemblyByPath(range0, f)) // Add script references + | None -> (basicReferencesForScriptLoadClosure useFsiAuxLib assumeDotNetFramework) |> List.iter(fun f->tcConfigB.AddReferencedAssemblyByPath(range0, f)) // Add script references | Some rs -> for m, r in rs do tcConfigB.AddReferencedAssemblyByPath(m, r) tcConfigB.resolutionEnvironment <- @@ -5116,7 +4906,7 @@ module private ScriptPreprocessClosure = | CodeContext.CompilationAndEvaluation -> ResolutionEnvironment.CompilationAndEvaluation tcConfigB.framework <- false tcConfigB.useSimpleResolution <- useSimpleResolution - // Indicates that there are some references not in BasicReferencesForScriptLoadClosure which should + // Indicates that there are some references not in basicReferencesForScriptLoadClosure which should // be added conditionally once the relevant version of mscorlib.dll has been detected. tcConfigB.implicitlyResolveAssemblies <- false TcConfig.Create(tcConfigB, validate=true) @@ -5651,3 +5441,7 @@ let TypeCheckClosedInputSet (ctok, checkForErrors, tcConfig, tcImports, tcGlobal let (tcEnvAtEndOfLastFile, topAttrs, implFiles, _), tcState = TypeCheckMultipleInputsFinish(results, tcState) let tcState, declaredImpls = TypeCheckClosedInputSetFinish (implFiles, tcState) tcState, topAttrs, declaredImpls, tcEnvAtEndOfLastFile + +// Existing public APIs delegate to newer implementations +let GetFSharpCoreLibraryName () = getFSharpCoreLibraryName +let DefaultReferencesForScriptsAndOutOfProjectSources assumeDotNetFramework = defaultReferencesForScriptsAndOutOfProjectSources assumeDotNetFramework \ No newline at end of file diff --git a/src/fsharp/DotNetFrameworkDependencies.fs b/src/fsharp/DotNetFrameworkDependencies.fs new file mode 100644 index 00000000000..16d9f70f77d --- /dev/null +++ b/src/fsharp/DotNetFrameworkDependencies.fs @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. + +// Functions to retrieve framework dependencies + + +module internal FSharp.Compiler.DotNetFrameworkDependencies + + open System + open System.Collections.Generic + open System.IO + open System.Reflection + + type private TypeInThisAssembly = class end + + let getFSharpCoreLibraryName = "FSharp.Core" + let getFsiLibraryName = "FSharp.Compiler.Interactive.Settings" + let frameworkDir = Path.GetDirectoryName(typeof.Assembly.Location) + let getDefaultFSharpCoreReference = typeof.Assembly.Location + let getFSharpCompilerLocation = Path.GetDirectoryName(typeof.Assembly.Location) + + // Use the ValueTuple that is executing with the compiler if it is from System.ValueTuple + // or the System.ValueTuple.dll that sits alongside the compiler. (Note we always ship one with the compiler) + let getDefaultSystemValueTupleReference () = + try + let asm = typeof>.Assembly + if asm.FullName.StartsWith("System.ValueTuple", StringComparison.OrdinalIgnoreCase) then + Some asm.Location + else + let location = Path.GetDirectoryName(typeof.Assembly.Location) + let valueTuplePath = Path.Combine(location, "System.ValueTuple.dll") + if File.Exists(valueTuplePath) then + Some valueTuplePath + else + None + with _ -> None + + let getDependenciesOf assemblyReferences = + let assemblies = new Dictionary() + + // Identify path to a dll in the framework directory from a simple name + let frameworkPathFromSimpleName simpleName = + let pathDll = Path.Combine(frameworkDir, simpleName + ".dll") + if not (File.Exists(pathDll)) then + let pathExe = Path.Combine(frameworkDir, simpleName + ".exe") + if not (File.Exists(pathExe)) then + pathDll + else + pathExe + else + pathDll + + // Collect all assembly dependencies into assemblies dictionary + let rec traverseDependencies reference = + // Reference can be either path to a file on disk or a Assembly Simple Name + let referenceName, path = + try + if File.Exists(reference) then + // Reference is a path to a file on disk + Path.GetFileNameWithoutExtension(reference), reference + else + // Reference is a SimpleAssembly name + reference, frameworkPathFromSimpleName reference + + with _ -> reference, frameworkPathFromSimpleName reference + + if not (assemblies.ContainsKey(referenceName)) then + try + assemblies.Add(referenceName, path) |> ignore + if referenceName <> "System.Private.CoreLib" then + let asm = System.Reflection.Assembly.LoadFrom(path) + for reference in asm.GetReferencedAssemblies() do + // System.Private.CoreLib doesn't load with reflection + traverseDependencies reference.Name + with e -> () + + assemblyReferences |> List.iter(traverseDependencies) + assemblies + + // This list is the default set of references for "non-project" files. + // + // These DLLs are + // (a) included in the environment used for all .fsx files (see service.fs) + // (b) included in environment for files 'orphaned' from a project context + // -- for orphaned files (files in VS without a project context) + // -- for files given on a command line without --noframework set + let getDesktopDefaultReferences useFsiAuxLib = [ + yield "mscorlib" + yield "System" + yield "System.Xml" + yield "System.Runtime.Remoting" + yield "System.Runtime.Serialization.Formatters.Soap" + yield "System.Data" + yield "System.Drawing" + yield "System.Core" + yield getDefaultFSharpCoreReference + if useFsiAuxLib then yield getFsiLibraryName + + // always include a default reference to System.ValueTuple.dll in scripts and out-of-project sources + match getDefaultSystemValueTupleReference() with + | None -> () + | Some v -> yield v + + // These are the Portable-profile and .NET Standard 1.6 dependencies of FSharp.Core.dll. These are needed + // when an F# sript references an F# profile 7, 78, 259 or .NET Standard 1.6 component which in turn refers + // to FSharp.Core for profile 7, 78, 259 or .NET Standard. + yield "netstandard" + yield "System.Runtime" // lots of types + yield "System.Linq" // System.Linq.Expressions.Expression + yield "System.Reflection" // System.Reflection.ParameterInfo + yield "System.Linq.Expressions" // System.Linq.IQueryable + yield "System.Threading.Tasks" // valuetype [System.Threading.Tasks]System.Threading.CancellationToken + yield "System.IO" // System.IO.TextWriter + yield "System.Net.Requests" // System.Net.WebResponse etc. + yield "System.Collections" // System.Collections.Generic.List + yield "System.Runtime.Numerics" // BigInteger + yield "System.Threading" // OperationCanceledException + yield "System.Web" + yield "System.Web.Services" + yield "System.Windows.Forms" + yield "System.Numerics" + ] + + let fetchPathsForDefaultReferencesForScriptsAndOutOfProjectSources useFsiAuxLib assumeDotNetFramework = + if assumeDotNetFramework then + getDesktopDefaultReferences useFsiAuxLib + else + // Coreclr supports netstandard assemblies only for now + (getDependenciesOf [ + yield Path.Combine(frameworkDir, "netstandard.dll"); + yield getDefaultFSharpCoreReference; + if useFsiAuxLib then yield getFsiLibraryName + ]).Values |> Seq.toList + + let defaultReferencesForScriptsAndOutOfProjectSources assumeDotNetFramework = + fetchPathsForDefaultReferencesForScriptsAndOutOfProjectSources false assumeDotNetFramework + + // A set of assemblies to always consider to be system assemblies. A common set of these can be used a shared + // resources between projects in the compiler services. Also all assemblies where well-known system types exist + // referenced from TcGlobals must be listed here. + let systemAssemblies = + HashSet [ + yield "mscorlib" + yield "netstandard" + yield "System.Runtime" + yield getFSharpCoreLibraryName + + yield "System" + yield "System.Xml" + yield "System.Runtime.Remoting" + yield "System.Runtime.Serialization.Formatters.Soap" + yield "System.Data" + yield "System.Deployment" + yield "System.Design" + yield "System.Messaging" + yield "System.Drawing" + yield "System.Net" + yield "System.Web" + yield "System.Web.Services" + yield "System.Windows.Forms" + yield "System.Core" + yield "System.Runtime" + yield "System.Observable" + yield "System.Numerics" + yield "System.ValueTuple" + + // Additions for coreclr and portable profiles + yield "System.Collections" + yield "System.Collections.Concurrent" + yield "System.Console" + yield "System.Diagnostics.Debug" + yield "System.Diagnostics.Tools" + yield "System.Globalization" + yield "System.IO" + yield "System.Linq" + yield "System.Linq.Expressions" + yield "System.Linq.Queryable" + yield "System.Net.Requests" + yield "System.Reflection" + yield "System.Reflection.Emit" + yield "System.Reflection.Emit.ILGeneration" + yield "System.Reflection.Extensions" + yield "System.Resources.ResourceManager" + yield "System.Runtime.Extensions" + yield "System.Runtime.InteropServices" + yield "System.Runtime.InteropServices.PInvoke" + yield "System.Runtime.Numerics" + yield "System.Text.Encoding" + yield "System.Text.Encoding.Extensions" + yield "System.Text.RegularExpressions" + yield "System.Threading" + yield "System.Threading.Tasks" + yield "System.Threading.Tasks.Parallel" + yield "System.Threading.Thread" + yield "System.Threading.ThreadPool" + yield "System.Threading.Timer" + + yield "FSharp.Compiler.Interactive.Settings" + yield "Microsoft.Win32.Registry" + yield "System.Diagnostics.Tracing" + yield "System.Globalization.Calendars" + yield "System.Reflection.Primitives" + yield "System.Runtime.Handles" + yield "Microsoft.Win32.Primitives" + yield "System.IO.FileSystem" + yield "System.Net.Primitives" + yield "System.Net.Sockets" + yield "System.Private.Uri" + yield "System.AppContext" + yield "System.Buffers" + yield "System.Collections.Immutable" + yield "System.Diagnostics.DiagnosticSource" + yield "System.Diagnostics.Process" + yield "System.Diagnostics.TraceSource" + yield "System.Globalization.Extensions" + yield "System.IO.Compression" + yield "System.IO.Compression.ZipFile" + yield "System.IO.FileSystem.Primitives" + yield "System.Net.Http" + yield "System.Net.NameResolution" + yield "System.Net.WebHeaderCollection" + yield "System.ObjectModel" + yield "System.Reflection.Emit.Lightweight" + yield "System.Reflection.Metadata" + yield "System.Reflection.TypeExtensions" + yield "System.Runtime.InteropServices.RuntimeInformation" + yield "System.Runtime.Loader" + yield "System.Security.Claims" + yield "System.Security.Cryptography.Algorithms" + yield "System.Security.Cryptography.Cng" + yield "System.Security.Cryptography.Csp" + yield "System.Security.Cryptography.Encoding" + yield "System.Security.Cryptography.OpenSsl" + yield "System.Security.Cryptography.Primitives" + yield "System.Security.Cryptography.X509Certificates" + yield "System.Security.Principal" + yield "System.Security.Principal.Windows" + yield "System.Threading.Overlapped" + yield "System.Threading.Tasks.Extensions" + yield "System.Xml.ReaderWriter" + yield "System.Xml.XDocument" + ] + + // The set of references entered into the TcConfigBuilder for scripts prior to computing the load closure. + let basicReferencesForScriptLoadClosure useFsiAuxLib assumeDotNetFramework = + fetchPathsForDefaultReferencesForScriptsAndOutOfProjectSources useFsiAuxLib assumeDotNetFramework diff --git a/src/fsharp/ErrorLogger.fs b/src/fsharp/ErrorLogger.fs index 8c5aa94fc6a..cb43aded141 100755 --- a/src/fsharp/ErrorLogger.fs +++ b/src/fsharp/ErrorLogger.fs @@ -330,17 +330,25 @@ type internal CompileThreadStatic = module ErrorLoggerExtensions = open System.Reflection + // Dev15.0 shipped with a bug in diasymreader in the portable pdb symbol reader which causes an AV + // This uses a simple heuristic to detect it (the vsversion is < 16.0) + let tryAndDetectDev15 = + let vsVersion = Environment.GetEnvironmentVariable("VisualStudioVersion") + match Double.TryParse(vsVersion) with + | true, v -> v < 16.0 + | _ -> false + /// Instruct the exception not to reset itself when thrown again. let PreserveStackTrace(exn) = - try - let preserveStackTrace = typeof.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance ||| BindingFlags.NonPublic) - preserveStackTrace.Invoke(exn, null) |> ignore + try + if not(tryAndDetectDev15) then + let preserveStackTrace = typeof.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance ||| BindingFlags.NonPublic) + preserveStackTrace.Invoke(exn, null) |> ignore with _ -> // This is probably only the mono case. System.Diagnostics.Debug.Assert(false, "Could not preserve stack trace for watson exception.") () - /// Reraise an exception if it is one we want to report to Watson. let ReraiseIfWatsonable(exn:exn) = #if FX_REDUCED_EXCEPTIONS diff --git a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj index 2117cda30c4..70a80240b4b 100644 --- a/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj +++ b/src/fsharp/FSharp.Compiler.Private/FSharp.Compiler.Private.fsproj @@ -489,6 +489,9 @@ + + Driver\DotNetFrameworkDependencies.fs + Driver\CompileOps.fsi diff --git a/src/fsharp/service/IncrementalBuild.fs b/src/fsharp/service/IncrementalBuild.fs index d061f3f75ee..c372fa2d8fc 100755 --- a/src/fsharp/service/IncrementalBuild.fs +++ b/src/fsharp/service/IncrementalBuild.fs @@ -1785,11 +1785,8 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput tcConfigB.projectReferences <- projectReferences -#if COMPILER_SERVICE_ASSUMES_DOTNETCORE_COMPILATION - tcConfigB.useSimpleResolution <- true // turn off msbuild resolution -#else tcConfigB.useSimpleResolution <- (getSwitchValue useSimpleResolutionSwitch) |> Option.isSome -#endif + // Apply command-line arguments and collect more source files if they are in the arguments let sourceFilesNew = ApplyCommandLineArgs(tcConfigB, sourceFiles, commandLineArgs) @@ -1816,11 +1813,9 @@ type IncrementalBuilder(tcGlobals, frameworkTcImports, nonFrameworkAssemblyInput | None -> () let tcConfig = TcConfig.Create(tcConfigB, validate=true) - let niceNameGen = NiceNameGenerator() - let outfile, _, assemblyName = tcConfigB.DecideNames sourceFilesNew - + // Resolve assemblies and create the framework TcImports. This is done when constructing the // builder itself, rather than as an incremental task. This caches a level of "system" references. No type providers are // included in these references. diff --git a/src/fsharp/service/service.fs b/src/fsharp/service/service.fs index b51ceeb2f65..3ca94694558 100644 --- a/src/fsharp/service/service.fs +++ b/src/fsharp/service/service.fs @@ -3360,7 +3360,7 @@ type CompilerEnvironment = module CompilerEnvironment = /// These are the names of assemblies that should be referenced for .fs, .ml, .fsi, .mli files that /// are not associated with a project - let DefaultReferencesForOrphanSources(assumeDotNetFramework) = DefaultReferencesForScriptsAndOutOfProjectSources(assumeDotNetFramework) + let DefaultReferencesForOrphanSources assumeDotNetFramework = DefaultReferencesForScriptsAndOutOfProjectSources assumeDotNetFramework /// Publish compiler-flags parsing logic. Must be fast because its used by the colorizer. let GetCompilationDefinesForEditing (parsingOptions: FSharpParsingOptions) = From 92ffe0ce2611a17134a8cef57df99bf9f81a7a6f Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Mon, 1 Apr 2019 10:46:02 -0700 Subject: [PATCH 25/27] Upload the experimental nightly package Fixes #6406. --- setup/publish-assets.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup/publish-assets.ps1 b/setup/publish-assets.ps1 index 7ef01a5ffc3..3d1a505bfd2 100644 --- a/setup/publish-assets.ps1 +++ b/setup/publish-assets.ps1 @@ -41,7 +41,7 @@ try { } $branchName = $branchName.Replace("/", "_") # can't have slashes in the branch name - $vsix = Join-Path $artifactsPath "VSSetup\$configuration\Insertion\VisualFSharpFull.vsix" + $vsix = Join-Path $artifactsPath "VSSetup\$configuration\VisualFSharpFull.vsix" Write-Host " Uploading '$vsix' to '$requestUrl'." From 483337d05478ba10f2318f4210bb7f994497d2a6 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Tue, 2 Apr 2019 13:34:56 -0700 Subject: [PATCH 26/27] publish nightly package as ADO artifact (#6418) This makes it much easier to install one-off builds for testing. --- .vsts-signed.yaml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.vsts-signed.yaml b/.vsts-signed.yaml index 21986906d64..0623f2e36f6 100644 --- a/.vsts-signed.yaml +++ b/.vsts-signed.yaml @@ -73,7 +73,7 @@ jobs: ArtifactName: 'VSSetup' condition: succeeded() - # Archive NuGet packages to DevOps. + # Archive NuGet packages to DevOps. - task: PublishBuildArtifacts@1 displayName: Publish Artifact Packages inputs: @@ -81,6 +81,14 @@ jobs: ArtifactName: 'Packages' condition: succeeded() + # Publish nightly package to ADO + - task: PublishBuildArtifacts@1 + displayName: Publish Artifact Nightly + inputs: + PathtoPublish: '$(Build.SourcesDirectory)\artifacts\VSSetup\$(BuildConfiguration)\VisualFSharpFull.vsix' + ArtifactName: 'Nightly' + condition: succeeded() + # Publish nightly package to MyGet - task: PowerShell@1 displayName: Publish nightly package to MyGet From fdd1bbe11d88550a2309538c80ac8bfbafae770a Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Tue, 2 Apr 2019 16:27:26 -0700 Subject: [PATCH 27/27] Fix vsix redirects (#6416) --- .../Vsix/RegisterFsharpPackage.pkgdef | 12 +++--- .../src/FSharp.Editor/Common/AssemblyInfo.fs | 5 --- .../src/FSharp.Editor/FSharp.Editor.fsproj | 13 ++++++ .../FSharp.LanguageService.Base.csproj | 8 ++++ .../Properties/AssemblyInfo.cs | 2 - .../FSharp.LanguageService/AssemblyInfo.fs | 11 ----- .../FSharp.LanguageService.fsproj | 9 ++++- .../Project/AssemblyInfo.cs | 1 - .../Project/ProjectSystem.Base.csproj | 8 ++++ .../AssemblyInfo.fs | 11 ----- .../FSharp.ProjectSystem.FSharp/Project.fs | 5 --- .../ProjectSystem.fsproj | 40 +++++++++++++++---- .../src/FSharp.VS.FSI/AssemblyInfo.fs | 2 - .../src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj | 8 ++++ 14 files changed, 83 insertions(+), 52 deletions(-) delete mode 100644 vsintegration/src/FSharp.LanguageService/AssemblyInfo.fs delete mode 100644 vsintegration/src/FSharp.ProjectSystem.FSharp/AssemblyInfo.fs diff --git a/vsintegration/Vsix/RegisterFsharpPackage.pkgdef b/vsintegration/Vsix/RegisterFsharpPackage.pkgdef index e7daeb0df08..f05ac43faa5 100644 --- a/vsintegration/Vsix/RegisterFsharpPackage.pkgdef +++ b/vsintegration/Vsix/RegisterFsharpPackage.pkgdef @@ -62,42 +62,42 @@ [$RootKey$\CLSID\{e1194663-db3c-49eb-8b45-276fcdc440ea}] "InprocServer32"="$WinDir$\SYSTEM32\MSCOREE.DLL" "Class"="Microsoft.VisualStudio.FSharp.ProjectSystem.FSharpBuildPropertyPage" -"Assembly"="FSharp.ProjectSystem.FSharp, Version=15.7.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" +"Assembly"="FSharp.ProjectSystem.FSharp, Version=15.9.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" "ThreadingModel"="Both" @="Microsoft.VisualStudio.FSharp.ProjectSystem.FSharpBuildPropertyPage" [$RootKey$\CLSID\{6d2d9b56-2691-4624-a1bf-d07a14594748}] "InprocServer32"="$WinDir$\SYSTEM32\MSCOREE.DLL" "Class"="Microsoft.VisualStudio.Editors.PropertyPages.FSharpApplicationPropPageComClass" -"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.7.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" +"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.9.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" "ThreadingModel"="Both" @="Microsoft.VisualStudio.Editors.PropertyPages.FSharpApplicationPropPageComClass" [$RootKey$\CLSID\{dd84aa8f-71bb-462a-8ef8-c9992cb325b7}] "InprocServer32"="$System$mscoree.dll" "Class"="Microsoft.VisualStudio.Editors.PropertyPages.FSharpBuildEventsPropPageComClass" -"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.7.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" +"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.9.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" "ThreadingModel"="Both" @="Microsoft.VisualStudio.Editors.PropertyPages.FSharpBuildEventsPropPageComClass" [$RootKey$\CLSID\{fac0a17e-2e70-4211-916a-0d34fb708bff}] "InprocServer32"="$System$mscoree.dll" "Class"="Microsoft.VisualStudio.Editors.PropertyPages.FSharpBuildPropPageComClass" -"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.7.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" +"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.9.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" "ThreadingModel"="Both" @="Microsoft.VisualStudio.Editors.PropertyPages.FSharpBuildPropPageComClass" [$RootKey$\CLSID\{9cfbeb2a-6824-43e2-bd3b-b112febc3772}] "InprocServer32"="$WinDir$\SYSTEM32\MSCOREE.DLL" "Class"="Microsoft.VisualStudio.Editors.PropertyPages.FSharpDebugPropPageComClass" -"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.7.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" +"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.9.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" "ThreadingModel"="Both" @="Microsoft.VisualStudio.Editors.PropertyPages.FSharpDebugPropPageComClass" [$RootKey$\CLSID\{df16b1a2-0e91-4499-ae60-c7144e614bf1}] "InprocServer32"="$WinDir$\SYSTEM32\MSCOREE.DLL" "Class"="Microsoft.VisualStudio.Editors.PropertyPages.FSharpReferencePathsPropPageComClass" -"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.7.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" +"Assembly"="FSharp.ProjectSystem.PropertyPages, Version=15.9.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" "ThreadingModel"="Both" @="Microsoft.VisualStudio.Editors.PropertyPages.FSharpReferencePathsPropPageComClass" diff --git a/vsintegration/src/FSharp.Editor/Common/AssemblyInfo.fs b/vsintegration/src/FSharp.Editor/Common/AssemblyInfo.fs index 89c8b09c241..124f3de404c 100644 --- a/vsintegration/src/FSharp.Editor/Common/AssemblyInfo.fs +++ b/vsintegration/src/FSharp.Editor/Common/AssemblyInfo.fs @@ -4,11 +4,6 @@ namespace Microsoft.VisualStudio.FSharp.Editor open Microsoft.VisualStudio.Shell -[] -[] - -do() - // This is needed to load XAML resource dictionaries from FSharp.UIResources assembly because ProvideCodeBase attribute does not work for that purpose. // This adds $PackageFolder$ to the directories probed for assemblies to load. // The attribute is inexplicably class-targeted, hence the dummy class. diff --git a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj index 6a95fa56b62..f07c8974244 100644 --- a/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj +++ b/vsintegration/src/FSharp.Editor/FSharp.Editor.fsproj @@ -160,4 +160,17 @@ + + + FSharp.Editor + $(VSAssemblyVersion) + $PackageFolder$\FSharp.Editor.dll + + + FSharp.UIResources + $(VSAssemblyVersion) + $PackageFolder$\FSharp.UIResources.dll + + + diff --git a/vsintegration/src/FSharp.LanguageService.Base/FSharp.LanguageService.Base.csproj b/vsintegration/src/FSharp.LanguageService.Base/FSharp.LanguageService.Base.csproj index 336ba963f5a..75970c600f2 100644 --- a/vsintegration/src/FSharp.LanguageService.Base/FSharp.LanguageService.Base.csproj +++ b/vsintegration/src/FSharp.LanguageService.Base/FSharp.LanguageService.Base.csproj @@ -63,4 +63,12 @@ + + + FSharp.LanguageService.Base + $(VSAssemblyVersion) + $PackageFolder$\FSharp.LanguageService.Base.dll + + + diff --git a/vsintegration/src/FSharp.LanguageService.Base/Properties/AssemblyInfo.cs b/vsintegration/src/FSharp.LanguageService.Base/Properties/AssemblyInfo.cs index 4cfaf6553c3..4d45cbc2204 100644 --- a/vsintegration/src/FSharp.LanguageService.Base/Properties/AssemblyInfo.cs +++ b/vsintegration/src/FSharp.LanguageService.Base/Properties/AssemblyInfo.cs @@ -15,5 +15,3 @@ [assembly: Guid("1EB3E293-6A40-4480-8FE6-7436C4879CA4")] [assembly: CLSCompliant(true)] - -[assembly: Microsoft.VisualStudio.Shell.ProvideCodeBase (CodeBase = @"$PackageFolder$\FSharp.LanguageService.Base.dll")] diff --git a/vsintegration/src/FSharp.LanguageService/AssemblyInfo.fs b/vsintegration/src/FSharp.LanguageService/AssemblyInfo.fs deleted file mode 100644 index a043d6eb300..00000000000 --- a/vsintegration/src/FSharp.LanguageService/AssemblyInfo.fs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. - -namespace Microsoft.FSharp - -open System.Reflection -open Microsoft.VisualStudio.Shell - -[] - -do() - diff --git a/vsintegration/src/FSharp.LanguageService/FSharp.LanguageService.fsproj b/vsintegration/src/FSharp.LanguageService/FSharp.LanguageService.fsproj index 29eee6ad191..ae682a73eee 100644 --- a/vsintegration/src/FSharp.LanguageService/FSharp.LanguageService.fsproj +++ b/vsintegration/src/FSharp.LanguageService/FSharp.LanguageService.fsproj @@ -33,7 +33,6 @@ true Microsoft.VisualStudio.FSharp.LanguageService.Strings - @@ -85,4 +84,12 @@ + + + FSharp.LanguageService + $(VSAssemblyVersion) + $PackageFolder$\FSharp.LanguageService.dll + + + diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/AssemblyInfo.cs b/vsintegration/src/FSharp.ProjectSystem.Base/Project/AssemblyInfo.cs index 0e5934a6de8..a69ce87d35a 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/AssemblyInfo.cs +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/AssemblyInfo.cs @@ -6,4 +6,3 @@ using System.Runtime.InteropServices; [assembly:ComVisible(false)] -[assembly: Microsoft.VisualStudio.Shell.ProvideCodeBase(CodeBase = @"$PackageFolder$\FSharp.ProjectSystem.Base.dll")] diff --git a/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectSystem.Base.csproj b/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectSystem.Base.csproj index 17a5023ae7c..1262d6644e7 100644 --- a/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectSystem.Base.csproj +++ b/vsintegration/src/FSharp.ProjectSystem.Base/Project/ProjectSystem.Base.csproj @@ -61,6 +61,14 @@ + + + FSharp.ProjectSystem.Base + $(VSAssemblyVersion) + $PackageFolder$\FSharp.ProjectSystem.Base.dll + + +