From fc6c4c99414e35b13a4c5292a38b8165b2a1aff0 Mon Sep 17 00:00:00 2001 From: Matt Thalman Date: Tue, 25 Mar 2025 13:24:03 -0500 Subject: [PATCH 01/20] Use correct TFM for source build when OfficialBuildId isn't set (#18397) --- src/Compiler/FSharp.Compiler.Service.fsproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Compiler/FSharp.Compiler.Service.fsproj b/src/Compiler/FSharp.Compiler.Service.fsproj index 493248a11d3..ca08c3f63d9 100644 --- a/src/Compiler/FSharp.Compiler.Service.fsproj +++ b/src/Compiler/FSharp.Compiler.Service.fsproj @@ -23,7 +23,7 @@ OSX and Linux has problems with Xliff targets for net9, skipping via SKIP_NETCURRENT_FSC_BUILD until resolved ( The target "UpdateXlf" does not exist in the project.) --> - $(FSharpNetCoreProductDefaultTargetFramework);$(TargetFrameworks) + $(FSharpNetCoreProductTargetFramework);$(TargetFrameworks) $(DefineConstants);FSHARPCORE_USE_PACKAGE $(OtherFlags) --extraoptimizationloops:1 From d4a9f1356b119fa810cb32e56e0f90ab8698d82c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20S=C3=A1nchez=20L=C3=B3pez?= <1175054+carlossanlop@users.noreply.github.com> Date: Tue, 25 Mar 2025 15:37:38 -0700 Subject: [PATCH 02/20] Update dependencies coming from maintenance-packages (#18329) * Update dependencies coming from maintenance-packages * Remove temp feed * Sort * Push for real the changes this time * Update to latest in nuget.org * Update dependencies from https://github.com/dotnet/source-build-reference-packages build 20250320.3 Microsoft.SourceBuild.Intermediate.source-build-reference-packages From Version 9.0.0-alpha.1.25163.3 -> To Version 9.0.0-alpha.1.25170.3 * Bring back conditions * missing space --------- Co-authored-by: dotnet-maestro[bot] Co-authored-by: Kevin Ransom (msft) Co-authored-by: Tomas Grosup --- eng/Versions.props | 16 ++++++++++++---- src/FSharp.Build/Microsoft.FSharp.NetSdk.props | 2 +- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/eng/Versions.props b/eng/Versions.props index 5993821c9ea..5ce287e802b 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -71,21 +71,29 @@ $(VersionPrefix).0 + + + 4.6.1 + 4.6.2 + 6.1.1 + + + + 4.6.0 + 4.5.5 + 6.1.0 + 8.0.0 - 4.6.0 $(SystemPackageVersionVersion) $(SystemPackageVersionVersion) $(SystemPackageVersionVersion) $(SystemPackageVersionVersion) - 4.5.5 - 4.6.0 4.7.0 $(SystemPackageVersionVersion) - 6.1.0 $(SystemPackageVersionVersion) 1.6.0 diff --git a/src/FSharp.Build/Microsoft.FSharp.NetSdk.props b/src/FSharp.Build/Microsoft.FSharp.NetSdk.props index 38d83cd8ab4..e45f864ce22 100644 --- a/src/FSharp.Build/Microsoft.FSharp.NetSdk.props +++ b/src/FSharp.Build/Microsoft.FSharp.NetSdk.props @@ -94,7 +94,7 @@ WARNING: DO NOT MODIFY this file unless you are knowledgeable about MSBuild and - 4.4.0 + 4.6.1 From 2408d66391b7d6717e9e11c178d9c1f45fdeb1c8 Mon Sep 17 00:00:00 2001 From: Martin <29605222+Martin521@users.noreply.github.com> Date: Wed, 26 Mar 2025 09:04:39 +0100 Subject: [PATCH 03/20] update devcontainer sdk (#18412) --- .devcontainer/devcontainer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 8f6f1eee176..47927f1f370 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,7 +1,7 @@ // For format details, see https://aka.ms/vscode-remote/devcontainer.json or this file's README at: { "name": "F#", - "image": "mcr.microsoft.com/dotnet/sdk:9.0.200", + "image": "mcr.microsoft.com/dotnet/sdk:9.0.202", "features": { "ghcr.io/devcontainers/features/common-utils:2.5.2": {}, "ghcr.io/devcontainers/features/git:1.3.2": {}, From f4b677e0462ebd27df8813fbbab2a5d1ecec4284 Mon Sep 17 00:00:00 2001 From: Jakub Majocha <1760221+majocha@users.noreply.github.com> Date: Wed, 26 Mar 2025 09:05:07 +0100 Subject: [PATCH 04/20] deal with hanging test (#18411) --- .../CompilerService/AsyncMemoize.fs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs b/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs index 3e940c51ea6..f37b64eb0f5 100644 --- a/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs +++ b/tests/FSharp.Compiler.ComponentTests/CompilerService/AsyncMemoize.fs @@ -430,7 +430,7 @@ let ``Cancel running jobs with the same key`` () = let current = eventsWhen events (received Requested) Assert.Equal(0, current |> countOf Canceled) - waitUntil events (countOf Canceled >> (=) 10) + // waitUntil events (countOf Canceled >> (=) 10) waitUntil events (received Started) @@ -442,6 +442,7 @@ let ``Cancel running jobs with the same key`` () = Assert.Equal(0, events |> countOf Failed) + // All outdated jobs should have been canceled by now. Assert.Equal(10, events |> countOf Canceled) Assert.Equal(1, events |> countOf Finished) From e37ef75d1ef70a3e0ba87b506666fd15a3d951af Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Wed, 26 Mar 2025 01:05:28 -0700 Subject: [PATCH 05/20] typo (#18413) --- vsintegration/src/FSharp.Editor/Common/Extensions.fs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/vsintegration/src/FSharp.Editor/Common/Extensions.fs b/vsintegration/src/FSharp.Editor/Common/Extensions.fs index 3483c9c583e..2ed87e5ec82 100644 --- a/vsintegration/src/FSharp.Editor/Common/Extensions.fs +++ b/vsintegration/src/FSharp.Editor/Common/Extensions.fs @@ -97,10 +97,10 @@ type ConnectionPointSubscription = System.IDisposable option // Usage example: // If a handler is None, to not handle that event -// let subscription = subscribeToTextViewEvents (textView, onChangeCaretHandler, onKillFocus, OnSetFocus) +// let subscription = subscribeToTextViewEvents (textView, onChangeCaretHandler, onKillFocus, onSetFocus) // Unsubscribe using subscription.Dispose() -let subscribeToTextViewEvents (textView: IVsTextView, onChangeCaretHandler, onKillFocus, OnSetFocus) : ConnectionPointSubscription = - let handler = TextViewEventsHandler(onChangeCaretHandler, onKillFocus, OnSetFocus) +let subscribeToTextViewEvents (textView: IVsTextView, onChangeCaretHandler, onKillFocus, onSetFocus) : ConnectionPointSubscription = + let handler = TextViewEventsHandler(onChangeCaretHandler, onKillFocus, onSetFocus) match textView with | :? IConnectionPointContainer as cpContainer -> From 55d736b7b42e8bae16b9a15ea7755fbcfaed2910 Mon Sep 17 00:00:00 2001 From: Tomas Grosup Date: Thu, 27 Mar 2025 09:30:09 +0100 Subject: [PATCH 06/20] Remove a bunch of files from fantomas ignore (#18407) * Remove a bunch of files from fantomas ignore * see what happens - bunch of IFDEFs related to nullness removed to enable more fantomas * nowarn specific nullness when proto builds f.c.s and fsharpbuild --- .fantomasignore | 51 ----- Directory.Build.props | 2 +- FSharp.Profiles.props | 28 +-- src/Compiler/AbstractIL/il.fs | 144 ++++++++------ src/Compiler/AbstractIL/ilreflect.fs | 2 +- src/Compiler/AbstractIL/ilwrite.fs | 6 +- .../AssemblyResolveHandler.fsi | 2 +- .../DependencyManager/DependencyProvider.fs | 63 ++---- .../DependencyManager/DependencyProvider.fsi | 7 +- .../NativeDllResolveHandler.fsi | 2 +- src/Compiler/Driver/CompilerImports.fs | 181 ++++++++---------- src/Compiler/FSharp.Compiler.Service.fsproj | 5 +- src/Compiler/Facilities/AsyncMemoize.fs | 181 +++++++++++------- src/Compiler/Facilities/AsyncMemoize.fsi | 9 +- src/Compiler/Symbols/SymbolHelpers.fs | 2 - src/Compiler/TypedTree/QuotationPickler.fs | 6 +- src/Compiler/TypedTree/TypeProviders.fs | 63 +----- src/Compiler/TypedTree/TypeProviders.fsi | 94 +++------ src/Compiler/TypedTree/TypedTreeOps.fs | 13 +- src/Compiler/TypedTree/tainted.fs | 5 - src/Compiler/TypedTree/tainted.fsi | 8 +- src/Compiler/Utilities/Activity.fs | 19 +- src/Compiler/Utilities/Activity.fsi | 6 +- src/Compiler/Utilities/Cancellable.fsi | 9 +- src/Compiler/Utilities/HashMultiMap.fs | 6 +- src/Compiler/Utilities/HashMultiMap.fsi | 10 +- src/Compiler/Utilities/LruCache.fs | 12 +- src/Compiler/Utilities/LruCache.fsi | 9 +- src/Compiler/Utilities/NullnessShims.fs | 57 ++---- src/Compiler/Utilities/illib.fs | 80 ++++---- src/Compiler/Utilities/illib.fsi | 61 ++---- src/Compiler/Utilities/lib.fsi | 7 +- src/Compiler/Utilities/sformat.fs | 21 +- src/FSharp.Build/FSharp.Build.fsproj | 6 +- src/FSharp.Build/FSharpCommandLineBuilder.fs | 13 +- src/FSharp.Build/FSharpEmbedResourceText.fs | 7 +- src/FSharp.Core/array.fs | 35 ++-- src/FSharp.Core/fslib-extra-pervasives.fs | 14 +- src/FSharp.Core/local.fs | 5 +- src/FSharp.Core/option.fs | 40 +--- src/FSharp.Core/option.fsi | 32 +--- src/FSharp.Core/prim-types-prelude.fs | 4 - src/FSharp.Core/prim-types-prelude.fsi | 4 - src/FSharp.Core/prim-types.fs | 28 +-- src/FSharp.Core/prim-types.fsi | 32 +--- src/FSharp.Core/resumable.fs | 45 ++--- src/FSharp.Core/tasks.fs | 78 +++----- src/FSharp.Core/tasks.fsi | 2 +- src/fsi/console.fs | 8 +- ...y_FSharp.Compiler.Service_Debug_net9.0.bsl | 4 +- ....Compiler.Service_Debug_netstandard2.0.bsl | 8 +- ...FSharp.Compiler.Service_Release_net9.0.bsl | 2 +- ...ompiler.Service_Release_netstandard2.0.bsl | 8 +- ...erify_FSharp.Core_Debug_netstandard2.0.bsl | 4 +- ...erify_FSharp.Core_Debug_netstandard2.1.bsl | 4 +- ...ify_FSharp.Core_Release_netstandard2.0.bsl | 4 +- ...ify_FSharp.Core_Release_netstandard2.1.bsl | 4 +- 57 files changed, 567 insertions(+), 995 deletions(-) diff --git a/.fantomasignore b/.fantomasignore index f5798fbdf00..c2677d44fa4 100644 --- a/.fantomasignore +++ b/.fantomasignore @@ -40,19 +40,6 @@ src/Compiler/Checking/SignatureConformance.fs src/Compiler/Checking/TypeHierarchy.fs src/Compiler/Checking/TypeRelations.fs -# nullness-related problems -src/Compiler/Utilities/lib.fsi -src/Compiler/Utilities/Cancellable.fsi -src/FSharp.Core/tasks.fsi -src/FSharp.Core/tasks.fs -src/FSharp.Core/resumable.fs -src/Compiler/DependencyManager/DependencyProvider.fs -src/FSharp.Core/fslib-extra-pervasives.fs -src/FSharp.Core/fslib-extra-pervasives.fsi - -# Incorrectly formatted: https://github.com/dotnet/fsharp/pull/14645/commits/49443a67ea8a17670c8a7c80c8bdf91f82231e91 or https://github.com/fsprojects/fantomas/issues/2733 -# This CompilerImports.fs behavior is not fixed yet, following up in https://github.com/fsprojects/fantomas/issues/2733 -src/Compiler/Driver/CompilerImports.fs # The following files were formatted, but the "format, --check" loop is not stable. # Fantomas formats them, but still thinks they need formatting src/Compiler/Optimize/DetupleArgs.fs @@ -96,44 +83,6 @@ src/FSharp.Core/printf.fs src/FSharp.Core/Query.fs src/FSharp.Core/seqcore.fs - -# fsharp (to investigate) - -**/TypeProviders.fsi -**/tainted.fsi - -# uses nullness features - -**/DependencyProvider.fsi -src/FSharp.Core/array.fs -src/FSharp.Core/option.fsi -src/FSharp.Core/option.fs -src/fsi/console.fs -src/FSharp.Build/FSharpCommandLineBuilder.fs - -src/Compiler/Utilities/Activity.fs -src/Compiler/Utilities/sformat.fs -src/Compiler/Utilities/illib.fsi -src/Compiler/Utilities/illib.fs - - -src/Compiler/Utilities/NullnessShims.fs -src/Compiler/Utilities/DependencyGraph.fs -src/Compiler/Utilities/LruCache.fsi -src/Compiler/Utilities/LruCache.fs -src/Compiler/Utilities/HashMultiMap.fsi -src/Compiler/Utilities/HashMultiMap.fs -src/Compiler/Facilities/AsyncMemoize.fsi -src/Compiler/Facilities/AsyncMemoize.fs -src/Compiler/AbstractIL/il.fs -src/Compiler/SyntaxTree/LexerStore.fs - -src/Compiler/Driver/GraphChecking/Graph.fsi -src/Compiler/Driver/GraphChecking/Graph.fs - -src/Compiler/DependencyManager/NativeDllResolveHandler.fsi -src/Compiler/DependencyManager/AssemblyResolveHandler.fsi - # Fantomas limitations on implementation files (to investigate) src/Compiler/AbstractIL/ilwrite.fs diff --git a/Directory.Build.props b/Directory.Build.props index c4f2bff9287..fbb9c8332c7 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -62,7 +62,7 @@ since it's a non-arcade and non-sourcebuild scenario --> $(ArtifactsDir)/bin/fslex/$(Configuration)/$(FSharpNetCoreProductDefaultTargetFramework)/$(RuntimeIdentifier)/fslex.dll $(ArtifactsDir)/bin/fsyacc/$(Configuration)/$(FSharpNetCoreProductDefaultTargetFramework)/$(RuntimeIdentifier)/fsyacc.dll - NO_CHECKNULLS;BUILDING_WITH_LKG;NO_NULLCHECKING_LIB_SUPPORT;$(DefineConstants) + BUILDING_WITH_LKG;$(DefineConstants) diff --git a/FSharp.Profiles.props b/FSharp.Profiles.props index 186875ad357..35a907b2e6f 100644 --- a/FSharp.Profiles.props +++ b/FSharp.Profiles.props @@ -1,41 +1,15 @@ - - - - false - - - - - false - - false - NO_CHECKNULLS;BUILDING_WITH_LKG;NO_NULLCHECKING_LIB_SUPPORT;$(DefineConstants) - false + BUILDING_WITH_LKG;$(DefineConstants) preview - - false - - - - enable - - - - - $(NoWarn);3271 - NO_CHECKNULLS;$(DefineConstants) - - diff --git a/src/Compiler/AbstractIL/il.fs b/src/Compiler/AbstractIL/il.fs index 33a46ff0a23..d0770b414ed 100644 --- a/src/Compiler/AbstractIL/il.fs +++ b/src/Compiler/AbstractIL/il.fs @@ -170,11 +170,8 @@ let splitTypeNameRight nm = // -------------------------------------------------------------------- /// This is used to store event, property and field maps. -type LazyOrderedMultiMap<'Key, 'Data when 'Key: equality -#if !NO_CHECKNULLS - and 'Key:not null -#endif - >(keyf: 'Data -> 'Key, lazyItems: InterruptibleLazy<'Data list>) = +type LazyOrderedMultiMap<'Key, 'Data when 'Key: equality and 'Key: not null>(keyf: 'Data -> 'Key, lazyItems: InterruptibleLazy<'Data list>) + = let quickMap = lazyItems @@ -519,7 +516,11 @@ type ILAssemblyRef(data) = let retargetable = aname.Flags = AssemblyNameFlags.Retargetable - let name = match aname.Name with | null -> aname.FullName | name -> name + let name = + match aname.Name with + | null -> aname.FullName + | name -> name + ILAssemblyRef.Create(name, None, publicKey, retargetable, version, locale) member aref.QualifiedName = @@ -1862,7 +1863,7 @@ type ILGenericParameterDef = Name: string Constraints: ILTypes Variance: ILGenericVariance - HasReferenceTypeConstraint: bool + HasReferenceTypeConstraint: bool HasNotNullableValueTypeConstraint: bool HasDefaultConstructorConstraint: bool HasAllowsRefStruct: bool @@ -1910,7 +1911,11 @@ let inline conditionalAdd condition flagToAdd source = let NoMetadataIdx = -1 type InterfaceImpl = - { Idx: int; Type: ILType; mutable CustomAttrsStored: ILAttributesStored } + { + Idx: int + Type: ILType + mutable CustomAttrsStored: ILAttributesStored + } member x.CustomAttrs = match x.CustomAttrsStored with @@ -1919,12 +1924,16 @@ type InterfaceImpl = x.CustomAttrsStored <- ILAttributesStored.Given res res | ILAttributesStored.Given attrs -> attrs - - static member Create(ilType: ILType, customAttrsStored: ILAttributesStored) = - { Idx = NoMetadataIdx; Type = ilType; CustomAttrsStored = customAttrsStored } - static member Create(ilType: ILType) = InterfaceImpl.Create(ilType, emptyILCustomAttrsStored) + static member Create(ilType: ILType, customAttrsStored: ILAttributesStored) = + { + Idx = NoMetadataIdx + Type = ilType + CustomAttrsStored = customAttrsStored + } + static member Create(ilType: ILType) = + InterfaceImpl.Create(ilType, emptyILCustomAttrsStored) [] type ILMethodDef @@ -2575,17 +2584,15 @@ type ILTypeDefAdditionalFlags = | CanContainExtensionMethods = 1024 let internal typeKindFlags = - ILTypeDefAdditionalFlags.Class ||| - ILTypeDefAdditionalFlags.ValueType ||| - ILTypeDefAdditionalFlags.Interface ||| - ILTypeDefAdditionalFlags.Enum ||| - ILTypeDefAdditionalFlags.Delegate + ILTypeDefAdditionalFlags.Class + ||| ILTypeDefAdditionalFlags.ValueType + ||| ILTypeDefAdditionalFlags.Interface + ||| ILTypeDefAdditionalFlags.Enum + ||| ILTypeDefAdditionalFlags.Delegate -let inline internal resetTypeKind flags = - flags &&& ~~~typeKindFlags +let inline internal resetTypeKind flags = flags &&& ~~~typeKindFlags -let (|HasFlag|_|) (flag: ILTypeDefAdditionalFlags) flags = - flags &&& flag = flag +let (|HasFlag|_|) (flag: ILTypeDefAdditionalFlags) flags = flags &&& flag = flag let inline typeKindByNames extendsName typeName = match extendsName with @@ -2676,21 +2683,24 @@ type ILTypeDef let hasFlag flag = additionalFlags &&& flag = flag - new(name, - attributes, - layout, - implements, - genericParams, - extends, - methods, - nestedTypes, - fields, - methodImpls, - events, - properties, - additionalFlags, - securityDecls, - customAttrs) = + new + ( + name, + attributes, + layout, + implements, + genericParams, + extends, + methods, + nestedTypes, + fields, + methodImpls, + events, + properties, + additionalFlags, + securityDecls, + customAttrs + ) = ILTypeDef( name, attributes, @@ -2710,23 +2720,27 @@ type ILTypeDef NoMetadataIdx ) - new(name, - attributes, - layout, - implements, - genericParams, - extends, - methods, - nestedTypes, - fields, - methodImpls, - events, - properties, - securityDecls, - customAttrs) = + new + ( + name, + attributes, + layout, + implements, + genericParams, + extends, + methods, + nestedTypes, + fields, + methodImpls, + events, + properties, + securityDecls, + customAttrs + ) = let additionalFlags = - ILTypeDefAdditionalFlags.CanContainExtensionMethods ||| - typeKindOfFlags name extends (int attributes) + ILTypeDefAdditionalFlags.CanContainExtensionMethods + ||| typeKindOfFlags name extends (int attributes) + ILTypeDef( name, attributes, @@ -2955,10 +2969,10 @@ and [] ILPreTypeDef = and [] ILPreTypeDefImpl(nameSpace: string list, name: string, metadataIndex: int32, storage: ILTypeDefStored) = let stored = lazy - match storage with - | ILTypeDefStored.Given td -> td - | ILTypeDefStored.Computed f -> f () - | ILTypeDefStored.Reader f -> f metadataIndex + match storage with + | ILTypeDefStored.Given td -> td + | ILTypeDefStored.Computed f -> f () + | ILTypeDefStored.Reader f -> f metadataIndex interface ILPreTypeDef with member _.Namespace = nameSpace @@ -4248,25 +4262,31 @@ let mkILStorageCtorWithParamNames (preblock: ILInstr list, ty, extraParams, flds | Some x -> I_seqpoint x | None -> () yield! preblock - for (n, (_pnm, nm, fieldTy,_attrs)) in List.indexed flds do + for (n, (_pnm, nm, fieldTy, _attrs)) in List.indexed flds do mkLdarg0 mkLdarg (uint16 (n + 1)) mkNormalStfld (mkILFieldSpecInTy (ty, nm, fieldTy)) ] let body = mkMethodBody (false, [], 2, nonBranchingInstrsToCode code, tag, imports) - let fieldParams = + + let fieldParams = [ - for (pnm,_,ty,attrs) in flds do + for (pnm, _, ty, attrs) in flds do let ilParam = mkILParamNamed (pnm, ty) + let ilParam = match attrs with | [] -> ilParam - | attrs -> {ilParam with CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs attrs ) } + | attrs -> + { ilParam with + CustomAttrsStored = storeILCustomAttrs (mkILCustomAttrs attrs) + } + yield ilParam - ] + ] - mkILCtor (access, fieldParams @ extraParams , body) + mkILCtor (access, fieldParams @ extraParams, body) let mkILSimpleStorageCtorWithParamNames (baseTySpec, ty, extraParams, flds, access, tag, imports) = let preblock = diff --git a/src/Compiler/AbstractIL/ilreflect.fs b/src/Compiler/AbstractIL/ilreflect.fs index 6151c28b8f0..ca309e95875 100644 --- a/src/Compiler/AbstractIL/ilreflect.fs +++ b/src/Compiler/AbstractIL/ilreflect.fs @@ -164,7 +164,7 @@ type TypeBuilder with printfn "typeBuilder%d.CreateType()" (abs <| hash typB) //Buggy annotation in ns20, will not be fixed. -#if NETSTANDARD && !NO_CHECKNULLS +#if NETSTANDARD !!(typB.CreateTypeInfo()) :> Type #else typB.CreateTypeInfo() :> Type diff --git a/src/Compiler/AbstractIL/ilwrite.fs b/src/Compiler/AbstractIL/ilwrite.fs index 2cb9bb01a1b..1d5111daa50 100644 --- a/src/Compiler/AbstractIL/ilwrite.fs +++ b/src/Compiler/AbstractIL/ilwrite.fs @@ -362,11 +362,7 @@ let envForOverrideSpec (ospec: ILOverridesSpec) = { EnclosingTyparCount=ospec.De //--------------------------------------------------------------------- [] -type MetadataTable<'T -#if !NO_CHECKNULLS - when 'T:not null -#endif - > = +type MetadataTable<'T when 'T:not null> = { name: string dict: Dictionary<'T, int> // given a row, find its entry number mutable rows: ResizeArray<'T> } diff --git a/src/Compiler/DependencyManager/AssemblyResolveHandler.fsi b/src/Compiler/DependencyManager/AssemblyResolveHandler.fsi index e1c0b2574e3..354eb07efd6 100644 --- a/src/Compiler/DependencyManager/AssemblyResolveHandler.fsi +++ b/src/Compiler/DependencyManager/AssemblyResolveHandler.fsi @@ -12,7 +12,7 @@ type AssemblyResolutionProbe = delegate of Unit -> seq type AssemblyResolveHandler = /// Construct a new DependencyProvider - new: assemblyProbingPaths: AssemblyResolutionProbe|null -> AssemblyResolveHandler + new: assemblyProbingPaths: AssemblyResolutionProbe | null -> AssemblyResolveHandler /// Construct a new DependencyProvider internal new: assemblyProbingPaths: AssemblyResolutionProbe option -> AssemblyResolveHandler diff --git a/src/Compiler/DependencyManager/DependencyProvider.fs b/src/Compiler/DependencyManager/DependencyProvider.fs index 6e641af607b..a94e296d465 100644 --- a/src/Compiler/DependencyManager/DependencyProvider.fs +++ b/src/Compiler/DependencyManager/DependencyProvider.fs @@ -123,9 +123,6 @@ type IResolveDependenciesResult = /// #I @"c:\somepath\to\packages\1.1.1\ResolvedPackage" abstract Roots: seq -#if NO_CHECKNULLS -[] -#endif type IDependencyManagerProvider = abstract Name: string abstract Key: string @@ -334,42 +331,36 @@ type ReflectionDependencyManagerProvider member _.StdOut = match getInstanceProperty (result.GetType()) "StdOut" with | None -> [||] - | Some p -> !! p.GetValue(result) :?> string[] + | Some p -> !!p.GetValue(result) :?> string[] /// The resolution error log (* process stderror *) member _.StdError = match getInstanceProperty (result.GetType()) "StdError" with | None -> [||] - | Some p -> !! p.GetValue(result) :?> string[] + | Some p -> !!p.GetValue(result) :?> string[] /// The resolution paths member _.Resolutions = match getInstanceProperty> (result.GetType()) "Resolutions" with | None -> Seq.empty - | Some p -> !! p.GetValue(result) :?> seq + | Some p -> !!p.GetValue(result) :?> seq /// The source code file paths member _.SourceFiles = match getInstanceProperty> (result.GetType()) "SourceFiles" with | None -> Seq.empty - | Some p -> !! p.GetValue(result) :?> seq + | Some p -> !!p.GetValue(result) :?> seq /// The roots to package directories member _.Roots = match getInstanceProperty> (result.GetType()) "Roots" with | None -> Seq.empty - | Some p -> !! p.GetValue(result) :?> seq + | Some p -> !!p.GetValue(result) :?> seq } static member MakeResultFromFields - ( - success: bool, - stdOut: string[], - stdError: string[], - resolutions: seq, - sourceFiles: seq, - roots: seq - ) = + (success: bool, stdOut: string[], stdError: string[], resolutions: seq, sourceFiles: seq, roots: seq) + = { new IResolveDependenciesResult with /// Succeeded? member _.Success = success @@ -409,16 +400,8 @@ type ReflectionDependencyManagerProvider /// Resolve the dependencies for the given arguments member _.ResolveDependencies - ( - scriptDir, - mainScriptName, - scriptName, - scriptExt, - packageManagerTextLines, - tfm, - rid, - timeout - ) : IResolveDependenciesResult = + (scriptDir, mainScriptName, scriptName, scriptExt, packageManagerTextLines, tfm, rid, timeout) + : IResolveDependenciesResult = // The ResolveDependencies method, has two signatures, the original signature in the variable resolveDeps and the updated signature resolveDepsEx // the resolve method can return values in two different tuples: // (bool * string list * string list * string list) @@ -564,7 +547,7 @@ type DependencyProvider new() = new DependencyProvider(None, None, true) /// Returns a formatted help messages for registered dependencymanagers for the host to present - member _.GetRegisteredDependencyManagerHelpText(compilerTools, outputDir : string | null, errorReport) = + member _.GetRegisteredDependencyManagerHelpText(compilerTools, outputDir: string | null, errorReport) = [| let managers = RegisteredDependencyManagers compilerTools (Option.ofString outputDir) errorReport @@ -575,7 +558,7 @@ type DependencyProvider |] /// Clear the DependencyManager results caches - member _.ClearResultsCache(compilerTools, outputDir : string | null, errorReport) = + member _.ClearResultsCache(compilerTools, outputDir: string | null, errorReport) = let managers = RegisteredDependencyManagers compilerTools (Option.ofString outputDir) errorReport @@ -584,12 +567,8 @@ type DependencyProvider /// Returns a formatted error message for the host to present member _.CreatePackageManagerUnknownError - ( - compilerTools: seq, - outputDir: string, - packageManagerKey: string, - reportError: ResolvingErrorReport - ) = + (compilerTools: seq, outputDir: string, packageManagerKey: string, reportError: ResolvingErrorReport) + = let registeredKeys = String.Join( ", ", @@ -602,12 +581,8 @@ type DependencyProvider /// Fetch a dependencymanager that supports a specific key member this.TryFindDependencyManagerInPath - ( - compilerTools: seq, - outputDir: string, - reportError: ResolvingErrorReport, - path: string - ) : string | null * IDependencyManagerProvider | null = + (compilerTools: seq, outputDir: string, reportError: ResolvingErrorReport, path: string) + : string | null * IDependencyManagerProvider | null = try if path.Contains ":" && not (Path.IsPathRooted path) then let managers = @@ -632,12 +607,8 @@ type DependencyProvider /// Fetch a dependencymanager that supports a specific key member _.TryFindDependencyManagerByKey - ( - compilerTools: seq, - outputDir: string, - reportError: ResolvingErrorReport, - key: string - ) : IDependencyManagerProvider | null = + (compilerTools: seq, outputDir: string, reportError: ResolvingErrorReport, key: string) + : IDependencyManagerProvider | null = try RegisteredDependencyManagers compilerTools (Option.ofString outputDir) reportError |> Map.tryFind key diff --git a/src/Compiler/DependencyManager/DependencyProvider.fsi b/src/Compiler/DependencyManager/DependencyProvider.fsi index aa1bd27d5b7..1fe1c400525 100644 --- a/src/Compiler/DependencyManager/DependencyProvider.fsi +++ b/src/Compiler/DependencyManager/DependencyProvider.fsi @@ -39,9 +39,6 @@ type IResolveDependenciesResult = abstract Roots: seq /// Wraps access to a DependencyManager implementation -#if NO_CHECKNULLS -[] -#endif type IDependencyManagerProvider = /// Name of the dependency manager @@ -123,7 +120,7 @@ type DependencyProvider = packageManagerTextLines: (string * string) seq * reportError: ResolvingErrorReport * executionTfm: string * - [] executionRid: string MaybeNull* + [] executionRid: string MaybeNull * [] implicitIncludeDir: string * [] mainScriptName: string * [] fileName: string * @@ -138,4 +135,4 @@ type DependencyProvider = /// TryFindDependencyManagerInPath - given a #r "key:sometext" go and find a DependencyManager that satisfies the key member TryFindDependencyManagerInPath: compilerTools: string seq * outputDir: string * reportError: ResolvingErrorReport * path: string -> - string | null * IDependencyManagerProvider | null \ No newline at end of file + string | null * IDependencyManagerProvider | null diff --git a/src/Compiler/DependencyManager/NativeDllResolveHandler.fsi b/src/Compiler/DependencyManager/NativeDllResolveHandler.fsi index 9d2961aa94e..e9d623df7bd 100644 --- a/src/Compiler/DependencyManager/NativeDllResolveHandler.fsi +++ b/src/Compiler/DependencyManager/NativeDllResolveHandler.fsi @@ -12,7 +12,7 @@ type NativeResolutionProbe = delegate of Unit -> seq type NativeDllResolveHandler = /// Construct a new NativeDllResolveHandler - new: nativeProbingRoots: NativeResolutionProbe|null -> NativeDllResolveHandler + new: nativeProbingRoots: NativeResolutionProbe | null -> NativeDllResolveHandler /// Construct a new NativeDllResolveHandler internal new: nativeProbingRoots: NativeResolutionProbe option -> NativeDllResolveHandler diff --git a/src/Compiler/Driver/CompilerImports.fs b/src/Compiler/Driver/CompilerImports.fs index ae14ee51157..4ab1ca3d7e4 100644 --- a/src/Compiler/Driver/CompilerImports.fs +++ b/src/Compiler/Driver/CompilerImports.fs @@ -94,20 +94,22 @@ let GetSignatureDataResourceName (r: ILResource) = failwith "unreachable" let GetResourceNameAndSignatureDataFuncs (resources: ILResource list) = - [ for r in resources do - if IsSignatureDataResource r then - let readerA, ccuName = GetSignatureDataResourceName r - - let readerB = - resources |> List.tryPick (fun rB -> - if IsSignatureDataResourceB rB then - let readerB, ccuNameB = GetSignatureDataResourceName rB - if ccuName = ccuNameB then - Some readerB - else None - else None) + [ + for r in resources do + if IsSignatureDataResource r then + let readerA, ccuName = GetSignatureDataResourceName r + + let readerB = + resources + |> List.tryPick (fun rB -> + if IsSignatureDataResourceB rB then + let readerB, ccuNameB = GetSignatureDataResourceName rB + if ccuName = ccuNameB then Some readerB else None + else + None) - ccuName, (readerA, readerB) ] + ccuName, (readerA, readerB) + ] let GetOptimizationDataResourceName (r: ILResource) = if r.Name.StartsWithOrdinal FSharpOptimizationDataResourceName then @@ -124,19 +126,22 @@ let GetOptimizationDataResourceName (r: ILResource) = failwith $"GetOptimizationDataResourceName - {r.Name}" let GetResourceNameAndOptimizationDataFuncs (resources: ILResource list) = - [ for r in resources do - if IsOptimizationDataResource r then - let readerA, ccuName = GetOptimizationDataResourceName r - - let readerB = - resources |> List.tryPick (fun rB -> - if IsOptimizationDataResourceB rB then - let readerB, ccuNameB = GetOptimizationDataResourceName rB - if ccuName = ccuNameB then - Some readerB - else None - else None) - ccuName, (readerA, readerB) ] + [ + for r in resources do + if IsOptimizationDataResource r then + let readerA, ccuName = GetOptimizationDataResourceName r + + let readerB = + resources + |> List.tryPick (fun rB -> + if IsOptimizationDataResourceB rB then + let readerB, ccuNameB = GetOptimizationDataResourceName rB + if ccuName = ccuNameB then Some readerB else None + else + None) + + ccuName, (readerA, readerB) + ] let IsReflectedDefinitionsResource (r: ILResource) = r.Name.StartsWithOrdinal(QuotationPickler.SerializedReflectedDefinitionsResourceNameBase) @@ -163,7 +168,7 @@ let PickleToResource inMem file (g: TcGlobals) compress scope rName rNameB p x = let byteStorage = ByteStorage.FromByteArray(bytes) let byteStorageB = - if inMem then + if inMem then ByteStorage.FromMemoryAndCopy(bytesB.AsMemory(), useBackingMemoryMappedFile = true) else ByteStorage.FromByteArray(bytesB.AsMemory().ToArray()) @@ -478,27 +483,28 @@ let isHashRReference (r: range) = && not (equals r rangeCmdArgs) && FileSystem.IsPathRootedShim r.FileName -let IsNetModule (fileName:string) = +let IsNetModule (fileName: string) = let ext = Path.GetExtension fileName String.Compare(ext, ".netmodule", StringComparison.OrdinalIgnoreCase) = 0 -let IsDLL (fileName:string) = +let IsDLL (fileName: string) = let ext = Path.GetExtension fileName String.Compare(ext, ".dll", StringComparison.OrdinalIgnoreCase) = 0 -let IsExe (fileName:string) = +let IsExe (fileName: string) = let ext = Path.GetExtension fileName String.Compare(ext, ".exe", StringComparison.OrdinalIgnoreCase) = 0 -let addConstraintSources(ia: ImportedAssembly) = +let addConstraintSources (ia: ImportedAssembly) = let contents = ia.FSharpViewOfMetadata.Contents + let addCxsToMember name (v: Val) = for typar in fst v.GeneralizedType do for cx in typar.Constraints do match cx with - | TyparConstraint.MayResolveMember(TTrait(source=source), _) -> - source.Value <- Some name + | TyparConstraint.MayResolveMember(TTrait(source = source), _) -> source.Value <- Some name | _ -> () + let rec addCxsToModule name (m: ModuleOrNamespaceType) = for e in m.ModuleAndNamespaceDefinitions do if e.IsModuleOrNamespace then @@ -506,8 +512,12 @@ let addConstraintSources(ia: ImportedAssembly) = if String.length name > 0 then name + "." + e.DisplayName elif e.IsModule then e.DisplayName else "" + addCxsToModule mname e.ModuleOrNamespaceType - for memb in m.AllValsAndMembers do addCxsToMember (name + "." + memb.LogicalName) memb + + for memb in m.AllValsAndMembers do + addCxsToMember (name + "." + memb.LogicalName) memb + addCxsToModule "" contents.ModuleOrNamespaceType type TcConfig with @@ -541,7 +551,7 @@ type TcConfig with yield! tcConfig.GetSearchPathsForLibraryFiles() if isHashRReference m then - !! Path.GetDirectoryName(m.FileName) + !!Path.GetDirectoryName(m.FileName) } let resolved = TryResolveFileUsingPaths(searchPaths, m, nm) @@ -629,12 +639,8 @@ type TcConfig with // // NOTE!! if mode=ReportErrors then this method must not raise exceptions. It must just report the errors and recover static member TryResolveLibsUsingMSBuildRules - ( - tcConfig: TcConfig, - originalReferences: AssemblyReference list, - errorAndWarningRange: range, - mode: ResolveAssemblyReferenceMode - ) : AssemblyResolution list * UnresolvedAssemblyReference list = + (tcConfig: TcConfig, originalReferences: AssemblyReference list, errorAndWarningRange: range, mode: ResolveAssemblyReferenceMode) + : AssemblyResolution list * UnresolvedAssemblyReference list = use _ = UseBuildPhase BuildPhase.Parameter @@ -798,11 +804,8 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, originalReferenceToResolution.TryFind nm static member ResolveAssemblyReferences - ( - tcConfig: TcConfig, - assemblyList: AssemblyReference list, - knownUnresolved: UnresolvedAssemblyReference list - ) : TcAssemblyResolutions = + (tcConfig: TcConfig, assemblyList: AssemblyReference list, knownUnresolved: UnresolvedAssemblyReference list) + : TcAssemblyResolutions = let resolved, unresolved = if tcConfig.useSimpleResolution then let resolutions = @@ -899,7 +902,7 @@ type TcAssemblyResolutions(tcConfig: TcConfig, results: AssemblyResolution list, let addedText = "\nIf you want to debug this right now, attach a debugger, and put a breakpoint in 'CompileOps.fs' near the text '!itFailed', and you can re-step through the assembly resolution logic." - for UnresolvedAssemblyReference (referenceText, _ranges) in unresolved do + for UnresolvedAssemblyReference(referenceText, _ranges) in unresolved do if referenceText.Contains("mscorlib") then Debug.Assert(false, sprintf "whoops, did not resolve mscorlib: '%s'%s" referenceText addedText) itFailed <- true @@ -989,7 +992,7 @@ type RawFSharpAssemblyDataBackedByFileOnDisk(ilModule: ILModuleDef, ilAssemblyRe let sigDataReaders = if sigDataReaders.IsEmpty && List.contains ilShortAssemName externalSigAndOptData then - let sigFileName = !! Path.ChangeExtension(fileName, "sigdata") + let sigFileName = !!Path.ChangeExtension(fileName, "sigdata") if not (FileSystem.FileExistsShim sigFileName) then error (Error(FSComp.SR.buildExpectedSigdataFile (FileSystem.GetFullPathShim sigFileName), m)) @@ -1014,7 +1017,7 @@ type RawFSharpAssemblyDataBackedByFileOnDisk(ilModule: ILModuleDef, ilAssemblyRe // Look for optimization data in a file let optDataReaders = if optDataReaders.IsEmpty && List.contains ilShortAssemName externalSigAndOptData then - let optDataFile = !! Path.ChangeExtension(fileName, "optdata") + let optDataFile = !!Path.ChangeExtension(fileName, "optdata") if not (FileSystem.FileExistsShim optDataFile) then error ( @@ -1097,11 +1100,7 @@ type RawFSharpAssemblyData(ilModule: ILModuleDef, ilAssemblyRefs) = [] type TcImportsSafeDisposal - ( - tciLock: TcImportsLock, - disposeActions: ResizeArray unit>, - disposeTypeProviderActions: ResizeArray unit> - ) = + (tciLock: TcImportsLock, disposeActions: ResizeArray unit>, disposeTypeProviderActions: ResizeArray unit>) = let mutable isDisposed = false @@ -1194,7 +1193,7 @@ type TcImportsWeakFacade(tciLock: TcImportsLock, tcImportsWeak: WeakReference match tcImports.Base with - | Some (baseTcImports: TcImports) -> Some baseTcImports.Weak + | Some(baseTcImports: TcImports) -> Some baseTcImports.Weak | _ -> None | _ -> None @@ -1218,11 +1217,11 @@ and [] TcImports initialResolutions: TcAssemblyResolutions, importsBase: TcImports option, dependencyProviderOpt: DependencyProvider option - ) + ) #if !NO_TYPEPROVIDERS as this #endif - = + = let tciLock = TcImportsLock() @@ -1298,7 +1297,7 @@ and [] TcImports if publicOnly then match e.TypeReprInfo with | TILObjectRepr data -> - let (TILObjectReprData (_, _, tyDef)) = data + let (TILObjectReprData(_, _, tyDef)) = data tyDef.Access = ILTypeDefAccess.Public | _ -> false else @@ -1433,14 +1432,14 @@ and [] TcImports CheckDisposed() match tcImports.FindCcuInfo(ctok, m, assemblyName, lookupOnly) with - | ResolvedImportedAssembly (importedAssembly, _) -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) - | UnresolvedImportedAssembly (assemblyName, _) -> UnresolvedCcu assemblyName + | ResolvedImportedAssembly(importedAssembly, _) -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) + | UnresolvedImportedAssembly(assemblyName, _) -> UnresolvedCcu assemblyName member tcImports.FindCcuFromAssemblyRef(ctok, m, assemblyRef: ILAssemblyRef) = CheckDisposed() match tcImports.FindCcuInfo(ctok, m, assemblyRef.Name, lookupOnly = false) with - | ResolvedImportedAssembly (importedAssembly, _) -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) + | ResolvedImportedAssembly(importedAssembly, _) -> ResolvedCcu(importedAssembly.FSharpViewOfMetadata) | UnresolvedImportedAssembly _ -> UnresolvedCcu(assemblyRef.QualifiedName) member tcImports.TryFindXmlDocumentationInfo(assemblyName: string) = @@ -1562,7 +1561,7 @@ and [] TcImports member _.RecordGeneratedTypeRoot root = tciLock.AcquireLock(fun tcitok -> // checking if given ProviderGeneratedType was already recorded before (probably for another set of static parameters) - let (ProviderGeneratedType (_, ilTyRef, _)) = root + let (ProviderGeneratedType(_, ilTyRef, _)) = root let index = RequireTcImportsLock(tcitok, generatedTypeRoots) @@ -1810,7 +1809,7 @@ and [] TcImports | TNoRepr -> TProvidedNamespaceRepr(typeProviderEnvironment, [ provider ]) // Add to the existing list of extensions - | TProvidedNamespaceRepr (resolutionFolder, prior) as repr -> + | TProvidedNamespaceRepr(resolutionFolder, prior) as repr -> if not (prior |> List.exists (fun r -> Tainted.EqTainted r provider)) then TProvidedNamespaceRepr(resolutionFolder, provider :: prior) else @@ -1860,7 +1859,7 @@ and [] TcImports |> Option.get // MSDN: this method causes the file to be opened and closed, but the assembly is not added to this domain let name = AssemblyName.GetAssemblyName(resolution.resolvedPath) - !! name.Version + !!name.Version // Note, this only captures systemRuntimeContainsTypeRef (which captures tcImportsWeak, using name tcImports) let systemRuntimeContainsType = @@ -1869,8 +1868,7 @@ and [] TcImports // The name of this captured value must not change, see comments on TcImportsWeakFacade above assert (nameof (tcImports) = "tcImports") - let mutable systemRuntimeContainsTypeRef = - tcImports.SystemRuntimeContainsType + let mutable systemRuntimeContainsTypeRef = tcImports.SystemRuntimeContainsType // When the tcImports is disposed the systemRuntimeContainsTypeRef thunk is replaced // with one raising an exception. @@ -1961,7 +1959,7 @@ and [] TcImports match providers with | [] -> - let typeName = !! typeof.FullName + let typeName = !!typeof.FullName warning (Error(FSComp.SR.etHostingAssemblyFoundWithoutHosts (fileNameOfRuntimeAssembly, typeName), m)) | _ -> @@ -2122,7 +2120,7 @@ and [] TcImports let minfo: PickledCcuInfo = data.RawData let mspec = minfo.mspec - + if mspec.DisplayName = "FSharp.Core" then updateSeqTypeIsPrefix mspec @@ -2167,7 +2165,7 @@ and [] TcImports InterruptibleLazy(fun _ -> match Map.tryFind ccuName optDatas with | None -> None - | Some (readerA, readerB) -> + | Some(readerA, readerB) -> let data = GetOptimizationData(fileName, ilScopeRef, ilModule.TryGetILModuleDef(), readerA, readerB) @@ -2182,8 +2180,8 @@ and [] TcImports if ccuThunk.IsUnresolvedReference then ccuThunks.Add(ccuThunk, (fun () -> fixupThunk () |> ignore))) - Some(fixupThunk ()) - ) + Some(fixupThunk ())) + let ccuinfo = { FSharpViewOfMetadata = ccu @@ -2250,10 +2248,8 @@ and [] TcImports // NOTE: When used in the Language Service this can cause the transitive checking of projects. Hence it must be cancellable. member tcImports.TryRegisterAndPrepareToImportReferencedDll - ( - ctok, - r: AssemblyResolution - ) : Async<(_ * (unit -> AvailableImportedAssembly list)) option> = + (ctok, r: AssemblyResolution) + : Async<(_ * (unit -> AvailableImportedAssembly list)) option> = async { CheckDisposed() let m = r.originalReference.Range @@ -2349,9 +2345,11 @@ and [] TcImports let _dllinfos, phase2s = results |> Array.choose id |> List.ofArray |> List.unzip fixupOrphanCcus () let ccuinfos = List.collect (fun phase2 -> phase2 ()) phase2s + if importsBase.IsSome then importsBase.Value.CcuTable.Values |> Seq.iter addConstraintSources ccuTable.Values |> Seq.iter addConstraintSources + return ccuinfos } @@ -2374,7 +2372,7 @@ and [] TcImports ) match foundFile with - | OkResult (warns, res) -> + | OkResult(warns, res) -> ReportWarnings warns tcImports.RegisterAndImportReferencedAssemblies(ctok, res) @@ -2382,7 +2380,7 @@ and [] TcImports |> ignore true - | ErrorResult (_warns, _err) -> + | ErrorResult(_warns, _err) -> // Throw away warnings and errors - this is speculative loading false @@ -2418,11 +2416,8 @@ and [] TcImports |> Option.map (fun r -> r.resolvedPath)) member _.TryResolveAssemblyReference - ( - ctok, - assemblyReference: AssemblyReference, - mode: ResolveAssemblyReferenceMode - ) : OperationResult = + (ctok, assemblyReference: AssemblyReference, mode: ResolveAssemblyReferenceMode) + : OperationResult = tciLock.AcquireLock(fun tcitok -> let tcConfig = tcConfigP.Get ctok @@ -2462,8 +2457,7 @@ and [] TcImports | [], [] -> // Note, if mode=ResolveAssemblyReferenceMode.Speculative and the resolution failed then TryResolveLibsUsingMSBuildRules returns // the empty list and we convert the failure into an AssemblyNotResolved here. - ErrorD(AssemblyNotResolved(assemblyReference.Text, assemblyReference.Range)) - ) + ErrorD(AssemblyNotResolved(assemblyReference.Text, assemblyReference.Range))) member tcImports.ResolveAssemblyReference(ctok, assemblyReference, mode) : AssemblyResolution list = CommitOperationResult(tcImports.TryResolveAssemblyReference(ctok, assemblyReference, mode)) @@ -2507,7 +2501,7 @@ and [] TcImports let primaryScopeRef = match primaryAssem with - | [ ResolvedImportedAssembly (ccu, _) ] -> ccu.FSharpViewOfMetadata.ILScopeRef + | [ ResolvedImportedAssembly(ccu, _) ] -> ccu.FSharpViewOfMetadata.ILScopeRef | _ -> failwith "primaryScopeRef - unexpected" let resolvedAssemblies = tcResolutions.GetAssemblyResolutions() @@ -2568,7 +2562,7 @@ and [] TcImports match resolvedAssemblyRef with | Some coreLibraryResolution -> match! frameworkTcImports.RegisterAndImportReferencedAssemblies(ctok, [ coreLibraryResolution ]) with - | [ ResolvedImportedAssembly (fslibCcuInfo, _) ] -> + | [ ResolvedImportedAssembly(fslibCcuInfo, _) ] -> return fslibCcuInfo.FSharpViewOfMetadata, fslibCcuInfo.ILScopeRef | _ -> return @@ -2633,17 +2627,12 @@ and [] TcImports knownUnresolved |> List.map (function - | UnresolvedAssemblyReference (file, originalReferences) -> file, originalReferences) + | UnresolvedAssemblyReference(file, originalReferences) -> file, originalReferences) |> List.iter reportAssemblyNotResolved static member BuildNonFrameworkTcImports - ( - tcConfigP: TcConfigProvider, - baseTcImports, - nonFrameworkReferences, - knownUnresolved, - dependencyProvider - ) = + (tcConfigP: TcConfigProvider, baseTcImports, nonFrameworkReferences, knownUnresolved, dependencyProvider) + = async { let ctok = CompilationThreadToken() @@ -2700,8 +2689,8 @@ let RequireReferences (ctok, tcImports: TcImports, tcEnv, thisAssemblyName, reso let asms = ccuinfos |> List.map (function - | ResolvedImportedAssembly (asm, m) -> asm, m - | UnresolvedImportedAssembly (assemblyName, m) -> error (Error(FSComp.SR.buildCouldNotResolveAssembly (assemblyName), m))) + | ResolvedImportedAssembly(asm, m) -> asm, m + | UnresolvedImportedAssembly(assemblyName, m) -> error (Error(FSComp.SR.buildCouldNotResolveAssembly (assemblyName), m))) let g = tcImports.GetTcGlobals() let amap = tcImports.GetImportMap() diff --git a/src/Compiler/FSharp.Compiler.Service.fsproj b/src/Compiler/FSharp.Compiler.Service.fsproj index ca08c3f63d9..75c03890c7d 100644 --- a/src/Compiler/FSharp.Compiler.Service.fsproj +++ b/src/Compiler/FSharp.Compiler.Service.fsproj @@ -15,7 +15,7 @@ FSharp.Compiler.Service true $(DefineConstants);COMPILER - true + enable $(OtherFlags) --warnon:3390 + + $(OtherFlags) --nowarn:3261 + $(OtherFlags) --generate-filter-blocks true diff --git a/src/Compiler/Facilities/AsyncMemoize.fs b/src/Compiler/Facilities/AsyncMemoize.fs index 991c8359312..a8a4d5b143f 100644 --- a/src/Compiler/Facilities/AsyncMemoize.fs +++ b/src/Compiler/Facilities/AsyncMemoize.fs @@ -21,17 +21,21 @@ type AsyncLazyState<'t> = /// When cacheException is false, subsequent requests will restart the computation after an exceptional result. type AsyncLazy<'t> private (initial: AsyncLazyState<'t>, cancelUnawaited: bool, cacheException: bool) = - let stateUpdateSync = obj() + let stateUpdateSync = obj () let mutable state = initial // This should remain the only function that mutates the state. let withStateUpdate f = - lock stateUpdateSync <| fun () -> + lock stateUpdateSync + <| fun () -> let next, result = f state state <- next result - let updateState f = withStateUpdate <| fun prev -> f prev, () - let cancelIfUnawaited cancelUnawaited = function + let updateState f = + withStateUpdate <| fun prev -> f prev, () + + let cancelIfUnawaited cancelUnawaited = + function | Running(computation, _, cts, 0) when cancelUnawaited -> // To keep state updates fast we don't actually wait for the work to cancel. // This means single execution is not strictly enforced. @@ -39,7 +43,8 @@ type AsyncLazy<'t> private (initial: AsyncLazyState<'t>, cancelUnawaited: bool, Initial computation | state -> state - let afterRequest = function + let afterRequest = + function | Running(c, work, cts, count) -> Running(c, work, cts, count - 1) |> cancelIfUnawaited cancelUnawaited | state -> state // Nothing more to do if state already transitioned. @@ -49,37 +54,42 @@ type AsyncLazy<'t> private (initial: AsyncLazyState<'t>, cancelUnawaited: bool, let! ct = Async.CancellationToken // Using ContinueWith with a CancellationToken allows detaching from the running 'work' task. // If the current async workflow is canceled, the 'work' task will continue running independently. - do! work.ContinueWith(ignore>, ct) |> Async.AwaitTask - with :? TaskCanceledException -> () + do! work.ContinueWith(ignore>, ct) |> Async.AwaitTask + with :? TaskCanceledException -> + () // If we're here it means there was no cancellation and the 'work' task has completed. return! work |> Async.AwaitTask } let onComplete (t: Task<'t>) = - updateState <| function - | Running (computation, _, _, _) -> - try Completed t.Result with exn -> if cacheException then Faulted exn else Initial computation + updateState + <| function + | Running(computation, _, _, _) -> + try + Completed t.Result + with exn -> + if cacheException then Faulted exn else Initial computation | state -> state + t.Result - let request = function + let request = + function | Initial computation -> let cts = new CancellationTokenSource() + let work = - Async.StartAsTask(computation, cancellationToken = cts.Token) + Async + .StartAsTask(computation, cancellationToken = cts.Token) .ContinueWith(onComplete, TaskContinuationOptions.NotOnCanceled) - Running (computation, work, cts, 1), - detachable work - | Running (c, work, cts, count) -> - Running (c, work, cts, count + 1), - detachable work - | Completed result as state -> - state, async { return result } - | Faulted exn as state -> - state, async { return raise exn } + + Running(computation, work, cts, 1), detachable work + | Running(c, work, cts, count) -> Running(c, work, cts, count + 1), detachable work + | Completed result as state -> state, async { return result } + | Faulted exn as state -> state, async { return raise exn } // computation will deallocate after state transition to Completed ot Faulted. - new (computation, ?cancelUnawaited: bool, ?cacheException) = + new(computation, ?cancelUnawaited: bool, ?cacheException) = AsyncLazy(Initial computation, defaultArg cancelUnawaited true, defaultArg cacheException true) member _.Request() = @@ -104,7 +114,7 @@ module internal Utils = /// Return file name with one directory above it let shortPath (path: string) = - let dirPath = !! Path.GetDirectoryName(path) + let dirPath = !!Path.GetDirectoryName(path) let dir = dirPath.Split Path.DirectorySeparatorChar @@ -126,7 +136,21 @@ type internal JobEvent = | Strengthened | Failed | Cleared - static member AllEvents = [Requested; Started; Restarted; Finished; Canceled; Evicted; Collected; Weakened; Strengthened; Failed; Cleared] + + static member AllEvents = + [ + Requested + Started + Restarted + Finished + Canceled + Evicted + Collected + Weakened + Strengthened + Failed + Cleared + ] type internal ICacheKey<'TKey, 'TVersion> = // TODO Key should probably be renamed to Identifier @@ -155,7 +179,8 @@ type private KeyData<'TKey, 'TVersion> = type Job<'t> = AsyncLazy * CapturingDiagnosticsLogger> [] -type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality and 'TKey:not null and 'TVersion:not null> +type internal AsyncMemoize<'TKey, 'TVersion, 'TValue + when 'TKey: equality and 'TVersion: equality and 'TKey: not null and 'TVersion: not null> (?keepStrongly, ?keepWeakly, ?name: string, ?cancelUnawaitedJobs: bool, ?cancelDuplicateRunningJobs: bool) = let name = defaultArg name "N/A" @@ -164,11 +189,12 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'T let event = Event<_>() - let eventCounts = [for j in JobEvent.AllEvents -> j, ref 0] |> dict + let eventCounts = [ for j in JobEvent.AllEvents -> j, ref 0 ] |> dict let mutable hits = 0 let mutable duration = 0L - let keyTuple (keyData: KeyData<_, _>) = keyData.Label, keyData.Key, keyData.Version + let keyTuple (keyData: KeyData<_, _>) = + keyData.Label, keyData.Key, keyData.Version let logK (eventType: JobEvent) key = Interlocked.Increment(eventCounts[eventType]) |> ignore @@ -186,7 +212,8 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'T | CacheEvent.Collected -> logK JobEvent.Collected | CacheEvent.Weakened -> logK JobEvent.Weakened | CacheEvent.Strengthened -> logK JobEvent.Strengthened - | CacheEvent.Cleared -> logK JobEvent.Cleared)) + | CacheEvent.Cleared -> logK JobEvent.Cleared) + ) member _.Get(key: ICacheKey<_, _>, computation) = let key = @@ -197,38 +224,44 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'T } let wrappedComputation = - Async.TryCancelled( async { - let sw = Stopwatch.StartNew() - log Started key - let logger = CapturingDiagnosticsLogger "cache" - SetThreadDiagnosticsLoggerNoUnwind logger - - match! computation |> Async.Catch with - | Choice1Of2 result -> - log Finished key - Interlocked.Add(&duration, sw.ElapsedMilliseconds) |> ignore - return Result.Ok result, logger - | Choice2Of2 exn -> - log Failed key - return Result.Error exn, logger - }, fun _ -> log Canceled key) + Async.TryCancelled( + async { + let sw = Stopwatch.StartNew() + log Started key + let logger = CapturingDiagnosticsLogger "cache" + SetThreadDiagnosticsLoggerNoUnwind logger + + match! computation |> Async.Catch with + | Choice1Of2 result -> + log Finished key + Interlocked.Add(&duration, sw.ElapsedMilliseconds) |> ignore + return Result.Ok result, logger + | Choice2Of2 exn -> + log Failed key + return Result.Error exn, logger + }, + fun _ -> log Canceled key + ) let getOrAdd () = let cached, otherVersions = cache.GetAll(key.Key, key.Version) - let countHit v = Interlocked.Increment &hits |> ignore; v + let countHit v = + Interlocked.Increment &hits |> ignore + v + let cacheSetNewJob () = - let job = Job(wrappedComputation, cancelUnawaited = cancelUnawaitedJobs, cacheException = false) + let job = + Job(wrappedComputation, cancelUnawaited = cancelUnawaitedJobs, cacheException = false) + cache.Set(key.Key, key.Version, key.Label, job) job otherVersions, - cached - |> Option.map countHit - |> Option.defaultWith cacheSetNewJob + cached |> Option.map countHit |> Option.defaultWith cacheSetNewJob - async { + async { let otherVersions, job = lock cache getOrAdd log Requested key @@ -240,15 +273,15 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'T let! result, logger = job.Request() logger.CommitDelayedDiagnostics DiagnosticsThreadStatics.DiagnosticsLogger + match result with - | Ok result -> - return result - | Error exn -> - return raise exn + | Ok result -> return result + | Error exn -> return raise exn } member _.TryGet(key: 'TKey, predicate: 'TVersion -> bool) : 'TValue option = - lock cache <| fun () -> + lock cache + <| fun () -> cache.GetAll(key) |> Seq.tryPick (fun (version, job) -> match predicate version, job.TryResult with @@ -257,7 +290,8 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'T member _.Clear() = lock cache cache.Clear - member _.Clear predicate = lock cache <| fun () -> cache.Clear predicate + member _.Clear predicate = + lock cache <| fun () -> cache.Clear predicate member val Event = event.Publish @@ -267,26 +301,39 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'T member this.DebuggerDisplay = - let cachedJobs = cache.GetValues() |> Seq.map (fun (_,_,job) -> job) + let cachedJobs = cache.GetValues() |> Seq.map (fun (_, _, job) -> job) - let jobStateName = function - | Initial _ -> nameof Initial - | Running _ -> nameof Running - | Completed _ -> nameof Completed - | Faulted _ -> nameof Faulted + let jobStateName = + function + | Initial _ -> nameof Initial + | Running _ -> nameof Running + | Completed _ -> nameof Completed + | Faulted _ -> nameof Faulted let valueStats = cachedJobs |> Seq.countBy (_.State >> jobStateName) |> Map - let getStat key = valueStats.TryFind key |> Option.defaultValue 0 + + let getStat key = + valueStats.TryFind key |> Option.defaultValue 0 let running = let count = getStat "Running" - if count > 0 then $" Running {count}" else "" + if count > 0 then $" Running {count}" else "" let finished = eventCounts[Finished].Value - let avgDuration = if finished = 0 then "" else $"| Avg: %.0f{float duration / float finished} ms" + + let avgDuration = + if finished = 0 then + "" + else + $"| Avg: %.0f{float duration / float finished} ms" let requests = eventCounts[Requested].Value - let hitRatio = if requests = 0 then "" else $" (%.0f{float hits / (float (requests)) * 100.0} %%)" + + let hitRatio = + if requests = 0 then + "" + else + $" (%.0f{float hits / (float (requests)) * 100.0} %%)" let faulted = getStat "Faulted" let failed = eventCounts[Failed].Value @@ -295,9 +342,11 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'T seq { if faulted + failed > 0 then " (_!_) " + for j in eventCounts.Keys do let count = eventCounts[j].Value if count > 0 then $"| {j}: {count}" else "" + $"| hits: {hits}{hitRatio} " } |> String.concat "" @@ -317,4 +366,4 @@ type internal AsyncMemoizeDisabled<'TKey, 'TVersion, 'TValue when 'TKey: equalit Interlocked.Increment &requests |> ignore computation - member _.DebuggerDisplay = $"(disabled) requests: {requests}" \ No newline at end of file + member _.DebuggerDisplay = $"(disabled) requests: {requests}" diff --git a/src/Compiler/Facilities/AsyncMemoize.fsi b/src/Compiler/Facilities/AsyncMemoize.fsi index 6b9ffb4f433..1014dfc6874 100644 --- a/src/Compiler/Facilities/AsyncMemoize.fsi +++ b/src/Compiler/Facilities/AsyncMemoize.fsi @@ -42,7 +42,8 @@ type Extensions = /// /// Strongly holds at most one result per key. /// -type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality and 'TKey:not null and 'TVersion:not null> = +type internal AsyncMemoize<'TKey, 'TVersion, 'TValue + when 'TKey: equality and 'TVersion: equality and 'TKey: not null and 'TVersion: not null> = /// Maximum number of strongly held results to keep in the cache /// Maximum number of weakly held results to keep in the cache @@ -50,7 +51,11 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'T /// Cancels a job when all the awaiting requests are canceled. If set to false, unawaited job will run to completion and it's result will be cached. /// If true, when a job is started, all other jobs with the same key will be canceled. new: - ?keepStrongly: int * ?keepWeakly: int * ?name: string * ?cancelUnawaitedJobs: bool * ?cancelDuplicateRunningJobs: bool -> + ?keepStrongly: int * + ?keepWeakly: int * + ?name: string * + ?cancelUnawaitedJobs: bool * + ?cancelDuplicateRunningJobs: bool -> AsyncMemoize<'TKey, 'TVersion, 'TValue> member Clear: unit -> unit diff --git a/src/Compiler/Symbols/SymbolHelpers.fs b/src/Compiler/Symbols/SymbolHelpers.fs index 1fedee2968a..116e9ba95b7 100644 --- a/src/Compiler/Symbols/SymbolHelpers.fs +++ b/src/Compiler/Symbols/SymbolHelpers.fs @@ -406,12 +406,10 @@ module internal SymbolHelpers = //| _ -> false member x.Equals(item1, item2) = -#if !NO_CHECKNULLS match item1,item2 with | null,null -> true | null,_ | _,null -> false | item1,item2 -> -#endif // This may explore assemblies that are not in the reference set. // In this case just bail out and assume items are not equal protectAssemblyExploration false (fun () -> diff --git a/src/Compiler/TypedTree/QuotationPickler.fs b/src/Compiler/TypedTree/QuotationPickler.fs index f2a58203ec6..de18b73e5c0 100644 --- a/src/Compiler/TypedTree/QuotationPickler.fs +++ b/src/Compiler/TypedTree/QuotationPickler.fs @@ -249,11 +249,7 @@ let PickleBufferCapacity = 100000 module SimplePickle = - type Table<'T -#if !NO_CHECKNULLS - when 'T:not null -#endif - > = + type Table<'T when 'T:not null> = { tbl: HashMultiMap<'T, int> // This should be "Dictionary" mutable rows: 'T list mutable count: int } diff --git a/src/Compiler/TypedTree/TypeProviders.fs b/src/Compiler/TypedTree/TypeProviders.fs index 42caa723619..425e31ea453 100644 --- a/src/Compiler/TypedTree/TypeProviders.fs +++ b/src/Compiler/TypedTree/TypeProviders.fs @@ -220,13 +220,8 @@ let TryTypeMemberArray (st: Tainted<_>, fullName, memberName, m, f) = [||] /// Try to access a member on a provided type, catching and reporting errors and checking the result is non-null, -#if NO_CHECKNULLS -let TryTypeMemberNonNull<'T, 'U when 'U : null and 'U : not struct>(st: Tainted<'T>, fullName, memberName, m, recover: 'U, (f: 'T -> 'U)) : Tainted<'U> = - match TryTypeMember(st, fullName, memberName, m, recover, f) with -#else let TryTypeMemberNonNull<'T, 'U when 'U : not null and 'U : not struct>(st: Tainted<'T>, fullName, memberName, m, recover: 'U, (f: 'T -> 'U | null)) : Tainted<'U> = match TryTypeMember<'T, 'U | null>(st, fullName, memberName, m, withNull recover, f) with -#endif | Tainted.Null -> errorR(Error(FSComp.SR.etUnexpectedNullFromProvidedTypeMember(fullName, memberName), m)) st.PApplyNoFailure(fun _ -> recover) @@ -339,9 +334,6 @@ type ProvidedTypeContext = )) [] -#if NO_CHECKNULLS -[] -#endif type ProvidedType (x: Type, ctxt: ProvidedTypeContext) = inherit ProvidedMemberInfo(x, ctxt) @@ -506,9 +498,6 @@ type ProvidedType (x: Type, ctxt: ProvidedTypeContext) = static member TaintedEquals (pt1: Tainted, pt2: Tainted) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) -#if NO_CHECKNULLS -[] -#endif type IProvidedCustomAttributeProvider = abstract GetDefinitionLocationAttribute : provider: ITypeProvider -> (string MaybeNull * int * int) option @@ -569,9 +558,6 @@ type ProvidedCustomAttributeProvider (attributes :ITypeProvider -> seq Seq.toArray [] -#if NO_CHECKNULLS -[] -#endif type ProvidedMemberInfo (x: MemberInfo, ctxt) = let provide () = ProvidedCustomAttributeProvider (fun _ -> x.CustomAttributes) :> IProvidedCustomAttributeProvider @@ -594,9 +580,6 @@ type ProvidedMemberInfo (x: MemberInfo, ctxt) = provide().GetAttributeConstructorArgs (provider, attribName) [] -#if NO_CHECKNULLS -[] -#endif type ProvidedParameterInfo (x: ParameterInfo, ctxt) = let provide () = ProvidedCustomAttributeProvider (fun _ -> x.CustomAttributes) :> IProvidedCustomAttributeProvider @@ -645,9 +628,6 @@ type ProvidedParameterInfo (x: ParameterInfo, ctxt) = override _.GetHashCode() = assert false; x.GetHashCode() [] -#if NO_CHECKNULLS -[] -#endif type ProvidedAssembly (x: Assembly) = member _.GetName() = x.GetName() @@ -665,9 +645,6 @@ type ProvidedAssembly (x: Assembly) = override _.GetHashCode() = assert false; x.GetHashCode() [] -#if NO_CHECKNULLS -[] -#endif type ProvidedMethodBase (x: MethodBase, ctxt) = inherit ProvidedMemberInfo(x, ctxt) @@ -762,9 +739,6 @@ type ProvidedMethodBase (x: MethodBase, ctxt) = [] -#if NO_CHECKNULLS -[] -#endif type ProvidedFieldInfo (x: FieldInfo, ctxt) = inherit ProvidedMemberInfo(x, ctxt) @@ -812,9 +786,6 @@ type ProvidedFieldInfo (x: FieldInfo, ctxt) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) [] -#if NO_CHECKNULLS -[] -#endif type ProvidedMethodInfo (x: MethodInfo, ctxt) = inherit ProvidedMethodBase(x, ctxt) @@ -841,9 +812,6 @@ type ProvidedMethodInfo (x: MethodInfo, ctxt) = override _.GetHashCode() = assert false; x.GetHashCode() [] -#if NO_CHECKNULLS -[] -#endif type ProvidedPropertyInfo (x: PropertyInfo, ctxt) = inherit ProvidedMemberInfo(x, ctxt) @@ -885,9 +853,6 @@ type ProvidedPropertyInfo (x: PropertyInfo, ctxt) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) [] -#if NO_CHECKNULLS -[] -#endif type ProvidedEventInfo (x: EventInfo, ctxt) = inherit ProvidedMemberInfo(x, ctxt) @@ -923,9 +888,6 @@ type ProvidedEventInfo (x: EventInfo, ctxt) = Tainted.EqTainted (pt1.PApplyNoFailure(fun st -> st.Handle)) (pt2.PApplyNoFailure(fun st -> st.Handle)) [] -#if NO_CHECKNULLS -[] -#endif type ProvidedConstructorInfo (x: ConstructorInfo, ctxt) = inherit ProvidedMethodBase(x, ctxt) @@ -967,11 +929,8 @@ type ProvidedExprType = | ProvidedIfThenElseExpr of ProvidedExpr * ProvidedExpr * ProvidedExpr | ProvidedVarExpr of ProvidedVar -#if NO_CHECKNULLS -[] -#else + [] -#endif type ProvidedExpr (x: Expr, ctxt) = member _.Type = x.Type |> ProvidedType.CreateNonNull ctxt @@ -1043,11 +1002,7 @@ type ProvidedExpr (x: Expr, ctxt) = override _.GetHashCode() = x.GetHashCode() -#if NO_CHECKNULLS -[] -#else [] -#endif type ProvidedVar (x: Var, ctxt) = member _.Type = x.Type |> ProvidedType.CreateNonNull ctxt member _.Name = x.Name @@ -1097,11 +1052,9 @@ let ValidateExpectedName m expectedPath expectedName (st: Tainted) if name <> expectedName then raise (TypeProviderError(FSComp.SR.etProvidedTypeHasUnexpectedName(expectedName, name), st.TypeProviderDesignation, m)) -#if NO_CHECKNULLS - let namespaceName = TryTypeMember(st, name, "Namespace", m, "", fun st -> st.Namespace) |> unmarshal -#else - let namespaceName = TryTypeMember<_, string | null>(st, name, "Namespace", m, "", fun st -> st.Namespace) |> unmarshal // TODO NULLNESS: why is this explicit instantiation needed? -#endif + + let namespaceName = TryTypeMember(st, name, "Namespace", m, ("":_|null), fun st -> st.Namespace) |> unmarshal + let rec declaringTypes (st: Tainted) accu = match TryTypeMember(st, name, "DeclaringType", m, null, fun st -> st.DeclaringType) with @@ -1124,11 +1077,7 @@ let ValidateProvidedTypeAfterStaticInstantiation(m, st: Tainted, e // Do all the calling into st up front with recovery let fullName, namespaceName, usedMembers = let name = CheckAndComputeProvidedNameProperty(m, st, (fun st -> st.Name), "Name") -#if NO_CHECKNULLS - let namespaceName = TryTypeMember(st, name, "Namespace", m, FSComp.SR.invalidNamespaceForProvidedType(), fun st -> st.Namespace) |> unmarshal -#else let namespaceName = TryTypeMember<_, string | null>(st, name, "Namespace", m, FSComp.SR.invalidNamespaceForProvidedType(), fun st -> st.Namespace) |> unmarshal -#endif let fullName = TryTypeMemberNonNull(st, name, "FullName", m, FSComp.SR.invalidFullNameForProvidedType(), fun st -> st.FullName) |> unmarshal ValidateExpectedName m expectedPath expectedName st // Must be able to call (GetMethods|GetEvents|GetProperties|GetNestedTypes|GetConstructors)(bindingFlags). @@ -1233,11 +1182,7 @@ let ValidateProvidedTypeDefinition(m, st: Tainted, expectedPath: s // Validate the Name, Namespace and FullName properties let name = CheckAndComputeProvidedNameProperty(m, st, (fun st -> st.Name), "Name") -#if NO_CHECKNULLS - let _namespaceName = TryTypeMember(st, name, "Namespace", m, FSComp.SR.invalidNamespaceForProvidedType(), fun st -> st.Namespace) |> unmarshal -#else let _namespaceName = TryTypeMember<_, string | null>(st, name, "Namespace", m, FSComp.SR.invalidNamespaceForProvidedType(), fun st -> st.Namespace) |> unmarshal -#endif let _fullname = TryTypeMemberNonNull(st, name, "FullName", m, FSComp.SR.invalidFullNameForProvidedType(), fun st -> st.FullName) |> unmarshal ValidateExpectedName m expectedPath expectedName st diff --git a/src/Compiler/TypedTree/TypeProviders.fsi b/src/Compiler/TypedTree/TypeProviders.fsi index b8ec2158ea4..c29f091be78 100755 --- a/src/Compiler/TypedTree/TypeProviders.fsi +++ b/src/Compiler/TypedTree/TypeProviders.fsi @@ -15,7 +15,7 @@ open FSharp.Compiler.AbstractIL.IL open FSharp.Compiler.Text type TypeProviderDesignation = TypeProviderDesignation of string -type 'a ProvidedArray= ('a[]) MaybeNull +type 'a ProvidedArray = ('a[]) MaybeNull /// Raised when a type provider has thrown an exception. exception ProvidedTypeResolution of range * exn @@ -92,10 +92,7 @@ type ProvidedTypeContext = /// Map the TyconRef objects, if any member RemapTyconRefs: (obj -> obj) -> ProvidedTypeContext -[] -#if NO_CHECKNULLS -[] -#endif +[] type ProvidedType = inherit ProvidedMemberInfo @@ -209,9 +206,6 @@ type ProvidedType = static member TaintedEquals: Tainted * Tainted -> bool -#if NO_CHECKNULLS -[] -#endif type IProvidedCustomAttributeProvider = abstract GetHasTypeProviderEditorHideMethodsAttribute: provider: ITypeProvider -> bool @@ -221,12 +215,9 @@ type IProvidedCustomAttributeProvider = abstract GetAttributeConstructorArgs: provider: ITypeProvider * attribName: string -> (obj option list * (string * obj option) list) option - -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedAssembly = + +[] +type ProvidedAssembly = member GetName: unit -> System.Reflection.AssemblyName member FullName: string @@ -235,23 +226,17 @@ type ProvidedAssembly = member Handle: System.Reflection.Assembly -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedMemberInfo = +[] +type ProvidedMemberInfo = member Name: string member DeclaringType: ProvidedType MaybeNull - interface IProvidedCustomAttributeProvider + interface IProvidedCustomAttributeProvider -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedMethodBase = +[] +type ProvidedMethodBase = inherit ProvidedMemberInfo member IsGenericMethod: bool @@ -286,11 +271,8 @@ type ProvidedMethodBase = static member TaintedEquals: Tainted * Tainted -> bool -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedMethodInfo = +[] +type ProvidedMethodInfo = inherit ProvidedMethodBase @@ -298,11 +280,8 @@ type ProvidedMethodInfo = member MetadataToken: int -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedParameterInfo = +[] +type ProvidedParameterInfo = member Name: string @@ -320,11 +299,8 @@ type ProvidedParameterInfo = interface IProvidedCustomAttributeProvider -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedFieldInfo = +[] +type ProvidedFieldInfo = inherit ProvidedMemberInfo @@ -352,11 +328,8 @@ type ProvidedFieldInfo = static member TaintedEquals: Tainted * Tainted -> bool -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedPropertyInfo = +[] +type ProvidedPropertyInfo = inherit ProvidedMemberInfo @@ -376,11 +349,8 @@ type ProvidedPropertyInfo = static member TaintedEquals: Tainted * Tainted -> bool -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedEventInfo = +[] +type ProvidedEventInfo = inherit ProvidedMemberInfo @@ -394,11 +364,8 @@ type ProvidedEventInfo = static member TaintedEquals: Tainted * Tainted -> bool -[] -#if NO_CHECKNULLS -[] -#endif -type ProvidedConstructorInfo = +[] +type ProvidedConstructorInfo = inherit ProvidedMethodBase type ProvidedExprType = @@ -442,11 +409,8 @@ type ProvidedExprType = | ProvidedIfThenElseExpr of ProvidedExpr * ProvidedExpr * ProvidedExpr | ProvidedVarExpr of ProvidedVar - -[] -#if NO_CHECKNULLS -[] -#endif + +[] type ProvidedExpr = member Type: ProvidedType @@ -456,10 +420,7 @@ type ProvidedExpr = member GetExprType: unit -> ProvidedExprType option -[] -#if NO_CHECKNULLS -[] -#endif +[] type ProvidedVar = member Type: ProvidedType @@ -481,7 +442,10 @@ val ValidateProvidedTypeAfterStaticInstantiation: /// to check the type name is as expected (this function is called by the caller of TryApplyProvidedType /// after other checks are made). val TryApplyProvidedType: - typeBeforeArguments: Tainted * optGeneratedTypePath: string list option * staticArgs: objnull[] * range -> + typeBeforeArguments: Tainted * + optGeneratedTypePath: string list option * + staticArgs: objnull[] * + range -> (Tainted * (unit -> unit)) option /// Try to apply a provided method to the given static arguments. diff --git a/src/Compiler/TypedTree/TypedTreeOps.fs b/src/Compiler/TypedTree/TypedTreeOps.fs index e5e330759dc..33dd6c2757c 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.fs +++ b/src/Compiler/TypedTree/TypedTreeOps.fs @@ -39,17 +39,11 @@ let RemapExprStackGuardDepth = GetEnvInteger "FSHARP_RemapExpr" 50 let FoldExprStackGuardDepth = GetEnvInteger "FSHARP_FoldExpr" 50 let inline compareBy (x: 'T MaybeNull) (y: 'T MaybeNull) ([]func: 'T -> 'K) = -#if NO_CHECKNULLS - compare (func x) (func y) -#else match x,y with | null,null -> 0 | null,_ -> -1 | _,null -> 1 | x,y -> compare (func !!x) (func !!y) -#endif - - //--------------------------------------------------------------------------- // Basic data structures @@ -3576,12 +3570,7 @@ let TryFindLocalizedFSharpStringAttribute g nm attrs = match TryFindFSharpAttribute g nm attrs with | Some(Attrib(_, _, [ AttribStringArg b ], namedArgs, _, _, _)) -> match namedArgs with - | ExtractAttribNamedArg "Localize" (AttribBoolArg true) -> - #if PROTO || BUILDING_WITH_LKG - Some b - #else - FSComp.SR.GetTextOpt(b) - #endif + | ExtractAttribNamedArg "Localize" (AttribBoolArg true) -> FSComp.SR.GetTextOpt(b) | _ -> Some b | _ -> None diff --git a/src/Compiler/TypedTree/tainted.fs b/src/Compiler/TypedTree/tainted.fs index 76a0ba131e4..8b3561aaaa3 100644 --- a/src/Compiler/TypedTree/tainted.fs +++ b/src/Compiler/TypedTree/tainted.fs @@ -171,13 +171,8 @@ type internal Tainted<'T> (context: TaintedContext, value: 'T) = module internal Tainted = -#if NO_CHECKNULLS - let (|Null|NonNull|) (p:Tainted<'T>) : Choice> when 'T : null and 'T : not struct = - if p.PUntaintNoFailure isNull then Null else NonNull (p.PApplyNoFailure id) -#else let (|Null|NonNull|) (p:Tainted<'T | null>) : Choice> when 'T : not null and 'T : not struct = if p.PUntaintNoFailure isNull then Null else NonNull (p.PApplyNoFailure nonNull) -#endif let Eq (p:Tainted<'T>) (v:'T) = p.PUntaintNoFailure (fun pv -> pv = v) diff --git a/src/Compiler/TypedTree/tainted.fsi b/src/Compiler/TypedTree/tainted.fsi index d066eefd3b2..b75c8c43a5b 100644 --- a/src/Compiler/TypedTree/tainted.fsi +++ b/src/Compiler/TypedTree/tainted.fsi @@ -81,7 +81,7 @@ type internal Tainted<'T> = member PApplyArray: ('T -> 'U[] MaybeNull) * string * range: range -> Tainted<'U>[] /// Apply an operation that returns an array. Filter the array. Unwrap array. Any exception will be attributed to the type provider with an error located at the given range. String is method name of thing-returning-array, to diagnostically attribute if it is null - member PApplyFilteredArray: ('T -> 'U[] MaybeNull) * ('U -> bool) *string * range: range -> Tainted<'U>[] + member PApplyFilteredArray: ('T -> 'U[] MaybeNull) * ('U -> bool) * string * range: range -> Tainted<'U>[] /// Apply an operation that returns an option. Unwrap option. Any exception will be attributed to the type provider with an error located at the given range member PApplyOption: ('T -> 'U option) * range: range -> Tainted<'U> option @@ -104,11 +104,7 @@ type internal Tainted<'T> = module internal Tainted = /// Test whether the tainted value is null -#if NO_CHECKNULLS - val (|Null|NonNull|) : Tainted<'T MaybeNull> -> Choice> when 'T : null and 'T : not struct -#else - val (|Null|NonNull|) : Tainted<'T MaybeNull> -> Choice> when 'T : not null and 'T : not struct -#endif + val (|Null|NonNull|): Tainted<'T MaybeNull> -> Choice> when 'T: not null and 'T: not struct /// Test whether the tainted value equals given value. /// Failure in call to equality operation will be blamed on type provider of first operand diff --git a/src/Compiler/Utilities/Activity.fs b/src/Compiler/Utilities/Activity.fs index 2d204864f69..121b52cf07f 100644 --- a/src/Compiler/Utilities/Activity.fs +++ b/src/Compiler/Utilities/Activity.fs @@ -9,7 +9,6 @@ open System.Text open Internal.Utilities.Library open System.Collections.Generic - module ActivityNames = [] let FscSourceName = "fsc" @@ -90,18 +89,18 @@ module internal Activity = let private activitySource = new ActivitySource(ActivityNames.FscSourceName) - let start (name: string) (tags: (string * string) seq) : IDisposable MaybeNull = + let start (name: string) (tags: (string * string) seq) : ActivityDisposable = let activity = activitySource.CreateActivity(name, ActivityKind.Internal) match activity with - | null -> activity + | null -> activity | activity -> for key, value in tags do activity.AddTag(key, value) |> ignore activity.Start() - let startNoTags (name: string) : IDisposable MaybeNull = activitySource.StartActivity name + let startNoTags (name: string) : ActivityDisposable = activitySource.StartActivity name let addEventWithTags name (tags: (string * objnull) seq) = match Activity.Current with @@ -128,7 +127,7 @@ module internal Activity = let private profiledSource = new ActivitySource(ActivityNames.ProfiledSourceName) - let startAndMeasureEnvironmentStats (name: string) : IDisposable MaybeNull = profiledSource.StartActivity(name) + let startAndMeasureEnvironmentStats (name: string) : ActivityDisposable = profiledSource.StartActivity(name) type private GCStats = int[] @@ -210,7 +209,11 @@ module internal Activity = match o with | null -> "" | o -> - let mutable txtVal = match o.ToString() with | null -> "" | s -> s + let mutable txtVal = + match o.ToString() with + | null -> "" + | s -> s + let hasComma = txtVal.IndexOf(',') > -1 let hasQuote = txtVal.IndexOf('"') > -1 @@ -243,7 +246,7 @@ module internal Activity = sb.ToString() - let addCsvFileListener (pathToFile:string) = + let addCsvFileListener (pathToFile: string) = if pathToFile |> File.Exists |> not then File.WriteAllLines( pathToFile, @@ -265,7 +268,7 @@ module internal Activity = let l = new ActivityListener( - ShouldListenTo = (fun a ->ActivityNames.AllRelevantNames |> Array.contains a.Name), + ShouldListenTo = (fun a -> ActivityNames.AllRelevantNames |> Array.contains a.Name), Sample = (fun _ -> ActivitySamplingResult.AllData), ActivityStopped = (fun a -> msgQueue.Post(createCsvRow a)) ) diff --git a/src/Compiler/Utilities/Activity.fsi b/src/Compiler/Utilities/Activity.fsi index 041b2998765..773c7528869 100644 --- a/src/Compiler/Utilities/Activity.fsi +++ b/src/Compiler/Utilities/Activity.fsi @@ -40,16 +40,16 @@ module internal Activity = module Events = val cacheHit: string - val startNoTags: name: string -> IDisposable MaybeNull + val startNoTags: name: string -> ActivityDisposable - val start: name: string -> tags: (string * string) seq -> IDisposable MaybeNull + val start: name: string -> tags: (string * string) seq -> ActivityDisposable val addEvent: name: string -> unit val addEventWithTags: name: string -> tags: (string * objnull) seq -> unit module Profiling = - val startAndMeasureEnvironmentStats: name: string -> IDisposable MaybeNull + val startAndMeasureEnvironmentStats: name: string -> ActivityDisposable val addConsoleListener: unit -> IDisposable module CsvExport = diff --git a/src/Compiler/Utilities/Cancellable.fsi b/src/Compiler/Utilities/Cancellable.fsi index e74404c7eec..0d82faa68cb 100644 --- a/src/Compiler/Utilities/Cancellable.fsi +++ b/src/Compiler/Utilities/Cancellable.fsi @@ -68,12 +68,9 @@ type internal CancellableBuilder = comp: Cancellable<'T> * [] handler: (exn -> Cancellable<'T>) -> Cancellable<'T> member inline Using: - resource: 'Resource MaybeNull * [] comp: ('Resource MaybeNull -> Cancellable<'T>) -> Cancellable<'T> - when 'Resource :> IDisposable - and 'Resource:not struct -#if !(NO_CHECKNULLS || BUILDING_WITH_LKG) - and 'Resource:not null -#endif + resource: 'Resource MaybeNull * [] comp: ('Resource MaybeNull -> Cancellable<'T>) -> + Cancellable<'T> + when 'Resource :> IDisposable and 'Resource: not struct and 'Resource: not null member inline Zero: unit -> Cancellable diff --git a/src/Compiler/Utilities/HashMultiMap.fs b/src/Compiler/Utilities/HashMultiMap.fs index c0fc897121d..2688869136e 100644 --- a/src/Compiler/Utilities/HashMultiMap.fs +++ b/src/Compiler/Utilities/HashMultiMap.fs @@ -8,11 +8,7 @@ open System.Collections.Concurrent // Each entry in the HashMultiMap dictionary has at least one entry. Under normal usage each entry has _only_ // one entry. So use two hash tables: one for the main entries and one for the overflow. [] -type internal HashMultiMap<'Key, 'Value -#if !NO_CHECKNULLS - when 'Key:not null -#endif - >(size: int, comparer: IEqualityComparer<'Key>, ?useConcurrentDictionary: bool) = +type internal HashMultiMap<'Key, 'Value when 'Key: not null>(size: int, comparer: IEqualityComparer<'Key>, ?useConcurrentDictionary: bool) = let comparer = comparer diff --git a/src/Compiler/Utilities/HashMultiMap.fsi b/src/Compiler/Utilities/HashMultiMap.fsi index 6a4ba2ce119..475f9db558d 100644 --- a/src/Compiler/Utilities/HashMultiMap.fsi +++ b/src/Compiler/Utilities/HashMultiMap.fsi @@ -7,11 +7,7 @@ open System.Collections.Generic /// Hash tables, by default based on F# structural "hash" and (=) functions. /// The table may map a single key to multiple bindings. [] -type internal HashMultiMap<'Key, 'Value -#if !NO_CHECKNULLS - when 'Key:not null -#endif - > = +type internal HashMultiMap<'Key, 'Value when 'Key: not null> = /// Create a new empty mutable HashMultiMap with the given key hash/equality functions. new: comparer: IEqualityComparer<'Key> * ?useConcurrentDictionary: bool -> HashMultiMap<'Key, 'Value> @@ -20,7 +16,9 @@ type internal HashMultiMap<'Key, 'Value new: size: int * comparer: IEqualityComparer<'Key> * ?useConcurrentDictionary: bool -> HashMultiMap<'Key, 'Value> /// Build a map that contains the bindings of the given IEnumerable. - new: entries: seq<'Key * 'Value> * comparer: IEqualityComparer<'Key> * ?useConcurrentDictionary: bool -> HashMultiMap<'Key, 'Value> + new: + entries: seq<'Key * 'Value> * comparer: IEqualityComparer<'Key> * ?useConcurrentDictionary: bool -> + HashMultiMap<'Key, 'Value> /// Make a shallow copy of the collection. member Copy: unit -> HashMultiMap<'Key, 'Value> diff --git a/src/Compiler/Utilities/LruCache.fs b/src/Compiler/Utilities/LruCache.fs index 92f73885eb7..942b9acfc34 100644 --- a/src/Compiler/Utilities/LruCache.fs +++ b/src/Compiler/Utilities/LruCache.fs @@ -23,12 +23,8 @@ type internal ValueLink<'T when 'T: not struct> = | Weak of WeakReference<'T> [] -type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality and 'TValue: not struct -#if !NO_CHECKNULLS - and 'TKey:not null - and 'TVersion:not null -#endif - > +type internal LruCache<'TKey, 'TVersion, 'TValue + when 'TKey: equality and 'TVersion: equality and 'TValue: not struct and 'TKey: not null and 'TVersion: not null> (keepStrongly, ?keepWeakly, ?requiredToKeep, ?event) = let keepWeakly = defaultArg keepWeakly 100 @@ -72,7 +68,7 @@ type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVers let mutable node = weakList.Last while weakList.Count > keepWeakly && node <> null do - let notNullNode = !! node + let notNullNode = !!node let previous = notNullNode.Previous let key, version, label, _ = notNullNode.Value weakList.Remove notNullNode @@ -90,7 +86,7 @@ type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVers let mutable anythingWeakened = false while strongList.Count > keepStrongly && node <> null do - let notNullNode = !! node + let notNullNode = !!node let previous = notNullNode.Previous match notNullNode.Value with diff --git a/src/Compiler/Utilities/LruCache.fsi b/src/Compiler/Utilities/LruCache.fsi index 5979304f163..0d6b9c2e750 100644 --- a/src/Compiler/Utilities/LruCache.fsi +++ b/src/Compiler/Utilities/LruCache.fsi @@ -12,13 +12,8 @@ type internal CacheEvent = /// /// It's also versioned, meaning each key can have multiple versions and only the latest one is kept strongly. /// Older versions are kept weakly and can be collected by GC. -type internal LruCache<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality and 'TValue: not struct -#if !NO_CHECKNULLS - and 'TKey:not null - and 'TVersion:not null -#endif - > = - +type internal LruCache<'TKey, 'TVersion, 'TValue + when 'TKey: equality and 'TVersion: equality and 'TValue: not struct and 'TKey: not null and 'TVersion: not null> = /// Maximum number of strongly held results to keep in the cache /// Maximum number of weakly held results to keep in the cache /// A predicate that determines if a value should be kept strongly (no matter what) diff --git a/src/Compiler/Utilities/NullnessShims.fs b/src/Compiler/Utilities/NullnessShims.fs index ee801610255..848bf650e98 100644 --- a/src/Compiler/Utilities/NullnessShims.fs +++ b/src/Compiler/Utilities/NullnessShims.fs @@ -7,44 +7,6 @@ module internal NullnessShims = let inline isNotNull (x: 'T) = not (isNull x) -#if NO_CHECKNULLS || BUILDING_WITH_LKG - type 'T MaybeNull when 'T: not struct = 'T - type objnull = obj - - let inline (^) (a: 'a) ([] b: 'a -> 'b) : 'b = - match a with - | null -> Unchecked.defaultof<'b> - | _ -> b a - - let inline (|NonNullQuick|) (x: 'T MaybeNull) = - match x with - | null -> raise (NullReferenceException()) - | v -> v - - let inline nonNull<'T when 'T:not struct and 'T:null> (x: 'T MaybeNull ) = - match x with - | null -> raise (NullReferenceException()) - | v -> v - - let inline (|Null|NonNull|) (x: 'T MaybeNull) : Choice = - match x with - | null -> Null - | v -> NonNull v - - let inline nullArgCheck paramName (x: 'T MaybeNull) = - if isNull (box x) then raise (ArgumentNullException(paramName)) - else x - - let inline (!!) x = x - - let inline defaultIfNull defaultValue arg = match arg with | null -> defaultValue | _ -> arg - - let inline nullSafeEquality (x: MaybeNull<'T>) (y: MaybeNull<'T>) ([]nonNullEqualityFunc:'T->'T->bool) = - match box x, box y with - | null, null -> true - | null,_ | _, null -> false - | _,_ -> nonNullEqualityFunc x y -#else type 'T MaybeNull when 'T: not null and 'T: not struct = 'T | null let inline (^) (a: 'a | null) ([] b: 'a -> 'b) : ('b | null) = @@ -52,16 +14,20 @@ module internal NullnessShims = | Null -> null | NonNull v -> b v - let inline (!!) (x:'T | null) = Unchecked.nonNull x + let inline (!!) (x: 'T | null) = Unchecked.nonNull x - let inline nullSafeEquality (x: MaybeNull<'T>) (y: MaybeNull<'T>) ([]nonNullEqualityFunc:'T->'T->bool) = + let inline nullSafeEquality (x: MaybeNull<'T>) (y: MaybeNull<'T>) ([] nonNullEqualityFunc: 'T -> 'T -> bool) = match x, y with | null, null -> true - | null,_ | _, null -> false + | null, _ + | _, null -> false | x, y -> nonNullEqualityFunc !!x !!y -#endif - +#if BUILDING_WITH_LKG + type ActivityDisposable = System.IDisposable +#else + type ActivityDisposable = System.IDisposable | null +#endif #if NET5_0_OR_GREATER // Argument type for overriding System.Object.Equals(arg) @@ -71,10 +37,9 @@ module internal NullnessShims = type objEqualsArg = obj #endif - - [] + [] let inline (|NonEmptyString|_|) (x: string MaybeNull) = match x with | null -> ValueNone | "" -> ValueNone - | v -> ValueSome v \ No newline at end of file + | v -> ValueSome v diff --git a/src/Compiler/Utilities/illib.fs b/src/Compiler/Utilities/illib.fs index 0f68d92a429..470d7402e07 100644 --- a/src/Compiler/Utilities/illib.fs +++ b/src/Compiler/Utilities/illib.fs @@ -17,8 +17,7 @@ type InterruptibleLazy<'T> private (value, valueFactory: unit -> 'T) = [] // TODO nullness - this is boxed to obj because of an attribute targets bug fixed in main, but not yet shipped (needs shipped 8.0.400) - let mutable valueFactory : objnull = valueFactory - + let mutable valueFactory: objnull = valueFactory let mutable value = value @@ -104,7 +103,7 @@ module internal PervasiveAutoOpens = member inline x.EndsWithOrdinalIgnoreCase value = x.EndsWith(value, StringComparison.OrdinalIgnoreCase) - member inline x.IndexOfOrdinal (value:string) = + member inline x.IndexOfOrdinal(value: string) = x.IndexOf(value, StringComparison.Ordinal) member inline x.IndexOfOrdinal(value, startIndex) = @@ -154,8 +153,8 @@ module internal PervasiveAutoOpens = type DelayInitArrayMap<'T, 'TDictKey, 'TDictValue>(f: unit -> 'T[]) = let syncObj = obj () - let mutable arrayStore : _ array MaybeNull = null - let mutable dictStore : _ MaybeNull = null + let mutable arrayStore: _ array MaybeNull = null + let mutable dictStore: _ MaybeNull = null let mutable func = f @@ -206,12 +205,12 @@ module Order = member _.Compare(x, xx) = compare (p !!x) (p !!xx) } - let orderOn (p:'T->'U) (pxOrder: IComparer<'U>) = + let orderOn (p: 'T -> 'U) (pxOrder: IComparer<'U>) = { new IComparer<'T> with member _.Compare(x, xx) = pxOrder.Compare(p !!x, p !!xx) } - let toFunction (pxOrder: IComparer<'U>) (x:'U) (y:'U) = pxOrder.Compare(x, y) + let toFunction (pxOrder: IComparer<'U>) (x: 'U) (y: 'U) = pxOrder.Compare(x, y) //------------------------------------------------------------------------- // Library: arrays, lists, options, resizearrays @@ -242,7 +241,7 @@ module Array = let order (eltOrder: IComparer<'T>) = { new IComparer<'T array> with member _.Compare(xs, ys) = - let xs,ys = nullArgCheck "xs" xs, nullArgCheck "ys" ys + let xs, ys = nullArgCheck "xs" xs, nullArgCheck "ys" ys let c = compare xs.Length ys.Length if c <> 0 then @@ -412,8 +411,8 @@ module Option = with _ -> None -module internal ValueTuple = - let inline map1Of2 ([]f) struct(a1, a2) = struct(f a1, a2) +module internal ValueTuple = + let inline map1Of2 ([] f) struct (a1, a2) = struct (f a1, a2) module List = @@ -539,7 +538,8 @@ module List = let order (eltOrder: IComparer<'T>) = { new IComparer<'T list> with member _.Compare(xs, ys) = - let xs,ys = nullArgCheck "xs" xs, nullArgCheck "ys" ys + let xs, ys = nullArgCheck "xs" xs, nullArgCheck "ys" ys + let rec loop xs ys = match xs, ys with | [], [] -> 0 @@ -642,21 +642,22 @@ module List = | Some x -> x :: l | _ -> l - [] - let rec private vMapFoldWithAcc<'T, 'State, 'Result> (mapping: 'State -> 'T -> struct('Result * 'State)) state list acc : struct('Result list * 'State) = + let rec private vMapFoldWithAcc<'T, 'State, 'Result> + (mapping: 'State -> 'T -> struct ('Result * 'State)) + state + list + acc + : struct ('Result list * 'State) = match list with | [] -> acc, state - | [h] -> - mapping state h - |> ValueTuple.map1Of2 (fun x -> x::acc) + | [ h ] -> mapping state h |> ValueTuple.map1Of2 (fun x -> x :: acc) | h :: t -> - let struct(mappedHead, stateHead) = mapping state h + let struct (mappedHead, stateHead) = mapping state h vMapFoldWithAcc mapping stateHead t (mappedHead :: acc) - let vMapFold<'T, 'State, 'Result> (mapping: 'State -> 'T -> struct('Result * 'State)) state list : struct('Result list * 'State) = - vMapFoldWithAcc mapping state list [] - |> ValueTuple.map1Of2 List.rev + let vMapFold<'T, 'State, 'Result> (mapping: 'State -> 'T -> struct ('Result * 'State)) state list : struct ('Result list * 'State) = + vMapFoldWithAcc mapping state list [] |> ValueTuple.map1Of2 List.rev module ResizeArray = @@ -796,13 +797,11 @@ module String = elif (!!value).StartsWithOrdinal pattern then Some() else None - let (|Contains|_|) (pattern:string) (value:string|null) = - match value with + let (|Contains|_|) (pattern: string) (value: string | null) = + match value with | null -> None | value when String.IsNullOrWhiteSpace value -> None - | value -> - if value.Contains pattern then Some() - else None + | value -> if value.Contains pattern then Some() else None let getLines (str: string) = use reader = new StringReader(str) @@ -854,9 +853,7 @@ module Lazy = // Single threaded execution and mutual exclusion /// Represents a permission active at this point in execution -type ExecutionToken = - interface - end +type ExecutionToken = interface end /// Represents a token that indicates execution on the compilation thread, i.e. /// - we have full access to the (partially mutable) TAST and TcImports data structures @@ -941,11 +938,7 @@ module ResultOrException = | Exception _err -> f () /// Generates unique stamps -type UniqueStampGenerator<'T when 'T: equality -#if !NO_CHECKNULLS - and 'T:not null -#endif - >() = +type UniqueStampGenerator<'T when 'T: equality and 'T: not null>() = let encodeTable = ConcurrentDictionary<'T, Lazy>(HashIdentity.Structural) let mutable nItems = -1 @@ -957,11 +950,7 @@ type UniqueStampGenerator<'T when 'T: equality member _.Table = encodeTable.Keys /// memoize tables (all entries cached, never collected) -type MemoizationTable<'T, 'U -#if !NO_CHECKNULLS - when 'T:not null -#endif - >(compute: 'T -> 'U, keyComparer: IEqualityComparer<'T>, ?canMemoize) = +type MemoizationTable<'T, 'U when 'T: not null>(compute: 'T -> 'U, keyComparer: IEqualityComparer<'T>, ?canMemoize) = let table = new ConcurrentDictionary<'T, Lazy<'U>>(keyComparer) let computeFunc = Func<_, _>(fun key -> lazy (compute key)) @@ -977,11 +966,7 @@ type MemoizationTable<'T, 'U compute x /// A thread-safe lookup table which is assigning an auto-increment stamp with each insert -type internal StampedDictionary<'T, 'U -#if !NO_CHECKNULLS - when 'T:not null -#endif - >(keyComparer: IEqualityComparer<'T>) = +type internal StampedDictionary<'T, 'U when 'T: not null>(keyComparer: IEqualityComparer<'T>) = let table = new ConcurrentDictionary<'T, Lazy>(keyComparer) let mutable count = -1 @@ -1307,12 +1292,13 @@ module MultiMap = let initBy f xs : MultiMap<_, _> = xs |> Seq.groupBy f |> Seq.map (fun (k, v) -> (k, List.ofSeq v)) |> Map.ofSeq - let ofList (xs: ('a * 'b) list) : MultiMap<'a,'b> = + let ofList (xs: ('a * 'b) list) : MultiMap<'a, 'b> = (Map.empty, xs) ||> List.fold (fun m (k, v) -> - m |> Map.change k (function - | None -> Some [v] - | Some vs -> Some (v :: vs))) + m + |> Map.change k (function + | None -> Some [ v ] + | Some vs -> Some(v :: vs))) |> Map.map (fun _ values -> List.rev values) type LayeredMap<'Key, 'Value when 'Key: comparison> = Map<'Key, 'Value> diff --git a/src/Compiler/Utilities/illib.fsi b/src/Compiler/Utilities/illib.fsi index bd9d330cfe4..e2fba355366 100644 --- a/src/Compiler/Utilities/illib.fsi +++ b/src/Compiler/Utilities/illib.fsi @@ -86,18 +86,9 @@ type DelayInitArrayMap<'T, 'TDictKey, 'TDictValue> = module internal Order = - val orderBy: p: ('T -> 'U) -> IComparer<'T> - when 'U: comparison -#if !NO_CHECKNULLS - and 'T:not null - and 'T:not struct -#endif + val orderBy: p: ('T -> 'U) -> IComparer<'T> when 'U: comparison and 'T: not null and 'T: not struct - val orderOn: p: ('T -> 'U) -> pxOrder: IComparer<'U> -> IComparer<'T> -#if !NO_CHECKNULLS - when 'T:not null - and 'T:not struct -#endif + val orderOn: p: ('T -> 'U) -> pxOrder: IComparer<'U> -> IComparer<'T> when 'T: not null and 'T: not struct val toFunction: pxOrder: IComparer<'U> -> x: 'U -> y: 'U -> int @@ -230,7 +221,11 @@ module internal List = val prependIfSome: x: 'a option -> l: 'a list -> 'a list - val vMapFold<'T,'State,'Result> : mapping:('State -> 'T -> struct('Result * 'State)) -> state:'State -> list:'T list -> struct('Result list * 'State) + val vMapFold<'T, 'State, 'Result> : + mapping: ('State -> 'T -> struct ('Result * 'State)) -> + state: 'State -> + list: 'T list -> + struct ('Result list * 'State) module internal ResizeArray = @@ -284,7 +279,7 @@ module internal String = val (|StartsWith|_|): pattern: string -> value: string -> unit option - val (|Contains|_|): pattern: string -> value: string|null -> unit option + val (|Contains|_|): pattern: string -> value: string | null -> unit option val getLines: str: string -> string[] @@ -306,9 +301,7 @@ module internal Lazy = val force: x: Lazy<'T> -> 'T /// Represents a permission active at this point in execution -type internal ExecutionToken = - interface - end +type internal ExecutionToken = interface end /// Represents a token that indicates execution on the compilation thread, i.e. /// - we have full access to the (partially mutable) TAST and TcImports data structures @@ -381,11 +374,7 @@ module internal ResultOrException = val otherwise: f: (unit -> ResultOrException<'a>) -> x: ResultOrException<'a> -> ResultOrException<'a> /// Generates unique stamps -type internal UniqueStampGenerator<'T when 'T: equality -#if !NO_CHECKNULLS - and 'T:not null -#endif - > = +type internal UniqueStampGenerator<'T when 'T: equality and 'T: not null> = new: unit -> UniqueStampGenerator<'T> @@ -394,11 +383,7 @@ type internal UniqueStampGenerator<'T when 'T: equality member Table: ICollection<'T> /// Memoize tables (all entries cached, never collected unless whole table is collected) -type internal MemoizationTable<'T, 'U -#if !NO_CHECKNULLS - when 'T:not null -#endif - > = +type internal MemoizationTable<'T, 'U when 'T: not null> = new: compute: ('T -> 'U) * keyComparer: IEqualityComparer<'T> * ?canMemoize: ('T -> bool) -> MemoizationTable<'T, 'U> @@ -406,11 +391,7 @@ type internal MemoizationTable<'T, 'U member Apply: x: 'T -> 'U /// A thread-safe lookup table which is assigning an auto-increment stamp with each insert -type internal StampedDictionary<'T, 'U -#if !NO_CHECKNULLS - when 'T:not null -#endif - > = +type internal StampedDictionary<'T, 'U when 'T: not null> = new: keyComparer: IEqualityComparer<'T> -> StampedDictionary<'T, 'U> @@ -443,10 +424,10 @@ type internal LazyWithContext<'T, 'ctxt> = /// Intern tables to save space. module internal Tables = - val memoize: f: ('a -> 'b) -> ('a -> 'b) - when 'a: equality -#if !NO_CHECKNULLS && NET8_0_OR_GREATER - and 'a:not null +#if NET8_0_OR_GREATER + val memoize: f: ('a -> 'b) -> ('a -> 'b) when 'a: equality and 'a: not null +#else + val memoize: f: ('a -> 'b) -> ('a -> 'b) when 'a: equality #endif /// Interface that defines methods for comparing objects using partial equality relation @@ -456,11 +437,9 @@ type internal IPartialEqualityComparer<'T> = /// Interface that defines methods for comparing objects using partial equality relation module internal IPartialEqualityComparer = - val On: f: ('a -> 'b) -> c: IPartialEqualityComparer<'b> -> IPartialEqualityComparer<'a> -#if !NO_CHECKNULLS - when 'a:not null - and 'a:not struct -#endif + val On: + f: ('a -> 'b) -> c: IPartialEqualityComparer<'b> -> IPartialEqualityComparer<'a> + when 'a: not null and 'a: not struct /// Like Seq.distinctBy but only filters out duplicates for some of the elements val partialDistinctBy: per: IPartialEqualityComparer<'T> -> seq: 'T list -> 'T list @@ -574,7 +553,7 @@ module internal MultiMap = val initBy: f: ('a -> 'b) -> xs: seq<'a> -> MultiMap<'b, 'a> when 'b: comparison - val ofList: xs: ('a * 'b) list -> MultiMap<'a,'b> when 'a: comparison + val ofList: xs: ('a * 'b) list -> MultiMap<'a, 'b> when 'a: comparison type internal LayeredMap<'Key, 'Value when 'Key: comparison> = Map<'Key, 'Value> diff --git a/src/Compiler/Utilities/lib.fsi b/src/Compiler/Utilities/lib.fsi index ea0669bdf4a..1dfd610d55a 100644 --- a/src/Compiler/Utilities/lib.fsi +++ b/src/Compiler/Utilities/lib.fsi @@ -263,12 +263,7 @@ type DisposablesTracker = new: unit -> DisposablesTracker /// Register some items to dispose - member Register: i:'a MaybeNull -> unit - when 'a:>System.IDisposable -#if !(NO_CHECKNULLS || BUILDING_WITH_LKG) - and 'a:not null -#endif - and 'a:not struct + member Register: i: 'a MaybeNull -> unit when 'a :> System.IDisposable and 'a: not struct and 'a: not null interface System.IDisposable diff --git a/src/Compiler/Utilities/sformat.fs b/src/Compiler/Utilities/sformat.fs index f6fc27b1e51..6ba5b68c462 100644 --- a/src/Compiler/Utilities/sformat.fs +++ b/src/Compiler/Utilities/sformat.fs @@ -122,13 +122,6 @@ type IEnvironment = abstract MaxColumns: int abstract MaxRows: int -#if NO_CHECKNULLS -[] -module NullShim = - // Shim to match nullness checking library support in preview - let inline (|Null|NonNull|) (x: 'T) : Choice = match x with null -> Null | v -> NonNull v -#endif - [] module TaggedText = let mkTag tag text = TaggedText(tag, text) @@ -575,6 +568,7 @@ module ReflectUtils = let GetValueInfo bindingFlags (x: 'a, ty: Type) (* x could be null *) = let obj = (box x) + match obj with | Null -> let isNullaryUnion = @@ -594,8 +588,7 @@ module ReflectUtils = UnitValue else NullValue - | NonNull obj -> - GetValueInfoOfObject bindingFlags obj + | NonNull obj -> GetValueInfoOfObject bindingFlags obj module Display = open ReflectUtils @@ -1014,6 +1007,7 @@ module Display = and objL showMode depthLim prec (x: objnull, ty: Type) = let info = Value.GetValueInfo bindingFlags (x, ty) + try if depthLim <= 0 || exceededPrintSize () then wordL (tagPunctuation "...") @@ -1034,9 +1028,11 @@ module Display = Some(wordL (tagText (x.ToString()))) else // Try the StructuredFormatDisplayAttribute extensibility attribute - match ty.GetCustomAttributes (typeof, true) with - | Null | [| |] -> None - | NonNull res -> structuredFormatObjectL showMode ty depthLim (res[0] :?> StructuredFormatDisplayAttribute) x + match ty.GetCustomAttributes(typeof, true) with + | Null + | [||] -> None + | NonNull res -> + structuredFormatObjectL showMode ty depthLim (res[0] :?> StructuredFormatDisplayAttribute) x #if COMPILER // This is the PrintIntercepts extensibility point currently revealed by fsi.exe's AddPrinter @@ -1069,6 +1065,7 @@ module Display = // Format an object that has a layout specified by StructuredFormatAttribute and structuredFormatObjectL showMode ty depthLim (attr: StructuredFormatDisplayAttribute) (obj: obj) = let txt = attr.Value + if isNull (box txt) || txt.Length <= 1 then None else diff --git a/src/FSharp.Build/FSharp.Build.fsproj b/src/FSharp.Build/FSharp.Build.fsproj index 3c392ef1158..8f2fd4f5951 100644 --- a/src/FSharp.Build/FSharp.Build.fsproj +++ b/src/FSharp.Build/FSharp.Build.fsproj @@ -9,11 +9,13 @@ FSharp.Build $(NoWarn);75 true - true + enable $(DefineConstants);LOCALIZATION_FSBUILD $(NoWarn);NU1701;FS0075 + + $(OtherFlags) --nowarn:3261 true - 7.0 + 9 Debug;Release;Proto diff --git a/src/FSharp.Build/FSharpCommandLineBuilder.fs b/src/FSharp.Build/FSharpCommandLineBuilder.fs index 51d7b12f1b7..a708f94fe87 100644 --- a/src/FSharp.Build/FSharpCommandLineBuilder.fs +++ b/src/FSharp.Build/FSharpCommandLineBuilder.fs @@ -15,21 +15,10 @@ do () // Shim to match nullness checking library support in preview [] module Utils = -#if NO_CHECKNULLS - /// Match on the nullness of an argument. - let inline (|Null|NonNull|) (x: 'T) : Choice = - match x with - | null -> Null - | v -> NonNull v /// Indicates that a type may be null. 'MaybeNull' used internally in the F# compiler as unchecked /// replacement for 'string?' for example for future FS-1060. - type MaybeNull<'T when 'T : null> = 'T -#else - /// Indicates that a type may be null. 'MaybeNull' used internally in the F# compiler as unchecked - /// replacement for 'string?' for example for future FS-1060. - type MaybeNull<'T when 'T : not null and 'T : not struct> = 'T | null -#endif + type MaybeNull<'T when 'T: not null and 'T: not struct> = 'T | null type FSharpCommandLineBuilder() = diff --git a/src/FSharp.Build/FSharpEmbedResourceText.fs b/src/FSharp.Build/FSharpEmbedResourceText.fs index 3e3c79f82ee..d8f4a46eb25 100644 --- a/src/FSharp.Build/FSharpEmbedResourceText.fs +++ b/src/FSharp.Build/FSharpEmbedResourceText.fs @@ -270,6 +270,9 @@ open Microsoft.FSharp.Collections open Printf #nowarn ""3262"" // The call to Option.ofObj below is applied in multiple compilation modes for GetString, sometimes the value is typed as a non-nullable string +#if BUILDING_WITH_LKG +#nowarn ""3261"" // Nullness warnings can happen due to LKG not having latest fixes +#endif " let StringBoilerPlate fileName = @@ -319,7 +322,7 @@ open Printf // PERF: this technique is a bit slow (e.g. in simple cases, like 'sprintf ""%x""') mkFunctionValue tys (fun inp -> impl rty inp) - #if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT + #if !NULLABLE static let capture1 (fmt:string) i args ty (go: obj list -> System.Type -> int -> obj) : obj = #else static let capture1 (fmt:string) i args ty (go: objnull list -> System.Type -> int -> obj) : obj = @@ -345,7 +348,7 @@ open Printf if i >= len || (fmt.[i] = '%' && i+1 >= len) then let b = new System.Text.StringBuilder() b.AppendFormat(messageString, [| for x in List.rev args -> x |]) |> ignore - #if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT + #if !NULLABLE box(b.ToString()) #else box(b.ToString()) |> Unchecked.nonNull diff --git a/src/FSharp.Core/array.fs b/src/FSharp.Core/array.fs index 27c6d6426b6..ca88e22465d 100644 --- a/src/FSharp.Core/array.fs +++ b/src/FSharp.Core/array.fs @@ -836,21 +836,13 @@ module Array = count -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - let private createMask<'a> - (f: 'a -> bool) - (src: 'a array) - (maskArrayOut: byref) - (leftoverMaskOut: byref) - = -#else let private createMask<'a> (f: 'a -> bool) (src: array<'a>) (maskArrayOut: byref | null>) (leftoverMaskOut: byref) = -#endif + let maskArrayLength = src.Length / 0x20 // null when there are less than 32 items in src array. @@ -1040,11 +1032,8 @@ module Array = dstIdx -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - let private filterViaMask (maskArray: uint32 array) (leftoverMask: uint32) (count: int) (src: _ array) = -#else let private filterViaMask (maskArray: uint32 array | null) (leftoverMask: uint32) (count: int) (src: _ array) = -#endif + let dst = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked count let mutable dstIdx = 0 @@ -2196,14 +2185,20 @@ module Array = [] let tryFindIndex predicate (array: _ array) = let i = tryFindIndexAux predicate array - if i.HasValue then Some (int (i.GetValueOrDefault())) - else None + + if i.HasValue then + Some(int (i.GetValueOrDefault())) + else + None [] let tryFind predicate (array: _ array) = let i = tryFindIndexAux predicate array - if i.HasValue then Some array[int (i.GetValueOrDefault())] - else None + + if i.HasValue then + Some array[int (i.GetValueOrDefault())] + else + None [] let tryPick chooser (array: _ array) = @@ -2222,8 +2217,10 @@ module Array = pState.Break()) ) - if pResult.LowestBreakIteration.HasValue then allChosen[int (pResult.LowestBreakIteration.GetValueOrDefault())] - else None + if pResult.LowestBreakIteration.HasValue then + allChosen[int (pResult.LowestBreakIteration.GetValueOrDefault())] + else + None [] let choose chooser (array: 'T array) = diff --git a/src/FSharp.Core/fslib-extra-pervasives.fs b/src/FSharp.Core/fslib-extra-pervasives.fs index c0b0bc05a04..07a03675937 100644 --- a/src/FSharp.Core/fslib-extra-pervasives.fs +++ b/src/FSharp.Core/fslib-extra-pervasives.fs @@ -347,21 +347,15 @@ open Microsoft.FSharp.Quotations /// Represents the product of two measure expressions when returned as a generic argument of a provided type. [] -type MeasureProduct<'Measure1, 'Measure2>() = - class - end +type MeasureProduct<'Measure1, 'Measure2>() = class end /// Represents the inverse of a measure expressions when returned as a generic argument of a provided type. [] -type MeasureInverse<'Measure> = - class - end +type MeasureInverse<'Measure> = class end /// Represents the '1' measure expression when returned as a generic argument of a provided type. [] -type MeasureOne = - class - end +type MeasureOne = class end [] type TypeProviderAttribute() = @@ -473,7 +467,7 @@ type IProvidedNamespace = abstract GetTypes: unit -> Type array - abstract ResolveTypeName: typeName: string -> (Type|null) + abstract ResolveTypeName: typeName: string -> (Type | null) type ITypeProvider = inherit System.IDisposable diff --git a/src/FSharp.Core/local.fs b/src/FSharp.Core/local.fs index 206ccf4ee3d..a1c9c2fa644 100644 --- a/src/FSharp.Core/local.fs +++ b/src/FSharp.Core/local.fs @@ -1090,11 +1090,8 @@ module internal Array = if array.Length > 1 then Array.Sort<_>(array, fastComparerForArraySort()) -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - let stableSortWithKeysAndComparer (cFast:IComparer<'Key>) (c:IComparer<'Key>) (array:'T array) (keys: 'Key array) = -#else let stableSortWithKeysAndComparer (cFast:IComparer<'Key> | null) (c:IComparer<'Key>) (array:array<'T>) (keys:array<'Key>) = -#endif + // 'places' is an array or integers storing the permutation performed by the sort let len = array.Length let places = zeroCreateUnchecked len diff --git a/src/FSharp.Core/option.fs b/src/FSharp.Core/option.fs index 1b29141df64..ea5da774d87 100644 --- a/src/FSharp.Core/option.fs +++ b/src/FSharp.Core/option.fs @@ -148,35 +148,21 @@ module Option = [] let inline ofNullable (value: System.Nullable<'T>) = if value.HasValue then - Some (value.GetValueOrDefault()) + Some(value.GetValueOrDefault()) else None -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT [] - let inline ofObj value = + let inline ofObj (value: 'T | null) : 'T option when 'T: not struct and 'T: not null = match value with | null -> None | _ -> Some value [] - let inline toObj value = + let inline toObj (value: 'T option) : 'T | null when 'T: not struct = match value with | None -> null | Some x -> x -#else - [] - let inline ofObj (value: 'T | null) : 'T option when 'T: not struct and 'T : not null = - match value with - | null -> None - | _ -> Some value - - [] - let inline toObj (value: 'T option) : 'T | null when 'T: not struct (* and 'T : not null *) = - match value with - | None -> null - | Some x -> x -#endif [] let inline ofValueOption (voption: 'T voption) = @@ -338,35 +324,21 @@ module ValueOption = [] let inline ofNullable (value: System.Nullable<'T>) = if value.HasValue then - ValueSome (value.GetValueOrDefault()) + ValueSome(value.GetValueOrDefault()) else ValueNone -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT [] - let inline ofObj value = - match value with - | null -> ValueNone - | _ -> ValueSome value - - [] - let inline toObj value = - match value with - | ValueNone -> null - | ValueSome x -> x -#else - [] - let inline ofObj (value: 'T | null) : 'T voption when 'T: not struct and 'T : not null = + let inline ofObj (value: 'T | null) : 'T voption when 'T: not struct and 'T: not null = match value with | null -> ValueNone | _ -> ValueSome value [] - let inline toObj (value : 'T voption) : 'T | null when 'T: not struct (* and 'T : not null *) = + let inline toObj (value: 'T voption) : 'T | null when 'T: not struct = match value with | ValueNone -> null | ValueSome x -> x -#endif [] let inline ofOption (option: 'T option) = diff --git a/src/FSharp.Core/option.fsi b/src/FSharp.Core/option.fsi index 57adb485cb4..db381aec8ad 100644 --- a/src/FSharp.Core/option.fsi +++ b/src/FSharp.Core/option.fsi @@ -440,13 +440,8 @@ module Option = /// /// [] -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - val inline ofObj: value: 'T -> 'T option when 'T : null -#else - // TODO NULLNESS: assess this change - is it a breaking change? - [] - val inline ofObj: value: 'T | null -> 'T option when 'T : not null and 'T : not struct -#endif + [] + val inline ofObj: value: 'T | null -> 'T option when 'T: not null and 'T: not struct /// Convert an option to a potentially null value. /// @@ -461,12 +456,7 @@ module Option = /// /// [] -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - val inline toObj: value: 'T option -> 'T when 'T : null -#else - // TODO NULLNESS: assess this change - is it a breaking change? - val inline toObj: value: 'T option -> 'T | null when 'T : not struct (* and 'T : not null *) -#endif + val inline toObj: value: 'T option -> 'T | null when 'T: not struct /// Convert a value option to an option. /// @@ -929,13 +919,8 @@ module ValueOption = /// /// [] -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - val inline ofObj: value: 'T -> 'T voption when 'T : null -#else - // TODO NULLNESS: assess this change - is it a breaking change? - [] - val inline ofObj: value: 'T | null -> 'T voption when 'T : not struct and 'T : not null -#endif + [] + val inline ofObj: value: 'T | null -> 'T voption when 'T: not struct and 'T: not null /// Convert an option to a potentially null value. /// @@ -950,12 +935,7 @@ module ValueOption = /// /// [] -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - val inline toObj: value: 'T voption -> 'T when 'T : null -#else - // TODO NULLNESS: assess this change - is it a breaking change? - val inline toObj: value: 'T voption -> 'T | null when 'T : not struct (* and 'T : not null *) -#endif + val inline toObj: value: 'T voption -> 'T | null when 'T: not struct /// Convert an option to a value option. /// diff --git a/src/FSharp.Core/prim-types-prelude.fs b/src/FSharp.Core/prim-types-prelude.fs index 12ed91cfba2..f8797339628 100644 --- a/src/FSharp.Core/prim-types-prelude.fs +++ b/src/FSharp.Core/prim-types-prelude.fs @@ -6,11 +6,7 @@ namespace Microsoft.FSharp.Core // Basic type abbreviations type obj = System.Object -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - type objnull = obj -#else type objnull = obj | null -#endif type exn = System.Exception type nativeint = System.IntPtr type unativeint = System.UIntPtr diff --git a/src/FSharp.Core/prim-types-prelude.fsi b/src/FSharp.Core/prim-types-prelude.fsi index 8cc0515350d..a32ccdbf105 100644 --- a/src/FSharp.Core/prim-types-prelude.fsi +++ b/src/FSharp.Core/prim-types-prelude.fsi @@ -22,11 +22,7 @@ namespace Microsoft.FSharp.Core /// With the 'nullable reference types' feature, this is an alias to 'obj | null'. /// /// Basic Types -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - type objnull = obj -#else type objnull = obj | null -#endif /// An abbreviation for the CLI type . /// diff --git a/src/FSharp.Core/prim-types.fs b/src/FSharp.Core/prim-types.fs index 4f4849eb849..d9a7e41bf55 100644 --- a/src/FSharp.Core/prim-types.fs +++ b/src/FSharp.Core/prim-types.fs @@ -739,11 +739,8 @@ namespace Microsoft.FSharp.Core let inline TypeTestFast<'T>(source: objnull) = //assert not(TypeInfo<'T>.TypeInfo = TypeNullnessSemantics_NullTrueValue) notnullPrim(isinstPrim<'T>(source)) -#if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT + let Dispose<'T when 'T :> IDisposable >(resource:'T|null) = -#else - let Dispose<'T when 'T :> IDisposable >(resource:'T) = -#endif match box resource with | null -> () | _ -> resource.Dispose() @@ -4419,8 +4416,6 @@ namespace Microsoft.FSharp.Core | null -> false | _ -> true -#if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT - [] let inline isNullV (value : Nullable<'T>) = not value.HasValue @@ -4473,13 +4468,6 @@ namespace Microsoft.FSharp.Core match value with | null -> raise (new ArgumentNullException(argumentName)) | _ -> (# "" value : 'T #) -#else - [] - let inline (|Null|NonNull|) (value : 'T) : Choice when 'T : null and 'T : not struct = - match value with - | null -> Null () - | _ -> NonNull (# "" value : 'T #) -#endif [] let inline raise (exn: exn) = @@ -4573,7 +4561,6 @@ namespace Microsoft.FSharp.Core [] let defaultValueArg arg defaultValue = match arg with ValueNone -> defaultValue | ValueSome v -> v -#if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT [] let inline defaultIfNull defaultValue (arg: 'T | null when 'T : not null and 'T : not struct) = match arg with null -> defaultValue | _ -> (# "" arg : 'T #) @@ -4581,7 +4568,6 @@ namespace Microsoft.FSharp.Core [] let inline defaultIfNullV defaultValue (arg: Nullable<'T>) = if arg.HasValue then arg.Value else defaultValue -#endif [] let inline (~-) (n: ^T) : ^T = @@ -5527,24 +5513,12 @@ namespace Microsoft.FSharp.Core [] let inline hash x = GenericHash x - #if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT - [] let inline nonNull (x: 'T | null when 'T : not null and 'T : not struct) : 'T = (# "" x : 'T #) [] let inline (|NonNullQuick|) (value : 'T | null when 'T : not null and 'T : not struct) = nonNull value - #else - - [] - let inline nonNull (x: 'T ) : 'T = x - - [] - let inline (|NonNullQuick|) (value) = nonNull value - - #endif - module Checked = let inline (+) (x: ^T) (y: ^U) : ^V = diff --git a/src/FSharp.Core/prim-types.fsi b/src/FSharp.Core/prim-types.fsi index c56fe5375e4..7c2f171a600 100644 --- a/src/FSharp.Core/prim-types.fsi +++ b/src/FSharp.Core/prim-types.fsi @@ -1391,11 +1391,8 @@ namespace Microsoft.FSharp.Core val inline FastGenericComparer<'T> : System.Collections.Generic.IComparer<'T> when 'T: comparison /// Make an F# comparer object for the given type, where it can be null if System.Collections.Generic.Comparer<'T>.Default -#if BUILDING_WITH_LKG || NO_NULLCHECKING_LIB_SUPPORT - val internal FastGenericComparerCanBeNull<'T> : System.Collections.Generic.IComparer<'T> when 'T : comparison -#else val internal FastGenericComparerCanBeNull<'T> : System.Collections.Generic.IComparer<'T> | null when 'T : comparison -#endif + /// Make an F# hash/equality object for the given type val inline FastGenericEqualityComparer<'T> : System.Collections.Generic.IEqualityComparer<'T> when 'T: equality @@ -1796,11 +1793,8 @@ namespace Microsoft.FSharp.Core /// A compiler intrinsic for the efficient compilation of sequence expressions [] -#if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT val Dispose<'T when 'T :> System.IDisposable> : resource: 'T|null -> unit -#else - val Dispose<'T when 'T :> System.IDisposable> : resource: 'T -> unit -#endif + /// A compiler intrinsic for checking initialization soundness of recursive bindings [] @@ -3206,7 +3200,6 @@ namespace Microsoft.FSharp.Core /// val inline (<|||): func: ('T1 -> 'T2 -> 'T3 -> 'U) -> arg1: 'T1 * arg2: 'T2 * arg3: 'T3 -> 'U -#if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT /// Used to specify a default value for a nullable reference argument in the implementation of a function /// The default value of the argument. /// A nullable value representing the argument. @@ -3220,7 +3213,6 @@ namespace Microsoft.FSharp.Core /// The argument value. If it is null, the defaultValue is returned. [] val inline defaultIfNullV : defaultValue:'T -> arg:Nullable<'T> -> 'T -#endif /// Used to specify a default value for an optional argument in the implementation of a function /// @@ -3519,7 +3511,6 @@ namespace Microsoft.FSharp.Core [] val inline isNull: value: 'T -> bool when 'T: null -#if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT /// Determines whether the given value is null. /// The value to check. /// A choice indicating whether the value is null or not-null. @@ -3554,13 +3545,6 @@ namespace Microsoft.FSharp.Core /// True when value is null, false otherwise. [] val inline isNullV : value:Nullable<'T> -> bool -#else - /// Determines whether the given value is null. - /// The value to check. - /// A choice indicating whether the value is null or not-null. - [] - val inline (|Null|NonNull|) : value: 'T -> Choice when 'T : null and 'T : not struct -#endif /// Determines whether the given value is not null. /// @@ -3570,7 +3554,6 @@ namespace Microsoft.FSharp.Core [] val inline internal isNotNull: value:'T -> bool when 'T : null -#if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT /// Get the null value for a value type. /// In a future revision of nullness support this may be unified with 'null'. /// The null value for a value type. @@ -3603,7 +3586,6 @@ namespace Microsoft.FSharp.Core /// System.Nullable wrapper of the input argument. [] val inline withNullV : value:'T -> Nullable<'T> -#endif /// Throw a exception. /// @@ -3669,7 +3651,6 @@ namespace Microsoft.FSharp.Core [] val inline nullArg: argumentName: string -> 'T -#if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT /// Throw a System.ArgumentNullException if the given value is null exception /// /// The argument name. @@ -3677,7 +3658,6 @@ namespace Microsoft.FSharp.Core /// The result value. [] val inline nullArgCheck : argumentName:string -> 'T | null -> 'T when 'T : not null and 'T : not struct -#endif /// Throw a exception /// @@ -5812,21 +5792,13 @@ namespace Microsoft.FSharp.Core /// The possibly nullable value. /// The same value as in the input. [] - #if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT val inline nonNull : value: 'T | null -> 'T when 'T : not null and 'T : not struct - #else - val inline nonNull : value: 'T -> 'T - #endif /// When used in a pattern forgets 'nullness' of the value without any runtime check. This is an unsafe operation, as null check is being skipped and null value can be returned. /// The value to retype from ('T | null) to 'T . /// The non-null value. [] - #if !BUILDING_WITH_LKG && !NO_NULLCHECKING_LIB_SUPPORT val inline (|NonNullQuick|) : value: 'T | null -> 'T when 'T : not null and 'T : not struct - #else - val inline (|NonNullQuick|) : value: 'T -> 'T - #endif /// A module of comparison and equality operators that are statically resolved, but which are not fully generic and do not make structural comparison. Opening this /// module may make code that relies on structural or generic comparison no longer compile. diff --git a/src/FSharp.Core/resumable.fs b/src/FSharp.Core/resumable.fs index 1488ab220cf..9e24b64bffc 100644 --- a/src/FSharp.Core/resumable.fs +++ b/src/FSharp.Core/resumable.fs @@ -131,11 +131,8 @@ module ResumableCode = /// Note that this requires that the first step has no result. /// This prevents constructs like `task { return 1; return 2; }`. let CombineDynamic - ( - sm: byref>, - code1: ResumableCode<'Data, unit>, - code2: ResumableCode<'Data, 'T> - ) : bool = + (sm: byref>, code1: ResumableCode<'Data, unit>, code2: ResumableCode<'Data, 'T>) + : bool = if code1.Invoke(&sm) then code2.Invoke(&sm) else @@ -170,11 +167,8 @@ module ResumableCode = CombineDynamic(&sm, code1, code2)) let rec WhileDynamic - ( - sm: byref>, - condition: unit -> bool, - body: ResumableCode<'Data, unit> - ) : bool = + (sm: byref>, condition: unit -> bool, body: ResumableCode<'Data, unit>) + : bool = if condition () then if body.Invoke(&sm) then WhileDynamic(&sm, condition, body) @@ -207,10 +201,8 @@ module ResumableCode = /// Builds a step that executes the body while the condition predicate is true. let inline While - ( - [] condition: unit -> bool, - body: ResumableCode<'Data, unit> - ) : ResumableCode<'Data, unit> = + ([] condition: unit -> bool, body: ResumableCode<'Data, unit>) + : ResumableCode<'Data, unit> = ResumableCode<'Data, unit>(fun sm -> if __useResumableCode then //-- RESUMABLE CODE START @@ -252,10 +244,8 @@ module ResumableCode = /// Wraps a step in a try/with. This catches exceptions both in the evaluation of the function /// to retrieve the step, and in the continuation of the step (if any). let inline TryWith - ( - body: ResumableCode<'Data, 'T>, - catch: exn -> ResumableCode<'Data, 'T> - ) : ResumableCode<'Data, 'T> = + (body: ResumableCode<'Data, 'T>, catch: exn -> ResumableCode<'Data, 'T>) + : ResumableCode<'Data, 'T> = ResumableCode<'Data, 'T>(fun sm -> if __useResumableCode then //-- RESUMABLE CODE START @@ -283,11 +273,8 @@ module ResumableCode = TryWithDynamic(&sm, body, catch)) let rec TryFinallyCompensateDynamic - ( - sm: byref>, - mf: ResumptionFunc<'Data>, - savedExn: exn option - ) : bool = + (sm: byref>, mf: ResumptionFunc<'Data>, savedExn: exn option) + : bool = let mutable fin = false fin <- mf.Invoke(&sm) @@ -362,10 +349,8 @@ module ResumableCode = /// Wraps a step in a try/finally. This catches exceptions both in the evaluation of the function /// to retrieve the step, and in the continuation of the step (if any). let inline TryFinallyAsync - ( - body: ResumableCode<'Data, 'T>, - compensation: ResumableCode<'Data, unit> - ) : ResumableCode<'Data, 'T> = + (body: ResumableCode<'Data, 'T>, compensation: ResumableCode<'Data, unit>) + : ResumableCode<'Data, 'T> = ResumableCode<'Data, 'T>(fun sm -> if __useResumableCode then //-- RESUMABLE CODE START @@ -396,10 +381,8 @@ module ResumableCode = TryFinallyAsyncDynamic(&sm, body, compensation)) let inline Using - ( - resource: 'Resource, - body: 'Resource -> ResumableCode<'Data, 'T> - ) : ResumableCode<'Data, 'T> when 'Resource :> IDisposable|null = + (resource: 'Resource, body: 'Resource -> ResumableCode<'Data, 'T>) + : ResumableCode<'Data, 'T> when 'Resource :> IDisposable | null = // A using statement is just a try/finally with the finally block disposing if non-null. TryFinally( ResumableCode<'Data, 'T>(fun sm -> (body resource).Invoke(&sm)), diff --git a/src/FSharp.Core/tasks.fs b/src/FSharp.Core/tasks.fs index dfe7f4ba624..687bae5af85 100644 --- a/src/FSharp.Core/tasks.fs +++ b/src/FSharp.Core/tasks.fs @@ -58,36 +58,28 @@ type TaskBuilderBase() = /// Note that this requires that the first step has no result. /// This prevents constructs like `task { return 1; return 2; }`. member inline _.Combine - ( - task1: TaskCode<'TOverall, unit>, - task2: TaskCode<'TOverall, 'T> - ) : TaskCode<'TOverall, 'T> = + (task1: TaskCode<'TOverall, unit>, task2: TaskCode<'TOverall, 'T>) + : TaskCode<'TOverall, 'T> = ResumableCode.Combine(task1, task2) /// Builds a step that executes the body while the condition predicate is true. member inline _.While - ( - [] condition: unit -> bool, - body: TaskCode<'TOverall, unit> - ) : TaskCode<'TOverall, unit> = + ([] condition: unit -> bool, body: TaskCode<'TOverall, unit>) + : TaskCode<'TOverall, unit> = ResumableCode.While(condition, body) /// Wraps a step in a try/with. This catches exceptions both in the evaluation of the function /// to retrieve the step, and in the continuation of the step (if any). member inline _.TryWith - ( - body: TaskCode<'TOverall, 'T>, - catch: exn -> TaskCode<'TOverall, 'T> - ) : TaskCode<'TOverall, 'T> = + (body: TaskCode<'TOverall, 'T>, catch: exn -> TaskCode<'TOverall, 'T>) + : TaskCode<'TOverall, 'T> = ResumableCode.TryWith(body, catch) /// Wraps a step in a try/finally. This catches exceptions both in the evaluation of the function /// to retrieve the step, and in the continuation of the step (if any). member inline _.TryFinally - ( - body: TaskCode<'TOverall, 'T>, - [] compensation: unit -> unit - ) : TaskCode<'TOverall, 'T> = + (body: TaskCode<'TOverall, 'T>, [] compensation: unit -> unit) + : TaskCode<'TOverall, 'T> = ResumableCode.TryFinally( body, ResumableCode<_, _>(fun _sm -> @@ -100,10 +92,8 @@ type TaskBuilderBase() = #if NETSTANDARD2_1 member inline internal this.TryFinallyAsync - ( - body: TaskCode<'TOverall, 'T>, - compensation: unit -> ValueTask - ) : TaskCode<'TOverall, 'T> = + (body: TaskCode<'TOverall, 'T>, compensation: unit -> ValueTask) + : TaskCode<'TOverall, 'T> = ResumableCode.TryFinallyAsync( body, ResumableCode<_, _>(fun sm -> @@ -138,11 +128,9 @@ type TaskBuilderBase() = false) ) - member inline this.Using<'Resource, 'TOverall, 'T when 'Resource :> IAsyncDisposable|null> - ( - resource: 'Resource, - body: 'Resource -> TaskCode<'TOverall, 'T> - ) : TaskCode<'TOverall, 'T> = + member inline this.Using<'Resource, 'TOverall, 'T when 'Resource :> IAsyncDisposable | null> + (resource: 'Resource, body: 'Resource -> TaskCode<'TOverall, 'T>) + : TaskCode<'TOverall, 'T> = this.TryFinallyAsync( (fun sm -> (body resource).Invoke(&sm)), (fun () -> @@ -310,11 +298,8 @@ module LowPriority = and ^Awaiter :> ICriticalNotifyCompletion and ^Awaiter: (member get_IsCompleted: unit -> bool) and ^Awaiter: (member GetResult: unit -> 'TResult1)> - ( - sm: byref<_>, - task: ^TaskLike, - continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>) - ) : bool = + (sm: byref<_>, task: ^TaskLike, continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>)) + : bool = let mutable awaiter = (^TaskLike: (member GetAwaiter: unit -> ^Awaiter) (task)) @@ -337,10 +322,8 @@ module LowPriority = and ^Awaiter :> ICriticalNotifyCompletion and ^Awaiter: (member get_IsCompleted: unit -> bool) and ^Awaiter: (member GetResult: unit -> 'TResult1)> - ( - task: ^TaskLike, - continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>) - ) : TaskCode<'TOverall, 'TResult2> = + (task: ^TaskLike, continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>)) + : TaskCode<'TOverall, 'TResult2> = TaskCode<'TOverall, _>(fun sm -> if __useResumableCode then @@ -382,11 +365,9 @@ module LowPriority = this.Bind(task, this.Return) - member inline _.Using<'Resource, 'TOverall, 'T when 'Resource :> IDisposable|null> - ( - resource: 'Resource, - body: 'Resource -> TaskCode<'TOverall, 'T> - ) = + member inline _.Using<'Resource, 'TOverall, 'T when 'Resource :> IDisposable | null> + (resource: 'Resource, body: 'Resource -> TaskCode<'TOverall, 'T>) + = ResumableCode.Using(resource, body) module HighPriority = @@ -394,11 +375,8 @@ module HighPriority = type TaskBuilderBase with static member BindDynamic - ( - sm: byref<_>, - task: Task<'TResult1>, - continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>) - ) : bool = + (sm: byref<_>, task: Task<'TResult1>, continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>)) + : bool = let mutable awaiter = task.GetAwaiter() let cont = @@ -415,10 +393,8 @@ module HighPriority = false member inline _.Bind - ( - task: Task<'TResult1>, - continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>) - ) : TaskCode<'TOverall, 'TResult2> = + (task: Task<'TResult1>, continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>)) + : TaskCode<'TOverall, 'TResult2> = TaskCode<'TOverall, _>(fun sm -> if __useResumableCode then @@ -455,10 +431,8 @@ module MediumPriority = type TaskBuilderBase with member inline this.Bind - ( - computation: Async<'TResult1>, - continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>) - ) : TaskCode<'TOverall, 'TResult2> = + (computation: Async<'TResult1>, continuation: ('TResult1 -> TaskCode<'TOverall, 'TResult2>)) + : TaskCode<'TOverall, 'TResult2> = this.Bind(Async.StartImmediateAsTask computation, continuation) member inline this.ReturnFrom(computation: Async<'T>) : TaskCode<'T, 'T> = diff --git a/src/FSharp.Core/tasks.fsi b/src/FSharp.Core/tasks.fsi index c626cb4bb7b..e6c801351a1 100644 --- a/src/FSharp.Core/tasks.fsi +++ b/src/FSharp.Core/tasks.fsi @@ -237,7 +237,7 @@ module LowPriority = /// member inline Using: resource: 'Resource * body: ('Resource -> TaskCode<'TOverall, 'T>) -> TaskCode<'TOverall, 'T> - when 'Resource :> IDisposable|null + when 'Resource :> IDisposable | null /// /// Contains medium-priority overloads for the `task` computation expression builder. diff --git a/src/fsi/console.fs b/src/fsi/console.fs index d644180d384..1d495d0cd48 100644 --- a/src/fsi/console.fs +++ b/src/fsi/console.fs @@ -30,14 +30,14 @@ type internal History() = list.Clear() current <- -1 - member _.Add (line: string | null) = - match line with + member _.Add(line: string | null) = + match line with | null | "" -> () | _ -> list.Add(line) - member _.AddLast (line: string | null) = - match line with + member _.AddLast(line: string | null) = + match line with | null | "" -> () | _ -> diff --git a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_net9.0.bsl b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_net9.0.bsl index 4466d718308..69842b9e059 100644 --- a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_net9.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_net9.0.bsl @@ -50,7 +50,7 @@ [IL]: Error [StackUnexpected]: : .$FSharp.Compiler.Syntax.PrettyNaming::.cctor()][offset 0x00001220][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$FSharp.Compiler.Syntax.PrettyNaming::.cctor()][offset 0x00001229][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryWriter::writeILMetadataAndCode(bool, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.IL+ILVersionInfo, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.IL+ILGlobals, bool, bool, bool, [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1, [S.P.CoreLib]System.Collections.Generic.IEnumerable`1, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.IL+ILModuleDef, int32, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2)][offset 0x0000063F][found Boolean] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryWriter+bigness@3406::Invoke(int32)][offset 0x00000007][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryWriter+bigness@3402::Invoke(int32)][offset 0x00000007][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILPdbWriter+PortablePdbGenerator::serializeDocumentName(string)][offset 0x00000090][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILPdbWriter+pushShadowedLocals@959::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000232][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::seekReadUntaggedIdx([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.BinaryConstants+TableName, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+ILMetadataReader, [FSharp.Compiler.Service]FSharp.Compiler.IO.ReadOnlyByteMemory, int32&)][offset 0x0000000D][found Byte] Unexpected type on the stack. @@ -70,4 +70,4 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.IO.FileSystemUtils::trimQuotes(string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.IO.FileSystemUtils::trimQuotes(string)][offset 0x00000014][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.Library.String::lowerCaseFirstChar(string)][offset 0x0000003F][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Internal.Utilities.Library.Array+loop@276-4::Invoke(int32)][offset 0x00000012][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Internal.Utilities.Library.Array+loop@275-4::Invoke(int32)][offset 0x00000012][found Byte] Unexpected type on the stack. diff --git a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_netstandard2.0.bsl b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_netstandard2.0.bsl index d5617f6de03..6e41547cd11 100644 --- a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_netstandard2.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Debug_netstandard2.0.bsl @@ -55,7 +55,7 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions+ResponseFile+parseLine@239::Invoke(string)][offset 0x00000031][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+Pipe #1 stage #1 at line 1845@1845::Invoke(int32)][offset 0x00000030][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+Pipe #1 stage #1 at line 1845@1845::Invoke(int32)][offset 0x00000039][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerImports+line@560-1::Invoke(string)][offset 0x0000000B][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerImports+line@570-1::Invoke(string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerConfig+TcConfig::.ctor([FSharp.Compiler.Service]FSharp.Compiler.CompilerConfig+TcConfigBuilder, bool)][offset 0x0000062B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerConfig+TcConfig::.ctor([FSharp.Compiler.Service]FSharp.Compiler.CompilerConfig+TcConfigBuilder, bool)][offset 0x00000634][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.PatternMatchCompilation::isProblematicClause([FSharp.Compiler.Service]FSharp.Compiler.PatternMatchCompilation+MatchClause)][offset 0x00000065][found Byte] Unexpected type on the stack. @@ -70,7 +70,7 @@ [IL]: Error [StackUnexpected]: : .$FSharp.Compiler.Syntax.PrettyNaming::.cctor()][offset 0x00001220][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : .$FSharp.Compiler.Syntax.PrettyNaming::.cctor()][offset 0x00001229][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryWriter::writeILMetadataAndCode(bool, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.IL+ILVersionInfo, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.IL+ILGlobals, bool, bool, bool, [FSharp.Core]Microsoft.FSharp.Core.FSharpOption`1, [S.P.CoreLib]System.Collections.Generic.IEnumerable`1, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.IL+ILModuleDef, int32, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2)][offset 0x0000063F][found Boolean] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryWriter+bigness@3406::Invoke(int32)][offset 0x00000007][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryWriter+bigness@3402::Invoke(int32)][offset 0x00000007][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILPdbWriter+PortablePdbGenerator::serializeDocumentName(string)][offset 0x00000090][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILPdbWriter+pushShadowedLocals@959::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000232][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.ILBinaryReader::seekReadUntaggedIdx([FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.BinaryConstants+TableName, [FSharp.Compiler.Service]FSharp.Compiler.AbstractIL.ILBinaryReader+ILMetadataReader, [FSharp.Compiler.Service]FSharp.Compiler.IO.ReadOnlyByteMemory, int32&)][offset 0x0000000D][found Byte] Unexpected type on the stack. @@ -79,7 +79,7 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.NativeRes+VersionHelper::TryParse(string, bool, uint16, bool, [S.P.CoreLib]System.Version&)][offset 0x0000003D][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.IL::parseILVersion(string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.IL::parseILVersion(string)][offset 0x00000021][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.IL+parseNamed@5291::Invoke([FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1>, int32, int32)][offset 0x00000087][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.IL+parseNamed@5311::Invoke([FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1>, int32, int32)][offset 0x00000087][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.Collections.Utils::shortPath(string)][offset 0x00000015][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.FSharpEnvironment+probePathForDotnetHost@316::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000028][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CodeAnalysis.SimulatedMSBuildReferenceResolver+Pipe #6 input at line 68@68::FSharp.Compiler.CodeAnalysis.ILegacyReferenceResolver.Resolve([FSharp.Compiler.Service]FSharp.Compiler.CodeAnalysis.LegacyResolutionEnvironment, [S.P.CoreLib]System.Tuple`2[], string, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, string, string, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, string, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>>)][offset 0x0000034D][found Char] Unexpected type on the stack. @@ -95,4 +95,4 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.IO.FileSystemUtils::trimQuotes(string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.IO.FileSystemUtils::trimQuotes(string)][offset 0x00000014][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.Library.String::lowerCaseFirstChar(string)][offset 0x0000003F][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Internal.Utilities.Library.Array+loop@276-4::Invoke(int32)][offset 0x00000012][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Internal.Utilities.Library.Array+loop@275-4::Invoke(int32)][offset 0x00000012][found Byte] Unexpected type on the stack. diff --git a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_net9.0.bsl b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_net9.0.bsl index 9e78cdedccd..4e7b5396676 100644 --- a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_net9.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_net9.0.bsl @@ -96,4 +96,4 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.IO.FileSystemUtils::trimQuotes(string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.IO.FileSystemUtils::trimQuotes(string)][offset 0x00000014][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.Library.String::lowerCaseFirstChar(string)][offset 0x0000003A][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Internal.Utilities.Library.Array::loop@275-3(bool[], int32)][offset 0x00000008][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Internal.Utilities.Library.Array::loop@274-3(bool[], int32)][offset 0x00000008][found Byte] Unexpected type on the stack. diff --git a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_netstandard2.0.bsl b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_netstandard2.0.bsl index 87b09e193a5..431d4e5512a 100644 --- a/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_netstandard2.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Compiler.Service_Release_netstandard2.0.bsl @@ -57,8 +57,8 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerOptions+ResponseFile+parseLine@239::Invoke(string)][offset 0x00000026][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+CheckMultipleInputsUsingGraphMode@1845::Invoke(int32)][offset 0x00000031][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.ParseAndCheckInputs+CheckMultipleInputsUsingGraphMode@1845::Invoke(int32)][offset 0x0000003A][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerImports+TcConfig-TryResolveLibWithDirectories@558-1::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000021][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerImports+TcConfig-TryResolveLibWithDirectories@558-1::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x0000003B][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerImports+TcConfig-TryResolveLibWithDirectories@568-1::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x00000021][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerImports+TcConfig-TryResolveLibWithDirectories@568-1::Invoke([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x0000003B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerConfig+TcConfig::.ctor([FSharp.Compiler.Service]FSharp.Compiler.CompilerConfig+TcConfigBuilder, bool)][offset 0x0000059C][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CompilerConfig+TcConfig::.ctor([FSharp.Compiler.Service]FSharp.Compiler.CompilerConfig+TcConfigBuilder, bool)][offset 0x000005A5][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.IlxGen::HashRangeSorted([S.P.CoreLib]System.Collections.Generic.IDictionary`2>)][offset 0x00000011][found ref '[FSharp.Compiler.Service]FSharp.Compiler.IlxGen+HashRangeSorted@1873-1'][expected ref '[FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2,int32>'] Unexpected type on the stack. @@ -106,7 +106,7 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.NativeRes+VersionHelper::TryParse(string, bool, uint16, bool, [S.P.CoreLib]System.Version&)][offset 0x00000026][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.IL::parseILVersion(string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.IL::parseILVersion(string)][offset 0x00000021][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.IL::parseNamed@5290(uint8[], [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1>, int32, int32)][offset 0x0000007E][found Char] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : FSharp.Compiler.AbstractIL.IL::parseNamed@5310(uint8[], [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1>, int32, int32)][offset 0x0000007E][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.Collections.Utils::shortPath(string)][offset 0x00000016][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.FSharpEnvironment::probePathForDotnetHost@315([FSharp.Core]Microsoft.FSharp.Core.Unit)][offset 0x0000002A][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.CodeAnalysis.SimulatedMSBuildReferenceResolver+SimulatedMSBuildResolver@68::FSharp.Compiler.CodeAnalysis.ILegacyReferenceResolver.Resolve([FSharp.Compiler.Service]FSharp.Compiler.CodeAnalysis.LegacyResolutionEnvironment, [S.P.CoreLib]System.Tuple`2[], string, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, string, string, [FSharp.Core]Microsoft.FSharp.Collections.FSharpList`1, string, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, [FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>>)][offset 0x000002F5][found Char] Unexpected type on the stack. @@ -122,4 +122,4 @@ [IL]: Error [StackUnexpected]: : FSharp.Compiler.IO.FileSystemUtils::trimQuotes(string)][offset 0x0000000B][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : FSharp.Compiler.IO.FileSystemUtils::trimQuotes(string)][offset 0x00000014][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Internal.Utilities.Library.String::lowerCaseFirstChar(string)][offset 0x0000003A][found Char] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Internal.Utilities.Library.Array::loop@275-3(bool[], int32)][offset 0x00000008][found Byte] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Internal.Utilities.Library.Array::loop@274-3(bool[], int32)][offset 0x00000008][found Byte] Unexpected type on the stack. diff --git a/tests/ILVerify/ilverify_FSharp.Core_Debug_netstandard2.0.bsl b/tests/ILVerify/ilverify_FSharp.Core_Debug_netstandard2.0.bsl index 2e94b26033c..4e6bca186fd 100644 --- a/tests/ILVerify/ilverify_FSharp.Core_Debug_netstandard2.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Core_Debug_netstandard2.0.bsl @@ -1,8 +1,8 @@ [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Choose([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, !!0[])][offset 0x000000A0][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Filter([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, !!0[])][offset 0x00000029][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Partition([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, !!0[])][offset 0x00000038][found Byte] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Pipe #2 input at line 2241@2245-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000030][found Boolean] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Pipe #2 input at line 2571@2575-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000022][found Boolean] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Pipe #2 input at line 2238@2242-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000030][found Boolean] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Pipe #2 input at line 2568@2572-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000022][found Boolean] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::Map([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, string)][offset 0x00000020][found Short] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::Map([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, string)][offset 0x00000031][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::MapIndexed([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, string)][offset 0x00000029][found Short] Unexpected type on the stack. diff --git a/tests/ILVerify/ilverify_FSharp.Core_Debug_netstandard2.1.bsl b/tests/ILVerify/ilverify_FSharp.Core_Debug_netstandard2.1.bsl index 2e94b26033c..4e6bca186fd 100644 --- a/tests/ILVerify/ilverify_FSharp.Core_Debug_netstandard2.1.bsl +++ b/tests/ILVerify/ilverify_FSharp.Core_Debug_netstandard2.1.bsl @@ -1,8 +1,8 @@ [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Choose([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, !!0[])][offset 0x000000A0][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Filter([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, !!0[])][offset 0x00000029][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Partition([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, !!0[])][offset 0x00000038][found Byte] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Pipe #2 input at line 2241@2245-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000030][found Boolean] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Pipe #2 input at line 2571@2575-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000022][found Boolean] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Pipe #2 input at line 2238@2242-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000030][found Boolean] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Pipe #2 input at line 2568@2572-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000022][found Boolean] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::Map([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, string)][offset 0x00000020][found Short] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::Map([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, string)][offset 0x00000031][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::MapIndexed([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, string)][offset 0x00000029][found Short] Unexpected type on the stack. diff --git a/tests/ILVerify/ilverify_FSharp.Core_Release_netstandard2.0.bsl b/tests/ILVerify/ilverify_FSharp.Core_Release_netstandard2.0.bsl index 4bc36bdc008..6ab50914fdd 100644 --- a/tests/ILVerify/ilverify_FSharp.Core_Release_netstandard2.0.bsl +++ b/tests/ILVerify/ilverify_FSharp.Core_Release_netstandard2.0.bsl @@ -1,8 +1,8 @@ [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Choose([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, !!0[])][offset 0x00000081][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Filter([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, !!0[])][offset 0x00000029][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Partition([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, !!0[])][offset 0x00000038][found Byte] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Choose@2245-2::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000030][found Boolean] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+countAndCollectTrueItems@2575-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000022][found Boolean] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Choose@2242-2::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000030][found Boolean] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+countAndCollectTrueItems@2572-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000022][found Boolean] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::Map([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, string)][offset 0x0000001E][found Short] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::Map([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, string)][offset 0x0000002D][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::MapIndexed([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, string)][offset 0x00000029][found Short] Unexpected type on the stack. diff --git a/tests/ILVerify/ilverify_FSharp.Core_Release_netstandard2.1.bsl b/tests/ILVerify/ilverify_FSharp.Core_Release_netstandard2.1.bsl index 4bc36bdc008..6ab50914fdd 100644 --- a/tests/ILVerify/ilverify_FSharp.Core_Release_netstandard2.1.bsl +++ b/tests/ILVerify/ilverify_FSharp.Core_Release_netstandard2.1.bsl @@ -1,8 +1,8 @@ [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Choose([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, !!0[])][offset 0x00000081][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Filter([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, !!0[])][offset 0x00000029][found Byte] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel::Partition([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, !!0[])][offset 0x00000038][found Byte] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Choose@2245-2::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000030][found Boolean] Unexpected type on the stack. -[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+countAndCollectTrueItems@2575-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000022][found Boolean] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+Choose@2242-2::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000030][found Boolean] Unexpected type on the stack. +[IL]: Error [StackUnexpected]: : Microsoft.FSharp.Collections.ArrayModule+Parallel+countAndCollectTrueItems@2572-1::Invoke(int32, [System.Threading.Tasks.Parallel]System.Threading.Tasks.ParallelLoopState, int32)][offset 0x00000022][found Boolean] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::Map([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, string)][offset 0x0000001E][found Short] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::Map([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2, string)][offset 0x0000002D][found Char] Unexpected type on the stack. [IL]: Error [StackUnexpected]: : Microsoft.FSharp.Core.StringModule::MapIndexed([FSharp.Core]Microsoft.FSharp.Core.FSharpFunc`2>, string)][offset 0x00000029][found Short] Unexpected type on the stack. From a3181c4c8e5a286a38f986a79024a74bfc650fb5 Mon Sep 17 00:00:00 2001 From: Maxime Mangel Date: Thu, 27 Mar 2025 12:06:05 +0100 Subject: [PATCH 07/20] Fix `fcs.fs` link (#18419) --- docs/reusing-typechecking-results.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reusing-typechecking-results.md b/docs/reusing-typechecking-results.md index 247e26f21dd..9eedc036ab0 100644 --- a/docs/reusing-typechecking-results.md +++ b/docs/reusing-typechecking-results.md @@ -25,7 +25,7 @@ Here are some assumptions I am coming with after tinkering with the topic and in ### Premise 1: current compiler design -The heart of the compiler, [fsc.fs](src\Compiler\Driver\fsc.fs), is split into 6 phases (`main1` - `main6`). The code is designed to pass minimum information between phases, using the `Args` structure, which is essentially a data bag. The first phase takes info from the program arguments. +The heart of the compiler, [fsc.fs](../src/Compiler/Driver/fsc.fs), is split into 6 phases (`main1` - `main6`). The code is designed to pass minimum information between phases, using the `Args` structure, which is essentially a data bag. The first phase takes info from the program arguments. ```fsharp main1 (...args...) From af2ebfa79eb026c92dc28974608ddfa06cba3964 Mon Sep 17 00:00:00 2001 From: Tomas Grosup Date: Thu, 27 Mar 2025 15:02:40 +0100 Subject: [PATCH 08/20] Re-enable unused bindings detection (#18420) * reenable unused binding detection * fantomas * vsintegration/tests - ignored unused bindings in selected test projects --- Directory.Build.props | 5 ----- FSharp.sln | 1 + FSharpBuild.Directory.Build.props | 3 ++- .../Checking/Expressions/CheckExpressions.fs | 4 ++-- .../Expressions/CheckSequenceExpressions.fs | 4 ++-- src/Compiler/Checking/TailCallChecks.fs | 2 +- src/Compiler/Checking/infos.fs | 4 ++-- src/Compiler/CodeGen/EraseUnions.fs | 1 - src/Compiler/Driver/CompilerDiagnostics.fs | 2 +- src/Compiler/FSharp.Compiler.Service.fsproj | 8 +------ src/Compiler/Facilities/AsyncMemoize.fs | 2 +- src/Compiler/Service/TransparentCompiler.fs | 2 +- src/Compiler/SyntaxTree/LexerStore.fs | 2 -- src/Compiler/SyntaxTree/SyntaxTreeOps.fs | 6 ++--- src/Compiler/TypedTree/TypedTreeOps.fs | 4 ++-- .../CreateFSharpManifestResourceName.fs | 2 +- src/FSharp.Build/FSharpEmbedResourceText.fs | 8 +++---- src/FSharp.Build/Fsc.fs | 5 +---- src/FSharp.Build/Fsi.fs | 3 --- src/FSharp.Build/MapSourceRoots.fs | 2 +- .../FSharp.DependencyManager.Nuget.fsproj | 1 - .../MapSourceRootsTests.fs | 2 ++ .../DependencyManagerInteractiveTests.fs | 21 ++++-------------- .../FSharpScriptTests.fs | 22 +++++++++---------- .../AssemblyReaderShim.fs | 2 +- tests/FSharp.Compiler.Service.Tests/Common.fs | 8 +++---- .../FSharp.Compiler.Service.Tests.fsproj | 1 + .../FSharpExprPatternsTests.fs | 4 ++-- .../GeneratedCodeSymbolsTests.fs | 12 +++++----- .../ModuleReaderCancellationTests.fs | 17 +++++--------- .../ProjectAnalysisTests.fs | 11 +++++----- .../FSharp.Compiler.Service.Tests/Symbols.fs | 10 ++++----- .../TooltipTests.fs | 7 +++--- .../FSharp.Core.UnitTests.fsproj | 1 + tests/service/data/TestTP/TestTP.fs | 2 ++ .../src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj | 2 +- ...myProviderForLanguageServiceTesting.fsproj | 2 +- .../tests/Salsa/VisualFSharp.Salsa.fsproj | 2 +- .../UnitTests/VisualFSharp.UnitTests.fsproj | 2 +- 39 files changed, 83 insertions(+), 116 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index fbb9c8332c7..141c85ff4d2 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -10,11 +10,6 @@ $(DotNetBuildSourceOnly) - - - $(NoWarn);FS0064;FS1182 - - $(NoWarn);1204 $(NoWarn);NU5125 - $(NoWarn);64;1182;1204 - $(OtherFlags) --warnaserror-:1182 + $(NoWarn);64;1204 FSharp.Compiler.Service true $(DefineConstants);COMPILER @@ -26,11 +25,6 @@ $(FSharpNetCoreProductTargetFramework);$(TargetFrameworks) $(DefineConstants);FSHARPCORE_USE_PACKAGE $(OtherFlags) --extraoptimizationloops:1 - - - - $(OtherFlags) --nowarn:1182 - $(OtherFlags) --warnon:3218 diff --git a/src/Compiler/Facilities/AsyncMemoize.fs b/src/Compiler/Facilities/AsyncMemoize.fs index a8a4d5b143f..ac52eaf8607 100644 --- a/src/Compiler/Facilities/AsyncMemoize.fs +++ b/src/Compiler/Facilities/AsyncMemoize.fs @@ -183,7 +183,7 @@ type internal AsyncMemoize<'TKey, 'TVersion, 'TValue when 'TKey: equality and 'TVersion: equality and 'TKey: not null and 'TVersion: not null> (?keepStrongly, ?keepWeakly, ?name: string, ?cancelUnawaitedJobs: bool, ?cancelDuplicateRunningJobs: bool) = - let name = defaultArg name "N/A" + let _name = defaultArg name "N/A" let cancelUnawaitedJobs = defaultArg cancelUnawaitedJobs true let cancelDuplicateRunningJobs = defaultArg cancelDuplicateRunningJobs false diff --git a/src/Compiler/Service/TransparentCompiler.fs b/src/Compiler/Service/TransparentCompiler.fs index 39560cb3b6b..4385ca4f1e3 100644 --- a/src/Compiler/Service/TransparentCompiler.fs +++ b/src/Compiler/Service/TransparentCompiler.fs @@ -2355,7 +2355,7 @@ type internal TransparentCompiler ( fileName: string, sourceText: ISourceTextNew, - caret: Position option, + _caret: Position option, documentSource: DocumentSource, previewEnabled: bool option, loadedTimeStamp: DateTime option, diff --git a/src/Compiler/SyntaxTree/LexerStore.fs b/src/Compiler/SyntaxTree/LexerStore.fs index 711e9530cd9..2914d944c20 100644 --- a/src/Compiler/SyntaxTree/LexerStore.fs +++ b/src/Compiler/SyntaxTree/LexerStore.fs @@ -32,8 +32,6 @@ let private tryGetStoreData<'T when 'T: not null> (lexbuf: Lexbuf) key = | true, data -> Some(data :?> 'T) | _ -> None -let private setStoreData (lexbuf: Lexbuf) key data = lexbuf.BufferLocalStore[key] <- data - //------------------------------------------------------------------------ // A SynArgNameGenerator for the current file, used by the parser //------------------------------------------------------------------------ diff --git a/src/Compiler/SyntaxTree/SyntaxTreeOps.fs b/src/Compiler/SyntaxTree/SyntaxTreeOps.fs index ffb9bd65647..6633dab2408 100644 --- a/src/Compiler/SyntaxTree/SyntaxTreeOps.fs +++ b/src/Compiler/SyntaxTree/SyntaxTreeOps.fs @@ -1024,9 +1024,9 @@ let parsedHashDirectiveArgumentsNoCheck (input: ParsedHashDirectiveArgument list (function | ParsedHashDirectiveArgument.String(s, _, _) -> s | ParsedHashDirectiveArgument.SourceIdentifier(_, v, _) -> v - | ParsedHashDirectiveArgument.Int32(n, m) -> string n - | ParsedHashDirectiveArgument.Ident(ident, m) -> ident.idText - | ParsedHashDirectiveArgument.LongIdent(ident, m) -> longIdentToString ident) + | ParsedHashDirectiveArgument.Int32(n, _) -> string n + | ParsedHashDirectiveArgument.Ident(ident, _) -> ident.idText + | ParsedHashDirectiveArgument.LongIdent(ident, _) -> longIdentToString ident) input let parsedHashDirectiveStringArguments (input: ParsedHashDirectiveArgument list) (_langVersion: LanguageVersion) = diff --git a/src/Compiler/TypedTree/TypedTreeOps.fs b/src/Compiler/TypedTree/TypedTreeOps.fs index 33dd6c2757c..21c9783713e 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.fs +++ b/src/Compiler/TypedTree/TypedTreeOps.fs @@ -9241,7 +9241,7 @@ let GetDisallowedNullness (g:TcGlobals) (ty:TType) = | None -> [] | Some t -> hasWithNullAnyWhere t withNull - | TType_app (tcr, tinst, nullnessOrig) -> + | TType_app (tcr, tinst, _) -> let tyArgs = tinst |> List.collect (fun t -> hasWithNullAnyWhere t false) match alreadyWrappedInOuterWithNull, tcr.TypeAbbrev with @@ -9260,7 +9260,7 @@ let GetDisallowedNullness (g:TcGlobals) (ty:TType) = let inner = tupTypes |> List.collect (fun t -> hasWithNullAnyWhere t false) if alreadyWrappedInOuterWithNull then ty :: inner else inner - | TType_anon (anon,tys) -> + | TType_anon (tys=tys) -> let inner = tys |> List.collect (fun t -> hasWithNullAnyWhere t false) if alreadyWrappedInOuterWithNull then ty :: inner else inner | TType_fun (d, r, _) -> diff --git a/src/FSharp.Build/CreateFSharpManifestResourceName.fs b/src/FSharp.Build/CreateFSharpManifestResourceName.fs index a19c9fada32..c39f7ae3da0 100644 --- a/src/FSharp.Build/CreateFSharpManifestResourceName.fs +++ b/src/FSharp.Build/CreateFSharpManifestResourceName.fs @@ -18,7 +18,7 @@ type CreateFSharpManifestResourceName public () = linkFileName: string, rootNamespace: string, // may be null dependentUponFileName: string, // may be null - binaryStream: Stream // may be null + _binaryStream: Stream // may be null ) : string = // The Visual CSharp and XBuild CSharp toolchains transform resource names like this: diff --git a/src/FSharp.Build/FSharpEmbedResourceText.fs b/src/FSharp.Build/FSharpEmbedResourceText.fs index d8f4a46eb25..1c5ffbfb68b 100644 --- a/src/FSharp.Build/FSharpEmbedResourceText.fs +++ b/src/FSharp.Build/FSharpEmbedResourceText.fs @@ -447,7 +447,7 @@ open Printf let lines = File.ReadAllLines(fileName) |> Array.mapi (fun i s -> i, s) // keep line numbers - |> Array.filter (fun (i, s) -> not (s.StartsWith "#")) // filter out comments + |> Array.filter (fun (_i, s) -> not (s.StartsWith "#")) // filter out comments printMessage "Parsing %s" fileName let stringInfos = lines |> Array.map (fun (i, s) -> ParseLine fileName i s) @@ -511,7 +511,7 @@ open Printf printMessage "Generating resource methods for %s" outFileName // gen each resource method stringInfos - |> Seq.iter (fun (lineNum, (optErrNum, ident), str, holes, netFormatString) -> + |> Seq.iter (fun (lineNum, (optErrNum, ident), str, holes, _netFormatString) -> let formalArgs = new System.Text.StringBuilder() let actualArgs = new System.Text.StringBuilder() let mutable firstTime = true @@ -589,7 +589,7 @@ open Printf fprintfn outSignature " static member RunStartupValidation: unit -> unit" stringInfos - |> Seq.iter (fun (lineNum, (optErrNum, ident), str, holes, netFormatString) -> + |> Seq.iter (fun (_lineNum, (_optErrNum, ident), _str, _holes, _netFormatString) -> fprintfn out " ignore(GetString(\"%s\"))" ident) fprintfn out " ()" // in case there are 0 strings, we need the generated code to parse @@ -598,7 +598,7 @@ open Printf xd.LoadXml(xmlBoilerPlateString) stringInfos - |> Seq.iter (fun (lineNum, (optErrNum, ident), str, holes, netFormatString) -> + |> Seq.iter (fun (_lineNum, (_optErrNum, ident), _str, _holes, netFormatString) -> let xn = xd.CreateElement("data") xn.SetAttribute("name", ident) |> ignore xn.SetAttribute("xml:space", "preserve") |> ignore diff --git a/src/FSharp.Build/Fsc.fs b/src/FSharp.Build/Fsc.fs index ccbece545d5..3cce873e722 100644 --- a/src/FSharp.Build/Fsc.fs +++ b/src/FSharp.Build/Fsc.fs @@ -69,7 +69,6 @@ type public Fsc() as this = let mutable tailcalls: bool = true let mutable targetProfile: string MaybeNull = null let mutable targetType: string MaybeNull = null - let mutable toolExe: string = "fsc.exe" let defaultToolPath = let locationOfThisDll = @@ -733,8 +732,6 @@ type public Fsc() as this = match host with | null -> base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands) | _ -> - let sources = sources |> Array.map (fun i -> i.ItemSpec) - let invokeCompiler baseCallDelegate = try let ret = @@ -765,7 +762,7 @@ type public Fsc() as this = -> fsc.Log.LogError(tie.InnerException.Message, [||]) -1 - | e -> reraise () + | _ -> reraise () let baseCallDelegate = Func(fun () -> fsc.BaseExecuteTool(pathToTool, responseFileCommands, commandLineCommands)) diff --git a/src/FSharp.Build/Fsi.fs b/src/FSharp.Build/Fsi.fs index a8ad12d1b2c..88a6dbf3adb 100644 --- a/src/FSharp.Build/Fsi.fs +++ b/src/FSharp.Build/Fsi.fs @@ -37,15 +37,12 @@ type public Fsi() as this = let mutable provideCommandLineArgs = false let mutable references: ITaskItem[] = [||] let mutable referencePath: string MaybeNull = null - let mutable resources: ITaskItem[] = [||] let mutable skipCompilerExecution = false let mutable sources: ITaskItem[] = [||] let mutable loadSources: ITaskItem[] = [||] let mutable useSources: ITaskItem[] = [||] let mutable tailcalls: bool = true let mutable targetProfile: string MaybeNull = null - let mutable targetType: string MaybeNull = null - let mutable toolExe: string = "fsi.exe" let mutable toolPath: string = let locationOfThisDll = diff --git a/src/FSharp.Build/MapSourceRoots.fs b/src/FSharp.Build/MapSourceRoots.fs index c2131209dad..8ea92c02197 100644 --- a/src/FSharp.Build/MapSourceRoots.fs +++ b/src/FSharp.Build/MapSourceRoots.fs @@ -130,7 +130,7 @@ type MapSourceRoots() = for root in mappedSourceRoots do match root.GetMetadata SourceControl with - | HasValue v when isSourceControlled -> mapNestedRootIfEmpty root + | HasValue _ when isSourceControlled -> mapNestedRootIfEmpty root | NullOrEmpty when not isSourceControlled -> mapNestedRootIfEmpty root | _ -> () diff --git a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Nuget.fsproj b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Nuget.fsproj index 4700c172f52..96e318d282c 100644 --- a/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Nuget.fsproj +++ b/src/FSharp.DependencyManager.Nuget/FSharp.DependencyManager.Nuget.fsproj @@ -8,7 +8,6 @@ FSharp.DependencyManager.Nuget true $(DefineConstants);COMPILER - $(OtherFlags) --warnon:1182 true Debug;Release diff --git a/tests/FSharp.Build.UnitTests/MapSourceRootsTests.fs b/tests/FSharp.Build.UnitTests/MapSourceRootsTests.fs index bdefa03d96a..ec590e52e42 100644 --- a/tests/FSharp.Build.UnitTests/MapSourceRootsTests.fs +++ b/tests/FSharp.Build.UnitTests/MapSourceRootsTests.fs @@ -9,6 +9,8 @@ open Xunit open System.Collections.Generic open FSharp.Test +#nowarn "1182" //Unused arguments + type MockEngine() = member val Errors = ResizeArray() with get member val Warnings = ResizeArray() with get diff --git a/tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs b/tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs index 7f320fea23f..3e6b7b27e43 100644 --- a/tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs +++ b/tests/FSharp.Compiler.Private.Scripting.UnitTests/DependencyManagerInteractiveTests.fs @@ -39,8 +39,6 @@ type DependencyManagerInteractiveTests() = let getErrors ((_value: Result), (errors: FSharpDiagnostic[])) = errors - let ignoreValue = getValue >> ignore - [] member _.``SmokeTest - #r nuget``() = let text = """ @@ -58,7 +56,7 @@ type DependencyManagerInteractiveTests() = #r @"nuget:System.Collections.Immutable.DoesNotExist, version=1.5.0" 0""" use script = new scriptHost() - let opt, errors = script.Eval(text) + let _opt, errors = script.Eval(text) Assert.Equal(errors.Length, 1) (* @@ -152,8 +150,6 @@ type DependencyManagerInteractiveTests() = [] member _.``Multiple Instances of DependencyProvider should be isolated``() = - - let assemblyProbingPaths () = Seq.empty let nativeProbingRoots () = Seq.empty use dp1 = new DependencyProvider(NativeResolutionProbe(nativeProbingRoots), false) @@ -282,7 +278,6 @@ TorchSharp.Tensor.LongTensor.From([| 0L .. 100L |]).Device | ErrorReportType.Warning -> printfn "PackageManagementWarning %d : %s" code message ResolvingErrorReport (report) - let mutable resolverPackageRoots = Seq.empty let mutable resolverPackageRoots = Seq.empty let mutable resolverReferences = Seq.empty @@ -383,11 +378,9 @@ printfn ""%A"" result ResolvingErrorReport (report) let mutable resolverPackageRoots = Seq.empty - let mutable resolverPackageRoots = Seq.empty let mutable resolverReferences = Seq.empty let nativeProbingRoots () = resolverPackageRoots - let assemblyPaths () = resolverReferences // Restore packages, Get Reference dll paths and package roots let result = @@ -526,10 +519,7 @@ x |> Seq.iter(fun r -> ResolvingErrorReport (report) let mutable resolverPackageRoots = Seq.empty - let mutable resolverReferences = Seq.empty - let nativeProbingRoots () = resolverPackageRoots - let assemblyProbingPaths () = resolverReferences // Restore packages, Get Reference dll paths and package roots let result = @@ -552,10 +542,7 @@ x |> Seq.iter(fun r -> ResolvingErrorReport (report) let mutable resolverPackageRoots = Seq.empty - let mutable resolverReferences = Seq.empty - let nativeProbingRoots () = resolverPackageRoots - let assemblyProbingPaths () = resolverReferences // Restore packages, Get Reference dll paths and package roots let result = @@ -740,7 +727,7 @@ x |> Seq.iter(fun r -> use script = new FSharpScript(quiet = false, langVersion = LangVersion.V47) use capture = new TestConsole.ExecutionCapture() - let opt = script.Eval("#help") |> getValue + let _opt = script.Eval("#help") |> getValue let output = capture.OutText @@ -772,7 +759,7 @@ x |> Seq.iter(fun r -> use script = new FSharpScript(quiet = false, langVersion = LangVersion.Preview) use capture = new TestConsole.ExecutionCapture() - let opt = script.Eval("#help") |> getValue + let _opt = script.Eval("#help") |> getValue let output = capture.OutText @@ -871,7 +858,7 @@ x |> Seq.iter(fun r -> let idm = dp.TryFindDependencyManagerByKey(Seq.empty, "", reportError, "nuget") // Resolve and cache the results won't time out - let result = dp.Resolve(idm, ".fsx", [|"r", "FSharp.Data,3.3.3"; "r", "timeout=10000"|], reportError, "net9.0", null, "", "", "", -1) // Wait forever + let _result = dp.Resolve(idm, ".fsx", [|"r", "FSharp.Data,3.3.3"; "r", "timeout=10000"|], reportError, "net9.0", null, "", "", "", -1) // Wait forever // Clear the results foundCorrectError <- false diff --git a/tests/FSharp.Compiler.Private.Scripting.UnitTests/FSharpScriptTests.fs b/tests/FSharp.Compiler.Private.Scripting.UnitTests/FSharpScriptTests.fs index ecf5b81d97b..207cde1074f 100644 --- a/tests/FSharp.Compiler.Private.Scripting.UnitTests/FSharpScriptTests.fs +++ b/tests/FSharp.Compiler.Private.Scripting.UnitTests/FSharpScriptTests.fs @@ -71,7 +71,7 @@ x let ce = new ControlledExecution(true) ce.Run(fun () -> use script = new FSharpScript() - let result, errors = + let result, _errors = script.Eval(""" open System let x = 1 + 2 @@ -178,7 +178,7 @@ System.Configuration.ConfigurationManager.AppSettings.Item "Environment" <- "LOC Assert.Empty(errors) match result with | Ok(_) -> () - | Error(ex) -> Assert.True(true, "expected no failures") + | Error _ -> Assert.True(true, "expected no failures") [] [] // No argument @@ -186,7 +186,7 @@ System.Configuration.ConfigurationManager.AppSettings.Item "Environment" <- "LOC [] // whitespace only argument member _.``Script with #i syntax errors fail``(code, error0) = use script = new FSharpScript() - let result, errors = script.Eval(code) + let _result, errors = script.Eval(code) Assert.NotEmpty(errors) Assert.Equal(errors.[0].ToString(), error0) @@ -196,7 +196,7 @@ System.Configuration.ConfigurationManager.AppSettings.Item "Environment" <- "LOC "input.fsx (1,1)-(1,3) interactive warning Invalid directive '#i '")>] member _.``Script with more #i syntax errors fail``(code, error0, error1) = use script = new FSharpScript() - let result, errors = script.Eval(code) + let _result, errors = script.Eval(code) Assert.NotEmpty(errors) Assert.Equal(errors.Length, 2) Assert.Equal(error0, errors.[0].ToString()) @@ -207,7 +207,7 @@ System.Configuration.ConfigurationManager.AppSettings.Item "Environment" <- "LOC "input.fsx (1,1)-(1,42) interactive error #i is not supported by the registered PackageManagers")>] member _.``Script with #i and no package manager specified``(code, error0) = use script = new FSharpScript() - let result, errors = script.Eval(code) + let _result, errors = script.Eval(code) Assert.NotEmpty(errors) Assert.Equal(errors.Length, 1) Assert.Equal(errors.[0].ToString(), error0) @@ -217,7 +217,7 @@ System.Configuration.ConfigurationManager.AppSettings.Item "Environment" <- "LOC "input.fsx (1,1)-(1,15) interactive error Invalid URI: The format of the URI could not be determined.")>] member _.``Script with #i and forgot to add quotes``(code, error) = use script = new FSharpScript() - let result, errors = script.Eval(code) + let _result, errors = script.Eval(code) Assert.NotEmpty(errors) Assert.Equal(1, errors.Length) Assert.Equal(error, errors.[0].ToString()) @@ -227,7 +227,7 @@ System.Configuration.ConfigurationManager.AppSettings.Item "Environment" <- "LOC let path = Path.GetTempPath() let code = sprintf "#i @\"nuget:%s\" " path use script = new FSharpScript() - let result, errors = script.Eval(code) + let _result, errors = script.Eval(code) Assert.Empty(errors) Assert.Equal(0, errors.Length) @@ -239,7 +239,7 @@ System.Configuration.ConfigurationManager.AppSettings.Item "Environment" <- "LOC let code = sprintf "#i @\"nuget:%s\"" path let error = sprintf "interactive error The source directory '%s' not found" path use script = new FSharpScript() - let result, errors = script.Eval(code) + let _result, errors = script.Eval(code) Assert.NotEmpty(errors) Assert.Equal(1, errors.Length) Assert.True(errors.[0].ToString().EndsWith(error)) @@ -308,7 +308,7 @@ printfn "{@"%A"}" result member _.``Eval script with invalid PackageName should fail immediately``() = use capture = new TestConsole.ExecutionCapture() use script = new FSharpScript(additionalArgs=[| |]) - let result, errors = script.Eval("""#r "nuget:FSharp.Really.Not.A.Package" """) + let _result, errors = script.Eval("""#r "nuget:FSharp.Really.Not.A.Package" """) let lines = capture.OutText.Split([| Environment.NewLine |], StringSplitOptions.None) let found = lines |> Seq.exists (fun line -> line.Contains("error NU1101:") && line.Contains("FSharp.Really.Not.A.Package")) @@ -320,7 +320,7 @@ printfn "{@"%A"}" result member _.``Eval script with invalid PackageName should fail immediately and resolve one time only``() = use capture = new TestConsole.ExecutionCapture() use script = new FSharpScript(additionalArgs=[| |]) - let result, errors = + let _result, errors = script.Eval(""" #r "nuget:FSharp.Really.Not.A.Package" #r "nuget:FSharp.Really.Not.Another.Package" @@ -526,7 +526,7 @@ let add (col:IServiceCollection) = Assert.Empty(errors) match result with | Ok(_) -> () - | Error(ex) -> Assert.True(false, "expected no failures") + | Error _ -> Assert.True(false, "expected no failures") | false -> Assert.NotEmpty(errors) Assert.Equal(1, errors.Length) diff --git a/tests/FSharp.Compiler.Service.Tests/AssemblyReaderShim.fs b/tests/FSharp.Compiler.Service.Tests/AssemblyReaderShim.fs index 9e19b32834f..63d8ee1c284 100644 --- a/tests/FSharp.Compiler.Service.Tests/AssemblyReaderShim.fs +++ b/tests/FSharp.Compiler.Service.Tests/AssemblyReaderShim.fs @@ -20,6 +20,6 @@ module M let x = 123 """ - let fileName, options = mkTestFileAndOptions source [| |] + let fileName, options = mkTestFileAndOptions [| |] checker.ParseAndCheckFileInProject(fileName, 0, SourceText.ofString source, options) |> Async.RunImmediate |> ignore gotRequest |> Assert.True diff --git a/tests/FSharp.Compiler.Service.Tests/Common.fs b/tests/FSharp.Compiler.Service.Tests/Common.fs index b9f780fd506..5ad61b29ef9 100644 --- a/tests/FSharp.Compiler.Service.Tests/Common.fs +++ b/tests/FSharp.Compiler.Service.Tests/Common.fs @@ -129,7 +129,7 @@ let mkProjectCommandLineArgsForScript (dllName, fileNames) = |] #endif -let mkTestFileAndOptions source additionalArgs = +let mkTestFileAndOptions additionalArgs = let fileName = Path.ChangeExtension(getTemporaryFileName (), ".fs") let project = getTemporaryFileName () let dllName = Path.ChangeExtension(project, ".dll") @@ -193,7 +193,7 @@ let parseSourceCode (name: string, code: string) = let filePath = Path.Combine(location, name) let dllPath = Path.Combine(location, name + ".dll") let args = mkProjectCommandLineArgs(dllPath, [filePath]) - let options, errors = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) + let options, _errors = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) let parseResults = checker.ParseFile(filePath, SourceText.ofString code, options) |> Async.RunImmediate parseResults.ParseTree @@ -203,7 +203,7 @@ let matchBraces (name: string, code: string) = let filePath = Path.Combine(location, name + ".fs") let dllPath = Path.Combine(location, name + ".dll") let args = mkProjectCommandLineArgs(dllPath, [filePath]) - let options, errors = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) + let options, _errors = checker.GetParsingOptionsFromCommandLineArgs(List.ofArray args) let braces = checker.MatchBraces(filePath, SourceText.ofString code, options) |> Async.RunImmediate braces @@ -265,7 +265,7 @@ let attribsOfSymbol (symbol: FSharpSymbol) = if v.IsStatic then yield "static" if v.IsLiteral then yield sprintf "%A" v.LiteralValue.Value if v.IsAnonRecordField then - let info, tys, i = v.AnonRecordFieldDetails + let info, _tys, i = v.AnonRecordFieldDetails yield "anon(" + string i + ", [" + info.Assembly.QualifiedName + "/" + String.concat "+" info.EnclosingCompiledTypeNames + "/" + info.CompiledName + "]" + String.concat "," info.SortedFieldNames + ")" diff --git a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj index 57ce88d8f02..16e9df837ee 100644 --- a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj +++ b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj @@ -5,6 +5,7 @@ net472;$(FSharpNetCoreProductTargetFramework) $(FSharpNetCoreProductTargetFramework) true + $(NoWarn);1182 true xunit diff --git a/tests/FSharp.Compiler.Service.Tests/FSharpExprPatternsTests.fs b/tests/FSharp.Compiler.Service.Tests/FSharpExprPatternsTests.fs index abc6bbc9de4..0c5c9fc3305 100644 --- a/tests/FSharp.Compiler.Service.Tests/FSharpExprPatternsTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/FSharpExprPatternsTests.fs @@ -25,7 +25,7 @@ module TASTCollecting = | Application (funcExpr, _typeArgs, argExprs) -> visitExpr handler funcExpr visitExprs handler argExprs - | Call (objExprOpt, memberOrFunc, _typeArgs1, _typeArgs2, argExprs) -> + | Call (objExprOpt, _memberOrFunc, _typeArgs1, _typeArgs2, argExprs) -> visitObjArg handler objExprOpt visitExprs handler argExprs | Coerce (_targetType, inpExpr) -> visitExpr handler inpExpr @@ -132,7 +132,7 @@ let testPatterns handler source = Map.tryFind fileName files |> async.Return let projectOptions = - let _, projectOptions = mkTestFileAndOptions "" Array.empty + let _, projectOptions = mkTestFileAndOptions Array.empty { projectOptions with SourceFiles = [| "A.fs" |] diff --git a/tests/FSharp.Compiler.Service.Tests/GeneratedCodeSymbolsTests.fs b/tests/FSharp.Compiler.Service.Tests/GeneratedCodeSymbolsTests.fs index 5fac752952c..6e9a64d0191 100644 --- a/tests/FSharp.Compiler.Service.Tests/GeneratedCodeSymbolsTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/GeneratedCodeSymbolsTests.fs @@ -22,10 +22,10 @@ type T () = for implFile in wholeProjectResults.AssemblyContents.ImplementationFiles do for decl in implFile.Declarations do match decl with - | FSharpImplementationFileDeclaration.Entity(e,ds) -> + | FSharpImplementationFileDeclaration.Entity(_e,ds) -> for d in ds do match d with - | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue (mfv, args, body) -> + | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue (mfv, _args, _body) -> yield mfv | _ -> () | _ -> () @@ -51,10 +51,10 @@ type T = A | B for implFile in wholeProjectResults.AssemblyContents.ImplementationFiles do for decl in implFile.Declarations do match decl with - | FSharpImplementationFileDeclaration.Entity(e,ds) -> + | FSharpImplementationFileDeclaration.Entity(_e,ds) -> for d in ds do match d with - | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue (mfv, args, body) -> + | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue (mfv, _args, _body) -> yield mfv | _ -> () | _ -> () @@ -84,10 +84,10 @@ type T = for implFile in wholeProjectResults.AssemblyContents.ImplementationFiles do for decl in implFile.Declarations do match decl with - | FSharpImplementationFileDeclaration.Entity(e,ds) -> + | FSharpImplementationFileDeclaration.Entity(_e,ds) -> for d in ds do match d with - | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue (mfv, args, body) -> + | FSharpImplementationFileDeclaration.MemberOrFunctionOrValue (mfv, _args, _body) -> yield mfv | _ -> () | _ -> () diff --git a/tests/FSharp.Compiler.Service.Tests/ModuleReaderCancellationTests.fs b/tests/FSharp.Compiler.Service.Tests/ModuleReaderCancellationTests.fs index 981c4dda14b..f307586cd5c 100644 --- a/tests/FSharp.Compiler.Service.Tests/ModuleReaderCancellationTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/ModuleReaderCancellationTests.fs @@ -102,13 +102,6 @@ type PreTypeDefData = CancelOnImport: bool } member this.TypeDef = - let name = - match this.Namespace with - | [] -> this.Name - | ns -> - let ns = ns |> String.concat "." - $"{ns}.{this.Name}" - let methodsDefs = if this.HasCtor then let mkCtor = runCancelFirstTime (fun _ -> [| ModuleReader.mkCtor () |]) @@ -191,7 +184,7 @@ let ``Type defs 01 - assembly import`` () = let getPreTypeDefs typeData = runCancelFirstTime (fun _ -> createPreTypeDefs typeData) let typeDefs = getPreTypeDefs [ { Name = "T"; Namespace = []; HasCtor = false; CancelOnImport = false } ] - let path, options = mkTestFileAndOptions source [||] + let path, options = mkTestFileAndOptions [||] let options = referenceReaderProject typeDefs false options // First request, should be cancelled inside getPreTypeDefs @@ -217,7 +210,7 @@ let ``Type defs 02 - assembly import`` () = let source = source1 let typeDefs = fun _ -> createPreTypeDefs [ { Name = "T"; Namespace = ["Ns"]; HasCtor = false; CancelOnImport = true } ] - let path, options = mkTestFileAndOptions source [||] + let path, options = mkTestFileAndOptions [||] let options = referenceReaderProject typeDefs false options parseAndCheck path source options |> ignore @@ -235,7 +228,7 @@ let ``Type defs 03 - type import`` () = let source = source2 let typeDefs = fun _ -> createPreTypeDefs [ { Name = "T"; Namespace = ["Ns1"; "Ns2"]; HasCtor = false; CancelOnImport = true } ] - let path, options = mkTestFileAndOptions source [||] + let path, options = mkTestFileAndOptions [||] let options = referenceReaderProject typeDefs false options // First request, should be cancelled inside GetTypeDef @@ -260,7 +253,7 @@ let ``Type defs 04 - ctor import`` () = let source = source1 let typeDefs = fun _ -> createPreTypeDefs [ { Name = "T"; Namespace = []; HasCtor = true; CancelOnImport = false } ] - let path, options = mkTestFileAndOptions source [||] + let path, options = mkTestFileAndOptions [||] let options = referenceReaderProject typeDefs false options // First request, should be cancelled inside ILMethodDefs @@ -282,7 +275,7 @@ let ``Module def 01 - assembly import`` () = let getPreTypeDefs typeData = fun _ -> createPreTypeDefs typeData let typeDefs = getPreTypeDefs [ { Name = "T"; Namespace = []; HasCtor = false; CancelOnImport = false } ] - let path, options = mkTestFileAndOptions source [||] + let path, options = mkTestFileAndOptions [||] let options = referenceReaderProject typeDefs true options // First request, should be cancelled inside getPreTypeDefs diff --git a/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs b/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs index 0e12a33fe2f..cef9b119c77 100644 --- a/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/ProjectAnalysisTests.fs @@ -3,6 +3,7 @@ open System.Threading.Tasks #nowarn "57" // Experimental stuff +#nowarn "1182" //Lot of unused results are stored in a binding, since those tests are checking how internal caching works when changes are being applied let runningOnMono = try System.Type.GetType("Mono.Runtime") <> null with e -> false @@ -5460,7 +5461,7 @@ type A(i:int) = [] let ``#4030, Incremental builder creation warnings 1`` () = let source = "module M" - let fileName, options = mkTestFileAndOptions source [||] + let fileName, options = mkTestFileAndOptions [||] let _, checkResults = parseAndCheckFile fileName source options checkResults.Diagnostics |> Array.map (fun e -> e.Severity = FSharpDiagnosticSeverity.Error) |> shouldEqual [||] @@ -5468,7 +5469,7 @@ let ``#4030, Incremental builder creation warnings 1`` () = [] let ``#4030, Incremental builder creation warnings 2`` () = let source = "module M" - let fileName, options = mkTestFileAndOptions source [| "--times" |] + let fileName, options = mkTestFileAndOptions [| "--times" |] let _, checkResults = parseAndCheckFile fileName source options checkResults.Diagnostics |> Array.map (fun e -> e.Severity = FSharpDiagnosticSeverity.Error) |> shouldEqual [| false |] @@ -5476,7 +5477,7 @@ let ``#4030, Incremental builder creation warnings 2`` () = [] let ``#4030, Incremental builder creation warnings 3`` () = let source = "module M" - let fileName, options = mkTestFileAndOptions source [| "--times"; "--nowarn:75" |] + let fileName, options = mkTestFileAndOptions [| "--times"; "--nowarn:75" |] let _, checkResults = parseAndCheckFile fileName source options checkResults.Diagnostics |> Array.map (fun e -> e.Severity = FSharpDiagnosticSeverity.Error) |> shouldEqual [||] @@ -5484,7 +5485,7 @@ let ``#4030, Incremental builder creation warnings 3`` () = [] let ``#4030, Incremental builder creation warnings 4`` () = let source = "module M" - let fileName, options = mkTestFileAndOptions source [| "--times"; "--warnaserror:75" |] + let fileName, options = mkTestFileAndOptions [| "--times"; "--warnaserror:75" |] let _, checkResults = parseAndCheckFile fileName source options checkResults.Diagnostics |> Array.map (fun e -> e.Severity = FSharpDiagnosticSeverity.Error) |> shouldEqual [| true |] @@ -5492,7 +5493,7 @@ let ``#4030, Incremental builder creation warnings 4`` () = [] let ``#4030, Incremental builder creation warnings 5`` () = let source = "module M" - let fileName, options = mkTestFileAndOptions source [| "--times"; "--warnaserror-:75"; "--warnaserror" |] + let fileName, options = mkTestFileAndOptions [| "--times"; "--warnaserror-:75"; "--warnaserror" |] let _, checkResults = parseAndCheckFile fileName source options checkResults.Diagnostics |> Array.map (fun e -> e.Severity = FSharpDiagnosticSeverity.Error) |> shouldEqual [| false |] diff --git a/tests/FSharp.Compiler.Service.Tests/Symbols.fs b/tests/FSharp.Compiler.Service.Tests/Symbols.fs index 25617ca1235..181cbfe40af 100644 --- a/tests/FSharp.Compiler.Service.Tests/Symbols.fs +++ b/tests/FSharp.Compiler.Service.Tests/Symbols.fs @@ -30,7 +30,7 @@ match "foo" with """ let getCaseUsages source line = - let fileName, options = mkTestFileAndOptions source [| |] + let fileName, options = mkTestFileAndOptions [| |] let _, checkResults = parseAndCheckFile fileName source options checkResults.GetAllUsesOfAllSymbolsInFile() @@ -201,7 +201,7 @@ module Mod1 = module Mod2 = let func2 () = () """ - let fileName, options = mkTestFileAndOptions source [| |] + let fileName, options = mkTestFileAndOptions [| |] let _, checkResults = parseAndCheckFile fileName source options let mod1 = checkResults.PartialAssemblySignature.FindEntityByPath ["Ns1"; "Mod1"] |> Option.get @@ -221,7 +221,7 @@ let val1 = 1 module Mod2 = let func2 () = () """ - let fileName, options = mkTestFileAndOptions source [| |] + let fileName, options = mkTestFileAndOptions [| |] let _, checkResults = parseAndCheckFile fileName source options let mod1 = checkResults.PartialAssemblySignature.FindEntityByPath ["Mod1"] |> Option.get @@ -247,7 +247,7 @@ type FooAttribute() = [] let x = 123 """ - let fileName, options = mkTestFileAndOptions source [| "--noconditionalerasure" |] + let fileName, options = mkTestFileAndOptions [| "--noconditionalerasure" |] let _, checkResults = parseAndCheckFile fileName source options checkResults.GetAllUsesOfAllSymbolsInFile() @@ -370,7 +370,7 @@ type I<'T> = let _, checkResults = getParseAndCheckResults """ [1] |> ignore """ - let symbolUses = checkResults.GetAllUsesOfAllSymbolsInFile() + let _symbolUses = checkResults.GetAllUsesOfAllSymbolsInFile() () [] diff --git a/tests/FSharp.Compiler.Service.Tests/TooltipTests.fs b/tests/FSharp.Compiler.Service.Tests/TooltipTests.fs index 0b30a5a61e8..cbc82c6922e 100644 --- a/tests/FSharp.Compiler.Service.Tests/TooltipTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/TooltipTests.fs @@ -26,7 +26,7 @@ let testXmlDocFallbackToSigFileWhileInImplFile sigSource implSource line colAtEn let documentSource fileName = Map.tryFind fileName files |> async.Return let projectOptions = - let _, projectOptions = mkTestFileAndOptions "" Array.empty + let _, projectOptions = mkTestFileAndOptions Array.empty { projectOptions with SourceFiles = [| "A.fsi"; "A.fs" |] } @@ -274,7 +274,7 @@ let testToolTipSquashing source line colAtEndOfNames lineText names tokenTag = let documentSource fileName = Map.tryFind fileName files |> async.Return let projectOptions = - let _, projectOptions = mkTestFileAndOptions "" Array.empty + let _, projectOptions = mkTestFileAndOptions Array.empty { projectOptions with SourceFiles = [| "A.fs" |] } @@ -394,7 +394,6 @@ c.Abc let getCheckResults source options = let fileName, options = mkTestFileAndOptions - source options let _, checkResults = parseAndCheckFile fileName source options checkResults @@ -455,7 +454,7 @@ let exists() = System.IO.Path.Exists(null:string) let checkResults = getCheckResults source [|"--checknulls+";"--langversion:preview"|] checkResults.GetToolTip(2, 36, "let exists() = System.IO.Path.Exists(null:string)", [ "Exists" ], FSharpTokenTag.Identifier) |> assertAndExtractTooltip - |> fun (text,xml,remarks) -> + |> fun (text,xml,_remarks) -> text |> Assert.shouldBeEquivalentTo "System.IO.Path.Exists([] path: string | null) : bool" match xml with | FSharpXmlDoc.FromXmlFile (_dll,sigPath) -> sigPath |> Assert.shouldBeEquivalentTo "M:System.IO.Path.Exists(System.String)" diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj index 3e6bbbd282d..f5737066162 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj @@ -12,6 +12,7 @@ $(FSCoreUnitTestsPackageVersion) true preview + $(NoWarn);1182 true xunit diff --git a/tests/service/data/TestTP/TestTP.fs b/tests/service/data/TestTP/TestTP.fs index 4e7bf9dd092..062e1b8510d 100644 --- a/tests/service/data/TestTP/TestTP.fs +++ b/tests/service/data/TestTP/TestTP.fs @@ -5,6 +5,8 @@ open Microsoft.FSharp.Core.CompilerServices open System.Reflection open FSharp.Quotations +#nowarn "1182" // Lot of unused "args","x","y","c" around this test file + module Helper = let doNothing() = () let doNothingOneArg(x:int) = () diff --git a/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj b/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj index 68cc5c4de2e..21305e52a5d 100644 --- a/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj +++ b/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj @@ -4,7 +4,7 @@ Library - $(NoWarn);47;75 + $(NoWarn);47;75;1182 true $(OtherFlags) --subsystemversion:6.00 false diff --git a/vsintegration/tests/MockTypeProviders/DummyProviderForLanguageServiceTesting/DummyProviderForLanguageServiceTesting.fsproj b/vsintegration/tests/MockTypeProviders/DummyProviderForLanguageServiceTesting/DummyProviderForLanguageServiceTesting.fsproj index edf4b8a41e5..ae81965ef4c 100644 --- a/vsintegration/tests/MockTypeProviders/DummyProviderForLanguageServiceTesting/DummyProviderForLanguageServiceTesting.fsproj +++ b/vsintegration/tests/MockTypeProviders/DummyProviderForLanguageServiceTesting/DummyProviderForLanguageServiceTesting.fsproj @@ -5,7 +5,7 @@ net472 true - $(OtherFlags) --nowarn:3390 --nowarn:3218 + $(OtherFlags) --nowarn:3390 --nowarn:3218 --nowarn:1182 diff --git a/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj b/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj index 353e08336a6..4e556083776 100644 --- a/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj +++ b/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj @@ -4,7 +4,7 @@ Library - $(NoWarn);44;45;47;52;58;75 + $(NoWarn);44;45;47;52;58;75;1182 true true false diff --git a/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj b/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj index 2a764378864..4020cfd750d 100644 --- a/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj +++ b/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj @@ -6,7 +6,7 @@ net472 x86 Library - $(NoWarn);44;58;75;3005 + $(NoWarn);44;58;75;3005;1182 true true true From c01bc471ec95865b71b4a7f535bd6e2884e094f7 Mon Sep 17 00:00:00 2001 From: Edgar Gonzalez Date: Mon, 31 Mar 2025 09:51:31 +0100 Subject: [PATCH 09/20] Use a more accurate range for CE Combine methods (#18394) --- .../.FSharp.Compiler.Service/9.0.300.md | 1 + .../CheckComputationExpressions.fs | 11 +- .../Language/ComputationExpressionTests.fs | 532 ++++++++++++++++++ .../E_MissingCombine.fs | 2 +- 4 files changed, 543 insertions(+), 3 deletions(-) diff --git a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md index c4e4a6a1403..f40ab0428ed 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md +++ b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md @@ -29,6 +29,7 @@ * Symbols: Add FSharpAssembly.IsFSharp ([PR #18290](https://github.com/dotnet/fsharp/pull/18290)) * Type parameter constraint `null` in generic code will now automatically imply `not struct` ([Issue #18320](https://github.com/dotnet/fsharp/issues/18320), [PR #18323](https://github.com/dotnet/fsharp/pull/18323)) * Add a switch to determine whether to generate a default implementation body for overridden method when completing. [PR #18341](https://github.com/dotnet/fsharp/pull/18341) +* Use a more accurate range for CE Combine methods. [PR #18394](https://github.com/dotnet/fsharp/pull/18394) ### Changed diff --git a/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs b/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs index 52cb3c0d61a..fc804ab5e34 100644 --- a/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs +++ b/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs @@ -1612,6 +1612,12 @@ let rec TryTranslateComputationExpression // "cexpr; cexpr" is treated as builder.Combine(cexpr1, cexpr1) let m1 = rangeForCombine innerComp1 + let combineDelayRange = + match innerComp2 with + | SynExpr.YieldOrReturn(trivia = yieldOrReturn) -> yieldOrReturn.YieldOrReturnKeyword + | SynExpr.YieldOrReturnFrom(trivia = yieldOrReturnFrom) -> yieldOrReturnFrom.YieldOrReturnFromKeyword + | expr -> expr.Range + if isNil ( TryFindIntrinsicOrExtensionMethInfo @@ -1624,7 +1630,8 @@ let rec TryTranslateComputationExpression ceenv.builderTy ) then - error (Error(FSComp.SR.tcRequireBuilderMethod ("Combine"), m)) + + error (Error(FSComp.SR.tcRequireBuilderMethod "Combine", combineDelayRange)) if isNil ( @@ -1638,7 +1645,7 @@ let rec TryTranslateComputationExpression ceenv.builderTy ) then - error (Error(FSComp.SR.tcRequireBuilderMethod ("Delay"), m)) + error (Error(FSComp.SR.tcRequireBuilderMethod "Delay", combineDelayRange)) let combineCall = mkSynCall diff --git a/tests/FSharp.Compiler.ComponentTests/Language/ComputationExpressionTests.fs b/tests/FSharp.Compiler.ComponentTests/Language/ComputationExpressionTests.fs index 3555e97fd2d..55d49dbebc7 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/ComputationExpressionTests.fs +++ b/tests/FSharp.Compiler.ComponentTests/Language/ComputationExpressionTests.fs @@ -605,6 +605,538 @@ let run r2 r3 = (Error 708, Line 24, Col 19, Line 24, Col 26, "This control construct may only be used if the computation expression builder defines a 'ReturnFrom' method") ] + [] + let ``This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + +let result = ResultBuilder() + +let run r2 r3 = + result { + let! r2 = r2 + let! r3 = r3 + if r2 = Ok 1 then + do! r2 + return r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 27, Col 9, Line 27, Col 15, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence2 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + + member _.For(sequence: #seq<'T>, binder: 'T -> Result<_, _>) = + sequence + |> Seq.map binder + |> Seq.fold (fun acc x -> Result.bind (fun () -> x) acc) (Ok ()) + +let result = ResultBuilder() + +let run (r2: Result) (r3: Result) = + result { + let! r2 = r2 + let! r3 = r3 + for i in [ 1] do + do! r2 + return r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 32, Col 9, Line 32, Col 15, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 5 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + + member _.For(sequence: #seq<'T>, binder: 'T -> Result<_, _>) = + sequence + |> Seq.map binder + |> Seq.fold (fun acc x -> Result.bind (fun () -> x) acc) (Ok ()) + +let result = ResultBuilder() + +let run (r2: Result) (r3: Result) = + result { + let! r2 = r2 + let! r3 = r3 + for i in [ 1] do + do! r2 + return! r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 32, Col 9, Line 32, Col 16, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 7 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + + member _.For(sequence: #seq<'T>, binder: 'T -> Result<_, _>) = + sequence + |> Seq.map binder + |> Seq.fold (fun acc x -> Result.bind (fun () -> x) acc) (Ok ()) + +let result = ResultBuilder() + +let run (r2: Result) (r3: Result) = + result { + let! r2 = r2 + let! r3 = r3 + match r2 with + | 0 -> do! r2 + | _ -> do! r2 + return! r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 33, Col 9, Line 33, Col 16, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 8 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + + member _.For(sequence: #seq<'T>, binder: 'T -> Result<_, _>) = + sequence + |> Seq.map binder + |> Seq.fold (fun acc x -> Result.bind (fun () -> x) acc) (Ok ()) + +let result = ResultBuilder() + +let run (r2: Result) (r3: Result) = + result { + let! r2 = r2 + let! r3 = r3 + match! r2 with + | 0 -> do! r2 + | _ -> do! r2 + return! r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 33, Col 9, Line 33, Col 16, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 9 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + + member _.For(sequence: #seq<'T>, binder: 'T -> Result<_, _>) = + sequence + |> Seq.map binder + |> Seq.fold (fun acc x -> Result.bind (fun () -> x) acc) (Ok ()) + +let result = ResultBuilder() + +let run (r2: Result) (r3: Result) = + result { + let! r2 = r2 + let! r3 = r3 + match! r2 with + | 0 -> do! r2 + | _ -> do! r2 + return r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 33, Col 9, Line 33, Col 15, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence3 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + + member _.Yield(x: 'T) = Ok x + + member _.For(sequence: #seq<'T>, binder: 'T -> Result<_, _>) = + sequence + |> Seq.map binder + |> Seq.fold (fun acc x -> Result.bind (fun () -> x) acc) (Ok ()) + +let result = ResultBuilder() + +let run (r2: Result) (r3: Result) = + result { + let! r2 = r2 + let! r3 = r3 + for i in [ 1] do + yield r2 + return r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 34, Col 9, Line 34, Col 15, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 4 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + + member _.Yield(x: 'T) = Ok x + + member _.For(sequence: #seq<'T>, binder: 'T -> Result<_, _>) = + sequence + |> Seq.map binder + |> Seq.fold (fun acc x -> Result.bind (fun () -> x) acc) (Ok ()) + +let result = ResultBuilder() + +let run (r2: Result) (r3: Result) = + result { + let! r2 = r2 + let! r3 = r3 + for i in [ 1] do + yield r2 + yield r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 34, Col 9, Line 34, Col 14, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + [] + let ``Sequence 6 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Result = + let zip x1 x2 = + match x1,x2 with + | Ok x1res, Ok x2res -> Ok (x1res, x2res) + | Error e, _ -> Error e + | _, Error e -> Error e + +type ResultBuilder() = + member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 + member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x + member _.Bind(x: Result<'T,'U>, f) = + match x with + | Ok x -> f x + | Error e -> Error e + + member _.Zero() = Ok () + + member _.Yield(x: 'T) = Ok x + + member _.YieldFrom(x: Result<'T,'U>) = x + + member _.For(sequence: #seq<'T>, binder: 'T -> Result<_, _>) = + sequence + |> Seq.map binder + |> Seq.fold (fun acc x -> Result.bind (fun () -> x) acc) (Ok ()) + +let result = ResultBuilder() + +let run (r2: Result) (r3: Result) = + result { + let! r2 = r2 + let! r3 = r3 + for i in [ 1] do + yield! r2 + yield! r3 + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 36, Col 9, Line 36, Col 15, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 10 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Test = + type R = S of string + + type T() = + member x.Bind(p: R, rest: (string -> R)) = + match p with + | S(s) -> rest s + member x.Zero() = S("l") + member x.For(s : seq, rest: (int -> unit)) = S("") + + let t = new T() + + let t' = t { + let a = 10 + for x in [1] do () + 0 |> ignore + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 17, Col 7, Line 17, Col 18, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 11 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Test = + type R = S of string + + type T() = + member x.Bind(p: R, rest: string -> R) = + match p with + | S(s) -> rest s + member x.Zero() = S("l") + member x.For(s: seq, rest: (int -> R)) = + let folder state item = + match state with + | S(str) -> + match rest item with + | S(itemStr) -> S(str + itemStr) + Seq.fold folder (S("")) s + + let t = new T() + + let t' = t { + let a = 10 + for x in [1] do + () + for x in [1] do + () + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 24, Col 7, Line 25, Col 13, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 12 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Test = + type R = S of string + + type T() = + member x.Bind(p: R, rest: string -> R) = + match p with + | S(s) -> rest s + member x.Zero() = S("l") + member x.Yield(value: 'a) = S(string value) + member x.For(s: seq, rest: (int -> R)) = + let folder state item = + match state with + | S(str) -> + match rest item with + | S(itemStr) -> S(str + itemStr) + Seq.fold folder (S("")) s + + let t = new T() + + let t' = t { + let a = 10 + for x in [1] -> + () + for x in [1] -> + () + } + + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 25, Col 7, Line 26, Col 13, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] + let ``Sequence 13 This control construct may only be used if the computation expression builder defines a 'Combine' method`` () = + Fsx """ +module Test = + type R = S of string + + type T() = + member x.Bind(p: R, rest: string -> R) = + match p with + | S(s) -> rest s + member x.Zero() = S("l") + member x.For(s: seq, rest: (int -> R)) = + let folder state item = + match state with + | S(str) -> + match rest item with + | S(itemStr) -> S(str + itemStr) + Seq.fold folder (S("")) s + + let t = new T() + + let t' = t { + let a = 10 + for x in [1] do () + if true then + () + else + () + } + """ + |> ignoreWarnings + |> typecheck + |> shouldFail + |> withDiagnostics [ + (Error 708, Line 23, Col 7, Line 26, Col 13, "This control construct may only be used if the computation expression builder defines a 'Combine' method") + ] + + [] let ``Type constraint mismatch when using return!`` () = Fsx """ diff --git a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/ComputationExpressions/E_MissingCombine.fs b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/ComputationExpressions/E_MissingCombine.fs index 5a8e82d4074..b06d74f93e9 100644 --- a/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/ComputationExpressions/E_MissingCombine.fs +++ b/tests/fsharpqa/Source/Conformance/Expressions/DataExpressions/ComputationExpressions/E_MissingCombine.fs @@ -1,6 +1,6 @@ // #Regression #Conformance #DataExpressions #ComputationExpressions // Regression test for FSHARP1.0:6149 -//This control construct may only be used if the computation expression builder defines a 'Combine' method$ +//This control construct may only be used if the computation expression builder defines a 'Combine' method$ type R = S of string From 1595946abbb814148b4a9d52e9546df3e80c966e Mon Sep 17 00:00:00 2001 From: Tomas Grosup Date: Mon, 31 Mar 2025 15:21:09 +0200 Subject: [PATCH 10/20] Make unused bindings an error (#18421) --- FSharpBuild.Directory.Build.props | 2 +- buildtools/fslex/fslex.fsproj | 3 ++- buildtools/fsyacc/fsyacc.fsproj | 3 ++- tests/FSharp.Compiler.Service.Tests/EditorTests.fs | 2 ++ .../FSharp.Compiler.Service.Tests.fsproj | 1 + .../MultiProjectAnalysisTests.fs | 2 ++ tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj | 2 +- vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj | 2 +- vsintegration/src/FSharp.VS.FSI/sessions.fs | 6 +++--- .../DummyProviderForLanguageServiceTesting.fsproj | 2 +- vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj | 1 + vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj | 1 + 12 files changed, 18 insertions(+), 9 deletions(-) diff --git a/FSharpBuild.Directory.Build.props b/FSharpBuild.Directory.Build.props index 1b7ecd6fa27..33772456e28 100644 --- a/FSharpBuild.Directory.Build.props +++ b/FSharpBuild.Directory.Build.props @@ -28,7 +28,7 @@ $(ArtifactsDir)\Bootstrap 4.4.0 $(WarnOn);1182 - 0025;$(WarningsAsErrors) + 1182;0025;$(WarningsAsErrors) $(OtherFlags) --nowarn:3384 $(OtherFlags) --times --nowarn:75 $(OtherFlags) $(AdditionalFscCmdFlags) diff --git a/buildtools/fslex/fslex.fsproj b/buildtools/fslex/fslex.fsproj index b450de1668d..684fecb11da 100644 --- a/buildtools/fslex/fslex.fsproj +++ b/buildtools/fslex/fslex.fsproj @@ -5,7 +5,8 @@ $(FSharpNetCoreProductTargetFramework) true LatestMajor - $(NoWarn);64;1182;1204 + $(NoWarn);64;1204;1182 + $(OtherFlags) --warnaserror-:1182 diff --git a/buildtools/fsyacc/fsyacc.fsproj b/buildtools/fsyacc/fsyacc.fsproj index 5f97b762e03..38280006de3 100644 --- a/buildtools/fsyacc/fsyacc.fsproj +++ b/buildtools/fsyacc/fsyacc.fsproj @@ -5,7 +5,8 @@ $(FSharpNetCoreProductTargetFramework) true LatestMajor - $(NoWarn);64;1182;1204 + $(NoWarn);64;1204;1182 + $(OtherFlags) --warnaserror-:1182 diff --git a/tests/FSharp.Compiler.Service.Tests/EditorTests.fs b/tests/FSharp.Compiler.Service.Tests/EditorTests.fs index bc6ad3d3e88..6ac0789cd9c 100644 --- a/tests/FSharp.Compiler.Service.Tests/EditorTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/EditorTests.fs @@ -9,6 +9,8 @@ open FSharp.Compiler.Symbols open FSharp.Compiler.Text open FSharp.Compiler.Tokenization +#nowarn "1182" // Unused bindings when ignored parsed results etc. + let stringMethods = [ "Chars"; "Clone"; "CompareTo"; "Contains"; "CopyTo"; "EndsWith"; diff --git a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj index 16e9df837ee..1cf8d9c720b 100644 --- a/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj +++ b/tests/FSharp.Compiler.Service.Tests/FSharp.Compiler.Service.Tests.fsproj @@ -6,6 +6,7 @@ $(FSharpNetCoreProductTargetFramework) true $(NoWarn);1182 + $(OtherFlags) --warnaserror-:1182 true xunit diff --git a/tests/FSharp.Compiler.Service.Tests/MultiProjectAnalysisTests.fs b/tests/FSharp.Compiler.Service.Tests/MultiProjectAnalysisTests.fs index ee6b23794b1..b553d676cb3 100644 --- a/tests/FSharp.Compiler.Service.Tests/MultiProjectAnalysisTests.fs +++ b/tests/FSharp.Compiler.Service.Tests/MultiProjectAnalysisTests.fs @@ -13,6 +13,8 @@ open FSharp.Compiler.Text open FSharp.Compiler.Service.Tests.Common open TestFramework +#nowarn "1182" // Unused bindings when ignored parsed results etc. + let toIList (x: _ array) = x :> IList<_> let numProjectsForStressTest = 100 let internal checker = FSharpChecker.Create(projectCacheSize=numProjectsForStressTest + 10, useTransparentCompiler = CompilerAssertHelpers.UseTransparentCompiler) diff --git a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj index f5737066162..d4dbfdd4348 100644 --- a/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj +++ b/tests/FSharp.Core.UnitTests/FSharp.Core.UnitTests.fsproj @@ -13,7 +13,7 @@ true preview $(NoWarn);1182 - + $(OtherFlags) --warnaserror-:1182 true xunit true diff --git a/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj b/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj index 21305e52a5d..cc40ac675c7 100644 --- a/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj +++ b/vsintegration/src/FSharp.VS.FSI/FSharp.VS.FSI.fsproj @@ -6,7 +6,7 @@ Library $(NoWarn);47;75;1182 true - $(OtherFlags) --subsystemversion:6.00 + $(OtherFlags) --subsystemversion:6.00 --warnaserror-:1182 false diff --git a/vsintegration/src/FSharp.VS.FSI/sessions.fs b/vsintegration/src/FSharp.VS.FSI/sessions.fs index d46e963015e..ca2c980f553 100644 --- a/vsintegration/src/FSharp.VS.FSI/sessions.fs +++ b/vsintegration/src/FSharp.VS.FSI/sessions.fs @@ -41,7 +41,7 @@ type internal EventWrapper() = /// Run function application return Some (f x) or None if execution exceeds timeout (in ms). /// Exceptions raised by f x are caught and reported in DEBUG mode. -let timeoutApp descr timeoutMS (f : 'a -> 'b) (arg:'a) = +let timeoutApp _descr timeoutMS (f : 'a -> 'b) (arg:'a) = use ev = new EventWrapper() let mutable r = None ThreadPool.QueueUserWorkItem(fun _ -> @@ -57,7 +57,7 @@ let timeoutApp descr timeoutMS (f : 'a -> 'b) (arg:'a) = "fsi.exe starts the remoting server at the end of it's initialisation sequence.\n" + "The initialisation sequence takes an observable time (e.g. 2 seconds).\n" + "Remoting exceptions are to be expected on interrupt/intellisense calls made before that point.\n" + - "Context: " + descr + "\n" + + "Context: " + _descr + "\n" + "Exception: " + e.ToString()) |> ignore #endif None @@ -285,7 +285,7 @@ let fsiStartInfo channelName sourceFile = procInfo -let nonNull = function null -> false | (s:string) -> true +let nonNull = function null -> false | (_:string) -> true /// Represents an active F# Interactive process to which Visual Studio is connected via stdin/stdout/stderr and a remoting channel type FsiSession(sourceFile) = diff --git a/vsintegration/tests/MockTypeProviders/DummyProviderForLanguageServiceTesting/DummyProviderForLanguageServiceTesting.fsproj b/vsintegration/tests/MockTypeProviders/DummyProviderForLanguageServiceTesting/DummyProviderForLanguageServiceTesting.fsproj index ae81965ef4c..faca7cb840b 100644 --- a/vsintegration/tests/MockTypeProviders/DummyProviderForLanguageServiceTesting/DummyProviderForLanguageServiceTesting.fsproj +++ b/vsintegration/tests/MockTypeProviders/DummyProviderForLanguageServiceTesting/DummyProviderForLanguageServiceTesting.fsproj @@ -5,7 +5,7 @@ net472 true - $(OtherFlags) --nowarn:3390 --nowarn:3218 --nowarn:1182 + $(OtherFlags) --nowarn:3390 --nowarn:3218 --nowarn:1182 --warnaserror-:1182 diff --git a/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj b/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj index 4e556083776..7f24444a6e5 100644 --- a/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj +++ b/vsintegration/tests/Salsa/VisualFSharp.Salsa.fsproj @@ -5,6 +5,7 @@ Library $(NoWarn);44;45;47;52;58;75;1182 + $(OtherFlags) --warnaserror-:1182 true true false diff --git a/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj b/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj index 4020cfd750d..77c7d12e017 100644 --- a/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj +++ b/vsintegration/tests/UnitTests/VisualFSharp.UnitTests.fsproj @@ -7,6 +7,7 @@ x86 Library $(NoWarn);44;58;75;3005;1182 + $(OtherFlags) --warnaserror-:1182 true true true From dc01094ebe2c04a7f466b5ac74c63dd6d9df2eb0 Mon Sep 17 00:00:00 2001 From: Brian Rourke Boll Date: Mon, 31 Mar 2025 11:37:51 -0400 Subject: [PATCH 11/20] =?UTF-8?q?Reenable=20=CE=B2-reduction=20of=20immedi?= =?UTF-8?q?ately-invoked=20F#-defined=20generic=20delegates=20(#18401)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.FSharp.Compiler.Service/9.0.300.md | 1 + src/Compiler/Optimize/Optimizer.fs | 14 +- src/Compiler/TypedTree/TypedTreeOps.fs | 12 +- src/Compiler/TypedTree/TypedTreeOps.fsi | 6 +- .../ComputationExpressions.fs | 13 + .../CustomCollectionBuilderComputationExpr.fs | 14 + ...nBuilderComputationExpr.fs.Optimize.il.bsl | 228 +++++++ ...ilderComputationExpr.fs.OptimizeOff.il.bsl | 593 ++++++++++++++++++ ...CollectionBuilderComputationExprLibrary.fs | 59 ++ .../Inlining/FSharpDelegateBetaReduction.fs | 25 + ...n.fs.RealInternalSignature.Optimize.il.bsl | 247 ++++++++ ...s.RealInternalSignature.OptimizeOff.il.bsl | 277 ++++++++ .../EmittedIL/Inlining/Inlining.fs | 11 + tests/FSharp.Test.Utilities/ILChecker.fs | 3 +- 14 files changed, 1487 insertions(+), 16 deletions(-) create mode 100644 tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs create mode 100644 tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs.Optimize.il.bsl create mode 100644 tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs.OptimizeOff.il.bsl create mode 100644 tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExprLibrary.fs create mode 100644 tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs create mode 100644 tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs.RealInternalSignature.Optimize.il.bsl create mode 100644 tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs.RealInternalSignature.OptimizeOff.il.bsl diff --git a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md index f40ab0428ed..86672567838 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md +++ b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md @@ -20,6 +20,7 @@ * Fix duplicate parse error reporting for GetBackgroundCheckResultsForFileInProject ([Issue #18379](https://github.com/dotnet/fsharp/issues/18379) [PR #18380](https://github.com/dotnet/fsharp/pull/18380)) * Fix MethodDefNotFound when compiling code invoking delegate with option parameter ([Issue #5171](https://github.com/dotnet/fsharp/issues/5171), [PR #18385](https://github.com/dotnet/fsharp/pull/18385)) * Fix #r nuget ..." downloads unneeded packages ([Issue #18231](https://github.com/dotnet/fsharp/issues/18231), [PR #18393](https://github.com/dotnet/fsharp/pull/18393)) +* Reenable β-reduction and subsequent reoptimization of immediately-invoked F#-defined generic delegates. ([PR #18401](https://github.com/dotnet/fsharp/pull/18401)) ### Added * Added missing type constraints in FCS. ([PR #18241](https://github.com/dotnet/fsharp/pull/18241)) diff --git a/src/Compiler/Optimize/Optimizer.fs b/src/Compiler/Optimize/Optimizer.fs index 69fb9b45974..2840331f54b 100644 --- a/src/Compiler/Optimize/Optimizer.fs +++ b/src/Compiler/Optimize/Optimizer.fs @@ -1734,9 +1734,9 @@ let TryEliminateBinding cenv _env bind e2 _m = // Immediate consumption of delegate via an application in a sequential, e.g. 'let part1 = e in part1.Invoke(args); rest' // See https://github.com/fsharp/fslang-design/blob/master/tooling/FST-1034-lambda-optimizations.md - | Expr.Sequential(DebugPoints(DelegateInvokeExpr g (delInvokeRef, delInvokeTy, DebugPoints (Expr.Val (VRefLocal vspec2, _, _), recreate2), delInvokeArg, _), recreate1), rest, NormalSeq, m) + | Expr.Sequential(DebugPoints(DelegateInvokeExpr g (delInvokeRef, delInvokeTy, tyargs, DebugPoints (Expr.Val (VRefLocal vspec2, _, _), recreate2), delInvokeArg, _), recreate1), rest, NormalSeq, m) when IsUniqueUse vspec2 [rest;delInvokeArg] -> - let invoke = MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, recreate2 e1, delInvokeTy, delInvokeArg, m) + let invoke = MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, recreate2 e1, delInvokeTy, tyargs, delInvokeArg, m) Some (Expr.Sequential(recreate1 invoke, rest, NormalSeq, m) |> recreate0) // Immediate consumption of value by a pattern match 'let x = e in match x with ...' @@ -2397,8 +2397,8 @@ let rec OptimizeExpr cenv (env: IncrementalOptimizationEnv) expr = | Expr.App (f, fty, tyargs, argsl, m) -> match expr with - | DelegateInvokeExpr g (delInvokeRef, delInvokeTy, delExpr, delInvokeArg, m) -> - OptimizeFSharpDelegateInvoke cenv env (delInvokeRef, delExpr, delInvokeTy, delInvokeArg, m) + | DelegateInvokeExpr g (delInvokeRef, delInvokeTy, tyargs, delExpr, delInvokeArg, m) -> + OptimizeFSharpDelegateInvoke cenv env (delInvokeRef, delExpr, delInvokeTy, tyargs, delInvokeArg, m) | _ -> let attempt = if IsDebugPipeRightExpr cenv expr then @@ -3799,18 +3799,18 @@ and OptimizeDebugPipeRights cenv env expr = pipesExprR expr, { pipesInfo with HasEffect=true} -and OptimizeFSharpDelegateInvoke cenv env (delInvokeRef, delExpr, delInvokeTy, delInvokeArg, m) = +and OptimizeFSharpDelegateInvoke cenv env (delInvokeRef, delExpr, delInvokeTy, tyargs, delInvokeArg, m) = let g = cenv.g let optf0, finfo = OptimizeExpr cenv env delExpr - match StripPreComputationsFromComputedFunction g optf0 [delInvokeArg] (fun f delInvokeArgsR -> MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, f, delInvokeTy, List.head delInvokeArgsR, m)) with + match StripPreComputationsFromComputedFunction g optf0 [delInvokeArg] (fun f delInvokeArgsR -> MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, f, delInvokeTy, tyargs, List.head delInvokeArgsR, m)) with | Choice1Of2 remade -> OptimizeExpr cenv env remade | Choice2Of2 (newf0, remake) -> let newDelInvokeArgs, arginfos = OptimizeExprsThenConsiderSplits cenv env [delInvokeArg] let newDelInvokeArg = List.head newDelInvokeArgs - let reducedExpr = MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, newf0, delInvokeTy, newDelInvokeArg, m) + let reducedExpr = MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, newf0, delInvokeTy, tyargs, newDelInvokeArg, m) let newExpr = reducedExpr |> remake match newf0, reducedExpr with | Expr.Obj _, Expr.Let _ -> diff --git a/src/Compiler/TypedTree/TypedTreeOps.fs b/src/Compiler/TypedTree/TypedTreeOps.fs index 21c9783713e..4b41db72349 100644 --- a/src/Compiler/TypedTree/TypedTreeOps.fs +++ b/src/Compiler/TypedTree/TypedTreeOps.fs @@ -8465,9 +8465,9 @@ let (|NewDelegateExpr|_|) g expr = [] let (|DelegateInvokeExpr|_|) g expr = match expr with - | Expr.App ((Expr.Val (invokeRef, _, _)) as delInvokeRef, delInvokeTy, [], [delExpr;delInvokeArg], m) + | Expr.App ((Expr.Val (invokeRef, _, _)) as delInvokeRef, delInvokeTy, tyargs, [delExpr;delInvokeArg], m) when invokeRef.LogicalName = "Invoke" && isFSharpDelegateTy g (tyOfExpr g delExpr) -> - ValueSome(delInvokeRef, delInvokeTy, delExpr, delInvokeArg, m) + ValueSome(delInvokeRef, delInvokeTy, tyargs, delExpr, delInvokeArg, m) | _ -> ValueNone [] @@ -8494,17 +8494,17 @@ let (|OpPipeRight3|_|) g expr = ValueSome(resType, arg1, arg2, arg3, fExpr, m) | _ -> ValueNone -let rec MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, delExpr, delInvokeTy, delInvokeArg, m) = +let rec MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, delExpr, delInvokeTy, tyargs, delInvokeArg, m) = match delExpr with | Expr.Let (bind, body, mLet, _) -> - mkLetBind mLet bind (MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, body, delInvokeTy, delInvokeArg, m)) - | NewDelegateExpr g (_, argvs, body, m, _) when argvs.Length > 0 -> + mkLetBind mLet bind (MakeFSharpDelegateInvokeAndTryBetaReduce g (delInvokeRef, body, delInvokeTy, tyargs, delInvokeArg, m)) + | NewDelegateExpr g (_, argvs & _ :: _, body, m, _) -> let pairs, body = MultiLambdaToTupledLambdaIfNeeded g (argvs, delInvokeArg) body let argvs2, args2 = List.unzip pairs mkLetsBind m (mkCompGenBinds argvs2 args2) body | _ -> // Remake the delegate invoke - Expr.App (delInvokeRef, delInvokeTy, [], [delExpr; delInvokeArg], m) + Expr.App (delInvokeRef, delInvokeTy, tyargs, [delExpr; delInvokeArg], m) //--------------------------------------------------------------------------- // Adjust for expected usage diff --git a/src/Compiler/TypedTree/TypedTreeOps.fsi b/src/Compiler/TypedTree/TypedTreeOps.fsi index c67ccb30800..06200be47f7 100755 --- a/src/Compiler/TypedTree/TypedTreeOps.fsi +++ b/src/Compiler/TypedTree/TypedTreeOps.fsi @@ -1438,7 +1438,9 @@ val MakeApplicationAndBetaReduce: TcGlobals -> Expr * TType * TypeInst list * Ex /// Make a delegate invoke expression for an F# delegate type, doing beta reduction by introducing let-bindings /// if the delegate expression is a construction of a delegate. val MakeFSharpDelegateInvokeAndTryBetaReduce: - TcGlobals -> delInvokeRef: Expr * delExpr: Expr * delInvokeTy: TType * delInvokeArg: Expr * m: range -> Expr + TcGlobals -> + delInvokeRef: Expr * delExpr: Expr * delInvokeTy: TType * tyargs: TypeInst * delInvokeArg: Expr * m: range -> + Expr /// Combine two static-resolution requirements on a type parameter val JoinTyparStaticReq: TyparStaticReq -> TyparStaticReq -> TyparStaticReq @@ -2751,7 +2753,7 @@ val (|NewDelegateExpr|_|): TcGlobals -> Expr -> (Unique * Val list * Expr * rang /// Match a .Invoke on a delegate [] -val (|DelegateInvokeExpr|_|): TcGlobals -> Expr -> (Expr * TType * Expr * Expr * range) voption +val (|DelegateInvokeExpr|_|): TcGlobals -> Expr -> (Expr * TType * TypeInst * Expr * Expr * range) voption /// Match 'if __useResumableCode then ... else ...' expressions [] diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/ComputationExpressions.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/ComputationExpressions.fs index b6520a2f363..3fe71d27ac6 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/ComputationExpressions.fs +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/ComputationExpressions.fs @@ -73,3 +73,16 @@ module ComputationExpressions = compilation |> getCompilation |> verifyCompilation + + [] + let ``CustomCollectionBuilderComputationExpr_fs_OptimizeOff`` compilation = + compilation + |> getCompilation + |> asExe + |> withReferences [ + FsFromPath (Path.Combine (__SOURCE_DIRECTORY__, "CustomCollectionBuilderComputationExprLibrary.fs")) + |> withName "CustomCollectionBuilderComputationExprLibrary" + ] + |> withEmbeddedPdb + |> withEmbedAllSource + |> verifyILBaseline diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs new file mode 100644 index 00000000000..fd0522f6538 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs @@ -0,0 +1,14 @@ +module ComputationExpressions.Program + +let f0 () = + let xs = ResizeArray () + xs.Add 1 + xs.Add 2 + xs.Add 3 + xs + +let xs = f0 () + +let f1 () = resizeArray { 1; 2; 3 } +let f2 () = resizeArray { yield! xs } +let f3 () = resizeArray { for x in xs -> x * x } diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs.Optimize.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs.Optimize.il.bsl new file mode 100644 index 00000000000..706081806c7 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs.Optimize.il.bsl @@ -0,0 +1,228 @@ + + + + + +.assembly extern runtime { } +.assembly extern FSharp.Core { } +.assembly extern assemblyLibrary +{ + .ver 0:0:0:0 +} +.assembly assembly +{ + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.FSharpInterfaceDataVersionAttribute::.ctor(int32, + int32, + int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) + + + + + .hash algorithm 0x00008004 + .ver 0:0:0:0 +} +.module assembly.exe + +.imagebase {value} +.file alignment 0x00000200 +.stackreserve 0x00100000 +.subsystem 0x0003 +.corflags 0x00000001 + + + + + +.class public abstract auto ansi sealed ComputationExpressions.Program + extends [runtime]System.Object +{ + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .field static assembly class [runtime]System.Collections.Generic.List`1 xs@10 + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .method public static class [runtime]System.Collections.Generic.List`1 f0() cil managed + { + + .maxstack 4 + .locals init (class [runtime]System.Collections.Generic.List`1 V_0) + IL_0000: newobj instance void class [runtime]System.Collections.Generic.List`1::.ctor() + IL_0005: stloc.0 + IL_0006: ldloc.0 + IL_0007: ldc.i4.1 + IL_0008: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_000d: ldloc.0 + IL_000e: ldc.i4.2 + IL_000f: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_0014: ldloc.0 + IL_0015: ldc.i4.3 + IL_0016: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_001b: ldloc.0 + IL_001c: ret + } + + .method public specialname static class [runtime]System.Collections.Generic.List`1 get_xs() cil managed + { + + .maxstack 8 + IL_0000: ldsfld class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::xs@10 + IL_0005: ret + } + + .method public static class [runtime]System.Collections.Generic.List`1 f1() cil managed + { + + .maxstack 4 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_0, + class [runtime]System.Collections.Generic.List`1 V_1, + class [runtime]System.Collections.Generic.List`1& V_2) + IL_0000: call class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1::get_Instance() + IL_0005: stloc.0 + IL_0006: newobj instance void class [runtime]System.Collections.Generic.List`1::.ctor() + IL_000b: stloc.1 + IL_000c: ldloca.s V_1 + IL_000e: stloc.2 + IL_000f: ldloc.2 + IL_0010: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0015: ldc.i4.1 + IL_0016: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_001b: ldloca.s V_1 + IL_001d: stloc.2 + IL_001e: ldloc.2 + IL_001f: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0024: ldc.i4.2 + IL_0025: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_002a: ldloca.s V_1 + IL_002c: stloc.2 + IL_002d: ldloc.2 + IL_002e: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0033: ldc.i4.3 + IL_0034: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_0039: ldloc.1 + IL_003a: ret + } + + .method public static class [runtime]System.Collections.Generic.List`1 f2() cil managed + { + + .maxstack 4 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_0, + class [runtime]System.Collections.Generic.List`1 V_1, + class [runtime]System.Collections.Generic.List`1& V_2) + IL_0000: call class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1::get_Instance() + IL_0005: stloc.0 + IL_0006: newobj instance void class [runtime]System.Collections.Generic.List`1::.ctor() + IL_000b: stloc.1 + IL_000c: ldloca.s V_1 + IL_000e: stloc.2 + IL_000f: ldloc.2 + IL_0010: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0015: call class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::get_xs() + IL_001a: callvirt instance void class [runtime]System.Collections.Generic.List`1::AddRange(class [runtime]System.Collections.Generic.IEnumerable`1) + IL_001f: ldloc.1 + IL_0020: ret + } + + .method public static class [runtime]System.Collections.Generic.List`1 f3() cil managed + { + + .maxstack 5 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_0, + class [runtime]System.Collections.Generic.List`1 V_1, + int32 V_2, + int32 V_3, + int32 V_4, + int32 V_5, + class [runtime]System.Collections.Generic.List`1& V_6) + IL_0000: call class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1::get_Instance() + IL_0005: stloc.0 + IL_0006: newobj instance void class [runtime]System.Collections.Generic.List`1::.ctor() + IL_000b: stloc.1 + IL_000c: ldc.i4.0 + IL_000d: stloc.3 + IL_000e: call class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::get_xs() + IL_0013: callvirt instance int32 class [runtime]System.Collections.Generic.List`1::get_Count() + IL_0018: ldc.i4.1 + IL_0019: sub + IL_001a: stloc.2 + IL_001b: ldloc.2 + IL_001c: ldloc.3 + IL_001d: blt.s IL_004f + + IL_001f: call class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::get_xs() + IL_0024: ldloc.3 + IL_0025: callvirt instance !0 class [runtime]System.Collections.Generic.List`1::get_Item(int32) + IL_002a: stloc.s V_4 + IL_002c: ldloc.s V_4 + IL_002e: ldloc.s V_4 + IL_0030: mul + IL_0031: stloc.s V_5 + IL_0033: ldloca.s V_1 + IL_0035: stloc.s V_6 + IL_0037: ldloc.s V_6 + IL_0039: ldobj class [runtime]System.Collections.Generic.List`1 + IL_003e: ldloc.s V_5 + IL_0040: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_0045: ldloc.3 + IL_0046: ldc.i4.1 + IL_0047: add + IL_0048: stloc.3 + IL_0049: ldloc.3 + IL_004a: ldloc.2 + IL_004b: ldc.i4.1 + IL_004c: add + IL_004d: bne.un.s IL_001f + + IL_004f: ldloc.1 + IL_0050: ret + } + + .method private specialname rtspecialname static void .cctor() cil managed + { + + .maxstack 8 + IL_0000: ldc.i4.0 + IL_0001: stsfld int32 '.$ComputationExpressions'.Program::init@ + IL_0006: ldsfld int32 '.$ComputationExpressions'.Program::init@ + IL_000b: pop + IL_000c: ret + } + + .method assembly specialname static void staticInitialization@() cil managed + { + + .maxstack 8 + IL_0000: call class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::f0() + IL_0005: stsfld class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::xs@10 + IL_000a: ret + } + + .property class [runtime]System.Collections.Generic.List`1 + xs() + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 09 00 00 00 00 00 ) + .get class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::get_xs() + } +} + +.class private abstract auto ansi sealed '.$ComputationExpressions'.Program + extends [runtime]System.Object +{ + .field static assembly int32 init@ + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public static void main@() cil managed + { + .entrypoint + + .maxstack 8 + IL_0000: call void ComputationExpressions.Program::staticInitialization@() + IL_0005: ret + } + +} + + + + + + diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs.OptimizeOff.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs.OptimizeOff.il.bsl new file mode 100644 index 00000000000..cd7c9b8430b --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExpr.fs.OptimizeOff.il.bsl @@ -0,0 +1,593 @@ + + + + + +.assembly extern runtime { } +.assembly extern FSharp.Core { } +.assembly extern assemblyLibrary +{ + .ver 0:0:0:0 +} +.assembly assembly +{ + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.FSharpInterfaceDataVersionAttribute::.ctor(int32, + int32, + int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) + + + + + .hash algorithm 0x00008004 + .ver 0:0:0:0 +} +.module assembly.exe + +.imagebase {value} +.file alignment 0x00000200 +.stackreserve 0x00100000 +.subsystem 0x0003 +.corflags 0x00000001 + + + + + +.class public abstract auto ansi sealed ComputationExpressions.Program + extends [runtime]System.Object +{ + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto autochar serializable sealed nested assembly beforefieldinit specialname 'f1@12-1' + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .field public int32 x + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public specialname rtspecialname instance void .ctor(int32 x) cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: stfld int32 ComputationExpressions.Program/'f1@12-1'::x + IL_0007: ldarg.0 + IL_0008: call instance void [runtime]System.Object::.ctor() + IL_000d: ret + } + + .method assembly hidebysig instance void Invoke(class [runtime]System.Collections.Generic.List`1& sm) cil managed + { + + .maxstack 8 + IL_0000: ldarg.1 + IL_0001: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0006: ldarg.0 + IL_0007: ldfld int32 ComputationExpressions.Program/'f1@12-1'::x + IL_000c: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_0011: ret + } + + } + + .class auto autochar serializable sealed nested assembly beforefieldinit specialname 'f1@12-3' + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .field public int32 x + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public specialname rtspecialname instance void .ctor(int32 x) cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: stfld int32 ComputationExpressions.Program/'f1@12-3'::x + IL_0007: ldarg.0 + IL_0008: call instance void [runtime]System.Object::.ctor() + IL_000d: ret + } + + .method assembly hidebysig instance void Invoke(class [runtime]System.Collections.Generic.List`1& sm) cil managed + { + + .maxstack 8 + IL_0000: ldarg.1 + IL_0001: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0006: ldarg.0 + IL_0007: ldfld int32 ComputationExpressions.Program/'f1@12-3'::x + IL_000c: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_0011: ret + } + + } + + .class auto autochar serializable sealed nested assembly beforefieldinit specialname 'f1@12-4' + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .field public class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@ + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public specialname rtspecialname instance void .ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@) cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: stfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/'f1@12-4'::builder@ + IL_0007: ldarg.0 + IL_0008: call instance void [runtime]System.Object::.ctor() + IL_000d: ret + } + + .method assembly hidebysig instance void Invoke(class [runtime]System.Collections.Generic.List`1& sm) cil managed + { + + .maxstack 6 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_0, + int32 V_1, + class [runtime]System.Collections.Generic.List`1& V_2) + IL_0000: ldarg.0 + IL_0001: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/'f1@12-4'::builder@ + IL_0006: stloc.0 + IL_0007: ldc.i4.3 + IL_0008: stloc.1 + IL_0009: ldarg.1 + IL_000a: stloc.2 + IL_000b: ldloc.2 + IL_000c: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0011: ldloc.1 + IL_0012: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_0017: ret + } + + } + + .class auto autochar serializable sealed nested assembly beforefieldinit specialname 'f1@12-2' + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .field public class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@ + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public specialname rtspecialname instance void .ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@) cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: stfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/'f1@12-2'::builder@ + IL_0007: ldarg.0 + IL_0008: call instance void [runtime]System.Object::.ctor() + IL_000d: ret + } + + .method assembly hidebysig instance void Invoke(class [runtime]System.Collections.Generic.List`1& sm) cil managed + { + + .maxstack 6 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_0, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1> V_1, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_2, + int32 V_3, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1> V_4, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_5, + class [runtime]System.Collections.Generic.List`1& V_6) + IL_0000: ldarg.0 + IL_0001: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/'f1@12-2'::builder@ + IL_0006: stloc.0 + IL_0007: ldarg.0 + IL_0008: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/'f1@12-2'::builder@ + IL_000d: stloc.2 + IL_000e: ldc.i4.2 + IL_000f: stloc.3 + IL_0010: ldloc.3 + IL_0011: newobj instance void ComputationExpressions.Program/'f1@12-3'::.ctor(int32) + IL_0016: ldftn instance void ComputationExpressions.Program/'f1@12-3'::Invoke(class [runtime]System.Collections.Generic.List`1&) + IL_001c: newobj instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::.ctor(object, + native int) + IL_0021: stloc.1 + IL_0022: ldarg.0 + IL_0023: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/'f1@12-2'::builder@ + IL_0028: stloc.s V_5 + IL_002a: ldarg.0 + IL_002b: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/'f1@12-2'::builder@ + IL_0030: newobj instance void ComputationExpressions.Program/'f1@12-4'::.ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1) + IL_0035: ldftn instance void ComputationExpressions.Program/'f1@12-4'::Invoke(class [runtime]System.Collections.Generic.List`1&) + IL_003b: newobj instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::.ctor(object, + native int) + IL_0040: stloc.s V_4 + IL_0042: ldarg.1 + IL_0043: stloc.s V_6 + IL_0045: ldloc.1 + IL_0046: ldloc.s V_6 + IL_0048: callvirt instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::Invoke(!0&) + IL_004d: nop + IL_004e: ldloc.s V_4 + IL_0050: ldloc.s V_6 + IL_0052: callvirt instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::Invoke(!0&) + IL_0057: nop + IL_0058: ret + } + + } + + .class auto autochar serializable sealed nested assembly beforefieldinit specialname f1@12 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .field public class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@ + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public specialname rtspecialname instance void .ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@) cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: stfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f1@12::builder@ + IL_0007: ldarg.0 + IL_0008: call instance void [runtime]System.Object::.ctor() + IL_000d: ret + } + + .method assembly hidebysig instance void Invoke(class [runtime]System.Collections.Generic.List`1& sm) cil managed + { + + .maxstack 6 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_0, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1> V_1, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_2, + int32 V_3, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1> V_4, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_5, + class [runtime]System.Collections.Generic.List`1& V_6) + IL_0000: ldarg.0 + IL_0001: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f1@12::builder@ + IL_0006: stloc.0 + IL_0007: ldarg.0 + IL_0008: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f1@12::builder@ + IL_000d: stloc.2 + IL_000e: ldc.i4.1 + IL_000f: stloc.3 + IL_0010: ldloc.3 + IL_0011: newobj instance void ComputationExpressions.Program/'f1@12-1'::.ctor(int32) + IL_0016: ldftn instance void ComputationExpressions.Program/'f1@12-1'::Invoke(class [runtime]System.Collections.Generic.List`1&) + IL_001c: newobj instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::.ctor(object, + native int) + IL_0021: stloc.1 + IL_0022: ldarg.0 + IL_0023: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f1@12::builder@ + IL_0028: stloc.s V_5 + IL_002a: ldarg.0 + IL_002b: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f1@12::builder@ + IL_0030: newobj instance void ComputationExpressions.Program/'f1@12-2'::.ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1) + IL_0035: ldftn instance void ComputationExpressions.Program/'f1@12-2'::Invoke(class [runtime]System.Collections.Generic.List`1&) + IL_003b: newobj instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::.ctor(object, + native int) + IL_0040: stloc.s V_4 + IL_0042: ldarg.1 + IL_0043: stloc.s V_6 + IL_0045: ldloc.1 + IL_0046: ldloc.s V_6 + IL_0048: callvirt instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::Invoke(!0&) + IL_004d: nop + IL_004e: ldloc.s V_4 + IL_0050: ldloc.s V_6 + IL_0052: callvirt instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::Invoke(!0&) + IL_0057: nop + IL_0058: ret + } + + } + + .class auto autochar serializable sealed nested assembly beforefieldinit specialname f2@13 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .field public class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@ + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public specialname rtspecialname instance void .ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@) cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: stfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f2@13::builder@ + IL_0007: ldarg.0 + IL_0008: call instance void [runtime]System.Object::.ctor() + IL_000d: ret + } + + .method assembly hidebysig instance void Invoke(class [runtime]System.Collections.Generic.List`1& sm) cil managed + { + + .maxstack 6 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_0, + class [runtime]System.Collections.Generic.List`1 V_1, + class [runtime]System.Collections.Generic.List`1& V_2) + IL_0000: ldarg.0 + IL_0001: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f2@13::builder@ + IL_0006: stloc.0 + IL_0007: call class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::get_xs() + IL_000c: stloc.1 + IL_000d: ldarg.1 + IL_000e: stloc.2 + IL_000f: ldloc.2 + IL_0010: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0015: ldloc.1 + IL_0016: callvirt instance void class [runtime]System.Collections.Generic.List`1::AddRange(class [runtime]System.Collections.Generic.IEnumerable`1) + IL_001b: ret + } + + } + + .class auto autochar serializable sealed nested assembly beforefieldinit specialname f3@14 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .field public class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@ + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public specialname rtspecialname instance void .ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 builder@) cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: ldarg.1 + IL_0002: stfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f3@14::builder@ + IL_0007: ldarg.0 + IL_0008: call instance void [runtime]System.Object::.ctor() + IL_000d: ret + } + + .method assembly hidebysig instance void Invoke(class [runtime]System.Collections.Generic.List`1& sm) cil managed + { + + .maxstack 7 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_0, + class [runtime]System.Collections.Generic.List`1 V_1, + class [runtime]System.Collections.Generic.List`1& V_2, + int32 V_3, + int32 V_4, + int32 V_5, + int32 V_6, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_7, + int32 V_8, + class [runtime]System.Collections.Generic.List`1& V_9) + IL_0000: ldarg.0 + IL_0001: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f3@14::builder@ + IL_0006: stloc.0 + IL_0007: call class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::get_xs() + IL_000c: stloc.1 + IL_000d: ldarg.1 + IL_000e: stloc.2 + IL_000f: ldc.i4.0 + IL_0010: stloc.s V_4 + IL_0012: ldloc.1 + IL_0013: callvirt instance int32 class [runtime]System.Collections.Generic.List`1::get_Count() + IL_0018: ldc.i4.1 + IL_0019: sub + IL_001a: stloc.3 + IL_001b: ldloc.3 + IL_001c: ldloc.s V_4 + IL_001e: blt.s IL_005b + + IL_0020: ldloc.1 + IL_0021: ldloc.s V_4 + IL_0023: callvirt instance !0 class [runtime]System.Collections.Generic.List`1::get_Item(int32) + IL_0028: stloc.s V_5 + IL_002a: ldloc.s V_5 + IL_002c: stloc.s V_6 + IL_002e: ldarg.0 + IL_002f: ldfld class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 ComputationExpressions.Program/f3@14::builder@ + IL_0034: stloc.s V_7 + IL_0036: ldloc.s V_6 + IL_0038: ldloc.s V_6 + IL_003a: mul + IL_003b: stloc.s V_8 + IL_003d: ldloc.2 + IL_003e: stloc.s V_9 + IL_0040: ldloc.s V_9 + IL_0042: ldobj class [runtime]System.Collections.Generic.List`1 + IL_0047: ldloc.s V_8 + IL_0049: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_004e: ldloc.s V_4 + IL_0050: ldc.i4.1 + IL_0051: add + IL_0052: stloc.s V_4 + IL_0054: ldloc.s V_4 + IL_0056: ldloc.3 + IL_0057: ldc.i4.1 + IL_0058: add + IL_0059: bne.un.s IL_0020 + + IL_005b: ret + } + + } + + .field static assembly class [runtime]System.Collections.Generic.List`1 xs@10 + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .method public static class [runtime]System.Collections.Generic.List`1 f0() cil managed + { + + .maxstack 4 + .locals init (class [runtime]System.Collections.Generic.List`1 V_0) + IL_0000: newobj instance void class [runtime]System.Collections.Generic.List`1::.ctor() + IL_0005: stloc.0 + IL_0006: ldloc.0 + IL_0007: ldc.i4.1 + IL_0008: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_000d: ldloc.0 + IL_000e: ldc.i4.2 + IL_000f: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_0014: ldloc.0 + IL_0015: ldc.i4.3 + IL_0016: callvirt instance void class [runtime]System.Collections.Generic.List`1::Add(!0) + IL_001b: ldloc.0 + IL_001c: ret + } + + .method public specialname static class [runtime]System.Collections.Generic.List`1 get_xs() cil managed + { + + .maxstack 8 + IL_0000: ldsfld class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::xs@10 + IL_0005: ret + } + + .method public static class [runtime]System.Collections.Generic.List`1 f1() cil managed + { + + .maxstack 4 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_0, + class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_1, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1> V_2, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_3, + class [runtime]System.Collections.Generic.List`1 V_4) + IL_0000: call class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 [assemblyLibrary]ComputationExpressions.Library::resizeArray() + IL_0005: stloc.0 + IL_0006: ldloc.0 + IL_0007: stloc.1 + IL_0008: ldloc.0 + IL_0009: stloc.3 + IL_000a: ldloc.0 + IL_000b: newobj instance void ComputationExpressions.Program/f1@12::.ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1) + IL_0010: ldftn instance void ComputationExpressions.Program/f1@12::Invoke(class [runtime]System.Collections.Generic.List`1&) + IL_0016: newobj instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::.ctor(object, + native int) + IL_001b: stloc.2 + IL_001c: newobj instance void class [runtime]System.Collections.Generic.List`1::.ctor() + IL_0021: stloc.s V_4 + IL_0023: ldloc.2 + IL_0024: ldloca.s V_4 + IL_0026: callvirt instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::Invoke(!0&) + IL_002b: nop + IL_002c: ldloc.s V_4 + IL_002e: ret + } + + .method public static class [runtime]System.Collections.Generic.List`1 f2() cil managed + { + + .maxstack 4 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_0, + class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_1, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1> V_2, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_3, + class [runtime]System.Collections.Generic.List`1 V_4) + IL_0000: call class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 [assemblyLibrary]ComputationExpressions.Library::resizeArray() + IL_0005: stloc.0 + IL_0006: ldloc.0 + IL_0007: stloc.1 + IL_0008: ldloc.0 + IL_0009: stloc.3 + IL_000a: ldloc.0 + IL_000b: newobj instance void ComputationExpressions.Program/f2@13::.ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1) + IL_0010: ldftn instance void ComputationExpressions.Program/f2@13::Invoke(class [runtime]System.Collections.Generic.List`1&) + IL_0016: newobj instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::.ctor(object, + native int) + IL_001b: stloc.2 + IL_001c: newobj instance void class [runtime]System.Collections.Generic.List`1::.ctor() + IL_0021: stloc.s V_4 + IL_0023: ldloc.2 + IL_0024: ldloca.s V_4 + IL_0026: callvirt instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::Invoke(!0&) + IL_002b: nop + IL_002c: ldloc.s V_4 + IL_002e: ret + } + + .method public static class [runtime]System.Collections.Generic.List`1 f3() cil managed + { + + .maxstack 4 + .locals init (class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_0, + class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 V_1, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1> V_2, + class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilder V_3, + class [runtime]System.Collections.Generic.List`1 V_4) + IL_0000: call class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1 [assemblyLibrary]ComputationExpressions.Library::resizeArray() + IL_0005: stloc.0 + IL_0006: ldloc.0 + IL_0007: stloc.1 + IL_0008: ldloc.0 + IL_0009: stloc.3 + IL_000a: ldloc.0 + IL_000b: newobj instance void ComputationExpressions.Program/f3@14::.ctor(class [assemblyLibrary]ComputationExpressions.Library/ResizeArrayBuilder`1) + IL_0010: ldftn instance void ComputationExpressions.Program/f3@14::Invoke(class [runtime]System.Collections.Generic.List`1&) + IL_0016: newobj instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::.ctor(object, + native int) + IL_001b: stloc.2 + IL_001c: newobj instance void class [runtime]System.Collections.Generic.List`1::.ctor() + IL_0021: stloc.s V_4 + IL_0023: ldloc.2 + IL_0024: ldloca.s V_4 + IL_0026: callvirt instance void class [assemblyLibrary]ComputationExpressions.Library/CollectionBuilderCode`1>::Invoke(!0&) + IL_002b: nop + IL_002c: ldloc.s V_4 + IL_002e: ret + } + + .method private specialname rtspecialname static void .cctor() cil managed + { + + .maxstack 8 + IL_0000: ldc.i4.0 + IL_0001: stsfld int32 '.$ComputationExpressions'.Program::init@ + IL_0006: ldsfld int32 '.$ComputationExpressions'.Program::init@ + IL_000b: pop + IL_000c: ret + } + + .method assembly specialname static void staticInitialization@() cil managed + { + + .maxstack 8 + IL_0000: call class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::f0() + IL_0005: stsfld class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::xs@10 + IL_000a: ret + } + + .property class [runtime]System.Collections.Generic.List`1 + xs() + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 09 00 00 00 00 00 ) + .get class [runtime]System.Collections.Generic.List`1 ComputationExpressions.Program::get_xs() + } +} + +.class private abstract auto ansi sealed '.$ComputationExpressions'.Program + extends [runtime]System.Object +{ + .field static assembly int32 init@ + .custom instance void [runtime]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [runtime]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) + .custom instance void [runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) + .custom instance void [runtime]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) + .method public static void main@() cil managed + { + .entrypoint + + .maxstack 8 + IL_0000: call void ComputationExpressions.Program::staticInitialization@() + IL_0005: ret + } + +} + + + + + + diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExprLibrary.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExprLibrary.fs new file mode 100644 index 00000000000..5fa93736fb7 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/ComputationExpressions/CustomCollectionBuilderComputationExprLibrary.fs @@ -0,0 +1,59 @@ +namespace ComputationExpressions + +#nowarn 77 + +open System + +[] +module Library = + type CollectionBuilderCode<'T> = delegate of byref<'T> -> unit + + type CollectionBuilder () = + member inline _.Combine ([] f1 : CollectionBuilderCode<_>, [] f2 : CollectionBuilderCode<_>) = + CollectionBuilderCode (fun sm -> f1.Invoke &sm; f2.Invoke &sm) + + member inline _.Delay ([] f : unit -> CollectionBuilderCode<_>) = + CollectionBuilderCode (fun sm -> (f ()).Invoke &sm) + + member inline _.Zero () = CollectionBuilderCode (fun _ -> ()) + + member inline _.While ([] condition : unit -> bool, [] body : CollectionBuilderCode<_>) = + CollectionBuilderCode (fun sm -> + while condition () do + body.Invoke &sm) + + member inline _.TryWith ([] body : CollectionBuilderCode<_>, [] handle : exn -> CollectionBuilderCode<_>) = + CollectionBuilderCode (fun sm -> + try body.Invoke &sm + with e -> (handle e).Invoke &sm) + + member inline _.TryFinally ([] body : CollectionBuilderCode<_>, compensation : unit -> unit) = + CollectionBuilderCode (fun sm -> + try body.Invoke &sm + with _ -> + compensation () + reraise () + compensation ()) + + member inline builder.Using (disposable : #IDisposable, [] body : #IDisposable -> CollectionBuilderCode<_>) = + builder.TryFinally ((fun sm -> (body disposable).Invoke &sm), (fun () -> if not (isNull (box disposable)) then disposable.Dispose ())) + + member inline _.For (resizeArray : ResizeArray<_>, [] body : _ -> CollectionBuilderCode<_>) = + CollectionBuilderCode (fun sm -> + for i in 0 .. resizeArray.Count - 1 do + (body resizeArray[i]).Invoke &sm) + + member inline _.Yield x = CollectionBuilderCode (fun sm -> ignore (^a : (member Add : ^b -> _) (sm, x))) + + member inline builder.YieldFrom xs = CollectionBuilderCode (fun sm -> ignore (^a : (member AddRange : ^b -> _) (sm, xs))) + + [] + type ResizeArrayBuilder<'T> () = + inherit CollectionBuilder () + static member val Instance = ResizeArrayBuilder<'T> () + member inline _.Run ([] f : CollectionBuilderCode<_>) = + let mutable sm = ResizeArray<'T> () + f.Invoke &sm + sm + + let resizeArray<'T> = ResizeArrayBuilder<'T>.Instance diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs new file mode 100644 index 00000000000..21c23d68169 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs @@ -0,0 +1,25 @@ +module Program + +module DelegateImmediateInvoke1 = + type Foo = delegate of unit -> unit + + let f () = + let f1 = Foo ignore + f1.Invoke () + +module DelegateImmediateInvoke2 = + type Foo = delegate of unit -> unit + + let f () = Foo(ignore).Invoke() + +module DelegateImmediateInvoke3 = + type Foo<'T> = delegate of 'T -> unit + + let f () = + let f1 = Foo ignore + f1.Invoke(()) + +module DelegateImmediateInvoke4 = + type Foo<'T> = delegate of 'T -> unit + + let f () = Foo(ignore).Invoke(()) diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs.RealInternalSignature.Optimize.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs.RealInternalSignature.Optimize.il.bsl new file mode 100644 index 00000000000..5c03f90dab8 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs.RealInternalSignature.Optimize.il.bsl @@ -0,0 +1,247 @@ + + + + + +.assembly extern runtime { } +.assembly extern FSharp.Core { } +.assembly assembly +{ + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.FSharpInterfaceDataVersionAttribute::.ctor(int32, + int32, + int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) + + + + + .hash algorithm 0x00008004 + .ver 0:0:0:0 +} +.module assembly.exe + +.imagebase {value} +.file alignment 0x00000200 +.stackreserve 0x00100000 +.subsystem 0x0003 +.corflags 0x00000001 + + + + + +.class public abstract auto ansi sealed Program + extends [runtime]System.Object +{ + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class abstract auto ansi sealed nested public DelegateImmediateInvoke4 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto ansi serializable sealed nested public Foo`1 + extends [runtime]System.MulticastDelegate + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) + .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public hidebysig strict virtual instance void Invoke(!T A_1) runtime managed + { + } + + .method public hidebysig strict virtual + instance class [runtime]System.IAsyncResult + BeginInvoke(!T A_1, + class [runtime]System.AsyncCallback callback, + object objects) runtime managed + { + } + + .method public hidebysig strict virtual instance void EndInvoke(class [runtime]System.IAsyncResult result) runtime managed + { + } + + } + + .method public static void f() cil managed + { + + .maxstack 8 + IL_0000: ret + } + + } + + .class abstract auto ansi sealed nested public DelegateImmediateInvoke3 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto ansi serializable sealed nested public Foo`1 + extends [runtime]System.MulticastDelegate + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) + .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public hidebysig strict virtual instance void Invoke(!T A_1) runtime managed + { + } + + .method public hidebysig strict virtual + instance class [runtime]System.IAsyncResult + BeginInvoke(!T A_1, + class [runtime]System.AsyncCallback callback, + object objects) runtime managed + { + } + + .method public hidebysig strict virtual instance void EndInvoke(class [runtime]System.IAsyncResult result) runtime managed + { + } + + } + + .method public static void f() cil managed + { + + .maxstack 8 + IL_0000: ret + } + + } + + .class abstract auto ansi sealed nested public DelegateImmediateInvoke2 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto ansi serializable sealed nested public Foo + extends [runtime]System.MulticastDelegate + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) + .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public hidebysig strict virtual instance void Invoke() runtime managed + { + } + + .method public hidebysig strict virtual + instance class [runtime]System.IAsyncResult + BeginInvoke(class [runtime]System.AsyncCallback callback, + object objects) runtime managed + { + } + + .method public hidebysig strict virtual instance void EndInvoke(class [runtime]System.IAsyncResult result) runtime managed + { + } + + } + + .class abstract auto autochar serializable sealed nested assembly beforefieldinit specialname 'f@13-1' + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .method assembly static void Invoke() cil managed + { + + .maxstack 8 + IL_0000: ret + } + + } + + .method public static void f() cil managed + { + + .maxstack 8 + IL_0000: ldnull + IL_0001: ldftn void Program/DelegateImmediateInvoke2/'f@13-1'::Invoke() + IL_0007: newobj instance void Program/DelegateImmediateInvoke2/Foo::.ctor(object, + native int) + IL_000c: tail. + IL_000e: callvirt instance void Program/DelegateImmediateInvoke2/Foo::Invoke() + IL_0013: ret + } + + } + + .class abstract auto ansi sealed nested public DelegateImmediateInvoke1 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto ansi serializable sealed nested public Foo + extends [runtime]System.MulticastDelegate + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) + .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public hidebysig strict virtual instance void Invoke() runtime managed + { + } + + .method public hidebysig strict virtual + instance class [runtime]System.IAsyncResult + BeginInvoke(class [runtime]System.AsyncCallback callback, + object objects) runtime managed + { + } + + .method public hidebysig strict virtual instance void EndInvoke(class [runtime]System.IAsyncResult result) runtime managed + { + } + + } + + .class abstract auto autochar serializable sealed nested assembly beforefieldinit specialname f@7 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .method assembly static void Invoke() cil managed + { + + .maxstack 8 + IL_0000: ret + } + + } + + .method public static void f() cil managed + { + + .maxstack 8 + IL_0000: ldnull + IL_0001: ldftn void Program/DelegateImmediateInvoke1/f@7::Invoke() + IL_0007: newobj instance void Program/DelegateImmediateInvoke1/Foo::.ctor(object, + native int) + IL_000c: tail. + IL_000e: callvirt instance void Program/DelegateImmediateInvoke1/Foo::Invoke() + IL_0013: ret + } + + } + +} + +.class private abstract auto ansi sealed ''.$Program + extends [runtime]System.Object +{ + .method public static void main@() cil managed + { + .entrypoint + + .maxstack 8 + IL_0000: ret + } + +} + + + + + + diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs.RealInternalSignature.OptimizeOff.il.bsl b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs.RealInternalSignature.OptimizeOff.il.bsl new file mode 100644 index 00000000000..af56908af03 --- /dev/null +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/FSharpDelegateBetaReduction.fs.RealInternalSignature.OptimizeOff.il.bsl @@ -0,0 +1,277 @@ + + + + + +.assembly extern runtime { } +.assembly extern FSharp.Core { } +.assembly assembly +{ + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.FSharpInterfaceDataVersionAttribute::.ctor(int32, + int32, + int32) = ( 01 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 ) + + + + + .hash algorithm 0x00008004 + .ver 0:0:0:0 +} +.module assembly.exe + +.imagebase {value} +.file alignment 0x00000200 +.stackreserve 0x00100000 +.subsystem 0x0003 +.corflags 0x00000001 + + + + + +.class public abstract auto ansi sealed Program + extends [runtime]System.Object +{ + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class abstract auto ansi sealed nested public DelegateImmediateInvoke4 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto ansi serializable sealed nested public Foo`1 + extends [runtime]System.MulticastDelegate + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) + .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public hidebysig strict virtual instance void Invoke(!T A_1) runtime managed + { + } + + .method public hidebysig strict virtual + instance class [runtime]System.IAsyncResult + BeginInvoke(!T A_1, + class [runtime]System.AsyncCallback callback, + object objects) runtime managed + { + } + + .method public hidebysig strict virtual instance void EndInvoke(class [runtime]System.IAsyncResult result) runtime managed + { + } + + } + + .method public static void f() cil managed + { + + .maxstack 8 + IL_0000: ldnull + IL_0001: pop + IL_0002: ret + } + + } + + .class abstract auto ansi sealed nested public DelegateImmediateInvoke3 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto ansi serializable sealed nested public Foo`1 + extends [runtime]System.MulticastDelegate + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) + .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public hidebysig strict virtual instance void Invoke(!T A_1) runtime managed + { + } + + .method public hidebysig strict virtual + instance class [runtime]System.IAsyncResult + BeginInvoke(!T A_1, + class [runtime]System.AsyncCallback callback, + object objects) runtime managed + { + } + + .method public hidebysig strict virtual instance void EndInvoke(class [runtime]System.IAsyncResult result) runtime managed + { + } + + } + + .class abstract auto autochar serializable sealed nested assembly beforefieldinit specialname 'f1@19-1' + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .method assembly static void Invoke(class [FSharp.Core]Microsoft.FSharp.Core.Unit delegateArg0) cil managed + { + + .maxstack 8 + IL_0000: ldarg.0 + IL_0001: pop + IL_0002: ret + } + + } + + .method public static void f() cil managed + { + + .maxstack 4 + .locals init (class Program/DelegateImmediateInvoke3/Foo`1 V_0) + IL_0000: ldnull + IL_0001: ldftn void Program/DelegateImmediateInvoke3/'f1@19-1'::Invoke(class [FSharp.Core]Microsoft.FSharp.Core.Unit) + IL_0007: newobj instance void class Program/DelegateImmediateInvoke3/Foo`1::.ctor(object, + native int) + IL_000c: stloc.0 + IL_000d: ldloc.0 + IL_000e: ldnull + IL_000f: tail. + IL_0011: callvirt instance void class Program/DelegateImmediateInvoke3/Foo`1::Invoke(!0) + IL_0016: ret + } + + } + + .class abstract auto ansi sealed nested public DelegateImmediateInvoke2 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto ansi serializable sealed nested public Foo + extends [runtime]System.MulticastDelegate + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) + .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public hidebysig strict virtual instance void Invoke() runtime managed + { + } + + .method public hidebysig strict virtual + instance class [runtime]System.IAsyncResult + BeginInvoke(class [runtime]System.AsyncCallback callback, + object objects) runtime managed + { + } + + .method public hidebysig strict virtual instance void EndInvoke(class [runtime]System.IAsyncResult result) runtime managed + { + } + + } + + .class abstract auto autochar serializable sealed nested assembly beforefieldinit specialname f@13 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .method assembly static void Invoke() cil managed + { + + .maxstack 8 + IL_0000: ret + } + + } + + .method public static void f() cil managed + { + + .maxstack 8 + IL_0000: ldnull + IL_0001: ldftn void Program/DelegateImmediateInvoke2/f@13::Invoke() + IL_0007: newobj instance void Program/DelegateImmediateInvoke2/Foo::.ctor(object, + native int) + IL_000c: tail. + IL_000e: callvirt instance void Program/DelegateImmediateInvoke2/Foo::Invoke() + IL_0013: ret + } + + } + + .class abstract auto ansi sealed nested public DelegateImmediateInvoke1 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) + .class auto ansi serializable sealed nested public Foo + extends [runtime]System.MulticastDelegate + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 03 00 00 00 00 00 ) + .method public hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed + { + } + + .method public hidebysig strict virtual instance void Invoke() runtime managed + { + } + + .method public hidebysig strict virtual + instance class [runtime]System.IAsyncResult + BeginInvoke(class [runtime]System.AsyncCallback callback, + object objects) runtime managed + { + } + + .method public hidebysig strict virtual instance void EndInvoke(class [runtime]System.IAsyncResult result) runtime managed + { + } + + } + + .class abstract auto autochar serializable sealed nested assembly beforefieldinit specialname f1@7 + extends [runtime]System.Object + { + .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 06 00 00 00 00 00 ) + .method assembly static void Invoke() cil managed + { + + .maxstack 8 + IL_0000: ret + } + + } + + .method public static void f() cil managed + { + + .maxstack 4 + .locals init (class Program/DelegateImmediateInvoke1/Foo V_0) + IL_0000: ldnull + IL_0001: ldftn void Program/DelegateImmediateInvoke1/f1@7::Invoke() + IL_0007: newobj instance void Program/DelegateImmediateInvoke1/Foo::.ctor(object, + native int) + IL_000c: stloc.0 + IL_000d: ldloc.0 + IL_000e: tail. + IL_0010: callvirt instance void Program/DelegateImmediateInvoke1/Foo::Invoke() + IL_0015: ret + } + + } + +} + +.class private abstract auto ansi sealed ''.$Program + extends [runtime]System.Object +{ + .method public static void main@() cil managed + { + .entrypoint + + .maxstack 8 + IL_0000: ret + } + +} + + + + + + diff --git a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Inlining.fs b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Inlining.fs index d226b4dc25f..109b427ad5f 100644 --- a/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Inlining.fs +++ b/tests/FSharp.Compiler.ComponentTests/EmittedIL/Inlining/Inlining.fs @@ -41,6 +41,17 @@ module Inlining = |> getCompilation |> verifyCompilation + [] + let ``FSharpDelegateBetaReduction_fs`` compilation = + compilation + |> getCompilation + |> withOptions [ "--test:EmitFeeFeeAs100001" ] + |> asExe + |> withEmbeddedPdb + |> withEmbedAllSource + |> ignoreWarnings + |> verifyILBaseline + [] let ``List contains inlining`` () = Fsx """module Test diff --git a/tests/FSharp.Test.Utilities/ILChecker.fs b/tests/FSharp.Test.Utilities/ILChecker.fs index 69b5d6c6c6a..78579102120 100644 --- a/tests/FSharp.Test.Utilities/ILChecker.fs +++ b/tests/FSharp.Test.Utilities/ILChecker.fs @@ -60,8 +60,9 @@ module ILChecker = let unifyRuntimeAssemblyName ilCode = List.fold replace ilCode [ - "\[System\.Runtime\]|\[System\.Console\]|\[System\.Runtime\.Extensions\]|\[mscorlib\]|\[System\.Memory\]", "[runtime]" + "\[System\.Runtime\]|\[System\.Console\]|\[System\.Runtime\.Extensions\]|\[mscorlib\]|\[System\.Memory\]|\[System\.Collections\]", "[runtime]" "(\.assembly extern (System\.Runtime|System\.Console|System\.Runtime\.Extensions|mscorlib|System\.Memory)){1}([^\}]*)\}", ".assembly extern runtime { }" + "(\.assembly extern (System\.Collections)){1}([^\}]*)\}\\s+", "" "(\.assembly extern (FSharp.Core)){1}([^\}]*)\}", ".assembly extern FSharp.Core { }" ] let unifyImageBase ilCode = replace ilCode ("\.imagebase\s*0x\d*", ".imagebase {value}") From fdf1bddbf3ddc2e7ee344af6e5d6d2e65d2aa06a Mon Sep 17 00:00:00 2001 From: Tomas Grosup Date: Tue, 1 Apr 2025 13:58:36 +0200 Subject: [PATCH 12/20] Create resourceManagement.yml --- .github/policies/resourceManagement.yml | 43 +++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 .github/policies/resourceManagement.yml diff --git a/.github/policies/resourceManagement.yml b/.github/policies/resourceManagement.yml new file mode 100644 index 00000000000..6a4eae33150 --- /dev/null +++ b/.github/policies/resourceManagement.yml @@ -0,0 +1,43 @@ +id: +name: GitOps.PullRequestIssueManagement +description: GitOps.PullRequestIssueManagement primitive +owner: +resource: repository +disabled: false +where: +configuration: + resourceManagementConfiguration: + eventResponderTasks: + - if: + - payloadType: Issues + - labelAdded: + label: Breaking-change + then: + - addReply: + reply: >- + Refer to the [.NET SDK breaking change guidelines](https://github.com/dotnet/sdk/blob/main/documentation/project-docs/breaking-change-guidelines.md#required-process-for-all-net-sdk-breaking-changes) + description: Add breaking change doc instructions to issue + - if: + - payloadType: Pull_Request + - labelAdded: + label: Breaking-change + then: + - addLabel: + label: needs-breaking-change-doc-created + - addReply: + reply: >- + Added `needs-breaking-change-doc-created` label because this PR has the `breaking-change` label. + + + When you commit this breaking change: + + + 1. [ ] Create and link to this PR and the issue a matching issue in the dotnet/docs repo using the [breaking change documentation template](https://aka.ms/dotnet/docs/new-breaking-change-issue), then remove this `needs-breaking-change-doc-created` label. + + 2. [ ] Ask a committer to mail the `.NET SDK Breaking Change Notification` email list. + + + You can refer to the [.NET SDK breaking change guidelines](https://github.com/dotnet/sdk/blob/main/documentation/project-docs/breaking-change-guidelines.md) + description: Add breaking change instructions to PR. +onFailure: +onSuccess: From d43577caeba6396a1398553fb85f3167b978160a Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Wed, 2 Apr 2025 09:43:01 -0700 Subject: [PATCH 13/20] Fix PM (#18435) --- src/Compiler/Driver/ScriptClosure.fs | 6 ++++-- vsintegration/src/FSharp.Editor/Common/Extensions.fs | 2 +- .../LanguageService/FSharpProjectOptionsManager.fs | 10 ++++++---- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/Compiler/Driver/ScriptClosure.fs b/src/Compiler/Driver/ScriptClosure.fs index b97b11a8054..b45049627cf 100644 --- a/src/Compiler/Driver/ScriptClosure.fs +++ b/src/Compiler/Driver/ScriptClosure.fs @@ -327,11 +327,13 @@ module ScriptPreprocessClosure = for kv in tcConfig.packageManagerLines do let packageManagerKey, packageManagerLines = kv.Key, kv.Value - match packageManagerLines |> List.filter (not << isEditorCursorInPackageLines) with + let packageManagerLines = + packageManagerLines |> List.filter (not << isEditorCursorInPackageLines) + + match packageManagerLines with | [] -> () | packageManagerLine :: _ -> let m = packageManagerLine.Range - let packageManagerLines = packageManagerLines yield! processPackageManagerLines m packageManagerLines scriptName packageManagerKey ] diff --git a/vsintegration/src/FSharp.Editor/Common/Extensions.fs b/vsintegration/src/FSharp.Editor/Common/Extensions.fs index 2ed87e5ec82..ff17ac43662 100644 --- a/vsintegration/src/FSharp.Editor/Common/Extensions.fs +++ b/vsintegration/src/FSharp.Editor/Common/Extensions.fs @@ -139,7 +139,7 @@ type Document with | hr, _, _, docData, _ when ErrorHandler.Succeeded(hr) && docData <> IntPtr.Zero -> match Marshal.GetObjectForIUnknown docData with | :? IVsTextBuffer as ivsTextBuffer -> - match textManager.GetActiveView(1, ivsTextBuffer) with + match textManager.GetActiveView(0, ivsTextBuffer) with | hr, vsTextView when ErrorHandler.Succeeded(hr) -> Some vsTextView | _ -> None | _ -> None diff --git a/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs b/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs index edf31e68a57..d61ba717b4d 100644 --- a/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs +++ b/vsintegration/src/FSharp.Editor/LanguageService/FSharpProjectOptionsManager.fs @@ -200,13 +200,16 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = cancellableTask { let! ct = CancellableTask.getCancellationToken () let! fileStamp = document.GetTextVersionAsync(ct) + let textViewAndCaret () : (IVsTextView * Position) option = document.TryGetTextViewAndCaretPos() match singleFileCache.TryGetValue(document.Id) with | false, _ -> let! sourceText = document.GetTextAsync(ct) let getProjectOptionsFromScript textViewAndCaret = - match textViewAndCaret with + let caret = textViewAndCaret () + + match caret with | None -> checker.GetProjectOptionsFromScript( document.FilePath, @@ -226,7 +229,6 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = userOpName = userOpName ) - let textViewAndCaret = document.TryGetTextViewAndCaretPos() let! scriptProjectOptions, _ = getProjectOptionsFromScript textViewAndCaret let project = document.Project @@ -266,7 +268,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = let updateProjectOptions () = async { - let! scriptProjectOptions, _ = getProjectOptionsFromScript None + let! scriptProjectOptions, _ = getProjectOptionsFromScript textViewAndCaret checker.NotifyFileChanged(document.FilePath, scriptProjectOptions) |> Async.Start @@ -281,7 +283,7 @@ type private FSharpProjectOptionsReactor(checker: FSharpChecker) = match value with | projectId, fileStamp, parsingOptions, projectOptions, _ -> let subscription = - match textViewAndCaret with + match textViewAndCaret () with | Some(textView, _) -> subscribeToTextViewEvents (textView, (Some onChangeCaretHandler), (Some onKillFocus), (Some onSetFocus)) | None -> None From b1490e39505624bf5150484c40daa7c085a6bfcb Mon Sep 17 00:00:00 2001 From: Martin <29605222+Martin521@users.noreply.github.com> Date: Thu, 3 Apr 2025 11:41:39 +0200 Subject: [PATCH 14/20] Fix for #18433 (internal error during xml comment processing) (#18436) * fix for 18433 * release note for #18436 --- .../.FSharp.Compiler.Service/9.0.300.md | 1 + src/Compiler/SyntaxTree/XmlDoc.fs | 3 ++- .../Language/XmlComments.fs | 16 ++++++++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md index 86672567838..8893e4d237d 100644 --- a/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md +++ b/docs/release-notes/.FSharp.Compiler.Service/9.0.300.md @@ -21,6 +21,7 @@ * Fix MethodDefNotFound when compiling code invoking delegate with option parameter ([Issue #5171](https://github.com/dotnet/fsharp/issues/5171), [PR #18385](https://github.com/dotnet/fsharp/pull/18385)) * Fix #r nuget ..." downloads unneeded packages ([Issue #18231](https://github.com/dotnet/fsharp/issues/18231), [PR #18393](https://github.com/dotnet/fsharp/pull/18393)) * Reenable β-reduction and subsequent reoptimization of immediately-invoked F#-defined generic delegates. ([PR #18401](https://github.com/dotnet/fsharp/pull/18401)) +* Fixed [#18433](https://github.com/dotnet/fsharp/issues/18433), a rare case of an internal error in xml comment processing. ([PR #18436](https://github.com/dotnet/fsharp/pull/18436)) ### Added * Added missing type constraints in FCS. ([PR #18241](https://github.com/dotnet/fsharp/pull/18241)) diff --git a/src/Compiler/SyntaxTree/XmlDoc.fs b/src/Compiler/SyntaxTree/XmlDoc.fs index a366a69a8a6..d4c4cada576 100644 --- a/src/Compiler/SyntaxTree/XmlDoc.fs +++ b/src/Compiler/SyntaxTree/XmlDoc.fs @@ -139,7 +139,8 @@ type XmlDocCollector() = let xmlDocBlock = struct (savedLines.Count - currentGrabPointCommentsCount, savedLines.Count - 1, false) - savedGrabPoints.Add(pos, xmlDocBlock) + // silently override duplicate grab points (which happen only when preceded by nonsensical line directives) + savedGrabPoints[pos] <- xmlDocBlock currentGrabPointCommentsCount <- 0 delayedGrabPoint <- ValueNone diff --git a/tests/FSharp.Compiler.ComponentTests/Language/XmlComments.fs b/tests/FSharp.Compiler.ComponentTests/Language/XmlComments.fs index eed0e37e4db..47aee9362b7 100644 --- a/tests/FSharp.Compiler.ComponentTests/Language/XmlComments.fs +++ b/tests/FSharp.Compiler.ComponentTests/Language/XmlComments.fs @@ -242,3 +242,19 @@ module M = |> withXmlCommentChecking |> compile |> withDiagnostics [ ] + + // regression test for #18433 + [] + let OverrideXmlCommentsWithSameRange () = + Fs""" + module A + # 1 + /// A is int + type A = {a: int} + # 1 + /// B is int + type B = {b: int} + """ + |> withXmlCommentChecking + |> compile + |> shouldSucceed \ No newline at end of file From 0566db0c1dec6f7142c6f30b89b0698c3ef26c87 Mon Sep 17 00:00:00 2001 From: Bozhidar Batsov Date: Thu, 3 Apr 2025 13:22:38 +0300 Subject: [PATCH 15/20] Fix a small mistake in String.init's docs (#18438) There's no "mapping" parameter. I'm guessing this was a copy/paste mistake. --- src/FSharp.Core/string.fsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/FSharp.Core/string.fsi b/src/FSharp.Core/string.fsi index e7c6ef062ad..9178af3fcf9 100644 --- a/src/FSharp.Core/string.fsi +++ b/src/FSharp.Core/string.fsi @@ -139,7 +139,7 @@ module String = [] val forall: predicate: (char -> bool) -> str: string -> bool - /// Builds a new string whose characters are the results of applying the function mapping + /// Builds a new string whose characters are the results of applying the function initializer /// to each index from 0 to count-1 and concatenating the resulting /// strings. /// From 2598fb1d3d9631fe0e3cbb0cd64625b2b0a3c498 Mon Sep 17 00:00:00 2001 From: Bozhidar Batsov Date: Thu, 3 Apr 2025 13:32:09 +0300 Subject: [PATCH 16/20] Fix a bunch of typos (#18439) --- src/Compiler/Checking/CheckPatterns.fs | 8 +- .../CheckComputationExpressions.fs | 4 +- .../Checking/PatternMatchCompilation.fs | 78 +-- src/Compiler/Checking/PostInferenceChecks.fs | 26 +- src/Compiler/Facilities/CompilerLocation.fs | 2 +- src/Compiler/Symbols/SymbolHelpers.fs | 354 +++++----- src/Compiler/Utilities/range.fsi | 38 +- tests/FSharp.Test.Utilities/Compiler.fs | 19 +- tests/fsharp/core/members/absil.fsi | 650 +++++++++--------- .../HashLight/indent_off_01.fs | 6 +- .../HashLight/indent_off_01.fsi | 4 +- .../HashLight/indent_off_01.fsscript | 6 +- .../HashLight/indent_off_01.fsx | 6 +- .../HashLight/indent_off_after_comment01.fs | 6 +- 14 files changed, 601 insertions(+), 606 deletions(-) diff --git a/src/Compiler/Checking/CheckPatterns.fs b/src/Compiler/Checking/CheckPatterns.fs index 9587c3b5e9f..9665bfd2463 100644 --- a/src/Compiler/Checking/CheckPatterns.fs +++ b/src/Compiler/Checking/CheckPatterns.fs @@ -269,7 +269,7 @@ and TcPat warnOnUpper (cenv: cenv) env valReprInfo vFlags (patEnv: TcPatLinearEn | SynPat.As (pat1, pat2, m) -> TcPatUnnamedAs warnOnUpper cenv env vFlags patEnv ty pat1 pat2 m - + | SynPat.Named (SynIdent(id,_), isMemberThis, vis, m) -> TcPatNamed warnOnUpper cenv env vFlags patEnv id ty isMemberThis vis valReprInfo m @@ -522,7 +522,7 @@ and IsNameOf (cenv: cenv) (env: TcEnv) ad m (id: Ident) = /// Check a long identifier in a pattern and TcPatLongIdent warnOnUpper cenv env ad valReprInfo vFlags (patEnv: TcPatLinearEnv) ty (longDotId, tyargs, args, vis, m) = let (SynLongIdent(longId, _, _)) = longDotId - + if tyargs.IsSome then errorR(Error(FSComp.SR.tcInvalidTypeArgumentUsage(), m)) let warnOnUpperForId = @@ -643,7 +643,7 @@ and TcPatLongIdentUnionCaseOrExnCase warnOnUpper cenv env ad vFlags patEnv ty (m // Here we only care about the cases where the user has written the wildcard pattern explicitly // | Case _ -> ... // let myDiscardedArgFunc(Case _) = ...""" - // This needs to be a waring because it was a valid pattern in version 7.0 and earlier and we don't want to break existing code. + // This needs to be a warning because it was a valid pattern in version 7.0 and earlier and we don't want to break existing code. // The rest of the cases will still be reported as FS0725 warning(Error(FSComp.SR.matchNotAllowedForUnionCaseWithNoData(), m)) | _ -> () @@ -725,7 +725,7 @@ and TcPatLongIdentUnionCaseOrExnCase warnOnUpper cenv env ad vFlags patEnv ty (m if numArgTys > 1 then // Expects tuple without enough args let printTy = NicePrint.minimalStringOfType env.DisplayEnv - let missingArgs = + let missingArgs = argNames.[numArgs..numArgTys - 1] |> List.map (fun id -> (if id.rfield_name_generated then "" else id.DisplayName + ": ") + printTy id.FormalType) |> String.concat (Environment.NewLine + "\t") diff --git a/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs b/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs index fc804ab5e34..10b4a891b32 100644 --- a/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs +++ b/src/Compiler/Checking/Expressions/CheckComputationExpressions.fs @@ -914,7 +914,7 @@ let inline addVarsToVarSpace (varSpace: LazyWithContext /// Try translate the syntax sugar /// /// Computation expression context (carrying caches, environments, ranges, etc) -/// Flag if it's inital check +/// Flag if it's initial check /// a flag indicating if custom operators are allowed. They are not allowed inside try/with, try/finally, if/then/else etc. /// a lazy data structure indicating the variables bound so far in the overall computation /// the computation expression being analyzed @@ -2793,7 +2793,7 @@ and convertSimpleReturnToExpr (ceenv: ComputationExpressionContext<'a>) comp var | Some(thenExpr, None) -> let elseExprOptOpt = match elseCompOpt with - // When we are missing an 'else' part alltogether in case of 'if cond then return exp', we fallback from BindReturn into regular Bind+Return + // When we are missing an 'else' part altogether in case of 'if cond then return exp', we fallback from BindReturn into regular Bind+Return | None -> None | Some elseComp -> match convertSimpleReturnToExpr ceenv comp varSpace elseComp with diff --git a/src/Compiler/Checking/PatternMatchCompilation.fs b/src/Compiler/Checking/PatternMatchCompilation.fs index 00b25756801..3b42f561c1a 100644 --- a/src/Compiler/Checking/PatternMatchCompilation.fs +++ b/src/Compiler/Checking/PatternMatchCompilation.fs @@ -197,11 +197,11 @@ exception CannotRefute [] [] -type CounterExampleType = +type CounterExampleType = /// Maps to EnumMatchIncomplete exn - | EnumCoversKnown + | EnumCoversKnown /// Maps to MatchIncomplete exn - | WithoutEnum + | WithoutEnum with member x.Combine(other) = match other with EnumCoversKnown -> other | _ -> x let RefuteDiscrimSet g m path discrims : Expr * CounterExampleType = @@ -366,7 +366,7 @@ let ShowCounterExample g denv m refuted = | [] -> raise CannotRefute | (r, eck) :: t -> ((r, eck), t) ||> List.fold (fun (rAcc, eckAcc) (r, eck) -> - CombineRefutations g rAcc r, eckAcc.Combine(eck)) + CombineRefutations g rAcc r, eckAcc.Combine(eck)) let text = LayoutRender.showL (NicePrint.dataExprL denv counterExample) let failingWhenClause = refuted |> List.exists (function RefutedWhenClause -> true | _ -> false) Some(text, failingWhenClause, enumCoversKnown) @@ -400,7 +400,7 @@ let rec isMemOfActives p1 actives = | [] -> false | Active(p2, _, _) :: rest -> pathEq p1 p2 || isMemOfActives p1 rest -// Find the information about the active investigation +// Find the information about the active investigation let rec lookupActive x l = match l with | [] -> raise (KeyNotFoundException()) @@ -423,13 +423,13 @@ type Implication = /// Work out what a successful type test (against tgtTy1) implies about a null test for the same input value. /// /// Example: -/// match x with +/// match x with /// | :? string when false -> ... // note: "when false" used so type test succeeds but proceed to next type test /// | null -> ... /// For any inputs where ':? string' succeeds, 'null' will fail /// /// Example: -/// match x with +/// match x with /// | :? (int option) when false -> ... // note: "when false" used so type test succeeds but proceed to next type test /// | null -> ... /// Nothing can be learned. If ':? (int option)' succeeds, 'null' may still have to be run. @@ -442,7 +442,7 @@ let computeWhatSuccessfulTypeTestImpliesAboutNullTest g tgtTy1 = /// Work out what a failing type test (against tgtTy1) implies about a null test for the same input value. /// /// Example: -/// match x with +/// match x with /// | :? (int option) -> ... /// | null -> ... /// If ':? (int option)' fails then 'null' will fail @@ -455,13 +455,13 @@ let computeWhatFailingTypeTestImpliesAboutNullTest g tgtTy1 = /// Work out what one successful null test implies about a type test (against tgtTy2) for the same input value. /// /// Example: -/// match x with +/// match x with /// | null when false -> ... // note: "when false" used so null test succeeds but proceed to next type test /// | :? string -> ... /// For any inputs where 'null' succeeds, ':? string' will fail /// /// Example: -/// match x with +/// match x with /// | null when false -> ... // note: "when false" used so null test succeeds but proceed to next type test /// | :? (int option) -> ... /// For any inputs where 'null' succeeds, ':? (int option)' will succeed @@ -487,12 +487,12 @@ let computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = // supertypes (tgtTy2) always succeed. // // Example: - // match x with + // match x with // | :? string when false -> ... // note: "when false" used so type test succeeds but proceed to next type test // | :? IComparable -> ... // // Example: - // match x with + // match x with // | :? string when false -> ... // note: "when false" used so type test succeeds but proceed to next type test // | :? string -> ... // @@ -503,7 +503,7 @@ let computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = // type tests of the same object against a unrelated target type (tgtTy2) fails. // // Example: - // match x with + // match x with // | :? int when false -> ... // note: "when false" used so type test succeeds but proceed to next type test // | :? string -> ... // @@ -511,7 +511,7 @@ let computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = // // // This only applies if tgtTy2 is not potentially related to the sealed type tgtTy1: - // match x with + // match x with // | :? int when false -> ... // note: "when false" used so type test succeeds but proceed to next type test // | :? IComparable -> ... // @@ -520,7 +520,7 @@ let computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = // // // This rule also doesn't apply to unsealed types: - // match x with + // match x with // | :? SomeUnsealedClass when false -> ... // note: "when false" used so type test succeeds but proceed to next type test // | :? SomeInterface -> ... // because the input may be some subtype of SomeUnsealedClass and that type could implement SomeInterface even if @@ -528,7 +528,7 @@ let computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = // // // This rule also doesn't apply to types with null as true value: - // match x with + // match x with // | :? (int option) when false -> ... // "when false" means type test succeeds but proceed to next type test // | :? (string option) -> ... // @@ -542,7 +542,7 @@ let computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = // a type test of the same input value against an unrelated non-interface type (tgtTy2) always fails // // Example: - // match x with + // match x with // | :? SomeUnsealedClass when false -> ... // "when false" used so type test succeeds but proceed to next type test // | :? SomeUnrelatedClass -> ... // @@ -562,7 +562,7 @@ let computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = // always fails. // // Example: - // match x with + // match x with // | :? IComparable when false -> ... // "when false" used so type test succeeds but proceed to next type test // | :? SomeOtherSealedClass -> ... // @@ -586,12 +586,12 @@ let computeWhatFailingTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 = // testing the same input value against an equivalent or subtype type (tgtTy2) always fails. // // Example: - // match x with + // match x with // | :? IComparable -> ... // | :? string -> ... // // Example: - // match x with + // match x with // | :? string -> ... // | :? string -> ... if TypeDefinitelySubsumesTypeNoCoercion 0 g amap m tgtTy1 tgtTy2 then @@ -696,7 +696,7 @@ let discrimWithinSimultaneousClass g amap m discrim prev = | DecisionTreeTest.IsNull, _ -> // Check that each previous test in the set, if successful, gives some information about this test - prev |> List.forall (fun edge -> + prev |> List.forall (fun edge -> match edge with | DecisionTreeTest.IsNull -> true | DecisionTreeTest.IsInst (_, tgtTy1) -> computeWhatSuccessfulTypeTestImpliesAboutNullTest g tgtTy1 <> Implication.Nothing @@ -704,7 +704,7 @@ let discrimWithinSimultaneousClass g amap m discrim prev = | DecisionTreeTest.IsInst (_, tgtTy2), _ -> // Check that each previous test in the set, if successful, gives some information about this test - prev |> List.forall (fun edge -> + prev |> List.forall (fun edge -> match edge with | DecisionTreeTest.IsNull -> true | DecisionTreeTest.IsInst (_, tgtTy1) -> computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy1 tgtTy2 <> Implication.Nothing @@ -885,8 +885,8 @@ let rec investigationPoints inpPat = match inpPat with | TPat_query((_, _, _, _, _, apinfo), subPat, _) -> Array.prepend (not apinfo.IsTotal) (investigationPoints subPat) - | TPat_isinst(_, _tgtTy, subPatOpt, _) -> - match subPatOpt with + | TPat_isinst(_, _tgtTy, subPatOpt, _) -> + match subPatOpt with | None -> singleFalseInvestigationPoint | Some subPat -> Array.prepend false (investigationPoints subPat) | TPat_as(subPat, _, _) -> investigationPoints subPat @@ -904,7 +904,7 @@ let rec investigationPoints inpPat = |> Seq.collect investigationPoints |> Seq.toArray |> Array.prepend false - | TPat_null _ + | TPat_null _ | TPat_const _ -> singleFalseInvestigationPoint | TPat_wild _ | TPat_error _ -> [||] @@ -930,7 +930,7 @@ let rec erasePartialPatterns inpPat = and erasePartials inps = List.map erasePartialPatterns inps - + let ReportUnusedTargets (clauses: MatchClause list) dtree = match dtree, clauses with | TDSuccess _, [ _ ] -> () @@ -948,7 +948,7 @@ let ReportUnusedTargets (clauses: MatchClause list) dtree = | [ head ] -> head.Id.idRange | _ -> c.Pattern.Range | _, Some guard -> guard.Range - + withStartEnd c.Range.Start m.End m |> RuleNeverMatched |> warning) @@ -994,10 +994,10 @@ let CompilePatternBasic let mutable firstIncompleteMatchClauseWithThrowExpr = None let warningsGenerated = new ResizeArray(2) let getIncompleteMatchClause refuted = - // Emit the incomplete match warning. + // Emit the incomplete match warning. if warnOnIncomplete then match actionOnFailure with - | ThrowIncompleteMatchException + | ThrowIncompleteMatchException | IgnoreWithWarning -> let ignoreWithWarning = (actionOnFailure = IgnoreWithWarning) let counterExample = ShowCounterExample g denv mMatch refuted @@ -1070,7 +1070,7 @@ let CompilePatternBasic | ThrowIncompleteMatchException -> mkThrow mMatch resultTy - (mkExnExpr(g.MatchFailureException_tcr, + (mkExnExpr(g.MatchFailureException_tcr, [ mkString g mMatch mMatch.FileName mkInt g mMatch mMatch.StartLine mkInt g mMatch mMatch.StartColumn], mMatch)) @@ -1259,7 +1259,7 @@ let CompilePatternBasic | ActivePatternReturnKind.Boolean -> false let vOpt, addrExp, _readonly, _writeonly = mkExprAddrOfExprAux g mustTakeAddress false NeverMutates appExpr None mMatch match vOpt with - | None -> + | None -> let v, vExpr = mkCompGenLocal m ("activePatternResult" + string (newUnique())) resTy if origInputVal.IsMemberOrModuleBinding then AdjustValToHaveValReprInfo v origInputVal.TryDeclaringEntity ValReprInfo.emptyValData @@ -1316,7 +1316,7 @@ let CompilePatternBasic if not total && aparity > 1 then error(Error(FSComp.SR.patcPartialActivePatternsGenerateOneResult(), m)) - if not total then + if not total then match retKind with | ActivePatternReturnKind.Boolean -> DecisionTreeTest.Const(Const.Bool true) | ActivePatternReturnKind.RefTypeWrapper -> DecisionTreeTest.UnionCase(mkAnySomeCase g false, resTys) @@ -1497,7 +1497,7 @@ let CompilePatternBasic match discrim with | DecisionTreeTest.IsInst (_srcTy, tgtTy2) -> match computeWhatSuccessfulTypeTestImpliesAboutTypeTest g amap m tgtTy2 tgtTy1 with - | Implication.Succeeds -> + | Implication.Succeeds -> match pbindOpt with | Some pbind -> let subAccess tpinst exprIn = @@ -1534,7 +1534,7 @@ let CompilePatternBasic match discrim with | DecisionTreeTest.IsNull -> [Frontier (i, newActives, valMap)] - | DecisionTreeTest.IsInst (_, tgtTy) -> + | DecisionTreeTest.IsInst (_, tgtTy) -> match computeWhatSuccessfulTypeTestImpliesAboutNullTest g tgtTy with | Implication.Succeeds -> [Frontier (i, newActives, valMap)] | Implication.Fails -> [] @@ -1637,7 +1637,7 @@ let CompilePatternBasic // - Partial active patterns // - Disjunctive patterns // - Pattern clauses with 'when' -// - isinst patterns +// - isinst patterns // // Partial active patterns that are not the "last" thing in a clause, // combined with subsequent clauses, can cause significant code expansion @@ -1666,13 +1666,13 @@ let CompilePatternBasic // a partial pattern. This can lead to sub-standard code generation // but has long been the technique we use to avoid blow-up of pattern matching. // -// Disjunctive patterns combined with 'when' clauses can also cause signficant code +// Disjunctive patterns combined with 'when' clauses can also cause significant code // expansion. In particular this leads to multiple copies of 'when' expressions (even for one clause) // and each failure path of those 'when' will then continue on the expand any remaining // pattern logic in subsequent clauses. So when generating code we take clauses up // until the first one containing a disjunctive pattern with a 'when' clause. // -// Disjunction will still cause significant expansion, e.g. +// Disjunction will still cause significant expansion, e.g. // (A | B), (C | D) -> // is immediately expanded out to four frontiers each with two investigation points. // A, C -> ... @@ -1682,7 +1682,7 @@ let CompilePatternBasic // // Of course, some decision-logic expansion here is expected. Further, for unions, integers, characters, enums etc. // the column-based matching on A/B and C/D eliminates these relatively efficiently, e.g. to -// one-switch-on-A/B +// one-switch-on-A/B // on each path, one switch on C/D // So disjunction alone isn't considered problematic, but in combination with 'when' patterns @@ -1702,7 +1702,7 @@ let rec CompilePattern g denv amap tcVal infoReader mExpr mMatch warnOnUnused a // First make sure we generate at least some of the obvious incomplete match warnings. let warnOnUnused = false // we can't turn this on since we're pretending all partials fail in order to control the complexity of this. let warnOnIncomplete = true - let clausesPretendAllPartialFail = clausesL |> List.collect (fun (MatchClause(p, whenOpt, tg, m)) -> [MatchClause(erasePartialPatterns p, whenOpt, tg, m)]) + let clausesPretendAllPartialFail = clausesL |> List.collect (fun (MatchClause(p, whenOpt, tg, m)) -> [MatchClause(erasePartialPatterns p, whenOpt, tg, m)]) let _ = CompilePatternBasic g denv amap tcVal infoReader mExpr mMatch warnOnUnused warnOnIncomplete actionOnFailure (origInputVal, origInputValTypars, origInputExprOpt) clausesPretendAllPartialFail inputTy resultTy let warnOnIncomplete = false diff --git a/src/Compiler/Checking/PostInferenceChecks.fs b/src/Compiler/Checking/PostInferenceChecks.fs index 4df0185a2e5..d22f50cdc2f 100644 --- a/src/Compiler/Checking/PostInferenceChecks.fs +++ b/src/Compiler/Checking/PostInferenceChecks.fs @@ -335,9 +335,9 @@ let RecordAnonRecdInfo cenv (anonInfo: AnonRecdTypeInfo) = // approx walk of type //-------------------------------------------------------------------------- -/// Represents the container for nester type instantions, carrying information about the parent (generic type) and data about correspinding generic typar definition. +/// Represents the container for nester type instantions, carrying information about the parent (generic type) and data about corresponding generic typar definition. /// For current use, IlGenericParameterDef was enough. For other future use cases, conversion into F# Typar might be needed. -type TypeInstCtx = +type TypeInstCtx = | NoInfo | IlGenericInst of parent:TyconRef * genericArg:ILGenericParameterDef | TyparInst of parent:TyconRef @@ -649,7 +649,7 @@ let CheckTypeAux permitByRefLike (cenv: cenv) env m ty onInnerByrefError = errorR (Error(FSComp.SR.checkNotSufficientlyGenericBecauseOfScope(tp.DisplayName), m)) let visitTyconRef (ctx:TypeInstCtx) tcref = - let checkInner() = + let checkInner() = match ctx with | TopLevelAllowingByRef -> false | TyparInst(parentTcRef) @@ -694,11 +694,11 @@ let CheckTypeAux permitByRefLike (cenv: cenv) env m ty onInnerByrefError = cenv.potentialUnboundUsesOfVals <- cenv.potentialUnboundUsesOfVals.Add(vref.Stamp, m) | _ -> () - let initialCtx = + let initialCtx = match permitByRefLike with | PermitByRefType.SpanLike | PermitByRefType.NoInnerByRefLike -> TopLevelAllowingByRef - | _ -> NoInfo + | _ -> NoInfo CheckTypeDeep cenv (ignore, Some visitTyconRef, Some visitAppTy, Some visitTraitSolution, Some visitTyar) cenv.g env initialCtx ty @@ -1958,7 +1958,7 @@ and CheckAttribArgExpr cenv env expr = | Const.Single _ | Const.Char _ | Const.Zero - | Const.String _ + | Const.String _ | Const.Decimal _ -> () | _ -> if cenv.reportErrors then @@ -2231,7 +2231,7 @@ let CheckModuleBinding cenv env (TBind(v, e, _) as bind) = // Default augmentation contains the nasty 'Is' etc. let prefix = "Is" if not v.IsImplied && nm.StartsWithOrdinal prefix && hasDefaultAugmentation then - match tcref.GetUnionCaseByName(nm[prefix.Length ..]) with + match tcref.GetUnionCaseByName(nm[prefix.Length ..]) with | Some uc -> error(NameClash(nm, kind, v.DisplayName, v.Range, FSComp.SR.chkUnionCaseDefaultAugmentation(), uc.DisplayName, uc.Range)) | None -> () @@ -2398,10 +2398,10 @@ let CheckEntityDefn cenv env (tycon: Entity) = errorR(Error(FSComp.SR.chkCurriedMethodsCantHaveOutParams(), m)) if numCurriedArgSets = 1 then - let errorIfNotStringTy m ty callerInfo = + let errorIfNotStringTy m ty callerInfo = if not (typeEquiv g g.string_ty ty) then errorR(Error(FSComp.SR.tcCallerInfoWrongType(callerInfo |> string, "string", NicePrint.minimalStringOfType cenv.denv ty), m)) - + let errorIfNotStringOptionTy m ty callerInfo = if not ((isOptionTy g ty) && (typeEquiv g g.string_ty (destOptionTy g ty))) then errorR(Error(FSComp.SR.tcCallerInfoWrongType(callerInfo |> string, "string", NicePrint.minimalStringOfType cenv.denv (destOptionTy g ty)), m)) @@ -2523,7 +2523,7 @@ let CheckEntityDefn cenv env (tycon: Entity) = if TyconRefHasAttribute g m g.attrib_IsReadOnlyAttribute tcref && not tycon.IsStructOrEnumTycon then errorR(Error(FSComp.SR.tcIsReadOnlyNotStruct(), tycon.Range)) - // Considers TFSharpTyconRepr and TFSharpUnionRepr. + // Considers TFSharpTyconRepr and TFSharpUnionRepr. // [Review] are all cases covered: TILObjectRepr, TAsmRepr. [Yes - these are FSharp.Core.dll only] tycon.AllFieldsArray |> Array.iter (CheckRecdField false cenv env tycon) @@ -2559,10 +2559,10 @@ let CheckEntityDefn cenv env (tycon: Entity) = // We do not have to check access of interface implementations. - if tycon.IsFSharpDelegateTycon then - match tycon.TypeReprInfo with + if tycon.IsFSharpDelegateTycon then + match tycon.TypeReprInfo with | TFSharpTyconRepr r -> - match r.fsobjmodel_kind with + match r.fsobjmodel_kind with | TFSharpDelegate ss -> //ss.ClassTypars //ss.MethodTypars diff --git a/src/Compiler/Facilities/CompilerLocation.fs b/src/Compiler/Facilities/CompilerLocation.fs index 7d902aefc27..abd436647ae 100644 --- a/src/Compiler/Facilities/CompilerLocation.fs +++ b/src/Compiler/Facilities/CompilerLocation.fs @@ -304,7 +304,7 @@ module internal FSharpEnvironment = // How to find dotnet.exe --- woe is me; probing rules make me sad. // Algorithm: // 1. Look for DOTNET_HOST_PATH environment variable - // this is the main user programable override .. provided by user to find a specific dotnet.exe + // this is the main user programmable override .. provided by user to find a specific dotnet.exe // 2. Probe for are we part of an .NetSDK install // In an sdk install we are always installed in: sdk\3.0.100-rc2-014234\FSharp // dotnet or dotnet.exe will be found in the directory that contains the sdk directory diff --git a/src/Compiler/Symbols/SymbolHelpers.fs b/src/Compiler/Symbols/SymbolHelpers.fs index 116e9ba95b7..c516f0c377b 100644 --- a/src/Compiler/Symbols/SymbolHelpers.fs +++ b/src/Compiler/Symbols/SymbolHelpers.fs @@ -5,15 +5,15 @@ namespace FSharp.Compiler.Symbols open System open System.IO -open Internal.Utilities.Library +open Internal.Utilities.Library open Internal.Utilities.Library.Extras open FSharp.Core.Printf -open FSharp.Compiler -open FSharp.Compiler.AbstractIL.Diagnostics +open FSharp.Compiler +open FSharp.Compiler.AbstractIL.Diagnostics open FSharp.Compiler.DiagnosticsLogger open FSharp.Compiler.InfoReader open FSharp.Compiler.Infos -open FSharp.Compiler.IO +open FSharp.Compiler.IO open FSharp.Compiler.NameResolution open FSharp.Compiler.Syntax.PrettyNaming open FSharp.Compiler.Text @@ -25,7 +25,7 @@ open FSharp.Compiler.TypedTree open FSharp.Compiler.TypedTreeBasics open FSharp.Compiler.TypedTreeOps open FSharp.Compiler.TypeHierarchy -open FSharp.Compiler.TcGlobals +open FSharp.Compiler.TcGlobals /// Describe a comment as either a block of text or a file+signature reference into an intellidoc file. [] @@ -38,46 +38,46 @@ module EnvMisc2 = let maxMembers = GetEnvInteger "FCS_MaxMembersInQuickInfo" 10 [] -module internal SymbolHelpers = +module internal SymbolHelpers = let rangeOfValRef preferFlag (vref: ValRef) = - match preferFlag with - | None -> vref.Range - | Some false -> vref.DefinitionRange + match preferFlag with + | None -> vref.Range + | Some false -> vref.DefinitionRange | Some true -> vref.SigRange let rangeOfEntityRef preferFlag (eref: EntityRef) = - match preferFlag with - | None -> eref.Range - | Some false -> eref.DefinitionRange + match preferFlag with + | None -> eref.Range + | Some false -> eref.DefinitionRange | Some true -> eref.SigRange - + let rangeOfPropInfo preferFlag (pinfo: PropInfo) = match pinfo with -#if !NO_TYPEPROVIDERS +#if !NO_TYPEPROVIDERS | ProvidedProp(_, pi, _) -> Construct.ComputeDefinitionLocationOfProvidedItem pi #endif | _ -> pinfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) - let rangeOfMethInfo (g: TcGlobals) preferFlag (minfo: MethInfo) = + let rangeOfMethInfo (g: TcGlobals) preferFlag (minfo: MethInfo) = match minfo with -#if !NO_TYPEPROVIDERS +#if !NO_TYPEPROVIDERS | ProvidedMeth(_, mi, _, _) -> Construct.ComputeDefinitionLocationOfProvidedItem mi #endif | DefaultStructCtor(_, AppTy g (tcref, _)) -> Some(rangeOfEntityRef preferFlag tcref) | _ -> minfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) - let rangeOfEventInfo preferFlag (einfo: EventInfo) = + let rangeOfEventInfo preferFlag (einfo: EventInfo) = match einfo with -#if !NO_TYPEPROVIDERS +#if !NO_TYPEPROVIDERS | ProvidedEvent (_, ei, _) -> Construct.ComputeDefinitionLocationOfProvidedItem ei #endif | _ -> einfo.ArbitraryValRef |> Option.map (rangeOfValRef preferFlag) - - let rangeOfUnionCaseInfo preferFlag (ucinfo: UnionCaseInfo) = - match preferFlag with - | None -> ucinfo.UnionCase.Range - | Some false -> ucinfo.UnionCase.DefinitionRange + + let rangeOfUnionCaseInfo preferFlag (ucinfo: UnionCaseInfo) = + match preferFlag with + | None -> ucinfo.UnionCase.Range + | Some false -> ucinfo.UnionCase.DefinitionRange | Some true -> ucinfo.UnionCase.SigRange let rangeOfRecdField preferFlag (rField: RecdField) = @@ -89,7 +89,7 @@ module internal SymbolHelpers = let rangeOfRecdFieldInfo preferFlag (rfinfo: RecdFieldInfo) = rangeOfRecdField preferFlag rfinfo.RecdField - let rec rangeOfItem (g: TcGlobals) preferFlag d = + let rec rangeOfItem (g: TcGlobals) preferFlag d = match d with | Item.Value vref | Item.CustomBuilder (_, vref) -> Some (rangeOfValRef preferFlag vref) | Item.UnionCase(ucinfo, _) -> Some (rangeOfUnionCaseInfo preferFlag ucinfo) @@ -103,13 +103,13 @@ module internal SymbolHelpers = | Item.Property(info = pinfos; sourceIdentifierRange = mNameOpt) -> match mNameOpt with | Some m -> Some m - | None -> rangeOfPropInfo preferFlag pinfos.Head + | None -> rangeOfPropInfo preferFlag pinfos.Head | Item.Types(_, tys) -> tys |> List.tryPick (tryNiceEntityRefOfTyOption >> Option.map (rangeOfEntityRef preferFlag)) | Item.CustomOperation (_, _, Some minfo) -> rangeOfMethInfo g preferFlag minfo | Item.Trait _ -> None | Item.TypeVar (_, tp) -> Some tp.Range | Item.ModuleOrNamespaces modrefs -> modrefs |> List.tryPick (rangeOfEntityRef preferFlag >> Some) - | Item.MethodGroup(_, minfos, _) + | Item.MethodGroup(_, minfos, _) | Item.CtorGroup(_, minfos) -> minfos |> List.tryPick (rangeOfMethInfo g preferFlag) | Item.ActivePatternResult(APInfo _, _, _, m) -> Some m | Item.SetterArg (_, item) -> rangeOfItem g preferFlag item @@ -122,27 +122,27 @@ module internal SymbolHelpers = | Item.NewDef _ -> None // Provided type definitions do not have a useful F# CCU for the purposes of goto-definition. - let computeCcuOfTyconRef (tcref: TyconRef) = + let computeCcuOfTyconRef (tcref: TyconRef) = #if !NO_TYPEPROVIDERS - if tcref.IsProvided then None else + if tcref.IsProvided then None else #endif ccuOfTyconRef tcref - let ccuOfMethInfo (g: TcGlobals) (minfo: MethInfo) = + let ccuOfMethInfo (g: TcGlobals) (minfo: MethInfo) = match minfo with | DefaultStructCtor(_, AppTy g (tcref, _)) -> computeCcuOfTyconRef tcref - | _ -> - minfo.ArbitraryValRef - |> Option.bind ccuOfValRef + | _ -> + minfo.ArbitraryValRef + |> Option.bind ccuOfValRef |> Option.orElseWith (fun () -> minfo.DeclaringTyconRef |> computeCcuOfTyconRef) - let rec ccuOfItem (g: TcGlobals) d = + let rec ccuOfItem (g: TcGlobals) d = match d with | Item.Value vref | Item.CustomBuilder (_, vref) -> - ccuOfValRef vref + ccuOfValRef vref | Item.UnionCase(ucinfo, _) -> computeCcuOfTyconRef ucinfo.TyconRef @@ -165,9 +165,9 @@ module internal SymbolHelpers = | Item.ILField finfo -> finfo.DeclaringTyconRef |> computeCcuOfTyconRef - | Item.Property(info = pinfos) -> - pinfos |> List.tryPick (fun pinfo -> - pinfo.ArbitraryValRef + | Item.Property(info = pinfos) -> + pinfos |> List.tryPick (fun pinfo -> + pinfo.ArbitraryValRef |> Option.bind ccuOfValRef |> Option.orElseWith (fun () -> pinfo.DeclaringTyconRef |> computeCcuOfTyconRef)) @@ -192,9 +192,9 @@ module internal SymbolHelpers = | Item.DelegateCtor(ty) -> ty |> tryNiceEntityRefOfTyOption |> Option.bind computeCcuOfTyconRef - | Item.ModuleOrNamespaces erefs + | Item.ModuleOrNamespaces erefs | Item.UnqualifiedType erefs -> - erefs |> List.tryPick computeCcuOfTyconRef + erefs |> List.tryPick computeCcuOfTyconRef | Item.SetterArg (_, item) -> ccuOfItem g item @@ -219,22 +219,22 @@ module internal SymbolHelpers = /// Work out the source file for an item and fix it up relative to the CCU if it is relative. let fileNameOfItem (g: TcGlobals) qualProjectDir (m: range) h = - let file = m.FileName + let file = m.FileName if verbose then dprintf "file stored in metadata is '%s'\n" file - if not (FileSystem.IsPathRootedShim file) then - match ccuOfItem g h with - | Some ccu -> + if not (FileSystem.IsPathRootedShim file) then + match ccuOfItem g h with + | Some ccu -> Path.Combine(ccu.SourceCodeDirectory, file) - | None -> - match qualProjectDir with + | None -> + match qualProjectDir with | None -> file | Some dir -> Path.Combine(dir, file) else file - let ParamNameAndTypesOfUnaryCustomOperation g minfo = - match minfo with - | FSMeth(_, _, vref, _) -> - let argInfos = ArgInfosOfMember g vref |> List.concat + let ParamNameAndTypesOfUnaryCustomOperation g minfo = + match minfo with + | FSMeth(_, _, vref, _) -> + let argInfos = ArgInfosOfMember g vref |> List.concat // Drop the first 'seq' argument representing the computation space let argInfos = if argInfos.IsEmpty then [] else argInfos.Tail [ for ty, argInfo in argInfos do @@ -258,12 +258,12 @@ module internal SymbolHelpers = |> Option.map FSharpXmlDoc.FromXmlText |> Option.defaultValue xmlDoc - /// This function gets the signature to pass to Visual Studio to use its lookup functions for .NET stuff. + /// This function gets the signature to pass to Visual Studio to use its lookup functions for .NET stuff. let rec GetXmlDocHelpSigOfItemForLookup (infoReader: InfoReader) m d = let g = infoReader.g match d with - | Item.ActivePatternCase (APElemRef(_, vref, _, _)) - | Item.Value vref | Item.CustomBuilder (_, vref) -> + | Item.ActivePatternCase (APElemRef(_, vref, _, _)) + | Item.Value vref | Item.CustomBuilder (_, vref) -> mkXmlComment (GetXmlDocSigOfValRef g vref) | Item.UnionCase (ucinfo, _) -> @@ -311,7 +311,7 @@ module internal SymbolHelpers = mkXmlComment (GetXmlDocSigOfMethInfo infoReader m minfo) | Item.OtherName(container = Some argContainer) -> - match argContainer with + match argContainer with | ArgumentContainer.Method minfo -> mkXmlComment (GetXmlDocSigOfMethInfo infoReader m minfo) | ArgumentContainer.Type tcref -> mkXmlComment (GetXmlDocSigOfEntityRef infoReader m tcref) @@ -321,7 +321,7 @@ module internal SymbolHelpers = | Item.SetterArg (_, item) -> GetXmlDocHelpSigOfItemForLookup infoReader m item - // These do not have entires in XML doc files + // These do not have entries in XML doc files | Item.CustomOperation _ | Item.OtherName _ | Item.ActivePatternResult _ @@ -340,38 +340,38 @@ module internal SymbolHelpers = |> GetXmlDocFromLoader infoReader /// Produce an XmlComment with a signature or raw text, given the F# comment and the item - let GetXmlCommentForItemAux (xmlDoc: XmlDoc option) (infoReader: InfoReader) m d = - match xmlDoc with - | Some xmlDoc when not xmlDoc.IsEmpty -> + let GetXmlCommentForItemAux (xmlDoc: XmlDoc option) (infoReader: InfoReader) m d = + match xmlDoc with + | Some xmlDoc when not xmlDoc.IsEmpty -> FSharpXmlDoc.FromXmlText xmlDoc | _ -> GetXmlDocHelpSigOfItemForLookup infoReader m d - let GetXmlCommentForMethInfoItem infoReader m d (minfo: MethInfo) = + let GetXmlCommentForMethInfoItem infoReader m d (minfo: MethInfo) = if minfo.HasDirectXmlComment || minfo.XmlDoc.NonEmpty then - GetXmlCommentForItemAux (Some minfo.XmlDoc) infoReader m d + GetXmlCommentForItemAux (Some minfo.XmlDoc) infoReader m d else mkXmlComment (GetXmlDocSigOfMethInfo infoReader m minfo) - let FormatTyparMapping denv (prettyTyparInst: TyparInstantiation) = - [ for tp, ty in prettyTyparInst -> + let FormatTyparMapping denv (prettyTyparInst: TyparInstantiation) = + [ for tp, ty in prettyTyparInst -> wordL (tagTypeParameter ("'" + tp.DisplayName)) ^^ wordL (tagText (FSComp.SR.descriptionWordIs())) ^^ NicePrint.layoutType denv ty ] [] - let (|ItemWhereTypIsPreferred|_|) item = - match item with + let (|ItemWhereTypIsPreferred|_|) item = + match item with | Item.DelegateCtor ty | Item.CtorGroup(_, [DefaultStructCtor(_, ty)]) | Item.Types(_, [ty]) -> ValueSome ty | _ -> ValueNone - /// Specifies functions for comparing 'Item' objects with respect to the user - /// (this means that some values that are not technically equal are treated as equal + /// Specifies functions for comparing 'Item' objects with respect to the user + /// (this means that some values that are not technically equal are treated as equal /// if this is what we want to show to the user, because we're comparing just the name // for some cases e.g. when using 'fullDisplayTextOfModRef') - let ItemDisplayPartialEquality g = - { new IPartialEqualityComparer<_> with - member x.InEqualityRelation item = - match item with + let ItemDisplayPartialEquality g = + { new IPartialEqualityComparer<_> with + member x.InEqualityRelation item = + match item with | Item.Trait _ -> true | Item.Types(_, _ :: _) -> true | Item.ILField(_) -> true @@ -385,7 +385,7 @@ module internal SymbolHelpers = | Item.ActivePatternCase _ -> true | Item.DelegateCtor _ -> true | Item.UnionCase _ -> true - | Item.ExnCase _ -> true + | Item.ExnCase _ -> true | Item.Event _ -> true | Item.Property _ -> true | Item.CtorGroup _ -> true @@ -404,15 +404,15 @@ module internal SymbolHelpers = | Item.ModuleOrNamespaces [] -> false //| _ -> false - - member x.Equals(item1, item2) = + + member x.Equals(item1, item2) = match item1,item2 with | null,null -> true | null,_ | _,null -> false | item1,item2 -> // This may explore assemblies that are not in the reference set. // In this case just bail out and assume items are not equal - protectAssemblyExploration false (fun () -> + protectAssemblyExploration false (fun () -> let equalHeadTypes(ty1, ty2) = match tryTcrefOfAppTy g ty1 with | ValueSome tcref1 -> @@ -421,41 +421,41 @@ module internal SymbolHelpers = | _ -> typeEquiv g ty1 ty2 | _ -> typeEquiv g ty1 ty2 - ItemsAreEffectivelyEqual g item1 item2 || + ItemsAreEffectivelyEqual g item1 item2 || // Much of this logic is already covered by 'ItemsAreEffectivelyEqual' - match item1, item2 with + match item1, item2 with | Item.DelegateCtor ty1, Item.DelegateCtor ty2 -> equalHeadTypes(ty1, ty2) | Item.Types(dn1, ty1 :: _), Item.Types(dn2, ty2 :: _) -> // Bug 4403: We need to compare names as well, because 'int' and 'Int32' are physically the same type, but we want to show both - dn1 = dn2 && equalHeadTypes(ty1, ty2) - - // Prefer a type to a DefaultStructCtor, a DelegateCtor and a FakeInterfaceCtor - | ItemWhereTypIsPreferred ty1, ItemWhereTypIsPreferred ty2 -> equalHeadTypes(ty1, ty2) + dn1 = dn2 && equalHeadTypes(ty1, ty2) + + // Prefer a type to a DefaultStructCtor, a DelegateCtor and a FakeInterfaceCtor + | ItemWhereTypIsPreferred ty1, ItemWhereTypIsPreferred ty2 -> equalHeadTypes(ty1, ty2) | Item.ExnCase tcref1, Item.ExnCase tcref2 -> tyconRefEq g tcref1 tcref2 | Item.ILField(fld1), Item.ILField(fld2) -> ILFieldInfo.ILFieldInfosUseIdenticalDefinitions fld1 fld2 - | Item.CustomOperation (_, _, Some minfo1), Item.CustomOperation (_, _, Some minfo2) -> + | Item.CustomOperation (_, _, Some minfo1), Item.CustomOperation (_, _, Some minfo2) -> MethInfo.MethInfosUseIdenticalDefinitions minfo1 minfo2 - | Item.TypeVar (nm1, tp1), Item.TypeVar (nm2, tp2) -> + | Item.TypeVar (nm1, tp1), Item.TypeVar (nm2, tp2) -> (nm1 = nm2) && typarRefEq tp1 tp2 | Item.ModuleOrNamespaces(modref1 :: _), Item.ModuleOrNamespaces(modref2 :: _) -> fullDisplayTextOfModRef modref1 = fullDisplayTextOfModRef modref2 | Item.SetterArg(id1, _), Item.SetterArg(id2, _) -> Range.equals id1.idRange id2.idRange && id1.idText = id2.idText - | Item.MethodGroup(_, meths1, _), Item.MethodGroup(_, meths2, _) -> + | Item.MethodGroup(_, meths1, _), Item.MethodGroup(_, meths2, _) -> Seq.zip meths1 meths2 |> Seq.forall (fun (minfo1, minfo2) -> MethInfo.MethInfosUseIdenticalDefinitions minfo1 minfo2) - | (Item.Value vref1 | Item.CustomBuilder (_, vref1)), (Item.Value vref2 | Item.CustomBuilder (_, vref2)) -> + | (Item.Value vref1 | Item.CustomBuilder (_, vref1)), (Item.Value vref2 | Item.CustomBuilder (_, vref2)) -> valRefEq g vref1 vref2 | Item.ActivePatternCase(APElemRef(_apinfo1, vref1, idx1, _)), Item.ActivePatternCase(APElemRef(_apinfo2, vref2, idx2, _)) -> idx1 = idx2 && valRefEq g vref1 vref2 - | Item.UnionCase(UnionCaseInfo(_, ur1), _), Item.UnionCase(UnionCaseInfo(_, ur2), _) -> + | Item.UnionCase(UnionCaseInfo(_, ur1), _), Item.UnionCase(UnionCaseInfo(_, ur2), _) -> g.unionCaseRefEq ur1 ur2 - | Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref1, n1))), Item.RecdField(RecdFieldInfo(_, RecdFieldRef(tcref2, n2))) -> + | 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) -> + | Item.Property(info = pi1s), Item.Property(info = pi2s) -> (pi1s, pi2s) ||> List.forall2 PropInfo.PropInfosUseIdenticalDefinitions - | Item.Event evt1, Item.Event evt2 -> + | Item.Event evt1, Item.Event evt2 -> EventInfo.EventInfosUseIdenticalDefinitions evt1 evt2 | Item.AnonRecdField(anon1, _, i1, _), Item.AnonRecdField(anon2, _, i2, _) -> anonInfoEquiv anon1 anon2 && i1 = i2 @@ -470,13 +470,13 @@ module internal SymbolHelpers = | Item.Types(_, [AbbrevOrAppTy(tcref1, _)]), Item.UnqualifiedType([tcref2]) -> tyconRefEq g tcref1 tcref2 | Item.UnqualifiedType([tcref1]), Item.Types(_, [AbbrevOrAppTy(tcref2, _)]) -> tyconRefEq g tcref1 tcref2 | _ -> false) - + member x.GetHashCode item = // This may explore assemblies that are not in the reference set. // In this case just bail out and use a random hash code - protectAssemblyExploration 1027 (fun () -> - match item with - | ItemWhereTypIsPreferred ty -> + protectAssemblyExploration 1027 (fun () -> + match item with + | ItemWhereTypIsPreferred ty -> match tryTcrefOfAppTy g ty with | ValueSome tcref -> hash tcref.LogicalName | _ -> 1010 @@ -485,7 +485,7 @@ module internal SymbolHelpers = | Item.TypeVar (nm, _tp) -> hash nm | Item.CustomOperation (_, _, Some minfo) -> minfo.ComputeHashCode() | Item.CustomOperation (_, _, None) -> 1 - | Item.ModuleOrNamespaces(modref :: _) -> hash (fullDisplayTextOfModRef modref) + | Item.ModuleOrNamespaces(modref :: _) -> hash (fullDisplayTextOfModRef modref) | Item.SetterArg(id, _) -> hash (id.idRange, id.idText) | Item.MethodGroup(_, meths, _) -> meths |> List.fold (fun st a -> st + a.ComputeHashCode()) 0 | Item.CtorGroup(name, meths) -> name.GetHashCode() + (meths |> List.fold (fun st a -> st + a.ComputeHashCode()) 0) @@ -512,30 +512,30 @@ module internal SymbolHelpers = | Item.DelegateCtor _ | Item.ModuleOrNamespaces [] -> 0 ) } - + /// Remove all duplicate items - let RemoveDuplicateItems g (items: ItemWithInst list) = + let RemoveDuplicateItems g (items: ItemWithInst list) = if isNil items then items else items |> IPartialEqualityComparer.partialDistinctBy (IPartialEqualityComparer.On (fun item -> item.Item) (ItemDisplayPartialEquality g)) - let IsExplicitlySuppressed (g: TcGlobals) (item: Item) = + let IsExplicitlySuppressed (g: TcGlobals) (item: Item) = // This may explore assemblies that are not in the reference set. // In this case just assume the item is not suppressed. - protectAssemblyExploration true (fun () -> - match item with - | Item.Types(it, [ty]) -> + protectAssemblyExploration true (fun () -> + match item with + | Item.Types(it, [ty]) -> match tryTcrefOfAppTy g ty with | ValueSome tcr1 -> - g.suppressed_types + g.suppressed_types |> List.exists (fun supp -> let generalizedSupp = generalizedTyconRef g supp // check the display name is precisely the one we're suppressing match tryTcrefOfAppTy g generalizedSupp with | ValueSome tcr2 -> it = supp.DisplayName && - // check if they are the same logical type (after removing all abbreviations) + // check if they are the same logical type (after removing all abbreviations) tyconRefEq g tcr1 tcr2 - | _ -> false) + | _ -> false) | _ -> false | _ -> false) @@ -543,7 +543,7 @@ module internal SymbolHelpers = let RemoveExplicitlySuppressed (g: TcGlobals) (items: ItemWithInst list) = items |> List.filter (fun item -> not (IsExplicitlySuppressed g item.Item)) - let SimplerDisplayEnv denv = + let SimplerDisplayEnv denv = { denv with shortConstraints=true showStaticallyResolvedTyparAnnotations=false showNullnessAnnotations = Some true @@ -551,7 +551,7 @@ module internal SymbolHelpers = suppressNestedTypes=true maxMembers=Some EnvMisc2.maxMembers } - let rec FullNameOfItem g item = + let rec FullNameOfItem g item = let denv = DisplayEnv.Empty g match item with | Item.ImplicitOp(_, { contents = Some(TraitConstraintSln.FSMethSln(vref=vref)) }) @@ -559,7 +559,7 @@ module internal SymbolHelpers = | Item.UnionCase (ucinfo, _) -> fullDisplayTextOfUnionCaseRef ucinfo.UnionCaseRef | Item.ActivePatternResult(apinfo, _ty, idx, _) -> apinfo.DisplayNameByIdx idx | Item.ActivePatternCase apref -> FullNameOfItem g (Item.Value apref.ActivePatternVal) + "." + apref.DisplayName - | Item.ExnCase ecref -> fullDisplayTextOfExnRef ecref + | Item.ExnCase ecref -> fullDisplayTextOfExnRef ecref | Item.AnonRecdField(anon, _argTys, i, _) -> anon.DisplayNameByIdx i | Item.RecdField rfinfo -> fullDisplayTextOfRecdFieldRef rfinfo.RecdFieldRef | Item.NewDef id -> id.idText @@ -568,11 +568,11 @@ module internal SymbolHelpers = | Item.Property(info = pinfo :: _) -> buildString (fun os -> NicePrint.outputTyconRef denv os pinfo.DeclaringTyconRef; bprintf os ".%s" pinfo.PropertyName) | Item.CustomOperation (customOpName, _, _) -> customOpName | Item.CtorGroup(_, minfo :: _) -> buildString (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef) - | Item.MethodGroup(_, _, Some minfo) -> buildString (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef; bprintf os ".%s" minfo.DisplayName) - | Item.MethodGroup(_, minfo :: _, _) -> buildString (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef; bprintf os ".%s" minfo.DisplayName) + | Item.MethodGroup(_, _, Some minfo) -> buildString (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef; bprintf os ".%s" minfo.DisplayName) + | Item.MethodGroup(_, minfo :: _, _) -> buildString (fun os -> NicePrint.outputTyconRef denv os minfo.DeclaringTyconRef; bprintf os ".%s" minfo.DisplayName) | Item.UnqualifiedType (tcref :: _) -> buildString (fun os -> NicePrint.outputTyconRef denv os tcref) - | Item.DelegateCtor ty - | Item.Types(_, ty :: _) -> + | Item.DelegateCtor ty + | Item.Types(_, ty :: _) -> match tryTcrefOfAppTy g ty with | ValueSome tcref -> buildString (fun os -> NicePrint.outputTyconRef denv os tcref) | _ -> "" @@ -585,16 +585,16 @@ module internal SymbolHelpers = | Item.SetterArg (_, item) -> FullNameOfItem g item | Item.ImplicitOp(id, _) -> id.idText | Item.UnionCaseField (UnionCaseInfo (_, ucref), fieldIndex) -> ucref.FieldByIndex(fieldIndex).DisplayName - // unreachable - | Item.UnqualifiedType([]) - | Item.Types(_, []) - | Item.CtorGroup(_, []) - | Item.MethodGroup(_, [], _) + // unreachable + | Item.UnqualifiedType([]) + | Item.Types(_, []) + | Item.CtorGroup(_, []) + | Item.MethodGroup(_, [], _) | Item.ModuleOrNamespaces [] | Item.Property(info = []) -> "" /// Output the description of a language item - let rec GetXmlCommentForItem (infoReader: InfoReader) m item = + let rec GetXmlCommentForItem (infoReader: InfoReader) m item = let g = infoReader.g match item with | Item.ImplicitOp(_, sln) -> @@ -609,19 +609,19 @@ module internal SymbolHelpers = | None -> GetXmlCommentForItemAux None infoReader m item - | Item.Value vref | Item.CustomBuilder (_, vref) -> + | Item.Value vref | Item.CustomBuilder (_, vref) -> let doc = if valRefInThisAssembly g.compilingFSharpCore vref || vref.XmlDoc.NonEmpty then Some vref.XmlDoc else None GetXmlCommentForItemAux doc infoReader m item - | Item.UnionCase(ucinfo, _) -> + | Item.UnionCase(ucinfo, _) -> let doc = if tyconRefUsesLocalXmlDoc g.compilingFSharpCore ucinfo.TyconRef || ucinfo.UnionCase.XmlDoc.NonEmpty then Some ucinfo.UnionCase.XmlDoc else None GetXmlCommentForItemAux doc infoReader m item - | Item.ActivePatternCase apref -> + | Item.ActivePatternCase apref -> let doc = Some apref.ActivePatternVal.XmlDoc GetXmlCommentForItemAux doc infoReader m item - | Item.ExnCase ecref -> + | Item.ExnCase ecref -> let doc = if tyconRefUsesLocalXmlDoc g.compilingFSharpCore ecref || ecref.XmlDoc.NonEmpty then Some ecref.XmlDoc else None GetXmlCommentForItemAux doc infoReader m item @@ -641,13 +641,13 @@ module internal SymbolHelpers = let doc = if einfo.HasDirectXmlComment || einfo.XmlDoc.NonEmpty then Some einfo.XmlDoc else None GetXmlCommentForItemAux doc infoReader m item - | Item.Property(info = pinfos) -> + | Item.Property(info = pinfos) -> let pinfo = pinfos.Head let doc = if pinfo.HasDirectXmlComment || pinfo.XmlDoc.NonEmpty then Some pinfo.XmlDoc else None GetXmlCommentForItemAux doc infoReader m item - | Item.CustomOperation (_, _, Some minfo) - | Item.CtorGroup(_, minfo :: _) + | Item.CustomOperation (_, _, Some minfo) + | Item.CtorGroup(_, minfo :: _) | Item.MethodGroup(_, minfo :: _, _) -> GetXmlCommentForMethInfoItem infoReader m item minfo @@ -673,7 +673,7 @@ module internal SymbolHelpers = | _ -> None GetXmlCommentForItemAux doc infoReader m item - | Item.ModuleOrNamespaces(modref :: _ as modrefs) -> + | Item.ModuleOrNamespaces(modref :: _ as modrefs) -> let definiteNamespace = modrefs |> List.forall (fun modref -> modref.IsNamespace) if not definiteNamespace then let doc = if entityRefInThisAssembly g.compilingFSharpCore modref || modref.XmlDoc.NonEmpty then Some modref.XmlDoc else None @@ -685,7 +685,7 @@ module internal SymbolHelpers = let doc = match argContainer with | Some(ArgumentContainer.Method minfo) -> - if minfo.HasDirectXmlComment || minfo.XmlDoc.NonEmpty then Some minfo.XmlDoc else None + if minfo.HasDirectXmlComment || minfo.XmlDoc.NonEmpty then Some minfo.XmlDoc else None | Some(ArgumentContainer.Type tcref) -> if tyconRefUsesLocalXmlDoc g.compilingFSharpCore tcref || tcref.XmlDoc.NonEmpty then Some tcref.XmlDoc else None | _ -> None @@ -699,9 +699,9 @@ module internal SymbolHelpers = None GetXmlCommentForItemAux doc infoReader m item - | Item.SetterArg (_, item) -> + | Item.SetterArg (_, item) -> GetXmlCommentForItem infoReader m item - + // In all these cases, there is no direct XML documentation from F# comments | Item.MethodGroup (_, [], _) | Item.CtorGroup (_, []) @@ -735,7 +735,7 @@ module internal SymbolHelpers = #if !NO_TYPEPROVIDERS - /// Determine if an item is a provided type + /// Determine if an item is a provided type [] let (|ItemIsProvidedType|_|) g item = match item with @@ -757,11 +757,11 @@ module internal SymbolHelpers = match tys with | [AppTy g (tcref, _typeInst)] -> if tcref.IsProvidedErasedTycon || tcref.IsProvidedGeneratedTycon then - let typeBeforeArguments = - match tcref.TypeReprInfo with + let typeBeforeArguments = + match tcref.TypeReprInfo with | TProvidedTypeRepr info -> info.ProvidedType | _ -> failwith "unreachable" - let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters provider), range=m) + let staticParameters = typeBeforeArguments.PApplyWithProvider((fun (typeBeforeArguments, provider) -> typeBeforeArguments.GetStaticParameters provider), range=m) let staticParameters = staticParameters.PApplyArray(id, "GetStaticParameters", m) ValueSome staticParameters else @@ -774,11 +774,11 @@ module internal SymbolHelpers = match item with // Prefer the static parameters from the uninstantiated method info | Item.MethodGroup(_, _, Some minfo) -> - match minfo.ProvidedStaticParameterInfo with + match minfo.ProvidedStaticParameterInfo with | Some (_, staticParameters) -> ValueSome staticParameters | _ -> ValueNone | Item.MethodGroup(_, [minfo], _) -> - match minfo.ProvidedStaticParameterInfo with + match minfo.ProvidedStaticParameterInfo with | Some (_, staticParameters) -> ValueSome staticParameters | _ -> ValueNone | _ -> ValueNone @@ -794,20 +794,20 @@ module internal SymbolHelpers = #endif /// Get the "F1 Keyword" associated with an item, for looking up documentation help indexes on the web - let rec GetF1Keyword (g: TcGlobals) item = + let rec GetF1Keyword (g: TcGlobals) item = let rec getKeywordForMethInfo (minfo : MethInfo) = - match minfo with + match minfo with | FSMeth(_, _, vref, _) -> match vref.TryDeclaringEntity with | Parent tcref -> (tcref |> ticksAndArgCountTextOfTyconRef) + "." + vref.CompiledName g.CompilerGlobalState |> Some | ParentNone -> None - + | ILMeth (_, minfo, _) -> let typeString = minfo.DeclaringTyconRef |> ticksAndArgCountTextOfTyconRef let paramString = - let nGenericParams = minfo.RawMetadata.GenericParams.Length + let nGenericParams = minfo.RawMetadata.GenericParams.Length if nGenericParams > 0 then "``"+(nGenericParams.ToString()) else "" sprintf "%s.%s%s" typeString minfo.RawMetadata.Name paramString |> Some @@ -816,17 +816,17 @@ module internal SymbolHelpers = #if !NO_TYPEPROVIDERS | ProvidedMeth _ -> None #endif - + match item with - | Item.Value vref | Item.CustomBuilder (_, vref) -> + | Item.Value vref | Item.CustomBuilder (_, vref) -> let v = vref.Deref if v.IsModuleBinding && v.HasDeclaringEntity then let tyconRef = v.DeclaringEntity let paramsString = match v.Typars with | [] -> "" - | l -> "``"+(List.length l).ToString() - + | l -> "``"+(List.length l).ToString() + sprintf "%s.%s%s" (tyconRef |> ticksAndArgCountTextOfTyconRef) (v.CompiledName g.CompilerGlobalState) paramsString |> Some else None @@ -839,39 +839,39 @@ module internal SymbolHelpers = | Item.RecdField rfi -> (rfi.TyconRef |> ticksAndArgCountTextOfTyconRef) + "." + rfi.DisplayName |> Some - + | Item.AnonRecdField _ -> None - + | Item.ILField finfo -> - match finfo with - | ILFieldInfo(tinfo, fdef) -> + match finfo with + | ILFieldInfo(tinfo, fdef) -> (tinfo.TyconRefOfRawMetadata |> ticksAndArgCountTextOfTyconRef) + "." + fdef.Name |> Some #if !NO_TYPEPROVIDERS | ProvidedField _ -> None #endif - | Item.Types(_, AppTy g (tcref, _) :: _) + | Item.Types(_, AppTy g (tcref, _) :: _) | Item.DelegateCtor(AppTy g (tcref, _)) | Item.UnqualifiedType (tcref :: _) - | Item.ExnCase tcref -> + | Item.ExnCase tcref -> // strip off any abbreviation - match generalizedTyconRef g tcref with + match generalizedTyconRef g tcref with | AppTy g (tcref, _) -> Some (ticksAndArgCountTextOfTyconRef tcref) | _ -> None // Pathological cases of the above - | Item.Types _ + | Item.Types _ | Item.DelegateCtor _ - | Item.UnqualifiedType [] -> + | Item.UnqualifiedType [] -> None - | Item.ModuleOrNamespaces modrefs -> - match modrefs with - | modref :: _ -> + | Item.ModuleOrNamespaces modrefs -> + match modrefs with + | modref :: _ -> // namespaces from type providers need to be handled separately because they don't have compiled representation // otherwise we'll fail at tast.fs match modref.Deref.TypeReprInfo with -#if !NO_TYPEPROVIDERS - | TProvidedNamespaceRepr _ -> +#if !NO_TYPEPROVIDERS + | TProvidedNamespaceRepr _ -> modref.CompilationPathOpt |> Option.bind (fun path -> // works similar to generation of xml-docs at tastops.fs, probably too similar @@ -884,17 +884,17 @@ module internal SymbolHelpers = | _ -> modref.Deref.CompiledRepresentationForNamedType.FullName |> Some | [] -> None // Pathological case of the above - | Item.Property(info = pinfo :: _) -> - match pinfo with - | FSProp(_, _, Some vref, _) - | FSProp(_, _, _, Some vref) -> + | Item.Property(info = pinfo :: _) -> + match pinfo with + | FSProp(_, _, Some vref, _) + | FSProp(_, _, _, Some vref) -> // per spec, extension members in F1 keywords are qualified with definition class - match vref.TryDeclaringEntity with + match vref.TryDeclaringEntity with | Parent tcref -> - (tcref |> ticksAndArgCountTextOfTyconRef)+"."+vref.PropertyName|> Some + (tcref |> ticksAndArgCountTextOfTyconRef)+"."+vref.PropertyName|> Some | ParentNone -> None - | ILProp(ILPropInfo(tinfo, pdef)) -> + | ILProp(ILPropInfo(tinfo, pdef)) -> let tcref = tinfo.TyconRefOfRawMetadata (tcref |> ticksAndArgCountTextOfTyconRef)+"."+pdef.Name |> Some | FSProp _ -> None @@ -902,25 +902,25 @@ module internal SymbolHelpers = | ProvidedProp _ -> None #endif | Item.Property(info = []) -> None // Pathological case of the above - - | Item.Event einfo -> - match einfo with + + | Item.Event einfo -> + match einfo with | ILEvent _ -> let tcref = einfo.DeclaringTyconRef (tcref |> ticksAndArgCountTextOfTyconRef)+"."+einfo.EventName |> Some | FSEvent(_, pinfo, _, _) -> - match pinfo.ArbitraryValRef with + match pinfo.ArbitraryValRef with | Some vref -> // per spec, members in F1 keywords are qualified with definition class - match vref.TryDeclaringEntity with - | Parent tcref -> (tcref |> ticksAndArgCountTextOfTyconRef)+"."+vref.PropertyName|> Some + match vref.TryDeclaringEntity with + | Parent tcref -> (tcref |> ticksAndArgCountTextOfTyconRef)+"."+vref.PropertyName|> Some | ParentNone -> None | None -> None #if !NO_TYPEPROVIDERS - | ProvidedEvent _ -> None + | ProvidedEvent _ -> None #endif | Item.CtorGroup(_, minfos) -> - match minfos with + match minfos with | [] -> None | FSMeth(_, _, vref, _) :: _ -> match vref.TryDeclaringEntity with @@ -935,14 +935,14 @@ module internal SymbolHelpers = | Item.CustomOperation (_, _, Some minfo) -> getKeywordForMethInfo minfo | Item.MethodGroup(_, _, Some minfo) -> getKeywordForMethInfo minfo | Item.MethodGroup(_, minfo :: _, _) -> getKeywordForMethInfo minfo - | Item.SetterArg (_, propOrField) -> GetF1Keyword g propOrField - | Item.MethodGroup(_, [], _) + | Item.SetterArg (_, propOrField) -> GetF1Keyword g propOrField + | Item.MethodGroup(_, [], _) | Item.CustomOperation (_, _, None) // "into" | Item.NewDef _ // "let x$yz = ..." - no keyword - | Item.OtherName _ // no keyword on named parameters + | Item.OtherName _ // no keyword on named parameters | Item.Trait _ | Item.UnionCaseField _ - | Item.TypeVar _ + | Item.TypeVar _ | Item.ImplicitOp _ | Item.ActivePatternResult _ // "let (|Foo|Bar|) = .. Fo$o ..." - no keyword -> None @@ -954,21 +954,21 @@ module internal SymbolHelpers = // the VS integration. let SelectMethodGroupItems2 g (m: range) (item: ItemWithInst) : ItemWithInst list = ignore m - match item.Item with + match item.Item with | Item.MethodGroup(nm, minfos, orig) -> minfos |> List.map (fun minfo -> { Item = Item.MethodGroup(nm, [minfo], orig); TyparInstantiation = item.TyparInstantiation }) | Item.CtorGroup(nm, cinfos) -> - cinfos |> List.map (fun minfo -> { Item = Item.CtorGroup(nm, [minfo]); TyparInstantiation = item.TyparInstantiation }) + cinfos |> List.map (fun minfo -> { Item = Item.CtorGroup(nm, [minfo]); TyparInstantiation = item.TyparInstantiation }) | Item.DelegateCtor _ -> [item] - | Item.NewDef _ + | Item.NewDef _ | Item.ILField _ -> [] | Item.Event _ -> [] | Item.RecdField rfinfo -> if isForallFunctionTy g rfinfo.FieldType then [item] else [] | Item.Value v -> if isForallFunctionTy g v.Type then [item] else [] | Item.UnionCase(ucr, _) -> if not ucr.UnionCase.IsNullary then [item] else [] | Item.ExnCase ecr -> if isNil (recdFieldsOfExnDefRef ecr) then [] else [item] - | Item.Property(info = pinfos) -> - let pinfo = List.head pinfos + | Item.Property(info = pinfos) -> + let pinfo = List.head pinfos if pinfo.IsIndexer then [item] else [] #if !NO_TYPEPROVIDERS | ItemIsWithStaticArguments m g _ -> [item] // we pretend that provided-types-with-static-args are method-like in order to get ParamInfo for them diff --git a/src/Compiler/Utilities/range.fsi b/src/Compiler/Utilities/range.fsi index 40a52efa879..90deb76d976 100755 --- a/src/Compiler/Utilities/range.fsi +++ b/src/Compiler/Utilities/range.fsi @@ -6,7 +6,7 @@ namespace FSharp.Compiler.Text open System.Collections.Generic /// An index into a global tables of filenames -type internal FileIndex = int32 +type internal FileIndex = int32 [] type internal NotedSourceConstruct = @@ -59,10 +59,10 @@ type Position = /// Check if the position is adjacent to another position member internal IsAdjacentTo: otherPos: Position -> bool - /// Decode a position fro a 64-bit integer + /// Decode a position for a 64-bit integer static member internal Decode: int64 -> pos - /// The maximum number of bits needed to store an encoded position + /// The maximum number of bits needed to store an encoded position static member internal EncodingSize: int /// Represents a position in a file @@ -105,7 +105,7 @@ type Range = /// Synthetic marks ranges which are produced by intermediate compilation phases. This /// bit signifies that the range covers something that should not be visible to language /// service operations like dot-completion. - member IsSynthetic: bool + member IsSynthetic: bool /// Convert a range to be synthetic member internal MakeSynthetic: unit -> range @@ -122,13 +122,13 @@ type Range = /// The range where all values are zero static member Zero: range - + /// Represents a range within a file and range = Range /// Represents a line number when using zero-based line counting (used by Visual Studio) #if CHECK_LINE0_TYPES -// Visual Studio uses line counts starting at 0, F# uses them starting at 1 +// Visual Studio uses line counts starting at 0, F# uses them starting at 1 [] type ZeroBasedLineAnnotation type Line0 = int @@ -158,7 +158,7 @@ module Position = /// Compare positions for greater-than-or-equal-to val posGeq: pos -> pos -> bool - /// Convert a position from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages) + /// Convert a position from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages) val fromZ: line:Line0 -> column:int -> pos /// Convert a position from one-based line counting (used internally in the F# compiler and in F# error messages) to zero-based line counting (used by Visual Studio) @@ -188,10 +188,10 @@ module Range = /// Ordering on positions val posOrder: IComparer - /// This view of range marks uses file indexes explicitly + /// This view of range marks uses file indexes explicitly val mkFileIndexRange: FileIndex -> pos -> pos -> range - /// This view hides the use of file indexes and just uses filenames + /// This view hides the use of file indexes and just uses filenames val mkRange: string -> pos -> pos -> range /// Make a range for the first non-whitespace line of the file if any. Otherwise use line 1 chars 0-80. @@ -211,21 +211,21 @@ module Range = /// Union two ranges, taking their first occurring start position and last occurring end position val unionRanges: range -> range -> range - + // Create a new range with the given start and end positions val withStartEnd: Position -> Position -> range -> range - + // Create a new range with the given start position val withStart: Position -> range -> range - + // Create a new range with the given end position val withEnd: Position -> range -> range - + // Create a new range with the start position shifted by the given deltas val shiftStart: int -> int -> range -> range - + // Create a new range with the end position shifted by the given deltas - val shiftEnd: int -> int -> range -> range + val shiftEnd: int -> int -> range -> range /// Test to see if one range contains another range val rangeContainsRange: range -> range -> bool @@ -247,7 +247,7 @@ module Range = /// A range associated with a dummy file for the command line arguments val rangeCmdArgs: range - + /// Convert a range to a string val stringOfRange: range -> string @@ -263,10 +263,8 @@ module Range = /// Functions related to converting between lines indexed at 0 and 1 module Line = - /// Convert a line number from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages) + /// Convert a line number from zero-based line counting (used by Visual Studio) to one-based line counting (used internally in the F# compiler and in F# error messages) val fromZ: Line0 -> int /// Convert a line number from one-based line counting (used internally in the F# compiler and in F# error messages) to zero-based line counting (used by Visual Studio) - val toZ: int -> Line0 - - + val toZ: int -> Line0 diff --git a/tests/FSharp.Test.Utilities/Compiler.fs b/tests/FSharp.Test.Utilities/Compiler.fs index c6346cb30f2..e21079818d7 100644 --- a/tests/FSharp.Test.Utilities/Compiler.fs +++ b/tests/FSharp.Test.Utilities/Compiler.fs @@ -462,7 +462,7 @@ module rec Compiler = let FsxFromPath (path: string) : CompilationUnit = fsFromString (SourceFromPath path) |> FS - + let Fs (source: string) : CompilationUnit = fsFromString (FsSource source) |> FS @@ -1049,7 +1049,7 @@ module rec Compiler = let compilation = Compilation.Compilation([], CompileOutput.Exe,Array.empty, TargetFramework.Current, references, None, None) evaluateReferences outputDirectory fsSource.IgnoreWarnings compilation |> fst - + let options = [| yield! fsSource.Options |> Array.ofList @@ -1211,7 +1211,7 @@ module rec Compiler = CompilationResult.Success (mkResult output) else let err = (errors |> String.concat "\n").Replace("\r\n","\n") - let output = + let output = ExecutionOutput {Outcome = NoExitCode; StdOut = String.Empty; StdErr = err } CompilationResult.Failure (mkResult output) @@ -1243,7 +1243,7 @@ Actual: elif FileSystem.FileExistsShim baseline.FilePath then FileSystem.FileDeleteShim baseline.FilePath - + let private createBaselineErrors (baselineFile: BaselineFile) (actualErrors: string) : unit = printfn $"creating baseline error file for convenience: {baselineFile.FilePath}, expected: {baselineFile.BslSource}" let file = FileSystem.OpenFileForWriteShim(baselineFile.FilePath) @@ -1300,7 +1300,7 @@ Actual: | Some p -> match ILChecker.verifyILAndReturnActual [] p expected with | true, _, _ -> result - | false, errorMsg, _actualIL -> + | false, errorMsg, _actualIL -> CompilationResult.Failure( {s with Output = Some (ExecutionOutput {Outcome = NoExitCode; StdOut = errorMsg; StdErr = ""})} ) | CompilationResult.Failure f -> printfn "Failure:" @@ -1614,7 +1614,7 @@ Actual: // For lists longer than 100 errors: expectedErrors |> List.iter System.Diagnostics.Debug.WriteLine - // TODO: Check all "categories", collect all results and print alltogether. + // TODO: Check all "categories", collect all results and print all together. checkEqual "Errors count" expectedErrors.Length sourceErrors.Length (sourceErrors, expectedErrors) @@ -1832,10 +1832,10 @@ Actual: let m = Regex(pattern, RegexOptions.Multiline).Match(input) if m.Success then m.Index - else + else -1 else - input.IndexOf(pattern) + input.IndexOf(pattern) let private checkOutputInOrderCore useWildcards (category: string) (substrings: string list) (selector: ExecutionOutput -> string) (result: CompilationResult) : CompilationResult = match result.RunOutput with @@ -1944,10 +1944,9 @@ Actual: let printSignatures cUnit = printSignaturesImpl None cUnit let printSignaturesWith pageWidth cUnit = printSignaturesImpl (Some pageWidth) cUnit - let getImpliedSignatureHash cUnit = + let getImpliedSignatureHash cUnit = let tcResults = cUnit |> typecheckResults let hash = tcResults.CalculateSignatureHash() match hash with | Some h -> h | None -> failwith "Implied signature hash returned 'None' which should not happen" - diff --git a/tests/fsharp/core/members/absil.fsi b/tests/fsharp/core/members/absil.fsi index 11d322553a2..c7755fa4222 100644 --- a/tests/fsharp/core/members/absil.fsi +++ b/tests/fsharp/core/members/absil.fsi @@ -6,13 +6,13 @@ open System type Guid = Option - type Document = + type Document = { Language: Option; Vendor: Option; Type: Option; File: string; } - type SourceAnnotation = + type SourceAnnotation = { Document: Document; Line: int; Column: int; @@ -23,43 +23,43 @@ open System type ModuleName = string type Locale = string - type PublicKeyInfo = + type PublicKeyInfo = | PublicKey of Bytes | PublicKeyToken of Bytes type VersionInfo = UInt16 * UInt16 * UInt16 * UInt16 - type AssemblyRef = + type AssemblyRef = { Name: string; Hash: Option; PublicKeyInfo: Option; - Version: Option; - Locale: Option; } + Version: Option; + Locale: Option; } - type ModuleRef = + type ModuleRef = { Name: string; NoMetadata: bool; - Hash: Option; } + Hash: Option; } - type ScopeRef = - | Local - | Module of ModuleRef - | Assembly of AssemblyRef + type ScopeRef = + | Local + | Module of ModuleRef + | Assembly of AssemblyRef - type BasicCallconv = + type BasicCallconv = | Default - | Cdecl - | Stdcall - | Thiscall - | Fastcall + | Cdecl + | Stdcall + | Thiscall + | Fastcall | Vararg - - type HasThis = + + type HasThis = | Instance (* accepts an implicit 'this' pointer *) | InstanceExplicit (* any 'this' pointer is made explicit (C++ only) *) | Static (* no 'this' pointer is passed *) - type Callconv + type Callconv static member InstanceCallconv: Callconv static member StaticCallconv: Callconv member IsVararg: bool @@ -72,7 +72,7 @@ open System val is_static_callconv: Callconv -> bool type ArrayShape - member Details: (Int32 option * Int32 option) list + member Details: (Int32 option * Int32 option) list member Rank: Int32 static member SingleDimensional: ArrayShape @@ -84,7 +84,7 @@ open System - type TypeRef + type TypeRef member TypeName: string member FullTypeName: string member EnclosingTypeNames: List @@ -95,17 +95,17 @@ open System val enclosing_tnames_of_tref: TypeRef -> List val scoref_of_tref: TypeRef -> ScopeRef - type TypeSpec + type TypeSpec member TypeRef: TypeSpec -> TypeRef member TypeName: TypeSpec -> string member FullTypeName: TypeSpec -> string member ScopeRef: TypeSpec -> ScopeRef member EnclosingTypeNames: TypeSpec -> List - - and Type + + and Type // member Details: (?k:TypeKind. TypeDetails) // These properties let you access the contents of a type in a - // semi-safe way - they may throw exceptions. They could be + // semi-safe way - they may throw exceptions. They could be // given different names. member Shape: ArrayShape member ElementType: Type @@ -125,14 +125,14 @@ open System static member Tyvar: Callsig -> Type static member Modified: bool * Type * Type -> Type - and TypeKind = - | Void - | Array - | Value - | Boxed - | Ptr + and TypeKind = + | Void + | Array + | Value + | Boxed + | Ptr | Byref - | Fptr + | Fptr | Tyvar | Modified @@ -179,7 +179,7 @@ open System val is_tyvar_ty: Type -> bool - type CallSig = + type CallSig = { Callconv: Callconv; ArgTypes: List; ReturnType: Type } @@ -192,11 +192,11 @@ open System // F# library signature: //------------------------------------------------------------------------- - // This is the primitive interface for implementing events corresponding to + // This is the primitive interface for implementing events corresponding to // any delegate type. // // Note 'a and 'args must correspond - if they do not runtime exceptions will arise. - // We could add a constraint of the form + // We could add a constraint of the form // when 'a :> delegate(object * 'arg -> void) type EventForDelegateType<'a> = { Add: 'a -> unit; @@ -205,7 +205,7 @@ open System type ListenerListForDelegateType<'a,'arg> = { Fire: 'arg -> unit; AsEvent: EventForDelegateType<'a> } - + val ListenerListForDelegateType: unit -> ListenerListForDelegateType<'a,'arg> when 'a :> System.Delegate // This is for the common case for F# where the event type is EventHandler @@ -215,26 +215,26 @@ open System { Fire: 'a -> unit; AsEvent: Event<'a> } - val NewListenerList: unit -> ListenerList<'a> - + val NewListenerList: unit -> ListenerList<'a> + // A component signature: type NoiseLevel = Double - - type MyComponent + + type MyComponent member OnNoise: Event member OnPaint: EventForDelegateType - + val NewMyComponent: unit -> MyComponent - - - type MethodRef + + + type MethodRef member Name: string member Callconv: Callconv member Return: Type member ArgTypes: List - member Parent: TypeRef + member Parent: TypeRef member GenericArity: int member CallSig: CallSig member Rename: MethodRef -> MethodRef @@ -245,14 +245,14 @@ open System val callconv_of_mref: MethodRef -> Callconv val ret_of_mref: MethodRef -> Type val args_of_mref: MethodRef -> List - val tref_of_mref: MethodRef -> TypeRef + val tref_of_mref: MethodRef -> TypeRef val parent_of_mref: MethodRef -> TypeRef (* same as tref_of_mref *) val genarity_of_mref: MethodRef -> int val callsig_of_mref: MethodRef -> CallSig val rename_mref: string -> MethodRef -> MethodRef val relocate_mref: Type -> MethodRef -> MethodRef - type FieldRef + type FieldRef member Type: FieldRef member Name: string member TypeRef: TypeRef @@ -318,7 +318,7 @@ open System type CodeLabel = string - type BasicType = + type BasicType = | DT_R | DT_I1 | DT_U1 @@ -334,91 +334,91 @@ open System | DT_U | DT_REF - type LdtokenInfo = - | Token_type of Type - | Token_method of MethodSpec + type LdtokenInfo = + | Token_type of Type + | Token_method of MethodSpec | Token_field of FieldSpec - type LdcInfo = + type LdcInfo = | NUM_I4 of Int32 | NUM_I8 of Int64 | NUM_R4 of Single | NUM_R8 of Double - type Tailness = + type Tailness = | Tailcall | Normalcall - type Alignment = + type Alignment = | Aligned | Unaligned_1 | Unaligned_2 | Unaligned_4 - type Volatility = + type Volatility = | Volatile | Nonvolatile - type Readonly = + type Readonly = | ReadonlyAddress | NormalAddress type VarargTypes = Option< List > type CompareOp = - | BI_beq - | BI_bge - | BI_bge_un - | BI_bgt - | BI_bgt_un - | BI_ble - | BI_ble_un - | BI_blt - | BI_blt_un - | BI_bne_un - | BI_brfalse - | BI_brtrue + | BI_beq + | BI_bge + | BI_bge_un + | BI_bgt + | BI_bgt_un + | BI_ble + | BI_ble_un + | BI_blt + | BI_blt_un + | BI_bne_un + | BI_brfalse + | BI_brtrue type ArithmeticOp = - | AI_add + | AI_add | AI_add_ovf | AI_add_ovf_un - | AI_and - | AI_div + | AI_and + | AI_div | AI_div_un - | AI_ceq - | AI_cgt - | AI_cgt_un - | AI_clt - | AI_clt_un + | AI_ceq + | AI_cgt + | AI_cgt_un + | AI_clt + | AI_clt_un | AI_conv of BasicType | AI_conv_ovf of BasicType | AI_conv_ovf_un of BasicType - | AI_mul - | AI_mul_ovf + | AI_mul + | AI_mul_ovf | AI_mul_ovf_un - | AI_rem - | AI_rem_un - | AI_shl - | AI_shr + | AI_rem + | AI_rem_un + | AI_shl + | AI_shr | AI_shr_un - | AI_sub - | AI_sub_ovf - | AI_sub_ovf_un - | AI_xor - | AI_or - | AI_neg - | AI_not - | AI_ldnull - | AI_dup + | AI_sub + | AI_sub_ovf + | AI_sub_ovf_un + | AI_xor + | AI_or + | AI_neg + | AI_not + | AI_ldnull + | AI_dup | AI_pop - | AI_ckfinite + | AI_ckfinite | AI_nop | AI_ldc of BasicType * LdcInfo // A discriminated union automatically defines a kind and a "details"? - type Instr = + type Instr = (* Basic *) | I_arith of ArithmeticOp | I_ldarg of UInt16 @@ -435,7 +435,7 @@ open System | I_jmp of MethodSpec | I_brcmp of CompareOp * CodeLabel * CodeLabel (* second label is fall-through *) | I_switch of (CodeLabel list * CodeLabel) (* last label is fallthrough *) - | I_ret + | I_ret (* Method call *) | I_call of Tailness * MethodSpec * VarargTypes @@ -444,7 +444,7 @@ open System | I_calli of Tailness * CallSig * VarargTypes | I_ldftn of MethodSpec | I_newobj of MethodSpec * VarargTypes - + (* Exceptions *) | I_throw | I_endfinally @@ -455,7 +455,7 @@ open System | I_ldsfld of Volatility * FieldSpec | I_ldfld of Alignment * Volatility * FieldSpec | I_ldsflda of FieldSpec - | I_ldflda of FieldSpec + | I_ldflda of FieldSpec | I_stsfld of Volatility * FieldSpec | I_stfld of Alignment * Volatility * FieldSpec | I_ldstr of Bytes (* Beware! This is a unicode encoding of the string! *) @@ -483,21 +483,21 @@ open System | I_ldlen | I_mkrefany of Type - | I_refanytype + | I_refanytype | I_refanyval of Type | I_rethrow - | I_break - | I_seqpoint of SourceAnnotation + | I_break + | I_seqpoint of SourceAnnotation - | I_arglist + | I_arglist | I_localloc | I_cpblk of Alignment * Volatility | I_initblk of Alignment * Volatility -type basic_block = +type basic_block = { bblockLabel: CodeLabel; bblockInstrs: Instr array } @@ -512,11 +512,11 @@ val instr_is_tailcall: Instr -> bool -type local_debug_info = +type local_debug_info = { localNum: int; localName: string; } -type Code = +type Code = | BasicBlock of basic_block | GroupBlock of local_debug_info list * Code list | RestrictBlock of List * Code @@ -524,12 +524,12 @@ type Code = member Name: string member X : int - + and seh = - | FaultBlock of Code + | FaultBlock of Code | FinallyBlock of Code | FilterCatchBlock of (filter * Code) list -and filter = +and filter = | TypeFilter of Type | CodeFilter of Code @@ -538,11 +538,11 @@ val exits_of_code: Code -> List val unique_entry_of_code: Code -> CodeLabel val unique_exit_of_code: Code -> CodeLabel -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Field Init * -------------------------------------------------------------------- *) -type FieldInit = +type FieldInit = | FieldInit_Bytes of Bytes | FieldInit_bool of bool | FieldInit_char of UInt16 @@ -558,10 +558,10 @@ type FieldInit = | FieldInit_Double of Double | FieldInit_ref -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Native Types, for marshalling to the native C interface. * These are taken directly from the ILASM syntax, and don't really - * correspond yet to the ECMA Spec (Partition II, 7.4). + * correspond yet to the ECMA Spec (Partition II, 7.4). * -------------------------------------------------------------------- *) type native_type = @@ -598,76 +598,76 @@ type native_type = | (* COM interop *) NativeType_iunknown | (* COM interop *) NativeType_idispatch | (* COM interop *) NativeType_interface - | (* COM interop *) NativeType_error - | (* COM interop *) NativeType_safe_array of variant_type * string option + | (* COM interop *) NativeType_error + | (* COM interop *) NativeType_safe_array of variant_type * string option | (* COM interop *) NativeType_ansi_bstr | (* COM interop *) NativeType_variant_bool -and variant_type = +and variant_type = | VariantType_empty | VariantType_null | VariantType_variant | VariantType_currency - | VariantType_decimal - | VariantType_date - | VariantType_bstr - | VariantType_lpstr - | VariantType_lpwstr - | VariantType_iunknown - | VariantType_idispatch - | VariantType_safearray - | VariantType_error - | VariantType_hresult - | VariantType_carray - | VariantType_userdefined - | VariantType_record + | VariantType_decimal + | VariantType_date + | VariantType_bstr + | VariantType_lpstr + | VariantType_lpwstr + | VariantType_iunknown + | VariantType_idispatch + | VariantType_safearray + | VariantType_error + | VariantType_hresult + | VariantType_carray + | VariantType_userdefined + | VariantType_record | VariantType_filetime - | VariantType_blob - | VariantType_stream - | VariantType_storage - | VariantType_streamed_object - | VariantType_stored_object - | VariantType_blob_object - | VariantType_cf + | VariantType_blob + | VariantType_stream + | VariantType_storage + | VariantType_streamed_object + | VariantType_stored_object + | VariantType_blob_object + | VariantType_cf | VariantType_clsid - | VariantType_void + | VariantType_void | VariantType_bool | VariantType_Int8 - | VariantType_Int16 - | VariantType_Int32 - | VariantType_Int64 - | VariantType_Single - | VariantType_Double - | VariantType_unsigned_Int8 - | VariantType_unsigned_Int16 - | VariantType_unsigned_Int32 - | VariantType_unsigned_Int64 - | VariantType_ptr - | VariantType_array of variant_type - | VariantType_vector of variant_type - | VariantType_byref of variant_type - | VariantType_int - | VariantType_unsigned_int - - -(* -------------------------------------------------------------------- + | VariantType_Int16 + | VariantType_Int32 + | VariantType_Int64 + | VariantType_Single + | VariantType_Double + | VariantType_unsigned_Int8 + | VariantType_unsigned_Int16 + | VariantType_unsigned_Int32 + | VariantType_unsigned_Int64 + | VariantType_ptr + | VariantType_array of variant_type + | VariantType_vector of variant_type + | VariantType_byref of variant_type + | VariantType_int + | VariantType_unsigned_int + + +(* -------------------------------------------------------------------- * Local variables * -------------------------------------------------------------------- *) -type local = +type local = { localType: Type; localPinned: bool } - :> Object + :> Object :> IComparable val typ_of_local: local -> Type -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * IL method bodies * -------------------------------------------------------------------- *) -type CILMethodBody = +type CILMethodBody = { ilZeroInit: bool; ilMaxStack: Int32; (* strictly speaking should be a UInt16 *) ilNoInlining: bool; @@ -678,26 +678,26 @@ type CILMethodBody = val locals_of_ilmbody: CILMethodBody -> local list val code_of_ilmbody: CILMethodBody -> Code -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Member Access * -------------------------------------------------------------------- *) -type MemberAccess = +type MemberAccess = | MemAccess_assembly | MemAccess_compilercontrolled | MemAccess_famandassem | MemAccess_famorassem | MemAccess_family - | MemAccess_private - | MemAccess_public + | MemAccess_private + | MemAccess_public (* -------------------------------------------------------------------- - * Custom attributes: @todo: provide a helper to parse the Bytes - * to CustomAttribute_elem's as best as possible. + * Custom attributes: @todo: provide a helper to parse the Bytes + * to CustomAttribute_elem's as best as possible. * -------------------------------------------------------------------- *) -type CustomAttributeElement = - | String of String +type CustomAttributeElement = + | String of String | Bool of Boolean | Char of Char | Int8 of SByte @@ -710,25 +710,25 @@ type CustomAttributeElement = | UInt64 of UInt64 | Single of Single | Double of Double - | Type of TypeRef + | Type of TypeRef | Enum of Type * CustomAttributeElement type CustomAttribute = - { customMethod: MethodSpec; + { customMethod: MethodSpec; customData: Bytes } type CustomAttributes (* Equivalent to CustomAttribute list - use helpers below to construct/destruct these *) val dest_CustomAttributes: CustomAttributes -> CustomAttribute list -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Method parameters and return values * -------------------------------------------------------------------- *) -type param = +type param = { Name: string option; Type: Type; - Default: Option; + Default: Option; Marshal: native_type option; (* Marshalling map for parameters. COM Interop only. *) In: bool; Out: bool; @@ -738,29 +738,29 @@ type param = val name_of_param: param -> string option val typ_of_param: param -> Type -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Method return values * -------------------------------------------------------------------- *) -type ReturnSpec = +type ReturnSpec = { returnMarshal: native_type option; returnType: Type; } val typ_of_return: ReturnSpec -> Type -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Security Permissions - * + * * Attached to various structures... * -------------------------------------------------------------------- *) -type SecurityAction = - | Request +type SecurityAction = + | Request | Demand | Assert | Deny | Permitonly - | Linkcheck + | Linkcheck | Inheritcheck | Reqmin | Reqopt @@ -771,7 +771,7 @@ type SecurityAction = | Noncaslinkdemand | Noncasinheritance -type PermissionValue = +type PermissionValue = Bool of bool | Int32 of Int32 | String of string @@ -779,7 +779,7 @@ type PermissionValue = | EnumInt16 of TypeRef * Int16 | EnumInt32 of TypeRef * Int32 -type permission = +type permission = | Permission of SecurityAction * Type * (string * PermissionValue) list | PermissionSet of SecurityAction * Bytes @@ -787,11 +787,11 @@ type SecurityDecls (* Opaque type equivalent to permission list - use helpers be val dest_SecurityDecls: SecurityDecls -> permission list -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * PInvoke attributes. * -------------------------------------------------------------------- *) -type pinvoke_Callconv = +type pinvoke_Callconv = | PInvoke_CC_none | PInvoke_CC_cdecl | PInvoke_CC_stdcall @@ -799,13 +799,13 @@ type pinvoke_Callconv = | PInvoke_CC_fastcall | PInvoke_CC_winapi -type pinvoke_encoding = +type pinvoke_encoding = | PInvoke_Encoding_none | PInvoke_Encoding_ansi | PInvoke_Encoding_unicode | PInvoke_Encoding_autochar -type pinvoke_attr = +type pinvoke_attr = { pinvokeWhere: ModuleRef; pinvokeName: string; pinvokeCallconv: pinvoke_Callconv; @@ -827,20 +827,20 @@ val formal_CallSig_of_ospec: OverridesSpec -> CallSig val actual_CallSig_of_ospec: OverridesSpec -> CallSig -type virtual_info = - { Final: bool; - Newslot: bool; +type virtual_info = + { Final: bool; + Newslot: bool; Abstract: bool; Overrides: OverridesSpec option; } -type method_kind = - | Static - | Cctor - | Ctor - | Nonvirtual +type method_kind = + | Static + | Cctor + | Ctor + | Nonvirtual | Virtual of virtual_info -type MethodBody_details = +type MethodBody_details = | MethodBody_il of CILMethodBody | MethodBody_pinvoke of pinvoke_attr (* platform invoke to native *) | MethodBody_abstract @@ -853,17 +853,17 @@ type method_code_kind = type MethodBody (* isomorphic to MethodBody_details *) -val dest_mbody : MethodBody -> MethodBody_details +val dest_mbody : MethodBody -> MethodBody_details -type MethodDef = +type MethodDef = { mdName: string; mdKind: method_kind; mdCallconv: Callconv; mdParams: List; mdReturn: ReturnSpec; mdAccess: MemberAccess; - mdBody: MethodBody; - mdCodeKind: method_code_kind; + mdBody: MethodBody; + mdCodeKind: method_code_kind; mdInternalCall: bool; mdManaged: bool; mdForwardRef: bool; @@ -876,9 +876,9 @@ type MethodDef = mdSynchronized: bool; mdPreserveSig: bool; mdMustRun: bool; (* Whidbey feature: SafeHandle finalizer must be run *) - mdExport: (Int32 * string option) option; + mdExport: (Int32 * string option) option; mdVtableEntry: (Int32 * Int32) option; - + (* MS-GENERICS *) mdGenericParams: GenericParams; mdCustomAttrs: CustomAttributes; } @@ -893,9 +893,9 @@ val code_of_mdef: MethodDef -> Code val entry_of_mdef: MethodDef -> CodeLabel val CallSig_of_mdef: MethodDef -> CallSig -(* -------------------------------------------------------------------- - * Delegates. Derived functions for telling if a method/class definition - * is really a delegate. Also for telling if method signatures refer to +(* -------------------------------------------------------------------- + * Delegates. Derived functions for telling if a method/class definition + * is really a delegate. Also for telling if method signatures refer to * delegate methods. * -------------------------------------------------------------------- *) @@ -907,9 +907,9 @@ val is_delegate_begin_invoke: MethodDef -> bool val is_delegate_end_invoke: MethodDef -> bool val dest_delegate_begin_end_invoke: MethodDef -> MethodDef -> List * Type -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Tables of methods. Logically equivalent to a list of methods but - * the table is kept in a form optimized for looking up methods by + * the table is kept in a form optimized for looking up methods by * name and arity. * -------------------------------------------------------------------- *) @@ -919,20 +919,20 @@ val dest_mdefs: MethodDefs -> MethodDef list val filter_mdefs: (MethodDef -> bool) -> MethodDefs -> MethodDefs val find_mdefs_by_arity: string * int -> MethodDefs -> MethodDef list -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Field definitions * -------------------------------------------------------------------- *) -type FieldDef = +type FieldDef = { Name: string; Type: Type; Static: bool; Access: MemberAccess; Data: Option; - Init: Option; + Init: Option; Offset: Int32 option; (* The explicit offset in Bytes when explicit layout is used. *) SpecialName: bool; - Marshal: native_type option; + Marshal: native_type option; NotSerialized: bool; Literal: bool ; InitOnly: bool; @@ -941,9 +941,9 @@ type FieldDef = val typ_of_fdef : FieldDef -> Type val name_of_fdef: FieldDef -> string -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Tables of FieldDefs. Logically equivalent to a list of FieldDefs but - * the table is kept in a form optimized for looking up FieldDefs by + * the table is kept in a form optimized for looking up FieldDefs by * name. * -------------------------------------------------------------------- *) @@ -953,22 +953,22 @@ val dest_fdefs: FieldDefs -> FieldDef list val filter_fdefs: (FieldDef -> bool) -> FieldDefs -> FieldDefs val find_fdef: string -> FieldDefs -> FieldDef list -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Event definitions * -------------------------------------------------------------------- *) -type EventDef = - { eventType: Type option; +type EventDef = + { eventType: Type option; eventName: string; eventRTSpecialName: bool; eventSpecialName: bool; - eventAddOn: MethodRef; + eventAddOn: MethodRef; eventRemoveOn: MethodRef; eventFire: Option; eventOther: MethodRef list; eventCustomAttrs: CustomAttributes; } -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Table of those events in a type definition. * -------------------------------------------------------------------- *) @@ -977,23 +977,23 @@ type EventDefs val dest_events: EventDefs -> EventDef list val filter_events: (EventDef -> bool) -> EventDefs -> EventDefs -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Property definitions * -------------------------------------------------------------------- *) -type PropertyDef = +type PropertyDef = { propName: string; propRTSpecialName: bool; propSpecialName: bool; propSet: Option; propGet: Option; propCallconv: HasThis; - propType: Type; + propType: Type; propInit: Option; propArgs: List; propCustomAttrs: CustomAttributes; } -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Table of those properties in a type definition. * -------------------------------------------------------------------- *) @@ -1002,15 +1002,15 @@ type ILPropertyDefs val dest_properties: properties -> PropertyDef list val filter_properties: (PropertyDef -> bool) -> ILPropertyDefs -> ILPropertyDefs -(* ------------------------------------------------------------------ +(* ------------------------------------------------------------------ * Method Impls - * - * If there is an entry (pms --> ms) in this table, then method [ms] - * is used to implement method [pms] for the purposes of this class - * and its subclasses. + * + * If there is an entry (pms --> ms) in this table, then method [ms] + * is used to implement method [pms] for the purposes of this class + * and its subclasses. * ------------------------------------------------------------------ *) -type MethodImpl = +type MethodImpl = { mimplOverrides: OverridesSpec; mimplOverrideBy: MethodSpec } @@ -1018,18 +1018,18 @@ type MethodImpls val dest_mimpls: MethodImpls -> MethodImpl list -(* ------------------------------------------------------------------ +(* ------------------------------------------------------------------ * Type Access, Layout etc. * ------------------------------------------------------------------ *) type TypeLayout = | TypeLayout_auto | TypeLayout_sequential of TypeLayout_info - | TypeLayout_explicit of TypeLayout_info + | TypeLayout_explicit of TypeLayout_info and TypeLayout_info = { typeSize: Int32 option; - typePack: UInt16 option } + typePack: UInt16 option } type TypeInit = | TypeInit_beforefield @@ -1040,26 +1040,26 @@ type TypeEncoding = | TypeEncoding_autochar | TypeEncoding_unicode -type TypeDefAccess = - | TypeAccess_public +type TypeDefAccess = + | TypeAccess_public | TypeAccess_private - | TypeAccess_nested of MemberAccess + | TypeAccess_nested of MemberAccess type delegate_kind = Multicast | Singlecast -type delegate_info = - { delKind: delegate_kind; +type delegate_info = + { delKind: delegate_kind; delAsync: bool; delArgs: List; delRet: Type } -type enum_info = - { enumValues: (string * FieldInit) list; +type enum_info = + { enumValues: (string * FieldInit) list; enumType: Type } val values_of_enum_info: enum_info -> (string * FieldInit) list val typ_of_enum_info: enum_info -> Type -type TypeDefKind = +type TypeDefKind = | TypeDef_class | TypeDef_valuetype | TypeDef_interface @@ -1070,21 +1070,21 @@ type TypeDefKind = val split_type_name: string -> List * string -type TypeDef = +type TypeDef = { tdKind: TypeDefKind; - tdName: string; + tdName: string; tdGenericParams: GenericParams; - tdAccess: TypeDefAccess; + tdAccess: TypeDefAccess; tdAbstract: bool; - tdSealed: bool; - tdSerializable: bool; - tdComInterop: bool; (* Class or interface generated for COM interop *) + tdSealed: bool; + tdSerializable: bool; + tdComInterop: bool; (* Class or interface generated for COM interop *) tdLayout: TypeLayout; tdSpecialName: bool; tdEncoding: TypeEncoding; tdNested: TypeDefs; - tdImplements: List; - tdExtends: Type option; + tdImplements: List; + tdExtends: Type option; tdMethodDefs: MethodDefs; tdSecurityDecls: SecurityDecls; tdFieldDefs: FieldDefs; @@ -1132,50 +1132,49 @@ val iter_lazy_tdefs: (string -> TypeDef Lazy.t -> unit) -> TypeDefs -> unit val tname_for_toplevel: string val is_toplevel_tname: string -> bool val dest_tdefs_with_toplevel_first: TypeDefs -> TypeDef list - -(* -------------------------------------------------------------------- - * "Classes Elsewhere" - classes in auxillary modules. +(* -------------------------------------------------------------------- + * "Classes Elsewhere" - classes in auxiliary modules. * - * Manifests include declarations for all the classes in an + * Manifests include declarations for all the classes in an * assembly, regardless of which module they are in. * - * The ".class extern" construct describes so-called exported Types -- - * these are public classes defined in the auxillary modules of this assembly, - * i.e. modules other than the manifest-carrying module. - * - * For example, if you have a two-module - * assembly (A.DLL and B.DLL), and the manifest resides in the A.DLL, + * The ".class extern" construct describes so-called exported Types -- + * these are public classes defined in the auxiliary modules of this assembly, + * i.e. modules other than the manifest-carrying module. + * + * For example, if you have a two-module + * assembly (A.DLL and B.DLL), and the manifest resides in the A.DLL, * then in the manifest all the public classes declared in B.DLL should - * be defined as exported Types, i.e., as ".class extern". The public classes - * defined in A.DLL should not be defined as ".class extern" -- they are - * already available in the manifest-carrying module. The union of all - * public classes defined in the manifest-carrying module and all - * exported Types defined there is the set of all classes exposed by - * this assembly. Thus, by analysing the metadata of the manifest-carrying - * module of an assembly, you can identify all the classes exposed by + * be defined as exported Types, i.e., as ".class extern". The public classes + * defined in A.DLL should not be defined as ".class extern" -- they are + * already available in the manifest-carrying module. The union of all + * public classes defined in the manifest-carrying module and all + * exported Types defined there is the set of all classes exposed by + * this assembly. Thus, by analysing the metadata of the manifest-carrying + * module of an assembly, you can identify all the classes exposed by * this assembly, and where to find them. * - * Nested classes found in external modules should also be located in + * Nested classes found in external modules should also be located in * this table, suitably nested inside another "class_elsewhere" * definition. * -------------------------------------------------------------------- *) (* these are only found in the "Nested" field of class_elsewhere objects *) -type nested_class_elsewhere = +type nested_class_elsewhere = { Name: string; Access: MemberAccess; Nested: nested_classes_elsewhere; - CustomAttrs: CustomAttributes } + CustomAttrs: CustomAttributes } and nested_classes_elsewhere (* these are only found in the classes_elsewhere table in the manifest *) -type class_elsewhere = +type class_elsewhere = { Module: ModuleRef; Name: string; Access: TypeDefAccess; Nested: nested_classes_elsewhere; - CustomAttrs: CustomAttributes } + CustomAttrs: CustomAttributes } type classes_elsewhere @@ -1183,28 +1182,28 @@ val dest_nested_classes_elsewhere: nested_classes_elsewhere -> nested_class_else val dest_classes_elsewhere: classes_elsewhere -> class_elsewhere list val find_class_elsewhere: string -> classes_elsewhere -> class_elsewhere -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * "Manifest Resources" are chunks of resource data, being one of: - * - the data section of the current module (Bytes of resource given directly) - * - in an external file in this assembly (offset given in the resource_where field) - * - as a resources in another assembly of the same name. + * - the data section of the current module (Bytes of resource given directly) + * - in an external file in this assembly (offset given in the resource_where field) + * - as a resources in another assembly of the same name. * -------------------------------------------------------------------- *) -type resource_access = - | Public - | Private -type resource_where = - | Local of Bytes +type resource_access = + | Public + | Private +type resource_where = + | Local of Bytes | File of ModuleRef * Int32 | Assembly of AssemblyRef -type Resource = +type Resource = { Name: string; Where: resource_where; Access: resource_access; CustomAttrs: CustomAttributes } -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Table of resources in a module * -------------------------------------------------------------------- *) @@ -1212,7 +1211,7 @@ type Resources val dest_resources: Resources -> Resource list -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Fixups are pretty obscure stuff for C++ code. These are not * yet correctly represented in the AbstractIL syntax. * -------------------------------------------------------------------- *) @@ -1220,20 +1219,20 @@ val dest_resources: Resources -> Resource list (* type fixup = Fixup of (Int32 * List * data_label) *) (* type fixups = fixup list *) -(* -------------------------------------------------------------------- - * Manifests, The "main" module of an assembly, and Assemblies. - * +(* -------------------------------------------------------------------- + * Manifests, The "main" module of an assembly, and Assemblies. + * * The main module of an assembly is a module plus some manifest information. * - * An assembly is built by joining together a "main" module plus - * several auxiliary modules. + * An assembly is built by joining together a "main" module plus + * several auxiliary modules. * -------------------------------------------------------------------- *) -type manifest = +type manifest = { Name: string; - AuxModuleHashAlgorithm: Int32; + AuxModuleHashAlgorithm: Int32; SecurityDecls: SecurityDecls; - PublicKey: Option; + PublicKey: Option; Version: VersionInfo option; Locale: Locale option; CustomAttrs: CustomAttributes; @@ -1244,9 +1243,9 @@ type manifest = NoMachine: bool; ClassesElsewhere: classes_elsewhere; EntrypointElsewhere: ModuleRef option; - } + } -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * One module in the "current" assembly, either a main-module or * an auxiliary module. The main module will have a manifest. * @@ -1254,7 +1253,7 @@ type manifest = * code because "module" is a reserved word in OCaml. * -------------------------------------------------------------------- *) -type modul = +type modul = { Manifest: manifest option; CustomAttrs: CustomAttributes; Name: string; @@ -1265,7 +1264,7 @@ type modul = VirtAlignment: Int32; PhysAlignment: Int32; ImageBase: Int32; - Resources: Resources; + Resources: Resources; NativeResources: Bytes Lazy.t option; (* e.g. win86 resources, as the exact contents of a .res or .obj file *) } @@ -1275,33 +1274,33 @@ val assemblyName_of_mainmod: modul -> AssemblyName (* ==================================================================== * PART 2 - * - * Making metadata. Where no explicit static member - * is given, you should create the concrete datatype directly, + * + * Making metadata. Where no explicit static member + * is given, you should create the concrete datatype directly, * e.g. by filling in all appropriate record FieldDefs. * ==================================================================== *) -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Generate references to existing assemblies and modules * -------------------------------------------------------------------- *) val mk_simple_assemblyRef: AssemblyName -> AssemblyRef val mk_simple_modref: ModuleName -> ModuleRef -val mk_simple_scoref_from_assemblyName: AssemblyName -> ScopeRef -val mk_simple_scoref_from_assemblyRef: AssemblyRef -> ScopeRef +val mk_simple_scoref_from_assemblyName: AssemblyName -> ScopeRef +val mk_simple_scoref_from_assemblyRef: AssemblyRef -> ScopeRef val assemblyRef_for_manifest: manifest -> AssemblyRef val assemblyRef_for_mainmod: modul -> AssemblyRef -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Take apart MethodSpecs * -------------------------------------------------------------------- *) val rename_mspec: string -> MethodSpec -> MethodSpec val relocate_mspec: Type -> MethodSpec -> MethodSpec (* deprecated *) -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Make type refs * -------------------------------------------------------------------- *) @@ -1314,7 +1313,7 @@ val mk_nested_tref: ScopeRef * List * string -> TypeRef val mk_tref: ScopeRef * string -> TypeRef val mk_tref_in_tref: TypeRef * string -> TypeRef -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Make type specs * -------------------------------------------------------------------- *) @@ -1322,7 +1321,7 @@ val mk_nongeneric_tspec: TypeRef -> TypeSpec val mk_tspec: TypeRef * Instantiation -> TypeSpec val mk_Callconv: HasThis -> Callconv -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Make Types * -------------------------------------------------------------------- *) @@ -1336,7 +1335,7 @@ val mk_nongeneric_value_typ: TypeRef -> Type val mk_array_ty: Type * ArrayShape -> Type val mk_sdarray_ty: Type -> Type -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Make method references and specs * -------------------------------------------------------------------- *) @@ -1399,7 +1398,7 @@ val mk_mspec_to_mdef: Type * MethodDef * Instantiation -> MethodSpec val mk_CallSig: Callconv * List * Type -> CallSig -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Make generalized versions of possibly-generic Types, * e.g. Given the TypeDef for List, return the type "List". * -------------------------------------------------------------------- *) @@ -1413,17 +1412,17 @@ val gparam_of_gactual: Type -> GenericParam val gparams_of_inst: Instantiation -> GenericParam list val generalize_gparams: GenericParam list -> List -(* -------------------------------------------------------------------- - * Custom attributes +(* -------------------------------------------------------------------- + * Custom attributes * -------------------------------------------------------------------- *) -val mk_CustomAttributeibute: - TypeRef * - List (* fixed args: values and implicit Types *) * - List<(FieldSpec * bool * CustomAttributeElement)> (* named args: vluaes and flags indicating if they are FieldDefs or properties *) +val mk_CustomAttributeibute: + TypeRef * + List (* fixed args: values and implicit Types *) * + List<(FieldSpec * bool * CustomAttributeElement)> (* named args: vluaes and flags indicating if they are FieldDefs or properties *) -> CustomAttribute -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Making code. * -------------------------------------------------------------------- *) @@ -1451,7 +1450,7 @@ type ('a, 'b) choice = Choice1of2 of 'a | Choice2of2 of 'b val mk_try_multi_filter_catch_block: Code * (((CodeLabel * Code), typ) choice * (CodeLabel * Code)) list -> Code -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Injecting code into existing code blocks. A branch will * be added from the given instructions to the (unique) entry of * the code, and the first instruction will be the new entry @@ -1466,7 +1465,7 @@ val prepend_instrs_to_code: Instr list -> Code -> Code val prepend_instrs_to_ilmbody: Instr list -> CILMethodBody -> CILMethodBody val prepend_instrs_to_mdef: Instr list -> MethodDef -> MethodDef -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Default values for some of the strange flags in a module. * -------------------------------------------------------------------- *) @@ -1475,13 +1474,13 @@ val default_modulVirtAlignment: Int32 val default_modulPhysAlignment: Int32 val default_modulImageBase: Int32 -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Helper to check a class is really an enum * -------------------------------------------------------------------- *) val check_enum_FieldDefs: TypeRef -> FieldDef list -> Type * FieldDef list -(* -------------------------------------------------------------------- +(* -------------------------------------------------------------------- * Derived functions for making some instructions * -------------------------------------------------------------------- *) @@ -1543,7 +1542,7 @@ val tspec_for_nested_tdef: ScopeRef -> TypeDef list * TypeDef -> TypeSpec val prepend_instrs_to_cctor: Instr list -> Option -> TypeDef -> TypeDef -type tmps = { num_old_locals: int; mutable newlocals: local list; } +type tmps = { num_old_locals: int; mutable newlocals: local list; } val alloc_tmp: tmps -> local -> UInt16 val mk_storage_ctor: Option -> Instr list -> TypeSpec -> (string * typ) list -> MethodDef @@ -1551,7 +1550,7 @@ val mk_simple_storage_ctor: Option -> TypeSpec option -> TypeS val and_Tailness: Tailness -> bool -> Tailness -val mk_ctor_mspec_for_delegate_tdef: ScopeRef * TypeDef * Instantiation -> MethodSpec +val mk_ctor_mspec_for_delegate_tdef: ScopeRef * TypeDef * Instantiation -> MethodSpec val tref_for_toplevel: ScopeRef -> TypeRef val tspec_for_toplevel: ScopeRef -> TypeSpec @@ -1622,31 +1621,31 @@ val rescope_tspec: ScopeRef -> TypeSpec -> TypeSpec val rescope_typ: ScopeRef -> Type -> Type val rescope_mspec: ScopeRef -> MethodSpec -> MethodSpec val rescope_ospec: ScopeRef -> OverridesSpec -> OverridesSpec -val rescope_mref: ScopeRef -> MethodRef -> MethodRef +val rescope_mref: ScopeRef -> MethodRef -> MethodRef val rescope_fref: ScopeRef -> FieldRef -> FieldRef val rescope_fspec: ScopeRef -> FieldSpec -> FieldSpec -type seh_clause = +type seh_clause = | SEH_finally of (CodeLabel * CodeLabel) | SEH_fault of (CodeLabel * CodeLabel) | SEH_filter_catch of (CodeLabel * CodeLabel) * (CodeLabel * CodeLabel) | SEH_type_catch of Type * (CodeLabel * CodeLabel) -type exception_spec = +type exception_spec = { exnRange: (CodeLabel * CodeLabel); exnClauses: seh_clause list } -type local_spec = +type local_spec = { locRange: (CodeLabel * CodeLabel); locInfos: local_debug_info list } val build_code: string -> - (CodeLabel -> int) -> - Instr array -> - exception_spec list -> - local_spec list -> + (CodeLabel -> int) -> + Instr array -> + exception_spec list -> + local_spec list -> Code val inst_tspec_aux: int -> Instantiation -> TypeSpec -> TypeSpec @@ -1821,7 +1820,7 @@ val mspec_Object_Equals: MethodSpec val mspec_Object_GetHashCode: MethodSpec val mspec_IComparable_CompareTo: MethodSpec val mspec_Console_WriteLine: MethodSpec -val mspec_RuntimeHelpers_InitializeArray: MethodSpec +val mspec_RuntimeHelpers_InitializeArray: MethodSpec val mk_DebuggableAttribute: bool (* debug tracking *) * bool (* disable JIT optimizations *) -> CustomAttribute @@ -1849,11 +1848,10 @@ val intern_tspec: TypeSpec -> TypeSpec val intern_typ: Type -> Type val intern_instr: Instr -> Instr -type refs = - { refsAssembly: AssemblyRef list; +type refs = + { refsAssembly: AssemblyRef list; refsModul: ModuleRef list; } val refs_of_module: modul -> refs val combine_refs: refs -> refs -> refs val empty_refs: refs - diff --git a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fs b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fs index 6285f89c2ec..d2c6b7da964 100644 --- a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fs +++ b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fs @@ -1,12 +1,12 @@ -// #Regression #Conformance #LexFilter +// #Regression #Conformance #LexFilter #indent "off" // Regression test for FSHARP1.0:1078 -// The opposit of #light is (for now) #indent "off" +// The opposite of #light is (for now) #indent "off" //This value is not a function and cannot be applied let SimpleSample() = let x = 10 + 12 - 3 in - let y = x * 2 + 1 in + let y = x * 2 + 1 in let r1,r2 = x/3, x%3 in (x,y,r1,r2) diff --git a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsi b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsi index 244dcae5e55..a37b71dc6c5 100644 --- a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsi +++ b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsi @@ -1,7 +1,7 @@ -// #Regression #Conformance #LexFilter +// #Regression #Conformance #LexFilter #indent "off" // Regression test for FSHARP1.0:1078 -// The opposit of #light is (for now) #indent "off" +// The opposite of #light is (for now) #indent "off" //The signature file 'Indent_off_01' does not have a corresponding implementation file\. If an implementation file exists then check the 'module' and 'namespace' declarations in the signature and implementation files match type R diff --git a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsscript b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsscript index 3fe10bcccc5..059332d9484 100644 --- a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsscript +++ b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsscript @@ -1,11 +1,11 @@ -// #Regression #Conformance #LexFilter +// #Regression #Conformance #LexFilter #indent "off" // Regression test for FSHARP1.0:1078 -// The opposit of #light is (for now) #indent "off" +// The opposite of #light is (for now) #indent "off" //Main module of program is empty let SimpleSample() = let x = 10 + 12 - 3 in - let y = x * 2 + 1 in + let y = x * 2 + 1 in let r1,r2 = x/3, x%3 in (x,y,r1,r2) diff --git a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsx b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsx index 893df008972..794b7288ab2 100644 --- a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsx +++ b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_01.fsx @@ -1,11 +1,11 @@ -// #Regression #Conformance #LexFilter +// #Regression #Conformance #LexFilter #indent "off" // Regression test for FSHARP1.0:1078 -// The opposit of #light is (for now) #indent "off" +// The opposite of #light is (for now) #indent "off" //Main module of program is empty let SimpleSample() = let x = 10 + 12 - 3 in - let y = x * 2 + 1 in + let y = x * 2 + 1 in let r1,r2 = x/3, x%3 in (x,y,r1,r2) diff --git a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_after_comment01.fs b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_after_comment01.fs index 6ba9a667f22..bcfe12fdd79 100644 --- a/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_after_comment01.fs +++ b/tests/fsharpqa/Source/Conformance/LexicalFiltering/HashLight/indent_off_after_comment01.fs @@ -1,11 +1,11 @@ -// #Regression #Conformance #LexFilter +// #Regression #Conformance #LexFilter // Regression test for FSHARP1.0:1078 -// The opposit of #light is (for now) #indent "off" +// The opposite of #light is (for now) #indent "off" // #indent "off" module M let SimpleSample() = let x = 10 + 12 - 3 in - let y = x * 2 + 1 in + let y = x * 2 + 1 in let r1,r2 = x/3, x%3 in (x,y,r1,r2) From 2a4146e0d42c70cfce0b2b13b0b4097de162dc08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20S=C3=A1nchez=20L=C3=B3pez?= <1175054+carlossanlop@users.noreply.github.com> Date: Mon, 7 Apr 2025 00:30:04 -0700 Subject: [PATCH 17/20] Update maintenance-packages versions (#18446) * Update maintenance-packages versions * Update dependencies from https://github.com/dotnet/source-build-reference-packages build 20250404.3 Microsoft.SourceBuild.Intermediate.source-build-reference-packages From Version 9.0.0-alpha.1.25170.3 -> To Version 9.0.0-alpha.1.25204.3 --------- Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index a3b61734d48..5d099d46ea5 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,9 +1,9 @@ - + https://github.com/dotnet/source-build-reference-packages - 6968f7059f4418e985febe704a3b1320f9e5887d + 643689c88b1d5a0f1561383972c4189a0c673abe diff --git a/eng/Versions.props b/eng/Versions.props index 5ce287e802b..3b796e557b9 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -74,8 +74,8 @@ 4.6.1 - 4.6.2 - 6.1.1 + 4.6.3 + 6.1.2 From 4231126be3db239f2e66cf1a0a2b811f642fc14e Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 7 Apr 2025 12:08:20 +0200 Subject: [PATCH 18/20] Update dependencies from https://github.com/dotnet/source-build-reference-packages build 20250404.3 (#18447) Microsoft.SourceBuild.Intermediate.source-build-reference-packages From Version 9.0.0-alpha.1.25170.3 -> To Version 9.0.0-alpha.1.25204.3 Co-authored-by: dotnet-maestro[bot] From 4ba36db1f42f33a66d9677f0b9d589d39b204a9c Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Mon, 7 Apr 2025 10:59:49 -0700 Subject: [PATCH 19/20] Update dependencies from https://github.com/dotnet/arcade build 20250404.5 (#18449) Microsoft.SourceBuild.Intermediate.arcade , Microsoft.DotNet.Arcade.Sdk From Version 9.0.0-beta.25164.2 -> To Version 9.0.0-beta.25204.5 Co-authored-by: dotnet-maestro[bot] Co-authored-by: Kevin Ransom (msft) --- eng/Version.Details.xml | 8 ++++---- global.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 5d099d46ea5..da463444bca 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -42,14 +42,14 @@ - + https://github.com/dotnet/arcade - 5ba9ca776c1d0bb72b2791591e54cf51fc52dfee + 97cbc7361ff28b2948c8182720c166a744049f55 - + https://github.com/dotnet/arcade - 5ba9ca776c1d0bb72b2791591e54cf51fc52dfee + 97cbc7361ff28b2948c8182720c166a744049f55 diff --git a/global.json b/global.json index eca327e814a..434c70939fc 100644 --- a/global.json +++ b/global.json @@ -17,7 +17,7 @@ "perl": "5.38.2.2" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.25164.2", + "Microsoft.DotNet.Arcade.Sdk": "9.0.0-beta.25204.5", "Microsoft.DotNet.Helix.Sdk": "8.0.0-beta.23255.2" } } From 38aab8f7cd329126c5e2a57ebd16fafe2a195539 Mon Sep 17 00:00:00 2001 From: "Kevin Ransom (msft)" Date: Mon, 7 Apr 2025 14:50:06 -0700 Subject: [PATCH 20/20] Update service-branch-merge.json --- .config/service-branch-merge.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.config/service-branch-merge.json b/.config/service-branch-merge.json index 49561874be8..9eaf6479d45 100644 --- a/.config/service-branch-merge.json +++ b/.config/service-branch-merge.json @@ -10,8 +10,8 @@ "ExtraSwitches": "-QuietComments" }, "main": { - "MergeToBranch": "release/dev17.14", + "MergeToBranch": "release/dev18.0", "ExtraSwitches": "-QuietComments" } } -} \ No newline at end of file +}