From 2a25184293e39a635217670652b00680de04472a Mon Sep 17 00:00:00 2001 From: Tuomas Hietanen Date: Wed, 22 Nov 2023 19:22:47 +0000 Subject: [PATCH] Some performance optimizations and code cleanup (#16302) * code optimisations and cleanup: Some ContainsKey double lookups to TryContainsKey Some nested list Contains to set Contains. Some FSharpLint rules also "dotnet fantomas . -r" but I bet it'll make merging harder. * Made FSharp.Core.dll expectation tighter. It would be nice to get both SelfContained_Trimming_Test and StaticLinkedFSharpCore_Trimming_Test the results once. * As expected, StaticLinkedFSharpCore_Trimming_Test smaller too... * vzarytovskii feedback implemented * Reverted Sets to Lists due to speculation of memory consumption in the PR comments Will open this as separate PR --- src/Compiler/AbstractIL/il.fs | 2 +- src/Compiler/AbstractIL/illex.fsl | 20 ++-- src/Compiler/AbstractIL/ilnativeres.fs | 2 +- src/Compiler/AbstractIL/ilprint.fs | 2 +- src/Compiler/AbstractIL/ilread.fs | 13 +-- src/Compiler/AbstractIL/ilreflect.fs | 10 +- src/Compiler/AbstractIL/ilsign.fs | 10 +- src/Compiler/AbstractIL/ilwritepdb.fs | 2 +- src/Compiler/Checking/CheckDeclarations.fs | 11 +- src/Compiler/Checking/CheckExpressions.fs | 17 +-- src/Compiler/Checking/CheckPatterns.fs | 2 +- .../Checking/CheckRecordSyntaxHelpers.fs | 2 +- src/Compiler/Checking/ConstraintSolver.fs | 2 +- src/Compiler/Checking/MethodOverrides.fs | 10 +- src/Compiler/Checking/NameResolution.fs | 12 +- src/Compiler/Checking/NicePrint.fs | 14 +-- .../Checking/PatternMatchCompilation.fs | 34 +++--- src/Compiler/Checking/QuotationTranslator.fs | 9 +- src/Compiler/Checking/SignatureConformance.fs | 12 +- src/Compiler/Checking/import.fs | 2 +- src/Compiler/CodeGen/EraseUnions.fs | 2 +- src/Compiler/CodeGen/IlxGen.fs | 8 +- src/Compiler/Driver/CompilerConfig.fs | 4 +- src/Compiler/Driver/CompilerDiagnostics.fs | 28 ++--- src/Compiler/Driver/CompilerImports.fs | 11 +- src/Compiler/Driver/CompilerOptions.fs | 30 +---- src/Compiler/Driver/FxResolver.fs | 2 +- .../Driver/GraphChecking/TrieMapping.fs | 8 +- src/Compiler/Driver/ParseAndCheckInputs.fs | 8 +- src/Compiler/Driver/fsc.fs | 2 +- src/Compiler/Facilities/CompilerLocation.fs | 2 +- src/Compiler/Facilities/prim-parsing.fs | 2 +- src/Compiler/Interactive/fsi.fs | 22 ++-- .../Optimize/InnerLambdasToTopLevelFuncs.fs | 8 +- src/Compiler/Optimize/LowerStateMachines.fs | 2 +- src/Compiler/Optimize/Optimizer.fs | 22 ++-- src/Compiler/Service/ExternalSymbol.fs | 2 +- src/Compiler/Service/ItemKey.fs | 4 +- .../Service/SemanticClassification.fs | 3 +- .../Service/ServiceDeclarationLists.fs | 5 +- .../Service/ServiceParamInfoLocations.fs | 2 +- src/Compiler/Symbols/Exprs.fs | 9 +- src/Compiler/Symbols/SymbolHelpers.fs | 4 +- src/Compiler/Symbols/Symbols.fs | 4 +- src/Compiler/SyntaxTree/SyntaxTreeOps.fs | 6 +- src/Compiler/SyntaxTree/XmlDoc.fs | 2 + src/Compiler/TypedTree/TcGlobals.fs | 4 +- src/Compiler/TypedTree/TypeProviders.fs | 4 +- src/Compiler/TypedTree/TypedTree.fs | 2 +- src/Compiler/TypedTree/TypedTreeOps.fs | 38 +++--- src/Compiler/TypedTree/TypedTreePickle.fs | 30 ++--- src/Compiler/TypedTree/tainted.fs | 2 +- src/Compiler/Utilities/Activity.fs | 8 +- src/Compiler/Utilities/Cancellable.fs | 3 +- src/Compiler/Utilities/XmlAdapters.fs | 2 +- src/Compiler/Utilities/illib.fs | 12 +- src/Compiler/Utilities/lib.fs | 2 +- src/Compiler/Utilities/sformat.fs | 6 +- src/Compiler/Utilities/sr.fs | 4 +- src/FSharp.Build/FSharpEmbedResourceText.fs | 2 +- src/FSharp.Build/Fsc.fs | 4 +- src/FSharp.Core/Linq.fs | 110 +++++++++--------- src/FSharp.Core/Query.fs | 24 ++-- src/FSharp.Core/QueryExtensions.fs | 9 +- src/FSharp.Core/array.fs | 16 ++- src/FSharp.Core/async.fs | 14 +-- src/FSharp.Core/eventmodule.fs | 2 +- src/FSharp.Core/fslib-extra-pervasives.fs | 10 +- src/FSharp.Core/list.fs | 8 +- src/FSharp.Core/mailbox.fs | 2 +- src/FSharp.Core/printf.fs | 16 +-- src/FSharp.Core/quotations.fs | 2 +- src/FSharp.Core/seq.fs | 6 +- src/FSharp.Core/seqcore.fs | 2 +- src/FSharp.Core/set.fs | 2 +- src/FSharp.Core/tasks.fs | 4 +- .../FSharp.DependencyManager.Utilities.fs | 6 +- .../FSharp.DependencyManager.fs | 4 +- .../LegacyMSBuildReferenceResolver.fs | 57 ++------- tests/AheadOfTime/Trimming/check.ps1 | 4 +- tests/fsharp/single-test.fs | 2 +- tests/service/data/TestTP/ProvidedTypes.fs | 2 +- 82 files changed, 374 insertions(+), 441 deletions(-) diff --git a/src/Compiler/AbstractIL/il.fs b/src/Compiler/AbstractIL/il.fs index d12eb8e7c8a..5e475d96193 100644 --- a/src/Compiler/AbstractIL/il.fs +++ b/src/Compiler/AbstractIL/il.fs @@ -5118,7 +5118,7 @@ let decodeILAttribData (ca: ILAttribute) = ILAttribElem.Char(char (int32 n)), sigptr | ILType.Value tspec when tspec.Name = "System.Boolean" -> let n, sigptr = sigptr_get_byte bytes sigptr - ILAttribElem.Bool(not (n = 0)), sigptr + ILAttribElem.Bool(n <> 0), sigptr | ILType.Boxed tspec when tspec.Name = "System.String" -> let n, sigptr = sigptr_get_serstring_possibly_null bytes sigptr ILAttribElem.String n, sigptr diff --git a/src/Compiler/AbstractIL/illex.fsl b/src/Compiler/AbstractIL/illex.fsl index 30f179e7ed9..92c1190b14c 100644 --- a/src/Compiler/AbstractIL/illex.fsl +++ b/src/Compiler/AbstractIL/illex.fsl @@ -57,16 +57,16 @@ let kwdInstrTable = (let t = HashMultiMap(1000, HashIdentity.Structural) List.iter t.Add (Lazy.force keywords); let addTable f l = List.iter (fun (x,i) -> t.Add (String.concat "." x,f i)) (Lazy.force l) - addTable (fun i -> INSTR_NONE i) NoArgInstrs; - addTable (fun i -> INSTR_I i) Int32Instrs; - addTable (fun i -> INSTR_I32_I32 i) Int32Int32Instrs; - addTable (fun i -> INSTR_I8 i) Int64Instrs; - addTable (fun i -> INSTR_R i) DoubleInstrs; - addTable (fun i -> INSTR_TYPE i) TypeInstrs; - addTable (fun i -> INSTR_INT_TYPE i) IntTypeInstrs; - addTable (fun i -> INSTR_VALUETYPE i) ValueTypeInstrs; - addTable (fun i -> INSTR_STRING i) StringInstrs; - addTable (fun i -> INSTR_TOK i) TokenInstrs; + addTable (INSTR_NONE) NoArgInstrs; + addTable (INSTR_I) Int32Instrs; + addTable (INSTR_I32_I32) Int32Int32Instrs; + addTable (INSTR_I8) Int64Instrs; + addTable (INSTR_R) DoubleInstrs; + addTable (INSTR_TYPE) TypeInstrs; + addTable (INSTR_INT_TYPE) IntTypeInstrs; + addTable (INSTR_VALUETYPE) ValueTypeInstrs; + addTable (INSTR_STRING) StringInstrs; + addTable (INSTR_TOK) TokenInstrs; t) let kwdOrInstr s = (Lazy.force kwdInstrTable).[s] (* words *) diff --git a/src/Compiler/AbstractIL/ilnativeres.fs b/src/Compiler/AbstractIL/ilnativeres.fs index 36a83a04f55..0d0b6a1c986 100644 --- a/src/Compiler/AbstractIL/ilnativeres.fs +++ b/src/Compiler/AbstractIL/ilnativeres.fs @@ -54,7 +54,7 @@ type CvtResFile() = let mutable resourceNames = List() // The stream might be empty, so let's check - if not (reader.PeekChar() = -1) then + if reader.PeekChar() <> -1 then let mutable startPos = stream.Position let mutable initial32Bits = reader.ReadUInt32() diff --git a/src/Compiler/AbstractIL/ilprint.fs b/src/Compiler/AbstractIL/ilprint.fs index 44df57dc323..9d278dbe317 100644 --- a/src/Compiler/AbstractIL/ilprint.fs +++ b/src/Compiler/AbstractIL/ilprint.fs @@ -272,7 +272,7 @@ and output_tyvar os d = and goutput_typ_with_shortened_class_syntax env os = function - | ILType.Boxed tspec when tspec.GenericArgs = [] -> goutput_tref env os tspec.TypeRef + | ILType.Boxed tspec when List.isEmpty tspec.GenericArgs -> goutput_tref env os tspec.TypeRef | typ2 -> goutput_typ env os typ2 and goutput_gactuals env os inst = diff --git a/src/Compiler/AbstractIL/ilread.fs b/src/Compiler/AbstractIL/ilread.fs index 8f806c61fe7..2e28354e95c 100644 --- a/src/Compiler/AbstractIL/ilread.fs +++ b/src/Compiler/AbstractIL/ilread.fs @@ -40,14 +40,13 @@ let _ = let noStableFileHeuristic = try - (Environment.GetEnvironmentVariable("FSharp_NoStableFileHeuristic") <> null) + not (isNull (Environment.GetEnvironmentVariable "FSharp_NoStableFileHeuristic")) with _ -> false let alwaysMemoryMapFSC = try - (Environment.GetEnvironmentVariable("FSharp_AlwaysMemoryMapCommandLineCompiler") - <> null) + not (isNull (Environment.GetEnvironmentVariable "FSharp_AlwaysMemoryMapCommandLineCompiler")) with _ -> false @@ -639,9 +638,9 @@ let instrs () = | Some ty -> I_callconstraint(true, tl, ty, mspec, y) | None -> I_callvirt(tl, mspec, y)) )) - i_leave_s, I_unconditional_i8_instr(noPrefixes (fun x -> I_leave x)) + i_leave_s, I_unconditional_i8_instr(noPrefixes I_leave) i_br_s, I_unconditional_i8_instr(noPrefixes I_br) - i_leave, I_unconditional_i32_instr(noPrefixes (fun x -> I_leave x)) + i_leave, I_unconditional_i32_instr(noPrefixes I_leave) i_br, I_unconditional_i32_instr(noPrefixes I_br) i_brtrue_s, I_conditional_i8_instr(noPrefixes (fun x -> I_brcmp(BI_brtrue, x))) i_brfalse_s, I_conditional_i8_instr(noPrefixes (fun x -> I_brcmp(BI_brfalse, x))) @@ -2826,7 +2825,7 @@ and seekReadMethodDefAsMethodDataUncached ctxtH idx = seekReadIndexedRow ( ctxt.getNumRows TableNames.TypeDef, (fun i -> i, seekReadTypeDefRowWithExtents ctxt i), - (fun r -> r), + id, (fun (_, ((_, _, _, _, _, methodsIdx), (_, endMethodsIdx))) -> if endMethodsIdx <= idx then 1 elif methodsIdx <= idx && idx < endMethodsIdx then 0 @@ -2874,7 +2873,7 @@ and seekReadFieldDefAsFieldSpecUncached ctxtH idx = seekReadIndexedRow ( ctxt.getNumRows TableNames.TypeDef, (fun i -> i, seekReadTypeDefRowWithExtents ctxt i), - (fun r -> r), + id, (fun (_, ((_, _, _, _, fieldsIdx, _), (endFieldsIdx, _))) -> if endFieldsIdx <= idx then 1 elif fieldsIdx <= idx && idx < endFieldsIdx then 0 diff --git a/src/Compiler/AbstractIL/ilreflect.fs b/src/Compiler/AbstractIL/ilreflect.fs index c61bb48f8fc..748ecafda21 100644 --- a/src/Compiler/AbstractIL/ilreflect.fs +++ b/src/Compiler/AbstractIL/ilreflect.fs @@ -265,12 +265,12 @@ type TypeBuilder with let t = typB.CreateTypeAndLog() let m = - if box t <> null then + if not (isNull (box t)) then t.GetMethod(nm, (args |> Seq.map (fun x -> x.GetType()) |> Seq.toArray)) else null - if m <> null then + if not (isNull m) then m.Invoke(null, args) else raise (MissingMethodException nm) @@ -1787,7 +1787,7 @@ let definePInvokeMethod = |] ) -let enablePInvoke = definePInvokeMethod <> null +let enablePInvoke = not (isNull definePInvokeMethod) let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) = let attrs = mdef.Attributes @@ -1828,7 +1828,7 @@ let rec buildMethodPass2 cenv tref (typB: TypeBuilder) emEnv (mdef: ILMethodDef) // Use reflection to invoke the api when we are executing on a platform that doesn't directly have this API. let methB = - System.Diagnostics.Debug.Assert(definePInvokeMethod <> null, "Runtime does not have DefinePInvokeMethod") // Absolutely can't happen + System.Diagnostics.Debug.Assert(not (isNull definePInvokeMethod), "Runtime does not have DefinePInvokeMethod") // Absolutely can't happen definePInvokeMethod.Invoke( typB, @@ -1988,7 +1988,7 @@ let buildFieldPass2 cenv tref (typB: TypeBuilder) emEnv (fdef: ILFieldDef) = delayedFieldInits = (fun () -> fieldB.SetConstant(initial.AsObject())) :: emEnv.delayedFieldInits } - fdef.Offset |> Option.iter (fun offset -> fieldB.SetOffset offset) + fdef.Offset |> Option.iter (fieldB.SetOffset) // custom attributes: done on pass 3 as they may reference attribute constructors generated on // pass 2. let fref = mkILFieldRef (tref, fdef.Name, fdef.FieldType) diff --git a/src/Compiler/AbstractIL/ilsign.fs b/src/Compiler/AbstractIL/ilsign.fs index 80418aeca48..7a383d4a079 100644 --- a/src/Compiler/AbstractIL/ilsign.fs +++ b/src/Compiler/AbstractIL/ilsign.fs @@ -183,10 +183,10 @@ let toCLRKeyBlob (rsaParameters: RSAParameters) (algId: int) : byte array = raise (CryptographicException(getResourceString (FSComp.SR.ilSignInvalidAlgId ()))) // Validate the RSA structure first. - if rsaParameters.Modulus = null then + if isNull rsaParameters.Modulus then raise (CryptographicException(String.Format(getResourceString (FSComp.SR.ilSignInvalidRSAParams ()), "Modulus"))) - if rsaParameters.Exponent = null || rsaParameters.Exponent.Length > 4 then + if isNull rsaParameters.Exponent || rsaParameters.Exponent.Length > 4 then raise (CryptographicException(String.Format(getResourceString (FSComp.SR.ilSignInvalidRSAParams ()), "Exponent"))) let modulusLength = rsaParameters.Modulus.Length @@ -194,7 +194,7 @@ let toCLRKeyBlob (rsaParameters: RSAParameters) (algId: int) : byte array = // We assume that if P != null, then so are Q, DP, DQ, InverseQ and D and indicate KeyPair RSA Parameters let isPrivate = - if rsaParameters.P <> null then + if not (isNull rsaParameters.P) then validateRSAField rsaParameters.P halfModulusLength "P" validateRSAField rsaParameters.Q halfModulusLength "Q" validateRSAField rsaParameters.DP halfModulusLength "DP" @@ -213,7 +213,7 @@ let toCLRKeyBlob (rsaParameters: RSAParameters) (algId: int) : byte array = bw.Write(int (modulusLength + BLOBHEADER_LENGTH)) // CLRHeader.KeyLength // Write out the BLOBHEADER - bw.Write(byte (if isPrivate = true then PRIVATEKEYBLOB else PUBLICKEYBLOB)) // BLOBHEADER.bType + bw.Write(byte (if isPrivate then PRIVATEKEYBLOB else PUBLICKEYBLOB)) // BLOBHEADER.bType bw.Write(byte BLOBHEADER_CURRENT_BVERSION) // BLOBHEADER.bVersion bw.Write(int16 0) // BLOBHEADER.wReserved @@ -235,7 +235,7 @@ let toCLRKeyBlob (rsaParameters: RSAParameters) (algId: int) : byte array = bw.Write expAsDword // RSAPubKey.pubExp bw.Write(rsaParameters.Modulus |> Array.rev) // Copy over the modulus for both public and private - if isPrivate = true then + if isPrivate then do bw.Write(rsaParameters.P |> Array.rev) bw.Write(rsaParameters.Q |> Array.rev) diff --git a/src/Compiler/AbstractIL/ilwritepdb.fs b/src/Compiler/AbstractIL/ilwritepdb.fs index 30f606e0230..24082eea2b3 100644 --- a/src/Compiler/AbstractIL/ilwritepdb.fs +++ b/src/Compiler/AbstractIL/ilwritepdb.fs @@ -324,7 +324,7 @@ let sortMethods info = let getRowCounts tableRowCounts = let builder = ImmutableArray.CreateBuilder(tableRowCounts |> Array.length) - tableRowCounts |> Seq.iter (fun x -> builder.Add x) + tableRowCounts |> Seq.iter (builder.Add) builder.MoveToImmutable() let scopeSorter (scope1: PdbMethodScope) (scope2: PdbMethodScope) = diff --git a/src/Compiler/Checking/CheckDeclarations.fs b/src/Compiler/Checking/CheckDeclarations.fs index e621eb98f4e..56497f344ad 100644 --- a/src/Compiler/Checking/CheckDeclarations.fs +++ b/src/Compiler/Checking/CheckDeclarations.fs @@ -1728,7 +1728,7 @@ module MutRecBindingChecking = // Check it is not one of the generalized variables... not (genSet.Contains tp) && // Check it involves a generalized variable in one of its constraints... - freeInTypar.Exists(fun otherTypar -> genSet.Contains otherTypar)) + freeInTypar.Exists(genSet.Contains)) //printfn "unsolvedTyparsInvolvingGeneralizedVariables.Length = %d" unsolvedTyparsInvolvingGeneralizedVariables.Length //for x in unsolvedTypars do // printfn "unsolvedTyparsInvolvingGeneralizedVariable: %s #%d" x.DisplayName x.Stamp @@ -2536,6 +2536,7 @@ module EstablishTypeDefinitionCores = error(Error(FSComp.SR.tcKindOfTypeSpecifiedDoesNotMatchDefinition(), m)) k + [] let private (|TyconCoreAbbrevThatIsReallyAUnion|_|) (hasMeasureAttr, envinner: TcEnv, id: Ident) synTyconRepr = match synTyconRepr with | SynTypeDefnSimpleRepr.TypeAbbrev(_, StripParenTypes (SynType.LongIdent(SynLongIdent([unionCaseName], _, _))), m) @@ -2543,9 +2544,9 @@ module EstablishTypeDefinitionCores = (not hasMeasureAttr && (isNil (LookupTypeNameInEnvNoArity OpenQualified unionCaseName.idText envinner.NameEnv) || id.idText = unionCaseName.idText)) -> - Some(unionCaseName, m) + ValueSome(unionCaseName, m) | _ -> - None + ValueNone /// Get the component types that make a record, union or struct type. /// @@ -5321,7 +5322,7 @@ and TcModuleOrNamespaceElements cenv parent endm env xml mutRecNSInfo openDecls0 let moduleContents = TMDefs moduleDefs // Collect up the attributes that are global to the file - let topAttrsNew = compiledDefs |> List.map p33 |> List.concat + let topAttrsNew = compiledDefs |> List.collect p33 return (moduleContents, topAttrsNew, envAtEnd) } @@ -5412,7 +5413,7 @@ let CombineTopAttrs topAttrs1 topAttrs2 = assemblyAttrs = topAttrs1.assemblyAttrs @ topAttrs2.assemblyAttrs } let rec IterTyconsOfModuleOrNamespaceType f (mty: ModuleOrNamespaceType) = - mty.AllEntities |> QueueList.iter (fun tycon -> f tycon) + mty.AllEntities |> QueueList.iter f mty.ModuleAndNamespaceDefinitions |> List.iter (fun v -> IterTyconsOfModuleOrNamespaceType f v.ModuleOrNamespaceType) diff --git a/src/Compiler/Checking/CheckExpressions.fs b/src/Compiler/Checking/CheckExpressions.fs index 3beb48b00f5..9f31d7f600e 100644 --- a/src/Compiler/Checking/CheckExpressions.fs +++ b/src/Compiler/Checking/CheckExpressions.fs @@ -1118,7 +1118,7 @@ let PublishValueDefn (cenv: cenv) env declKind (vspec: Val) = | Some _ when (not vspec.IsCompilerGenerated && // Extrinsic extensions don't get added to the tcaug - not (declKind = ExtrinsicExtensionBinding)) -> + declKind <> ExtrinsicExtensionBinding) -> // // Static initializers don't get published to the tcaug // not (memberInfo.MemberFlags.MemberKind = SynMemberKind.ClassConstructor)) -> @@ -1223,10 +1223,11 @@ let CheckRequiredProperties (g:TcGlobals) (env: TcEnv) (cenv: TcFileState) (minf let setterPropNames = finalAssignedItemSetters |> List.choose (function | AssignedItemSetter(_, AssignedPropSetter (_, pinfo, _, _), _) -> Some pinfo.PropertyName | _ -> None) + |> Set.ofList let missingProps = requiredProps - |> List.filter (fun pinfo -> not (List.contains pinfo.PropertyName setterPropNames)) + |> List.filter (fun pinfo -> not (Set.contains pinfo.PropertyName setterPropNames)) if missingProps.Length > 0 then let details = NicePrint.multiLineStringOfPropInfos g cenv.amap mMethExpr env.DisplayEnv missingProps errorR(Error(FSComp.SR.tcMissingRequiredMembers details, mMethExpr)) @@ -4774,7 +4775,7 @@ and TcStaticConstantParameter (cenv: cenv) (env: TcEnv) tpenv kind (StripParenTy | SynConst.Double n when typeEquiv g g.float_ty kind -> record(g.float_ty); box (n: double) | SynConst.Char n when typeEquiv g g.char_ty kind -> record(g.char_ty); box (n: char) | SynConst.String (s, _, _) - | SynConst.SourceIdentifier (_, s, _) when s <> null && typeEquiv g g.string_ty kind -> record(g.string_ty); box (s: string) + | SynConst.SourceIdentifier (_, s, _) when (not (isNull s)) && typeEquiv g g.string_ty kind -> record(g.string_ty); box (s: string) | SynConst.Bool b when typeEquiv g g.bool_ty kind -> record(g.bool_ty); box (b: bool) | _ -> fail() v, tpenv @@ -5715,7 +5716,7 @@ and TcExprUndelayed (cenv: cenv) (overallTy: OverallTy) env tpenv (synExpr: SynE cenv.TcArrayOrListComputedExpression cenv env overallTy tpenv (isArray, comp) m | SynExpr.LetOrUse _ -> - TcLinearExprs (TcExprThatCanBeCtorBody cenv) cenv env overallTy tpenv false synExpr (fun x -> x) + TcLinearExprs (TcExprThatCanBeCtorBody cenv) cenv env overallTy tpenv false synExpr id | SynExpr.TryWith (synBodyExpr, synWithClauses, mTryToLast, spTry, spWith, trivia) -> TcExprTryWith cenv overallTy env tpenv (synBodyExpr, synWithClauses, trivia.WithToEndRange, mTryToLast, spTry, spWith) @@ -5747,7 +5748,7 @@ and TcExprUndelayed (cenv: cenv) (overallTy: OverallTy) env tpenv (synExpr: SynE TcStmtThatCantBeCtorBody cenv env tpenv synInnerExpr | SynExpr.IfThenElse _ -> - TcLinearExprs (TcExprThatCanBeCtorBody cenv) cenv env overallTy tpenv false synExpr (fun x -> x) + TcLinearExprs (TcExprThatCanBeCtorBody cenv) cenv env overallTy tpenv false synExpr id // This is for internal use in the libraries only | SynExpr.LibraryOnlyStaticOptimization (constraints, expr2, expr3, m) -> @@ -6088,7 +6089,7 @@ and TcExprJoinIn (cenv: cenv) overallTy env tpenv (synExpr1, mInToken, synExpr2, and TcExprSequential (cenv: cenv) overallTy env tpenv (synExpr, _sp, dir, synExpr1, synExpr2, m) = if dir then - TcLinearExprs (TcExprThatCanBeCtorBody cenv) cenv env overallTy tpenv false synExpr (fun x -> x) + TcLinearExprs (TcExprThatCanBeCtorBody cenv) cenv env overallTy tpenv false synExpr id else // Constructors using "new (...) = then " let env = { env with eIsControlFlow = true } @@ -11049,7 +11050,7 @@ and TcLetBinding (cenv: cenv) isUse env containerInfo declKind tpenv (synBinds, let lazyFreeInEnv = lazy (GeneralizationHelpers.ComputeUngeneralizableTypars env) // Generalize the bindings... - (((fun x -> x), env, tpenv), checkedBinds) ||> List.fold (fun (buildExpr, env, tpenv) tbinfo -> + ((id, env, tpenv), checkedBinds) ||> List.fold (fun (buildExpr, env, tpenv) tbinfo -> let (CheckedBindingInfo(inlineFlag, attrs, xmlDoc, tcPatPhase2, explicitTyparInfo, nameToPrelimValSchemeMap, rhsExpr, _, tauTy, m, debugPoint, _, literalValue, isFixed)) = tbinfo let enclosingDeclaredTypars = [] let (ExplicitTyparInfo(_, declaredTypars, canInferTypars)) = explicitTyparInfo @@ -12311,7 +12312,7 @@ and TcLetrecBindings overridesOK (cenv: cenv) env tpenv (binds, bindsm, scopem) bindsWithoutLaziness //(fun (fun doBindings bindings -> doBindings bindings) - (fun bindings -> bindings) + id (fun doBindings bindings -> [doBindings bindings]) bindsm List.concat results diff --git a/src/Compiler/Checking/CheckPatterns.fs b/src/Compiler/Checking/CheckPatterns.fs index b009ef02825..741d6c8f8fc 100644 --- a/src/Compiler/Checking/CheckPatterns.fs +++ b/src/Compiler/Checking/CheckPatterns.fs @@ -387,7 +387,7 @@ and TcPatOr warnOnUpper cenv env vFlags patEnv ty pat1 pat2 m = let pat2R, patEnv2 = TcPat warnOnUpper cenv env None vFlags (TcPatLinearEnv(tpenv, names, takenNames)) ty pat2 let (TcPatLinearEnv(tpenv, names2, takenNames2)) = patEnv2 - if not (takenNames1 = takenNames2) then + if takenNames1 <> takenNames2 then errorR (UnionPatternsBindDifferentNames m) names1 |> Map.iter (fun _ (PrelimVal1 (id=id1; prelimType=ty1)) -> diff --git a/src/Compiler/Checking/CheckRecordSyntaxHelpers.fs b/src/Compiler/Checking/CheckRecordSyntaxHelpers.fs index 100f0c87b27..5f59e1ac3ec 100644 --- a/src/Compiler/Checking/CheckRecordSyntaxHelpers.fs +++ b/src/Compiler/Checking/CheckRecordSyntaxHelpers.fs @@ -33,7 +33,7 @@ let GroupUpdatesToNestedFields (fields: ((Ident list * Ident) * SynExpr option) let rec groupIfNested res xs = match xs with | [] -> res - | x :: [] -> x :: res + | [ x ] -> x :: res | x :: y :: ys -> match x, y with | (lidwid, Some(SynExpr.Record(baseInfo, copyInfo, fields1, m))), (_, Some(SynExpr.Record(recordFields = fields2))) -> diff --git a/src/Compiler/Checking/ConstraintSolver.fs b/src/Compiler/Checking/ConstraintSolver.fs index d54f7c59883..e552cb3e993 100644 --- a/src/Compiler/Checking/ConstraintSolver.fs +++ b/src/Compiler/Checking/ConstraintSolver.fs @@ -1066,7 +1066,7 @@ and SolveAnonInfoEqualsAnonInfo (csenv: ConstraintSolverEnv) m2 (anonInfo1: Anon if not (ccuEq anonInfo1.Assembly anonInfo2.Assembly) then do! ErrorD (ConstraintSolverError(FSComp.SR.tcAnonRecdCcuMismatch(anonInfo1.Assembly.AssemblyName, anonInfo2.Assembly.AssemblyName), csenv.m,m2)) - if not (anonInfo1.SortedNames = anonInfo2.SortedNames) then + if anonInfo1.SortedNames <> anonInfo2.SortedNames then let (|Subset|Superset|Overlap|CompletelyDifferent|) (first, second) = let first = Set first let second = Set second diff --git a/src/Compiler/Checking/MethodOverrides.fs b/src/Compiler/Checking/MethodOverrides.fs index 9593ff9bb02..53f40ba7ce2 100644 --- a/src/Compiler/Checking/MethodOverrides.fs +++ b/src/Compiler/Checking/MethodOverrides.fs @@ -439,10 +439,7 @@ module DispatchSlotChecking = // check any of the missing overrides has isReqdTyInterface flag set // in which case we use the message "with suggestion" missingOverloadImplementation - |> Seq.map fst - |> Seq.filter id - |> Seq.isEmpty - |> not + |> Seq.exists fst if missingOverloadImplementation.Count = 1 then // only one missing override, we have specific message for that @@ -455,8 +452,7 @@ module DispatchSlotChecking = let signatures = (missingOverloadImplementation |> Seq.truncate maxDisplayedOverrides - |> Seq.map snd - |> Seq.map (fun signature -> System.Environment.NewLine + "\t'" + signature.Value + "'") + |> Seq.map (snd >> fun signature -> System.Environment.NewLine + "\t'" + signature.Value + "'") |> String.concat "") + System.Environment.NewLine // we have specific message if the list is truncated @@ -757,7 +753,7 @@ module DispatchSlotChecking = GetIntrinsicPropInfosOfType infoReader None ad AllowMultiIntfInstantiations.Yes IgnoreOverrides reqdTyRange reqdTy |> List.filter isRelevantRequiredProperty - let dispatchSlots = dispatchSlotSet |> List.map snd |> List.concat + let dispatchSlots = dispatchSlotSet |> List.collect snd let dispatchSlotsKeyed = dispatchSlots |> NameMultiMap.initBy (fun reqdSlot -> reqdSlot.MethodInfo.LogicalName) yield SlotImplSet(dispatchSlots, dispatchSlotsKeyed, availPriorOverrides, reqdProperties) ] diff --git a/src/Compiler/Checking/NameResolution.fs b/src/Compiler/Checking/NameResolution.fs index c5e50a97a30..fd6550983c5 100644 --- a/src/Compiler/Checking/NameResolution.fs +++ b/src/Compiler/Checking/NameResolution.fs @@ -4340,8 +4340,8 @@ let ResolveCompletionsInType (ncenv: NameResolver) nenv (completionTargets: Reso not (MethInfoIsUnseen g m ty minfo) && not minfo.IsConstructor && not minfo.IsClassConstructor && - not (minfo.LogicalName = ".cctor") && - not (minfo.LogicalName = ".ctor") && + (minfo.LogicalName <> ".cctor") && + (minfo.LogicalName <> ".ctor") && isApplicableMeth minfo ty && not (suppressedMethNames.Contains minfo.LogicalName) @@ -4404,7 +4404,7 @@ let ResolveCompletionsInType (ncenv: NameResolver) nenv (completionTargets: Reso if methsWithStaticParams.IsEmpty then minfos else minfos |> List.filter (fun minfo -> let nm = minfo.LogicalName - not (nm.Contains "," && methsWithStaticParams |> List.exists (fun m -> nm.StartsWithOrdinal m))) + not (nm.Contains "," && methsWithStaticParams |> List.exists (nm.StartsWithOrdinal))) #endif minfos @@ -5039,8 +5039,8 @@ let ResolveCompletionsInTypeForItem (ncenv: NameResolver) nenv m ad statics ty ( not (MethInfoIsUnseen g m ty minfo) && not minfo.IsConstructor && not minfo.IsClassConstructor && - not (minfo.LogicalName = ".cctor") && - not (minfo.LogicalName = ".ctor") && + (minfo.LogicalName <> ".cctor") && + (minfo.LogicalName <> ".ctor") && not (suppressedMethNames.Contains minfo.LogicalName) result @@ -5097,7 +5097,7 @@ let ResolveCompletionsInTypeForItem (ncenv: NameResolver) nenv m ad statics ty ( if methsWithStaticParams.IsEmpty then minfos else minfos |> List.filter (fun minfo -> let nm = minfo.LogicalName - not (nm.Contains "," && methsWithStaticParams |> List.exists (fun m -> nm.StartsWithOrdinal m))) + not (nm.Contains "," && methsWithStaticParams |> List.exists (nm.StartsWithOrdinal))) #endif minfos diff --git a/src/Compiler/Checking/NicePrint.fs b/src/Compiler/Checking/NicePrint.fs index c7062e058d2..12587b22aac 100644 --- a/src/Compiler/Checking/NicePrint.fs +++ b/src/Compiler/Checking/NicePrint.fs @@ -1960,7 +1960,7 @@ module TastDefinitionPrinting = IsMethInfoAccessible amap m ad minfo && // Discard method impls such as System.IConvertible.ToBoolean not (minfo.IsILMethod && minfo.DisplayName.Contains(".")) && - not (minfo.DisplayName.Split('.') |> Array.exists (fun part -> isDiscard part))) + not (minfo.DisplayName.Split('.') |> Array.exists isDiscard)) let ilFields = infoReader.GetILFieldInfosOfType (None, ad, m, ty) @@ -2425,8 +2425,7 @@ module InferredSigPrinting = |> List.choose (function ModuleOrNamespaceBinding.Binding bind -> Some bind | _ -> None) |> valsOfBinds |> List.filter filterVal - |> List.map mkLocalValRef - |> List.map (PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv infoReader) + |> List.map (mkLocalValRef >> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv infoReader) |> aboveListL) @@ (mbinds @@ -2437,8 +2436,7 @@ module InferredSigPrinting = | TMDefLet(bind, _) -> ([bind.Var] |> List.filter filterVal - |> List.map mkLocalValRef - |> List.map (PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv infoReader) + |> List.map (mkLocalValRef >> PrintTastMemberOrVals.prettyLayoutOfValOrMemberNoInst denv infoReader) |> aboveListL) | TMDefOpens _ -> emptyL @@ -2662,8 +2660,7 @@ let stringOfMethInfoFSharpStyle infoReader m denv minfo = /// Convert MethInfos to lines separated by newline including a newline as the first character let multiLineStringOfMethInfos infoReader m denv minfos = minfos - |> List.map (stringOfMethInfo infoReader m denv) - |> List.map (sprintf "%s %s" Environment.NewLine) + |> List.map (stringOfMethInfo infoReader m denv >> sprintf "%s %s" Environment.NewLine) |> String.concat "" let stringOfPropInfo g amap m denv pinfo = @@ -2672,8 +2669,7 @@ let stringOfPropInfo g amap m denv pinfo = /// Convert PropInfos to lines separated by newline including a newline as the first character let multiLineStringOfPropInfos g amap m denv pinfos = pinfos - |> List.map (stringOfPropInfo g amap m denv) - |> List.map (sprintf "%s %s" Environment.NewLine) + |> List.map (stringOfPropInfo g amap m denv >> sprintf "%s %s" Environment.NewLine) |> String.concat "" /// Convert a ParamData to a string diff --git a/src/Compiler/Checking/PatternMatchCompilation.fs b/src/Compiler/Checking/PatternMatchCompilation.fs index 7e22a4635c5..3caacecb982 100644 --- a/src/Compiler/Checking/PatternMatchCompilation.fs +++ b/src/Compiler/Checking/PatternMatchCompilation.fs @@ -232,7 +232,7 @@ let RefuteDiscrimSet g m path discrims : Expr * CounterExampleType = and mkOneKnown tm n tys = let flds = List.mapi (fun i ty -> if i = n then tm ty else (mkUnknown ty, CounterExampleType.WithoutEnum)) tys List.map fst flds, List.fold (fun acc (_, eCoversVals) -> acc.Combine(eCoversVals)) CounterExampleType.WithoutEnum flds - and mkUnknowns tys = List.map (fun x -> mkUnknown x) tys + and mkUnknowns tys = List.map mkUnknown tys let tm ty = match discrims with @@ -243,24 +243,24 @@ let RefuteDiscrimSet g m path discrims : Expr * CounterExampleType = | DecisionTreeTest.Const c :: rest -> let consts = Set.ofList (c :: List.choose (function DecisionTreeTest.Const c -> Some c | _ -> None) rest) let c' = - Seq.tryFind (fun c -> not (consts.Contains c)) + Seq.tryFind (consts.Contains >> not) (match c with - | Const.Bool _ -> [ true; false ] |> List.toSeq |> Seq.map (fun v -> Const.Bool v) - | Const.SByte _ -> Seq.append (seq { 0y .. System.SByte.MaxValue }) (seq { System.SByte.MinValue .. 0y })|> Seq.map (fun v -> Const.SByte v) - | Const.Int16 _ -> Seq.append (seq { 0s .. System.Int16.MaxValue }) (seq { System.Int16.MinValue .. 0s }) |> Seq.map (fun v -> Const.Int16 v) - | Const.Int32 _ -> Seq.append (seq { 0 .. System.Int32.MaxValue }) (seq { System.Int32.MinValue .. 0 })|> Seq.map (fun v -> Const.Int32 v) - | Const.Int64 _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map (fun v -> Const.Int64 v) - | Const.IntPtr _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map (fun v -> Const.IntPtr v) - | Const.Byte _ -> seq { 0uy .. System.Byte.MaxValue } |> Seq.map (fun v -> Const.Byte v) - | Const.UInt16 _ -> seq { 0us .. System.UInt16.MaxValue } |> Seq.map (fun v -> Const.UInt16 v) - | Const.UInt32 _ -> seq { 0u .. System.UInt32.MaxValue } |> Seq.map (fun v -> Const.UInt32 v) - | Const.UInt64 _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map (fun v -> Const.UInt64 v) - | Const.UIntPtr _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map (fun v -> Const.UIntPtr v) - | Const.Double _ -> seq { 0 .. System.Int32.MaxValue } |> Seq.map (fun v -> Const.Double(float v)) - | Const.Single _ -> seq { 0 .. System.Int32.MaxValue } |> Seq.map (fun v -> Const.Single(float32 v)) - | Const.Char _ -> seq { 32us .. System.UInt16.MaxValue } |> Seq.map (fun v -> Const.Char(char v)) + | Const.Bool _ -> [ true; false ] |> List.toSeq |> Seq.map Const.Bool + | Const.SByte _ -> Seq.append (seq { 0y .. System.SByte.MaxValue }) (seq { System.SByte.MinValue .. 0y })|> Seq.map Const.SByte + | Const.Int16 _ -> Seq.append (seq { 0s .. System.Int16.MaxValue }) (seq { System.Int16.MinValue .. 0s }) |> Seq.map Const.Int16 + | Const.Int32 _ -> Seq.append (seq { 0 .. System.Int32.MaxValue }) (seq { System.Int32.MinValue .. 0 })|> Seq.map Const.Int32 + | Const.Int64 _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map Const.Int64 + | Const.IntPtr _ -> Seq.append (seq { 0L .. System.Int64.MaxValue }) (seq { System.Int64.MinValue .. 0L })|> Seq.map Const.IntPtr + | Const.Byte _ -> seq { 0uy .. System.Byte.MaxValue } |> Seq.map Const.Byte + | Const.UInt16 _ -> seq { 0us .. System.UInt16.MaxValue } |> Seq.map Const.UInt16 + | Const.UInt32 _ -> seq { 0u .. System.UInt32.MaxValue } |> Seq.map Const.UInt32 + | Const.UInt64 _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map Const.UInt64 + | Const.UIntPtr _ -> seq { 0UL .. System.UInt64.MaxValue } |> Seq.map Const.UIntPtr + | Const.Double _ -> seq { 0 .. System.Int32.MaxValue } |> Seq.map (float >> Const.Double) + | Const.Single _ -> seq { 0 .. System.Int32.MaxValue } |> Seq.map (float32 >> Const.Single) + | Const.Char _ -> seq { 32us .. System.UInt16.MaxValue } |> Seq.map (char >> Const.Char) | Const.String _ -> seq { 1 .. System.Int32.MaxValue } |> Seq.map (fun v -> Const.String(System.String('a', v))) - | Const.Decimal _ -> seq { 1 .. System.Int32.MaxValue } |> Seq.map (fun v -> Const.Decimal(decimal v)) + | Const.Decimal _ -> seq { 1 .. System.Int32.MaxValue } |> Seq.map (decimal >> Const.Decimal) | _ -> raise CannotRefute) diff --git a/src/Compiler/Checking/QuotationTranslator.fs b/src/Compiler/Checking/QuotationTranslator.fs index 063609d0232..fa0d317ab95 100644 --- a/src/Compiler/Checking/QuotationTranslator.fs +++ b/src/Compiler/Checking/QuotationTranslator.fs @@ -263,11 +263,12 @@ and ConvWitnessInfo cenv env m traitInfo = let witnessInfo = traitInfo.GetWitnessInfo() let env = { env with suppressWitnesses = true } // First check if this is a witness in ReflectedDefinition code - if env.witnessesInScope.ContainsKey witnessInfo then - let witnessArgIdx = env.witnessesInScope[witnessInfo] + match env.witnessesInScope.TryGetValue witnessInfo with + | true, witnessesInScopeValue -> + let witnessArgIdx = witnessesInScopeValue QP.mkVar witnessArgIdx // Otherwise it is a witness in a quotation literal - else + | false, _ -> let holeTy = GenWitnessTy g witnessInfo let idx = cenv.exprSplices.Count let fillExpr = Expr.WitnessArg(traitInfo, m) @@ -708,7 +709,7 @@ and private ConvExprCore cenv (env : QuotationTranslationEnv) (expr: Expr) : QP. wfail(Error(FSComp.SR.crefQuotationsCantRequireByref(), m)) | TOp.TraitCall traitInfo, _, args -> - let g = g + //let g = g let inWitnessPassingScope = not env.witnessesInScope.IsEmpty let witnessArgInfo = if g.generateWitnesses && inWitnessPassingScope then diff --git a/src/Compiler/Checking/SignatureConformance.fs b/src/Compiler/Checking/SignatureConformance.fs index 27cbe35a13c..f24a93c5fc0 100644 --- a/src/Compiler/Checking/SignatureConformance.fs +++ b/src/Compiler/Checking/SignatureConformance.fs @@ -162,7 +162,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = (errorR(Error(FSComp.SR.typrelSigImplNotCompatibleConstraintsDifferRemove(sigTypar.Name, LayoutRender.showL(NicePrint.layoutTyparConstraint denv (sigTypar, sigTyparCx))), m)); false) else true) && - (not checkingSig || checkAttribs aenv implTypar.Attribs sigTypar.Attribs (fun attribs -> implTypar.SetAttribs attribs))) + (not checkingSig || checkAttribs aenv implTypar.Attribs sigTypar.Attribs (implTypar.SetAttribs))) and checkTypeDef (aenv: TypeEquivEnv) (infoReader: InfoReader) (implTycon: Tycon) (sigTycon: Tycon) = let m = implTycon.Range @@ -349,7 +349,7 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = checkTypars m aenv implTypars sigTypars && if not (typeAEquiv g aenv implValTy sigValTy) then err denv FSComp.SR.ValueNotContainedMutabilityTypesDiffer elif not (checkValInfo aenv (err denv) implVal sigVal) then false - elif not (implVal.IsExtensionMember = sigVal.IsExtensionMember) then err denv FSComp.SR.ValueNotContainedMutabilityExtensionsDiffer + elif implVal.IsExtensionMember <> sigVal.IsExtensionMember then err denv FSComp.SR.ValueNotContainedMutabilityExtensionsDiffer elif not (checkMemberDatasConform (err denv) (implVal.Attribs, implVal, implVal.MemberInfo) (sigVal.Attribs, sigVal, sigVal.MemberInfo)) then false else checkAttribs aenv implVal.Attribs sigVal.Attribs (fun attribs -> implVal.SetAttribs attribs) @@ -403,9 +403,9 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = match implMemberInfo, sigMemberInfo with | None, None -> true | Some implMembInfo, Some sigMembInfo -> - if not ((implVal.CompiledName g.CompilerGlobalState) = (sigVal.CompiledName g.CompilerGlobalState)) then + if (implVal.CompiledName g.CompilerGlobalState) <> (sigVal.CompiledName g.CompilerGlobalState) then err(FSComp.SR.ValueNotContainedMutabilityDotNetNamesDiffer) - elif not (implMembInfo.MemberFlags.IsInstance = sigMembInfo.MemberFlags.IsInstance) then + elif implMembInfo.MemberFlags.IsInstance <> sigMembInfo.MemberFlags.IsInstance then err(FSComp.SR.ValueNotContainedMutabilityStaticsDiffer) elif false then err(FSComp.SR.ValueNotContainedMutabilityVirtualsDiffer) @@ -419,9 +419,9 @@ type Checker(g, amap, denv, remapInfo: SignatureRepackageInfo, checkingSig) = // This is an example where it is OK for the signature to say 'non-final' when the implementation says 'final' elif not implMembInfo.MemberFlags.IsFinal && sigMembInfo.MemberFlags.IsFinal then err(FSComp.SR.ValueNotContainedMutabilityFinalsDiffer) - elif not (implMembInfo.MemberFlags.IsOverrideOrExplicitImpl = sigMembInfo.MemberFlags.IsOverrideOrExplicitImpl) then + elif implMembInfo.MemberFlags.IsOverrideOrExplicitImpl <> sigMembInfo.MemberFlags.IsOverrideOrExplicitImpl then err(FSComp.SR.ValueNotContainedMutabilityOverridesDiffer) - elif not (implMembInfo.MemberFlags.MemberKind = sigMembInfo.MemberFlags.MemberKind) then + elif implMembInfo.MemberFlags.MemberKind <> sigMembInfo.MemberFlags.MemberKind then err(FSComp.SR.ValueNotContainedMutabilityOneIsConstructor) else let finstance = ValSpecIsCompiledAsInstance g sigVal diff --git a/src/Compiler/Checking/import.fs b/src/Compiler/Checking/import.fs index d96286fa745..7f1f13efda2 100644 --- a/src/Compiler/Checking/import.fs +++ b/src/Compiler/Checking/import.fs @@ -503,7 +503,7 @@ let multisetDiscriminateAndMap nodef tipf (items: ('Key list * 'Value) list) = buckets[key] <- match buckets.TryGetValue key with | true, b -> (rest, v) :: b - | _ -> (rest, v) :: [] + | _ -> [rest, v] [ for KeyValue(key, items) in buckets -> nodef key items ] diff --git a/src/Compiler/CodeGen/EraseUnions.fs b/src/Compiler/CodeGen/EraseUnions.fs index ccac71c01fd..083feeb0534 100644 --- a/src/Compiler/CodeGen/EraseUnions.fs +++ b/src/Compiler/CodeGen/EraseUnions.fs @@ -1245,7 +1245,7 @@ let mkClassUnionDef let ctor = // Structs with fields are created using static makers methods // Structs without fields can share constructor for the 'tag' value, we just create one - if isStruct && not (cidx = minNullaryIdx) then + if isStruct && cidx <> minNullaryIdx then [] else [ diff --git a/src/Compiler/CodeGen/IlxGen.fs b/src/Compiler/CodeGen/IlxGen.fs index 52dae0137a0..08661366b35 100644 --- a/src/Compiler/CodeGen/IlxGen.fs +++ b/src/Compiler/CodeGen/IlxGen.fs @@ -4525,7 +4525,7 @@ and GenNamedLocalTyFuncCall cenv (cgbuf: CodeGenBuffer) eenv ty cloinfo tyargs m ilDirectGenericParams, ilDirectWitnessParams, directWitnessInfos - if not (List.length ilDirectGenericParams = ilTyArgs.Length) then + if List.length ilDirectGenericParams <> ilTyArgs.Length then errorR (Error(FSComp.SR.ilIncorrectNumberOfTypeArguments (), m)) // Recover result (value or reference types) via unbox_any. @@ -7839,10 +7839,10 @@ and GenDecisionTreeCases | _ -> contf targetInfos // Used for the peephole optimization below -and (|BoolExpr|_|) = +and [] (|BoolExpr|_|) = function - | Expr.Const(Const.Bool b1, _, _) -> Some b1 - | _ -> None + | Expr.Const(Const.Bool b1, _, _) -> ValueSome b1 + | _ -> ValueNone and GenDecisionTreeTest cenv diff --git a/src/Compiler/Driver/CompilerConfig.fs b/src/Compiler/Driver/CompilerConfig.fs index 4a289c40c75..32298c0cf05 100644 --- a/src/Compiler/Driver/CompilerConfig.fs +++ b/src/Compiler/Driver/CompilerConfig.fs @@ -99,7 +99,7 @@ let GetWarningNumber (m, warningNumber: string) = // anything else is ignored None if Char.IsDigit(warningNumber[0]) then Some(int32 warningNumber) - elif warningNumber.StartsWithOrdinal("FS") = true then + elif warningNumber.StartsWithOrdinal "FS" then raise (ArgumentException()) else None @@ -864,7 +864,7 @@ type TcConfigBuilder = member tcConfigB.DecideNames sourceFiles = use _ = UseBuildPhase BuildPhase.Parameter - if sourceFiles = [] then + if List.isEmpty sourceFiles then errorR (Error(FSComp.SR.buildNoInputsSpecified (), rangeCmdArgs)) let ext () = diff --git a/src/Compiler/Driver/CompilerDiagnostics.fs b/src/Compiler/Driver/CompilerDiagnostics.fs index 42b12474c69..9894d505948 100644 --- a/src/Compiler/Driver/CompilerDiagnostics.fs +++ b/src/Compiler/Driver/CompilerDiagnostics.fs @@ -1337,18 +1337,20 @@ type Exception with |> List.exists (fun prods -> let prodIds = prods - |> List.map Parser.prodIdxToNonTerminal - |> List.map (fun nonTerminal -> - match nonTerminal with - | NONTERM_Category_Type -> Parser.NONTERM_typ - | NONTERM_Category_Expr -> Parser.NONTERM_declExpr - | NONTERM_Category_Pattern -> Parser.NONTERM_atomicPattern - | NONTERM_Category_IfThenElse -> Parser.NONTERM_ifExprThen - | NONTERM_Category_SignatureFile -> Parser.NONTERM_signatureFile - | NONTERM_Category_ImplementationFile -> Parser.NONTERM_implementationFile - | NONTERM_Category_Definition -> Parser.NONTERM_moduleDefn - | NONTERM_Category_Interaction -> Parser.NONTERM_interaction - | nt -> nt) + |> List.map ( + Parser.prodIdxToNonTerminal + >> fun nonTerminal -> + match nonTerminal with + | NONTERM_Category_Type -> Parser.NONTERM_typ + | NONTERM_Category_Expr -> Parser.NONTERM_declExpr + | NONTERM_Category_Pattern -> Parser.NONTERM_atomicPattern + | NONTERM_Category_IfThenElse -> Parser.NONTERM_ifExprThen + | NONTERM_Category_SignatureFile -> Parser.NONTERM_signatureFile + | NONTERM_Category_ImplementationFile -> Parser.NONTERM_implementationFile + | NONTERM_Category_Definition -> Parser.NONTERM_moduleDefn + | NONTERM_Category_Interaction -> Parser.NONTERM_interaction + | nt -> nt + ) |> Set.ofList |> Set.toList @@ -1655,7 +1657,7 @@ type Exception with os.AppendString(LetRecUnsound2E().Format (List.head path).DisplayName (bos.ToString())) - | LetRecEvaluatedOutOfOrder(_, _, _, _) -> os.AppendString(LetRecEvaluatedOutOfOrderE().Format) + | LetRecEvaluatedOutOfOrder(_) -> os.AppendString(LetRecEvaluatedOutOfOrderE().Format) | LetRecCheckedAtRuntime _ -> os.AppendString(LetRecCheckedAtRuntimeE().Format) diff --git a/src/Compiler/Driver/CompilerImports.fs b/src/Compiler/Driver/CompilerImports.fs index c5419de36c0..e828863c3a8 100644 --- a/src/Compiler/Driver/CompilerImports.fs +++ b/src/Compiler/Driver/CompilerImports.fs @@ -508,7 +508,7 @@ type TcConfig with if tcConfig.useSimpleResolution then failwith "MSBuild resolution is not supported." - if originalReferences = [] then + if List.isEmpty originalReferences then [], [] else // Group references by name with range values in the grouped value list. @@ -529,7 +529,7 @@ type TcConfig with [| for (_filename, maxIndexOfReference, references) in groupedReferences do let assemblyResolution = - references |> List.choose (fun r -> tcConfig.TryResolveLibWithDirectories r) + references |> List.choose (tcConfig.TryResolveLibWithDirectories) if not assemblyResolution.IsEmpty then (maxIndexOfReference, assemblyResolution) @@ -1755,14 +1755,14 @@ and [] TcImports assert (nameof (tcImports) = "tcImports") let mutable systemRuntimeContainsTypeRef = - (fun typeName -> tcImports.SystemRuntimeContainsType typeName) + tcImports.SystemRuntimeContainsType // When the tcImports is disposed the systemRuntimeContainsTypeRef thunk is replaced // with one raising an exception. tcImportsStrong.AttachDisposeTypeProviderAction(fun () -> systemRuntimeContainsTypeRef <- fun _ -> raise (ObjectDisposedException("The type provider has been disposed"))) - (fun arg -> systemRuntimeContainsTypeRef arg) + systemRuntimeContainsTypeRef // Note, this only captures tcImportsWeak let mutable getReferencedAssemblies = @@ -2129,8 +2129,7 @@ and [] TcImports ccuRawDataAndInfos |> List.iter (fun (_, _, phase2) -> phase2 ()) #endif ccuRawDataAndInfos - |> List.map p23 - |> List.map (fun asm -> ResolvedImportedAssembly(asm, m)) + |> List.map (p23 >> fun asm -> ResolvedImportedAssembly(asm, m)) phase2 diff --git a/src/Compiler/Driver/CompilerOptions.fs b/src/Compiler/Driver/CompilerOptions.fs index 85d5c0e7093..221d02bcbb2 100644 --- a/src/Compiler/Driver/CompilerOptions.fs +++ b/src/Compiler/Driver/CompilerOptions.fs @@ -570,7 +570,7 @@ let SetDeterministicSwitch (tcConfigB: TcConfigBuilder) switch = let SetReferenceAssemblyOnlySwitch (tcConfigB: TcConfigBuilder) switch = match tcConfigB.emitMetadataAssembly with - | MetadataAssemblyGeneration.None when tcConfigB.standalone = false && tcConfigB.extraStaticLinkRoots.IsEmpty -> + | MetadataAssemblyGeneration.None when (not tcConfigB.standalone) && tcConfigB.extraStaticLinkRoots.IsEmpty -> tcConfigB.emitMetadataAssembly <- if (switch = OptionSwitch.On) then MetadataAssemblyGeneration.ReferenceOnly @@ -580,7 +580,7 @@ let SetReferenceAssemblyOnlySwitch (tcConfigB: TcConfigBuilder) switch = let SetReferenceAssemblyOutSwitch (tcConfigB: TcConfigBuilder) outputPath = match tcConfigB.emitMetadataAssembly with - | MetadataAssemblyGeneration.None when tcConfigB.standalone = false && tcConfigB.extraStaticLinkRoots.IsEmpty -> + | MetadataAssemblyGeneration.None when (not tcConfigB.standalone) && tcConfigB.extraStaticLinkRoots.IsEmpty -> if FileSystem.IsInvalidPathShim outputPath then error (Error(FSComp.SR.optsInvalidRefOut (), rangeCmdArgs)) else @@ -747,13 +747,7 @@ let inputFileFlagsBoth (tcConfigB: TcConfigBuilder) = None, Some(FSComp.SR.optsReference ()) ) - CompilerOption( - "compilertool", - tagFile, - OptionString(fun s -> tcConfigB.AddCompilerToolsByPath s), - None, - Some(FSComp.SR.optsCompilerTool ()) - ) + CompilerOption("compilertool", tagFile, OptionString tcConfigB.AddCompilerToolsByPath, None, Some(FSComp.SR.optsCompilerTool ())) ] let inputFileFlagsFsc tcConfigB = inputFileFlagsBoth tcConfigB @@ -981,13 +975,7 @@ let resourcesFlagsFsc (tcConfigB: TcConfigBuilder) = Some(FSComp.SR.optsNowin32manifest ()) ) - CompilerOption( - "resource", - tagResInfo, - OptionString(fun s -> tcConfigB.AddEmbeddedResource s), - None, - Some(FSComp.SR.optsResource ()) - ) + CompilerOption("resource", tagResInfo, OptionString tcConfigB.AddEmbeddedResource, None, Some(FSComp.SR.optsResource ())) CompilerOption( "linkresource", @@ -1019,13 +1007,7 @@ let codeGenerationFlags isFsi (tcConfigB: TcConfigBuilder) = [ CompilerOption("embed", tagNone, OptionSwitch(SetEmbedAllSourceSwitch tcConfigB), None, Some(FSComp.SR.optsEmbedAllSource ())) - CompilerOption( - "embed", - tagFileList, - OptionStringList(fun f -> tcConfigB.AddEmbeddedSourceFile f), - None, - Some(FSComp.SR.optsEmbedSource ()) - ) + CompilerOption("embed", tagFileList, OptionStringList tcConfigB.AddEmbeddedSourceFile, None, Some(FSComp.SR.optsEmbedSource ())) CompilerOption("sourcelink", tagFile, OptionString(fun f -> tcConfigB.sourceLink <- f), None, Some(FSComp.SR.optsSourceLink ())) ] @@ -2217,7 +2199,7 @@ let PostProcessCompilerArgs (abbrevArgs: string Set) (args: string[]) = let testingAndQAFlags _tcConfigB = [ - CompilerOption("dumpAllCommandLineOptions", tagNone, OptionConsoleOnly(fun blocks -> DumpCompilerOptionBlocks blocks), None, None) // "Command line options") + CompilerOption("dumpAllCommandLineOptions", tagNone, OptionConsoleOnly(DumpCompilerOptionBlocks), None, None) // "Command line options") ] // Core compiler options, overview diff --git a/src/Compiler/Driver/FxResolver.fs b/src/Compiler/Driver/FxResolver.fs index 674639e0c24..6f8643c30a1 100644 --- a/src/Compiler/Driver/FxResolver.fs +++ b/src/Compiler/Driver/FxResolver.fs @@ -936,7 +936,7 @@ type internal FxResolver if useFsiAuxLib then getFsiLibraryImplementationReference () ] - |> List.filter (fun f -> systemAssemblies.Contains(Path.GetFileNameWithoutExtension(f))) + |> List.filter (Path.GetFileNameWithoutExtension >> systemAssemblies.Contains) sdkReferences, false with e -> diff --git a/src/Compiler/Driver/GraphChecking/TrieMapping.fs b/src/Compiler/Driver/GraphChecking/TrieMapping.fs index 575f06a6fe3..ff7b32e5640 100644 --- a/src/Compiler/Driver/GraphChecking/TrieMapping.fs +++ b/src/Compiler/Driver/GraphChecking/TrieMapping.fs @@ -84,10 +84,10 @@ let rec mergeTrieNodes (accumulatorTrie: TrieNode) (currentTrie: TrieNode) : Tri let nextChildren = (accumulatorTrie.Children, currentTrie.Children) ||> Seq.fold (fun accChildren (KeyValue(k, v)) -> - if not (accChildren.ContainsKey k) then - accChildren.Add(k, v) - else - let accNode = accChildren[k] + match accChildren.TryGetValue k with + | false, _ -> accChildren.Add(k, v) + | true, kVal -> + let accNode = kVal accChildren.SetItem(k, mergeTrieNodes accNode v)) { diff --git a/src/Compiler/Driver/ParseAndCheckInputs.fs b/src/Compiler/Driver/ParseAndCheckInputs.fs index 94bbcdee884..a9fc59b66d3 100644 --- a/src/Compiler/Driver/ParseAndCheckInputs.fs +++ b/src/Compiler/Driver/ParseAndCheckInputs.fs @@ -357,9 +357,9 @@ let DeduplicateModuleName (moduleNamesDict: ModuleNamesDict) fileName (qualNameO match moduleNamesDict.TryGetValue qualNameOfFile.Text with | true, paths -> - if paths.ContainsKey path then - paths[path], moduleNamesDict - else + match paths.TryGetValue path with + | true, pathV -> pathV, moduleNamesDict + | false, _ -> let count = paths.Count + 1 let id = qualNameOfFile.Id @@ -1681,7 +1681,7 @@ module private TypeCheckingGraphProcessing = let resultsToAdd = transitiveDeps - |> Array.filter (fun dep -> itemsPresent.Contains dep.Info.Item = false) + |> Array.filter (fun dep -> not (itemsPresent.Contains dep.Info.Item)) |> Array.distinctBy (fun dep -> dep.Info.Item) |> Array.sortWith (fun a b -> // We preserve the order in which items are folded to the state. diff --git a/src/Compiler/Driver/fsc.fs b/src/Compiler/Driver/fsc.fs index e674afa1810..d3bfd2e74cc 100644 --- a/src/Compiler/Driver/fsc.fs +++ b/src/Compiler/Driver/fsc.fs @@ -304,7 +304,7 @@ let ProcessCommandLineFlags (tcConfigB: TcConfigBuilder, lcidFromCodePage, argv) (* step - get dll references *) let dllFiles, sourceFiles = inputFiles - |> List.map (fun p -> FileSystemUtils.trimQuotes p) + |> List.map FileSystemUtils.trimQuotes |> List.partition FileSystemUtils.isDll match dllFiles with diff --git a/src/Compiler/Facilities/CompilerLocation.fs b/src/Compiler/Facilities/CompilerLocation.fs index 9f831346031..fa49445b769 100644 --- a/src/Compiler/Facilities/CompilerLocation.fs +++ b/src/Compiler/Facilities/CompilerLocation.fs @@ -184,7 +184,7 @@ module internal FSharpEnvironment = | None -> () | Some(p: string) -> match Path.GetDirectoryName(p) with - | s when s = "" || s = null || Path.GetFileName(p) = "packages" || s = p -> () + | s when s = "" || isNull s || Path.GetFileName(p) = "packages" || s = p -> () | parentDir -> yield! searchParentDirChain (Some parentDir) assemblyName for p in searchToolPaths path compilerToolPaths do diff --git a/src/Compiler/Facilities/prim-parsing.fs b/src/Compiler/Facilities/prim-parsing.fs index ae75cc7b974..3088a5579ed 100644 --- a/src/Compiler/Facilities/prim-parsing.fs +++ b/src/Compiler/Facilities/prim-parsing.fs @@ -367,7 +367,7 @@ module internal Implementation = let action = let immediateAction = int tables.immediateActions[state] - if not (immediateAction = anyMarker) then + if immediateAction <> anyMarker then // Action has been pre-determined, no need to lookahead // Expecting it to be a Reduce action on a non-fakeStartNonTerminal ? immediateAction diff --git a/src/Compiler/Interactive/fsi.fs b/src/Compiler/Interactive/fsi.fs index c5dee9abe43..4ed7363f6cd 100644 --- a/src/Compiler/Interactive/fsi.fs +++ b/src/Compiler/Interactive/fsi.fs @@ -410,18 +410,19 @@ type ILMultiInMemoryAssemblyEmitEnv /// Map the given ILTypeRef to the appropriate assembly fragment member _.MapTypeRef(tref: ILTypeRef) = - if tref.Scope.IsLocalRef && typeMap.ContainsKey(tref) then - typeMap[tref] |> snd + if tref.Scope.IsLocalRef then + match typeMap.TryGetValue tref with + | true, tmap -> tmap |> snd + | false, _ -> tref else tref /// Map an ILTypeRef built from reflection over loaded assembly fragments back to an ILTypeRef suitable /// to use on the F# compiler logic. member _.ReverseMapTypeRef(tref: ILTypeRef) = - if reverseTypeMap.ContainsKey(tref) then - reverseTypeMap[tref] - else - tref + match reverseTypeMap.TryGetValue tref with + | true, revtype -> revtype + | false, _ -> tref /// Convert an ILTypeRef to a dynamic System.Type given the dynamic emit context member _.LookupTypeRef(tref: ILTypeRef) = convTypeRef tref @@ -595,7 +596,7 @@ type internal FsiValuePrinter(fsi: FsiEvaluationSessionHostConfig, outWriter: Te try let itemLs = unfoldL // the function to layout each object in the unfold - (fun obj -> ienv.GetLayout obj) + ienv.GetLayout // the function to call at each step of the unfold (fun () -> if it.MoveNext() then Some((it.Key, it.Value), ()) else None) () @@ -1533,7 +1534,7 @@ let ConvReflectionTypeToILTypeRef (reflectionTy: Type) = else fullName.Substring(0, index) - let isTop = reflectionTy.DeclaringType = null + let isTop = isNull reflectionTy.DeclaringType if isTop then ILTypeRef.Create(scoref, [], fullName) @@ -1558,7 +1559,7 @@ let rec ConvReflectionTypeToILType (reflectionTy: Type) = if ctors.Length = 1 - && ctors[0].GetCustomAttribute() <> null + && (not (isNull (ctors[0].GetCustomAttribute()))) && not ctors[0].IsPublic && IsCompilerGeneratedName reflectionTy.Name then @@ -1583,8 +1584,7 @@ let rec ConvReflectionTypeToILType (reflectionTy: Type) = let genericArgs = reflectionTy.GenericTypeArguments - |> Seq.map ConvReflectionTypeToILType - |> Seq.map List.head + |> Seq.map (ConvReflectionTypeToILType >> List.head) |> List.ofSeq let boxity = diff --git a/src/Compiler/Optimize/InnerLambdasToTopLevelFuncs.fs b/src/Compiler/Optimize/InnerLambdasToTopLevelFuncs.fs index ed2097236fb..37b3f26c429 100644 --- a/src/Compiler/Optimize/InnerLambdasToTopLevelFuncs.fs +++ b/src/Compiler/Optimize/InnerLambdasToTopLevelFuncs.fs @@ -81,7 +81,7 @@ let showTyparSet tps = showL (commaListL (List.map typarL (Zset.elements tps))) // should never be needed let isDelayedRepr (f: Val) e = let _tps, vss, _b, _rty = stripTopLambda (e, f.Type) - List.length vss>0 + not(List.isEmpty vss) // REVIEW: these should just be replaced by direct calls to mkLocal, mkCompGenLocal etc. @@ -520,7 +520,7 @@ module Pass2_DetermineReqdItems = // occurrences contribute to env let reqdVals0 = frees.FreeLocals |> Zset.elements // tlrBs are not reqdVals0 for themselves - let reqdVals0 = reqdVals0 |> List.filter (fun gv -> not (fclass.Contains gv)) + let reqdVals0 = reqdVals0 |> List.filter (fclass.Contains >> not) let reqdVals0 = reqdVals0 |> Zset.ofList valOrder // collect into env over bodies let z = PushFrame fclass (reqdTypars0, reqdVals0,m) z @@ -817,7 +817,7 @@ let MakeSimpleArityInfo tps n = ValReprInfo (ValReprInfo.InferTyparInfo tps, Lis let CreateNewValuesForTLR g tlrS arityM fclassM envPackM = let createFHat (f: Val) = - let wf = Zmap.force f arityM ("createFHat - wf", (fun v -> showL (valL v))) + let wf = Zmap.force f arityM ("createFHat - wf", (valL >> showL)) let fc = Zmap.force f fclassM ("createFHat - fc", nameOfVal) let envp = Zmap.force fc envPackM ("CreateNewValuesForTLR - envp", string) let name = f.LogicalName (* + "_TLR_" + string wf *) @@ -1096,7 +1096,7 @@ module Pass4_RewriteAssembly = | Expr.Let _ | Expr.DebugPoint _ | Expr.Sequential _ -> - TransLinearExpr penv z expr (fun res -> res) + TransLinearExpr penv z expr id // app - call sites may require z. // - match the app (collapsing reclinks and type instances). diff --git a/src/Compiler/Optimize/LowerStateMachines.fs b/src/Compiler/Optimize/LowerStateMachines.fs index 5a6fadcfd6d..7c4835b3460 100644 --- a/src/Compiler/Optimize/LowerStateMachines.fs +++ b/src/Compiler/Optimize/LowerStateMachines.fs @@ -39,7 +39,7 @@ type StateMachineConversionFirstPhaseResult = } #if DEBUG -let sm_verbose = try System.Environment.GetEnvironmentVariable("FSharp_StateMachineVerbose") <> null with _ -> false +let sm_verbose = try not (isNull(System.Environment.GetEnvironmentVariable "FSharp_StateMachineVerbose")) with _ -> false #else let sm_verbose = false #endif diff --git a/src/Compiler/Optimize/Optimizer.fs b/src/Compiler/Optimize/Optimizer.fs index 7edabc43fba..a1e01d4a58d 100644 --- a/src/Compiler/Optimize/Optimizer.fs +++ b/src/Compiler/Optimize/Optimizer.fs @@ -2477,7 +2477,7 @@ and MakeOptimizedSystemStringConcatCall cenv env m args = and optimizeArgs args accArgs = (args, accArgs) - ||> List.foldBack (fun arg accArgs -> optimizeArg arg accArgs) + ||> List.foldBack (optimizeArg) let args = optimizeArgs args [] @@ -3353,10 +3353,10 @@ and TryInlineApplication cenv env finfo (tyargs: TType list, args: Expr list, m) not (Zset.contains lambdaId env.dontInline) && (// Check the number of argument groups is enough to saturate the lambdas of the target. (if tyargs |> List.exists (fun t -> match t with TType_measure _ -> false | _ -> true) then 1 else 0) + args.Length = arities && - (if size > cenv.settings.lambdaInlineThreshold + args.Length then - // Not inlining lambda near, size too big - false - else true))) -> + if size <= cenv.settings.lambdaInlineThreshold + args.Length then true + // Not inlining lambda near, size too big: + else false + )) -> let isBaseCall = not (List.isEmpty args) && match args[0] with @@ -4381,14 +4381,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 |> ConstValue | 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)) + | 2 -> u_tup2 u_vref loop st |> ValValue + | 3 -> u_array loop st |> TupleValue + | 4 -> u_tup2 u_ucref (u_array loop) st |> UnionCaseValue | 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)) + | 6 -> u_tup2 u_int u_expr st |> ConstExprValue + | 7 -> u_tup2 u_tcref (u_array loop) st |> RecdValue | _ -> failwith "loop" // calc size of unpicked ExprValueInfo MakeSizedValueInfo (loop st) diff --git a/src/Compiler/Service/ExternalSymbol.fs b/src/Compiler/Service/ExternalSymbol.fs index 7314fcac488..0be071f4fec 100644 --- a/src/Compiler/Service/ExternalSymbol.fs +++ b/src/Compiler/Service/ExternalSymbol.fs @@ -57,7 +57,7 @@ module FindDeclExternalType = | ILType.TypeVar ordinal -> typeVarNames |> Array.tryItem (int ordinal) - |> Option.map (fun typeVarName -> FindDeclExternalType.TypeVar typeVarName) + |> Option.map FindDeclExternalType.TypeVar | _ -> None [] diff --git a/src/Compiler/Service/ItemKey.fs b/src/Compiler/Service/ItemKey.fs index a2027491d32..daf6a28f544 100644 --- a/src/Compiler/Service/ItemKey.fs +++ b/src/Compiler/Service/ItemKey.fs @@ -271,7 +271,7 @@ and [] ItemKeyStoreBuilder(tcGlobals: TcGlobals) = debug.WriteEntityRef eref writeString ItemKeyTags.entityRef writeString eref.CompiledName - eref.CompilationPath.MangledPath |> List.iter (fun str -> writeString str) + eref.CompilationPath.MangledPath |> List.iter writeString let rec writeILType (ilTy: ILType) = debug.WriteILType ilTy @@ -312,7 +312,7 @@ and [] ItemKeyStoreBuilder(tcGlobals: TcGlobals) = writeChar '>' | ILType.FunctionPointer mref -> - mref.ArgTypes |> List.iter (fun x -> writeILType x) + mref.ArgTypes |> List.iter writeILType writeILType mref.ReturnType let rec writeType isStandalone (ty: TType) = diff --git a/src/Compiler/Service/SemanticClassification.fs b/src/Compiler/Service/SemanticClassification.fs index 5461e036124..3697d781373 100644 --- a/src/Compiler/Service/SemanticClassification.fs +++ b/src/Compiler/Service/SemanticClassification.fs @@ -197,8 +197,7 @@ module TcResolutionsExtensions = sResolutions.CapturedNameResolutions.ToArray() |> Array.filter (fun cnr -> rangeContainsPos range cnr.Range.Start || rangeContainsPos range cnr.Range.End) |> Array.groupBy (fun cnr -> cnr.Range) - |> Array.map (fun (_, cnrs) -> takeCustomBuilder cnrs) - |> Array.concat + |> Array.collect (fun (_, cnrs) -> takeCustomBuilder cnrs) | None -> sResolutions.CapturedNameResolutions.ToArray() let duplicates = HashSet(comparer) diff --git a/src/Compiler/Service/ServiceDeclarationLists.fs b/src/Compiler/Service/ServiceDeclarationLists.fs index 1251432d51c..1b955ead042 100644 --- a/src/Compiler/Service/ServiceDeclarationLists.fs +++ b/src/Compiler/Service/ServiceDeclarationLists.fs @@ -530,7 +530,7 @@ module DeclarationListHelpers = let FormatStructuredDescriptionOfItem isDecl infoReader ad m denv item symbol width = DiagnosticsScope.Protect m (fun () -> FormatItemDescriptionToToolTipElement isDecl infoReader ad m denv item symbol width) - (fun err -> ToolTipElement.CompositionError err) + ToolTipElement.CompositionError /// Represents one parameter for one method (or other item) in a group. [] @@ -739,8 +739,7 @@ module internal DescriptionListsImpl = // This is good enough as we don't provide ways to display info for the second curried argument let firstCurriedParamDatas = firstCurriedArgInfo - |> List.map ParamNameAndType.FromArgInfo - |> List.map (fun (ParamNameAndType(nmOpt, pty)) -> ParamData(false, false, false, NotOptional, NoCallerInfo, nmOpt, ReflectedArgInfo.None, pty)) + |> List.map (ParamNameAndType.FromArgInfo >> fun (ParamNameAndType(nmOpt, pty)) -> ParamData(false, false, false, NotOptional, NoCallerInfo, nmOpt, ReflectedArgInfo.None, pty)) // Adjust the return type so it only strips the first argument let curriedRetTy = diff --git a/src/Compiler/Service/ServiceParamInfoLocations.fs b/src/Compiler/Service/ServiceParamInfoLocations.fs index 15a2aad0860..129a40b93f6 100755 --- a/src/Compiler/Service/ServiceParamInfoLocations.fs +++ b/src/Compiler/Service/ServiceParamInfoLocations.fs @@ -177,7 +177,7 @@ module internal ParameterLocationsImpl = handleSingleArg traverseSynExpr (pos, synExpr, parenRange, rpRangeOpt) // dig into multiple parens - | SynExprParen(SynExprParen(_, _, _, _) as synExpr, _, _, _parenRange) -> + | SynExprParen(SynExprParen _ as synExpr, _, _, _parenRange) -> let r, _cacheOpt = searchSynArgExpr traverseSynExpr pos synExpr r, None diff --git a/src/Compiler/Symbols/Exprs.fs b/src/Compiler/Symbols/Exprs.fs index eabc11f3410..8e5f74e1996 100644 --- a/src/Compiler/Symbols/Exprs.fs +++ b/src/Compiler/Symbols/Exprs.fs @@ -925,11 +925,12 @@ module FSharpExprConvert = let witnessInfo = traitInfo.GetWitnessInfo() let env = { env with suppressWitnesses = true } // First check if this is a witness in ReflectedDefinition code - if env.witnessesInScope.ContainsKey witnessInfo then - let witnessArgIdx = env.witnessesInScope[witnessInfo] + match env.witnessesInScope.TryGetValue witnessInfo with + | true, scopewitnessinfo -> + let witnessArgIdx = scopewitnessinfo E.WitnessArg(witnessArgIdx) // Otherwise it is a witness in a quotation literal - else + | false, _ -> //failwith "witness not found" E.WitnessArg(-1) @@ -1159,7 +1160,7 @@ module FSharpExprConvert = let ty = if isStatic then ty else mkFunTy g enclosingTy ty mkForallTyIfNeeded (typars1 @ typars2) ty - let argCount = List.sum (List.map List.length argTys) + (if isStatic then 0 else 1) + let argCount = (List.sumBy List.length argTys) + (if isStatic then 0 else 1) let key = ValLinkageFullKey({ MemberParentMangledName=memberParentName; MemberIsOverride=false; LogicalName=logicalName; TotalArgCount= argCount }, Some linkageType) let (PubPath p) = tcref.PublicPath.Value diff --git a/src/Compiler/Symbols/SymbolHelpers.fs b/src/Compiler/Symbols/SymbolHelpers.fs index 6e4dbc284fe..f3ad450a461 100644 --- a/src/Compiler/Symbols/SymbolHelpers.fs +++ b/src/Compiler/Symbols/SymbolHelpers.fs @@ -453,7 +453,7 @@ module internal SymbolHelpers = | Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref1, n1))), Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref2, n2))) -> (tyconRefEq g tcref1 tcref2) && (n1 = n2) // there is no direct function as in the previous case | Item.Property(info = pi1s), Item.Property(info = pi2s) -> - (pi1s, pi2s) ||> List.forall2 (fun pi1 pi2 -> PropInfo.PropInfosUseIdenticalDefinitions pi1 pi2) + (pi1s, pi2s) ||> List.forall2 PropInfo.PropInfosUseIdenticalDefinitions | Item.Event evt1, Item.Event evt2 -> EventInfo.EventInfosUseIdenticalDefinitions evt1 evt2 | Item.AnonRecdField(anon1, _, i1, _), Item.AnonRecdField(anon2, _, i2, _) -> @@ -462,7 +462,7 @@ module internal SymbolHelpers = (traitInfo1.MemberLogicalName = traitInfo2.MemberLogicalName) | Item.CtorGroup(_, meths1), Item.CtorGroup(_, meths2) -> (meths1, meths2) - ||> List.forall2 (fun minfo1 minfo2 -> MethInfo.MethInfosUseIdenticalDefinitions minfo1 minfo2) + ||> List.forall2 MethInfo.MethInfosUseIdenticalDefinitions | Item.UnqualifiedType tcrefs1, Item.UnqualifiedType tcrefs2 -> (tcrefs1, tcrefs2) ||> List.forall2 (fun tcref1 tcref2 -> tyconRefEq g tcref1 tcref2) diff --git a/src/Compiler/Symbols/Symbols.fs b/src/Compiler/Symbols/Symbols.fs index e59caf2c6d4..ae8ce6b2500 100644 --- a/src/Compiler/Symbols/Symbols.fs +++ b/src/Compiler/Symbols/Symbols.fs @@ -204,7 +204,7 @@ module Impl = type FSharpDisplayContext(denv: TcGlobals -> DisplayEnv) = member _.Contents g = denv g - static member Empty = FSharpDisplayContext(fun g -> DisplayEnv.Empty g) + static member Empty = FSharpDisplayContext DisplayEnv.Empty member _.WithShortTypeNames shortNames = FSharpDisplayContext(fun g -> { denv g with shortTypeNames = shortNames }) @@ -1670,7 +1670,7 @@ type FSharpMemberOrFunctionOrValue(cenv, d:FSharpMemberOrValData, item) = let methods = if matchParameterNumber then methodInfos - |> List.filter (fun methodInfo -> not (methodInfo.NumArgs = m.NumArgs) ) + |> List.filter (fun methodInfo -> methodInfo.NumArgs <> m.NumArgs ) else methodInfos methods |> List.map (fun mi -> diff --git a/src/Compiler/SyntaxTree/SyntaxTreeOps.fs b/src/Compiler/SyntaxTree/SyntaxTreeOps.fs index a97220a94dd..66387dec053 100644 --- a/src/Compiler/SyntaxTree/SyntaxTreeOps.fs +++ b/src/Compiler/SyntaxTree/SyntaxTreeOps.fs @@ -69,7 +69,7 @@ let rec pushUnaryArg expr arg = SynExpr.App( ExprAtomicFlag.Atomic, infix, - SynExpr.LongIdent(false, SynLongIdent(arg :: ident :: [], [ ident.idRange ], [ None ]), None, ident.idRange), + SynExpr.LongIdent(false, SynLongIdent(arg :: [ ident ], [ ident.idRange ], [ None ]), None, ident.idRange), x1, m1 ) @@ -91,7 +91,7 @@ let rec pushUnaryArg expr arg = SynExpr.App(ExprAtomicFlag.Atomic, infix, SynExpr.DotGet((pushUnaryArg synExpr arg), rangeOfDot, synLongIdent, range), x1, m1) | SynExpr.App(ExprAtomicFlag.Atomic, infix, innerExpr, x1, m1) -> SynExpr.App(ExprAtomicFlag.Atomic, infix, pushUnaryArg innerExpr arg, x1, m1) - | SynExpr.Ident ident -> SynExpr.LongIdent(false, SynLongIdent(arg :: ident :: [], [ ident.idRange ], [ None ]), None, ident.idRange) + | SynExpr.Ident ident -> SynExpr.LongIdent(false, SynLongIdent(arg :: [ ident ], [ ident.idRange ], [ None ]), None, ident.idRange) | SynExpr.LongIdent(isOptional, SynLongIdent(id, dotRanges, trivia), altNameRefCell, range) -> SynExpr.LongIdent(isOptional, SynLongIdent(arg :: id, dotRanges, trivia), altNameRefCell, range) | SynExpr.DotGet(synExpr, rangeOfDot, synLongIdent, range) -> SynExpr.DotGet(pushUnaryArg synExpr arg, rangeOfDot, synLongIdent, range) @@ -524,7 +524,7 @@ let mkAttributeList attrs range : SynAttributeList list = [ { Attributes = attrs; Range = range } ] let ConcatAttributesLists (attrsLists: SynAttributeList list) = - attrsLists |> List.map (fun x -> x.Attributes) |> List.concat + attrsLists |> List.collect (fun x -> x.Attributes) let (|Attributes|) synAttributes = ConcatAttributesLists synAttributes diff --git a/src/Compiler/SyntaxTree/XmlDoc.fs b/src/Compiler/SyntaxTree/XmlDoc.fs index 6d933deb3e0..0bfb9c09f48 100644 --- a/src/Compiler/SyntaxTree/XmlDoc.fs +++ b/src/Compiler/SyntaxTree/XmlDoc.fs @@ -77,6 +77,7 @@ type XmlDoc(unprocessedLines: string[], range: range) = match paramNamesOpt with | None -> () | Some paramNames -> + for p in xml.Descendants(XName.op_Implicit "param") do match p.Attribute(XName.op_Implicit "name") with | null -> warning (Error(FSComp.SR.xmlDocMissingParameterName (), doc.Range)) @@ -95,6 +96,7 @@ type XmlDoc(unprocessedLines: string[], range: range) = ] if paramsWithDocs.Length > 0 then + for p in paramNames do if not (paramsWithDocs |> List.contains p) then warning (Error(FSComp.SR.xmlDocMissingParameter (p), doc.Range)) diff --git a/src/Compiler/TypedTree/TcGlobals.fs b/src/Compiler/TypedTree/TcGlobals.fs index 301096d092c..e754a5ad4ae 100755 --- a/src/Compiler/TypedTree/TcGlobals.fs +++ b/src/Compiler/TypedTree/TcGlobals.fs @@ -459,7 +459,7 @@ type TcGlobals( let makeIntrinsicValRefGeneral isKnown (enclosingEntity, logicalName, memberParentName, compiledNameOpt, typars, (argTys, retTy)) = let ty = mkForallTyIfNeeded typars (mkIteratedFunTy (List.map mkSmallRefTupledTy argTys) retTy) let isMember = Option.isSome memberParentName - let argCount = if isMember then List.sum (List.map List.length argTys) else 0 + let argCount = if isMember then List.sumBy List.length argTys else 0 let linkageType = if isMember then Some ty else None let key = ValLinkageFullKey({ MemberParentMangledName=memberParentName; MemberIsOverride=false; LogicalName=logicalName; TotalArgCount= argCount }, linkageType) let vref = IntrinsicValRef(enclosingEntity, logicalName, isMember, ty, key) @@ -1058,7 +1058,7 @@ type TcGlobals( member _.embeddedTypeDefs = embeddedILTypeDefs.Values |> Seq.toList member _.tryRemoveEmbeddedILTypeDefs () = [ - for key in embeddedILTypeDefs.Keys.OrderBy(fun k -> k) do + for key in embeddedILTypeDefs.Keys.OrderBy id do match (embeddedILTypeDefs.TryRemove(key)) with | true, ilTypeDef -> yield ilTypeDef | false, _ -> () diff --git a/src/Compiler/TypedTree/TypeProviders.fs b/src/Compiler/TypedTree/TypeProviders.fs index e16bad8ac94..9eb76091897 100644 --- a/src/Compiler/TypedTree/TypeProviders.fs +++ b/src/Compiler/TypedTree/TypeProviders.fs @@ -121,7 +121,7 @@ let CreateTypeProvider ( let getReferencedAssemblies () = resolutionEnvironment.GetReferencedAssemblies() |> Array.distinct - if typeProviderImplementationType.GetConstructor([| typeof |]) <> null then + if not(isNull(typeProviderImplementationType.GetConstructor([| typeof |]))) then // Create the TypeProviderConfig to pass to the type provider constructor let e = @@ -146,7 +146,7 @@ let CreateTypeProvider ( #endif protect (fun () -> Activator.CreateInstance(typeProviderImplementationType, [| box e|]) :?> ITypeProvider ) - elif typeProviderImplementationType.GetConstructor [| |] <> null then + elif not(isNull(typeProviderImplementationType.GetConstructor [| |])) then protect (fun () -> Activator.CreateInstance typeProviderImplementationType :?> ITypeProvider ) else diff --git a/src/Compiler/TypedTree/TypedTree.fs b/src/Compiler/TypedTree/TypedTree.fs index 3caccb5597d..30fd48aecd7 100644 --- a/src/Compiler/TypedTree/TypedTree.fs +++ b/src/Compiler/TypedTree/TypedTree.fs @@ -2897,7 +2897,7 @@ type Val = /// Indicates that this value's getter or setter are generated by the compiler member x.GetterOrSetterIsCompilerGenerated = - x.MemberInfo |> Option.exists (fun m -> m.MemberFlags.GetterOrSetterIsCompilerGenerated = true) + x.MemberInfo |> Option.exists (fun m -> m.MemberFlags.GetterOrSetterIsCompilerGenerated) /// Get the declared attributes for the value member x.Attribs = diff --git a/src/Compiler/TypedTree/TypedTreeOps.fs b/src/Compiler/TypedTree/TypedTreeOps.fs index 26630f4fa82..a3b987f46f6 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.fs +++ b/src/Compiler/TypedTree/TypedTreeOps.fs @@ -53,6 +53,10 @@ type TyparMap<'T> = member tm.ContainsKey (tp: Typar) = let (TPMap m) = tm m.ContainsKey(tp.Stamp) + + member tm.TryGetValue (tp: Typar) = + let (TPMap m) = tm + m.TryGetValue(tp.Stamp) member tm.TryFind (tp: Typar) = let (TPMap m) = tm @@ -72,6 +76,7 @@ type TyconRefMap<'T>(imap: StampMap<'T>) = member _.Add (tcref: TyconRef) x = TyconRefMap (imap.Add (tcref.Stamp, x)) member _.Remove (tcref: TyconRef) = TyconRefMap (imap.Remove tcref.Stamp) member _.IsEmpty = imap.IsEmpty + member _.TryGetValue (tcref: TyconRef) = imap.TryGetValue tcref.Stamp 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) @@ -1076,8 +1081,8 @@ and structnessAEquiv un1 un2 = and measureAEquiv g aenv un1 un2 = let vars1 = ListMeasureVarOccs un1 - let trans tp1 = if aenv.EquivTypars.ContainsKey tp1 then destAnyParTy g aenv.EquivTypars[tp1] else tp1 - let remapTyconRef tcref = if aenv.EquivTycons.ContainsKey tcref then aenv.EquivTycons[tcref] else tcref + let trans tp1 = match aenv.EquivTypars.TryGetValue tp1 with true, etv -> destAnyParTy g etv | false, _ -> tp1 + let remapTyconRef tcref = match aenv.EquivTycons.TryGetValue tcref with true, tval -> tval | false, _ -> tcref let vars1R = List.map trans vars1 let vars2 = ListSet.subtract typarEq (ListMeasureVarOccs un2) vars1R let cons1 = ListMeasureConOccsAfterRemapping g remapTyconRef un1 @@ -2932,7 +2937,7 @@ module PrettyTypes = let tys, cxs = (PrettifyThings g List.fold List.map (x |> List.map snd)) List.zip (List.map fst x) tys, cxs - let PrettifyCurriedTypes g x = PrettifyThings g (fun f -> List.fold (List.fold f)) List.mapSquared x + let PrettifyCurriedTypes g x = PrettifyThings g (List.fold >> List.fold) List.mapSquared x let PrettifyCurriedSigTypes g x = PrettifyThings g (fun f -> foldPair (List.fold (List.fold f), f)) (fun f -> mapPair (List.mapSquared f, f)) x // Badly formed code may instantiate rigid declared typars to types. @@ -2987,7 +2992,7 @@ module PrettyTypes = let PrettifyInst g x = PrettifyThings g - (fun f -> foldTyparInst f) + (foldTyparInst) (fun f -> mapTyparInst g f) x @@ -4934,8 +4939,7 @@ let IsHidden setF accessF remapF = Zset.contains x (setF mhi) || // Recurse... check rest (remapF rpi x)) - fun mrmi x -> - check mrmi x + check let IsHiddenTycon mrmi x = IsHidden (fun mhi -> mhi.HiddenTycons) (fun tc -> tc.Accessibility) (fun rpi x -> (remapTyconRef rpi.tyconRefRemap (mkLocalTyconRef x)).Deref) mrmi x @@ -5177,7 +5181,7 @@ and accFreeInInterfaceImpl opts (ty, overrides) acc = and accFreeInExpr (opts: FreeVarOptions) x acc = match x with - | Expr.Let _ -> accFreeInExprLinear opts x acc (fun e -> e) + | Expr.Let _ -> accFreeInExprLinear opts x acc id | _ -> accFreeInExprNonLinear opts x acc and accFreeInExprLinear (opts: FreeVarOptions) x acc contf = @@ -5771,7 +5775,7 @@ and remapExprImpl (ctxt: RemapContext) (compgen: ValCopyFlag) (tmenv: Remap) exp | Expr.Sequential _ | Expr.Let _ | Expr.DebugPoint _ -> - remapLinearExpr ctxt compgen tmenv expr (fun x -> x) + remapLinearExpr ctxt compgen tmenv expr id // Binding constructs - see also dtrees below | Expr.Lambda (_, ctorThisValOpt, baseValOpt, vs, b, m, bodyTy) -> @@ -7069,7 +7073,7 @@ let rec mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress let mkExprAddrOfExpr g mustTakeAddress useReadonlyForGenericArrayAddress mut e addrExprVal m = let optBind, addre, readonly, writeonly = mkExprAddrOfExprAux g mustTakeAddress useReadonlyForGenericArrayAddress mut e addrExprVal m match optBind with - | None -> (fun x -> x), addre, readonly, writeonly + | None -> id, addre, readonly, writeonly | Some (tmp, rval) -> (fun x -> mkCompGenLet m tmp rval x), addre, readonly, writeonly let mkTupleFieldGet g (tupInfo, e, tinst, i, m) = @@ -7978,7 +7982,7 @@ let tref_SourceConstructFlags (g: TcGlobals) = mkILTyRef (g.fslibCcu.ILScopeRef, let mkCompilationMappingAttrPrim (g: TcGlobals) k nums = mkILCustomAttribute (tref_CompilationMappingAttr g, ((mkILNonGenericValueTy (tref_SourceConstructFlags g)) :: (nums |> List.map (fun _ -> g.ilg.typ_Int32))), - ((k :: nums) |> List.map (fun n -> ILAttribElem.Int32 n)), + ((k :: nums) |> List.map (ILAttribElem.Int32)), []) let mkCompilationMappingAttr g kind = mkCompilationMappingAttrPrim g kind [] @@ -7989,7 +7993,7 @@ let mkCompilationMappingAttrWithVariantNumAndSeqNum g kind varNum seqNum = mkCom let mkCompilationArgumentCountsAttr (g: TcGlobals) nums = mkILCustomAttribute (tref_CompilationArgumentCountsAttr g, [ mkILArr1DTy g.ilg.typ_Int32 ], - [ILAttribElem.Array (g.ilg.typ_Int32, List.map (fun n -> ILAttribElem.Int32 n) nums)], + [ILAttribElem.Array (g.ilg.typ_Int32, List.map (ILAttribElem.Int32) nums)], []) let mkCompilationSourceNameAttr (g: TcGlobals) n = @@ -8446,7 +8450,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex binderBuilder, expr else if typeEquiv g (mkRefTupledTy g actualTys) argExprTy then - (fun tm -> tm), argExpr + id, argExpr else let detupledArgs, argTys = @@ -8464,7 +8468,7 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex // let f (x, y) = 1 // and we're not building lambdas, just coerce the arguments in place if detupledArgs.Length = actualTys.Length then - (fun tm -> tm), CoerceDetupled argTys detupledArgs actualTys + id, CoerceDetupled argTys detupledArgs actualTys else // In this case there is a tuple mismatch. // f p @@ -8544,13 +8548,13 @@ let AdjustPossibleSubsumptionExpr g (expr: Expr) (suppliedArgs: Expr list) : (Ex match suppliedArg with | Some arg -> let binderBuilder, inpsAsActualArg = CoerceTupled niceNames arg actualArgTys - let lambdaBuilder = (fun tm -> tm) + let lambdaBuilder = id lambdaBuilder, binderBuilder, inpsAsActualArg | None -> 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) + let binderBuilder = id lambdaBuilder, binderBuilder, inpsAsActualArg) |> List.unzip3 @@ -8950,7 +8954,7 @@ let rec TypeHasDefaultValue g m ty = // Note this includes fields implied by the use of the implicit class construction syntax tcref.AllInstanceFieldsAsList // We can ignore fields with the DefaultValue(false) attribute - |> List.filter (fun fld -> not (TryFindFSharpBoolAttribute g g.attrib_DefaultValueAttribute fld.FieldAttribs = Some false)) + |> List.filter (fun fld -> TryFindFSharpBoolAttribute g g.attrib_DefaultValueAttribute fld.FieldAttribs <> Some false) flds |> List.forall (actualTyOfRecdField (mkTyconRefInst tcref tinst) >> TypeHasDefaultValue g m) @@ -9261,7 +9265,7 @@ and RewriteExpr env expr = | Expr.Let _ | Expr.Sequential _ | Expr.DebugPoint _ -> - rewriteLinearExpr env expr (fun e -> e) + rewriteLinearExpr env expr id | _ -> let expr = match preRewriteExpr env expr with diff --git a/src/Compiler/TypedTree/TypedTreePickle.fs b/src/Compiler/TypedTree/TypedTreePickle.fs index 5750c9012de..b5b738f8ada 100644 --- a/src/Compiler/TypedTree/TypedTreePickle.fs +++ b/src/Compiler/TypedTree/TypedTreePickle.fs @@ -560,7 +560,7 @@ let u_list_revi f st = yield f st (n-1-i) ] -let u_wrap (f: 'U -> 'T) (u : 'U unpickler) : 'T unpickler = (fun st -> f (u st)) +let u_wrap (f: 'U -> 'T) (u : 'U unpickler) : 'T unpickler = (u >> f) let u_option f st = let tag = u_byte st @@ -950,7 +950,7 @@ let u_ILHasThis st = let u_ILCallConv st = let a, b = u_tup2 u_ILHasThis u_ILBasicCallConv st in Callconv(a, b) let u_ILTypeRef st = let a, b, c = u_tup3 u_ILScopeRef u_strings u_string st in ILTypeRef.Create(a, b, c) -let u_ILArrayShape = u_wrap (fun x -> ILArrayShape x) (u_list (u_tup2 (u_option u_int32) (u_option u_int32))) +let u_ILArrayShape = u_wrap (ILArrayShape) (u_list (u_tup2 (u_option u_int32) (u_option u_int32))) let rec u_ILType st = @@ -1155,30 +1155,30 @@ let decoders = itag_call, u_ILMethodSpec >> (fun a -> I_call (Normalcall, a, None)) itag_callvirt, u_ILMethodSpec >> (fun a -> I_callvirt (Normalcall, a, None)) itag_ldvirtftn, u_ILMethodSpec >> I_ldvirtftn - itag_conv, u_ILBasicType >> (fun a -> (AI_conv a)) - itag_conv_ovf, u_ILBasicType >> (fun a -> (AI_conv_ovf a)) - itag_conv_ovf_un, u_ILBasicType >> (fun a -> (AI_conv_ovf_un a)) + itag_conv, u_ILBasicType >> AI_conv + itag_conv_ovf, u_ILBasicType >> AI_conv_ovf + itag_conv_ovf_un, u_ILBasicType >> AI_conv_ovf_un itag_ldfld, u_tup2 u_ILVolatility u_ILFieldSpec >> (fun (b, c) -> I_ldfld (Aligned, b, c)) itag_ldflda, u_ILFieldSpec >> I_ldflda - itag_ldsfld, u_tup2 u_ILVolatility u_ILFieldSpec >> (fun (a, b) -> I_ldsfld (a, b)) + itag_ldsfld, u_tup2 u_ILVolatility u_ILFieldSpec >> I_ldsfld itag_ldsflda, u_ILFieldSpec >> I_ldsflda itag_stfld, u_tup2 u_ILVolatility u_ILFieldSpec >> (fun (b, c) -> I_stfld (Aligned, b, c)) - itag_stsfld, u_tup2 u_ILVolatility u_ILFieldSpec >> (fun (a, b) -> I_stsfld (a, b)) - itag_ldtoken, u_ILType >> (fun a -> I_ldtoken (ILToken.ILType a)) + itag_stsfld, u_tup2 u_ILVolatility u_ILFieldSpec >> I_stsfld + itag_ldtoken, u_ILType >> (ILToken.ILType >> I_ldtoken) itag_ldstr, u_string >> I_ldstr itag_box, u_ILType >> I_box itag_unbox, u_ILType >> I_unbox itag_unbox_any, u_ILType >> I_unbox_any - itag_newarr, u_tup2 u_ILArrayShape u_ILType >> (fun (a, b) -> I_newarr(a, b)) - itag_stelem_any, u_tup2 u_ILArrayShape u_ILType >> (fun (a, b) -> I_stelem_any(a, b)) - itag_ldelem_any, u_tup2 u_ILArrayShape u_ILType >> (fun (a, b) -> I_ldelem_any(a, b)) + itag_newarr, u_tup2 u_ILArrayShape u_ILType >> I_newarr + itag_stelem_any, u_tup2 u_ILArrayShape u_ILType >> I_stelem_any + itag_ldelem_any, u_tup2 u_ILArrayShape u_ILType >> I_ldelem_any itag_ldelema, u_tup3 u_ILReadonly u_ILArrayShape u_ILType >> (fun (a, b, c) -> I_ldelema(a, false, b, c)) itag_castclass, u_ILType >> I_castclass itag_isinst, u_ILType >> I_isinst itag_ldobj, u_ILType >> (fun c -> I_ldobj (Aligned, Nonvolatile, c)) itag_stobj, u_ILType >> (fun c -> I_stobj (Aligned, Nonvolatile, c)) itag_sizeof, u_ILType >> I_sizeof - itag_ldlen_multi, u_tup2 u_int32 u_int32 >> (fun (a, b) -> EI_ldlen_multi (a, b)) + itag_ldlen_multi, u_tup2 u_int32 u_int32 >> EI_ldlen_multi itag_ilzero, u_ILType >> EI_ilzero itag_ilzero, u_ILType >> EI_ilzero itag_initobj, u_ILType >> I_initobj @@ -1356,8 +1356,8 @@ let u_nonlocal_val_ref st : NonLocalValOrMemberRef = let u_vref st = let tag = u_byte st match tag with - | 0 -> u_local_item_ref st.ivals st |> (fun x -> VRefLocal x) - | 1 -> u_nonlocal_val_ref st |> (fun x -> VRefNonLocal x) + | 0 -> u_local_item_ref st.ivals st |> VRefLocal + | 1 -> u_nonlocal_val_ref st |> VRefNonLocal | _ -> ufailwith st "u_item_ref" let u_vrefs = u_list u_vref @@ -2425,7 +2425,7 @@ and u_const st = | 14 -> u_string st |> Const.String | 15 -> Const.Unit | 16 -> Const.Zero - | 17 -> u_array u_int32 st |> (fun bits -> Const.Decimal (System.Decimal bits)) + | 17 -> u_array u_int32 st |> (System.Decimal >> Const.Decimal) | _ -> ufailwith st "u_const" diff --git a/src/Compiler/TypedTree/tainted.fs b/src/Compiler/TypedTree/tainted.fs index 0eb274fa48b..f586f99a3cd 100644 --- a/src/Compiler/TypedTree/tainted.fs +++ b/src/Compiler/TypedTree/tainted.fs @@ -171,7 +171,7 @@ module internal Tainted = let EqTainted (t1:Tainted<'T>) (t2:Tainted<'T>) = t1.PUntaintNoFailure(fun t1 -> t1 === t2.AccessObjectDirectly) - let GetHashCodeTainted (t:Tainted<'T>) = t.PUntaintNoFailure(fun t -> hash t) + let GetHashCodeTainted (t:Tainted<'T>) = t.PUntaintNoFailure hash #endif diff --git a/src/Compiler/Utilities/Activity.fs b/src/Compiler/Utilities/Activity.fs index aed7b3908d8..79697eae494 100644 --- a/src/Compiler/Utilities/Activity.fs +++ b/src/Compiler/Utilities/Activity.fs @@ -84,11 +84,11 @@ module internal Activity = activity.Start() - let startNoTags (name: string) : IDisposable = activitySource.StartActivity(name) + let startNoTags (name: string) : IDisposable = activitySource.StartActivity name let addEvent name = - if Activity.Current <> null && Activity.Current.Source = activitySource then - Activity.Current.AddEvent(ActivityEvent(name)) |> ignore + if (not (isNull Activity.Current)) && Activity.Current.Source = activitySource then + Activity.Current.AddEvent(ActivityEvent name) |> ignore module Profiling = @@ -214,7 +214,7 @@ module internal Activity = appendWithLeadingComma (a.RootId) Tags.AllKnownTags - |> Array.iter (fun t -> a.GetTagItem(t) |> escapeStringForCsv |> appendWithLeadingComma) + |> Array.iter (a.GetTagItem >> escapeStringForCsv >> appendWithLeadingComma) sb.ToString() diff --git a/src/Compiler/Utilities/Cancellable.fs b/src/Compiler/Utilities/Cancellable.fs index 4c91929cdad..59e7def4c10 100644 --- a/src/Compiler/Utilities/Cancellable.fs +++ b/src/Compiler/Utilities/Cancellable.fs @@ -98,8 +98,7 @@ module Cancellable = | ValueOrCancelled.Cancelled ce -> ccont ce) } - let token () = - Cancellable(fun ct -> ValueOrCancelled.Value ct) + let token () = Cancellable(ValueOrCancelled.Value) type CancellableBuilder() = diff --git a/src/Compiler/Utilities/XmlAdapters.fs b/src/Compiler/Utilities/XmlAdapters.fs index f99853d61ea..bf1af34e997 100644 --- a/src/Compiler/Utilities/XmlAdapters.fs +++ b/src/Compiler/Utilities/XmlAdapters.fs @@ -12,6 +12,6 @@ let getEscapeSequence c = | '\"' -> """ | '\'' -> "'" | '&' -> "&" - | _ as ch -> ch.ToString() + | ch -> ch.ToString() let escape str = String.collect getEscapeSequence str diff --git a/src/Compiler/Utilities/illib.fs b/src/Compiler/Utilities/illib.fs index c7bf17bba42..f6deb3951ef 100644 --- a/src/Compiler/Utilities/illib.fs +++ b/src/Compiler/Utilities/illib.fs @@ -154,13 +154,7 @@ module internal PervasiveAutoOpens = let ts = TaskCompletionSource<'T>() let task = ts.Task - Async.StartWithContinuations( - computation, - (fun k -> ts.SetResult k), - (fun exn -> ts.SetException exn), - (fun _ -> ts.SetCanceled()), - cancellationToken - ) + Async.StartWithContinuations(computation, (ts.SetResult), (ts.SetException), (fun _ -> ts.SetCanceled()), cancellationToken) task.Result @@ -278,7 +272,7 @@ module Array = let rec loop p l n = (n < Array.length l) && (if p l[n] then - forallFrom (fun x -> not (p x)) l (n + 1) + forallFrom (p >> not) l (n + 1) else loop p l (n + 1)) @@ -628,7 +622,7 @@ module List = xss |> List.mapi (fun i xs -> xs |> List.mapi (fun j x -> f i j x)) let existsSquared f xss = - xss |> List.exists (fun xs -> xs |> List.exists (fun x -> f x)) + xss |> List.exists (fun xs -> xs |> List.exists f) let mapiFoldSquared f z xss = mapFoldSquared f z (xss |> mapiSquared (fun i j x -> (i, j, x))) diff --git a/src/Compiler/Utilities/lib.fs b/src/Compiler/Utilities/lib.fs index 04dce4c4aec..87e50acd74a 100755 --- a/src/Compiler/Utilities/lib.fs +++ b/src/Compiler/Utilities/lib.fs @@ -20,7 +20,7 @@ let mutable progress = false let mutable tracking = false let isEnvVarSet s = - try (Environment.GetEnvironmentVariable(s) <> null) with _ -> false + try not(isNull(Environment.GetEnvironmentVariable s)) with _ -> false let GetEnvInteger e dflt = match Environment.GetEnvironmentVariable(e) with null -> dflt | t -> try int t with _ -> dflt diff --git a/src/Compiler/Utilities/sformat.fs b/src/Compiler/Utilities/sformat.fs index 43f40808c3c..73497ce6bcb 100644 --- a/src/Compiler/Utilities/sformat.fs +++ b/src/Compiler/Utilities/sformat.fs @@ -365,7 +365,7 @@ module Layout = match layouts with | [] -> emptyL | [ x ] -> x - | x :: ys -> List.fold (fun pre y -> pre @@ y) x ys + | x :: ys -> List.fold (@@) x ys let optionL selector value = match value with @@ -768,7 +768,7 @@ module Display = | Leaf(_, obj, _) -> addText z obj.Text - | Node(l, r, Broken indent) when not (opts.PrintWidth = 0) -> + | Node(l, r, Broken indent) when opts.PrintWidth <> 0 -> let z = addL z pos l let z = newLine z (pos + indent) let z = addL z (pos + indent) r @@ -1469,7 +1469,7 @@ module Display = | RecordValue items -> recordValueL depthLim (Array.toList items) | UnionCaseValue(constr, recd) when // x is List. Note: "null" is never a valid list value. - x <> null && isListType (x.GetType()) + (not (isNull x)) && isListType (x.GetType()) -> listValueL depthLim constr recd diff --git a/src/Compiler/Utilities/sr.fs b/src/Compiler/Utilities/sr.fs index 8fb3409eebd..b081dfb6083 100644 --- a/src/Compiler/Utilities/sr.fs +++ b/src/Compiler/Utilities/sr.fs @@ -16,7 +16,7 @@ module internal SR = .Force() .GetString(name, System.Globalization.CultureInfo.CurrentUICulture) #if DEBUG - if null = s then + if isNull s then System.Diagnostics.Debug.Assert(false, sprintf "**RESOURCE ERROR**: Resource token %s does not exist!" name) #endif s @@ -98,7 +98,7 @@ module internal DiagnosticMessage = // validate that the message string exists let fmtString = fmt.Value - if null = messageString then + if isNull messageString then System.Diagnostics.Debug.Assert(false, sprintf "**DECLARED MESSAGE ERROR** String resource %s does not exist" messageID) messageString <- "" diff --git a/src/FSharp.Build/FSharpEmbedResourceText.fs b/src/FSharp.Build/FSharpEmbedResourceText.fs index 263400f9561..397842b41f6 100644 --- a/src/FSharp.Build/FSharpEmbedResourceText.fs +++ b/src/FSharp.Build/FSharpEmbedResourceText.fs @@ -285,7 +285,7 @@ open Printf static let GetString(name:string) = let s = resources.Value.GetString(name, System.Globalization.CultureInfo.CurrentUICulture) #if DEBUG - if null = s then + if isNull s then System.Diagnostics.Debug.Assert(false, sprintf ""**RESOURCE ERROR**: Resource token %s does not exist!"" name) #endif s diff --git a/src/FSharp.Build/Fsc.fs b/src/FSharp.Build/Fsc.fs index af7e16d13cc..614a6b4f392 100644 --- a/src/FSharp.Build/Fsc.fs +++ b/src/FSharp.Build/Fsc.fs @@ -107,7 +107,7 @@ type public Fsc() as this = array |> Array.map (fun item -> item.Trim(wsCharsToTrim)) - |> Array.filter (fun s -> not (String.IsNullOrEmpty s)) + |> Array.filter (String.IsNullOrEmpty >> not) // See bug 6483; this makes parallel build faster, and is fine to set unconditionally do this.YieldDuringToolExecution <- true @@ -224,7 +224,7 @@ type public Fsc() as this = builder.AppendSwitchIfNotNull( "--checksumalgorithm:", let ToUpperInvariant (s: string) = - if s = null then + if isNull s then null else s.ToUpperInvariant() diff --git a/src/FSharp.Core/Linq.fs b/src/FSharp.Core/Linq.fs index bdca8e9bab8..257dd27edb2 100644 --- a/src/FSharp.Core/Linq.fs +++ b/src/FSharp.Core/Linq.fs @@ -310,7 +310,7 @@ module LeafExpressionConverter = 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 (|NotQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (not)) 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)) @@ -322,72 +322,72 @@ module LeafExpressionConverter = 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 (|BitwiseNotQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof ( ~~~ )) + let (|CheckedNeg|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.( ~-))) 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 (|ConvIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.nativeint x)) - let (|ConvUIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Operators.unativeint x)) + let (|ConvCharQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.char)) + let (|ConvDecimalQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.decimal)) + let (|ConvFloatQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.float)) + let (|ConvFloat32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.float32)) + let (|ConvSByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.sbyte)) + + let (|ConvInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.int16)) + let (|ConvInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.int32)) + let (|ConvIntQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.int)) + let (|ConvInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.int64)) + let (|ConvByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.byte)) + let (|ConvUInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.uint16)) + let (|ConvUInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.uint32)) + let (|ConvUInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.uint64)) + let (|ConvIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.nativeint)) + let (|ConvUIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Operators.unativeint)) 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 (|ConvNullableIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.nativeint x)) - let (|ConvNullableUIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Nullable.unativeint x)) + let (|ConvNullableCharQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.char)) + let (|ConvNullableDecimalQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.decimal)) + let (|ConvNullableFloatQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.float)) + let (|ConvNullableDoubleQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.double)) + let (|ConvNullableFloat32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.float32)) + let (|ConvNullableSingleQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.single)) + let (|ConvNullableSByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.sbyte)) + let (|ConvNullableInt8Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.int8)) + let (|ConvNullableInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.int16)) + let (|ConvNullableInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.int32)) + let (|ConvNullableIntQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.int)) + let (|ConvNullableInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.int64)) + let (|ConvNullableByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.byte)) + let (|ConvNullableUInt8Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.uint8)) + let (|ConvNullableUInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.uint16)) + let (|ConvNullableUInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.uint32)) + let (|ConvNullableUInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.uint64)) + let (|ConvNullableIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.nativeint)) + let (|ConvNullableUIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Nullable.unativeint)) let (|UnboxGeneric|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> LanguagePrimitives.IntrinsicFunctions.UnboxGeneric x)) let (|TypeTestGeneric|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> LanguagePrimitives.IntrinsicFunctions.TypeTestGeneric x)) - let (|CheckedConvCharQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.char x)) - let (|CheckedConvSByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.sbyte x)) + let (|CheckedConvCharQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.char)) + let (|CheckedConvSByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.sbyte)) let (|CheckedConvInt8Q|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators+Checked").GetMethod("ToSByte")) let (|CheckedConvUInt8Q|_|) = SpecificCallToMethodInfo (typeof.Assembly.GetType("Microsoft.FSharp.Core.ExtraTopLevelOperators+Checked").GetMethod("ToByte")) - let (|CheckedConvInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.int16 x)) - let (|CheckedConvInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.int32 x)) - let (|CheckedConvInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.int64 x)) - let (|CheckedConvByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.byte x)) - let (|CheckedConvUInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.uint16 x)) - let (|CheckedConvUInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.uint32 x)) - let (|CheckedConvUInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.uint64 x)) - let (|CheckedConvIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.nativeint x)) - let (|CheckedConvUIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun x -> Checked.unativeint x)) - 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 (|CheckedConvInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.int16)) + let (|CheckedConvInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.int32)) + let (|CheckedConvInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.int64)) + let (|CheckedConvByteQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.byte)) + let (|CheckedConvUInt16Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.uint16)) + let (|CheckedConvUInt32Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.uint32)) + let (|CheckedConvUInt64Q|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.uint64)) + let (|CheckedConvIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.nativeint)) + let (|CheckedConvUIntPtrQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (Checked.unativeint)) + let (|ImplicitExpressionConversionHelperQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (ImplicitExpressionConversionHelper)) + let (|MemberInitializationHelperQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (MemberInitializationHelper)) + let (|NewAnonymousObjectHelperQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (NewAnonymousObjectHelper)) let (|ArrayLookupQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun (x, y) -> LanguagePrimitives.IntrinsicFunctions.GetArray x y)) //let (|ArrayAssignQ|_|) = (|SpecificCallToMethod|_|) (methodhandleof (fun -> LanguagePrimitives.IntrinsicFunctions.SetArray : int[] -> int -> int -> unit)) @@ -564,7 +564,7 @@ module LeafExpressionConverter = | MakeDecimalQ (_, _, [Int32 lo; Int32 med; Int32 hi; Bool isNegative; Byte scale]) -> Expression.Constant (new System.Decimal(lo, med, hi, isNegative, scale)) |> asExpr - | NegQ (_, _, [x]) -> transUnaryOp isLinqExpressionsArithmeticTypeButNotUnsignedInt inp env x Expression.Negate (methodhandleof (fun x -> LanguagePrimitives.UnaryNegationDynamic x)) + | NegQ (_, _, [x]) -> transUnaryOp isLinqExpressionsArithmeticTypeButNotUnsignedInt inp env x Expression.Negate (methodhandleof (LanguagePrimitives.UnaryNegationDynamic)) | PlusQ (_, _, [x1; x2]) -> transBinOp isLinqExpressionsArithmeticType inp env false x1 x2 false Expression.Add (methodhandleof (fun (x, y) -> LanguagePrimitives.AdditionDynamic x y)) | MinusQ (_, _, [x1; x2]) -> transBinOp isLinqExpressionsArithmeticType inp env false x1 x2 false Expression.Subtract (methodhandleof (fun (x, y) -> LanguagePrimitives.SubtractionDynamic x y)) | MultiplyQ (_, _, [x1; x2]) -> transBinOp isLinqExpressionsArithmeticType inp env false x1 x2 false Expression.Multiply (methodhandleof (fun (x, y) -> LanguagePrimitives.MultiplyDynamic x y)) @@ -576,7 +576,7 @@ module LeafExpressionConverter = | BitwiseAndQ (_, _, [x1; x2]) -> transBinOp isLinqExpressionsIntegerOrBool inp env false x1 x2 false Expression.And (methodhandleof (fun (x, y) -> LanguagePrimitives.BitwiseAndDynamic x y)) | BitwiseOrQ (_, _, [x1; x2]) -> transBinOp isLinqExpressionsIntegerOrBool inp env false x1 x2 false Expression.Or (methodhandleof (fun (x, y) -> LanguagePrimitives.BitwiseOrDynamic x y)) | BitwiseXorQ (_, _, [x1; x2]) -> transBinOp isLinqExpressionsIntegerOrBool inp env false x1 x2 false Expression.ExclusiveOr (methodhandleof (fun (x, y) -> LanguagePrimitives.ExclusiveOrDynamic x y)) - | BitwiseNotQ (_, _, [x]) -> transUnaryOp isLinqExpressionsIntegerOrBool inp env x Expression.Not (methodhandleof (fun x -> LanguagePrimitives.LogicalNotDynamic x)) + | BitwiseNotQ (_, _, [x]) -> transUnaryOp isLinqExpressionsIntegerOrBool inp env x Expression.Not (methodhandleof (LanguagePrimitives.LogicalNotDynamic)) | CheckedNeg (_, _, [x]) -> transUnaryOp isLinqExpressionsArithmeticTypeButNotUnsignedInt inp env x Expression.NegateChecked (methodhandleof (fun x -> LanguagePrimitives.CheckedUnaryNegationDynamic x)) | CheckedPlusQ (_, _, [x1; x2]) -> transBinOp isLinqExpressionsArithmeticType inp env false x1 x2 false Expression.AddChecked (methodhandleof (fun (x, y) -> LanguagePrimitives.CheckedAdditionDynamic x y)) @@ -865,7 +865,7 @@ module LeafExpressionConverter = if isLinqExpressionsConvertible e.Type inp.Type then exprErasedConstructor(e, inp.Type, null) else - let method = Reflection.MethodInfo.GetMethodFromHandle (if isChecked then methodhandleof (fun x -> LanguagePrimitives.CheckedExplicitDynamic x) else methodhandleof (fun x -> LanguagePrimitives.ExplicitDynamic x)) :?> Reflection.MethodInfo + let method = Reflection.MethodInfo.GetMethodFromHandle (if isChecked then methodhandleof (LanguagePrimitives.CheckedExplicitDynamic) else methodhandleof (LanguagePrimitives.ExplicitDynamic)) :?> Reflection.MethodInfo exprErasedConstructor(e, inp.Type, method.MakeGenericMethod [| getNonNullableType x.Type; getNonNullableType inp.Type |]) |> asExpr diff --git a/src/FSharp.Core/Query.fs b/src/FSharp.Core/Query.fs index 28a460619f6..9905362371d 100644 --- a/src/FSharp.Core/Query.fs +++ b/src/FSharp.Core/Query.fs @@ -244,7 +244,7 @@ type QueryBuilder() = 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))) + QuerySource (Enumerable.GroupJoin(outerSource.Source, innerSource.Source, Func<_, _>(outerKeySelector), Func<_, _>(innerKeySelector), Func<_, _, _>(resultSelector))) 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())))) @@ -403,7 +403,7 @@ module Query = (fun (obj: Expr, tyargs: Type list, args: Expr list) -> Expr.Call (obj, BindGenericStaticMethod methInfo tyargs, args)) let ImplicitExpressionConversionHelperMethodInfo = - methodhandleof (fun e -> LeafExpressionConverter.ImplicitExpressionConversionHelper e) + methodhandleof (LeafExpressionConverter.ImplicitExpressionConversionHelper) |> System.Reflection.MethodInfo.GetMethodFromHandle :?> MethodInfo @@ -722,21 +722,21 @@ module Query = (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 MakeFirst, CallFirst = MakeOrCallSimpleOp (methodhandleof (System.Linq.Queryable.First)) (methodhandleof (Enumerable.First)) - let MakeFirstOrDefault, CallFirstOrDefault = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.FirstOrDefault x)) (methodhandleof (fun x -> Enumerable.FirstOrDefault x)) + let MakeFirstOrDefault, CallFirstOrDefault = MakeOrCallSimpleOp (methodhandleof (System.Linq.Queryable.FirstOrDefault)) (methodhandleof (Enumerable.FirstOrDefault)) - let MakeLast, CallLast = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Last x)) (methodhandleof (fun x -> Enumerable.Last x)) + let MakeLast, CallLast = MakeOrCallSimpleOp (methodhandleof (System.Linq.Queryable.Last)) (methodhandleof (Enumerable.Last)) - let MakeLastOrDefault, CallLastOrDefault = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.LastOrDefault x)) (methodhandleof (fun x -> Enumerable.LastOrDefault x)) + let MakeLastOrDefault, CallLastOrDefault = MakeOrCallSimpleOp (methodhandleof (System.Linq.Queryable.LastOrDefault)) (methodhandleof (Enumerable.LastOrDefault)) - let MakeSingle, CallSingle = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Single x)) (methodhandleof (fun x -> Enumerable.Single x)) + let MakeSingle, CallSingle = MakeOrCallSimpleOp (methodhandleof (System.Linq.Queryable.Single)) (methodhandleof (Enumerable.Single)) - let MakeSingleOrDefault, CallSingleOrDefault = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.SingleOrDefault x)) (methodhandleof (fun x -> Enumerable.SingleOrDefault x)) + let MakeSingleOrDefault, CallSingleOrDefault = MakeOrCallSimpleOp (methodhandleof (System.Linq.Queryable.SingleOrDefault)) (methodhandleof (Enumerable.SingleOrDefault)) - let MakeCount, CallCount = MakeOrCallSimpleOp (methodhandleof (fun x -> System.Linq.Queryable.Count x)) (methodhandleof (fun x -> Enumerable.Count x)) + let MakeCount, CallCount = MakeOrCallSimpleOp (methodhandleof (System.Linq.Queryable.Count)) (methodhandleof (Enumerable.Count)) - let MakeDefaultIfEmpty = MakeGenericStaticMethod (methodhandleof (fun x -> Enumerable.DefaultIfEmpty x)) + let MakeDefaultIfEmpty = MakeGenericStaticMethod (methodhandleof (Enumerable.DefaultIfEmpty)) /// Indicates if we can eliminate redundant 'Select(x=>x)' nodes type CanEliminate = @@ -898,8 +898,8 @@ module Query = (methodhandleof (fun (x, y: Func<_, _>) -> Enumerable.TakeWhile(x, y))) let MakeDistinct = - let FQ = MakeGenericStaticMethod (methodhandleof (fun x -> System.Linq.Queryable.Distinct x)) - let FE = MakeGenericStaticMethod (methodhandleof (fun x -> Enumerable.Distinct x)) + let FQ = MakeGenericStaticMethod (methodhandleof (System.Linq.Queryable.Distinct)) + let FE = MakeGenericStaticMethod (methodhandleof (Enumerable.Distinct)) fun (isIQ, srcItemTy, src: Expr) -> if isIQ then FQ ([srcItemTy], [src]) diff --git a/src/FSharp.Core/QueryExtensions.fs b/src/FSharp.Core/QueryExtensions.fs index 4a588b0eb92..27d20d35fa4 100644 --- a/src/FSharp.Core/QueryExtensions.fs +++ b/src/FSharp.Core/QueryExtensions.fs @@ -47,12 +47,12 @@ module internal Adapters = && not (FSharpType.GetRecordFields t |> Array.forall (fun f -> f.CanWrite))) let MemberInitializationHelperMeth = - methodhandleof (fun x -> LeafExpressionConverter.MemberInitializationHelper x) + methodhandleof (LeafExpressionConverter.MemberInitializationHelper) |> MethodInfo.GetMethodFromHandle :?> MethodInfo let NewAnonymousObjectHelperMeth = - methodhandleof (fun x -> LeafExpressionConverter.NewAnonymousObjectHelper x) + methodhandleof (LeafExpressionConverter.NewAnonymousObjectHelper) |> MethodInfo.GetMethodFromHandle :?> MethodInfo @@ -78,7 +78,7 @@ module internal Adapters = | ((Patterns.PropertySet(Some(Patterns.Var var), _, _, _)) as p) :: xs when var = varArg -> propSetList (p :: acc) xs // skip unit values - | (Patterns.Value(v, _)) :: xs when v = null -> propSetList acc xs + | (Patterns.Value(v, _)) :: xs when isNull v -> propSetList acc xs // detect "v" | [ Patterns.Var var ] when var = varArg -> Some acc | _ -> None @@ -256,8 +256,7 @@ module internal Adapters = | NoConv -> ty let IsNewAnonymousObjectHelperQ = - let mhandle = - (methodhandleof (fun x -> LeafExpressionConverter.NewAnonymousObjectHelper x)) + let mhandle = (methodhandleof (LeafExpressionConverter.NewAnonymousObjectHelper)) let minfo = (MethodInfo.GetMethodFromHandle mhandle) :?> MethodInfo diff --git a/src/FSharp.Core/array.fs b/src/FSharp.Core/array.fs index 9ba8bc6e18c..9902a063871 100644 --- a/src/FSharp.Core/array.fs +++ b/src/FSharp.Core/array.fs @@ -247,7 +247,7 @@ module Array = let countByRefType (projection: 'T -> 'Key) (array: 'T[]) = countByImpl RuntimeHelpers.StructBox<'Key>.Comparer - (fun t -> RuntimeHelpers.StructBox(projection t)) + (projection >> RuntimeHelpers.StructBox) (fun sb -> sb.Value) array @@ -577,7 +577,7 @@ module Array = let groupByRefType (keyf: 'T -> 'Key) (array: 'T[]) = groupByImpl RuntimeHelpers.StructBox<'Key>.Comparer - (fun t -> RuntimeHelpers.StructBox(keyf t)) + (keyf >> RuntimeHelpers.StructBox) (fun sb -> sb.Value) array @@ -2300,7 +2300,7 @@ module Array = let groupByRefTypeParallel (keyf: 'T -> 'Key) (array: 'T[]) = groupByImplParallel RuntimeHelpers.StructBox<'Key>.Comparer - (fun t -> RuntimeHelpers.StructBox(keyf t)) + (keyf >> RuntimeHelpers.StructBox) (fun sb -> sb.Value) array @@ -2454,11 +2454,10 @@ module Array = array[i] <- array[j] array[j] <- tmp - let pivotIdx = - pickPivot (fun i j -> cmp array[i] array[j]) (fun i j -> swap i j) orig + let pivotIdx = pickPivot (fun i j -> cmp array[i] array[j]) swap orig let pivotItem = array[pivotIdx] - partitionIntoTwo (fun idx -> cmp array[idx] pivotItem) (fun i j -> swap i j) orig + partitionIntoTwo (fun idx -> cmp array[idx] pivotItem) swap orig let partitionIntoTwoUsingKeys (keys: 'A[]) (orig: ArraySegment<'T>) : ArraySegment<'T> * ArraySegment<'T> = let array = orig.Array @@ -2472,11 +2471,10 @@ module Array = array.[i] <- array.[j] array.[j] <- tmp - let pivotIdx = - pickPivot (fun i j -> compare keys[i] keys[j]) (fun i j -> swap i j) orig + let pivotIdx = pickPivot (fun i j -> compare keys[i] keys[j]) swap orig let pivotKey = keys[pivotIdx] - partitionIntoTwo (fun idx -> compare keys[idx] pivotKey) (fun i j -> swap i j) orig + partitionIntoTwo (fun idx -> compare keys[idx] pivotKey) swap orig let inline sortInPlaceHelper (array: 'T[]) diff --git a/src/FSharp.Core/async.fs b/src/FSharp.Core/async.fs index 6590c41a04d..bc9d676663b 100644 --- a/src/FSharp.Core/async.fs +++ b/src/FSharp.Core/async.fs @@ -717,7 +717,7 @@ module AsyncPrimitives = /// - Apply `catchFunction' to argument with exception protection (see TryWith) /// - Hijack check before invoking the resulting computation or exception continuation let inline CreateTryWithAsync catchFunction computation = - MakeAsync(fun ctxt -> TryWith ctxt computation (fun exn -> Some(catchFunction exn))) + MakeAsync(fun ctxt -> TryWith ctxt computation (catchFunction >> Some)) /// Call the finallyFunction if the computation results in a cancellation, and then continue with cancellation. /// If the finally function gives an exception then continue with cancellation regardless. @@ -1203,7 +1203,7 @@ module AsyncPrimitives = QueueAsync cancellationToken - (fun r -> tcs.SetResult r |> fake) + (tcs.SetResult >> fake) (fun edi -> tcs.SetException edi.SourceException |> fake) (fun _ -> tcs.SetCanceled() |> fake) computation @@ -1499,7 +1499,7 @@ type Async = // Turn the success or exception into data let newCtxt = ctxt.WithContinuations( - cont = (fun res -> ctxt.cont (Choice1Of2 res)), + cont = (Choice1Of2 >> ctxt.cont), econt = (fun edi -> ctxt.cont (Choice2Of2(edi.GetAssociatedSourceException()))) ) @@ -1620,9 +1620,9 @@ type Async = // on success, record the result (fun res -> recordSuccess i res) // on exception... - (fun edi -> recordFailure (Choice1Of2 edi)) + (Choice1Of2 >> recordFailure) // on cancellation... - (fun cexn -> recordFailure (Choice2Of2 cexn)) + (Choice2Of2 >> recordFailure) p |> unfake) | Some maxDegreeOfParallelism -> @@ -1783,8 +1783,8 @@ type Async = Async.StartWithContinuations( computation, - (fun k -> ts.SetResult k), - (fun exn -> ts.SetException exn), + (ts.SetResult), + (ts.SetException), (fun _ -> ts.SetCanceled()), cancellationToken ) diff --git a/src/FSharp.Core/eventmodule.fs b/src/FSharp.Core/eventmodule.fs index 00ab9d069b2..74078c6bafb 100644 --- a/src/FSharp.Core/eventmodule.fs +++ b/src/FSharp.Core/eventmodule.fs @@ -12,7 +12,7 @@ module Event = [] let map mapping (sourceEvent: IEvent<'Delegate, 'T>) = let ev = new Event<_>() - sourceEvent.Add(fun x -> ev.Trigger(mapping x)) + sourceEvent.Add(mapping >> ev.Trigger) ev.Publish [] diff --git a/src/FSharp.Core/fslib-extra-pervasives.fs b/src/FSharp.Core/fslib-extra-pervasives.fs index 53ae4414887..d12a20211b8 100644 --- a/src/FSharp.Core/fslib-extra-pervasives.fs +++ b/src/FSharp.Core/fslib-extra-pervasives.fs @@ -101,11 +101,11 @@ module ExtraTopLevelOperators = member _.TryGetValue(k, r) = let safeKey = makeSafeKey k - if t.ContainsKey(safeKey) then - (r <- t.[safeKey] + match t.TryGetValue safeKey with + | true, tsafe -> + (r <- tsafe true) - else - false + | false, _ -> false member _.Remove(_: 'Key) = (raise (NotSupportedException(SR.GetString(SR.thisValueCannotBeMutated))): bool) @@ -197,7 +197,7 @@ module ExtraTopLevelOperators = // Wrap a StructBox around all keys in case the key type is itself a type using null as a representation let dictRefType (l: seq<'Key * 'T>) = - dictImpl RuntimeHelpers.StructBox<'Key>.Comparer (fun k -> RuntimeHelpers.StructBox k) (fun sb -> sb.Value) l + dictImpl RuntimeHelpers.StructBox<'Key>.Comparer (RuntimeHelpers.StructBox) (fun sb -> sb.Value) l [] let dict (keyValuePairs: seq<'Key * 'T>) : IDictionary<'Key, 'T> = diff --git a/src/FSharp.Core/list.fs b/src/FSharp.Core/list.fs index de8ecd3a2ff..e3559a13958 100644 --- a/src/FSharp.Core/list.fs +++ b/src/FSharp.Core/list.fs @@ -78,7 +78,7 @@ module List = let countByRefType (projection: 'T -> 'Key) (list: 'T list) = countByImpl RuntimeHelpers.StructBox<'Key>.Comparer - (fun t -> RuntimeHelpers.StructBox(projection t)) + (projection >> RuntimeHelpers.StructBox) (fun sb -> sb.Value) list @@ -557,11 +557,7 @@ module List = // 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) (list: 'T list) = - groupByImpl - RuntimeHelpers.StructBox<'Key>.Comparer - (fun t -> RuntimeHelpers.StructBox(keyf t)) - (fun sb -> sb.Value) - list + groupByImpl RuntimeHelpers.StructBox<'Key>.Comparer (keyf >> RuntimeHelpers.StructBox) (fun sb -> sb.Value) list [] let groupBy (projection: 'T -> 'Key) (list: 'T list) = diff --git a/src/FSharp.Core/mailbox.fs b/src/FSharp.Core/mailbox.fs index c5b604074ac..699e40153b3 100644 --- a/src/FSharp.Core/mailbox.fs +++ b/src/FSharp.Core/mailbox.fs @@ -91,7 +91,7 @@ type Mailbox<'Msg>(cancellationSupported: bool) = lock syncRoot (fun () -> if arrivals.Count = 0 then // OK, no arrival so deschedule - savedCont <- Some(fun res -> ctxt.QueueContinuationWithTrampoline res) + savedCont <- Some(ctxt.QueueContinuationWithTrampoline) true else false) diff --git a/src/FSharp.Core/printf.fs b/src/FSharp.Core/printf.fs index 58cab425d1f..9a7d461d698 100644 --- a/src/FSharp.Core/printf.fs +++ b/src/FSharp.Core/printf.fs @@ -599,12 +599,12 @@ module internal PrintfImpl = let fmt = getFormat prec if spec.IsWidthSpecified then // width=val, prec=* - ValueConverter.Make (fun v -> - pad fmt spec.Width v) + ValueConverter.Make ( + pad fmt spec.Width) else // width=X, prec=* - ValueConverter.Make (fun v -> - basic fmt v) + ValueConverter.Make ( + basic fmt) /// pad here is function that converts T to string with respect of justification /// basic - function that converts T to string without applying justification rules @@ -617,12 +617,12 @@ module internal PrintfImpl = else if spec.IsWidthSpecified then // width=val, prec=* - ValueConverter.Make (fun v -> - pad spec.Width v) + ValueConverter.Make ( + pad spec.Width) else // width=X, prec=* - ValueConverter.Make (fun v -> - basic v) + ValueConverter.Make ( + basic) let withPaddingFormatted (spec: FormatSpecifier) getFormat (defaultFormat: string) (f: string -> obj -> string) left right : ValueConverter = if not (spec.IsWidthSpecified || spec.IsPrecisionSpecified) then diff --git a/src/FSharp.Core/quotations.fs b/src/FSharp.Core/quotations.fs index f0b029b46e6..18a3f4cae12 100644 --- a/src/FSharp.Core/quotations.fs +++ b/src/FSharp.Core/quotations.fs @@ -1976,7 +1976,7 @@ module Patterns = E(CombTerm(a tyargs (ValueSome args.Length), args))) | 1 -> let x = u_VarRef st - (fun env -> E(VarTerm(x env))) + (x >> VarTerm >> E) | 2 -> let a = u_VarDecl st let b = u_Expr st diff --git a/src/FSharp.Core/seq.fs b/src/FSharp.Core/seq.fs index 8f5eeae06ef..13770d726ca 100644 --- a/src/FSharp.Core/seq.fs +++ b/src/FSharp.Core/seq.fs @@ -1340,8 +1340,7 @@ module Seq = // 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) (seq: seq<'T>) = seq - |> groupByImpl RuntimeHelpers.StructBox<'Key>.Comparer (fun t -> RuntimeHelpers.StructBox(keyf t)) (fun sb -> - sb.Value) + |> groupByImpl RuntimeHelpers.StructBox<'Key>.Comparer (keyf >> RuntimeHelpers.StructBox) (fun sb -> sb.Value) [] let groupBy (projection: 'T -> 'Key) (source: seq<'T>) = @@ -1454,8 +1453,7 @@ module Seq = // Wrap a StructBox around all keys in case the key type is itself a type using null as a representation let countByRefType (keyf: 'T -> 'Key) (seq: seq<'T>) = seq - |> countByImpl RuntimeHelpers.StructBox<'Key>.Comparer (fun t -> RuntimeHelpers.StructBox(keyf t)) (fun sb -> - sb.Value) + |> countByImpl RuntimeHelpers.StructBox<'Key>.Comparer (keyf >> RuntimeHelpers.StructBox) (fun sb -> sb.Value) [] let countBy (projection: 'T -> 'Key) (source: seq<'T>) = diff --git a/src/FSharp.Core/seqcore.fs b/src/FSharp.Core/seqcore.fs index d5426d4ffe0..b95e96ff95a 100644 --- a/src/FSharp.Core/seqcore.fs +++ b/src/FSharp.Core/seqcore.fs @@ -399,7 +399,7 @@ module RuntimeHelpers = | None -> originalSource.Value.Current let disposeOriginal() = - if shouldDisposeOriginalAtTheEnd = true then + if shouldDisposeOriginalAtTheEnd then shouldDisposeOriginalAtTheEnd <- false originalSource.Value.Dispose() diff --git a/src/FSharp.Core/set.fs b/src/FSharp.Core/set.fs index f89ac29dbbc..aaed3e37a41 100644 --- a/src/FSharp.Core/set.fs +++ b/src/FSharp.Core/set.fs @@ -834,7 +834,7 @@ type Set<[] 'T when 'T: comparison>(comparer: IComparer<' 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 + Seq.fold (+) Set<'T>.Empty sets static member Intersection(sets: seq>) : Set<'T> = Seq.reduce (fun s1 s2 -> Set.Intersection(s1, s2)) sets diff --git a/src/FSharp.Core/tasks.fs b/src/FSharp.Core/tasks.fs index 4d814696e71..faaa920cb15 100644 --- a/src/FSharp.Core/tasks.fs +++ b/src/FSharp.Core/tasks.fs @@ -380,7 +380,7 @@ module LowPriority = (task: ^TaskLike) : TaskCode<'T, 'T> = - this.Bind(task, (fun v -> this.Return v)) + this.Bind(task, this.Return) member inline _.Using<'Resource, 'TOverall, 'T when 'Resource :> IDisposable> ( @@ -446,7 +446,7 @@ module HighPriority = ) member inline this.ReturnFrom(task: Task<'T>) : TaskCode<'T, 'T> = - this.Bind(task, (fun v -> this.Return v)) + this.Bind(task, this.Return) module MediumPriority = open HighPriority diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs index a0ff19f6aac..875ccec4dd2 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Utilities.fs @@ -44,7 +44,7 @@ type PackageBuildResolutionResult = module internal Utilities = let verifyFilesExist files = - files |> List.tryFind (fun f -> not (File.Exists(f))) |> Option.isNone + files |> List.tryFind (File.Exists >> not) |> Option.isNone let findLoadsFromResolutions (resolutions: Resolution[]) = resolutions @@ -98,7 +98,7 @@ module internal Utilities = File .ReadAllText(resolutionsFile) .Split([| '\r'; '\n' |], StringSplitOptions.None) - |> Array.filter (fun line -> not (String.IsNullOrEmpty(line))) + |> Array.filter (String.IsNullOrEmpty >> not) with _ -> [||] @@ -169,7 +169,7 @@ module internal Utilities = insideSQ <- not insideSQ // keep reading | _ -> () - result |> List.ofSeq |> List.map (fun option -> split option) + result |> List.ofSeq |> List.map split let executeTool pathToExe arguments workingDir environment timeout = match pathToExe with diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs index 6b216f30b44..c6c7247b0df 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.fs @@ -237,7 +237,7 @@ module FSharpDependencyManager = |> Seq.distinct |> Seq.toArray |> Seq.sort - |> Seq.fold (fun acc s -> acc + s) "" + |> Seq.fold (+) "" let value = $"""Tfm={targetFrameworkMoniker}:Rid={runtimeIdentifier}:PackageReferences={packageReferenceText}:Ext={match scriptExt with @@ -410,7 +410,7 @@ type FSharpDependencyManager(outputDirectory: string option, useResultsCache: bo let tryGetResultsForResolutionHash hash (projectDirectory: Lazy) : PackageBuildResolutionResult option = match hash with - | Some hash when useResultsCache = true -> + | Some hash when useResultsCache -> let resolutionsFile = Path.Combine(cacheDirectory.Value, (hash + ".resolvedReferences.paths")) diff --git a/src/LegacyMSBuildResolver/LegacyMSBuildReferenceResolver.fs b/src/LegacyMSBuildResolver/LegacyMSBuildReferenceResolver.fs index 80ee208263c..e1f6f41b9dc 100644 --- a/src/LegacyMSBuildResolver/LegacyMSBuildReferenceResolver.fs +++ b/src/LegacyMSBuildResolver/LegacyMSBuildReferenceResolver.fs @@ -114,60 +114,27 @@ let GetPathToDotNetFrameworkReferenceAssemblies version = let HighestInstalledRefAssembliesOrDotNETFramework () = let getHighestInstalledDotNETFramework () = try - if - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version48)) - <> null - then + if not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version48)))) then Net48 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version472)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version472)))) then Net472 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version471)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version471)))) then Net471 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version47)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version47)))) then Net47 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version462)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version462)))) then Net462 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version461)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version461)))) then Net461 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version461)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version461)))) then Net461 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version46)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version46)))) then Net46 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version452)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version452)))) then Net452 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version451)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version451)))) then Net451 - elif - box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version45)) - <> null - then + elif not (isNull (box (ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version45)))) then Net45 else Net45 // version is 4.5 assumed since this code is running. @@ -198,7 +165,7 @@ let HighestInstalledRefAssembliesOrDotNETFramework () = match SupportedDesktopFrameworkVersions - |> Seq.tryFind (fun v -> checkFrameworkForReferenceAssemblies v) + |> Seq.tryFind checkFrameworkForReferenceAssemblies with | Some v -> v | None -> getHighestInstalledDotNETFramework () diff --git a/tests/AheadOfTime/Trimming/check.ps1 b/tests/AheadOfTime/Trimming/check.ps1 index 23c3cdfb4b3..8528710b76f 100644 --- a/tests/AheadOfTime/Trimming/check.ps1 +++ b/tests/AheadOfTime/Trimming/check.ps1 @@ -39,7 +39,7 @@ function CheckTrim($root, $tfm, $outputfile, $expected_len) { # error NETSDK1124: Trimming assemblies requires .NET Core 3.0 or higher. # Check net7.0 trimmed assemblies -CheckTrim -root "SelfContained_Trimming_Test" -tfm "net8.0" -outputfile "FSharp.Core.dll" -expected_len 287744 +CheckTrim -root "SelfContained_Trimming_Test" -tfm "net8.0" -outputfile "FSharp.Core.dll" -expected_len 287232 # Check net7.0 trimmed assemblies -CheckTrim -root "StaticLinkedFSharpCore_Trimming_Test" -tfm "net8.0" -outputfile "StaticLinkedFSharpCore_Trimming_Test.dll" -expected_len 8821760 +CheckTrim -root "StaticLinkedFSharpCore_Trimming_Test" -tfm "net8.0" -outputfile "StaticLinkedFSharpCore_Trimming_Test.dll" -expected_len 8820736 diff --git a/tests/fsharp/single-test.fs b/tests/fsharp/single-test.fs index bc8978cce6f..50eaa7cb370 100644 --- a/tests/fsharp/single-test.fs +++ b/tests/fsharp/single-test.fs @@ -125,7 +125,7 @@ let generateProjectArtifacts (pc:ProjectConfiguration) outputType (targetFramewo sources |> List.map(fun src -> computeInclude src) - |> List.fold (fun acc s -> acc + s) "" + |> List.fold (+) "" let replace tag items addDirectory addCondition compileItem (template:string) = template.Replace(tag, computeSourceItems addDirectory addCondition compileItem items) diff --git a/tests/service/data/TestTP/ProvidedTypes.fs b/tests/service/data/TestTP/ProvidedTypes.fs index 4e7a7604c6b..828235a0b9d 100644 --- a/tests/service/data/TestTP/ProvidedTypes.fs +++ b/tests/service/data/TestTP/ProvidedTypes.fs @@ -5934,7 +5934,7 @@ module internal AssemblyReader = let tidx = seekReadIndexedRow (getNumRows ILTableNames.TypeDef, (fun i -> i, seekReadTypeDefRowWithExtents i), - (fun r -> r), + id, (fun (_, ((_, _, _, _, _, methodsIdx), (_, endMethodsIdx))) -> if endMethodsIdx <= idx then 1